1 Star 0 Fork 0

Git工具集 / git-secrets

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

git-secrets

Prevents you from committing passwords and other sensitive information to a git repository.

Synopsis

git secrets --scan [-r|--recursive] [--cached] [--no-index] [--untracked] [<files>...]
git secrets --scan-history
git secrets --install [-f|--force] [<target-directory>]
git secrets --list [--global]
git secrets --add [-a|--allowed] [-l|--literal] [--global] <pattern>
git secrets --add-provider [--global] <command> [arguments...]
git secrets --register-aws [--global]
git secrets --aws-provider [<credentials-file>]

Description

git-secrets scans commits, commit messages, and --no-ff merges to prevent adding secrets into your git repositories. If a commit, commit message, or any commit in a --no-ff merge history matches one of your configured prohibited regular expression patterns, then the commit is rejected.

Installing git-secrets

git-secrets must be placed somewhere in your PATH so that it is picked up by git when running git secrets.

*nix (Linux/macOS)

You can use the install target of the provided Makefile to install git secrets and the man page. You can customize the install path using the PREFIX and MANPREFIX variables.

make install

Windows

Run the provided install.ps1 powershell script. This will copy the needed files to an installation directory (%USERPROFILE%/.git-secrets by default) and add the directory to the current user PATH.

PS > ./install.ps1

Homebrew (for macOS users)

brew install git-secrets

Warning

You're not done yet! You MUST install the git hooks for every repo that you wish to use with git secrets --install.

Here's a quick example of how to ensure a git repository is scanned for secrets on each commit:

cd /path/to/my/repo
git secrets --install
git secrets --register-aws

Advanced configuration

Add a configuration template if you want to add hooks to all repositories you initialize or clone in the future.

git secrets --register-aws --global

Add hooks to all your local repositories.

git secrets --install ~/.git-templates/git-secrets
git config --global init.templateDir ~/.git-templates/git-secrets

Add custom providers to scan for security credentials.

git secrets --add-provider -- cat /path/to/secret/file/patterns

Before making public a repository

With git-secrets is also possible to scan a repository including all revisions:

git secrets --scan-history

Options

Operation Modes

Each of these options must appear first on the command line.

--install
Installs git hooks for a repository. Once the hooks are installed for a git repository, commits and non-fast-forward merges for that repository will be prevented from committing secrets.
--scan
Scans one or more files for secrets. When a file contains a secret, the matched text from the file being scanned will be written to stdout and the script will exit with a non-zero status. Each matched line will be written with the name of the file that matched, a colon, the line number that matched, a colon, and then the line of text that matched. If no files are provided, all files returned by git ls-files are scanned.
--scan-history
Scans repository including all revisions. When a file contains a secret, the matched text from the file being scanned will be written to stdout and the script will exit with a non-zero status. Each matched line will be written with the name of the file that matched, a colon, the line number that matched, a colon, and then the line of text that matched.
--list
Lists the git-secrets configuration for the current repo or in the global git config.
--add
Adds a prohibited or allowed pattern.
--add-provider
Registers a secret provider. Secret providers are executables that when invoked output prohibited patterns that git-secrets should treat as prohibited.
--register-aws

Adds common AWS patterns to the git config and ensures that keys present in ~/.aws/credentials are not found in any commit. The following checks are added:

  • AWS Access Key IDs via (A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}
  • AWS Secret Access Key assignments via ":" or "=" surrounded by optional quotes
  • AWS account ID assignments via ":" or "=" surrounded by optional quotes
  • Allowed patterns for example AWS keys (AKIAIOSFODNN7EXAMPLE and wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY)
  • Known credentials from ~/.aws/credentials

Note

While the patterns registered by this command should catch most instances of AWS credentials, these patterns are not guaranteed to catch them all. git-secrets should be used as an extra means of insurance -- you still need to do your due diligence to ensure that you do not commit credentials to a repository.

--aws-provider
Secret provider that outputs credentials found in an INI file. You can optionally provide the path to an INI file.

Options for --install

-f, --force
Overwrites existing hooks if present.
<target-directory>

When provided, installs git hooks to the given directory. The current directory is assumed if <target-directory> is not provided.

