age,cmd/age: detect invalid UTF-8 in identity and recipient files

For #663
This commit is contained in:
Filippo Valsorda
2025-12-23 23:05:34 +01:00
parent a7586b7557
commit 2e0f1efe4d
2 changed files with 18 additions and 6 deletions

View File

@@ -11,6 +11,7 @@ import (
"io"
"os"
"strings"
"unicode/utf8"
"filippo.io/age"
"filippo.io/age/agessh"
@@ -77,6 +78,9 @@ func parseRecipientsFile(name string) ([]age.Recipient, error) {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if !utf8.ValidString(line) {
return nil, fmt.Errorf("%q: recipients file is not valid UTF-8", name)
}
if len(line) > lineLengthLimit {
return nil, fmt.Errorf("%q: line %d is too long", name, n)
}
@@ -226,19 +230,20 @@ func parseIdentities(f io.Reader) ([]age.Identity, error) {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if !utf8.ValidString(line) {
return nil, fmt.Errorf("identities file is not valid UTF-8")
}
i, err := parseIdentity(line)
if err != nil {
return nil, fmt.Errorf("error at line %d: %v", n, err)
}
ids = append(ids, i)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read secret keys file: %v", err)
return nil, fmt.Errorf("failed to read identities file: %v", err)
}
if len(ids) == 0 {
return nil, fmt.Errorf("no secret keys found")
return nil, fmt.Errorf("no identities found")
}
return ids, nil
}

View File

@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"strings"
"unicode/utf8"
)
// ParseIdentities parses a file with one or more private key encodings, one per
@@ -31,6 +32,9 @@ func ParseIdentities(f io.Reader) ([]Identity, error) {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if !utf8.ValidString(line) {
return nil, fmt.Errorf("identities file is not valid UTF-8")
}
i, err := parseIdentity(line)
if err != nil {
return nil, fmt.Errorf("error at line %d: %v", n, err)
@@ -38,10 +42,10 @@ func ParseIdentities(f io.Reader) ([]Identity, error) {
ids = append(ids, i)
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read secret keys file: %v", err)
return nil, fmt.Errorf("failed to read identities file: %v", err)
}
if len(ids) == 0 {
return nil, fmt.Errorf("no secret keys found")
return nil, fmt.Errorf("no identities found")
}
return ids, nil
}
@@ -78,6 +82,9 @@ func ParseRecipients(f io.Reader) ([]Recipient, error) {
if strings.HasPrefix(line, "#") || line == "" {
continue
}
if !utf8.ValidString(line) {
return nil, fmt.Errorf("recipients file is not valid UTF-8")
}
r, err := parseRecipient(line)
if err != nil {
// Hide the error since it might unintentionally leak the contents