From 45303b7143d2a31b11e48d4cf65e688545e4534d Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 9 Nov 2026 20:00:47 +0100 Subject: [PATCH] feat(dkimsign): key generation, DNS record formatting and parsing helpers --- internal/dkimsign/dkimsign.go | 62 ++++++++++++++++++++ internal/dkimsign/dkimsign_test.go | 90 ++++++++++++++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/internal/dkimsign/dkimsign.go b/internal/dkimsign/dkimsign.go index 9bb067f..20fb26c 100644 --- a/internal/dkimsign/dkimsign.go +++ b/internal/dkimsign/dkimsign.go @@ -9,8 +9,10 @@ import ( "bytes" "crypto" "crypto/ed25519" + "crypto/rand" "crypto/rsa" "crypto/x509" + "encoding/base64" "encoding/pem" "errors" "fmt" @@ -164,3 +166,63 @@ func (s *Signer) Sign(msg []byte) ([]byte, error) { } return out.Bytes(), nil } + +// GenerateKeyPEM creates an RSA private key and returns it as PKCS#8 PEM. Use +// 2048 bits: every receiver verifies it and it fits a DNS record. +func GenerateKeyPEM(bits int) ([]byte, error) { + if bits < 1024 { + return nil, fmt.Errorf("RSA keys under 1024 bits are not accepted (use 2048)") + } + k, err := rsa.GenerateKey(rand.Reader, bits) + if err != nil { + return nil, err + } + der, err := x509.MarshalPKCS8PrivateKey(k) + if err != nil { + return nil, err + } + return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil +} + +// Record returns the DKIM DNS TXT value that publishes a public key. +func Record(pub crypto.PublicKey) (string, error) { + switch k := pub.(type) { + case *rsa.PublicKey: + der, err := x509.MarshalPKIXPublicKey(k) + if err != nil { + return "", err + } + return "v=DKIM1; k=rsa; p=" + base64.StdEncoding.EncodeToString(der), nil + case ed25519.PublicKey: + return "v=DKIM1; k=ed25519; p=" + base64.StdEncoding.EncodeToString(k), nil + } + return "", fmt.Errorf("unsupported public key type %T", pub) +} + +// RecordKey extracts the base64 public key (the p= tag, whitespace removed) +// from a DKIM TXT value. +func RecordKey(txt string) (string, bool) { + for _, tag := range strings.Split(txt, ";") { + name, value, ok := strings.Cut(strings.TrimSpace(tag), "=") + if ok && strings.TrimSpace(name) == "p" { + key := strings.Join(strings.Fields(value), "") + return key, key != "" + } + } + return "", false +} + +// SplitTXT cuts a TXT value into the strings of at most 255 bytes that a DNS +// record is made of. +func SplitTXT(value string) []string { + const max = 255 + var parts []string + for len(value) > max { + parts = append(parts, value[:max]) + value = value[max:] + } + if value != "" { + parts = append(parts, value) + } + return parts +} diff --git a/internal/dkimsign/dkimsign_test.go b/internal/dkimsign/dkimsign_test.go index 3d99bbe..c75635a 100644 --- a/internal/dkimsign/dkimsign_test.go +++ b/internal/dkimsign/dkimsign_test.go @@ -312,3 +312,93 @@ func TestLoadKeyRejectsUnusableFiles(t *testing.T) { t.Fatal("do not echo key bytes in errors") } } + +func TestGenerateKeyPEMProducesAUsableKey(t *testing.T) { + pemBytes, err := GenerateKeyPEM(2048) + if err != nil { + t.Fatal(err) + } + if !bytes.HasPrefix(pemBytes, []byte("-----BEGIN PRIVATE KEY-----")) { + t.Fatalf("PKCS#8 expected:\n%s", pemBytes) + } + path := filepath.Join(t.TempDir(), "k.pem") + os.WriteFile(path, pemBytes, 0o600) + key, err := LoadKey("lists.example.org", "mail", path) + if err != nil { + t.Fatal(err) + } + out, err := newSigner(t, key).Sign(message("dev@lists.example.org")) + if err != nil { + t.Fatal(err) + } + rec, err := Record(key.Signer.Public()) + if err != nil { + t.Fatal(err) + } + vs, err := dkim.VerifyWithOptions(bytes.NewReader(out), &dkim.VerifyOptions{ + LookupTXT: func(string) ([]string, error) { return []string{rec}, nil }, + }) + if err != nil || len(vs) != 1 || vs[0].Err != nil { + t.Fatalf("the generated key and its DNS record must work together: %v %+v", err, vs) + } + if _, err := GenerateKeyPEM(512); err == nil { + t.Fatal("keys that are too small must be refused") + } +} + +func TestRecordFormat(t *testing.T) { + k := rsaKey(t, 2048) + rec, err := Record(&k.PublicKey) + if err != nil { + t.Fatal(err) + } + der, _ := x509.MarshalPKIXPublicKey(&k.PublicKey) + if rec != "v=DKIM1; k=rsa; p="+base64.StdEncoding.EncodeToString(der) { + t.Fatalf("rsa record: %s", rec) + } + pub, _, _ := ed25519.GenerateKey(rand.Reader) + rec, _ = Record(pub) + if rec != "v=DKIM1; k=ed25519; p="+base64.StdEncoding.EncodeToString(pub) { + t.Fatalf("ed25519 record: %s", rec) + } + if _, err := Record("not a key"); err == nil { + t.Fatal("unsupported key type") + } +} + +func TestRecordKeyParsing(t *testing.T) { + for in, want := range map[string]string{ + "v=DKIM1; k=rsa; p=AAAA": "AAAA", + "v=DKIM1;k=rsa;p=AA AA": "AAAA", + "v=DKIM1; p=AAAA; t=y": "AAAA", + "p=AAAA": "AAAA", + "v=DKIM1; k=rsa; p=AAAA BBBB\tCCCC": "AAAABBBBCCCC", + } { + if got, ok := RecordKey(in); !ok || got != want { + t.Errorf("RecordKey(%q) = %q %v, want %q", in, got, ok, want) + } + } + for _, in := range []string{"", "v=spf1 -all", "v=DKIM1; k=rsa", "v=DKIM1; p="} { + if _, ok := RecordKey(in); ok { + t.Errorf("RecordKey(%q) must fail", in) + } + } +} + +func TestSplitTXTChunks(t *testing.T) { + for _, n := range []int{0, 1, 254, 255, 256, 400, 510, 511, 1000} { + v := strings.Repeat("a", n) + parts := SplitTXT(v) + if strings.Join(parts, "") != v { + t.Errorf("n=%d: the parts must rebuild the value", n) + } + for _, p := range parts { + if len(p) > 255 { + t.Errorf("n=%d: chunk of %d bytes exceeds the DNS limit", n, len(p)) + } + } + if want := (n + 254) / 255; n > 0 && len(parts) != want { + t.Errorf("n=%d: %d chunks, want %d", n, len(parts), want) + } + } +}