DNS Engineering Internals: A, AAAA, MX, SPF, DKIM, DMARC & Native .NET 11 APIs
From DNS Wire Format and Recursive Resolution to Email Authentication, Cryptographic Signatures, Domain Alignment, Negative Caching and Production-Grade C# Monitoring.
1. Introduction — DNS Is More Than Name Resolution
DNS is frequently described as the system that translates domain names into IP addresses.
That description is correct but radically incomplete.
The Domain Name System is a hierarchical, distributed database with a specialized query protocol, authoritative delegation, recursive resolution, caching semantics, typed resource records and an extensible namespace.
Modern email infrastructure depends on DNS for several independent functions:
- discovering hosts through A and AAAA records;
- locating inbound mail exchangers through MX records;
- publishing sender authorization through SPF;
- distributing public cryptographic keys through DKIM;
- publishing domain-alignment policies through DMARC.
Each function answers a different question.
An A record does not prove that a web server is available.
An MX record does not prove that an SMTP server accepts messages.
An SPF record does not prove that a message has passed SPF authentication.
A DKIM public key does not prove that a particular email was correctly signed.
And the presence of a DMARC policy does not establish that the domain's actual email traffic passes DMARC.
.NET 11 introduces native typed DNS record-resolution APIs that substantially simplify the first two layers.
This article studies the protocols from their binary representation to the implementation of a monitoring system in C#.
2. DNS Architecture — Hierarchy, Delegation and Resolution
The DNS namespace forms a hierarchy of labels separated by dots.
.
|
com
|
example.com
|
+-----------+-----------+
| | |
www mail _dmarc
|
www.example.com
The root is represented by the empty label. Fully qualified domain names may be written with a final dot, such as example.com.
DNS distinguishes authoritative name servers from recursive resolvers.
An authoritative name server publishes records for zones it is responsible for.
A recursive resolver obtains the answers requested by clients, following delegations and using its cache.
2.1 Recursive versus iterative resolution
When a client asks for the address of mail.example.com, its configured resolver may:
- check its cache;
- query a root server if necessary;
- follow the delegation to the relevant top-level domain servers;
- follow the delegation to the authoritative servers for
example.com; - retrieve the requested A or AAAA records;
- return the response and cache eligible results.
Application
|
v
Recursive Resolver
|
+-- Cache hit ------> Immediate answer
|
+-- Cache miss
|
v
Root Servers
|
v
TLD Servers
|
v
Authoritative Servers
|
v
Answer
A recursive resolver performs work on behalf of the application. An authoritative server normally responds according to the zone data for which it has authority.
This distinction matters when diagnosing DNS problems: a stale recursive cache is different from an incorrect authoritative record.
3. Inside a DNS Packet
Traditional DNS messages begin with a fixed 12-byte header followed by variable-length sections.
| Field | Size | Meaning |
|---|---|---|
| ID | 16 bits | Transaction identifier |
| Flags | 16 bits | QR, Opcode, AA, TC, RD, RA, AD, CD and RCODE fields |
| QDCOUNT | 16 bits | Questions |
| ANCOUNT | 16 bits | Answer resource records |
| NSCOUNT | 16 bits | Authority-section resource records |
| ARCOUNT | 16 bits | Additional-section resource records |
The following sections contain:
+----------------------+
| DNS Header |
+----------------------+
| Question Section |
+----------------------+
| Answer Section |
+----------------------+
| Authority Section |
+----------------------+
| Additional Section |
+----------------------+
3.1 Resource Record encoding
A DNS resource record contains:
Its binary structure is conceptually:
NAME Variable-length domain name
TYPE 16 bits
CLASS 16 bits
TTL 32 bits
RDLENGTH 16 bits
RDATA RDLENGTH octets
All multibyte numeric fields are encoded in network byte order.
DNS names use length-prefixed labels. For example, mail.example.com consists of labels with lengths 4, 7 and 3, followed by a zero-length root label.
DNS also supports name compression through pointers into earlier message bytes. A parser must handle compression safely, including malformed pointer loops and invalid offsets.
3.2 Transport
DNS traditionally uses UDP port 53. TCP port 53 is also part of the protocol and is important for larger responses, retries and zone transfers where applicable.
EDNS(0) extends DNS capabilities, including communication about supported UDP payload sizes.
Modern deployments may also use DNS-over-TLS and DNS-over-HTTPS.
Transport encryption protects the DNS exchange with a resolver, but it does not by itself establish the cryptographic authenticity of the underlying DNS data.
4. A Records — IPv4 Address Resolution
An A record maps a DNS owner name to a 32-bit IPv4 address.
example.com. 300 IN A 192.0.2.10
www.example.com. 300 IN A 192.0.2.20
The addresses in these examples belong to documentation ranges.
The A record's RDATA consists of exactly four octets.
A domain can publish multiple A records.
However, multiple A records do not guarantee load balancing, health-aware routing or session affinity.
DNS clients and resolvers can process and cache these records differently. Application connection behavior must be evaluated separately.
4.1 DNS record versus service availability
Suppose:
api.example.com. 60 IN A 192.0.2.50
The record proves only that the DNS system returned an address.
It does not prove:
- that TCP port 443 is reachable;
- that a TLS handshake succeeds;
- that the certificate matches the domain;
- that the application returns a successful HTTP response;
- that the application is healthy.
DNS monitoring and HTTP monitoring must therefore be different checks.
5. AAAA Records — IPv6 Address Resolution
An AAAA record maps a name to a 128-bit IPv6 address.
example.com. 300 IN AAAA 2001:db8::10
The RDATA contains 16 octets.
Unlike IPv4, IPv6 uses a much larger address space and different addressing conventions.
The presence of an AAAA record can affect client connectivity because a client may attempt IPv6 before or in parallel with IPv4.
5.1 Dual-stack behavior
A dual-stack service may publish:
app.example.com. 300 IN A 192.0.2.10
app.example.com. 300 IN AAAA 2001:db8::10
If the IPv4 endpoint is working but the IPv6 endpoint is unreachable, users may encounter connection delays or failures depending on their operating system, network and connection strategy.
Modern clients often implement Happy Eyeballs to reduce delays caused by a failing address family.
Nevertheless, an incorrect AAAA record remains a configuration defect.
6. MX Records — SMTP Mail Exchanger Discovery
MX records identify the hosts responsible for receiving email addressed to a domain.
example.com. 300 IN MX 10 mx1.example.net.
example.com. 300 IN MX 20 mx2.example.net.
The MX RDATA contains a 16-bit preference value and an exchange domain name.
Lower preference numbers have higher priority.
When multiple MX records have the same preference, SMTP clients distribute selection according to the relevant SMTP behavior rather than interpreting the values as weights.
6.1 Resolution procedure
Recipient: user@example.com
|
v
Resolve MX example.com
|
v
Select mail exchanger
|
v
Resolve A / AAAA
|
v
Connect to TCP 25
|
v
SMTP dialogue
The exchange hostname should resolve directly to address records. SMTP does not define CNAME indirection as an acceptable target of an MX record.
6.2 No MX record does not always mean no email
RFC 5321 defines an implicit-MX fallback.
If no MX records exist, SMTP delivery can attempt the domain's own A or AAAA records.
For example:
example.com. 300 IN A 192.0.2.40
# No MX record
Under SMTP semantics, the domain may still be considered a candidate for email delivery.
Therefore, a monitoring system must not automatically classify every domain without MX records as unable to receive email.
6.3 Null MX
RFC 7505 defines a special MX record indicating that a domain intentionally does not receive mail:
example.com. 300 IN MX 0 .
This is called a Null MX.
It differs fundamentally from an absent MX record.
| Condition | Meaning |
|---|---|
| MX with reachable exchanger | Potentially capable of receiving SMTP mail |
| No MX, A/AAAA present | Implicit-MX fallback may apply |
| Single MX 0 pointing to "." | Explicitly declares no mail reception |
| NXDOMAIN | Requested domain name does not exist |
| DNS timeout | Temporary inability to determine DNS state |
7. DNS TTL and Cache Semantics
The Time to Live is the maximum time for which a DNS record may be retained by a cache.
If a record has a TTL of 300 seconds, a conforming cache can reuse the answer for up to five minutes from the corresponding cache lifetime, subject to resolver policies.
But TTL does not mean that a DNS change becomes instantly visible everywhere after exactly 300 seconds.
Different resolvers may have queried the record at different times.
Resolvers may also impose TTL limits or implement additional caching behavior.
7.1 Positive caching
For a positive cached response, a simple expiration model is:
When a record is changed at the authoritative server, resolvers holding earlier cached data may continue returning that data until their cached response expires.
7.2 Negative caching
Negative DNS responses can also be cached.
Two important cases are:
- NXDOMAIN: the requested domain name does not exist;
- NODATA: the name exists, but no record of the requested type is available.
RFC 2308 defines negative caching semantics using SOA information in the authority section.
For the authoritative negative response, the effective negative TTL is derived from the minimum of the SOA RR TTL and the SOA MINIMUM field.
Further resolver behavior can affect the actual remaining cache lifetime.
This matters when enabling DKIM or DMARC records: a name that previously returned NXDOMAIN can remain negatively cached after the TXT record is created.
8. SPF — Sender Policy Framework
SPF is defined by RFC 7208.
Its purpose is to determine whether the IP address of an SMTP client is authorized to send mail using a particular SMTP identity.
SPF does not authenticate the human-visible From header directly.
For ordinary email, its primary evaluated identity is the domain in the SMTP envelope MAIL FROM address.
Under the required null reverse-path behavior, the HELO/EHLO identity is relevant.
8.1 SPF record structure
example.com. 300 IN TXT
"v=spf1 ip4:192.0.2.0/24 include:_spf.provider.net -all"
The record begins with the version marker v=spf1 and contains mechanisms and modifiers.
| Mechanism | Meaning |
|---|---|
ip4 | Matches an IPv4 address or prefix |
ip6 | Matches an IPv6 address or prefix |
a | Evaluates A/AAAA records of a domain |
mx | Evaluates the addresses of mail exchangers |
include | Uses another SPF policy as an authorization mechanism |
exists | Matches based on the existence of an address result |
all | Always matches |
redirect | Redirects SPF evaluation to another domain when appropriate |
8.2 SPF qualifiers
+ Pass
- Fail
~ SoftFail
? Neutral
If no qualifier is specified, + is implied.
Examples:
v=spf1 ip4:192.0.2.10 -all
v=spf1 include:_spf.provider.net ~all
v=spf1 -all
The last policy declares that no IP address is authorized to send using the evaluated domain identity.
8.3 SPF is an ordered evaluation algorithm
Mechanisms are evaluated in sequence.
The first matching mechanism determines the corresponding result, subject to error and redirect semantics.
For example:
v=spf1 ip4:192.0.2.0/24 include:_spf.example.net -all
For IP 192.0.2.25, the first mechanism matches.
For IP 198.51.100.40, the evaluator must continue with the include mechanism and potentially evaluate the referenced policy.
A simple string search for the sending IP is therefore not a valid general SPF evaluator.
9. SPF DNS Lookup Budget — A Frequent Configuration Failure
SPF imposes a limit on DNS-query-producing terms during evaluation.
The mechanisms and modifiers counted toward the limit include:
include
a
mx
ptr
exists
redirect
The maximum is ten evaluated terms that require DNS lookups.
Exceeding the limit produces a permanent SPF error.
The limit applies to the actual evaluation path, including nested policies; it is not merely the number of literal include: strings in the top-level record.
Other restrictions apply to MX and PTR expansion and to DNS responses without useful answers.
9.1 Why a static include counter is not sufficient
Consider:
v=spf1 include:a.example
include:b.example
include:c.example
-all
Each included domain may contain additional lookup-producing terms.
Furthermore, evaluation can stop early when a mechanism matches.
Consequently, a static count can be useful as an early warning, but it cannot replace evaluation of the actual SPF decision tree.
9.2 SPF result types
A correct implementation must distinguish:
Pass
Fail
SoftFail
Neutral
None
TempError
PermError
DNS timeouts and transient resolver errors must not be collapsed into permanent policy errors.
10. DKIM — DomainKeys Identified Mail
DKIM is fundamentally different from SPF.
SPF evaluates authorization of an SMTP client IP address.
DKIM uses public-key cryptography to verify that selected message headers and the body have not been modified outside the permitted canonicalization semantics.
The signing domain publishes a public key through DNS.
10.1 DKIM selector and key location
A public key is published at:
selector._domainkey.example.com
Example:
mail2026._domainkey.example.com. 300 IN TXT
"v=DKIM1; k=rsa; p=MIIBIjANBgkq..."
The selector allows a domain to publish multiple independent keys.
This is useful for key rotation and separation between mail providers.
There is no general DNS operation that enumerates every possible DKIM selector.
A monitoring system must receive the selectors from configuration, message headers or other authoritative inventory sources.
10.2 DKIM-Signature header
DKIM-Signature:
v=1;
a=rsa-sha256;
d=example.com;
s=mail2026;
c=relaxed/relaxed;
h=from:to:subject:date;
bh=BASE64_BODY_HASH;
b=BASE64_SIGNATURE
Important fields:
| Tag | Purpose |
|---|---|
d= | Signing domain |
s= | Selector |
a= | Signature algorithm |
c= | Canonicalization mode |
h= | Signed header fields |
bh= | Encoded body hash |
b= | Cryptographic signature |
t= | Optional signing time |
x= | Optional signature expiration |
11. DKIM Cryptography — Hashing, Canonicalization and Signature Verification
The signing process first canonicalizes the message body.
Then it calculates a digest:
The digest is encoded into the bh= field.
Selected headers, including the DKIM-Signature field with its signature value treated as empty, are canonicalized according to the specified rules.
The resulting data are used for signature generation.
Where sk is the private signing key.
On reception, the verifier retrieves the public key from DNS and verifies the signature.
11.1 Simple versus relaxed canonicalization
DKIM supports two principal canonicalization modes for both headers and body:
- simple: preserves almost all of the original representation;
- relaxed: tolerates certain whitespace and formatting changes.
For example:
c=relaxed/relaxed
The first mode applies to headers, the second to the body.
Canonicalization is necessary because mail systems may modify line folding or whitespace while transporting a message.
However, relaxed canonicalization does not permit arbitrary modification of message content.
11.2 Cryptographic algorithm requirements
RFC 8301 updates the original DKIM cryptographic requirements.
RSA-SHA1 must no longer be used for DKIM signing or verification.
RSA keys shorter than 1024 bits cannot be accepted as valid; 2048-bit RSA keys are recommended for signing.
RFC 8463 also defines Ed25519-SHA256 as an additional DKIM signing algorithm.
A monitoring system should therefore distinguish key publication from complete algorithm and signature compatibility.
12. Why a Published DKIM Record Is Not Proof of Authentication
Suppose the following DNS lookup succeeds:
mail2026._domainkey.example.com TXT
The result shows that key material is published.
It does not show:
- that an email contains a corresponding DKIM-Signature header;
- that the signing selector matches the published key;
- that the signature is cryptographically valid;
- that the body hash matches;
- that the signing domain aligns with the visible From domain.
These conditions can only be evaluated using an actual message and its signature.
13. DMARC — Domain-Based Message Authentication, Reporting and Conformance
DMARC combines the results of SPF and DKIM with the concept of identifier alignment.
It provides a policy framework for handling messages whose authentication results do not align with the visible author domain.
A DMARC record is published at:
_dmarc.example.com
Example:
v=DMARC1; p=reject; rua=mailto:dmarc@example.com;
adkim=r; aspf=r; pct=100
13.1 DMARC policy tags
| Tag | Meaning |
|---|---|
v | Protocol version |
p | Requested policy for the domain |
sp | Policy for subdomains |
rua | Aggregate report destinations |
ruf | Failure report destinations |
adkim | DKIM alignment mode |
aspf | SPF alignment mode |
pct | Policy sampling percentage |
The principal policies are:
p=none
p=quarantine
p=reject
A policy is a request to receiving systems. Actual processing also depends on receiver policy and implementation.
14. DMARC Alignment — The Most Frequently Misunderstood Concept
The visible message author domain comes from the RFC5322.From header.
SPF normally authenticates a domain associated with the SMTP envelope.
DKIM authenticates the domain identified by the signature's d= parameter.
DMARC requires a successful authentication result whose authenticated domain is aligned with the visible From domain.
14.1 Formal DMARC condition
A message does not need both SPF and DKIM to pass DMARC.
At least one successful and aligned authentication mechanism is sufficient under the applicable DMARC evaluation rules.
14.2 Relaxed alignment
In relaxed mode, two domains align when their Organizational Domains match under the applicable domain-discovery rules.
For example:
RFC5322.From:
example.com
DKIM d=:
mail.example.com
Relaxed DKIM alignment:
PASS
14.3 Strict alignment
In strict mode, the authenticated domain must match the From domain exactly.
RFC5322.From:
example.com
DKIM d=:
mail.example.com
Strict DKIM alignment:
FAIL
Determining the Organizational Domain requires more than taking the last two labels. Domains such as example.co.uk demonstrate why suffix-aware domain discovery matters.
15. DMARC Evaluation Examples
| SPF | SPF alignment | DKIM | DKIM alignment | DMARC |
|---|---|---|---|---|
| Pass | Yes | Fail | No | Pass |
| Fail | No | Pass | Yes | Pass |
| Pass | No | Pass | No | Fail |
| Fail | No | Fail | No | Fail |
| Pass | Yes | Pass | Yes | Pass |
These rows illustrate the alignment predicate for decisive pass/fail results. A complete implementation must also handle temporary errors, permanent errors, absent authentication results and receiver policy.
16. Forwarding, Mailing Lists and DKIM Survival
Forwarding frequently changes the network identity of the SMTP sender.
Consider:
Original Sender
|
v
Forwarding Server
|
v
Final Recipient
The final recipient observes the IP address of the forwarding server, not necessarily the original outbound mail server.
SPF may therefore fail.
DKIM can survive forwarding because it authenticates selected message content rather than the connecting SMTP IP.
However, changes introduced by a mailing list, such as modifying the subject or message body, may invalidate the signature.
ARC — Authenticated Received Chain — addresses related problems by allowing intermediaries to preserve authenticated information about previous handling.
ARC does not replace DMARC and does not guarantee delivery.
17. DMARC Reporting — From DNS Policy to Operational Evidence
DMARC can publish destinations for aggregate reporting.
rua=mailto:dmarc-reports@example.com
Aggregate reports can include information about:
- source IP addresses;
- message counts;
- SPF authentication results;
- DKIM authentication results;
- alignment outcomes;
- policy disposition.
A monitoring system can use these reports to identify legitimate senders that are not correctly configured.
This is much stronger evidence than merely checking whether a domain has published p=reject.
The decision to enforce quarantine or rejection should be based on observed legitimate mail flows, not simply on the desire to maximize a configuration score.
18. .NET 11 — Native DNS Resolution APIs
.NET 11 introduces native typed DNS queries in System.Net.Dns.
Important APIs include:
Dns.ResolveMxAsync(...)
Dns.ResolveTxtAsync(...)
Dns.ResolveNsAsync(...)
Dns.ResolvePtrAsync(...)
Dns.ResolveCNameAsync(...)
Dns.ResolveSrvAsync(...)
Dns.ResolveAddressesAsync(...)
The APIs return typed result objects, such as:
Task<DnsResult<MxRecord>>
Task<DnsResult<TxtRecord>>
A resolver result includes the record collection, DNS response information and negative-cache TTL metadata.
The new DnsResolver class also supports explicit resolver configuration.
These APIs are available on supported Windows, Linux and macOS environments.
19. Laboratory — Create a .NET 11 DNS Inspector
Install the .NET 11 SDK and create a console application:
dotnet new console -n DnsEngineeringLab -f net11.0
cd DnsEngineeringLab
No external DNS package is required for the native queries used below.
19.1 Query A and AAAA separately
using System.Net;
using System.Net.Sockets;
string domain = "example.com";
var ipv4 = await Dns.ResolveAddressesAsync(
domain,
AddressFamily.InterNetwork);
var ipv6 = await Dns.ResolveAddressesAsync(
domain,
AddressFamily.InterNetworkV6);
Console.WriteLine("IPv4 result:");
Console.WriteLine(
System.Text.Json.JsonSerializer.Serialize(ipv4));
Console.WriteLine("IPv6 result:");
Console.WriteLine(
System.Text.Json.JsonSerializer.Serialize(ipv6));
Using AddressFamily avoids conflating the two address families.
The typed resolver result can be inspected without relying on third-party DNS record models.
19.2 Query MX and TXT records
using System.Net;
using System.Text.Json;
var mx = await Dns.ResolveMxAsync("example.com");
var txt = await Dns.ResolveTxtAsync("example.com");
var dmarc = await Dns.ResolveTxtAsync(
"_dmarc.example.com");
Console.WriteLine(
JsonSerializer.Serialize(mx));
Console.WriteLine(
JsonSerializer.Serialize(txt));
Console.WriteLine(
JsonSerializer.Serialize(dmarc));
Serialization is used here as an exploratory inspection technique.
For a production application, map the typed records into explicit domain objects rather than persisting the entire framework result indiscriminately.
19.3 Query a DKIM selector
string domain = "example.com";
string selector = "mail2026";
string keyName =
$"{selector}._domainkey.{domain}";
var keyResponse = await Dns.ResolveTxtAsync(
keyName);
Console.WriteLine(
JsonSerializer.Serialize(keyResponse));
The selector must come from the sending infrastructure configuration or the DKIM-Signature header.
20. Configure a Custom DNS Resolver
The new DnsResolver instance API accepts DnsResolverOptions.
This makes it possible to query specified DNS servers rather than relying exclusively on the platform's configured resolver.
For example, the following code illustrates the construction of a resolver with custom server addresses:
using System.Net;
var options = new DnsResolverOptions();
// Configure options.Servers with the
// supported DNS-server endpoint representation
// for the installed .NET 11 runtime.
using var resolver = new DnsResolver(options);
var records = await resolver.ResolveMxAsync(
"example.com");
The explicit server collection is intentionally left as a configuration step because the endpoint representation should be checked against the installed .NET 11 API reference.
In a production monitoring system, compare responses from multiple independent resolvers, but do not assume that resolver disagreement always indicates corruption.
Propagation delays, split-horizon DNS, geographic routing, resolver policy and caching can produce legitimate differences.
21. TXT Records — An Important Binary Encoding Detail
A DNS TXT resource record is not simply an unrestricted text string.
Its RDATA consists of one or more length-prefixed character-strings, each limited to 255 octets.
Long SPF or DKIM records may therefore be split into multiple character-strings inside a single TXT resource record.
For example:
selector._domainkey.example.com TXT
"v=DKIM1; k=rsa; p=MIIBIjANBgkq..."
"...remaining-key-material..."
For DKIM, these pieces represent one logical key record and must be concatenated according to the DNS TXT interpretation before the policy is parsed.
But separate TXT resource records must not be concatenated with one another.
22. A Safe SPF Publication Parser in C#
The following laboratory parses an already reconstructed TXT string.
It checks publication-level conditions, not SMTP SPF authorization.
public sealed record SpfPublication(
string RawRecord,
IReadOnlyList<string> Terms,
int LookupTermUpperBound,
IReadOnlyList<string> Warnings);
public static class SpfPublicationParser
{
private static readonly string[] LookupTerms =
[
"include:",
"a",
"mx",
"ptr",
"exists:",
"redirect="
];
public static SpfPublication Parse(string record)
{
ArgumentException.ThrowIfNullOrWhiteSpace(record);
var terms = record.Split(
' ',
StringSplitOptions.RemoveEmptyEntries |
StringSplitOptions.TrimEntries);
var warnings = new List<string>();
if (terms.Length == 0 ||
terms[0] != "v=spf1")
{
warnings.Add("Missing SPF version marker.");
}
int lookupUpperBound = terms.Count(IsDnsTerm);
if (lookupUpperBound > 10)
{
warnings.Add(
"More than ten lookup-producing terms " +
"appear in this record.");
}
if (!terms.Any(t =>
t is "-all" or "~all" or "?all" or "all" or "+all"))
{
warnings.Add(
"No explicit all mechanism was found.");
}
return new SpfPublication(
record,
terms,
lookupUpperBound,
warnings);
}
private static bool IsDnsTerm(string term)
{
string value = term.TrimStart(
'+', '-', '~', '?');
return LookupTerms.Any(prefix =>
value.Equals(prefix, StringComparison.OrdinalIgnoreCase) ||
value.StartsWith(
prefix is "a" or "mx" or "ptr"
? prefix + ":"
: prefix,
StringComparison.OrdinalIgnoreCase));
}
}
This intentionally simplified parser demonstrates a publication-level diagnostic.
It does not evaluate nested includes, macro expansion, mechanisms, DNS response limits or complete SPF syntax.
It also does not replace a standards-compliant parser for all possible SPF terms.
In production, these checks should be implemented as explicit validation rules rather than treated as the definitive SPF evaluation result.
23. DMARC Policy Parsing in C#
DMARC uses a semicolon-separated tag-value syntax.
A useful first step is to parse the tags into an immutable representation.
public sealed record DmarcPolicy(
string Version,
string Policy,
string? SubdomainPolicy,
string Aspf,
string Adkim,
int Percentage,
string? AggregateReports);
public static class DmarcParser
{
public static DmarcPolicy Parse(string text)
{
var fields = new Dictionary<string, string>(
StringComparer.OrdinalIgnoreCase);
foreach (var segment in text.Split(';'))
{
var item = segment.Trim();
if (item.Length == 0)
continue;
int index = item.IndexOf('=');
if (index <= 0)
throw new FormatException("Invalid tag-value.");
string key = item[..index].Trim();
string value = item[(index + 1)..].Trim();
if (!fields.TryAdd(key, value))
throw new FormatException(
$"Duplicate DMARC tag: {key}");
}
string Get(string name, string fallback) =>
fields.TryGetValue(name, out var value)
? value
: fallback;
string version = Get("v", "");
string policy = Get("p", "");
if (version != "DMARC1")
throw new FormatException("Invalid DMARC version.");
if (policy is not ("none" or "quarantine" or "reject"))
throw new FormatException("Invalid DMARC policy.");
if (!int.TryParse(Get("pct", "100"),
out int percentage) ||
percentage is < 0 or > 100)
{
throw new FormatException("Invalid pct value.");
}
string aspf = Get("aspf", "r");
string adkim = Get("adkim", "r");
if (aspf is not ("r" or "s") ||
adkim is not ("r" or "s"))
{
throw new FormatException(
"Invalid alignment mode.");
}
return new DmarcPolicy(
version,
policy,
fields.GetValueOrDefault("sp"),
aspf,
adkim,
percentage,
fields.GetValueOrDefault("rua"));
}
}
Example usage:
var policy = DmarcParser.Parse(
"v=DMARC1; p=quarantine; " +
"rua=mailto:reports@example.com; " +
"adkim=r; aspf=s; pct=100");
Console.WriteLine(policy.Policy);
Console.WriteLine(policy.Aspf);
Console.WriteLine(policy.Adkim);
This is a bounded laboratory parser. It is not a full implementation of DMARC record discovery, complete ABNF validation, external reporting authorization or the Organizational Domain algorithm.
24. Domain Alignment in C#
Strict alignment can be implemented through exact normalized domain comparison.
public static bool StrictlyAligned(
string authenticatedDomain,
string fromDomain)
{
static string Normalize(string value) =>
value.TrimEnd('.')
.ToLowerInvariant();
return Normalize(authenticatedDomain) ==
Normalize(fromDomain);
}
Relaxed alignment is more complicated.
It requires correctly identifying Organizational Domains, considering public suffixes and the applicable domain-discovery rules.
Simply comparing the last two labels fails for domains such as:
example.co.uk
company.com.au
service.example.org
For production use, domain alignment should rely on a maintained implementation of the relevant public-suffix and DMARC discovery semantics.
25. Evaluating a DMARC Decision
Once authentication and alignment have been computed by dedicated components, the central DMARC pass predicate is straightforward.
public sealed record AuthenticationEvidence(
bool SpfPassed,
bool SpfAligned,
bool DkimPassed,
bool DkimAligned);
public static class DmarcDecision
{
public static bool Passes(
AuthenticationEvidence evidence)
{
bool spfPass =
evidence.SpfPassed &&
evidence.SpfAligned;
bool dkimPass =
evidence.DkimPassed &&
evidence.DkimAligned;
return spfPass || dkimPass;
}
}
Example:
var evidence = new AuthenticationEvidence(
SpfPassed: false,
SpfAligned: false,
DkimPassed: true,
DkimAligned: true);
bool dmarcPass = DmarcDecision.Passes(evidence);
Console.WriteLine(dmarcPass); // True
The correctness of the result depends on the accuracy of the supplied evidence.
This code does not perform DKIM cryptographic verification or SPF network evaluation.
26. DNS Monitoring Architecture in .NET 11
A production DNS monitor should separate discovery, interpretation and operational decisions.
Scheduled Worker
|
v
DNS Query Service
|
+------------+------------+
| | |
v v v
A/AAAA MX TXT
| | |
v v v
Address Check Mail Routing SPF/DKIM/DMARC
| | |
+------------+------------+
|
v
Policy Evaluation
|
v
Structured Findings
|
v
Historical SQL Storage
|
v
Alerting Engine
|
v
Dashboard / Email
Recommended application components:
| Component | Responsibility |
|---|---|
| DnsQueryService | Typed record resolution |
| DnsResultNormalizer | Normalize response status and record values |
| SpfPublicationAnalyzer | Check SPF policy publication and warnings |
| DkimKeyMonitor | Check configured selectors and key records |
| DmarcPublicationAnalyzer | Parse policy and reporting destinations |
| SmtpProbeService | Check TCP, SMTP banner and supported TLS behavior |
| AuthenticationVerifier | Evaluate real-message SPF, DKIM and DMARC evidence |
| HealthPolicyEngine | Apply customer-specific alerting rules |
The AuthenticationVerifier is optional for a simple DNS configuration monitoring product, but necessary if the system claims to verify real email authentication.
27. Monitoring State Is Not Binary
A monitoring service should avoid representing every check as only healthy or unhealthy.
Consider:
Healthy
Degraded
Misconfigured
NotConfigured
TemporarilyUnavailable
Unknown
The distinction is critical for DNS.
For example, a timeout does not prove a record is absent.
An intentionally configured Null MX is not necessarily a failure.
An AAAA record can be absent by design.
A DKIM selector may be intentionally disabled after key rotation.
The health state should therefore depend on an explicit desired configuration.
28. An Error Budget for DNS Monitoring
Transient DNS errors should not necessarily generate immediate critical incidents.
A monitor can define a time-window failure ratio:
For a check with a defined service objective, alerts can consider consecutive failures, duration, independent resolver agreement and operational impact.
For example:
Critical:
Authoritative and independent resolvers agree
that an essential MX record is missing.
Warning:
One resolver returns a transient timeout.
Information:
A planned DKIM selector is nearing retirement.
Healthy:
Published records match desired configuration.
These are illustrative policy examples, not mandatory DNS standards.
29. DNSSEC — Authentication of DNS Data
DNSSEC adds cryptographic authentication to DNS data.
It uses signatures and a chain of trust involving DNSKEY, DS and RRSIG records.
The goal is to authenticate the origin and integrity of DNS responses.
DNSSEC does not encrypt DNS traffic.
It also does not establish that a mail server or website is secure.
DNSSEC validation can protect against certain forms of DNS response forgery, while SPF, DKIM and DMARC operate at the email authentication layer.
Therefore, DNSSEC and email authentication are complementary rather than interchangeable.
30. Security Engineering — Avoid Turning DNS Monitoring into an SSRF Primitive
A system allowing customers to enter arbitrary hostnames must not blindly connect to every address returned by DNS.
DNS records can resolve to:
- loopback addresses;
- private address ranges;
- link-local addresses;
- cloud instance metadata endpoints;
- internal administrative services.
The risk becomes especially important when DNS monitoring includes active HTTP or SMTP probes.
A production system should validate the resolved destination address, enforce network egress controls and consider DNS rebinding between resolution and connection.
For public monitoring products, a dedicated outbound network policy is preferable to relying entirely on application-level filters.
31. Testing Strategy
A reliable DNS monitoring system should be tested at multiple levels.
| Test level | Representative case |
|---|---|
| Parser unit tests | Malformed SPF and DMARC tags |
| Resolver integration | A, AAAA, MX and TXT responses |
| Negative caching | NXDOMAIN and NODATA |
| Timeout handling | Unavailable recursive resolver |
| SPF policy analysis | Nested includes and lookup budget |
| DKIM publication | Valid selector, missing selector, revoked key |
| DMARC alignment | Strict and relaxed domain matching |
| DNS propagation | Different recursive answers |
| SMTP connectivity | MX present but TCP 25 unavailable |
| Security | Private addresses and DNS rebinding |
32. Benchmarking Native .NET DNS APIs
Performance testing must distinguish:
A cached resolver response may complete much faster than a cold recursive lookup.
A benchmark should therefore record:
- warm-cache and cold-cache behavior;
- query type;
- resolver identity;
- response status;
- latency P50, P95 and P99;
- timeout frequency;
- positive and negative caching;
- concurrent request limits.
Parallel DNS queries should use bounded concurrency to avoid overwhelming resolvers or triggering rate limits.
A practical implementation can use SemaphoreSlim, Channels or a bounded worker pipeline.
33. Operational Runbook — Investigating an Email Authentication Failure
When a message fails DMARC, the investigation should follow a structured sequence.
1. Identify the RFC5322.From domain
2. Identify the SMTP MAIL FROM domain
3. Identify the connecting SMTP IP
4. Inspect the SPF authentication result
5. Inspect all DKIM signatures
6. Verify signing-domain alignment
7. Verify SPF-domain alignment
8. Inspect the applicable DMARC policy
9. Determine the actual receiver disposition
10. Correct the responsible sending system
It is often incorrect to respond to a DMARC failure by immediately weakening the domain policy.
The correct remediation may instead involve fixing a relay, enabling DKIM signing, correcting SPF authorization or changing the domain used in the SMTP envelope.
34. Final Engineering Checklist
- Monitor A and AAAA independently.
- Distinguish MX absence from Null MX.
- Validate that MX targets resolve appropriately.
- Check SMTP connectivity separately from DNS publication.
- Identify the effective SPF policy and evaluation limits.
- Do not mistake SPF publication for SPF authentication.
- Maintain an authoritative inventory of DKIM selectors.
- Distinguish public-key discovery from message signature verification.
- Evaluate DMARC using aligned SPF or DKIM results.
- Implement Organizational Domain logic correctly.
- Monitor DMARC aggregate reports before tightening enforcement.
- Handle NXDOMAIN, NODATA, SERVFAIL and timeouts separately.
- Respect positive and negative DNS caching.
- Compare independent resolvers when investigating propagation problems.
- Enforce outbound network security on active probes.
- Persist historical measurements and configuration changes.
- Use native .NET 11 DNS APIs where they satisfy the requirements.
- Keep advanced protocol evaluation in independent testable components.
35. Conclusions — DNS Is a Distributed Policy and Trust Infrastructure
DNS is not merely a mapping from domain names to IP addresses.
It is a distributed namespace used for service discovery, policy publication and cryptographic key distribution.
A and AAAA records describe network destinations.
MX records describe mail-routing preferences.
SPF describes authorization of SMTP sending infrastructure.
DKIM provides message-level cryptographic authentication.
DMARC connects authentication results to the domain visible to the recipient.
These layers solve different problems and provide different guarantees.
.NET 11 significantly improves the engineering experience by introducing native typed DNS APIs, configurable resolvers and structured result metadata.
But the availability of these APIs should not encourage developers to confuse DNS querying with full protocol verification.
36. Technical References
- RFC 1034 — Domain Names: Concepts and Facilities
- RFC 1035 — Domain Names: Implementation and Specification
- RFC 2308 — Negative Caching of DNS Queries
- RFC 5321 — Simple Mail Transfer Protocol
- RFC 7505 — Null MX
- RFC 7208 — Sender Policy Framework
- RFC 6376 — DomainKeys Identified Mail
- RFC 8301 — DKIM Cryptographic Algorithm and Key Updates
- RFC 8463 — Ed25519-SHA256 for DKIM
- RFC 7489 — DMARC
- RFC 8617 — Authenticated Received Chain
- Microsoft — What's New in .NET 11 Libraries
- Microsoft — System.Net.Dns API
- Microsoft — DnsResolver API
NicoGIS Tech Weekly · DNS Engineering Internals · 4 December 2026
All example domains and IP addresses are illustrative. The laboratory demonstrates native DNS resolution and selected publication-level policy checks. Complete SPF evaluation, DKIM cryptographic verification and DMARC policy enforcement require additional protocol-conformant implementations and real SMTP message evidence.
Commenti