Skip to content
Changes

Reference

privatekey · Nov 21, 2026

What this change means

Source files changed. The change could not be classified.

pkg/detectors/privatekey/cracker.go+28−2View file
@@ -2,9 +2,11 @@ package privatekey
22
33import (
44 "bytes"
5added: "context"
56 "crypto/x509"
67 _ "embed"
78 "errors"
9added: "fmt"
810
911 "golang.org/x/crypto/ssh"
1012)
@@ -19,10 +21,34 @@ func init() {
1921
2022var (
2123 ErrUncrackable = errors.New("unable to crack encryption")
24added: // ErrKDFTooExpensive is returned without attempting any passphrase when a
25added: // key's KDF is more expensive than the crack budget allows.
26added: ErrKDFTooExpensive = errors.New("key KDF is too expensive to crack")
2227)
2328
24removed: func Crack(in []byte) (any, string, error) {
25removed: for _, passphrase := range passphrases {
29added: // maxCrackRounds caps the bcrypt KDF round count this detector will attempt
30added: // to crack. The round count is chosen by whoever created the key and the KDF
31added: // cost is linear in rounds; OpenSSH's default is 16. 256 is 16x that default:
32added: // a single wrong guess on a key at the cap costs on the order of a second of
33added: // CPU, so a wordlist crack is hopeless within any bounded budget. x/crypto
34added: // refuses round counts above 2048 on its own; this lower cap keeps
35added: // hardened-but-legal keys from making each attempt that expensive. Division
36added: // of labor: the cap bounds what one attempt can cost, and the context check
37added: // below bounds the total, where the caller sets a deadline at all.
38added: const maxCrackRounds = 256
39added:
40added: func Crack(ctx context.Context, in []byte) (any, string, error) {
41added: if rounds, ok := opensshBcryptRounds(in); ok && rounds > maxCrackRounds {
42added: return nil, "", fmt.Errorf("%w: %d rounds exceeds cap of %d", ErrKDFTooExpensive, rounds, maxCrackRounds)
43added: }
44added: for i, passphrase := range passphrases {
45added: // A wrong passphrase costs a full KDF run whose cost is set by the
46added: // key's author, so stop between attempts once the caller's context is
47added: // done. The in-flight attempt cannot be interrupted:
48added: // ssh.ParseRawPrivateKeyWithPassphrase takes no context.
49added: if err := ctx.Err(); err != nil {
50added: return nil, "", fmt.Errorf("stopped cracking after %d of %d passphrase attempts: %w", i, len(passphrases), err)
51added: }
2652 parsed, err := ssh.ParseRawPrivateKeyWithPassphrase(in, passphrase)
2753 if err != nil {
2854 if errors.Is(err, x509.IncorrectPasswordError) {
pkg/detectors/privatekey/openssh.go+83−0View file
@@ -0,0 +1,83 @@
1added: package privatekey
2added:
3added: import (
4added: "encoding/pem"
5added: "math"
6added:
7added: "golang.org/x/crypto/ssh"
8added: )
9added:
10added: // privateKeyAuthMagic starts the decoded body of every key in the OpenSSH
11added: // private key format (see PROTOCOL.key in the OpenSSH source distribution).
12added: const privateKeyAuthMagic = "openssh-key-v1\x00"
13added:
14added: // openSSHEncryptedPrivateKey and kdfOpts mirror the wire structs x/crypto
15added: // parses the same bytes with in ssh/keys.go, so the round count read here is
16added: // the round count the KDF will actually run at. Keep them in sync with
17added: // x/crypto's private structs: if the parses ever diverge, the count read
18added: // here silently stops matching the KDF's cost and keys are over- or
19added: // under-refused. x/crypto exports no way to read the KDF options, so the
20added: // header is read in the detector.
21added: type openSSHEncryptedPrivateKey struct {
22added: CipherName string
23added: KdfName string
24added: KdfOpts string
25added: NumKeys uint32
26added: PubKey []byte
27added: PrivKeyBlock []byte
28added: // Rest swallows trailing bytes the way x/crypto's copy of this struct
29added: // does. Without the tag, a key with bytes after PrivKeyBlock would fail
30added: // to parse here, read as ok=false, and skip the cap check that
31added: // x/crypto would still apply.
32added: Rest []byte `ssh:"rest"`
33added: }
34added:
35added: // kdfOpts deliberately has no ssh:"rest" field: that is what makes
36added: // ssh.Unmarshal reject options blobs carrying trailing bytes, which is the
37added: // fail-closed path below. Adding one for forward compatibility would
38added: // silently disarm it.
39added: type kdfOpts struct {
40added: Salt string
41added: Rounds uint32
42added: }
43added:
44added: // opensshBcryptRounds reads the bcrypt round count from an OpenSSH key's
45added: // header. The decoded key stores the cipher name, KDF name, and KDF options
46added: // before the encrypted section, so the round count is readable without the
47added: // passphrase; Crack uses it to refuse keys whose KDF exceeds maxCrackRounds
48added: // before spending any passphrase attempt.
49added: //
50added: // ok=false means the key is not an OpenSSH bcrypt key, and it should be
51added: // cracked exactly as before. ok=true means the round count is binding,
52added: // including fail-closed: a bcrypt key whose options blob does not parse
53added: // returns the maximum round count rather than ok=false, because the key is
54added: // a bcrypt key and should be refused, not silently cracked. ssh.Unmarshal
55added: // rejects such a blob as well, so the key could not have been decrypted at
56added: // any round count.
57added: func opensshBcryptRounds(pemBytes []byte) (rounds uint32, ok bool) {
58added: block, _ := pem.Decode(pemBytes)
59added: if block == nil || block.Type != "OPENSSH PRIVATE KEY" ||
60added: len(block.Bytes) < len(privateKeyAuthMagic) ||
61added: string(block.Bytes[:len(privateKeyAuthMagic)]) != privateKeyAuthMagic {
62added: return 0, false
63added: }
64added:
65added: var w openSSHEncryptedPrivateKey
66added: if err := ssh.Unmarshal(block.Bytes[len(privateKeyAuthMagic):], &w); err != nil {
67added: return 0, false
68added: }
69added: if w.KdfName != "bcrypt" {
70added: return 0, false
71added: }
72added:
73added: ok = true
74added:
75added: var opts kdfOpts
76added: if err := ssh.Unmarshal([]byte(w.KdfOpts), &opts); err != nil {
77added: rounds = math.MaxUint32
78added: } else {
79added: rounds = opts.Rounds
80added: }
81added:
82added: return rounds, ok
83added: }
pkg/detectors/privatekey/privatekey.go+8−6View file
@@ -79,13 +79,15 @@ func (s Scanner) FromData(ctx context.Context, verify bool, data []byte) (result
7979 parsedKey, err := ssh.ParseRawPrivateKey([]byte(token))
8080 if err != nil && strings.Contains(err.Error(), "private key is passphrase protected") {
8181 s1.ExtraData["encrypted"] = "true"
82removed: parsedKey, passphrase, err = Crack([]byte(token))
82added: parsedKey, passphrase, err = Crack(ctx, []byte(token))
8383 if err != nil {
84removed: // The key is encrypted and the passphrase could not be
85removed: // recovered from the wordlist. It still represents a real
86removed: // exposure (offline-crackable, weak/legacy KDFs, passphrase
87removed: // often reused or committed nearby), so surface it as an
88removed: // unverified finding instead of dropping it silently.
84added: // The key is encrypted but could not be cracked: the
85added: // passphrase is not in the wordlist, the key's KDF exceeded
86added: // the crack budget, or the scan context ended first. It still
87added: // represents a real exposure (offline-crackable, weak/legacy
88added: // KDFs, passphrase often reused or committed nearby), so
89added: // surface it as an unverified finding instead of dropping it
90added: // silently.
8991 s1.SetVerificationError(err, token)
9092 results = append(results, s1)
9193 continue