228 lines
6.5 KiB
Go
228 lines
6.5 KiB
Go
// Package dkimsign signs outgoing messages with DKIM.
|
|
//
|
|
// The signing domain comes from the address in the message's From header: a key
|
|
// for that exact domain, else a key for one of its parent domains (relaxed
|
|
// alignment). A message from a domain without a key is left unsigned.
|
|
package dkimsign
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"encoding/base64"
|
|
"encoding/pem"
|
|
"errors"
|
|
"fmt"
|
|
"net/mail"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/emersion/go-msgauth/dkim"
|
|
)
|
|
|
|
// headerKeys are the header fields covered by the signature. The list headers
|
|
// are included so a recipient can trust the unsubscribe links. Received and
|
|
// Return-Path are left out: MTAs add them on the way.
|
|
var headerKeys = []string{
|
|
"From", "To", "Cc", "Subject", "Date", "Message-ID", "In-Reply-To", "References", "Reply-To",
|
|
"MIME-Version", "Content-Type", "Content-Transfer-Encoding",
|
|
"List-Id", "List-Post", "List-Unsubscribe", "List-Unsubscribe-Post",
|
|
}
|
|
|
|
var selectorRe = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`)
|
|
|
|
// Key is a signing key for one domain.
|
|
type Key struct {
|
|
Domain string
|
|
Selector string
|
|
Signer crypto.Signer // *rsa.PrivateKey or ed25519.PrivateKey
|
|
}
|
|
|
|
// Signer signs messages with the key that matches their From domain.
|
|
type Signer struct {
|
|
keys map[string]Key // by lowercase domain
|
|
}
|
|
|
|
// New builds a Signer. Domains must be unique.
|
|
func New(keys []Key) (*Signer, error) {
|
|
s := &Signer{keys: map[string]Key{}}
|
|
for _, k := range keys {
|
|
k.Domain = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(k.Domain), "."))
|
|
switch {
|
|
case k.Domain == "":
|
|
return nil, errors.New("dkim: a key needs a domain")
|
|
case !selectorRe.MatchString(k.Selector):
|
|
return nil, fmt.Errorf("dkim: invalid selector %q for %s", k.Selector, k.Domain)
|
|
case k.Signer == nil:
|
|
return nil, fmt.Errorf("dkim: no private key for %s", k.Domain)
|
|
}
|
|
switch k.Signer.Public().(type) {
|
|
case *rsa.PublicKey, ed25519.PublicKey:
|
|
default:
|
|
return nil, fmt.Errorf("dkim: unsupported key type for %s", k.Domain)
|
|
}
|
|
if _, dup := s.keys[k.Domain]; dup {
|
|
return nil, fmt.Errorf("dkim: more than one key for %s", k.Domain)
|
|
}
|
|
s.keys[k.Domain] = k
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// LoadKey reads a PEM private key file (PKCS#1 or PKCS#8; RSA or Ed25519).
|
|
func LoadKey(domain, selector, path string) (Key, error) {
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return Key{}, err
|
|
}
|
|
block, _ := pem.Decode(raw)
|
|
if block == nil {
|
|
return Key{}, fmt.Errorf("%s: not a PEM file", path)
|
|
}
|
|
var priv crypto.Signer
|
|
switch block.Type {
|
|
case "RSA PRIVATE KEY":
|
|
k, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
|
if err != nil {
|
|
return Key{}, fmt.Errorf("%s: invalid RSA private key", path)
|
|
}
|
|
priv = k
|
|
case "PRIVATE KEY":
|
|
k, err := x509.ParsePKCS8PrivateKey(block.Bytes)
|
|
if err != nil {
|
|
return Key{}, fmt.Errorf("%s: invalid PKCS#8 private key", path)
|
|
}
|
|
switch k := k.(type) {
|
|
case *rsa.PrivateKey:
|
|
priv = k
|
|
case ed25519.PrivateKey:
|
|
priv = k
|
|
default:
|
|
return Key{}, fmt.Errorf("%s: unsupported key type %T (use RSA or Ed25519)", path, k)
|
|
}
|
|
default:
|
|
return Key{}, fmt.Errorf("%s: unsupported PEM type %q", path, block.Type)
|
|
}
|
|
return Key{Domain: domain, Selector: selector, Signer: priv}, nil
|
|
}
|
|
|
|
// fromDomain returns the lowercase domain of the first address in From.
|
|
func fromDomain(msg []byte) (string, bool) {
|
|
m, err := mail.ReadMessage(bytes.NewReader(msg))
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
addrs, err := m.Header.AddressList("From")
|
|
if err != nil || len(addrs) == 0 {
|
|
return "", false
|
|
}
|
|
at := strings.LastIndex(addrs[0].Address, "@")
|
|
if at < 0 || at == len(addrs[0].Address)-1 {
|
|
return "", false
|
|
}
|
|
return strings.ToLower(addrs[0].Address[at+1:]), true
|
|
}
|
|
|
|
func (s *Signer) keyFor(domain string) (Key, bool) {
|
|
for {
|
|
if k, ok := s.keys[domain]; ok {
|
|
return k, true
|
|
}
|
|
i := strings.Index(domain, ".")
|
|
if i < 0 {
|
|
return Key{}, false
|
|
}
|
|
domain = domain[i+1:]
|
|
}
|
|
}
|
|
|
|
// Sign returns msg with a DKIM-Signature header in front. When no key applies
|
|
// (or the message has no usable From) it returns msg unchanged and no error.
|
|
func (s *Signer) Sign(msg []byte) ([]byte, error) {
|
|
domain, ok := fromDomain(msg)
|
|
if !ok {
|
|
return msg, nil
|
|
}
|
|
key, ok := s.keyFor(domain)
|
|
if !ok {
|
|
return msg, nil
|
|
}
|
|
var out bytes.Buffer
|
|
err := dkim.Sign(&out, bytes.NewReader(msg), &dkim.SignOptions{
|
|
Domain: key.Domain,
|
|
Selector: key.Selector,
|
|
Signer: key.Signer,
|
|
Hash: crypto.SHA256,
|
|
HeaderCanonicalization: dkim.CanonicalizationRelaxed,
|
|
BodyCanonicalization: dkim.CanonicalizationRelaxed,
|
|
HeaderKeys: headerKeys,
|
|
})
|
|
if err != nil {
|
|
return msg, fmt.Errorf("dkim sign for %s: %w", key.Domain, err)
|
|
}
|
|
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
|
|
}
|