If the provided <target-directory> is not in a git repository, the directory will be created and hooks will be placed in <target-directory>/hooks. This can be useful for creating git template directories using with git init --template <target-directory>.

You can run git init on a repository that has already been initialized. From the git init documentation:

From the git documentation: Running git init in an existing repository is safe. It will not overwrite things that are already there. The primary reason for rerunning git init is to pick up newly added templates (or to move the repository to another place if --separate-git-dir is given).

The following git hooks are installed:

  1. pre-commit: Used to check if any of the files changed in the commit use prohibited patterns.
  2. commit-msg: Used to determine if a commit message contains a prohibited patterns.
  3. prepare-commit-msg: Used to determine if a merge commit will introduce a history that contains a prohibited pattern at any point. Please note that this hook is only invoked for non fast-forward merges.

Note

Git only allows a single script to be executed per hook. If the repository contains Debian-style subdirectories like pre-commit.d and commit-msg.d, then the git hooks will be installed into these directories, which assumes that you've configured the corresponding hooks to execute all of the scripts found in these directories. If these git subdirectories are not present, then the git hooks will be installed to the git repo's .git/hooks directory.

Examples

Install git hooks to the current directory:

cd /path/to/my/repository
git secrets --install

Install git hooks to a repository other than the current directory:

git secrets --install /path/to/my/repository

Create a git template that has git-secrets installed, and then copy that template into a git repository:

git secrets --install ~/.git-templates/git-secrets
git init --template ~/.git-templates/git-secrets

Overwrite existing hooks if present:

git secrets --install -f

Options for --scan

-r, --recursive

Scans the given files recursively. If a directory is encountered, the directory will be scanned. If -r is not provided, directories will be ignored.

-r cannot be used alongside --cached, --no-index, or --untracked.

--cached
Searches blobs registered in the index file.
--no-index
Searches files in the current directory that is not managed by git.
--untracked
In addition to searching in the tracked files in the working tree, --scan also in untracked files.
<files>...

The path to one or more files on disk to scan for secrets.

If no files are provided, all files returned by git ls-files are scanned.

Examples

Scan all files in the repo:

git secrets --scan

Scans a single file for secrets:

git secrets --scan /path/to/file

Scans a directory recursively for secrets:

git secrets --scan -r /path/to/directory

Scans multiple files for secrets:

git secrets --scan /path/to/file /path/to/other/file

You can scan by globbing:

