diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 2dfa020..81e4c80 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -51,6 +51,14 @@ Administration (talks to the REST API): queue ls outbound queue queue rm discard one queued delivery +DKIM (works offline, needs no token): + dkim keygen [--selector mail] [--out FILE] [--force] + create a signing key and print the DNS record and config + dkim record --key FILE [--selector mail] + print the DNS record of an existing key + dkim check --key FILE [--selector mail] + look the record up in DNS and compare it with the key + Daemon: serve [-config FILE] run the mailing list server @@ -94,6 +102,7 @@ func Run(args []string, io IO, getenv func(string) string) int { "held": {"ls": c.heldLs, "approve": c.heldApprove, "discard": c.heldDiscard}, "archive": {"ls": c.archiveLs, "show": c.archiveShow, "rm": c.archiveRm, "import": c.archiveImport}, "queue": {"ls": c.queueLs, "rm": c.queueRm}, + "dkim": {"keygen": c.dkimKeygen, "record": c.dkimRecord, "check": c.dkimCheck}, } group, ok := commands[rest[0]] if !ok { diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index f64aece..dacaa65 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -3,17 +3,25 @@ package cli import ( "bytes" "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" "encoding/json" + "encoding/pem" + "errors" "fmt" "io" "net/http" "net/http/httptest" "os" + "path/filepath" + "regexp" "strings" "testing" "time" "codeberg.org/squidd/parsimony/internal/api" + "codeberg.org/squidd/parsimony/internal/dkimsign" "codeberg.org/squidd/parsimony/internal/store" ) @@ -552,3 +560,203 @@ func TestArchiveImportSendsTheFileAsAnMbox(t *testing.T) { t.Fatalf("content type %q, body unchanged: %v", contentType, body == cliMbox) } } + +// --- dkim ---------------------------------------------------------------------- + +// noAuth runs a command that must not need the API token or URL. +func noAuth(t *testing.T, args ...string) (int, string, string) { + t.Helper() + var out, errb bytes.Buffer + code := Run(args, IO{In: strings.NewReader(""), Out: &out, Err: &errb}, func(string) string { return "" }) + return code, out.String(), errb.String() +} + +func TestDKIMKeygen(t *testing.T) { + dir := t.TempDir() + keyFile := filepath.Join(dir, "dkim.pem") + code, out, errs := noAuth(t, "dkim", "keygen", "example.org", "--out", keyFile) + if code != 0 { + t.Fatalf("exit %d: %s", code, errs) + } + info, err := os.Stat(keyFile) + if err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("the private key must be created with mode 0600: %v %v", err, info) + } + key, err := dkimsign.LoadKey("example.org", "mail", keyFile) + if err != nil { + t.Fatal(err) + } + want, _ := dkimsign.Record(key.Signer.Public()) + for _, s := range []string{ + "mail._domainkey.example.org.", "IN TXT", "Wrote private key to " + keyFile, + "dkim:", "domain: example.org", "selector: mail", "key_file: " + keyFile, want, + "parsimony dkim check example.org", + } { + if !strings.Contains(out, s) { + t.Errorf("output lacks %q:\n%s", s, out) + } + } + // The zone-file form is split in strings of at most 255 bytes. + for _, line := range strings.Split(out, "\n") { + if strings.Contains(line, "IN TXT") { + for _, q := range regexp.MustCompile(`"([^"]*)"`).FindAllStringSubmatch(line, -1) { + if len(q[1]) > 255 { + t.Fatalf("a TXT string of %d bytes exceeds the DNS limit", len(q[1])) + } + } + } + } + if strings.Contains(out, "PRIVATE KEY") { + t.Fatal("never print the private key") + } +} + +func TestDKIMKeygenOptions(t *testing.T) { + dir := t.TempDir() + keyFile := filepath.Join(dir, "k.pem") + code, out, _ := noAuth(t, "dkim", "keygen", "lists.example.org", "--selector", "s2024", "--out", keyFile) + if code != 0 || !strings.Contains(out, "s2024._domainkey.lists.example.org.") || !strings.Contains(out, "selector: s2024") { + t.Fatalf("selector: %d %s", code, out) + } + + first, _ := os.ReadFile(keyFile) + code, _, errs := noAuth(t, "dkim", "keygen", "lists.example.org", "--out", keyFile) + if code != 1 || !strings.Contains(errs, "already exists") { + t.Fatalf("an existing key must not be overwritten: %d %q", code, errs) + } + if again, _ := os.ReadFile(keyFile); !bytes.Equal(first, again) { + t.Fatal("the existing key was modified") + } + if code, _, errs := noAuth(t, "dkim", "keygen", "lists.example.org", "--out", keyFile, "--force"); code != 0 { + t.Fatalf("--force: %d %s", code, errs) + } + if replaced, _ := os.ReadFile(keyFile); bytes.Equal(first, replaced) { + t.Fatal("--force must replace the key") + } + if info, _ := os.Stat(keyFile); info.Mode().Perm() != 0o600 { + t.Fatalf("mode after --force: %v", info.Mode().Perm()) + } +} + +func TestDKIMKeygenDefaultFileName(t *testing.T) { + dir := t.TempDir() + old, _ := os.Getwd() + os.Chdir(dir) + defer os.Chdir(old) + if code, _, errs := noAuth(t, "dkim", "keygen", "example.org"); code != 0 { + t.Fatalf("%d %s", code, errs) + } + if _, err := os.Stat(filepath.Join(dir, "dkim-example.org.pem")); err != nil { + t.Fatalf("default file name: %v", err) + } +} + +func TestDKIMUsageErrors(t *testing.T) { + for name, args := range map[string][]string{ + "no domain": {"dkim", "keygen"}, + "domain with @": {"dkim", "keygen", "a@example.org"}, + "domain with space": {"dkim", "keygen", "my domain.org"}, + "no dot": {"dkim", "keygen", "localhost"}, + "bad selector": {"dkim", "keygen", "example.org", "--selector", "my sel"}, + "bits not a number": {"dkim", "keygen", "example.org", "--bits", "abc"}, + "record no key": {"dkim", "record", "example.org"}, + "check no key": {"dkim", "check", "example.org"}, + "unknown": {"dkim", "frobnicate"}, + } { + if code, _, errs := noAuth(t, args...); code != 2 { + t.Errorf("%s: exit %d, want 2 (%q)", name, code, errs) + } + } + if code, _, errs := noAuth(t, "dkim", "keygen", "example.org", "--bits", "512", "--out", filepath.Join(t.TempDir(), "k")); code != 1 || !strings.Contains(errs, "1024") { + t.Fatalf("a tiny key is refused: %d %q", code, errs) + } +} + +func writeKey(t *testing.T) (string, string) { + t.Helper() + dir := t.TempDir() + keyFile := filepath.Join(dir, "k.pem") + if code, _, errs := noAuth(t, "dkim", "keygen", "example.org", "--out", keyFile); code != 0 { + t.Fatalf("%d %s", code, errs) + } + key, _ := dkimsign.LoadKey("example.org", "mail", keyFile) + rec, _ := dkimsign.Record(key.Signer.Public()) + return keyFile, rec +} + +func TestDKIMRecord(t *testing.T) { + keyFile, rec := writeKey(t) + code, out, errs := noAuth(t, "dkim", "record", "example.org", "--key", keyFile) + if code != 0 || !strings.Contains(out, "mail._domainkey.example.org.") || !strings.Contains(out, rec) { + t.Fatalf("record: %d %q %q", code, out, errs) + } + code, out, _ = noAuth(t, "dkim", "record", "example.org", "--key", keyFile, "--selector", "x1") + if !strings.Contains(out, "x1._domainkey.example.org.") { + t.Fatalf("selector: %q", out) + } + if code, _, errs := noAuth(t, "dkim", "record", "example.org", "--key", "/nonexistent.pem"); code != 1 || errs == "" { + t.Fatalf("missing key: %d %q", code, errs) + } +} + +func withDNS(t *testing.T, records map[string][]string) *[]string { + t.Helper() + var asked []string + old := lookupTXT + lookupTXT = func(name string) ([]string, error) { + asked = append(asked, name) + if r, ok := records[name]; ok { + return r, nil + } + return nil, errors.New("no such host") + } + t.Cleanup(func() { lookupTXT = old }) + return &asked +} + +func TestDKIMCheck(t *testing.T) { + keyFile, rec := writeKey(t) + + asked := withDNS(t, map[string][]string{"mail._domainkey.example.org": {"v=spf1 -all", rec}}) + code, out, errs := noAuth(t, "dkim", "check", "example.org", "--key", keyFile) + if code != 0 || !strings.Contains(out, "OK") || len(*asked) != 1 || (*asked)[0] != "mail._domainkey.example.org" { + t.Fatalf("matching record: %d %q %q asked=%v", code, out, errs, *asked) + } + + withDNS(t, map[string][]string{"mail._domainkey.example.org": {"v=DKIM1; k=rsa; p=AAAAAAAA"}}) + code, _, errs = noAuth(t, "dkim", "check", "example.org", "--key", keyFile) + if code != 1 || !strings.Contains(errs, "different key") { + t.Fatalf("mismatch: %d %q", code, errs) + } + + withDNS(t, map[string][]string{}) + code, _, errs = noAuth(t, "dkim", "check", "example.org", "--key", keyFile) + if code != 1 || !strings.Contains(errs, "no DKIM record") || !strings.Contains(errs, "mail._domainkey.example.org") { + t.Fatalf("missing: %d %q", code, errs) + } + + withDNS(t, map[string][]string{"mail._domainkey.example.org": {"v=spf1 -all"}}) + if code, _, errs = noAuth(t, "dkim", "check", "example.org", "--key", keyFile); code != 1 || !strings.Contains(errs, "no DKIM record") { + t.Fatalf("only unrelated TXT records: %d %q", code, errs) + } + + asked = withDNS(t, map[string][]string{"s9._domainkey.example.org": {rec}}) + if code, _, errs = noAuth(t, "dkim", "check", "example.org", "--key", keyFile, "--selector", "s9"); code != 0 { + t.Fatalf("selector: %d %q asked=%v", code, errs, *asked) + } + if code, _, errs = noAuth(t, "dkim", "check", "example.org", "--key", "/nonexistent.pem"); code != 1 { + t.Fatalf("missing key file: %d %q", code, errs) + } +} + +func TestDKIMCheckEd25519Key(t *testing.T) { + pub, priv, _ := ed25519.GenerateKey(rand.Reader) + der, _ := x509.MarshalPKCS8PrivateKey(priv) + keyFile := filepath.Join(t.TempDir(), "ed.pem") + os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0o600) + rec, _ := dkimsign.Record(pub) + withDNS(t, map[string][]string{"mail._domainkey.example.org": {rec}}) + if code, out, errs := noAuth(t, "dkim", "check", "example.org", "--key", keyFile); code != 0 || !strings.Contains(out, "OK") { + t.Fatalf("%d %q %q", code, out, errs) + } +} diff --git a/internal/cli/dkim.go b/internal/cli/dkim.go new file mode 100644 index 0000000..1574cce --- /dev/null +++ b/internal/cli/dkim.go @@ -0,0 +1,185 @@ +package cli + +import ( + "errors" + "fmt" + "net" + "os" + "path/filepath" + "regexp" + "strings" + + "codeberg.org/squidd/parsimony/internal/dkimsign" +) + +// lookupTXT resolves DNS TXT records; tests replace it. +var lookupTXT = net.LookupTXT + +var ( + domainRe = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$`) + selectorRe = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`) +) + +// dkimTarget parses " --selector S ..." and validates domain and selector. +type dkimTarget struct { + domain, selector string +} + +func (t dkimTarget) recordName() string { return t.selector + "._domainkey." + t.domain } + +// zoneLine is the TXT record as it is written in a DNS zone file. +func (t dkimTarget) zoneLine(value string) string { + quoted := make([]string, 0, 2) + for _, p := range dkimsign.SplitTXT(value) { + quoted = append(quoted, `"`+p+`"`) + } + return fmt.Sprintf("%s. IN TXT %s", t.recordName(), strings.Join(quoted, " ")) +} + +func (c *cmd) dkimKeygen(args []string) int { + fs := newFlagSet("dkim keygen") + selector := fs.String("selector", "mail", "") + out := fs.String("out", "", "") + bits := fs.Int("bits", 2048, "") + force := fs.Bool("force", false, "") + pos, err := parseArgs(fs, args) + if err != nil { + return c.usageError("%v", err) + } + t, code := c.dkimDomain("dkim keygen [--selector S] [--out FILE] [--bits N] [--force]", pos, *selector) + if code != 0 { + return code + } + path := *out + if path == "" { + path = "dkim-" + t.domain + ".pem" + } + if abs, err := filepath.Abs(path); err == nil { + path = abs + } + pemBytes, err := dkimsign.GenerateKeyPEM(*bits) + if err != nil { + return c.fail(err) + } + flags := os.O_WRONLY | os.O_CREATE | os.O_EXCL + if *force { + flags = os.O_WRONLY | os.O_CREATE | os.O_TRUNC + } + f, err := os.OpenFile(path, flags, 0o600) + if errors.Is(err, os.ErrExist) { + return c.fail(fmt.Errorf("%s already exists (use --force to replace it)", path)) + } + if err != nil { + return c.fail(err) + } + if _, err := f.Write(pemBytes); err != nil { + f.Close() + return c.fail(err) + } + if err := f.Close(); err != nil { + return c.fail(err) + } + // An existing file keeps its old mode when truncated: make it private. + if err := os.Chmod(path, 0o600); err != nil { + return c.fail(err) + } + + key, err := dkimsign.LoadKey(t.domain, t.selector, path) + if err != nil { + return c.fail(err) + } + record, err := dkimsign.Record(key.Signer.Public()) + if err != nil { + return c.fail(err) + } + fmt.Fprintf(c.io.Out, "Wrote private key to %s (mode 0600)\n\n", path) + fmt.Fprintf(c.io.Out, "Publish this DNS TXT record:\n\n%s\n\n", t.zoneLine(record)) + fmt.Fprintf(c.io.Out, "Value, for a DNS control panel that wants one string:\n\n%s\n\n", record) + fmt.Fprintf(c.io.Out, "Then add this to the Parsimony config and restart it:\n\ndkim:\n - domain: %s\n selector: %s\n key_file: %s\n\n", t.domain, t.selector, path) + fmt.Fprintf(c.io.Out, "Check the record once it is published:\n\n parsimony dkim check %s --key %s --selector %s\n", t.domain, path, t.selector) + return 0 +} + +// dkimKeyArgs parses " --key FILE [--selector S]" and loads the key. +func (c *cmd) dkimKeyArgs(name string, args []string) (dkimTarget, dkimsign.Key, int) { + fs := newFlagSet(name) + selector := fs.String("selector", "mail", "") + keyFile := fs.String("key", "", "") + pos, err := parseArgs(fs, args) + if err != nil { + return dkimTarget{}, dkimsign.Key{}, c.usageError("%v", err) + } + t, code := c.dkimDomain(name+" --key FILE [--selector S]", pos, *selector) + if code != 0 { + return t, dkimsign.Key{}, code + } + if *keyFile == "" { + return t, dkimsign.Key{}, c.usageError("usage: parsimony %s --key FILE [--selector S]", name) + } + key, err := dkimsign.LoadKey(t.domain, t.selector, *keyFile) + if err != nil { + return t, dkimsign.Key{}, c.fail(err) + } + return t, key, 0 +} + +// dkimDomain validates the positional domain and the selector. +func (c *cmd) dkimDomain(usage string, pos []string, selector string) (dkimTarget, int) { + if len(pos) != 1 { + return dkimTarget{}, c.usageError("usage: parsimony %s", usage) + } + if !domainRe.MatchString(pos[0]) { + return dkimTarget{}, c.usageError("%q is not a valid domain name", pos[0]) + } + if !selectorRe.MatchString(selector) { + return dkimTarget{}, c.usageError("%q is not a valid selector", selector) + } + return dkimTarget{domain: strings.ToLower(pos[0]), selector: selector}, 0 +} + +func (c *cmd) dkimRecord(args []string) int { + t, key, code := c.dkimKeyArgs("dkim record", args) + if code != 0 { + return code + } + record, err := dkimsign.Record(key.Signer.Public()) + if err != nil { + return c.fail(err) + } + fmt.Fprintf(c.io.Out, "%s\n\nValue:\n\n%s\n", t.zoneLine(record), record) + return 0 +} + +func (c *cmd) dkimCheck(args []string) int { + t, key, code := c.dkimKeyArgs("dkim check", args) + if code != 0 { + return code + } + want, err := dkimsign.Record(key.Signer.Public()) + if err != nil { + return c.fail(err) + } + wantKey, _ := dkimsign.RecordKey(want) + + txts, err := lookupTXT(t.recordName()) + found := false + for _, txt := range txts { + got, ok := dkimsign.RecordKey(txt) + if !ok { + continue // not a DKIM record (no p= tag), for instance an SPF record + } + found = true + if got == wantKey { + fmt.Fprintf(c.io.Out, "OK: %s publishes the public key of this private key\n", t.recordName()) + return 0 + } + } + if !found { + reason := "" + if err != nil { + reason = fmt.Sprintf(" (%v)", err) + } + return c.fail(fmt.Errorf("no DKIM record at %s%s; publish the one from `parsimony dkim record`", t.recordName(), reason)) + } + return c.fail(fmt.Errorf("%s publishes a different key than this private key: the record is stale or belongs to another key", t.recordName())) +}