From 17d47b375adf0ab964ece5d8f0b4d94428ad686a Mon Sep 17 00:00:00 2001 From: SuperQ Date: Tue, 23 Jun 2026 21:40:28 +0200 Subject: [PATCH] Fix crypto parsing panic Make sure that we don't panic when parsing invalid crypto files that have entries that don't start with a `name`. * Continuation of https://github.com/prometheus/procfs/pull/745 Signed-off-by: SuperQ --- crypto.go | 8 +++++++- crypto_test.go | 15 +++++++++++++++ testdata/fixtures.ttar | 17 +++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/crypto.go b/crypto.go index e4a5876e..d93b712e 100644 --- a/crypto.go +++ b/crypto.go @@ -48,11 +48,13 @@ type Crypto struct { Walksize *uint64 } +var cryptoFile = "crypto" + // Crypto parses an crypto-file (/proc/crypto) and returns a slice of // structs containing the relevant info. More information available here: // https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html func (fs FS) Crypto() ([]Crypto, error) { - path := fs.proc.Path("crypto") + path := fs.proc.Path(cryptoFile) b, err := util.ReadFileNoStat(path) if err != nil { return nil, fmt.Errorf("%w: Cannot read file %v: %w", ErrFileRead, b, err) @@ -82,6 +84,10 @@ func parseCrypto(r io.Reader) ([]Crypto, error) { continue } + if len(out) == 0 { + return nil, fmt.Errorf("%w: parsed invalid line before name parsed: %q", ErrFileParse, text) + } + kv := strings.Split(text, ":") if len(kv) != 2 { return nil, fmt.Errorf("%w: Cannot parse line: %q", ErrFileParse, text) diff --git a/crypto_test.go b/crypto_test.go index 794be9c0..0f83b9b2 100644 --- a/crypto_test.go +++ b/crypto_test.go @@ -14,6 +14,7 @@ package procfs import ( + "errors" "testing" "github.com/google/go-cmp/cmp" @@ -121,6 +122,20 @@ func TestFS_Crypto(t *testing.T) { } } +func TestFS_CryptoCorrupted(t *testing.T) { + cryptoFile = "crypto_corrupted" + fs := getProcFixtures(t) + crypto, err := fs.Crypto() + + if !errors.Is(err, ErrFileParse) { + t.Fatalf("expected ErrFileParse error, got: %s", err) + } + + if crypto != nil { + t.Fatalf("expected empty crypto result") + } +} + func newint64(i int64) *int64 { return &i } diff --git a/testdata/fixtures.ttar b/testdata/fixtures.ttar index c3753713..b4b14ffb 100644 --- a/testdata/fixtures.ttar +++ b/testdata/fixtures.ttar @@ -2265,6 +2265,23 @@ max keysize : 32 Mode: 444 Mode: 644 # ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/proc/crypto_corrupted +Lines: 13 +driver : ccm_base(ctr(aes-aesni),cbcmac(aes-aesni)) +name : ccm(aes) +module : ccm +priority : 300 +refcnt : 4 +selftest : passed +internal : no +type : aead +async : no +blocksize : 1 +ivsize : 16 +maxauthsize : 16 +geniv : +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Path: fixtures/proc/diskstats Lines: 52 1 0 ram0 0 0 0 0 0 0 0 0 0 0 0