Documentation
¶
Overview ¶
Package spf evaluates Sender Policy Framework policies as defined by RFC 7208.
CheckHostWithOptions accepts cancellation, a ContextResolver, and independent SMTP HELO/receiver identities. CheckHost uses the system resolver; CheckHostWithResolver preserves the legacy Resolver interface. Each call owns its evaluation state, including recursion, DNS budgets, and macro values.
Inspect Result as well as error: None can accompany invalid input or a missing policy, and Fail normally has no error. Explanation text is untrusted policy data. Missing or invalid explanation text produces an empty string without changing Fail. Use errors.Is/errors.As to inspect wrapped DNS and context errors.
The evaluator does not serialize Received-SPF or Authentication-Results headers, perform SMTP transactions, or decide whether to reject a message. The system resolver cannot query every legal utility label; select the configured server resolver for those names. Legacy resolvers cannot provide complete DNS accounting or PTR validation. See CONFORMANCE.md in the repository for the tested scope, evidence, and compatibility details.
Index ¶
- Variables
- func NormalizeFQDN(name string) string
- type ContextResolver
- type DNSResolver
- func (r *DNSResolver) Exists(name string) (bool, error)
- func (r *DNSResolver) LookupAddrContext(ctx context.Context, addr string) ([]string, error)
- func (r *DNSResolver) LookupIPContext(ctx context.Context, network, name string) ([]net.IP, error)
- func (r *DNSResolver) LookupMXContext(ctx context.Context, name string) ([]*net.MX, error)
- func (r *DNSResolver) LookupTXT(name string) ([]string, error)
- func (r *DNSResolver) LookupTXTContext(ctx context.Context, name string) ([]string, error)
- func (r *DNSResolver) LookupTXTStrict(name string) ([]string, error)
- func (r *DNSResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
- func (r *DNSResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
- type IPMatcherFunc
- type LimitedResolver
- func (r *LimitedResolver) Exists(name string) (bool, error)
- func (r *LimitedResolver) LookupTXT(name string) ([]string, error)
- func (r *LimitedResolver) LookupTXTStrict(name string) ([]string, error)
- func (r *LimitedResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
- func (r *LimitedResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
- type MiekgDNSResolverdeprecated
- type Options
- type Resolver
- type Result
- type ServerResolver
- func (r *ServerResolver) Exists(name string) (bool, error)
- func (r *ServerResolver) LookupAddrContext(ctx context.Context, addr string) ([]string, error)
- func (r *ServerResolver) LookupIPContext(ctx context.Context, network, name string) ([]net.IP, error)
- func (r *ServerResolver) LookupMXContext(ctx context.Context, name string) ([]*net.MX, error)
- func (r *ServerResolver) LookupTXT(name string) ([]string, error)
- func (r *ServerResolver) LookupTXTContext(ctx context.Context, name string) ([]string, error)
- func (r *ServerResolver) LookupTXTStrict(name string) ([]string, error)
- func (r *ServerResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
- func (r *ServerResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
- type SyntaxError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrDNSTemperror = errors.New("temporary DNS error") ErrDNSPermerror = errors.New("permanent DNS error") ErrInvalidIP = errors.New("invalid IP address") ErrInvalidDomain = errors.New("invalid domain name") ErrDNSLimitExceeded = errors.New("limit exceeded") ErrSPFNotFound = errors.New("SPF record not found") )
Errors could be used for root couse analysis
var ErrUnsupportedResolver = errors.New("resolver lacks required DNS capability")
ErrUnsupportedResolver indicates that a legacy resolver lacks a required capability. A custom resolver is never supplemented with public DNS.
Functions ¶
func NormalizeFQDN ¶
NormalizeFQDN appends a root domain (a dot) to the FQDN.
Types ¶
type ContextResolver ¶
type ContextResolver interface {
LookupTXTContext(ctx context.Context, name string) ([]string, error)
LookupIPContext(ctx context.Context, network, name string) ([]net.IP, error)
LookupMXContext(ctx context.Context, name string) ([]*net.MX, error)
LookupAddrContext(ctx context.Context, addr string) ([]string, error)
}
ContextResolver supplies DNS records before the evaluator performs address matching or MX/PTR fan-out. Implementations must honor ctx, return only the requested family (network is "ip4" or "ip6"), and join strings within each TXT RR, never across RRs. Names use literal dot-separated ASCII labels, including punctuation/spaces, with a final root dot and no DNS presentation escapes. Empty results or errors wrapping a net.DNSError with IsNotFound set denote a void logical lookup. Intermediate CNAME responses and transport retries are not exposed by this interface. Implementations must be safe for concurrent evaluations.
func NewMiekgDNSResolverContext
deprecated
func NewMiekgDNSResolverContext(addr string) (ContextResolver, error)
NewMiekgDNSResolverContext returns the context-capable view of the resolver.
Deprecated: Use NewServerResolver.
type DNSResolver ¶
type DNSResolver struct{}
DNSResolver implements Resolver and ContextResolver using Go's resolver with the system DNS configuration and net.DefaultResolver.Dial, when configured. It uses the Go DNS path for cancelable connections, which can differ from platform-native resolution (for example, native split-DNS routing). Recursive servers supply complete alias answers; Go handles TCP fallback. Intermediate wire responses and retries are not observable; budgets count logical lookups.
func (*DNSResolver) LookupAddrContext ¶
LookupAddrContext returns reverse DNS candidates without forward validation.
func (*DNSResolver) LookupIPContext ¶
LookupIPContext looks up only network ("ip4" or "ip6").
func (*DNSResolver) LookupMXContext ¶
LookupMXContext returns exchanges without resolving their addresses.
func (*DNSResolver) LookupTXTContext ¶
LookupTXTContext returns one concatenated string per TXT resource record.
func (*DNSResolver) LookupTXTStrict ¶
func (r *DNSResolver) LookupTXTStrict(name string) ([]string, error)
func (*DNSResolver) MatchIP ¶
func (r *DNSResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
func (*DNSResolver) MatchMX ¶
func (r *DNSResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
type IPMatcherFunc ¶
IPMatcherFunc returns true if ip matches to implemented rules. Built-in resolvers call the matcher sequentially and finish all matcher calls before returning from the lookup. If IPMatcherFunc returns any non nil error, the Resolver must stop any further processing and use the error as resulting error.
type LimitedResolver ¶
type LimitedResolver struct {
// contains filtered or unexported fields
}
LimitedResolver wraps a Resolver and limits number of lookups possible to do with it. All overlimited calls return ErrDNSLimitExceeded. This legacy wrapper counts method calls and MX matcher callbacks, not SPF terms or DNS dispatches. Use CheckHostWithOptions for evaluation-wide SPF accounting.
func (*LimitedResolver) Exists ¶
func (r *LimitedResolver) Exists(name string) (bool, error)
Exists is used for a DNS A RR lookup (even when the connection type is IPv6). If any A record is returned, this mechanism matches. Returns false and ErrDNSLimitExceeded if total number of lookups made by underlying resolver exceed the limit.
func (*LimitedResolver) LookupTXT ¶
func (r *LimitedResolver) LookupTXT(name string) ([]string, error)
LookupTXT returns the DNS TXT records for the given domain name. Returns nil and ErrDNSLimitExceeded if total number of lookups made by underlying resolver exceed the limit.
func (*LimitedResolver) LookupTXTStrict ¶
func (r *LimitedResolver) LookupTXTStrict(name string) ([]string, error)
LookupTXTStrict returns the DNS TXT records for the given domain name. Returns nil and ErrDNSLimitExceeded if total number of lookups made by underlying resolver exceed the limit. It will also return ErrDNSPermerror upon DNS call return error NXDOMAIN (RCODE 3)
func (*LimitedResolver) MatchIP ¶
func (r *LimitedResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
MatchIP provides an address lookup, which should be done on the name using the type of lookup (A or AAAA). Then IPMatcherFunc used to compare checked IP to the returned address(es). If any address matches, the mechanism matches Returns false and ErrDNSLimitExceeded if total number of lookups made by underlying resolver exceed the limit.
func (*LimitedResolver) MatchMX ¶
func (r *LimitedResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
MatchMX is similar to MatchIP but first performs an MX lookup on the name. Then it performs an address lookup on each MX name returned. Then IPMatcherFunc used to compare checked IP to the returned address(es). If any address matches, the mechanism matches.
mxQueriesLimit bounds matcher callbacks, not underlying address lookups. The Resolver interface cannot enforce a pre-dispatch MX fan-out limit.
Returns false and ErrDNSLimitExceeded if total number of lookups made by underlying resolver exceed the limit.
type MiekgDNSResolver
deprecated
type MiekgDNSResolver = ServerResolver
MiekgDNSResolver is the former name of ServerResolver.
Deprecated: Use ServerResolver.
type Options ¶
type Options struct {
Resolver ContextResolver
HELO string
Receiver string
Time time.Time
}
Options configures one evaluation. A nil Resolver selects DNSResolver. HELO, Receiver and Time supply macro values unchanged through recursion. Missing identities use "unknown"; zero Time captures the time at entry.
type Resolver ¶
type Resolver interface {
// LookupTXT returns the DNS TXT records for the given domain name.
LookupTXT(string) ([]string, error)
// LookupTXTStrict returns DNS TXT records for the given name, however it
// will return ErrDNSPermerror upon returned NXDOMAIN (RCODE 3)
LookupTXTStrict(string) ([]string, error)
// Exists is used for a DNS A RR lookup (even when the
// connection type is IPv6). If any A record is returned, this
// mechanism matches.
Exists(string) (bool, error)
// MatchIP provides an address lookup, which should be done on the name
// using the type of lookup (A or AAAA).
// Then IPMatcherFunc used to compare checked IP to the returned address(es).
// If any address matches, the mechanism matches
MatchIP(string, IPMatcherFunc) (bool, error)
// MatchMX is similar to MatchIP but first performs an MX lookup on the
// name. Then it performs an address lookup on each MX name returned.
// Then IPMatcherFunc used to compare checked IP to the returned address(es).
// If any address matches, the mechanism matches
MatchMX(string, IPMatcherFunc) (bool, error)
}
Resolver provides abstraction for DNS layer
func NewLimitedResolver ¶
NewLimitedResolver returns a resolver which will pass up to lookupLimit calls to r. In addition to that limit, the evaluation of each "MX" record will be limited to mxQueryLimit. All calls over the limit will return ErrDNSLimitExceeded.
func NewMiekgDNSResolver
deprecated
type Result ¶
type Result int
Result represents result of SPF evaluation as it defined by RFC7208 https://tools.ietf.org/html/rfc7208#section-2.6
const ( // None means either (a) no syntactically valid DNS // domain name was extracted from the SMTP session that could be used // as the one to be authorized, or (b) no SPF records were retrieved // from the DNS. None Result // Neutral result means the ADMD has explicitly stated that it // is not asserting whether the IP address is authorized. Neutral // Pass result is an explicit statement that the client // is authorized to inject mail with the given identity. Pass // Fail result is an explicit statement that the client // is not authorized to use the domain in the given identity. Fail // Softfail result is a weak statement by the publishing ADMD // that the host is probably not authorized. It has not published // a stronger, more definitive policy that results in a "fail". Softfail // Temperror result means the SPF verifier encountered a transient // (generally DNS) error while performing the check. // A later retry may succeed without further DNS operator action. Temperror // Permerror result means the domain's published records could // not be correctly interpreted. // This signals an error condition that definitely requires // DNS operator intervention to be resolved. Permerror )
func CheckHost ¶
CheckHost is a main entrypoint function evaluating e-mail with regard to SPF and it utilizes DNSResolver as a resolver. As per RFC 7208 it will accept 3 parameters: <ip> - IP{4,6} address of the connected client <domain> - domain portion of the MAIL FROM or HELO identity <sender> - MAIL FROM or HELO identity All the parameters should be parsed and dereferenced from real email fields. This means domain should already be extracted from MAIL FROM field so this function can focus on the core part.
CheckHost returns result of verification, explanations as result of "exp=", and error as the reason for the encountered problem.
func CheckHostWithOptions ¶
func CheckHostWithOptions(ctx context.Context, ip net.IP, domain, sender string, options Options) (Result, string, error)
CheckHostWithOptions evaluates SPF with a shared 20-second deadline (or an earlier caller deadline), ten DNS-causing terms, two void logical lookups, and at most ten MX address lookups per mechanism. Initial and explanation TXT lookups do not consume terms; explanation lookup errors leave Fail intact.
Example ¶
package main
import (
"context"
"fmt"
"net"
"github.com/zaccone/spf"
)
// A deterministic resolver for this example; production applications can use
// spf.NewServerResolver("192.0.2.53:53") or their own ContextResolver.
type exampleResolver struct{}
func (exampleResolver) LookupTXTContext(_ context.Context, name string) ([]string, error) {
if name == "example.com." {
return []string{"v=spf1 ip4:192.0.2.0/24 -all"}, nil
}
return nil, nil
}
func (exampleResolver) LookupIPContext(context.Context, string, string) ([]net.IP, error) {
return nil, nil
}
func (exampleResolver) LookupMXContext(context.Context, string) ([]*net.MX, error) { return nil, nil }
func (exampleResolver) LookupAddrContext(context.Context, string) ([]string, error) { return nil, nil }
func main() {
result, explanation, err := spf.CheckHostWithOptions(
context.Background(), net.ParseIP("192.0.2.1"), "example.com", "sender@example.com",
spf.Options{Resolver: exampleResolver{}, HELO: "mail.example.com", Receiver: "mx.receiver.example"},
)
fmt.Println(result, explanation == "", err)
}
Output: pass true <nil>
Example (Cancellation) ¶
package main
import (
"context"
"errors"
"fmt"
"net"
"github.com/zaccone/spf"
)
// A deterministic resolver for this example; production applications can use
// spf.NewServerResolver("192.0.2.53:53") or their own ContextResolver.
type exampleResolver struct{}
func (exampleResolver) LookupTXTContext(_ context.Context, name string) ([]string, error) {
if name == "example.com." {
return []string{"v=spf1 ip4:192.0.2.0/24 -all"}, nil
}
return nil, nil
}
func (exampleResolver) LookupIPContext(context.Context, string, string) ([]net.IP, error) {
return nil, nil
}
func (exampleResolver) LookupMXContext(context.Context, string) ([]*net.MX, error) { return nil, nil }
func (exampleResolver) LookupAddrContext(context.Context, string) ([]string, error) { return nil, nil }
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
result, _, err := spf.CheckHostWithOptions(ctx, net.ParseIP("192.0.2.1"), "example.com", "sender@example.com", spf.Options{Resolver: exampleResolver{}})
fmt.Println(result, errors.Is(err, context.Canceled))
}
Output: temperror true
func CheckHostWithResolver ¶
func CheckHostWithResolver(ip net.IP, domain, sender string, resolver Resolver) (Result, string, error)
CheckHostWithResolver allows using custom Resolver. The evaluator enforces shared term limits. ContextResolver implementations also support family selection, void accounting, cancellation, and MX fan-out limits. Legacy-only resolvers cannot provide those guarantees; they are never supplemented with another DNS source.
The function returns result of verification, explanations as result of "exp=", and error as the reason for the encountered problem. Invalid IP arguments return None and ErrInvalidIP; invalid or single-label domains return None and ErrInvalidDomain, before DNS lookup. A bare sender is treated as a HELO domain with local-part "postmaster"; an empty sender uses the supplied domain. Unavailable or invalid explanation text leaves Fail unchanged with no error.
func (Result) String ¶
String returns string form of the result as defined by RFC7208 https://tools.ietf.org/html/rfc7208#section-2.6
type ServerResolver ¶
type ServerResolver struct {
// contains filtered or unexported fields
}
ServerResolver implements Resolver and ContextResolver using a configured DNS server. It is safe for concurrent lookups and must be created with NewServerResolver. Use DNSResolver to query through the system resolver. Each query owns its connection. Aliases are limited to ten hops, including aliases present in a single response. Truncated UDP is retried once over TCP.
func NewServerResolver ¶
func NewServerResolver(addr string) (*ServerResolver, error)
NewServerResolver returns a resolver using the specified DNS server address, in host:port form. It supports both Resolver and ContextResolver. Construction validates the address format without connecting to the server.
func (*ServerResolver) LookupAddrContext ¶
LookupAddrContext performs the IPv4 or IPv6 reverse query, without forward validation. Only the first ten PTR candidates are returned (RFC 7208, 4.6.4).
func (*ServerResolver) LookupIPContext ¶
func (r *ServerResolver) LookupIPContext(ctx context.Context, network, name string) ([]net.IP, error)
LookupIPContext queries only the selected address family.
func (*ServerResolver) LookupMXContext ¶
LookupMXContext returns exchanges before address resolution.
func (*ServerResolver) LookupTXT ¶
func (r *ServerResolver) LookupTXT(name string) ([]string, error)
func (*ServerResolver) LookupTXTContext ¶
LookupTXTContext returns one string per TXT RR, joining its component strings.
func (*ServerResolver) LookupTXTStrict ¶
func (r *ServerResolver) LookupTXTStrict(name string) ([]string, error)
func (*ServerResolver) MatchIP ¶
func (r *ServerResolver) MatchIP(name string, matcher IPMatcherFunc) (bool, error)
func (*ServerResolver) MatchMX ¶
func (r *ServerResolver) MatchMX(name string, matcher IPMatcherFunc) (bool, error)
type SyntaxError ¶
type SyntaxError struct {
// contains filtered or unexported fields
}
SyntaxError represents parsing error, it holds reference to faulty token as well as error describing fault
func (SyntaxError) Error ¶
func (e SyntaxError) Error() string
func (SyntaxError) Unwrap ¶
func (e SyntaxError) Unwrap() error
Unwrap exposes the underlying cause to errors.Is and errors.As.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
benchmarks
|
|
|
nsd
command
Mixed-result, bounded-memory load driver for real DNS and Postfix policy.
|
Mixed-result, bounded-memory load driver for real DNS and Postfix policy. |
|
unbound
command
Cached loopback benchmark.
|
Cached loopback benchmark. |
|
vm
command
Synthetic resolver benchmark; intentionally excludes DNS transport and MTA overhead.
|
Synthetic resolver benchmark; intentionally excludes DNS transport and MTA overhead. |
|
cmd
|
|
|
spfd
command
Command spfd evaluates SPF directly or serves Postfix access-policy requests.
|
Command spfd evaluates SPF directly or serves Postfix access-policy requests. |