parsimony/internal/cli/dkim.go
tgiachi 1e223f1ad1 feat(cli): dkim keygen, record and check
- Create a signing key (mode 0600, never overwritten without --force) and print the DNS record and the config snippet
- Print the record of an existing key, split in DNS-sized strings
- Check that DNS publishes the key that matches the private key file
- Work offline of the API: no token needed
2026-11-09 20:01:36 +01:00

185 lines
5.6 KiB
Go

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 "<domain> --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 <domain> [--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 "<domain> --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+" <domain> --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 <domain> --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()))
}