git secrets --scan /path/to/directory/*

Scan from stdin:

echo 'hello!' | git secrets --scan -

Options for --list

--global
Lists only git-secrets configuration in the global git config.

Options for --add

--global
Adds patterns to the global git config
-l, --literal
Escapes special regular expression characters in the provided pattern so that the pattern is searched for literally.
-a, --allowed
Mark the pattern as allowed instead of prohibited. Allowed patterns are used to filter our false positives.
<pattern>
The regex pattern to search.

Examples

Adds a prohibited pattern to the current repo:

git secrets --add '[A-Z0-9]{20}'

Adds a prohibited pattern to the global git config:

git secrets --add --global '[A-Z0-9]{20}'

Adds a string that is scanned for literally (+ is escaped):

git secrets --add --literal 'foo+bar'

Add an allowed pattern:

git secrets --add -a 'allowed pattern'

Options for --register-aws

--global
Adds AWS specific configuration variables to the global git config.

Options for --aws-provider

[<credentials-file>]
If provided, specifies the custom path to an INI file to scan. If not provided, ~/.aws/credentials is assumed.

Options for --add-provider

--global
Adds the provider to the global git config.
<command>
Provider command to invoke. When invoked the command is expected to write prohibited patterns separated by new lines to stdout. Any extra arguments provided are passed on to the command.

Examples

Registers a secret provider with arguments:

git secrets --add-provider -- git secrets --aws-provider

Cats secrets out of a file:

git secrets --add-provider -- cat /path/to/secret/file/patterns

Defining prohibited patterns

egrep-compatible regular expressions are used to determine if a commit or commit message contains any prohibited patterns. These regular expressions are defined using the git config command. It is important to note that different systems use different versions of egrep. For example, when running on macOS, you will use a different version of egrep than when running on something like Ubuntu (BSD vs GNU).

You can add prohibited regular expression patterns to your git config using git secrets --add <pattern>.

Ignoring false positives

Sometimes a regular expression might match false positives. For example, git commit SHAs look a lot like AWS access keys. You can specify many different regular expression patterns as false positives using the following command:

git secrets --add --allowed 'my regex pattern'

You can also add regular expressions patterns to filter false positives to a .gitallowed file located in the repository's root directory. Lines starting with # are skipped (comment line) and empty lines are also skipped.

First, git-secrets will extract all lines from a file that contain a prohibited match. Included in the matched results will be the full path to the name of the file that was matched, followed by ':', followed by the line number that was matched, followed by the entire line from the file that was matched by a secret pattern. Then, if you've defined allowed regular expressions, git-secrets will check to see if all of the matched lines match at least one of your registered allowed regular expressions. If all of the lines that were flagged as secret are canceled out by an allowed match, then the subject text does not contain any secrets. If any of the matched lines are not matched by an allowed regular expression, then git-secrets will fail the commit/merge/message.

Important

Just as it is a bad practice to add prohibited patterns that are too greedy, it is also a bad practice to add allowed patterns that are too forgiving. Be sure to test out your patterns using ad-hoc calls to git secrets --scan $filename to ensure they are working as intended.

Secret providers

Sometimes you want to check for an exact pattern match against a set of known secrets. For example, you might want to ensure that no credentials present in ~/.aws/credentials ever show up in a commit. In these cases, it's better to leave these secrets in one location rather than spread them out across git repositories in git configs. You can use "secret providers" to fetch these types of credentials. A secret provider is an executable that when invoked outputs prohibited patterns separated by new lines.

You can add secret providers using the --add-provider command:

git secrets --add-provider -- git secrets --aws-provider

Notice the use of --. This ensures that any arguments associated with the provider are passed to the provider each time it is invoked when scanning for secrets.

Example walkthrough

Let's take a look at an example. Given the following subject text (stored in /tmp/example):

This is a test!
password=ex@mplepassword
password=******
More test...

And the following registered patterns:

git secrets --add 'password\s*=\s*.+'
git secrets --add --allowed --literal 'ex@mplepassword'

Running git secrets --scan /tmp/example, the result will result in the following error output:

/tmp/example:3:password=******

[ERROR] Matched prohibited pattern

Possible mitigations:
- Mark false positives as allowed using: git config --add secrets.allowed ...
- List your configured patterns: git config --get-all secrets.patterns
- List your configured allowed patterns: git config --get-all secrets.allowed
- Use --no-verify if this is a one-time false positive

Breaking this down, the prohibited pattern value of password\s*=\s*.+ will match the following lines:

/tmp/example:2:password=ex@mplepassword
/tmp/example:3:password=******

...But the first match will be filtered out due to the fact that it matches the allowed regular expression of ex@mplepassword. Because there is still a remaining line that did not match, it is considered a secret.

Because that matching lines are placed on lines that start with the filename and line number (e.g., /tmp/example:3:...), you can create allowed patterns that take filenames and line numbers into account in the regular expression. For example, you could whitelist an entire file using something like:

git secrets --add --allowed '/tmp/example:.*'
git secrets --scan /tmp/example && echo $?
# Outputs: 0

Alternatively, you could allow a specific line number of a file if that line is unlikely to change using something like the following:

git secrets --add --allowed '/tmp/example:3:.*'
git secrets --scan /tmp/example && echo $?
# Outputs: 0

Keep this in mind when creating allowed patterns to ensure that your allowed patterns are not inadvertently matched due to the fact that the filename is included in the subject text that allowed patterns are matched against.

Skipping validation

Use the --no-verify option in the event of a false positive match in a commit, merge, or commit message. This will skip the execution of the git hook and allow you to make the commit or merge.

About

Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Note: Other license terms may apply to certain, identified software files contained within or distributed with the accompanying software if such terms are included in the directory containing the accompanying software. Such other license terms will then apply in lieu of the terms of the software license above.

简介

阻止你在 Git 提交信息中包含敏感信息 展开 收起
Shell
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Shell
1
https://gitee.com/vcs-all-in-one/git-secrets.git
git@gitee.com:vcs-all-in-one/git-secrets.git
vcs-all-in-one
git-secrets
git-secrets
master

搜索帮助