Documentation
¶
Overview ¶
Package leakgate is the pure scanner behind the H-55 leak gate.
The repository is public, so the names of the operator's machines, people and brands must never reach the tracked tree. The gate scans the tracked files (and their names) for a list of denied entries and fails on any hit. The list itself is a secret: the committed form of it is a file of keyed digests (HMAC-SHA256), so the gate can say "this file contains a denied name" without the repository ever holding the name.
This package is the whole matcher and nothing else. It reads no environment variable and starts no process: the key is passed in, the file system is a small interface (so an unreadable file, a deleted file or a 17 MiB file is a unit test, not a disk experiment), and the git plumbing lives in the command that calls it. The pieces:
- entries and the list file (this file), the matcher and tokenizer (match.go);
- the fold that makes encoded spellings visible (fold.go, foldtable.go);
- the PNG chunk walk (png.go) and the tree scan with its fail-closed rules (scan.go);
- the keyless shape rules (shape.go);
- the digest file, its MAC and key selection (digest.go) and key resolution (key.go).
Index ¶
- Constants
- Variables
- func AllowDigest(key []byte, chunk string) string
- func BlankEscapes(b []byte) ([]byte, bool)
- func CanaryText() string
- func DecodeKey(s string) ([]byte, error)
- func Fold(b []byte) []byte
- func IsPNG(data []byte) bool
- func NeedsFold(b []byte) bool
- func ParseRequired(v string) (bool, error)
- func PatternBlock(es []Entry) string
- func Patterns(es []Entry) []string
- func ReplaceBlock(existing, block string) string
- func ResolveFileList(specs []FileSpec, tracked map[string]bool) (map[string]bool, error)
- func SelectKey(df *DigestFile, k Keys) ([]byte, error)
- func ValidateEntries(es []Entry) error
- type AllowRow
- type Classes
- type Decision
- type DigestEntry
- type DigestFile
- type DirFS
- type Entry
- type ExemptRow
- type FS
- type Fatal
- type FileSpec
- type Finding
- type Keys
- type Matcher
- type Mode
- type PNGInfo
- type Report
- type ScanOptions
- type Scanner
- type TrackedFile
Constants ¶
const ( DigestVersion = 2 DigestAlgo = "hmac-sha256" )
Version and algorithm of the digest file format.
const ( WhyBinary = "binary" WhyOversize = "oversize" WhyLongRun = "longrun" WhySymlink = "symlink" WhySubmodule = "submodule" )
The reasons an exempt row may give.
const ( EnvKey = "OFFLOAD_LEAK_GATE_KEY" EnvKeyPrev = "OFFLOAD_LEAK_GATE_KEY_PREV" EnvKeyFile = "OFFLOAD_LEAK_GATE_KEY_FILE" EnvRequired = "OFFLOAD_LEAK_GATE_REQUIRED" )
Environment variable names the gate reads (the caller reads them; this package never touches the environment).
Variables ¶
var ( ErrMalformedKey = errors.New("malformed gate key") ErrMalformedPrevKey = errors.New("malformed previous gate key") ErrKeyFile = errors.New("gate key file") ErrKeyMissing = errors.New("key missing where secrets exist") ErrBadRequired = errors.New("unrecognized " + EnvRequired + " value") ErrMACMismatch = errors.New("digest file does not match this key") ErrBlind = errors.New("gate went blind") )
The messages are part of the contract: the behaviour matrix and the operator documentation quote them.
var ( ErrPNGSignature = errors.New("png: bad signature") ErrPNGOverflow = errors.New("png: chunk length overflows the file") ErrPNGNoIEND = errors.New("png: missing IEND") ErrPNGInflate = errors.New("png: compressed text over the 16 MiB cap") ErrPNGCorrupt = errors.New("png: corrupt compressed text chunk") )
The walk's fatal conditions.
Functions ¶
func AllowDigest ¶
AllowDigest is the keyed digest of an allow-row chunk (lower case).
func BlankEscapes ¶
BlankEscapes is pass B. It returns b itself and false when there is no escape to blank, and otherwise a copy with every escape replaced in place by spaces of the same length (so every column equals pass A's).
func CanaryText ¶
func CanaryText() string
CanaryText is the entry the generator always appends (mode sub).
func Fold ¶
Fold is pass A. Callers check NeedsFold first; on text with nothing to fold it returns an equal copy.
func NeedsFold ¶
NeedsFold reports whether b holds a byte at or above 0x80 or the two bytes \u, the only inputs the fold changes.
func ParseRequired ¶
ParseRequired reads OFFLOAD_LEAK_GATE_REQUIRED: empty is off, exactly "1" is on, anything else is an error (a typo must not silently switch the gate off).
func PatternBlock ¶
PatternBlock is the pattern lines bracketed by BEGIN and END marker comments, so a re-run replaces the block (ReplaceBlock).
func ReplaceBlock ¶
ReplaceBlock puts block into existing: in place of the previous BEGIN to END block when there is one, at the end of the text otherwise. block uses LF; a text that uses CRLF gets the block with CRLF.
func ResolveFileList ¶
ResolveFileList turns a parsed list into the set of tracked paths to scan. A path that is listed (not optional) and not tracked is an error, and so is a rename with both sides or neither side tracked.
func SelectKey ¶
func SelectKey(df *DigestFile, k Keys) ([]byte, error)
SelectKey picks the key that verifies the file: the current key, else the previous one (a rotation in flight). No key is ErrKeyMissing; neither verifying is ErrMACMismatch (the message says nothing about either key).
func ValidateEntries ¶
ValidateEntries applies the generator's validation to a list (entries are normalized first): at least four characters for sub, subcs and word, three for exact, two or three words for a phrase, ASCII letters and digits only (spaces only between phrase words), no duplicate within a mode.
Types ¶
type AllowRow ¶
AllowRow allows one finding: Where is "name" or "body", D the keyed digest (AllowDigest) of the lower-case chunk of [A-Za-z0-9_.-] around the finding. No row ships today.
type Classes ¶
type Classes struct {
Runs96 int // runs over 96 characters
Binaries int // unknown binary files (name scanned only)
PNGNonStd int // PNG files with a chunk other than IHDR, tEXt, IDAT, IEND
PNGAfterIEND int // PNG files with bytes after IEND
PNGCompressed int // PNG files with compressed text
PNGNoIEND int // PNG files that could not be walked to IEND
Oversize int
Symlink int
Submodule int
}
Classes count the inputs where the specified scanner and the reference oracle differ; each is a precondition of the parity check (zero, or the result is "not comparable").
type Decision ¶
type Decision struct {
Enforce bool // run the gate
SkipReason string // when not enforcing: the visible reason to log
}
Decision is what the tree gate does with the resolved keys.
type DigestEntry ¶
type DigestEntry struct {
D string `json:"d"`
Mode string `json:"mode"`
Len int `json:"len,omitempty"`
N int `json:"n,omitempty"`
F string `json:"f,omitempty"`
}
DigestEntry is one hashed entry. Len is the entry length (window modes), N the word count and F the first-word prefilter (phrases).
func EntryDigest ¶
func EntryDigest(key []byte, e Entry) DigestEntry
EntryDigest hashes one normalized entry.
type DigestFile ¶
type DigestFile struct {
Version int `json:"version"`
Algo string `json:"algo"`
MAC string `json:"mac"`
Entries []DigestEntry `json:"entries"`
Allow []AllowRow `json:"allow"`
Exempt []ExemptRow `json:"exempt"`
}
DigestFile is the parsed digest file.
func BuildDigest ¶
BuildDigest hashes a plaintext list (plus the canary, which it always appends) under key and returns the signed digest file. The list is validated; allow and exempt rows are copied, sorted and validated.
func ParseDigest ¶
func ParseDigest(b []byte) (*DigestFile, error)
ParseDigest reads a digest file strictly (unknown fields, trailing data and every structural defect are errors). It does not verify the mac: that needs the key (SelectKey).
func (*DigestFile) ComputeMAC ¶
func (df *DigestFile) ComputeMAC(key []byte) string
ComputeMAC is HMAC-SHA256(key, "leakgate/2" + the canonical text of the entries, allow rows and exempt rows), as hex.
func (*DigestFile) Marshal ¶
func (df *DigestFile) Marshal() ([]byte, error)
Marshal is the committed form: LF line endings, one row per line, one trailing newline, byte-for-byte reproducible.
func (*DigestFile) Validate ¶
func (df *DigestFile) Validate() error
Validate checks the structure of the file without a key: version and algorithm, hex lengths, entries sorted by digest and unique, per-mode field rules, and sorted unique allow and exempt rows with known places and reasons.
func (*DigestFile) VerifyMAC ¶
func (df *DigestFile) VerifyMAC(key []byte) bool
VerifyMAC reports whether the file's mac is the one key computes.
type DirFS ¶
type DirFS struct{ Root string }
DirFS reads tracked paths (slash-separated, relative) from a work tree.
type Entry ¶
Entry is one denied name. Text is normalized: lower case (case preserved for subcs) and, for a phrase, words joined by one space.
func ParseList ¶
ParseList reads the plaintext list: one entry per line, `mode<TAB>text`, a line whose first non-blank character is `#` is a comment. Entries are normalized and validated; an error names the line and never the entry text (the text may be a real name and error messages travel).
func WithCanary ¶
WithCanary returns a copy of es with the canary appended.
type ExemptRow ¶
type ExemptRow struct {
Path string `json:"path"`
Blob string `json:"blob"`
Why string `json:"why"`
}
ExemptRow exempts one file from one fail-closed rule, bound to the file's git blob id so editing the file un-exempts it.
type FS ¶
FS is how the scan reaches file contents: the work tree, the blobs of a commit, or memory in a test.
Read returns the file's size and, when size <= max, its bytes. A larger file is not read (data is nil and size says how large it is). A missing file is an error satisfying errors.Is(err, fs.ErrNotExist).
type Fatal ¶
Fatal is a fail-closed record: a path (empty for a whole-scan condition), a line for a run over the limit, and a reason that never carries matched text.
type FileSpec ¶
FileSpec is one parsed entry: either Path (Optional or not), or Old and New.
func ParseFileList ¶
ParseFileList parses a -files list.
type Finding ¶
Finding is one hit. Path is the tracked path; a name finding (Name) is a hit in the path itself. Line is 1-based; Col is the 1-based byte offset in the folded line. A plaintext matcher fills Text with the entry text; a digest matcher fills ID with the first four bytes of the entry digest (hex) and leaves Text empty, so its output never carries matched text. Shape findings carry the rule name in Text.
func ShapeFindings ¶
ShapeFindings applies both rules to one text body (the bytes as read, after UTF-16 decoding or PNG text extraction, before the fold). The column is the 1-based byte offset of the match in its line.
func (Finding) DisplayPath ¶
DisplayPath is Path, with " (name)" appended for a name finding.
type Keys ¶
Keys are the resolved keys: Key is the current key and Prev the previous one (rotation), each nil when unset.
func ResolveKey ¶
func ResolveKey(getenv func(string) string, readFile func(string) ([]byte, error), defaultFile string) (Keys, error)
ResolveKey resolves the gate key and the previous key.
- OFFLOAD_LEAK_GATE_KEY, when non-empty, must be 64 hex characters, else ErrMalformedKey; the key file is then never read.
- Else OFFLOAD_LEAK_GATE_KEY_FILE, when non-empty: the file must exist, be readable and hold 64 hex characters, else ErrKeyFile (the operator asked for that file).
- Else defaultFile, when given and the file exists (present but unreadable or malformed is ErrKeyFile; absent is unset).
OFFLOAD_LEAK_GATE_KEY_PREV is read only when a key was found: empty is ignored, non-empty must be 64 hex characters (else ErrMalformedPrevKey), and it never counts as the key by itself. With no key, a previous key (valid or not) is ignored: the gate is keyless and the rows for a missing key apply.
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher is the compiled entry list, either plaintext (NewPlainMatcher) or keyed (NewDigestMatcher). It is read-only after construction and safe for concurrent use; the mutable scan state lives in a Scanner.
func NewDigestMatcher ¶
func NewDigestMatcher(df *DigestFile, key []byte) (*Matcher, error)
NewDigestMatcher compiles a digest file with its key. The caller has already chosen the key that verifies the file's MAC (SelectKey); this checks the file's structure and builds the tables from the digests alone.
func NewPlainMatcher ¶
NewPlainMatcher compiles a plaintext list (used by the local scanner, the parity check and the tests). Entries are normalized and validated.
func (*Matcher) NewScanner ¶
NewScanner returns a scanner of m. A Scanner is not safe for concurrent use.
func (*Matcher) ScanName ¶
ScanName scans a tracked path as one line; the findings are name findings.
type Mode ¶
type Mode string
Mode is how an entry matches. See the package documentation of the design:
sub any window of one alphanumeric run (lower case)
word a sub window with letter boundaries (a camel cut, a digit or a
non-letter ends a word; a plural or a longer word does not match)
exact the whole run equals the entry (no camel splitting)
subcs a sub window compared as written, case preserved
phrase two or three consecutive runs on one line
type PNGInfo ¶
type PNGInfo struct {
Segments [][]byte
NonStd bool // a chunk other than IHDR, tEXt, IDAT and IEND
AfterIEND bool // bytes after IEND
CompressedText bool // a zTXt chunk or a compressed iTXt chunk
NoIEND bool // no IEND reached: truncated, or a length that overflows the file
}
PNGInfo is what the walk found. Segments are the byte ranges to scan, in a fixed order: the text chunks first (tEXt, zTXt and iTXt, in file order; the keyword is kept and a compressed body is inflated), so that the line numbers of a text finding equal those of a scan of the text chunks alone; then the bodies of every other chunk but IDAT; then the bytes after IEND. A scan joins them with a newline.
type Report ¶
type Report struct {
Findings []Finding
Fatals []Fatal
Scanned int // files scanned (after the filter)
Total int // tracked files
Missing int // tracked paths missing from the work tree (name scanned only)
Classes Classes
}
Report is the result of a tree scan.
func ScanTree ¶
func ScanTree(m *Matcher, files []TrackedFile, fsys FS, opts ScanOptions) Report
ScanTree scans a set of tracked files. m may be nil: with Shapes set that is the keyless mode (shape rules and the fail-closed rows only, no name scan).
type ScanOptions ¶
type ScanOptions struct {
// Required: a tracked path missing from the work tree, and an empty file
// set, are fatal (a clean checkout is expected).
Required bool
// Shapes also applies the keyless shape rules.
Shapes bool
// Exempt rows exempt a file from one fail-closed rule.
Exempt []ExemptRow
// Allow rows allow one finding each (a keyed matcher only).
Allow []AllowRow
// Workers is the number of scanning goroutines (default: the CPU count).
Workers int
// MaxFile is the size limit in bytes (default 16 MiB).
MaxFile int64
// Filter, when set, restricts the scan to the paths it accepts; the rest are
// not scanned and not reported (they still count in Report.Total).
Filter func(path string) bool
}
ScanOptions configure ScanTree.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner is the per-goroutine scan state of a Matcher.
type TrackedFile ¶
TrackedFile is one row of `git ls-files -z -s`: the mode, the object id and the path. The library needs the mode to see symlinks and submodules.
func ParseLsFiles ¶
func ParseLsFiles(b []byte) ([]TrackedFile, error)
ParseLsFiles parses the output of `git ls-files -z -s`: "<mode> <object> <stage><TAB><path>" records, each ending in a NUL. A non-zero stage (an unmerged path) is an error.