Documentation
¶
Overview ¶
Package secrets provides built-in secret-pattern scanning for gk push.
Index ¶
- Constants
- Variables
- func CompilePatterns(raw []string) (compiled []*regexp.Regexp, bad []string)
- func DecodeUTF16(data []byte) (string, bool)
- func IsArchive(p string) bool
- func IsLFSPointer(data []byte) bool
- func IsLowEntropySecret(value string) bool
- func IsPlaceholderLine(line string) bool
- func LooksBinary(data []byte) bool
- func MaskLine(line string) string
- func OpensAsArchive(data []byte) bool
- func OpensAsZip(data []byte) bool
- func PayloadFileHeader(path string) string
- func SecretValue(sm []string) string
- func WalkArchive(name string, data []byte, limits ZipLimits, fn func(name, content string)) (unread int, err error)
- type Credential
- func BindOCI(candidate *Credential, profiles []OCIProfile) *Credential
- func KeyCandidate(pemText string) *Credential
- func NewAWSCredential(keyID string, secretCandidates []string, token string) *Credential
- func NewOCICredential(key *rsa.PrivateKey, profiles []OCIProfile) *Credential
- func NewTokenCredential(provider, kind, value string) *Credential
- func PairAWS(lines []string, idx int, keyID string) *Credential
- func TokenCredential(ruleID, line string, col int, match string) *Credential
- func (c *Credential) GoString() string
- func (c *Credential) ID() string
- func (c *Credential) Kind() string
- func (c *Credential) MarshalJSON() ([]byte, error)
- func (c *Credential) Masked() string
- func (c *Credential) OCIKey() *rsa.PrivateKey
- func (c *Credential) OCIProfiles() []OCIProfile
- func (c *Credential) Provider() string
- func (c *Credential) SecretCandidates() []string
- func (c *Credential) SessionToken() string
- func (c *Credential) String() string
- func (c *Credential) Value() string
- func (c *Credential) Verifiable() bool
- type Finding
- type OCIProfile
- type Pattern
- type Secret
- type ZipLimits
Constants ¶
const ( ProviderAWS = "aws" ProviderSlack = "slack" ProviderGCP = "gcp" ProviderOCI = "oci" )
Provider names the issuer that can check a Credential.
const ( OCIProfileInvalid = "invalid_profile" OCIProfileUnsupportedRealm = "unsupported_realm" OCIProfileNoRegion = "region_not_found" )
Reasons a profile cannot be sent to OCI.
const ArchiveSeparator = "!"
ArchiveSeparator joins an archive path and the path of a file inside it, as in app.jar!BOOT-INF/classes/application.yml. Gitleaks reports archive entries the same way, so a path allowlist written for it matches here too.
const BinarySniff = 8000
BinarySniff is how far git looks for a NUL byte to call a file binary.
const MaxArchiveDepth = 2
MaxArchiveDepth is how deep WalkArchive opens archives: an archive, and the archives in it.
const ( // OCIMaxSendable bounds the profiles that can be sent for one key, and // so the requests a verifier spends on it. OCIMaxSendable = 3 )
Variables ¶
var ArchiveExts = []string{
".jar", ".war", ".ear", ".zip", ".apk", ".aar", ".whl", ".egg", ".nupkg", ".ipa", ".vsix",
".tar", ".tar.gz", ".tgz",
}
ArchiveExts are the lowercase name endings that IsArchive accepts: the zip formats of Java, Android, Python, .NET, iOS, and VS Code packages, and tar files, plain or compressed with gzip.
var BuiltinPatterns = []Pattern{ literalPattern("aws-access-key", `\bAKIA[0-9A-Z]{16}\b`, true, false, "AKIA"), literalPattern("aws-secret-key", `(?i)aws[_-]?(?:secret|sk)[^"']{0,5}["']?([A-Za-z0-9/+=]{40})`, false, true, "aws"), literalPattern("github-token", `\bghp_[A-Za-z0-9]{36}\b`, true, false, "ghp_"), literalPattern("github-fine", `\bgithub_pat_[A-Za-z0-9_]{82}\b`, true, false, "github_pat_"), literalPattern("slack-token", `\bxox[abpr]-[A-Za-z0-9-]{10,}\b`, true, false, "xox"), literalPattern("openai-key", `\bsk-[A-Za-z0-9]{20,}\b`, true, false, "sk-"), {Kind: "private-key", Regex: regexp.MustCompile(`-----BEGIN (RSA |EC |OPENSSH |DSA |ENCRYPTED |PGP )?PRIVATE KEY-----`)}, literalPattern("generic-secret", `(?i)(api[_-]?key|secret|token|password)\s*[:=]\s*["']([A-Za-z0-9/_\-+=]{24,})["']`, false, true, "api", "secret", "token", "password"), }
BuiltinPatterns is the default scan set. Keep it small and high-signal. Each entry must be broadly unambiguous (avoid matching normal code).
var PayloadFileHeaderRE = regexp.MustCompile(`^>>> gk-file (.+) <<<$`)
PayloadFileHeaderRE matches a single header line. Anchored on both ends so a stray ">>> gk-file foo <<<" appearing inside real content (e.g. quoted in a doc) cannot trigger a false boundary.
Functions ¶
func CompilePatterns ¶
CompilePatterns compiles user-supplied regex strings. Returns compiled list and the list of raw patterns that failed to compile.
func DecodeUTF16 ¶ added in v0.170.0
DecodeUTF16 returns data as UTF-8 when it starts with a UTF-16 byte order mark, and false otherwise. Git calls such a file binary, because its ASCII characters hold NUL bytes, yet Windows tools such as PowerShell write text this way. An odd last byte and an unpaired surrogate become U+FFFD. Text without a byte order mark is not guessed at.
func IsArchive ¶ added in v0.170.0
IsArchive reports whether path names an archive that the secret scan opens. Gitleaks identifies archives by name and does not treat .jar, .war, or .ear as zip files, so it never reads the configuration packed into a Java build.
func IsLFSPointer ¶ added in v0.156.0
IsLFSPointer reports whether data is a Git LFS pointer, which names a file kept outside the repository.
func IsLowEntropySecret ¶
isLowEntropySecret reports whether a matched value is too monotonous to be a real credential. Genuine tokens are near-random over a large alphabet (base62 for github-token/openai-key); fixtures repeat a tiny one — "ghp_0000…0000", "sk-aaaa…aaaa", "1234…". Only values of 20+ characters are judged, so the distinct-rune floor never trips a real key: any real base62 token that long clears 8 distinct characters with overwhelming probability, while reproduction-by-hand fakes do not.
func IsPlaceholderLine ¶
IsPlaceholderLine returns true when the line contains an example/placeholder value (example/dummy/test/changeme/…). Applied to every kind except private-key.
Judged on the whole LINE, not the value alone, because the giveaway usually sits beside the credential — a comment, a variable name, an assert. That breadth is why callers that BLOCK on a hit (the push/ship scanner) drop the finding outright, while callers that merely REDACT (the aicommit privacy gate) keep redacting and only exempt the value from their abort threshold.
func LooksBinary ¶ added in v0.156.0
LooksBinary reports whether data is binary by the test git uses: a NUL byte in the first 8000 bytes.
func MaskLine ¶
MaskLine returns line with every built-in secret match masked in place. The credential value is replaced by its mask() form while the surrounding code (variable names, comments) stays intact, so verbose context output around a hit reads naturally yet never exposes an adjacent secret. For keyword=value kinds (generic-secret) only the value is masked, not the keyword.
func OpensAsArchive ¶ added in v0.170.0
OpensAsArchive reports whether data opens as a zip file, or starts as a gzip stream or a tar file.
func OpensAsZip ¶ added in v0.157.0
OpensAsZip reports whether archive/zip can open data as a zip file.
func PayloadFileHeader ¶
PayloadFileHeader formats the file boundary marker that the secret-scan pipeline emits between files in its aggregated blob. The marker uses ">>> gk-file <path> <<<" so it cannot collide with markdown H3 headers (`### foo`) — an earlier `### <path>` convention caused README section titles like "### 첫 호출" to be mistaken for filenames in finding output.
PayloadFileHeaderRE is the matching parser. Both must stay in sync; callers should never hand-roll either.
func SecretValue ¶
SecretValue returns the substring worth masking for display. Patterns like generic-secret (group 1 = keyword, group 2 = value) or aws-secret-key (group 1 = value) capture the credential separately from surrounding boilerplate; we mask the last non-empty capture group so the sample shows the value's prefix (e.g. "dev-****") instead of the keyword ("secr****"), which is what a reader needs to judge a false positive. Patterns with no capture groups fall back to the full match.
Exported so the aicommit privacy gate identifies the credential inside its own (differently-grouped) patterns the same way, rather than weighing the whole `key = "value"` match as if it were the secret.
func WalkArchive ¶ added in v0.170.0
func WalkArchive(name string, data []byte, limits ZipLimits, fn func(name, content string)) (unread int, err error)
WalkArchive calls fn for each regular file in the archive data, a zip file, a tar file, or a gzip tar file, in archive order, and returns how many files it could not read. name is the archive's own name. Content is "" for a binary file, so only path rules apply to it, and a UTF-16 file with a byte order mark is passed as UTF-8.
An archive in the archive is opened too, and its files are named inner!file. A Java archive's dependencies, the archives in its lib directories, are not opened: a dependency holds no configuration of the application. An archive deeper than MaxArchiveDepth is not opened and counts as unread.
A file that is larger than limits.EntryBytes or than what is left of limits.TotalBytes, that uses a compression method Go cannot read, or whose data is corrupt is not passed to fn and counts as unread, as does an archive in the archive that does not open. An error means the archive itself did not open, or a zip file lists more than limits.Entries.
Types ¶
type Credential ¶ added in v0.156.0
type Credential struct {
// contains filtered or unexported fields
}
Credential is a raw credential a scan found, kept for live verification: an AWS access key ID with the secret candidates and session token next to it, a Slack token, a GCP API key, or an OCI API signing key with the profiles that name its fingerprint. Every formatter and encoder sees only the masked value, so a finding that carries one can be printed or marshaled without leaking.
A private-key finding carries a candidate: the PEM text with no provider. It is not verifiable until BindOCI pairs it with a profile.
The scanner constructors copy their values: a credential outlives the scanned text, and a substring of it would keep all of it in memory.
func BindOCI ¶ added in v0.156.0
func BindOCI(candidate *Credential, profiles []OCIProfile) *Credential
BindOCI pairs a private-key candidate with the profiles that name its fingerprint and returns the OCI credential, or nil when the PEM is not an unencrypted RSA key of an accepted size or no profile names it. The fingerprint is computed from the key, so the pairing does not depend on where the profile and the key sit: they can be in different files or commits. The profiles are kept in the order given, bounded as AppendOCIProfile describes.
func KeyCandidate ¶ added in v0.156.0
func KeyCandidate(pemText string) *Credential
KeyCandidate wraps the PEM text of a private-key finding so a later pass can test whether it is an OCI API signing key. It returns nil for a block too large to be one.
func NewAWSCredential ¶ added in v0.155.0
func NewAWSCredential(keyID string, secretCandidates []string, token string) *Credential
NewAWSCredential builds an AWS credential directly; scanners use PairAWS.
func NewOCICredential ¶ added in v0.156.0
func NewOCICredential(key *rsa.PrivateKey, profiles []OCIProfile) *Credential
NewOCICredential builds an OCI credential directly; scanners use BindOCI.
func NewTokenCredential ¶ added in v0.156.0
func NewTokenCredential(provider, kind, value string) *Credential
NewTokenCredential builds a single-value credential directly; scanners use TokenCredential.
func PairAWS ¶ added in v0.155.0
func PairAWS(lines []string, idx int, keyID string) *Credential
PairAWS collects the secret access key candidates and the session token around lines[idx], which holds keyID. It searches the raw lines instead of other findings because the generic-api-key finding for a secret on the key ID's own line is dropped as shadowed. Candidates on lines that mention "secret" come first, then nearer lines.
func TokenCredential ¶ added in v0.156.0
func TokenCredential(ruleID, line string, col int, match string) *Credential
TokenCredential returns the credential for a finding of a token rule, or nil for any other rule. Several Slack rules bound the length of the token tail, so the match can stop inside a longer token, and a truncated token would read as invalid. The value is therefore extended to the end of the token's character run on the raw line. col is where match starts in line: two tokens on one line can share the same truncated match, so the match text alone does not say which token a finding belongs to. If line does not hold match at col, the value is match as is.
func (*Credential) GoString ¶ added in v0.156.0
func (c *Credential) GoString() string
func (*Credential) ID ¶ added in v0.156.0
func (c *Credential) ID() string
ID identifies the credential across findings: the same value found in several files or commits has one ID. It contains the raw value.
func (*Credential) Kind ¶ added in v0.156.0
func (c *Credential) Kind() string
Kind returns the scanner rule ID that found the credential.
func (*Credential) MarshalJSON ¶ added in v0.156.0
func (c *Credential) MarshalJSON() ([]byte, error)
MarshalJSON keeps raw values out of any encoded finding.
func (*Credential) Masked ¶ added in v0.156.0
func (c *Credential) Masked() string
Masked shows the value's first and last four characters.
func (*Credential) OCIKey ¶ added in v0.156.0
func (c *Credential) OCIKey() *rsa.PrivateKey
OCIKey returns the parsed private key of an OCI credential, or nil.
func (*Credential) OCIProfiles ¶ added in v0.156.0
func (c *Credential) OCIProfiles() []OCIProfile
OCIProfiles returns the profile candidates of an OCI credential, nearest first.
func (*Credential) Provider ¶ added in v0.156.0
func (c *Credential) Provider() string
Provider returns one of the Provider constants.
func (*Credential) SecretCandidates ¶ added in v0.156.0
func (c *Credential) SecretCandidates() []string
SecretCandidates returns the raw AWS secret access key candidates, nearest first.
func (*Credential) SessionToken ¶ added in v0.156.0
func (c *Credential) SessionToken() string
SessionToken returns the raw AWS session token, or "" when none was found.
func (*Credential) String ¶ added in v0.156.0
func (c *Credential) String() string
func (*Credential) Value ¶ added in v0.156.0
func (c *Credential) Value() string
Value returns the raw AWS access key ID, Slack token, or GCP API key. For an OCI key it is the key fingerprint, which is not a secret, and for a private-key candidate it is empty: the PEM is never part of Value or ID.
func (*Credential) Verifiable ¶ added in v0.156.0
func (c *Credential) Verifiable() bool
Verifiable reports whether an issuer can check the credential. A private-key candidate that no OCI profile names is not verifiable.
type Finding ¶
type Finding struct {
Kind string // short label: "aws-access-key", "github-token", "private-key", ...
Line int // 1-based line number within the input blob (kept verbatim for
// callers — e.g. aicommit — that remap blob lines themselves)
File string // owning file path, recovered from PayloadFileHeader markers; "" when none present
FileLine int // 1-based line within File; equals Line when no file header precedes the hit
// Commit is the introducing git commit when the input is `git log -p` output.
Commit string `json:"commit,omitempty"`
Sample string // a masked sample suitable for display
// Secret is the value that Sample masks. It formats masked too; only
// Secret.Reveal returns the value.
Secret Secret `json:"-"`
// LineText, ContextBefore, and ContextAfter back verbose ("show the
// surrounding source") output. They are populated only by diff-aware
// callers (the push/ship scanner) and are all secret-masked, so printing
// them never leaks an adjacent credential. Empty when not collected or at
// a hunk edge.
LineText string `json:"line_text,omitempty"`
ContextBefore string `json:"context_before,omitempty"`
ContextAfter string `json:"context_after,omitempty"`
// Credential is set on an embedded-engine finding that
// `gk guard check --verify` can test (AWS, Slack, GCP); it formats masked.
Credential *Credential `json:"-"`
}
Finding is a single secret-pattern hit.
func Scan ¶
Scan scans blob for secret findings. extra lets callers append user-provided compiled regexes from config. Returns findings in line order; multiple findings per line are included.
type OCIProfile ¶ added in v0.156.0
OCIProfile is the identity half of an OCI API signing key: the values an OCI config, Terraform variable file, or environment file keeps next to the key fingerprint. None of them is a secret. Region is "" when none was found near the fingerprint.
func AppendOCIProfile ¶ added in v0.156.0
func AppendOCIProfile(list []OCIProfile, p OCIProfile) []OCIProfile
AppendOCIProfile adds p to the candidates for one key and keeps the list bounded: at most OCIMaxSendable profiles that can be sent, and at most one that cannot. Only sendable profiles count toward the limit, because a profile that cannot be sent would otherwise push out one that can. The one unsendable profile stays for two reasons: it carries the reason when nothing can be sent, and it keeps a key that has other candidates from looking like a key with a single profile.
func FindOCIProfiles ¶ added in v0.156.0
func FindOCIProfiles(text string) []OCIProfile
FindOCIProfiles returns the OCI profile candidates in text, which is a file's content or a raw diff. A fingerprint anchors each profile; the user OCID, tenancy OCID, and region come from the lines around it. When several values are in range, the nearest combinations come first, bounded for each fingerprint occurrence as AppendOCIProfile describes. A region counts only on a line that mentions "region", so another hyphenated word is not taken for one.
In a diff, removed lines count too. The pair is made by fingerprint, so a profile that a commit deleted still names its key.
func (OCIProfile) Problem ¶ added in v0.156.0
func (p OCIProfile) Problem() string
Problem returns the reason the profile cannot be sent to OCI, or "". The values come from repository text and become the request host, path, and key ID, so the patterns here are anchored. A verifier must call Problem on each profile right before it builds the request, whatever filtered the list before.
type Secret ¶ added in v0.167.0
type Secret struct {
// contains filtered or unexported fields
}
Secret holds a secret value that a finding matched. A Finding or a Violation carries it, and it must not leak through them into logs, errors, or agent output: only Reveal returns the value.
Where fmt can call its methods, it prints masked in every verb: formatted directly, through a pointer, or in an exported field. fmt cannot call them for %p, for a verb that it rejects for the value, or for a field that is not exported; there it prints what the struct holds. So the value is behind a pointer, which fmt prints as an address and does not follow. JSON gets the masked text.
func (Secret) Format ¶ added in v0.167.0
Format prints the masked text for every verb. The verbs for a string (%s, %q, %x, %X) apply to it. Any other verb prints it as %s does: without this method fmt uses String for %v only, and prints the fields of the struct for a verb such as %d.
func (Secret) MarshalJSON ¶ added in v0.167.0
MarshalJSON keeps the value out of any encoded finding.
type ZipLimits ¶ added in v0.156.0
type ZipLimits struct {
// Entries is the most entries an archive and the archives in it may list
// together.
Entries int
// EntryBytes is the largest decompressed size of one entry.
EntryBytes int64
// TotalBytes is the most that the entries of an archive and of the
// archives in it may decompress to together. For a tar file it also
// counts the entries that are not read, because gzip decompresses them
// to skip them.
TotalBytes int64
}
ZipLimits bound what WalkArchive reads from one archive, the archives in it included. A repository can hold any blob, including one built to expand without end.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package gitleaksrules scans unified diffs with the gitleaks default ruleset embedded in the gk binary, so secret scanning works without the gitleaks binary installed.
|
Package gitleaksrules scans unified diffs with the gitleaks default ruleset embedded in the gk binary, so secret scanning works without the gitleaks binary installed. |
|
codec
Package codec decodes base64, hex, percent, and unicode escapes in place so the rules can run on the decoded text, and maps decoded matches back to their location in the original text.
|
Package codec decodes base64, hex, percent, and unicode escapes in place so the rules can run on the decoded text, and maps decoded matches back to their location in the original text. |
|
Package verify checks whether credentials found by a secret scan are live, with one read-only identity call to the issuer:
|
Package verify checks whether credentials found by a secret scan are live, with one read-only identity call to the issuer: |