Documentation
¶
Overview ¶
Package dns implements a full featured interface to the Domain Name System. Both server- and client-side programming is supported.
The package allows complete control over what is sent out to the DNS. The API follows the less-is-more principle, by presenting a small, clean interface.
It supports (asynchronous) querying/replying, incoming/outgoing zone transfers, TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing.
Resource records (RRs) are native types. They are not stored in wire format, but every Msg holds the wire-format in its Data field. Everything is modelled or made to look like an RR. The question section holds an RR and the EDNS0 option codes are also (fake/pseudo) RRs.
Basic usage pattern for creating a new resource record:
r := &MX{Header{Name:"miek.nl.", Class: dns.ClassINET, TTL: 3600}, Preference: 10, Mx: "mx.miek.nl."}
Or directly from a string (which is slower):
mx, err := dns.New("miek.nl. 3600 IN MX 10 mx.miek.nl.")
Or when the default origin (.) and TTL (3600) and class (IN) suit you:
mx, err := dns.New("miek.nl MX 10 mx.miek.nl")
Or even:
mx, err := dns.New("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
In the DNS, messages are exchanged, these messages contain RRs ([RRset]s). Use pattern for creating a message:
m := new(dns.Msg) m.Question = []dns.RR{mx}
The message m is now a message with the question section set to ask the MX records for the miek.nl. zone. Or when making an actual request.
m.ID = dns.ID() m.RecursionDesired = true
After creating a message it can be sent. Basic use pattern for synchronous querying the DNS at a server configured on 127.0.0.1 and port 53 using UDP:
c := new(dns.Client) in, rtt, err := c.Exchange(m1, "udp", "127.0.0.1:53")
When this functions returns you will get DNS message back. A DNS message consists out of four (five in this package) sections.
- The question section: in.Question.
- The answer section: in.Answer.
- The authority section: in.Ns.
- The additional section: in.Extra.
- And the extra and new fifth the pseudo section: in.Pseudo, see Msg.
The latter was added to make it easier to deal with EDNS0 option codes, which become more and more prevalent.
Each of these sections contain a []RR. Basic use pattern for accessing the rdata of a TXT RR as the first RR in the Answer section:
if t, ok := in.Answer[0].(*dns.TXT); ok { // do something with t.Txt }
Domain Name and TXT Character String Representations ¶
Both domain names and TXT character strings are converted to presentation form both when unpacked and when converted to strings.
For TXT character strings, tabs, carriage returns and line feeds will be converted to \t, \r and \n respectively. Back slashes and quotations marks will be escaped. Bytes below 32 and above 127 will be converted to \DDD form.
For domain names, in addition to the above rules brackets, periods, spaces, semicolons and the at symbol are escaped.
DNSSEC ¶
DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It uses public key cryptography to sign resource records. The public keys are stored in DNSKEY records and the signatures in RRSIG records.
Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK) bit to a request.
m := new(dns.Msg) m.Security = true m.UDPSize = 4096
When sending a message Msg.Pack is called, this takes care of allocating an OPT RR and setting the DO bit and the UDPSize in there.
Signature generation, signature verification (See RRSIG) and key generation are all supported.
EDNS0 ¶
EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated by RFC 6891. It defines a RR type, the OPT RR, which holds type-length-value sub-types. In this package all EDNS0 options are implemented as RRs. Doing basic "EDNS0" things, like setting the DNSSEC OK bit (DO) or the UDP buffer size is handled for you and these can be set directly on message as shown above.
The data of an OPT RR sits in the Msg Pseudo section consists out of a slice of EDNS0 (RFC 6891) interfaces. These are just RRs with an extra Pseudo() method.
Basic use pattern for a server to check if (and which) options are set, which is similar to how to deal with RRs.
for _, o := range m.Pseudo { switch x := o.(type) { case *dns.NSID: // do stuff with x.Nsid case *dns.SUBNET: // access x.Family, x.Address, etc. } }
Further Reading ¶
All functionality and types are documented in their respective types and functions.
Index ¶
- Constants
- Variables
- func ActivateAndServe(l net.Listener, p net.PacketConn, handler Handler) error
- func Compare(a, b RR) int
- func CompareName(a, b string) int
- func CompareSerial(a, b uint32) int
- func DefaultMsgInvalidFunc(m *Msg, err error)
- func Equal(a, b RR) bool
- func EqualName(a, b string) bool
- func EqualSerial(a, b uint32) bool
- func Handle(pattern string, handler Handler)
- func HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Msg))
- func HandleRemove(pattern string)
- func ListenAndServe(addr string, network string, handler Handler) error
- func RRToCode(o EDNS0) uint16
- func RRToStateful(rr DSO) uint16
- func RRToType(rr RR) uint16
- func SIG0Sign(m *Msg, k SIG0Signer, options *SIG0Option) error
- func SIG0Verify(m *Msg, y *KEY, k SIG0Signer, options *SIG0Option) error
- func TSIGSign(m *Msg, k TSIGSigner, options *TSIGOption) error
- func TSIGVerify(m *Msg, k TSIGSigner, options *TSIGOption) error
- func Zone(ctx context.Context) string
- type A
- type AAAA
- type AFSDB
- type ANY
- type AVC
- type AXFR
- type CAA
- type CDNSKEY
- type CDS
- type CERT
- type CNAME
- type COOKIE
- type CSYNC
- type Client
- func (c *Client) Exchange(ctx context.Context, m *Msg, network, address string) (r *Msg, rtt time.Duration, err error)
- func (c *Client) ExchangeWithConn(ctx context.Context, m *Msg, conn net.Conn) (r *Msg, rtt time.Duration, err error)
- func (c *Client) TransferIn(ctx context.Context, m *Msg, network, address string) (<-chan *Envelope, error)
- func (c *Client) TransferInWithConn(ctx context.Context, m *Msg, conn net.Conn) (<-chan *Envelope, error)
- func (c *Client) TransferOut(w ResponseWriter, r *Msg, env <-chan *Envelope) (err error)
- type Comparer
- type Copier
- type CryptoSIG0
- type DAU
- type DELEG
- type DELEGI
- type DHCID
- type DHU
- type DLV
- type DNAME
- type DNSKEY
- func (rr *DNSKEY) Copy() RR
- func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error)
- func (rr *DNSKEY) Header() *Header
- func (k *DNSKEY) KeyTag() uint16
- func (rr *DNSKEY) Len() int
- func (k *DNSKEY) NewPrivate(s string) (crypto.PrivateKey, error)
- func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string
- func (rr *DNSKEY) String() string
- func (k *DNSKEY) ToCDNSKEY() *CDNSKEY
- func (k *DNSKEY) ToDS(h uint8) *DS
- type DS
- type DSO
- type EDE
- type EDNS0
- type EID
- type ESU
- type EUI48
- type EUI64
- type EXPIRE
- type Envelope
- type Error
- type GID
- type GPOS
- type HINFO
- type HIP
- type HTTPS
- type Handler
- type HandlerFunc
- type Header
- type HmacTSIG
- type ISDN
- type IXFR
- type InvalidMsgFunc
- type KEEPALIVE
- type KEY
- type KX
- type L32
- type L64
- type LLQ
- type LOC
- type LP
- type MB
- type MD
- type MF
- type MG
- type MINFO
- type MR
- type MX
- type Msg
- func (m *Msg) All() iter.Seq[RR]
- func (m *Msg) Hijack()
- func (m *Msg) Len() int
- func (m *Msg) Pack() error
- func (m *Msg) Read(p []byte) (n int, err error)
- func (m *Msg) ReadFrom(r io.Reader) (int64, error)
- func (m *Msg) String() string
- func (m *Msg) Unpack() error
- func (m *Msg) Write(p []byte) (n int, err error)
- func (m *Msg) WriteTo(w io.Writer) (int64, error)
- type MsgAcceptAction
- type MsgAcceptFunc
- type MsgHeader
- type MsgOption
- type N3U
- type NAPTR
- type NID
- type NIMLOC
- type NINFO
- type NS
- type NSAPPTR
- type NSEC
- type NSEC3
- type NSEC3PARAM
- type NSID
- type NULL
- type NXNAME
- type NXT
- type OPENPGPKEY
- type OPT
- func (rr *OPT) CompactAnswers() bool
- func (rr *OPT) Copy() RR
- func (rr *OPT) Delegation() bool
- func (rr *OPT) Header() *Header
- func (rr *OPT) Len() int
- func (rr *OPT) Rcode() uint16
- func (rr *OPT) Security() bool
- func (rr *OPT) SetCompactAnswers(co bool)
- func (rr *OPT) SetDelegation(de bool)
- func (rr *OPT) SetRcode(v uint16)
- func (rr *OPT) SetSecurity(do bool)
- func (rr *OPT) SetUDPSize(size uint16)
- func (rr *OPT) SetVersion(v uint8)
- func (rr *OPT) SetZ(z uint16)
- func (rr *OPT) String() string
- func (rr *OPT) UDPSize() uint16
- func (rr *OPT) Version() uint8
- func (rr *OPT) Z() uint16
- type PADDING
- type PTR
- type PX
- type Packer
- type ParseError
- type Pool
- type Pooler
- type REPORTING
- type RESINFO
- type RFC3597
- type RKEY
- type RP
- type RR
- type RRSIG
- func (rr *RRSIG) Copy() RR
- func (rr *RRSIG) Header() *Header
- func (rr *RRSIG) Len() int
- func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR, options *SignOption) error
- func (rr *RRSIG) String() string
- func (rr *RRSIG) ValidPeriod(t time.Time) bool
- func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR, options *SignOption) error
- type RRset
- type RT
- type ResponseController
- type ResponseWriter
- type SIG
- type SIG0Option
- type SIG0Signer
- type SMIMEA
- type SOA
- type SPF
- type SRV
- type SSHFP
- type SUBNET
- type SVCB
- type ServeMux
- type Server
- type Session
- type SignOption
- type TA
- type TALINK
- type TCPKEEPALIVE
- type TKEY
- type TLSA
- type TSIG
- type TSIGOption
- type TSIGSigner
- type TXT
- type Transfer
- type Transport
- type Typer
- type UID
- type UINFO
- type URI
- type X25
- type ZONEMD
- type ZONEVERSION
- type ZoneParser
Constants ¶
const ( // DefaultMsgSize is the standard default for messages larger than 512 bytes. DefaultMsgSize = 4096 // MinMsgSize is the minimal size of a DNS message. MinMsgSize = 512 // MaxMsgSize is the largest possible DNS message. MaxMsgSize = 65535 // MsgHeaderSize is the length of the header in the DNS message. MsgHeaderSize = 12 )
const ( RSAMD5 uint8 DH DSA RSASHA1 DSANSEC3SHA1 RSASHA1NSEC3SHA1 RSASHA256 RSASHA512 ECCGOST ECDSAP256SHA256 ECDSAP384SHA384 ED25519 ED448 INDIRECT uint8 = 252 PRIVATEDNS uint8 = 253 // Private (experimental keys) PRIVATEOID uint8 = 254 )
DNSSEC encryption algorithm codes.
const ( SHA1 uint8 // RFC 4034 SHA256 // RFC 4509 GOST94 // RFC 5933 SHA384 // Experimental SHA512 // Experimental )
DNSSEC hashing algorithm codes.
const ( FlagSEP = 1 FlagREVOKE = 1 << 7 FlagZONE = 1 << 8 FlagDELEG = 1 << 14 )
DNSKEY flag values.
const ( StatefulNone uint16 = 0x0 StatefulKEEPALIVE uint16 = 0x1 StatefulRETRYDELAY uint16 = 0x2 StatefulENCRYPTIONPADDING uint16 = 0x3 )
DSO option codes. All DSO types and constants in this package carry the Stateful prefix.
const ( CodeNone uint16 = 0x0 CodeLLQ uint16 = 0x1 // Long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01. CodeUL uint16 = 0x2 // Update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt. CodeNSID uint16 = 0x3 // Nsid (see RFC 5001). CodeESU uint16 = 0x4 // ENUM Source-URI draft: https://datatracker.ietf.org/doc/html/draft-kaplan-enum-source-uri-00. CodeDAU uint16 = 0x5 // DNSSEC Algorithm Understood. CodeDHU uint16 = 0x6 // DS Hash Understood. CodeN3U uint16 = 0x7 // NSEC3 Hash Understood. CodeSUBNET uint16 = 0x8 // Client-subnet, see RFC 7871. CodeEXPIRE uint16 = 0x9 // Expire, RFC 7314. CodeCOOKIE uint16 = 0xa // Cookie, RFC 7873. CodeTCPKEEPALIVE uint16 = 0xb // TCP keep alive (see RFC 7828). CodePADDING uint16 = 0xc // Padding (see RFC 7830). CodeEDE uint16 = 0xf // Extended DNS errors (see RFC 8914). CodeREPORTING uint16 = 0x12 // EDNS0 reporting (see RFC 9567). CodeZONEVERSION uint16 = 0x13 // Zone version (see RFC 9660). CodeLOCALSTART uint16 = 0xFDE9 // Beginning of range reserved for local/experimental use (see RFC 6891). CodeLOCALEND uint16 = 0xFFFE // End of range reserved for local/experimental use (see RFC 6891). )
ENDS0 option codes.
const ( ExtendedErrorOther uint16 = iota ExtendedErrorUnsupportedDNSKEYAlgorithm ExtendedErrorUnsupportedDSDigestType ExtendedErrorStaleAnswer ExtendedErrorForgedAnswer ExtendedErrorDNSSECIndeterminate ExtendedErrorDNSBogus ExtendedErrorSignatureExpired ExtendedErrorSignatureNotYetValid ExtendedErrorDNSKEYMissing ExtendedErrorRRSIGsMissing ExtendedErrorNoZoneKeyBitSet ExtendedErrorNSECMissing ExtendedErrorCachedError ExtendedErrorNotReady ExtendedErrorBlocked ExtendedErrorCensored ExtendedErrorFiltered ExtendedErrorProhibited ExtendedErrorStaleNXDOMAINAnswer ExtendedErrorNotAuthoritative ExtendedErrorNotSupported ExtendedErrorNoReachableAuthority ExtendedErrorNetworkError ExtendedErrorInvalidData ExtendedErrorSignatureExpiredBeforeValid ExtendedErrorTooEarly ExtendedErrorUnsupportedNSEC3IterValue ExtendedErrorUnableToConformToPolicy ExtendedErrorSynthesized ExtendedErrorInvalidQueryType )
Extended DNS Error Codes (RFC 8914).
const ( HmacSHA1 = "hmac-sha1." HmacSHA224 = "hmac-sha224." HmacSHA256 = "hmac-sha256." HmacSHA384 = "hmac-sha384." HmacSHA512 = "hmac-sha512." HmacMD5 = "hmac-md5.sig-alg.reg.int." // Deprecated: HmacMD5 is no longer supported. )
HMAC hashing codes. These are transmitted as domain names.
const ( TypeNone uint16 = 0 TypeA uint16 = 1 TypeNS uint16 = 2 TypeMD uint16 = 3 TypeMF uint16 = 4 TypeCNAME uint16 = 5 TypeSOA uint16 = 6 TypeMB uint16 = 7 TypeMG uint16 = 8 TypeMR uint16 = 9 TypeNULL uint16 = 10 TypePTR uint16 = 12 TypeHINFO uint16 = 13 TypeMINFO uint16 = 14 TypeMX uint16 = 15 TypeTXT uint16 = 16 TypeRP uint16 = 17 TypeAFSDB uint16 = 18 TypeX25 uint16 = 19 TypeISDN uint16 = 20 TypeRT uint16 = 21 TypeNSAPPTR uint16 = 23 TypeSIG uint16 = 24 TypeKEY uint16 = 25 TypePX uint16 = 26 TypeGPOS uint16 = 27 TypeAAAA uint16 = 28 TypeLOC uint16 = 29 TypeNXT uint16 = 30 TypeEID uint16 = 31 TypeNIMLOC uint16 = 32 TypeSRV uint16 = 33 TypeATMA uint16 = 34 TypeNAPTR uint16 = 35 TypeKX uint16 = 36 TypeCERT uint16 = 37 TypeDNAME uint16 = 39 TypeOPT uint16 = 41 TypeAPL uint16 = 42 // Not implemented. TypeDS uint16 = 43 TypeSSHFP uint16 = 44 TypeIPSECKEY uint16 = 45 // Not implemented. TypeRRSIG uint16 = 46 TypeNSEC uint16 = 47 TypeDNSKEY uint16 = 48 TypeDHCID uint16 = 49 TypeNSEC3 uint16 = 50 TypeNSEC3PARAM uint16 = 51 TypeTLSA uint16 = 52 TypeSMIMEA uint16 = 53 TypeHIP uint16 = 55 TypeNINFO uint16 = 56 TypeRKEY uint16 = 57 TypeTALINK uint16 = 58 TypeCDS uint16 = 59 TypeCDNSKEY uint16 = 60 TypeOPENPGPKEY uint16 = 61 TypeCSYNC uint16 = 62 TypeZONEMD uint16 = 63 TypeSVCB uint16 = 64 TypeHTTPS uint16 = 65 TypeSPF uint16 = 99 TypeUINFO uint16 = 100 TypeUID uint16 = 101 TypeGID uint16 = 102 TypeUNSPEC uint16 = 103 TypeNID uint16 = 104 TypeL32 uint16 = 105 TypeL64 uint16 = 106 TypeLP uint16 = 107 TypeEUI48 uint16 = 108 TypeEUI64 uint16 = 109 TypeNXNAME uint16 = 128 TypeURI uint16 = 256 TypeCAA uint16 = 257 TypeAVC uint16 = 258 TypeAMTRELAY uint16 = 260 // Not implemented. TypeRESINFO uint16 = 261 TypeTKEY uint16 = 249 TypeTSIG uint16 = 250 // Valid question types only. TypeIXFR uint16 = 251 TypeAXFR uint16 = 252 TypeMAILB uint16 = 253 TypeMAILA uint16 = 254 TypeANY uint16 = 255 TypeTA uint16 = 32768 TypeDLV uint16 = 32769 TypeDELEG uint16 = 65432 // Provisional type TypeDELEGI uint16 = 65433 // Provisional type TypeReserved uint16 = 65535 // valid question classes only. ClassINET = 1 ClassCSNET = 2 ClassCHAOS = 3 ClassHESIOD = 4 ClassNONE = 254 ClassANY = 255 // Message Response Codes, see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml RcodeSuccess = 0 // NoError - No Error [DNS] RcodeFormatError = 1 // FormErr - Format Error [DNS] RcodeServerFailure = 2 // ServFail - Server Failure [DNS] RcodeNameError = 3 // NXDomain - Non-Existent Domain [DNS] RcodeNotImplemented = 4 // NotImp - Not Implemented [DNS] RcodeRefused = 5 // Refused - Query Refused [DNS] RcodeYXDomain = 6 // YXDomain - Name Exists when it should not [DNS Update] RcodeYXRrset = 7 // YXRRSet - RR Set Exists when it should not [DNS Update] RcodeNXRrset = 8 // NXRRSet - RR Set that should exist does not [DNS Update] RcodeNotAuth = 9 // NotAuth - Server Not Authoritative for zone [DNS Update] RcodeNotZone = 10 // NotZone - Name not contained in zone [DNS Update/TSIG] RcodeStatefulNotImplemented = 11 // DSOTYPENI - DSO-TYPE Not Implemented [DSO] [DSO] RcodeBadSig = 16 // BADSIG - TSIG Signature Failure [TSIG] RcodeBadVers = 16 // BADVERS - Bad OPT Version [EDNS0] RcodeBadKey = 17 // BADKEY - Key not recognized [TSIG] RcodeBadTime = 18 // BADTIME - Signature out of time window [TSIG] RcodeBadMode = 19 // BADMODE - Bad TKEY Mode [TKEY] RcodeBadName = 20 // BADNAME - Duplicate key name [TKEY] RcodeBadAlg = 21 // BADALG - Algorithm not supported [TKEY] RcodeBadTrunc = 22 // BADTRUNC - Bad Truncation [TSIG] RcodeBadCookie = 23 // BADCOOKIE - Bad/missing Server Cookie [DNS Cookies] // Message Opcodes. There is no 3. OpcodeQuery = 0 OpcodeIQuery = 1 OpcodeStatus = 2 OpcodeNotify = 4 OpcodeUpdate = 5 OpcodeStateful = 6 )
Wire constants and supported types.
const ( ZONEMDSchemeSimple = 1 ZONEMDHashSHA384 = 1 ZONEMDHashSHA512 = 2 )
Used in ZONEMD, RFC 8976.
const ( IPSECGatewayNone uint8 = iota IPSECGatewayIPv4 IPSECGatewayIPv6 IPSECGatewayHost )
Used in IPSEC, RFC 4025, Section 2.3.
const ( AMTRELAYNone = IPSECGatewayNone AMTRELAYIPv4 = IPSECGatewayIPv4 AMTRELAYIPv6 = IPSECGatewayIPv6 AMTRELAYHost = IPSECGatewayHost )
Used in AMTRELAY, RFC 8777, Section 4.2.3.
const ( LOCEquator = 1 << 31 // RFC 1876, Section 2. LOCPrimemeridian = 1 << 31 // RFC 1876, Section 2. LOCHours = 60 * 1000 LOCDegrees = 60 * LOCHours LOCAltitudebase = 100000 )
Various constants used in the LOC RR. See RFC 1876.
const ( CertPKIX = 1 + iota CertSPKI CertPGP CertIPIX CertISPKI CertIPGP CertACPKIX CertIACPKIX CertURI = 253 CertOID = 254 )
Different Certificate Types, see RFC 4398, Section 2.1
const BatchSize = 15
BatchSize controls the maximum of packets we should read using recvmmsg, using ReadBatch, a tradeoff needs to be made with how much memory needs to be pre-allocated and how fast things should go. It is set to set to 15.
const MaxSerialIncrement = 2147483647
MaxSerialIncrement is the maximum difference between two serial numbers. See RFC 1982.
Variables ¶
var ( ErrID = &Error{err: "ID mismatch"} ErrAlg = &Error{err: "bad algorithm"} // ErrAlg indicates an error with the (DNSSEC) algorithm. ErrSig = &Error{err: "bad signature"} // ErrSig indicates that a signature can not be cryptographically validated. ErrKeyAlg = &Error{err: "bad key algorithm"} // ErrKeyAlg indicates that the algorithm in the key is not valid. ErrKey = &Error{err: "bad key"} ErrKeySize = &Error{err: "bad key size"} ErrNoTSIG = &Error{err: "no TSIG signature"} ErrNoSIG0 = &Error{err: "no SIG(0) signature"} ErrRcode = &Error{err: "bad rcode"} ErrRRset = &Error{err: "bad rrset"} ErrSOA = &Error{err: "no SOA"} // ErrSOA indicates that no SOA RR was seen when doing zone transfers. ErrTime = &Error{err: "bad time"} // ErrTime indicates a timing error in TSIG authentication. )
var AlgorithmToHash = map[uint8]crypto.Hash{ RSAMD5: crypto.MD5, DSA: crypto.SHA1, RSASHA1: crypto.SHA1, RSASHA1NSEC3SHA1: crypto.SHA1, RSASHA256: crypto.SHA256, ECDSAP256SHA256: crypto.SHA256, ECDSAP384SHA384: crypto.SHA384, RSASHA512: crypto.SHA512, }
AlgorithmToHash is a map of algorithm crypto hash IDs to crypto.Hash's. Newer algorithm that do their own hashing (i.e. ED25519) are not present here.
var AlgorithmToString = map[uint8]string{ RSAMD5: "RSAMD5", DH: "DH", DSA: "DSA", RSASHA1: "RSASHA1", DSANSEC3SHA1: "DSA-NSEC3-SHA1", RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1", RSASHA256: "RSASHA256", RSASHA512: "RSASHA512", ECCGOST: "ECC-GOST", ECDSAP256SHA256: "ECDSAP256SHA256", ECDSAP384SHA384: "ECDSAP384SHA384", ED25519: "ED25519", ED448: "ED448", INDIRECT: "INDIRECT", PRIVATEDNS: "PRIVATEDNS", PRIVATEOID: "PRIVATEOID", }
AlgorithmToString is a map of algorithm IDs to algorithm names.
var CertTypeToString = map[uint16]string{ CertPKIX: "PKIX", CertSPKI: "SPKI", CertPGP: "PGP", CertIPIX: "IPIX", CertISPKI: "ISPKI", CertIPGP: "IPGP", CertACPKIX: "ACPKIX", CertIACPKIX: "IACPKIX", CertURI: "URI", CertOID: "OID", }
CertTypeToString converts the Cert Type to its string representation. See RFC 4398 and RFC 6944.
var ClassToString = map[uint16]string{
ClassINET: "IN",
ClassCSNET: "CS",
ClassCHAOS: "CH",
ClassHESIOD: "HS",
ClassNONE: "NONE",
ClassANY: "ANY",
}
ClassToString is a maps Classes to strings for each CLASS wire type.
var CodeToRR = map[uint16]func() EDNS0{ CodeLLQ: func() EDNS0 { return new(LLQ) }, CodeREPORTING: func() EDNS0 { return new(REPORTING) }, CodeCOOKIE: func() EDNS0 { return new(COOKIE) }, CodeNSID: func() EDNS0 { return new(NSID) }, CodePADDING: func() EDNS0 { return new(PADDING) }, CodeEXPIRE: func() EDNS0 { return new(EXPIRE) }, CodeDAU: func() EDNS0 { return new(DAU) }, CodeDHU: func() EDNS0 { return new(DHU) }, CodeN3U: func() EDNS0 { return new(N3U) }, CodeTCPKEEPALIVE: func() EDNS0 { return new(TCPKEEPALIVE) }, CodeEDE: func() EDNS0 { return new(EDE) }, CodeSUBNET: func() EDNS0 { return new(SUBNET) }, CodeESU: func() EDNS0 { return new(ESU) }, CodeZONEVERSION: func() EDNS0 { return new(ZONEVERSION) }, }
CodeToRR is a map of constructors for each EDNS0 RR type.
var CodeToString = map[uint16]string{
CodeLLQ: "LLQ",
CodeREPORTING: "REPORTING",
CodeCOOKIE: "COOKIE",
CodeNSID: "NSID",
CodePADDING: "PADDING",
CodeEXPIRE: "EXPIRE",
CodeDAU: "DAU",
CodeDHU: "DHU",
CodeN3U: "N3U",
CodeTCPKEEPALIVE: "TCPKEEPALIVE",
CodeEDE: "EDE",
CodeSUBNET: "SUBNET",
CodeESU: "ESU",
CodeZONEVERSION: "ZONEVERSION",
}
CodeToString is a map of strings for each EDNS0 RR type.
var DefaultServeMux = NewServeMux()
DefaultServeMux is the default ServeMux used by Serve.
var ExtendedErrorToString = map[uint16]string{ ExtendedErrorOther: "Other", ExtendedErrorUnsupportedDNSKEYAlgorithm: "Unsupported DNSKEY Algorithm", ExtendedErrorUnsupportedDSDigestType: "Unsupported DS Digest Type", ExtendedErrorStaleAnswer: "Stale Answer", ExtendedErrorForgedAnswer: "Forged Answer", ExtendedErrorDNSSECIndeterminate: "DNSSEC Indeterminate", ExtendedErrorDNSBogus: "DNSSEC Bogus", ExtendedErrorSignatureExpired: "Signature Expired", ExtendedErrorSignatureNotYetValid: "Signature Not Yet Valid", ExtendedErrorDNSKEYMissing: "DNSKEY Missing", ExtendedErrorRRSIGsMissing: "RRSIGs Missing", ExtendedErrorNoZoneKeyBitSet: "No Zone Key Bit Set", ExtendedErrorNSECMissing: "NSEC Missing", ExtendedErrorCachedError: "Cached Error", ExtendedErrorNotReady: "Not Ready", ExtendedErrorBlocked: "Blocked", ExtendedErrorCensored: "Censored", ExtendedErrorFiltered: "Filtered", ExtendedErrorProhibited: "Prohibited", ExtendedErrorStaleNXDOMAINAnswer: "Stale NXDOMAIN Answer", ExtendedErrorNotAuthoritative: "Not Authoritative", ExtendedErrorNotSupported: "Not Supported", ExtendedErrorNoReachableAuthority: "No Reachable Authority", ExtendedErrorNetworkError: "Network Error", ExtendedErrorInvalidData: "Invalid Data", ExtendedErrorSignatureExpiredBeforeValid: "Signature Expired Before Valid", ExtendedErrorTooEarly: "Too Early", ExtendedErrorUnsupportedNSEC3IterValue: "Unsupported NSEC3 Iterations Value", ExtendedErrorUnableToConformToPolicy: "Unable To Conform To Policy", ExtendedErrorSynthesized: "Synthesized", ExtendedErrorInvalidQueryType: "Invalid Query Type", }
ExtendedErrorToString maps extended error info codes to a human readable description.
var HashToString = map[uint8]string{ SHA1: "SHA1", SHA256: "SHA256", GOST94: "GOST94", SHA384: "SHA384", SHA512: "SHA512", }
HashToString is a map of hash IDs to names.
var ID = id
ID by default returns a 16-bit random number to be used as a message id. The number is drawn from a cryptographically secure random number generator. This being a variable the function can be reassigned to a custom function. For instance, to make it return a static value for testing:
dns.ID = func() uint16 { return 3 }
var OpcodeToString = map[uint8]string{
OpcodeQuery: "QUERY",
OpcodeIQuery: "IQUERY",
OpcodeStatus: "STATUS",
OpcodeNotify: "NOTIFY",
OpcodeUpdate: "UPDATE",
OpcodeStateful: "STATEFUL",
}
OpcodeToString maps Opcodes to strings.
var RcodeToString = map[uint16]string{
RcodeSuccess: "NOERROR",
RcodeFormatError: "FORMERR",
RcodeServerFailure: "SERVFAIL",
RcodeNameError: "NXDOMAIN",
RcodeNotImplemented: "NOTIMPL",
RcodeRefused: "REFUSED",
RcodeYXDomain: "YXDOMAIN",
RcodeYXRrset: "YXRRSET",
RcodeNXRrset: "NXRRSET",
RcodeNotAuth: "NOTAUTH",
RcodeNotZone: "NOTZONE",
RcodeBadSig: "BADSIG",
RcodeStatefulNotImplemented: "DSOTYPENI",
RcodeBadKey: "BADKEY",
RcodeBadTime: "BADTIME",
RcodeBadMode: "BADMODE",
RcodeBadName: "BADNAME",
RcodeBadAlg: "BADALG",
RcodeBadTrunc: "BADTRUNC",
RcodeBadCookie: "BADCOOKIE",
}
RcodeToString maps Rcodes to strings.
var StatefulToRR = map[uint16]func() DSO{ StatefulKEEPALIVE: func() DSO { return new(KEEPALIVE) }, }
StatefulToRR is a map of constructors for each DSO RR type.
var StatefulToString = map[uint16]string{
StatefulKEEPALIVE: "KEEPALIVE",
}
StatefulToString is a map of strings for each DSO RR type.
var StringToAlgorithm = reverse.Int8(AlgorithmToString)
StringToAlgorithm is the reverse of AlgorithmToString.
var StringToCertType = reverse.Int16(CertTypeToString)
StringToCertType is the reverse of CertTypeToString.
var StringToClass = reverse.Int16(ClassToString)
StringToClass is the reverse of ClassToString.
var StringToCode = reverse.Int16(CodeToString)
StringtoCode is the reverse of CodeToString.
var StringToExtendedError = reverse.Int16(ExtendedErrorToString)
StringToExtendedError is a map from human readable descriptions to extended error info codes.
var StringToHash = reverse.Int8(HashToString)
StringToHash is a map of names to hash IDs.
var StringToOpcode = reverse.Int8(OpcodeToString)
StringToOpcode is a map of opcodes to strings.
var StringToRcode = reverse.Int16(RcodeToString)
StringToRcode is a map of rcodes to strings.
var StringToType = reverse.Int16(TypeToString)
StringToType is the reverse of TypeToString.
var TypeToRR = map[uint16]func() RR{ TypeNULL: func() RR { return new(NULL) }, TypeNXNAME: func() RR { return new(NXNAME) }, TypeCNAME: func() RR { return new(CNAME) }, TypeHINFO: func() RR { return new(HINFO) }, TypeMB: func() RR { return new(MB) }, TypeMG: func() RR { return new(MG) }, TypeMINFO: func() RR { return new(MINFO) }, TypeMR: func() RR { return new(MR) }, TypeMF: func() RR { return new(MF) }, TypeMD: func() RR { return new(MD) }, TypeMX: func() RR { return new(MX) }, TypeAFSDB: func() RR { return new(AFSDB) }, TypeX25: func() RR { return new(X25) }, TypeISDN: func() RR { return new(ISDN) }, TypeRT: func() RR { return new(RT) }, TypeNS: func() RR { return new(NS) }, TypePTR: func() RR { return new(PTR) }, TypeRP: func() RR { return new(RP) }, TypeSOA: func() RR { return new(SOA) }, TypeTXT: func() RR { return new(TXT) }, TypeSPF: func() RR { return new(SPF) }, TypeAVC: func() RR { return new(AVC) }, TypeSRV: func() RR { return new(SRV) }, TypeNAPTR: func() RR { return new(NAPTR) }, TypeCERT: func() RR { return new(CERT) }, TypeDNAME: func() RR { return new(DNAME) }, TypeA: func() RR { return new(A) }, TypeAAAA: func() RR { return new(AAAA) }, TypePX: func() RR { return new(PX) }, TypeGPOS: func() RR { return new(GPOS) }, TypeLOC: func() RR { return new(LOC) }, TypeSIG: func() RR { return new(SIG) }, TypeRRSIG: func() RR { return new(RRSIG) }, TypeNXT: func() RR { return new(NXT) }, TypeNSEC: func() RR { return new(NSEC) }, TypeDLV: func() RR { return new(DLV) }, TypeCDS: func() RR { return new(CDS) }, TypeDS: func() RR { return new(DS) }, TypeKX: func() RR { return new(KX) }, TypeTA: func() RR { return new(TA) }, TypeTALINK: func() RR { return new(TALINK) }, TypeSSHFP: func() RR { return new(SSHFP) }, TypeKEY: func() RR { return new(KEY) }, TypeCDNSKEY: func() RR { return new(CDNSKEY) }, TypeDNSKEY: func() RR { return new(DNSKEY) }, TypeRKEY: func() RR { return new(RKEY) }, TypeNSAPPTR: func() RR { return new(NSAPPTR) }, TypeNSEC3: func() RR { return new(NSEC3) }, TypeNSEC3PARAM: func() RR { return new(NSEC3PARAM) }, TypeTKEY: func() RR { return new(TKEY) }, TypeURI: func() RR { return new(URI) }, TypeDHCID: func() RR { return new(DHCID) }, TypeTLSA: func() RR { return new(TLSA) }, TypeSMIMEA: func() RR { return new(SMIMEA) }, TypeHIP: func() RR { return new(HIP) }, TypeNINFO: func() RR { return new(NINFO) }, TypeNID: func() RR { return new(NID) }, TypeL32: func() RR { return new(L32) }, TypeL64: func() RR { return new(L64) }, TypeLP: func() RR { return new(LP) }, TypeEUI48: func() RR { return new(EUI48) }, TypeEUI64: func() RR { return new(EUI64) }, TypeCAA: func() RR { return new(CAA) }, TypeUID: func() RR { return new(UID) }, TypeGID: func() RR { return new(GID) }, TypeUINFO: func() RR { return new(UINFO) }, TypeEID: func() RR { return new(EID) }, TypeNIMLOC: func() RR { return new(NIMLOC) }, TypeOPENPGPKEY: func() RR { return new(OPENPGPKEY) }, TypeCSYNC: func() RR { return new(CSYNC) }, TypeZONEMD: func() RR { return new(ZONEMD) }, TypeOPT: func() RR { return new(OPT) }, TypeRESINFO: func() RR { return new(RESINFO) }, TypeSVCB: func() RR { return new(SVCB) }, TypeHTTPS: func() RR { return new(HTTPS) }, TypeDELEG: func() RR { return new(DELEG) }, TypeDELEGI: func() RR { return new(DELEGI) }, TypeANY: func() RR { return new(ANY) }, TypeAXFR: func() RR { return new(AXFR) }, TypeIXFR: func() RR { return new(IXFR) }, TypeTSIG: func() RR { return new(TSIG) }, }
TypeToRR is a map of constructors for each RR type.
var TypeToString = map[uint16]string{
TypeNULL: "NULL",
TypeNXNAME: "NXNAME",
TypeCNAME: "CNAME",
TypeHINFO: "HINFO",
TypeMB: "MB",
TypeMG: "MG",
TypeMINFO: "MINFO",
TypeMR: "MR",
TypeMF: "MF",
TypeMD: "MD",
TypeMX: "MX",
TypeAFSDB: "AFSDB",
TypeX25: "X25",
TypeISDN: "ISDN",
TypeRT: "RT",
TypeNS: "NS",
TypePTR: "PTR",
TypeRP: "RP",
TypeSOA: "SOA",
TypeTXT: "TXT",
TypeSPF: "SPF",
TypeAVC: "AVC",
TypeSRV: "SRV",
TypeNAPTR: "NAPTR",
TypeCERT: "CERT",
TypeDNAME: "DNAME",
TypeA: "A",
TypeAAAA: "AAAA",
TypePX: "PX",
TypeGPOS: "GPOS",
TypeLOC: "LOC",
TypeSIG: "SIG",
TypeRRSIG: "RRSIG",
TypeNXT: "NXT",
TypeNSEC: "NSEC",
TypeDLV: "DLV",
TypeCDS: "CDS",
TypeDS: "DS",
TypeKX: "KX",
TypeTA: "TA",
TypeTALINK: "TALINK",
TypeSSHFP: "SSHFP",
TypeKEY: "KEY",
TypeCDNSKEY: "CDNSKEY",
TypeDNSKEY: "DNSKEY",
TypeRKEY: "RKEY",
TypeNSEC3: "NSEC3",
TypeNSEC3PARAM: "NSEC3PARAM",
TypeTKEY: "TKEY",
TypeURI: "URI",
TypeDHCID: "DHCID",
TypeTLSA: "TLSA",
TypeSMIMEA: "SMIMEA",
TypeHIP: "HIP",
TypeNINFO: "NINFO",
TypeNID: "NID",
TypeL32: "L32",
TypeL64: "L64",
TypeLP: "LP",
TypeEUI48: "EUI48",
TypeEUI64: "EUI64",
TypeCAA: "CAA",
TypeUID: "UID",
TypeGID: "GID",
TypeUINFO: "UINFO",
TypeEID: "EID",
TypeNIMLOC: "NIMLOC",
TypeOPENPGPKEY: "OPENPGPKEY",
TypeCSYNC: "CSYNC",
TypeZONEMD: "ZONEMD",
TypeOPT: "OPT",
TypeRESINFO: "RESINFO",
TypeSVCB: "SVCB",
TypeHTTPS: "HTTPS",
TypeDELEG: "DELEG",
TypeDELEGI: "DELEGI",
TypeANY: "ANY",
TypeAXFR: "AXFR",
TypeIXFR: "IXFR",
TypeTSIG: "TSIG",
TypeNSAPPTR: "NSAP-PTR",
}
TypeToString is a map of strings for each RR type.
var Version = v{0, 5, 2}
Version is current version of this library.
Functions ¶
func ActivateAndServe ¶
ActivateAndServe activates a server with a listener from systemd, l and p should not both be non-nil. If both l and p are not nil only p will be used. Invokes handler for incoming queries.
func Compare ¶
Compare returns an integer comparing two RRs according to "Canonical Form and Order of Resource Records" in RFC 4034 Section 6. Note the TTL is skipped when comparing. The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
func CompareName ¶ added in v0.0.3
CompareName compares the name a and b as defined in RFC 4034, canonical ordering of names. If a label is the asterisks label "*" it is always equal (wildcard match).
func CompareSerial ¶ added in v0.5.1
CompareSerial compares a, b which are serial numbers are timestamps from signatures, while taking into account RFC 1984 serial arithemetic, -1 is returned when a is smaller, +1 when a is larger, otherwise 0.
func DefaultMsgInvalidFunc ¶
DefaultMsgInvalidFunc is the default function used in case no InvalidMsgFunc is set. It is defined to be a noop.
func EqualName ¶ added in v0.0.3
EqualName returns true if the domain names a and b are equal. See CompareName.
func EqualSerial ¶ added in v0.5.1
EqualSerial return true if a and b are equal. This function is here for consistency only.
func Handle ¶
Handle registers the handler with the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
func HandleFunc ¶
func HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Msg))
HandleFunc registers the handler function with the given pattern in the DefaultServeMux.
func HandleRemove ¶
func HandleRemove(pattern string)
HandleRemove deregisters the handle with the given pattern in the DefaultServeMux.
func ListenAndServe ¶
ListenAndServe Starts a server on address and network specified and invokes handler for incoming queries.
func RRToStateful ¶
RRToStateful is the reverse of StatefulToRR, implemented as a function.
func SIG0Sign ¶ added in v0.1.10
func SIG0Sign(m *Msg, k SIG0Signer, options *SIG0Option) error
SOG0Sign signs a dns.Msg. It fills the signature with the appropriate data. The SIG record should have the SignerName, KeyTag, Algorithm, Inception and Expiration set.
func SIG0Verify ¶ added in v0.1.10
func SIG0Verify(m *Msg, y *KEY, k SIG0Signer, options *SIG0Option) error
Verify validates the message buf using the key k.
func TSIGSign ¶ added in v0.0.3
func TSIGSign(m *Msg, k TSIGSigner, options *TSIGOption) error
TSIGSign fills out the TSIG record in m. This should be a "stub" TSIG RR (see NewTSIG) with the algorithm, key name (owner name of the RR), time fudge (defaults to 300 seconds, if zero). When Sign is called for the first time: options.RequestMAC should be empty and options.TimersOnly should be false. When this function returns options.RequestMAC will have the MAC as calculated.
func TSIGVerify ¶ added in v0.0.3
func TSIGVerify(m *Msg, k TSIGSigner, options *TSIGOption) error
TSIGVerify verifies the TSIG on a message. On success a nil error is returned. The TSIG record is removed from m.Data, but left in the unpacked message m. TODO(miek): that a good plan? When this function returns options.RequestMAC will have the MAC seen on the TSIG.
Types ¶
type ANY ¶
type ANY struct {
Hdr Header
}
ANY is a wildcard record. See RFC 1035, Section 3.2.3. ANY is named "*" there.
type AVC ¶
AVC RR. See https://www.iana.org/assignments/dns-parameters/AVC/avc-completed-template.
type AXFR ¶
type AXFR struct {
Hdr Header
}
AXFR is a meta record used (solely) in question sections to ask for a zone transfer.
type CAA ¶
type CAA struct { Hdr Header Flag uint8 Tag string Value string `dns:"octet"` // Value is the character-string encoding of the value field as specified in RFC 1035, Section 5.1. }
CAA RR. See RFC 6844.
type CERT ¶
type CERT struct { Hdr Header Type uint16 KeyTag uint16 Algorithm uint8 Certificate string `dns:"base64"` }
CERT RR. See RFC 4398.
type COOKIE ¶
type COOKIE struct {
Cookie string `dns:"hex"`
}
The Cookie option is used to add a DNS Cookie to a message.
The Cookie field consists out of a client cookie (RFC 7873 Section 4), that is always 8 bytes. It may then optionally be followed by the server cookie. The server cookie is of variable length, 8 to a maximum of 32 bytes. In other words:
cCookie := o.Cookie[:16] sCookie := o.Cookie[16:]
There is no guarantee that the Cookie string has a specific length.
This record must be put in the pseudo section.
type Client ¶
type Client struct { *Transport // If Transport is nil it gets a [NewDefaultTransport]. *Transfer // If a transfer is attempted, this holds the optional signing settings. }
A Client is a DNS client. It is safe to use a client from multiple goroutines.
func NewClient ¶ added in v0.1.5
func NewClient() *Client
NewClient returns a client with the transport set to NewDefaultTransport.
func (*Client) Exchange ¶
func (c *Client) Exchange(ctx context.Context, m *Msg, network, address string) (r *Msg, rtt time.Duration, err error)
Exchange performs a synchronous query. It sends the message m to the address contained in a and waits for a reply. Basic use pattern with a *dns.Client:
c := new(dns.Client) resp, rtt, err := c.Exchange(ctx, m, "udp", "127.0.0.1:53")
If client does not have a transport set NewDefaultTransport is set and used. Exchange does not retry a failed query, nor will it fall back to TCP in case of truncation when UDP is used.
If the TLS config is set in the transport a (TCP) connection with TLS is attempted.
It is up to the caller to create a message that allows for larger responses to be returned. Specifically this means setting [Msg.Bufsize] that will advertise a larger buffer. Messages without an Bufsize will fall back to the historic limit of 512 octets (bytes).
The full binary data is included in the (decoded) message as r.Data. If the Data buffer in m is empty client.Exchange calls m.Pack().
It returns an error (ErrID) if the message returned does not have the same ID as the message sent.
func (*Client) ExchangeWithConn ¶
func (c *Client) ExchangeWithConn(ctx context.Context, m *Msg, conn net.Conn) (r *Msg, rtt time.Duration, err error)
ExchangeWithConn behaves like [client.Exchange], but with a supplied connection.
func (*Client) TransferIn ¶ added in v0.1.5
func (c *Client) TransferIn(ctx context.Context, m *Msg, network, address string) (<-chan *Envelope, error)
TransferIn performs a zone transfer with address over network, the message m is used to ask for the transfer and should have an AXFR or IXFR RR in the question section. For doing an IXFR a SOA record needs to be present in the [Ns] section of the Msg, see RFC 1995.
If the pseudo section contains a (stub) TSIG or in the future. SIG0 record, TSIG or SIG0 signing is performed, see NewTSIG and NewSIG0 on how create such RRs. For this the client also need a TSIGSigner or SIG0Signer.
On the returned channel the received RRs are returned (and a non-nil erorr in case of an error). These RRs are as they were found, i.e. including the starting and ending SOA RRs.
If m's buffer is empty TransferIn will call m.Pack(). If the clients's transport is nil NewDefaultTransport will be set and used.
Setting up a transfer is done as follows:
c := dns.NewClient() c.Transfer = &dns.Transfer{TSIGSigner: dns.HmacTSIG{[]byte("secret")}} // optionally set up TSIG with hmac m := dns.NewMsg("example.org.", dns.TypeAXFR) env, err := c.TransferIn(context.TODO(), m, "tcp", addr) if err != nil { return fmt.Errorf("failed to setup zone transfer in", err) } for e := range env { if e.Error != nil { // ... } // do things with e.Answer }
func (*Client) TransferInWithConn ¶ added in v0.1.5
func (c *Client) TransferInWithConn(ctx context.Context, m *Msg, conn net.Conn) (<-chan *Envelope, error)
TransferInWithConnn behaves like [client.TransferIn], but with a supplied connection.
func (*Client) TransferOut ¶ added in v0.1.5
func (c *Client) TransferOut(w ResponseWriter, r *Msg, env <-chan *Envelope) (err error)
TransferOut performs an outgoing transfer with the client connecting in w, r is the request that initiates the transfer and is used for TSIG/SIG0.
Example setup from within a dns.HandleFunc:
r.Unpack() w.Hijack() // hijack the connection as we should close when done env := make(chan *dns.Envelope) c := dns.NewClient() var wg sync.WaitGroup wg.Go(func() { c.TransferOut(w, r, env) w.Close() }) env <- &dns.Envelope{Answer: []dns.RR{...}} close(env)
The server is responsible for sending the correct sequence of RRs through the channel env. If the clients's transport is nil NewDefaultTransport will be set and used.
type Comparer ¶ added in v0.0.4
Comparer interface defines a compare function that returns -1, 0, or +1.
type Copier ¶
type Copier interface {
Copy() RR
}
The Copier interface defines a copy function that returns a deep copy of the RR. All RRs defined in this package implement this interface.
type CryptoSIG0 ¶ added in v0.1.10
func (CryptoSIG0) Key ¶ added in v0.1.10
func (c CryptoSIG0) Key() *KEY
func (CryptoSIG0) Sign ¶ added in v0.1.10
func (c CryptoSIG0) Sign(s *SIG, p []byte) ([]byte, error)
func (CryptoSIG0) Signer ¶ added in v0.1.10
func (c CryptoSIG0) Signer() crypto.Signer
type DAU ¶
type DAU struct {
AlgCode []uint8
}
DAU implements the EDNS0 "DNSSEC Algorithm Understood" option. See RFC 6975.
This record must be put in the pseudo section.
type DHU ¶
type DHU struct {
AlgCode []uint8
}
DHU implements the EDNS0 "DS Hash Understood" option. See RFC 6975.
This record must be put in the pseudo section.
type DNSKEY ¶
type DNSKEY struct { Hdr Header Flags uint16 Protocol uint8 Algorithm uint8 PublicKey string `dns:"base64"` }
DNSKEY RR. See RFC 4034 and RFC 3755.
func NewDNSKEY ¶ added in v0.1.10
NewDNSKEY returns a DNSKEY with good defaults for some fields. The key's flag field is set to 256.
func (*DNSKEY) Generate ¶
func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error)
Generate generates a DNSKEY of the given bit size. The public part is put inside the DNSKEY record. The Algorithm in the key must be set as this will define what kind of DNSKEY will be generated. The ECDSA algorithms imply a fixed keysize, in that case bits should be set to the size of the algorithm.
func (*DNSKEY) NewPrivate ¶ added in v0.1.12
func (k *DNSKEY) NewPrivate(s string) (crypto.PrivateKey, error)
NewPrivate returns a crypto.PrivateKey by parsing the string s. s should be in the same form of the BIND private key files.
func (*DNSKEY) PrivateKeyString ¶
func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string
PrivateKeyString converts a PrivateKey to a string. This string has the same format as the private-key-file of BIND9 (Private-key-format: v1.3). It needs some info from the key (the algorithm), so its a method of the DNSKEY. It supports *rsa.PrivateKey, *ecdsa.PrivateKey and ed25519.PrivateKey.
type DS ¶
type DSO ¶
DSO determines if the "RR" is posing as an DSO option. DSO options are considered just RRs and must be added to the [Stateful] section of a DNS message. The Len method must return the the length of the octets for the entire option, which is four (2 octets for the type, and 2 octets for the length) plus the encoded length of the option itself.
type EDE ¶
EDE option is used to return additional information about the cause of DNS errors.
This record must be put in the pseudo section.
type EDNS0 ¶
type EDNS0 interface { RR // Pseudo signal that the type implementing this interface is an EDNS0 sub-type. Pseudo() bool }
EDNS0 determines if the "RR" is posing as an EDNS0 option. EDNS0 options are considered just RRs and must be added to the [Pseudo] section of a DNS message. The Len method must return the length of the octets in the OPT RR, which is four (2 octets for the type, and 2 octets for the length) plus the encoded lengh of the option itself.
Note that these types has (in this package) a presentation format and can also be parsed from a string via New. That means you can create EDNS0 options directly from a string.
type EID ¶
EID RR. See http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt.
type ESU ¶ added in v0.0.3
type ESU struct {
URI string
}
The ESU option for ENUM Source-URI Extension.
type EXPIRE ¶
type EXPIRE struct { // If Expire is zero this option will be empty. Expire uint32 }
EXPIRE implements the EDNS0 option as described in RFC 7314.
This record must be put in the pseudo section.
type Envelope ¶ added in v0.0.3
type Envelope struct { Answer []RR // The RRs as returned by the remote server, or the ones to be send to the remote. Error error // If something went wrong, this contains the error. }
Envelope is used when doing a zone transfer with a remote server.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error represents a DNS error.
type HIP ¶
type HIP struct { Hdr Header HitLength uint8 PublicKeyAlgorithm uint8 PublicKeyLength uint16 Hit string `dns:"size-hex:HitLength"` PublicKey string `dns:"size-base64:PublicKeyLength"` RendezvousServers []string `dns:"domain-name"` }
HIP RR. See RFC 8005.
type HTTPS ¶
type HTTPS struct{ SVCB }
HTTPS RR. See RFC 9460. Everything valid for SVCB applies to HTTPS as well. Except that the HTTPS record is intended for use with the HTTP and HTTPS protocols.
type Handler ¶
type Handler interface {
ServeDNS(ctx context.Context, w ResponseWriter, r *Msg)
}
Handler is implemented by any value that implements ServeDNS. The message r is minimally decoded, only up to the question section (mostly first 20-ish bytes) are decoded, see [Option]. The rest of the message is available in r.Data, so if a message is deemed worthwhile a:
r.Unpack()
to get the entire message.
The context is cancelled when the server exits. The context carries the pattern of the handler (this is commonly the DNS zone) that was used to invoke it. You can retrieve that pattern with Zone.
type HandlerFunc ¶
type HandlerFunc func(context.Context, ResponseWriter, *Msg)
The HandlerFunc type is an adapter to allow the use of ordinary functions as DNS handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.
func (HandlerFunc) ServeDNS ¶
func (f HandlerFunc) ServeDNS(ctx context.Context, w ResponseWriter, r *Msg)
ServeDNS calls f(w, r).
type Header ¶
type Header struct { Name string `dns:"cdomain-name"` // Name is the owner name of the RR. Class uint16 // Class is the class of the RR, this is almost always [ClassINET]. TTL uint32 // TTL is the time-to-live of the RR. // contains filtered or unexported fields }
Header is the header in a DNS resource record. It implements the RR interface, as a header is the RR without any data.
type HmacTSIG ¶ added in v0.1.5
type HmacTSIG struct {
Secret []byte
}
HmacTSIG is TSIGSigner and TSIGVerifier that does the default HMAC for TSIG, see RFC 8945.
type ISDN ¶
ISDN RR. See RFC 1183, Section 3.2.
type IXFR ¶
type IXFR struct {
Hdr Header
}
IXFR is a meta record used (solely) in question sections to ask for an incremental zone transfer.
type InvalidMsgFunc ¶
InvalidMsgFunc is a listener hook for observing incoming messages that were discarded because they could not be parsed or an earlier error in the server. Every message that is read by a Reader will eventually be provided to the Handler, or passed to this function.
type KEEPALIVE ¶
KEEPALIVE implements RFC 8490, Section 7.1: Keepalive TLV.
This record must be put in the stateful section.
type LLQ ¶
LLQ stands for Long Lived Queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01 Implemented for completeness, as the EDNS0 type code is assigned.
This record must be put in the pseudo section.
type LOC ¶
type LOC struct { Hdr Header Version uint8 Size uint8 HorizPre uint8 VertPre uint8 Latitude uint32 Longitude uint32 Altitude uint32 }
LOC RR. See RFC 1876.
type MINFO ¶
type MINFO struct { Hdr Header Rmail string `dns:"cdomain-name"` Email string `dns:"cdomain-name"` }
MINFO RR. See RFC 1035.
type Msg ¶
type Msg struct { MsgHeader // Question holds a single "RR", in quotes because it is only the domain name, type and class that is // actually encoded here. This package takes care of taking and returning the right bit of an RR. // Setting the question is done like so: msg.Question = []RR{&MX{Hdr: Header{Name: "miek.nl.", Class: ClassINET}}} // This sets it to "miek.nl.", TypeMX, ClassINET. Just like all the other sections. Question []RR Answer []RR // Holds the RR(s) of the answer section. Ns []RR // Holds the RR(s) of the authority section. Extra []RR // Holds the RR(s) of the additional section, except records that go into the pseudo section. // The Pseudo section is a virtual section that holds the OPT EDNS0 options, that are interpreted (and shown) as RRs. // The OPT RR will never be visible in Extra, nor in the Pseudo section, this is all handled transparently. Pseudo []RR // Holds the RR(s) of the (virtual) pseudo section. // The Stateful section is a virtual section that holds the DSO option, that are interpreted (and shown) // as RRs. There is no OPT like record that holds these, the whole message format is slightly different. Stateful []RR // Holds the DSO RR(s) for Stateful operations, see RFC 8490. // Data is the data of the message that was either received from the wire or is about to be send // over the wire. Note that this data is a snapshot of the Msg when it was packed or unpacked. Data []byte // Option is a bit mask of options that control the unpacking. When zero the entire message is unpacked. Options MsgOption // contains filtered or unexported fields }
Msg is a DNS message. Each message has a Data field that contains the binary data buffer. This is filled when calling Msg.Pack, it is read and parsed into a Msg by Msg.Unpack. When the server allocated Data when reading from the wire, the server owns the allocation. Whenever the message is written to the default ResponseWriter it is returned to the server's pool. If you need to make the Msg the sole owner of the allocation call Msg.Hijack, the allocation will then not be returned. When you create a new Msg, you are in full control over the buffer as there is no relation to whatever server.
Msg implements iter.Seq, so you can range over it, when doing so the RRs of each section are returned, this includes the pseudo section.
func Exchange ¶
Exchange performs a synchronous query over "network". It sends the message m to the address and waits for a reply. Exchange does not retry a failed query, nor will it fall back to TCP in case of truncation. If the Data buffer in m is empty, Exchange calls m.Pack().
See Client.Exchange for more information on setting larger buffer sizes.
func NewMsg ¶ added in v0.1.5
NewMsg returns a new message with the question section sets to z (z is made fully qualified) and the type t. If the type isn't know nil is returned, the recursion desired bit is set.
func (*Msg) All ¶ added in v0.1.11
All() allows ranging over the RRs of all the sections in m. This includes the question, pseudo and stateful sections.
func (*Msg) Hijack ¶ added in v0.1.10
func (m *Msg) Hijack()
Hijack allows user hijacking the allocation in m.Data; this means that when the message is written through the default ResponseWriter its buffer is not returned the message pool. This is only applicable when the message was created by the default server.
func (*Msg) Read ¶
Read reads the data from m.Data into p. If m's Data buffer is empty Pack() is called.
func (*Msg) ReadFrom ¶
ReadFrom reads from r. When r is a *net.TCPConn, first 2 bytes of length are read, then m.Data is *resized* to this length and the data is read. Otherwise the data is read into m.Data. It is expected any deadlines are set if there is an underlying socket. No read timeouts are applied.
func (*Msg) String ¶
Convert a complete message to a string with dig-like output. String also looks at the [Msg.Options] and only prints up to that point, i.e. options set to MsgOptionUnpackHeader means String will only return the header.
func (*Msg) Write ¶
Write writes the buffer p to the m.Data. If m's Data buffer is empty Pack() is called.
func (*Msg) WriteTo ¶
WriteTo writes the message to w. W must be a ResponseWriter, when w contains a *net.TCPConn, the write is prefixed with an uint16 with the length of the buffer, otherwise the m.Data is written as-is. If w is a ResponseController a write timeout is applied.
If the message has not be hijacked, and m was create by the server, the Data buffer is returned to the server's pool and zeroed out in m.
type MsgAcceptAction ¶ added in v0.1.4
type MsgAcceptAction int
MsgAcceptAction represents the action to be taken.
const ( MsgAccept MsgAcceptAction = iota // Accept the message. MsgReject // Reject the message with a RcodeFormatError. MsgRejectNotImplemented // Reject the message with a RcodeNotImplemented. MsgIgnore // Ignore the message and send nothing back. )
Allowed returned values from a MsgAcceptFunc.
type MsgAcceptFunc ¶ added in v0.1.4
type MsgAcceptFunc func(m *Msg) MsgAcceptAction
MsgAcceptFunc is used early in the server code to accept or reject a message with RcodeFormatError. It returns a MsgAcceptAction to indicate what should happen with the message. Only the header of the message is unpacked when this function is called.
var DefaultMsgAcceptFunc MsgAcceptFunc = defaultMsgAcceptFunc
DefaultMsgAcceptFunc checks the request and will reject if:
- isn't a request (don't respond in that case)
- has an opcode that isn't recognized (also no response)
- has more than a single "RR" in the question section
type MsgHeader ¶
type MsgHeader struct { ID uint16 Response bool Opcode uint8 Authoritative bool Truncated bool RecursionDesired bool RecursionAvailable bool Zero bool AuthenticatedData bool CheckingDisabled bool Rcode uint16 // Rcode is the message response code, extended rcodes can be set here as well. // Extended DNS (version 0) option that can be set directly on the message. The package takes care of // putting the bits in the right places and creating an OPT RR if needed. UDPSize uint16 // UDPSize is the OPT's RR advertised UDP size. Version uint8 // Version is the EDNS version, always zero. Security bool // Security is the DNSSEC OK bit, see RFC 403{3,4,5}. CompactAnswers bool // Compact Answers OK, https://datatracker.ietf.org/doc/draft-ietf-dnsop-compact-denial-of-existence/. Delegation bool // Delegation is the DELEG OK bit, see https://datatracker.ietf.org/doc/draft-ietf-deleg/. }
MsgHeader is the header of a DNS message. This contains most header bits, except Rcode as that needs to be set via a function because of the extended Rcode that lives in the pseudo section.
type MsgOption ¶ added in v0.1.7
type MsgOption uint16
Option is an option on how to handle a message. Options can be combined, but that have to be "in order", if you only want to unpack the Question section you must also set unpack header: OptionUnpackHeader | OptionUnpackQuestion.
const ( MsgOptionUnpack MsgOption = 0 // Unpack the entire message, mostly defined to serve as documentation. MsgOptionUnpackHeader MsgOption = 1 << iota // Unpack only the header of the message. MsgOptionUnpackQuestion // Unpack up the question section of the message. MsgOptionUnpackAnswer // Unpack up to the answer section of the message. )
type N3U ¶
type N3U struct {
AlgCode []uint8
}
EDNS0_N3U implements the EDNS0 "NSEC3 Hash Understood" option. See RFC 6975.
This record must be put in the pseudo section.
type NAPTR ¶
type NAPTR struct { Hdr Header Order uint16 Preference uint16 Flags string Service string Regexp string Replacement string `dns:"domain-name"` }
NAPTR RR. See RFC 2915.
type NIMLOC ¶
NIMLOC RR. See http://ana-3.lcs.mit.edu/~jnc/nimrod/dns.txt.
type NINFO ¶
NINFO RR. See https://www.iana.org/assignments/dns-parameters/NINFO/ninfo-completed-template.
type NSEC ¶
type NSEC3 ¶
type NSEC3 struct { Hdr Header Hash uint8 Flags uint8 Iterations uint16 SaltLength uint8 Salt string `dns:"size-hex:SaltLength"` HashLength uint8 NextDomain string `dns:"size-base32:HashLength"` TypeBitMap []uint16 `dns:"nsec"` }
NSEC3 RR. See RFC 5155.
type NSEC3PARAM ¶
type NSEC3PARAM struct { Hdr Header Hash uint8 Flags uint8 Iterations uint16 SaltLength uint8 Salt string `dns:"size-hex:SaltLength"` }
NSEC3PARAM RR. See RFC 5155.
func (*NSEC3PARAM) Copy ¶ added in v0.1.10
func (rr *NSEC3PARAM) Copy() RR
func (*NSEC3PARAM) Header ¶
func (rr *NSEC3PARAM) Header() *Header
func (*NSEC3PARAM) Len ¶
func (rr *NSEC3PARAM) Len() int
func (*NSEC3PARAM) String ¶
func (rr *NSEC3PARAM) String() string
type NSID ¶
type NSID struct {
Nsid string `dns:"hex"`
}
NSID option is used to retrieve a nameserver identifier. When sending a request Nsid must be empty. The identifier is an opaque string encoded as hex.
This record must be put in the pseudo section.
type NXNAME ¶
type NXNAME struct {
Hdr Header
}
NXNAME is a meta record. See https://www.iana.org/go/draft-ietf-dnsop-compact-denial-of-existence-04 Reference: https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml
type OPENPGPKEY ¶
OPENPGPKEY RR. See RFC 7929.
func (*OPENPGPKEY) Copy ¶ added in v0.1.10
func (rr *OPENPGPKEY) Copy() RR
func (*OPENPGPKEY) Header ¶
func (rr *OPENPGPKEY) Header() *Header
func (*OPENPGPKEY) Len ¶
func (rr *OPENPGPKEY) Len() int
func (*OPENPGPKEY) String ¶
func (rr *OPENPGPKEY) String() string
type OPT ¶
OPT is the EDNS0 RR appended to messages to convey extra (meta) information. See RFC 6891. This record is not (directly) found in messages as the pack and unpack function take care of this. Any EDNS0 options are found in the [Pseudo] section of the message. There should be rarely the need to access specifics of this RR as you can just set things directly on Msg.
func (*OPT) CompactAnswers ¶
CompactAnswers returns the value of the CO (Compact Answers OK) bit. See [Msg.CompactAnswers].
func (*OPT) Delegation ¶ added in v0.1.7
Delegation returns the value of the delegation (DE OK) bit. See [Msg.Delegation].
func (*OPT) Rcode ¶
Rcode returns the EDNS extended Rcode field (the upper 8 bits of the TTL). See [Msg.Rcode].
func (*OPT) SetCompactAnswers ¶
SetCompactAnswers sets the CO (Compact Answers OK) bit. See [Msg.CompactAnswers].
func (*OPT) SetDelegation ¶ added in v0.1.7
SetDelegation sets the delegation (DE OK) bit. See [Msg.Delegation].
func (*OPT) SetRcode ¶
SetRcode sets the EDNS extended Rcode field. If the Rcode is not an extended Rcode, will reset the extended Rcode field to 0. See [Msg.Rcode].
func (*OPT) SetSecurity ¶
SetSecurity sets the security (DNSSEC OK) bit. See [Msg.Security].
func (*OPT) SetUDPSize ¶
SetUDPSize sets the UDP buffer size. See [Msg.UDPSize].
func (*OPT) SetVersion ¶
SetVersion sets the version of EDNS. This is usually zero. See [Msg.Version].
func (*OPT) SetZ ¶
SetZ sets the Z part of the OPT RR, note only the 15 least significant bits of z are used.
type PADDING ¶
type PADDING struct {
Padding string `dns:"octet"`
}
PADDING option is used to add padding to a request/response. The default value of padding SHOULD be 0x0 but other values MAY be used.
This record must be put in the pseudo section.
type PX ¶
type PX struct { Hdr Header Preference uint16 Map822 string `dns:"domain-name"` Mapx400 string `dns:"domain-name"` }
PX RR. See RFC 2163.
type Packer ¶
type Packer interface { // Pack packs the RR into msg at offset off. This method only needs to deals with the RR's rdata, as the // header is taken care off. For examples of such code look in zmsg.go. The returned int is the new offset in // msg when this RR is packed. New RRs do not have to deal with compression, as compressed rdata is not // allowed anymore. Pack(msg []byte, off int) (int, error) // Unpack unpacks the RR. Data is the byte slice that should contain the all the data for the RR. Unpack(data []byte) error }
The Packer interface defines the Pack and Unpack methods that are used to convert RRs to and from wire format.
type ParseError ¶
type ParseError struct {
// contains filtered or unexported fields
}
ParseError is a parsing error. It contains the parse error and the location in the io.Reader where the error occurred.
func (*ParseError) Error ¶
func (e *ParseError) Error() (s string)
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
type Pool ¶ added in v0.1.10
type Pool struct {
// contains filtered or unexported fields
}
Pool is the default pool used. The allocation size used is [server.UDPSize], if TCP allocation stay below this value too, it is also used for that.
type Pooler ¶ added in v0.1.10
type Pooler interface { // Get returns a (newly allocated) byte slice. Get() []byte // Put returns the byte slice. Put([]byte) }
Pooler is an interface that mimics a sync.Pool, but allows for different implementation.
type REPORTING ¶
type REPORTING struct {
AgentDomain string
}
REPORTING implements the EDNS0 Reporting Channel option (RFC 9567).
This record must be put in the pseudo section.
type RKEY ¶
type RKEY struct { Hdr Header Flags uint16 Protocol uint8 Algorithm uint8 PublicKey string `dns:"base64"` }
RKEY RR. See https://www.iana.org/assignments/dns-parameters/RKEY/rkey-completed-template.
type RP ¶
RP RR. See RFC 1138, Section 2.2.
type RR ¶
type RR interface { // Header returns the header of an resource record. The header contains everything up to the rdata. Header() *Header // String returns the text representation of the resource record. String() string // Len is the length of the RR when encoded in wire format, this is not a perfect metric and returning // a slightly too large value is OK. Len() int Copier }
An RR represents a DNS resource record.
func New ¶
New reads the RR contained in the string s. Only the first RR is returned. If s contains no records, New will return nil with no error. The origin for resolving relative domain names defaults to the DNS root (.).
The class defaults to IN and TTL defaults to 3600. The full zone file syntax like $TTL, $ORIGIN, etc. is supported.
Note that building an RR directly from it Go structure is far more efficient, i.e.
mx := &MX{Hdr: Header{Name: "miek.nl.", Class: ClassINET}, Preference: 10, Mx: "mx.miek.nl."}
instead of:
mx := New("miek.nl. 0 IN MX 10 mx.miek.nl.")
In this library EDNS0 option codes have a presentation format, which you see when you print them. This presentation format is also parsed back to EDNS0. In other words you can get an ENDS0 option code just from a string.
type RRSIG ¶
type RRSIG struct { Hdr Header TypeCovered uint16 Algorithm uint8 Labels uint8 OrigTTL uint32 Expiration uint32 Inception uint32 KeyTag uint16 SignerName string `dns:"domain-name"` Signature string `dns:"base64"` }
RRSIG RR. See RFC 4034 and RFC 3755.
func NewRRSIG ¶ added in v0.1.10
NewRRSIG returns a new RRSIG with many fields set. That can be used as a "stub" RRSIG before generating the signature. If incepexp, the inception and expiration dates, are not the given, now-300s and now+2w is used. origin (which must be in canonical form) is set as the signers name. The name of the RRSIG is set while signing.
func (*RRSIG) Sign ¶
Sign signs an RRset. The signature needs to be filled in with the values: Inception, Expiration, KeyTag, SignerName and Algorithm. See NewRRSIG, the rest is copied from the RRset. Sign returns a non-nill error when the signing went OK. There is no check if RRSet is a proper (RFC 2181) RRSet. Sign expect RRSIG to be initialized with NewRRSIG. Sign will skip RRSIG records, and return nil in that case.
func (*RRSIG) ValidPeriod ¶ added in v0.1.12
ValidPeriod uses RFC1982 serial arithmetic to calculate if a signature period is valid. If t is the zero time, the current time is taken other t is. Returns true if the signature is valid at the given time, otherwise returns false.
func (*RRSIG) Verify ¶
func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR, options *SignOption) error
Verify validates an RRSet with the signature and key. This is only the cryptographic test, the signature validity period must be checked separately. This function copies the rdata of some RRs (to lowercase domain names) for the validation to work. It also checks that the Zone Key bit (RFC 4034 2.1.1) is set on the DNSKEY and that the Protocol field is set to 3 (RFC 4034 2.1.2). Options can not be nil.
type RRset ¶
type RRset []RR
RRset is a just list of RRs. There is no guarantee that this is an official RRset as defined in RFC 7719, Section 4 "RRset", use [dnsutil.IsRRset] to make that determination. The type is defined here to implement the sort.Interface.
Typical use for sort a slice of RRs: sort.Sort(dns.RRset(....)).
type RT ¶
type RT struct { Hdr Header Preference uint16 Host string `dns:"domain-name"` // RFC 3597 prohibits compressing records not defined in RFC 1035. }
RT RR. See RFC 1183, Section 3.3.
type ResponseController ¶ added in v0.0.3
type ResponseController interface { // SetWriteDeadline sets the deadline for writing the response. SetWriteDeadline() error }
A ResponseController is used by an DNS handler to control the DNS response.
type ResponseWriter ¶
type ResponseWriter interface { // LocalAddr returns the net.Addr of the server. LocalAddr() net.Addr // RemoteAddr returns the net.Addr of the client that sent the current request. RemoteAddr() net.Addr // Conn returns the underlaying connection. Conn() net.Conn // ResponseWriter must also implement the io.Writer interface. Write([]byte) (int, error) // And the io.Closer interface. Close() error // Session returns the UDP oob session data to correctly route UDP packets. Session() *Session // Hijack lets the caller take over the TCP connection. For UDP this has no effect. The handler is then // responsible for the connection. Packets will still be read and given to the handler, MaxTCPQueries will // be ignored, and the client needs to call Close. Use Conn to check the connection's state. Hijack() }
A ResponseWriter interface is used by an DNS handler to construct an DNS response. Note that a response writer may be used concurrently with TCP pipelining, so be aware that writes need to be atomic. If a write is attmpted an the Data buffer in the message is empty the write methods will call m.Pack().
If a ResponseWriter also implements ResponseController a write deadline can be set, there is no default. The default ResponseWriter used a timeout 2s.
type SIG ¶
type SIG struct{ RRSIG }
SIG RR. See RFC 2535. The SIG RR is identical to RRSIG and nowadays only used for SIG(0), See RFC 2931.
type SIG0Option ¶ added in v0.1.10
type SIG0Option struct{}
SIG0ption are options that are given to the signer and verifier.
type SIG0Signer ¶ added in v0.1.10
type SIG0Signer interface { // Sign is passed the to-be-signed binary data extracted from the DNS message in p. It should return the signature or an error. Sign(s *SIG, p []byte, options SIG0Option) ([]byte, error) // Verify is passed the binary data with the TSIG octets and the TSIG RR. If the signature is valid it will return nil, otherwise an error. Verify(s *SIG, p []byte, options SIG0Option) error // Key returns the key to sign or verify with. Key() *KEY // Signer returns the crypto signer to sign or verify with. Signer() crypto.Signer }
SIG0Signer defines an interface that allows for pluggeable signers and verifiers.
type SMIMEA ¶
type SMIMEA struct { Hdr Header Usage uint8 Selector uint8 MatchingType uint8 Certificate string `dns:"hex"` }
SMIMEA RR. See RFC 8162.
type SOA ¶
type SOA struct { Hdr Header Ns string `dns:"cdomain-name"` Mbox string `dns:"cdomain-name"` Serial uint32 Refresh uint32 Retry uint32 Expire uint32 Minttl uint32 }
SOA RR. See RFC 1035.
type SPF ¶
SPF RR. See RFC 4408, Section 3.1.1.
type SRV ¶
type SRV struct { Hdr Header Priority uint16 Weight uint16 Port uint16 Target string `dns:"domain-name"` }
SRV RR. See RFC 2782.
type SUBNET ¶ added in v0.0.3
type SUBNET struct { Family uint16 // 1 for IP, 2 for IP6. SourceNetmask uint8 // 32 for IPV4, 128 for IPv6. SourceScope uint8 Address net.IP // Client IP address. }
SUBNET is the subnet option that is used to give the remote nameserver an idea of where the client is, see RFC 7871. It can give back a different answer depending on the location or network topology.
This record must be put in the pseudo section.
type SVCB ¶
type SVCB struct { Hdr Header Priority uint16 // If zero, Value must be empty or discarded by the user of this library. Target string `dns:"domain-name"` Value []svcb.Pair `dns:"pairs"` }
SVCB RR. See RFC 9460.
type ServeMux ¶
ServeMux is an DNS request multiplexer. It matches the zone name of each incoming request against a list of registered patterns add calls the handler for the pattern that most closely matches the zone name.
ServeMux is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if that is also registered), otherwise the child gets the query.
ServeMux is also safe for concurrent access from multiple goroutines.
The zero ServeMux is empty and ready for use.
func (*ServeMux) Handle ¶
Handle adds a handler to the ServeMux for pattern. An identical patterns silently overwrites earlier handlers.
func (*ServeMux) HandleFunc ¶
func (mux *ServeMux) HandleFunc(pattern string, handler func(context.Context, ResponseWriter, *Msg))
HandleFunc adds a handler function to the ServeMux for pattern.
func (*ServeMux) HandleRemove ¶
HandleRemove deregisters the handler specific for pattern from the ServeMux.
func (*ServeMux) ServeDNS ¶
func (mux *ServeMux) ServeDNS(ctx context.Context, w ResponseWriter, req *Msg)
ServeDNS dispatches the request to the handler whose pattern most closely matches the request message.
ServeDNS is DNSSEC aware, meaning that queries for the DS record are redirected to the parent zone (if that is also registered), otherwise the child gets the query.
If no handler is found a standard REFUSED message is returned. No checks are made on the request message.
type Server ¶
type Server struct { // Address to listen on, ":domain" if empty. Addr string // If "tcp" it will invoke a TCP listener, otherwise an UDP one. If TLSConfig is not nil and Net is "tcp" a TLS server is // started. Net string // TCP Listener to use, this is to aid in systemd's socket activation. Listener net.Listener // TLS connection configuration. TLSConfig *tls.Config // UDP "Listener" to use, this is to aid in systemd's socket activation. PacketConn net.PacketConn // Handler to invoke, dns.DefaultServeMux if nil. Handler Handler // Default buffer size to use to read incoming UDP messages. If not set it defaults to MinMsgSize (512 B). UDPSize int // The read timeout vaule for new connections, defaults to 2 * time.Second. ReadTimeout time.Duration // TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966). IdleTimeout time.Duration // Maximum number of TCP queries before we close the socket. Default is maxTCPQueries (128), unlimited if -1. // See [ResponseWriter.Hijack] on how a handler can bypass this. MaxTCPQueries int // Whether to set the SO_REUSEPORT socket option, allowing multiple listeners to be bound to a single address. // It is only supported on certain GOOSes and when using ListenAndServe. ReusePort bool // Whether to set the SO_REUSEADDR socket option, allowing multiple listeners to be bound to a single address. // Crucially this allows binding when an existing server is listening on `0.0.0.0` or `::`. // It is only supported on certain GOOSes and when using ListenAndServe. ReuseAddr bool // AcceptMsgFunc will check the incoming message and will reject it early in the process. Defaults to // [DefaultMsgAcceptFunc]. MsgAcceptFunc MsgAcceptFunc // MsgInvalidFunc is optional, it will be called if a message is received but cannot be parsed. MsgInvalidFunc InvalidMsgFunc // If NotifyStartedFunc is set it is called once the server has started listening. Both NotifyStartedFunc // and NotifyStartedFunc get a copy of the server's context. NotifyStartedFunc func(context.Context) // If NotifyShutdownFunc is set is is called when a server shutdown is initiated. The server will wait for // this function to return before stopping the server. NotifyShutdownFunc func(context.Context) // MsgPool is the default [Pooler] used for allocation. MsgPool Pooler // contains filtered or unexported fields }
A Server defines parameters for running an DNS server.
func NewServer ¶ added in v0.1.5
func NewServer() *Server
NewServer return a new server initialized with some defaults
func (*Server) ActivateAndServe ¶
ActivateAndServe starts a nameserver with the PacketConn or Listener configured in *Server. Its main use is to start a server from systemd.
func (*Server) ListenAndServe ¶
ListenAndServe starts a nameserver on the configured address in *Server. If TLS config is available a TLS listener will be started.
type Session ¶
type Session struct { Addr *net.UDPAddr // address from [net.ReadMsgUDP] // oob data also returned, this is needed to route to the correct interface. As these are small fixed // slices it makes sense to use a sync.Pool, to be able to override this behavior an OOB []byte }
Session is a small strucures that keep track of where the (potential) UDP message came from.
type SignOption ¶ added in v0.1.10
type SignOption struct {
Pooler // If Pooler is set is will be used for all memory allocations.
}
Signption are options that are given to the signer and verifier.
type TA ¶
type TA struct { Hdr Header KeyTag uint16 Algorithm uint8 DigestType uint8 Digest string `dns:"hex"` }
TA RR. See http://www.watson.org/~weiler/INI1999-19.pdf.
type TALINK ¶
type TALINK struct { Hdr Header PreviousName string `dns:"domain-name"` NextName string `dns:"domain-name"` }
TALINK RR. See https://www.iana.org/assignments/dns-parameters/TALINK/talink-completed-template.
type TCPKEEPALIVE ¶
type TCPKEEPALIVE struct { // Timeout is an idle timeout value for the TCP connection, specified in // units of 100 milliseconds, encoded in network byte order. If set to 0, // pack will return a nil slico. Timeout uint16 // Length is the option's length. // Deprecated: this field is deprecated and is always equal to 0. Length uint16 }
TCPKEEPALIVE is an EDNS0 option that instructs the server to keep the TCP connection alivo. See RFC 7828.
This record must be put in the pseudo section.
func (*TCPKEEPALIVE) Copy ¶ added in v0.1.10
func (rr *TCPKEEPALIVE) Copy() RR
func (*TCPKEEPALIVE) Header ¶
func (o *TCPKEEPALIVE) Header() *Header
func (*TCPKEEPALIVE) Len ¶
func (o *TCPKEEPALIVE) Len() int
func (*TCPKEEPALIVE) Pseudo ¶
func (o *TCPKEEPALIVE) Pseudo() bool
func (*TCPKEEPALIVE) String ¶
func (o *TCPKEEPALIVE) String() string
type TKEY ¶
type TKEY struct { Hdr Header Algorithm string `dns:"domain-name"` Inception uint32 Expiration uint32 Mode uint16 Error uint16 KeySize uint16 Key string `dns:"size-hex:KeySize"` OtherLen uint16 OtherData string `dns:"size-hex:OtherLen"` }
TKEY RR. See RFC 2930.
type TLSA ¶
type TLSA struct { Hdr Header Usage uint8 Selector uint8 MatchingType uint8 Certificate string `dns:"hex"` }
TLSA RR. See RFC 6698.
type TSIG ¶
type TSIG struct { Hdr Header Algorithm string `dns:"domain-name"` // Algorithm is encoded as a name, see HmacSHAXXX contstants. TimeSigned uint64 `dns:"uint48"` Fudge uint16 MACSize uint16 MAC string `dns:"size-hex:MACSize"` OrigID uint16 // OrigID is the original message ID, when creating a TSIG this should be set to the message ID. Error uint16 OtherLen uint16 OtherData string `dns:"size-hex:OtherLen"` }
TSIG is the RR the holds the transaction signature of a message. See RFC 2845 and RFC 4635. A TSIG RR when created must have the ClassANY, algorithm, timesigned, and optianal fudge factor. The owner name is the name of the key. I.e:
tsig := &dns.TSIG{Hdr: dns.Header{Name: "keyname.", Class: dns.ClassANY}, Algorithm: dns.HmacSHA512, TimeSigned: uint64(time.Now().Unix())}
See NewTSIG for an easier way of doing this.
type TSIGOption ¶
type TSIGOption struct { TimersOnly bool // Only use the timer information to create the TSIG. RequestMAC string // The RequestMAC is the previous MAC to use in this TSIG calculation. }
TSIGOption are options that are given to the signer and verifier.
type TSIGSigner ¶
type TSIGSigner interface { // Sign is passed the to-be-signed binary data extracted from the DNS message in p. It should return the signature or an error. Sign(t *TSIG, p []byte, options TSIGOption) ([]byte, error) // Verify is passed the binary data with the TSIG octets and the TSIG RR. If the signature is valid it will return nil, otherwise an error. Verify(t *TSIG, p []byte, options TSIGOption) error // Key returns the key to sign or verify with. Key() []byte }
TSIGigner defines an interface that allows for pluggeable signers and verifiers.
type Transfer ¶ added in v0.0.3
type Transfer struct { // If non zero, TSIG signing and verification is done on messages that have a TSIG record in the pseudo section. TSIGSigner // If non zero SIG0 signing and verification is done on messages that have a SIG0 record in the pseudo section. SIG0Signer }
Tranfer defines the signing parameters that are used during a zone transfer.
type Transport ¶
type Transport struct { // Dialer is used used to set local address and timeouts. Dialer *net.Dialer ReadTimeout time.Duration WriteTimeout time.Duration // TLSClientConfig specifies the TLS configuration to use with DialTLS, if TLSConfig is not nil it will // be used to dial. TLSConfig *tls.Config }
Transport is the transport used in Client, it deals with all the networking.
func NewDefaultTransport ¶ added in v0.0.4
func NewDefaultTransport() *Transport
NewDefaultTransport returns the default transport. That transport has Diailer timeout of 5s, keep alive of 3s and read and write timeout set to 2s.
type Typer ¶
type Typer interface {
Type() uint16
}
If an RR implements the Typer interface it will be used to return the type of RR in the RRToType function. This is only needed for RRs that are defined outside of this package.
type URI ¶
type URI struct { Hdr Header Priority uint16 Weight uint16 Target string `dns:"octet"` // Target is to be parsed as a sequence of character encoded octets according to RFC 3986. }
URI RR. See RFC 7553.
type X25 ¶
X25 RR. See RFC 1183, Section 3.1.
type ZONEVERSION ¶ added in v0.1.10
The ZONEVERSION option, see RFC 9660. Only a single type (0) has been allocated, if used the SOA serial is put in Version. Example on how to create a ZONEVERSION:
z := &ZONEVERSION{Labels: 8, Type: 0, Version: make([]byte, 4)} binary.BigEndian.PutUint32(z.Version, serial)
Or if you know your binary: &ZONEVERSION{Labels: 8, Type: 0, Version: {1,2,3,4}}
This record must be put in the pseudo section.
func (*ZONEVERSION) Copy ¶ added in v0.1.10
func (rr *ZONEVERSION) Copy() RR
func (*ZONEVERSION) Header ¶ added in v0.1.10
func (o *ZONEVERSION) Header() *Header
func (*ZONEVERSION) Len ¶ added in v0.1.10
func (o *ZONEVERSION) Len() int
func (*ZONEVERSION) Pseudo ¶ added in v0.1.10
func (o *ZONEVERSION) Pseudo() bool
func (*ZONEVERSION) String ¶ added in v0.1.10
func (o *ZONEVERSION) String() string
Strings outputs "ZONEVERSION 4 SOA-SERIAL 1002" as the presentation format.
type ZoneParser ¶
type ZoneParser struct {
// contains filtered or unexported fields
}
ZoneParser is a parser for an RFC 1035 style zone file.
Each parsed RR in the zone is returned sequentially from Next. An optional comment can be retrieved with Comment.
The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are all supported. Although $INCLUDE is disabled by default. Note that $GENERATE's range support up to a maximum of 65535 steps.
Basic usage pattern when reading from a string (z) containing the zone data:
zp := NewZoneParser(strings.NewReader(z), "", "") for rr, ok := zp.Next(); ok; rr, ok = zp.Next() { // Do something with rr } if err := zp.Err(); err != nil { // log.Println(err) }
Comments specified after an RR (and on the same line!) are returned too:
foo. IN A 10.0.0.1 ; this is a comment
The text "; this is comment" is returned from Comment. Comments inside the RR are returned concatenated along with the RR. Comments on a line by themselves are discarded.
Callers should not assume all returned data in a RR is syntactically correct, e.g. illegal base64 in RRSIGs will be returned as-is.
func NewZoneParser ¶
func NewZoneParser(r io.Reader, origin, file string) *ZoneParser
NewZoneParser returns an RFC 1035 style zone file parser that reads from r.
The string file is used in error reporting and to resolve relative $INCLUDE directives. The string origin is used as the initial origin, as if the file would start with an $ORIGIN directive.
func (*ZoneParser) Comment ¶
func (zp *ZoneParser) Comment() string
Comment returns an optional text comment that occurred alongside the RR.
func (*ZoneParser) Err ¶
func (zp *ZoneParser) Err() error
Err returns the first non-EOF error that was encountered by the ZoneParser.
func (*ZoneParser) Next ¶
func (zp *ZoneParser) Next() (RR, bool)
Next advances the parser to the next RR in the zone file and returns the (RR, true). It will return (nil, false) when the parsing stops, either by reaching the end of the input or an error. After Next returns (nil, false), the Err method will return any error that occurred during parsing.
func (*ZoneParser) SetDefaultTTL ¶
func (zp *ZoneParser) SetDefaultTTL(ttl uint32)
SetDefaultTTL sets the parsers default TTL to ttl.
func (*ZoneParser) SetIncludeAllowed ¶
func (zp *ZoneParser) SetIncludeAllowed(v bool)
SetIncludeAllowed controls whether $INCLUDE directives are allowed. $INCLUDE directives are not supported by default.
The $INCLUDE directive will open and read from a user controlled file on the system. Even if the file is not a valid zone file, the contents of the file may be revealed in error messages, such as:
/etc/passwd: dns: not a TTL: "root:x:0:0:root:/root:/bin/bash" at line: 1:31 /etc/shadow: dns: not a TTL: "root:$6$<redacted>::0:99999:7:::" at line: 1:125
func (*ZoneParser) SetIncludeFS ¶
func (zp *ZoneParser) SetIncludeFS(fsys fs.FS)
SetIncludeFS provides an fs.FS to use when looking for the target of $INCLUDE directives. ($INCLUDE must still be enabled separately by calling ZoneParser.SetIncludeAllowed.) If fsys is nil, os.Open will be used.
When fsys is an on-disk FS, the ability of $INCLUDE to reach files from outside its root directory depends upon the FS implementation. For instance, os.DirFS will refuse to open paths like "../../etc/passwd", however it will still follow links which may point anywhere on the system.
FS paths are slash-separated on all systems, even Windows. $INCLUDE paths containing other characters such as backslash and colon may be accepted as valid, but those characters will never be interpreted by an FS implementation as path element separators. See fs.ValidPath for more details.
Source Files
¶
- client.go
- dane.go
- dns.go
- dnssec.go
- dnssec_keygen.go
- dnssec_keyscan.go
- dnssec_privkey.go
- dnssec_signer.go
- doc.go
- dso_types.go
- edns_types.go
- errors.go
- generate.go
- headerpack.go
- listen_socket_options.go
- msg.go
- nsecpack.go
- opt.go
- optpack.go
- pool.go
- response.go
- reverse.go
- scan.go
- scan_ednsrr.go
- scan_rr.go
- serve_mux.go
- server.go
- sig0.go
- sig0_signer.go
- smimea.go
- sort.go
- string.go
- tlsa.go
- transfer.go
- transport.go
- tsig.go
- tsig_signer.go
- types.go
- udp.go
- udp_session.go
- udp_unix.go
- version.go
- zcompare.go
- zcopy.go
- zdnstest.go
- zdnsutil.go
- zdsolen.go
- zdsorr.go
- zednspack.go
- zednsrr.go
- zlen.go
- zmsg.go
- zpack.go
- zparse.go
- zrr.go
Directories
¶
Path | Synopsis |
---|---|
cmd
|
|
atomdns
command
|
|
atomdns/handlers/dbfile/zone
Package implement a DNS zone, held in a binary tree.
|
Package implement a DNS zone, held in a binary tree. |
atomdns/handlers/sign
Package sign implements a zone signer as a hander.
|
Package sign implements a zone signer as a hander. |
atomdns/internal/dnszone
Package implement a DNS zone, held in a binary tree.
|
Package implement a DNS zone, held in a binary tree. |
reflect
command
|
|
Package deleg deals with all the intricacies of the DELEG RR.
|
Package deleg deals with all the intricacies of the DELEG RR. |
Package dnsconf is used to get the DNS system configuration, typically stored in /etc/resolv.conf on unix systems.
|
Package dnsconf is used to get the DNS system configuration, typically stored in /etc/resolv.conf on unix systems. |
Package dnstest allows for easy testing of DNS clients against a test server.
|
Package dnstest allows for easy testing of DNS clients against a test server. |
Package dnsutil contains function that are useful in the context of working with the DNS.
|
Package dnsutil contains function that are useful in the context of working with the DNS. |
internal
|
|
bin
Package bin pretty prints a byte slice.
|
Package bin pretty prints a byte slice. |
generate
Package generate holds helper function for the code generation that we use.
|
Package generate holds helper function for the code generation that we use. |
jump
Package jump contain mini pack function that quick jumping through a binary message.
|
Package jump contain mini pack function that quick jumping through a binary message. |
Package svcb deals with all the intricacies of the SVCB/HTTPS RR.
|
Package svcb deals with all the intricacies of the SVCB/HTTPS RR. |