first commit
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
// Package dkim implements DKIM (RFC 6376) signing for outbound mail using
|
||||
// only stdlib crypto — no third-party DKIM library. Verification of inbound
|
||||
// DKIM signatures is added in Phase 4's security pipeline.
|
||||
package dkim
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// KeyPair holds a freshly generated DKIM signing key, both as PEM (for
|
||||
// encrypted storage) and the DNS TXT record value the operator must publish.
|
||||
type KeyPair struct {
|
||||
PrivateKeyPEM []byte // PKCS#1 PEM — store encrypted in domains.dkim_private_key_enc
|
||||
DNSRecordValue string // paste into: {selector}._domainkey.{domain} TXT record
|
||||
}
|
||||
|
||||
// GenerateKeyPair creates a new RSA-2048 DKIM key pair. RSA-2048 is used
|
||||
// (rather than Ed25519) because it has universal support across mail
|
||||
// receivers — Ed25519 DKIM (RFC 8463) support is not yet ubiquitous.
|
||||
func GenerateKeyPair() (*KeyPair, error) {
|
||||
priv, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("generating RSA key: %w", err)
|
||||
}
|
||||
|
||||
privDER := x509.MarshalPKCS1PrivateKey(priv)
|
||||
privPEM := pem.EncodeToMemory(&pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: privDER,
|
||||
})
|
||||
|
||||
pubDER, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshaling public key: %w", err)
|
||||
}
|
||||
pubB64 := base64.StdEncoding.EncodeToString(pubDER)
|
||||
|
||||
dnsValue := fmt.Sprintf("v=DKIM1; k=rsa; p=%s", pubB64)
|
||||
|
||||
return &KeyPair{
|
||||
PrivateKeyPEM: privPEM,
|
||||
DNSRecordValue: dnsValue,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParsePrivateKey decodes a PEM-encoded RSA private key (as produced by
|
||||
// GenerateKeyPair, after decryption from storage).
|
||||
func ParsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error) {
|
||||
block, _ := pem.Decode(pemBytes)
|
||||
if block == nil {
|
||||
return nil, fmt.Errorf("no PEM block found")
|
||||
}
|
||||
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parsing RSA private key: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ExtractSignatureInfo pulls the signing domain and selector out of a
|
||||
// message's DKIM-Signature header, without doing any verification — the
|
||||
// caller uses this to know which DNS TXT record to fetch before calling
|
||||
// Verify. Returns found=false if no DKIM-Signature header is present.
|
||||
func ExtractSignatureInfo(raw []byte) (domain, selector string, found bool) {
|
||||
headers, _ := splitMessage(raw)
|
||||
headerMap := parseHeaders(headers)
|
||||
sigHeader, ok := headerMap["dkim-signature"]
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
tags := parseDKIMTags(sigHeader)
|
||||
domain = tags["d"]
|
||||
selector = tags["s"]
|
||||
return domain, selector, domain != "" && selector != ""
|
||||
}
|
||||
|
||||
// ParseDNSPublicKey decodes the "p=" tag value from a DKIM DNS TXT record
|
||||
// (as published by GenerateKeyPair's DNSRecordValue, or any RFC 6376
|
||||
// compliant record) into the raw public key DER bytes Verify expects.
|
||||
func ParseDNSPublicKey(txtRecord string) ([]byte, error) {
|
||||
tags := parseDKIMTags(txtRecord)
|
||||
pValue, ok := tags["p"]
|
||||
if !ok || pValue == "" {
|
||||
return nil, fmt.Errorf("no p= tag found in DNS record")
|
||||
}
|
||||
return base64.StdEncoding.DecodeString(pValue)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package dkim
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// signedHeaders is the fixed set of headers we sign, in order, when present.
|
||||
// Keeping this list small and stable avoids the classic DKIM pitfall of
|
||||
// signing headers that get legitimately rewritten in transit (Received, etc).
|
||||
var signedHeaders = []string{"from", "to", "subject", "date", "message-id"}
|
||||
|
||||
// Sign adds a DKIM-Signature header to raw using relaxed/relaxed
|
||||
// canonicalization and RSA-SHA256, per RFC 6376. Returns the message with
|
||||
// the DKIM-Signature header prepended.
|
||||
func Sign(privateKeyPEM []byte, domain, selector string, raw []byte) ([]byte, error) {
|
||||
key, err := ParsePrivateKey(privateKeyPEM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
headers, body := splitMessage(raw)
|
||||
bodyCanon := canonicalizeBodyRelaxed(body)
|
||||
bodyHash := sha256.Sum256(bodyCanon)
|
||||
bodyHashB64 := base64.StdEncoding.EncodeToString(bodyHash[:])
|
||||
|
||||
headerMap := parseHeaders(headers)
|
||||
|
||||
var presentSigned []string
|
||||
for _, h := range signedHeaders {
|
||||
if _, ok := headerMap[h]; ok {
|
||||
presentSigned = append(presentSigned, h)
|
||||
}
|
||||
}
|
||||
if len(presentSigned) == 0 {
|
||||
return nil, fmt.Errorf("no signable headers present in message")
|
||||
}
|
||||
|
||||
// Build the DKIM-Signature header with an empty b= tag first — this
|
||||
// unsigned version is itself included (relaxed-canonicalized) in what we
|
||||
// sign, per RFC 6376 §3.7.
|
||||
dkimHeaderTemplate := buildDKIMHeader(domain, selector, presentSigned, bodyHashB64, "")
|
||||
|
||||
signInput := canonicalizeHeadersRelaxed(headerMap, presentSigned)
|
||||
signInput = append(signInput, canonicalizeHeaderRelaxed("dkim-signature", dkimHeaderTemplate)...)
|
||||
// Per spec, the DKIM-Signature header itself is canonicalized WITHOUT a
|
||||
// trailing CRLF when it's the last (signed) header being hashed.
|
||||
signInput = bytes.TrimSuffix(signInput, []byte("\r\n"))
|
||||
|
||||
hashed := sha256.Sum256(signInput)
|
||||
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hashed[:])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("signing: %w", err)
|
||||
}
|
||||
sigB64 := base64.StdEncoding.EncodeToString(signature)
|
||||
|
||||
finalHeader := buildDKIMHeader(domain, selector, presentSigned, bodyHashB64, sigB64)
|
||||
|
||||
var out bytes.Buffer
|
||||
out.WriteString("DKIM-Signature: ")
|
||||
out.WriteString(finalHeader)
|
||||
out.WriteString("\r\n")
|
||||
out.Write(headers)
|
||||
out.Write(body)
|
||||
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
func buildDKIMHeader(domain, selector string, signedHdrs []string, bodyHashB64, sigB64 string) string {
|
||||
return fmt.Sprintf(
|
||||
"v=1; a=rsa-sha256; c=relaxed/relaxed; d=%s; s=%s; t=%d; h=%s; bh=%s; b=%s",
|
||||
domain, selector, time.Now().Unix(), strings.Join(signedHdrs, ":"), bodyHashB64, sigB64,
|
||||
)
|
||||
}
|
||||
|
||||
// splitMessage separates the raw RFC 5322 message into its header block
|
||||
// (including the trailing blank line's CRLF) and body.
|
||||
func splitMessage(raw []byte) (headers, body []byte) {
|
||||
sep := []byte("\r\n\r\n")
|
||||
idx := bytes.Index(raw, sep)
|
||||
if idx == -1 {
|
||||
// Tolerate bare-LF input (shouldn't happen from our own DATA reader,
|
||||
// which always produces CRLF, but be defensive).
|
||||
sep = []byte("\n\n")
|
||||
idx = bytes.Index(raw, sep)
|
||||
if idx == -1 {
|
||||
return raw, nil
|
||||
}
|
||||
}
|
||||
return raw[:idx+len(sep)], raw[idx+len(sep):]
|
||||
}
|
||||
|
||||
// parseHeaders builds a lowercase-name -> raw-value-with-original-case map,
|
||||
// unfolding continuation lines (RFC 5322 §2.2.3).
|
||||
func parseHeaders(headerBlock []byte) map[string]string {
|
||||
result := map[string]string{}
|
||||
lines := strings.Split(string(headerBlock), "\r\n")
|
||||
|
||||
var currentName, currentValue string
|
||||
flush := func() {
|
||||
if currentName != "" {
|
||||
result[strings.ToLower(currentName)] = currentValue
|
||||
}
|
||||
}
|
||||
|
||||
for _, line := range lines {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
if (strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t")) && currentName != "" {
|
||||
currentValue += " " + strings.TrimSpace(line)
|
||||
continue
|
||||
}
|
||||
flush()
|
||||
name, value, found := strings.Cut(line, ":")
|
||||
if !found {
|
||||
currentName = ""
|
||||
continue
|
||||
}
|
||||
currentName = strings.TrimSpace(name)
|
||||
currentValue = strings.TrimSpace(value)
|
||||
}
|
||||
flush()
|
||||
return result
|
||||
}
|
||||
|
||||
// canonicalizeHeadersRelaxed builds the signed-header block per RFC 6376
|
||||
// §3.4.2: lowercase header name, unfold, collapse WSP runs to single space,
|
||||
// trim trailing WSP on the value, each header terminated with CRLF, in the
|
||||
// exact order listed by names.
|
||||
func canonicalizeHeadersRelaxed(headerMap map[string]string, names []string) []byte {
|
||||
var buf bytes.Buffer
|
||||
for _, name := range names {
|
||||
value, ok := headerMap[name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
buf.Write(canonicalizeHeaderRelaxed(name, value))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func canonicalizeHeaderRelaxed(name, value string) []byte {
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
value = collapseWSP(strings.TrimSpace(value))
|
||||
return []byte(name + ":" + value + "\r\n")
|
||||
}
|
||||
|
||||
var wspRunRE = regexp.MustCompile(`[ \t]+`)
|
||||
|
||||
func collapseWSP(s string) string {
|
||||
return wspRunRE.ReplaceAllString(s, " ")
|
||||
}
|
||||
|
||||
// canonicalizeBodyRelaxed implements RFC 6376 §3.4.4: reduce WSP sequences
|
||||
// within a line to a single space, remove trailing WSP from each line,
|
||||
// remove trailing empty lines (but keep exactly one CRLF if the body is
|
||||
// non-empty after trimming).
|
||||
func canonicalizeBodyRelaxed(body []byte) []byte {
|
||||
if len(body) == 0 {
|
||||
return []byte("")
|
||||
}
|
||||
|
||||
lines := bytes.Split(body, []byte("\r\n"))
|
||||
for i, line := range lines {
|
||||
line = wspRunRE.ReplaceAll(line, []byte(" "))
|
||||
lines[i] = bytes.TrimRight(line, " \t")
|
||||
}
|
||||
|
||||
// Remove trailing empty lines.
|
||||
end := len(lines)
|
||||
for end > 0 && len(lines[end-1]) == 0 {
|
||||
end--
|
||||
}
|
||||
lines = lines[:end]
|
||||
|
||||
if len(lines) == 0 {
|
||||
return []byte("")
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
for _, line := range lines {
|
||||
buf.Write(line)
|
||||
buf.WriteString("\r\n")
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package dkim
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Verify checks a signed message's DKIM-Signature header against the given
|
||||
// public key (as would be fetched from DNS in Phase 4's inbound pipeline).
|
||||
// This lean version only handles rsa-sha256/relaxed-relaxed — the exact
|
||||
// profile Sign() produces — since its purpose here is to prove the signer is
|
||||
// correct. Phase 4 will build a fuller verifier (multiple algorithms,
|
||||
// simple/simple and mixed canonicalization) for arbitrary inbound mail.
|
||||
func Verify(publicKeyDER []byte, raw []byte) error {
|
||||
headers, body := splitMessage(raw)
|
||||
headerMap := parseHeaders(headers)
|
||||
|
||||
dkimHeaderValue, ok := headerMap["dkim-signature"]
|
||||
if !ok {
|
||||
return fmt.Errorf("no DKIM-Signature header present")
|
||||
}
|
||||
|
||||
tags := parseDKIMTags(dkimHeaderValue)
|
||||
if tags["a"] != "rsa-sha256" {
|
||||
return fmt.Errorf("unsupported algorithm: %s", tags["a"])
|
||||
}
|
||||
if tags["c"] != "relaxed/relaxed" {
|
||||
return fmt.Errorf("unsupported canonicalization: %s", tags["c"])
|
||||
}
|
||||
|
||||
// Verify body hash.
|
||||
bodyCanon := canonicalizeBodyRelaxed(body)
|
||||
bodyHash := sha256.Sum256(bodyCanon)
|
||||
expectedBH := base64.StdEncoding.EncodeToString(bodyHash[:])
|
||||
if tags["bh"] != expectedBH {
|
||||
return fmt.Errorf("body hash mismatch: signature claims %s, computed %s", tags["bh"], expectedBH)
|
||||
}
|
||||
|
||||
signedHdrNames := strings.Split(tags["h"], ":")
|
||||
|
||||
// Rebuild the exact signing input: canonicalized signed headers, then the
|
||||
// DKIM-Signature header itself with b= emptied, no trailing CRLF.
|
||||
signInput := canonicalizeHeadersRelaxed(headerMap, signedHdrNames)
|
||||
|
||||
dkimHeaderNoB := replaceDKIMTag(dkimHeaderValue, "b", "")
|
||||
signInput = append(signInput, canonicalizeHeaderRelaxed("dkim-signature", dkimHeaderNoB)...)
|
||||
signInput = trimTrailingCRLF(signInput)
|
||||
|
||||
sigBytes, err := base64.StdEncoding.DecodeString(tags["b"])
|
||||
if err != nil {
|
||||
return fmt.Errorf("decoding signature: %w", err)
|
||||
}
|
||||
|
||||
pubAny, err := x509.ParsePKIXPublicKey(publicKeyDER)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing public key: %w", err)
|
||||
}
|
||||
pubKey, ok := pubAny.(*rsa.PublicKey)
|
||||
if !ok {
|
||||
return fmt.Errorf("public key is not RSA")
|
||||
}
|
||||
|
||||
hashed := sha256.Sum256(signInput)
|
||||
if err := rsa.VerifyPKCS1v15(pubKey, crypto.SHA256, hashed[:], sigBytes); err != nil {
|
||||
return fmt.Errorf("signature verification failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseDKIMTags(header string) map[string]string {
|
||||
tags := map[string]string{}
|
||||
for _, part := range strings.Split(header, ";") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
name, value, found := strings.Cut(part, "=")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
tags[strings.TrimSpace(name)] = strings.TrimSpace(value)
|
||||
}
|
||||
return tags
|
||||
}
|
||||
|
||||
func replaceDKIMTag(header, tag, newValue string) string {
|
||||
parts := strings.Split(header, ";")
|
||||
for i, part := range parts {
|
||||
trimmed := strings.TrimSpace(part)
|
||||
if strings.HasPrefix(trimmed, tag+"=") {
|
||||
parts[i] = " " + tag + "=" + newValue
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, ";")
|
||||
}
|
||||
|
||||
func trimTrailingCRLF(b []byte) []byte {
|
||||
for len(b) >= 2 && b[len(b)-2] == '\r' && b[len(b)-1] == '\n' {
|
||||
return b[:len(b)-2]
|
||||
}
|
||||
return b
|
||||
}
|
||||
Reference in New Issue
Block a user