Compare commits

...

193 Commits

Author SHA1 Message Date
Spencer Comfort d8fbd0a755
Update actions & add go 1.19.x and 1.20.x to go workflow (#1414)
* Update actions

* Update go.yml

* Update go.yml

* Update go.yml
2023-02-02 19:52:49 +01:00
dnschecktool f8a185d39e
readme: add some very thankful users (#1415) 2023-01-22 16:52:13 +01:00
Kian-Meng Ang 0089167cae
Fix typos (#1413)
Found via `codespell -L ede,ans,te,crasher`
2023-01-14 08:19:09 +01:00
Ali Mosajjal fe20d5d323
Update edns.go (#1409) 2023-01-06 08:54:28 +01:00
Tom Thorogood 41a7730f43
Remove space between NextLabel func and doc comment (#1410)
This was mistakenly added in #1406.
2023-01-06 08:51:52 +01:00
Miek Gieben 4bd038eb76
Run gofmt -w -s *.go (#1408)
Signed-off-by: Miek Gieben <miek@miek.nl>

Signed-off-by: Miek Gieben <miek@miek.nl>
2023-01-05 07:53:57 +01:00
Sam Therapy caa3fe0583
edns: add missing dig options (#1389)
* edns: add missing dig options

Signed-off-by: Sam Therapy <sam@samtherapy.net>

* Apply suggested change

Signed-off-by: Sam Therapy <sam@samtherapy.net>

Signed-off-by: Sam Therapy <sam@samtherapy.net>
2023-01-05 07:53:34 +01:00
Miek Gieben 3b7e0b9bdd
NextLabel: document neg. offset will panic (#1406)
Fixes: #1404

Signed-off-by: Miek Gieben <miek@miek.nl>

Signed-off-by: Miek Gieben <miek@miek.nl>
2023-01-05 07:52:29 +01:00
Caleb Jasik 8c643eba82
Add slackhq/nebula to users (#1403)
This is currently used to provide DNS server capabilities to the nebula lighthouses.
2022-12-30 18:08:40 +01:00
Simon Elsbrock 16b12df562
fix: example in docs with invalid syntax (#1401)
fixes invalid syntax in one of the examples of the README
2022-11-12 12:38:48 +01:00
Mike Schinkel 4822b271aa
Restructure license so Github will recognize it. (#1397) 2022-11-12 12:37:31 +01:00
Miek Gieben b3dfea0715 Release 1.1.50 2022-06-21 10:38:26 +02:00
Miek Gieben 69924a02cf
Make tsigGenerateProvider/TsigVerifyProvider public (#1382)
Make it public as TsigGenerateWithProvider and update the docs a little.
And TsigVerifyWithProvider also - tweak those docs also a little.

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-06-21 10:37:36 +02:00
João Oliveirinha ff611cdc4b
Add back support for *net.UnixCon with seqpacket type (#1378)
This was broken by PR: https://github.com/miekg/dns/pull/1322
2022-06-08 14:03:24 +02:00
Miek Gieben eb4745b695
Add more detail to NSEC packing errors (#1374)
Add 'in the type bitmap' to make clear where in the RR the error occurs.
Also use 'NSEC(3)' - as this code is shared between NSEC and NSEC3, the
first error used NSECx.

Technically backwards incompatible, but checking strings in errors as
bad practice (although this lib lacks library types).

See #1373

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-05-27 11:01:25 +02:00
Shane Kerr 7413c83334
Disallow names that start with '.' in IsDomainName() (#1376)
* Disallow names that start with '.' in IsDomainName()

* Also update packDomain()
2022-05-26 15:06:08 +02:00
Miek Gieben 5521648610 Release 1.1.49 2022-05-10 18:51:11 +02:00
Shane Kerr bfcbf0fd23
Fix dohpath parsing/stringify (#1366)
* dohpath escaped in String(), and parsed such values

* Update the test for dohpath with escaping

* Fix cut & paste error with svcdohpath error
2022-05-10 18:40:32 +02:00
Shane Kerr feda877277
Properly parse alpn values in SVCB (#1363)
* Modify the SVCBAlpn to properly parse/print

* Remove debug

* Change SVCB test from reflect to loop

* Refactor SVCB code to reduce indentation

* When stringifying SVCBAlpn, use strings.Builder for whole process

* Update comment in svcb.go

Co-authored-by: Miek Gieben <miek@miek.nl>

* Describe why we use a specific size for the alpn buffer

Co-authored-by: Miek Gieben <miek@miek.nl>
2022-05-10 18:40:09 +02:00
Miek Gieben 0d2c95b99c
Upgrade our test Go version to 1.17 and 1.18 (#1369)
Signed-off-by: Miek Gieben <miek@miek.nl>
2022-04-15 10:16:27 +02:00
Miek Gieben c760d3c7f1
Fix examples by using net.JoinHostPort (#1368)
Small fix in the examples to properly work with v6 addresses.

Closes: #1365 #1367

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-04-15 10:13:08 +02:00
Ainar Garipov 656b7409ac
Add notes about SVCB draft changes to SVCB-related API (#1364)
* Add notes about SVCB draft changes to SVCB-related API

* Decrease number of warnings, rephrase
2022-04-14 20:36:11 +02:00
Ainar Garipov 08c2616301
Add SVCB dohpath key (#1359)
* Add SVCB dohpath key

The parameter is being added in [its own IETF draft][1] and also being used in
the [IETF draft about Descovery of Designated Resolvers][2].

Additionally, the mappings of the numeric key values to strings are exported,
under names consistent with the already existing exported mappings, to make it
easier for the clients of the module to validate and print SVCB keys.

Testing was done by sending SVCB queries for the "_dns.resolver.arpa" domain to
OpenDNS's 146.112.41.2 server.

[1]: https://datatracker.ietf.org/doc/html/draft-ietf-add-svcb-dns-02
[2]: https://datatracker.ietf.org/doc/html/draft-ietf-add-ddr-06.html

* Fix template length, docs; reverse some changes

* Remove incorrect validations; improve docs
2022-04-12 17:49:30 +02:00
Miek Gieben dedee46bd4
Fix ExamplePrivateHandle (#1354)
Signed-off-by: Miek Gieben <miek@miek.nl>
2022-04-02 19:16:31 +02:00
Miek Gieben 49c1b2e20f Release 1.1.48 2022-04-01 14:02:37 +02:00
Miek Gieben 045ac4ec6c
Fix RSAMD5 keytag calucation. (#1353)
Of course the wording was changed (for the better) in an errata:
https://www.rfc-editor.org/errata/eid193

We still followed the original RFC4034 text. Note I haven't given this
much thought, just changed the 2 into a 3 and ran the test.

Fixes: #1352

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-04-01 14:01:47 +02:00
Olivier Poitrey 57e2e627a6
Invalid NSEC/3 bitmap on non-zero buffer (#1338)
* Invalid NSEC/3 bitmap on non-zero buffer

If the PackBuffer is used to encode an NSEC/3 record, the bitmap is
xored with the content of the buffer instead of being zeroed first.

The algorithm has been changed so it is able zero bytes without
losing too much performance (around 2x slower).

* Add some comments + rename some vars to make algo clearer

* Revert to previous algo with window length compute+0 on new window

* Use typeBitMapLen to compute the bitmap length to zero
2022-04-01 14:01:05 +02:00
DesWurstes 2f577ca35d
Update SVCB (#1341)
* Rename ECH, bump draft number

* AliasForm new treatment

* alpn is no longer mandatory by default

* Document the non-empty value requirement

* new test cases

* more test cases

* Continue forbidding v4-map-v6 but not v4-embed-v6

https://github.com/miekg/dns/pull/1067#discussion_r495556735 and https://github.com/MikeBishop/dns-alt-svc/issues/361

* Update documentation

* revert rename ech

* Reword AliasMode with key=value pairs
2022-04-01 14:00:53 +02:00
Miek Gieben d70eb7b9e1 Release 1.1.47 2022-03-12 10:49:06 +01:00
Dimitris Mavrommatis d48e92a0e6
Handle packing of empty RDATA correctly for EDNS0_EXPIRE (Resolves #1292) (#1293)
* Change EDNS_EXPIRE field to support zero length option data (Resolves #1292)

As per [RFC7134](https://datatracker.ietf.org/doc/html/rfc7314#section-2) the Expire
Option in queries should be zero-length. In the current implementation the field is
uint32 which always instatiates 4bytes for that field when packing to wire format.
For that reason we change the field to []uint8 so it can support 0-length and 4-byte
length option data.

* addressed comments

* addressed comments

* make change backwards compatible

* add comment for Empty field
2022-03-12 09:42:42 +01:00
Miek Gieben 05140a3136
Add indentityHash for algos that don't need hashing (#1340)
This adds hash.go and creates a identityHash that is used for algorithms
that do their own hashing (ED25519) for instance.

This unifies the hash variable naming between dnssec and sig(0) signing
and removes the special casing that existed for ED25519.

This unifies the variable naming between sig(0) and dnssec signing and
verifying.

I didn't want to used crypto.RegisterHash as not to fiddle with the
global namespaces of hashes, so the value of '0' from AlgorithmsToHash
is handled specially in dnssec and sig(0) code.

Note that ED448 isn't implemented at all.

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-03-12 09:41:21 +01:00
Miek Gieben af1ebf55eb
Id check tests: stop using Exchange (#1343)
Using Exchange doesn't add anything, as it just wraps client.Exchange
with a default client.

Remove them and speed up the tests, goes from 3s to 1s (for the entire
test suite).

Signed-off-by: Miek Gieben <miek@miek.nl>
2022-03-02 13:52:49 +01:00
Miek Gieben 84af068d46 Release 1.1.46 2022-02-07 08:05:09 +01:00
Tom Thorogood 33e64002b6
Support TsigProvider for Server and Transfer (#1331)
Automatically submitted.
2022-02-05 00:23:49 +00:00
JeremyRand 51afb90ed3
Fix doc typo (#1328) 2022-01-17 08:58:28 +01:00
Tom Thorogood 0544c8bb11
Only treat a *net.UnixConn of unixgram as a packet conn (#1322)
* Refactor net.PacketConn checks into helper function

* Only treat a *net.UnixConn of unixgram as a packet conn

* Handle wrapped net.Conn types in isPacketConn

* Use Error instead of Fatal where appropriate in TestIsPacketConn
2021-12-28 13:52:38 +00:00
bshea3 af5144a5ca
Fix location of opt pseudosection and prevent empty additional section in dig-like output (#1320)
Automatically submitted.
2021-12-24 17:12:14 +00:00
Mark 32b1ed5f32
Add https://github.com/markdingo/autoreverse into list of users (#1319) 2021-12-24 08:09:22 +01:00
Miek Gieben 294c41a1d8 Release 1.1.45 2021-12-23 09:46:38 +01:00
Andrey Meshkov ba44371638
Fix edns keepalive (#1317)
* Fix un/packing of EDNS0 TCP keepalive extension

The current code is assuming the OPT code and length are part of the
data passed to the unpacker and that it should be appenedded during
packing while those fields are parsed by the caller.

This change fixes the parsing and make sure a request with a keepalive
won't fail.

* added tests for EDNS0_TCP_KEEPALIVE pack/unpack

* mark Length as deprecated

* removed named returns

* restored String

Co-authored-by: Olivier Poitrey <rs@rhapsodyk.net>
2021-12-23 09:45:02 +01:00
Miek Gieben f4af58267c Release 1.1.44 2021-12-21 09:32:39 +01:00
Chris O'Haver 3a58872b63
Do not sign BADKEY and BADSIG TSIG error responses (#1316)
* Per RFC 8945 5.3.2, responses with BADKEY and BADSIG errors must not be signed.

Signed-off-by: Chris O'Haver <cohaver@infoblox.com>

* refactor to remove else block

Signed-off-by: Chris O'Haver <cohaver@infoblox.com>

* skip signing only for BADKEY and BADSIG

Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2021-12-20 10:31:57 +01:00
Konstantine 3b8982ccc6
fixed documentation for DefaultMsgAcceptFunc (#1308) 2021-10-15 09:02:59 +02:00
Tom Sellers 7318b01e11
APL: adjust error handling and tests (#1302) 2021-10-12 13:06:29 +02:00
Alexandru Ionut Tripon 1630ffe2ca
Added support for ENUM Source-URI Extension (#1301) 2021-09-27 15:50:21 +02:00
Johan Knutzen 4e8fe099f4
add fleetdeck project (#1298)
Co-authored-by: Johan Knutzen <johan@fleetdeck.io>
2021-09-15 08:58:44 +02:00
Tom Thorogood df84acab71
Fix go generate missing required go.mod entry (#1290)
* Fix go generate missing required go.mod entry

There were no non-excluded files importing golang.org/x/tools so it's
require was missing from go.mod. This caused the go run commands
invoked by go generate to fail.

tools.go is currently the recommended way to force non-build
dependencies to be retained by the go mod commands. If that changes in
the future, we can update then. As nothing from the import is actually
used, it won't impact anyone's build at all (except requiring an extra
download by the go tool which is unavoidable).

Pulling in the @master version of golang.org/x/tools (which doesn't yet
have a stable release version) also updates a number of other
dependencies, but not quite to latest, so while I'm here just update
them all.

* Add explanatory comment and build tag to tools.go
2021-09-14 16:59:49 +02:00
Miek Gieben ab67aa6423
Fix race condition in ExchangeContext. (#1281)
Automatically submitted.
2021-08-04 16:16:52 +00:00
Manabu Sonoda af0c865ab3
fix Msg.Used TTL must be zero (#1280)
* fix Msg.Used RRset exists (value dependent -- with rdata) TTL must be zero

* Used(): change ttl using Header()
2021-07-18 09:24:05 +02:00
Aveline c23d8b3ce0
readme: add misaka.io & ping.sx (#1278) 2021-07-07 19:22:17 +02:00
Miek Gieben 996478ee91 Release 1.1.43 2021-06-22 14:03:06 +02:00
Miek Gieben bd70190c4d
Move makeDataOpt into edns.go (#1273)
Make it more obvious that these two lists (const, and case) need to be
in sync.

Also sort the list to match the const sorting.

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-06-22 14:00:25 +02:00
Malte Granderath 595ee5aa98
Adding TCPKeepAlive to makeDataOpt (#1272) 2021-06-22 09:41:30 +02:00
Miek Gieben ce48a4b9ef
small cleans from go report card (#1268)
I went through the list and cleaned things up here and there.

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-06-17 11:05:49 +02:00
joseph-stanton-ax 9922549621
Incorrect HIP RR public key length decode (#1262)
When decoding a HIP resource record, 'base64.StdEncoding.DecodedLen' can return a length larger than the length of the decoded public key. This change decodes the public key and retrieves the correct length. In our tests, the public key length was being set to 33, instead of 32. Below is our offending resource record:
'23b5993f649c0827.a.b.c.      3600    IN      HIP     5 200100100020001523B5993F649C0827 Cm6k4jhir9YYoKq9JDqD3Ob1hBfCuwbWam1igFPhkGg='
2021-05-13 09:33:12 +02:00
Miek Gieben d2b5d38d4f
Remove cifuzz (#1260)
The existing of the file signifies it needs to run, so now it errors
that there is nothing to run (everything is commented out).

Remove the entire file.

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-05-10 09:32:16 +02:00
Miek Gieben 9f8f2e3a3c Release 1.1.42 2021-05-07 09:31:52 +02:00
Miek Gieben 21ccaf84aa
Bump go.mod and rename reuseport files (#1259)
Go 1.11 was a long time ago, so rename the reuseport go files to
something more sane. Contemplated _unix, or _posix but that didn't
really cut it. Went with reuseport and no_reuseport.

Also bump go.mod to 1.14

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-05-07 09:30:50 +02:00
Miek Gieben cce7f43db4
OPT: add Z and SetZ methods (#1246)
* OPT: add Z and SetZ methods

Fixes: #1169

Signed-off-by: Miek Gieben <miek@miek.nl>

* code review feedback

Change the mask and use and not (&^)

Signed-off-by: Miek Gieben <miek@miek.nl>

* Code review changes

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-05-05 15:38:29 +02:00
Fredrik Lönnegren 2a9acc8d83
Check if DNSKEY Zone-Key bit is set on RRSIG Verify (#1258) 2021-05-05 15:38:06 +02:00
Andrey Meshkov c99ea652e3
Fix copy() in SVCBIPv4Hint and SVCBIPv6Hint (#1256)
* Fix copy() in SVCBIPv4Hint and SVCBIPv6Hint

The problem with the current implementation is that it is not a real deep copy,
it points to the same base arrays behind the slices. This was causing some
issues in real-life application.

* Address review comments
2021-04-23 09:09:34 +02:00
Miek Gieben 88913150f0
Remove HmacMD5 from the documention (#1255)
* Remove HmacMD5 from the documention

The aglo is deprecated.

Signed-off-by: Miek Gieben <miek@miek.nl>

* bump to sha256

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-04-19 12:10:52 +02:00
Daniel Tang 83b388a80c
Add support for extended DNS errors (RFC 8914). (#1253)
Automatically submitted.
2021-04-08 15:11:06 +00:00
Miek Gieben 40060b4a4b
zoneparser: document not checking syntax (#1245)
* zoneparser: document not checking syntax

Add a couple of lines that we're not syntax checking.

Closes: #948

Signed-off-by: Miek Gieben <miek@miek.nl>

* Update wording after review.

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-03-22 16:21:34 +01:00
Miek Gieben ad89e5bc70
stop doing any fuzzing (#1247)
The whole fuzzing pipeline is broken. Comment it out for now.
See #1186 and #1223

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-03-22 15:47:47 +01:00
Miek Gieben 797f1f2953 Release 1.1.41 2021-03-19 07:46:51 +01:00
cesarkuroiwa a614451ab3
Use ed25519 from Go standard lib (#1243)
* Use "crypto/ed25519"

* Remove unused dependencies

* Version bump

Co-authored-by: Cesar Kuroiwa <cesar@registro.br>
2021-03-16 15:37:10 +01:00
Tom Thorogood e5407eb800
Remove fuzz from .github/workflows/go.yml (#1238) 2021-03-04 16:40:54 +01:00
Tom Thorogood 40ce7c7df7
Bump go versions in .github/workflows/go.yml (#1237)
* Bump go versions in .github/workflows/go.yml

These are very out of date and it's causing persistent failures in the
fuzz CI step.

* Remove GOPATH=$GOROOT assignment

go1.16 shows a warning:
  "warning: GOPATH set to GOROOT (/opt/hostedtoolcache/go/1.16.0/x64) has no effect"
2021-03-04 07:32:55 +01:00
Tom Thorogood b694ab3d93
Update go.mod dependencies (#1236)
Automatically submitted.
2021-03-04 06:25:23 +00:00
Miek Gieben 4fdbc51bbd
Run a go fmt -w -s (#1235)
Noticed a non-gofmted `;` earlier, run gofmt -w -s on all files.

(mechanical change)

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-03-01 15:30:32 +01:00
Miek Gieben db96610e5e
loc: use float64 to get enough precision (#1234)
Fixes: #1232

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-03-01 15:19:31 +01:00
madestro 375601dc88
Implementation of zone digest (ZONEMD) (#1208)
* adding ZONEMD

* adding ZONEMD

* deleting extra cod

* updating constants

* updating mod

* updating release

* Moving ZONEMD Implementation to project structure

* re adding indirect tools import

* case-insensitive digest

* fixing if zone has rfc 3597 RRs

* remove .idea folder

* restore go.mod imports

* gofmt files

* pseudo rollback

* after go generate...

* parsing zonemd in rfc3597

* removing the check for a STRING as HAsh Algorithm in ZONEMD, RFC says only numbers go there

* adding ZONEMD constants

* Reverting changes in generate.go

un-gofmt ing generate.go file

* Reverting changes in generate.go

un-gofmt ing generate.go file

* remove ZoneMD reserved types

* remove zonemd RFC3597 branch in ZONEMD parser

* revert rfc3597 related modifications

* revert rfc3597 related modifications

* removing unintentional changes from go.sum and types.go

* add line break to go.sum

* removing spaces from types.go

* Use ZONEMD official RFC link as reference

* Add ZONEMD parsing test

* Update parse_test.go

Co-authored-by: Miek Gieben <miek@miek.nl>

Co-authored-by: Eduardo <eriveros@dcc.uchile.cl>
Co-authored-by: Eduardo <e.sdfbsadjhgskndwegit@xor.cl>
Co-authored-by: Eduardo <e.git@xor.cl>
Co-authored-by: Miek Gieben <miek@miek.nl>
2021-02-26 16:35:05 +01:00
Josh Soref 883641f4a9
Spelling (#1222)
* spelling: artifacts

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: encoding

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: exponent

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: ignoring

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: implemented

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: implements

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: next

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: numeric

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: previous

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: positions

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: presentation

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: resetting

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: stringifying

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: subsequent

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: validated

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

Co-authored-by: Miek Gieben <miek@miek.nl>
2021-02-25 17:08:05 +01:00
Shubhendra Singh Chauhan 2f14d104f3
improve code quality (#1228)
* Combine multiple `append`s into a single call

* Fix Yoda conditions

* Fix check for empty string

* revert "combine multiple `append`s"
2021-02-25 17:01:55 +01:00
Miek Gieben 9884b9f446 Release 1.1.40 2021-02-25 11:00:46 +01:00
R+ 2543d8bb2d
Close the UDPConn before returning if `setUDPSocketOptions` went wrong (#1227)
Detail: https://github.com/miekg/dns/issues/1226
2021-02-25 09:24:39 +01:00
Nikolay Nikolaev c08efdcc07
readme: adding Kuma.io (#1225)
Signed-off-by: Nikolay Nikolaev <nikolay.nikolaev@konghq.com>
2021-02-23 10:54:40 +01:00
Miek Gieben 4ec3e54a9e Release 1.1.39 2021-02-23 10:30:20 +01:00
Miek Gieben 4495f1939f
readme: add CAA and ZOMEMD RFCs (#1224)
Try to keep this list semi up to date.

Signed-off-by: Miek Gieben <miek@miek.nl>
2021-02-23 10:10:31 +01:00
Andrey Meshkov 67bd57debd
Send DNS query in one packet when using TCP/TLS (#1219)
* Send DNS query in one packet when using TCP/TLS

* fix review comments

* Removed net.Buffers

* Added unit-tests for writing messages over TCP in one go
2021-02-13 19:49:02 +01:00
unknowndev233 7d5e1ea350
README.md: Users list update: add v2fly/v2ray-core (#1220) 2021-02-10 07:42:07 +01:00
chantra ee8fef6743
Update Truncate doc with compress behaviour (#1217)
* Update Truncate doc with compress behaviour

This is a documentation update to highlight the behaviour of Truncate, which will reset dns.Compress to false when the message fits in the requested size without truncation, and make it the caller responsibility to set it back to true if they wish to compress, regardless of fitting, uncompressed, in the requested message size in the first place or not.
Fixes #1216

* address comments

* d/Note that/
* s/reset/set/
* s/caller/caller's/
* removed backticks

* regardless of size
2021-02-10 07:41:26 +01:00
Miek Gieben 35023fab5c Release 1.1.38 2021-02-01 09:20:37 +01:00
Tom Thorogood 2fd5af9f92
Validate Rdlength and off in UnpackRRWithHeader (#1215) 2021-02-01 09:15:50 +01:00
Tom Thorogood e6df8867af
Fix Rdlength related parsing bug in RFC3597 records (#1214)
* Set Rdlength in fromRFC3597

This was a bug found by oss-fuzz. My bad (#1211).

* Limit maximum length of Rdata in (*RFC3597).parse

RDATA must be a 16-bit unsigned integer.

* Validate Rdlength and off in UnpackRRWithHeader

* Revert "Validate Rdlength and off in UnpackRRWithHeader"

This reverts commit 2f6a8811b944b100af7605e53a6fb164944a6d65.

* Use hex.DecodedLen in (*RFC3597).fromRFC3597

While this isn't done elsewhere, it is clearer and more obvious.
2021-02-01 09:10:38 +01:00
Miek Gieben ba2d042a57 Release 1.1.37 2021-01-30 14:07:04 +01:00
Miek Gieben a1362108be Merge branch 'master' of github.com:miekg/dns 2021-01-30 14:06:35 +01:00
Miek Gieben a25c26b5ed Release 1.1.36 2021-01-30 14:06:14 +01:00
Tom Thorogood 13238cb6ad
Support parsing known RR types in RFC 3597 format (#1211)
* Support parsing known RR types in RFC 3597 format

This is the format used for "Unknown DNS Resource Records", but it's
also useful to support parsing known RR types in this way.

RFC 3597 says:

   An implementation MAY also choose to represent some RRs of known type
   using the above generic representations for the type, class and/or
   RDATA, which carries the benefit of making the resulting master file
   portable to servers where these types are unknown.  Using the generic
   representation for the RDATA of an RR of known type can also be
   useful in the case of an RR type where the text format varies
   depending on a version, protocol, or similar field (or several)
   embedded in the RDATA when such a field has a value for which no text
   format is known, e.g., a LOC RR [RFC1876] with a VERSION other than
   0.

   Even though an RR of known type represented in the \# format is
   effectively treated as an unknown type for the purpose of parsing the
   RDATA text representation, all further processing by the server MUST
   treat it as a known type and take into account any applicable type-
   specific rules regarding compression, canonicalization, etc.

* Correct mistakes in TestZoneParserAddressAAAA

This was spotted when writing TestParseKnownRRAsRFC3597.

* Eliminate canParseAsRR

This has the advantage that concrete types will now be returned for
parsed ANY, NULL, OPT and TSIG records.

* Expand TestDynamicUpdateParsing for RFC 3597

This ensures we're properly handling empty RDATA for RFC 3597 parsed
records.
2021-01-30 14:05:25 +01:00
Tom Thorogood f9dc403cff
Fix potentially truncated int casts in $GENERATE code (#1212)
These were flagged by GitHub CodeQL code scanning as potential
vulnerabilities or issues. Fixing them is easy and they are incorrect.

Adding tests is less easy because int is 64-bits on most systems,
including those we test on, so we can't consistently provoke a failure
here.
2021-01-30 10:07:06 +01:00
Matt Dainty 731b191cab
Add a link to https://github.com/bodgit/tsig (#1206) 2021-01-09 09:37:20 +01:00
Matt Dainty 59aea23afe
Add GSS-TSIG support (#1201)
Automatically submitted.
2021-01-07 14:28:20 +00:00
Janik at Cloudflare 23c4faca9d
Fix comment about SVCB values in AliasMode (#1202)
Automatically submitted.
2020-12-18 19:16:09 +00:00
Till! 428cef3187
Add a link for dnsbl_exporter (#1194)
Adding a shameless plug to my Prometheus exporter. ;) Thanks for sharing your code on here.
2020-11-06 18:31:18 +01:00
Miek Gieben 91eca25c30
Remove travis (#1193)
This also removed the codecov that was still done. We could potentially
re-add as an action, but I don't really miss it. Add testing for 1.14
and 1.15 (it's very fast now).

Fuzzing needs to stay on 1.14 due to brokeness of some kind.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-11-06 18:30:22 +01:00
Catena cyber 9732cfa6b8
Runs CIFuzz only when go files are modified (#1192)
and run it for 5 minutes instead of 10
2020-11-05 15:35:21 +01:00
Miek Gieben 1ba9487b18
make the client.Exchange doc work (#1190)
Remove the newline so the comment is picked up as documentation.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-26 14:10:31 +01:00
Miek Gieben 3b41a31342 Release 1.1.35 2020-10-25 09:22:05 +01:00
Tom Thorogood fa528cceb7
Fix PacketConnReader typo in DecorateReader docs (#1189) 2020-10-25 02:26:19 +10:30
Tom Thorogood 0e1c4e69dd
Support generic net.PacketConn's for the Server (#1174)
* Support generic net.PacketConn's for the Server

This commit adds support for listening on generic net.PacketConn's for
UDP DNS requests, previously *net.UDPConn was the only supported type.

In the event of a future v2 of this module, this should be streamlined.

* Eliminate wrapper functions around RunLocalXServerWithFinChan

* Eliminate RunLocalTCPServerWithTsig function

* Replace RunLocalTLSServer with a wrapper around RunLocalTCPServer

This reduces code duplication.

* Add net.PacketConn server tests

This provides coverage over nearly all of the newly added code (with
the unfortunate exception of (*response).RemoteAddr).

* Fix broken client_test.go tests

a433fbede4 was merged into master between this PR being opened and
being merged. This broke the CI tests in rather strange ways as the
code was being merged into master in a way that wasn't at all clear.
This commit fixes the two broken lines.
2020-10-25 02:23:01 +10:30
Tom Thorogood a3ad44419a
Fix XFR tests (#1188)
* Fix XFR tests

axfrTestingSuite returned the test function that was never actually
executed. These were broken from the beginning awkwardly, though the
test cases pass fine once fixed.

* Switch axfrTestingSuite argument order

*testing.T is customarily the first argument.
2020-10-24 13:58:44 +02:00
Tom Thorogood 93945c2844
Remove HMAC-MD5 support from TSIG (#1187) 2020-10-24 13:57:51 +02:00
Tom Thorogood db53c847ca
Remove RSAMD5 support from (*RRSIG).Verify (#1185)
AFAIK, the only way to get an RSAMD5 DNSKEY was to manually construct
one. This is ancient, just get rid of it.

The only remaining usage of md5 is in tsig.go. Hopefully that might be
removable as well.
2020-10-24 13:55:55 +02:00
Tom Thorogood be51022368
Remove the remnants of DSA support (#1184)
crypto/dsa is formally deprecated as of go1.16 and DSA support was
largely removed from this library in 9c315c51c3, but some remnants
remained.
2020-10-24 13:55:21 +02:00
Peter Wu 6d41f43022
svcb: documentation fixes (#1182)
`&dns.HTTPS{Hdr: ...}` fails due to `cannot use promoted field SVCB.Hdr
in struct literal of type dns.HTTPS`. Fix this, less readable
alternatives include using `dns.SVCB` directly, or `&dns.HTTPS{SVCB:
dns.SVCB{Hdr: ...}}`.

Fix the draft reference, draft-02 has not been published yet. Fix ECH,
its type has changed from base64 to a byte array.
2020-10-21 17:42:39 +02:00
Laurent Demailly 04c41addaf
add link to https://github.com/fortio/dnsping (#1181)
Thanks for the great library!

I couldn't quite figure out the sort order so I put my link at the end...
2020-10-21 08:14:38 +02:00
Miek Gieben 276b51d84b Release 1.1.34 2020-10-18 07:56:38 +02:00
Andrew Ayer a433fbede4
Ignore responses with unexpected IDs (#1155)
* Ignore replies with unexpected IDs

This fixes the following problem:

At time 0, we send a query with ID X from port P.

At time T, we time out the query due to lack of response, and then send
a different query with ID Y.  By coincidence, the new query is sent from
the same port number P (since port numbers are only 16 bits, this can happen
with non-negligible probability when making queries at a high rate).

At time T+epsilon, we receive a response to the original query.
Since the ID in this response is X, not Y, we would previously return
ErrId, preventing the second query from succeeding.

With this commit, we simply ignore the response with the mismatched ID
and return once we receive the response with the correct ID.

* Update test for bad ID

The new test sends two replies: the first one has a bad ID, which should
be ignored, and the second one has the correct ID.

* Add test to ensure query times out when server returns bad ID

* Avoid use of error string matching in test case

* Check for mismatched query IDs when using TCP

* Reduce timeout in TestClientSyncBadID
2020-10-18 07:55:24 +02:00
Miek Gieben 61a22d0ee6
svcb: doc updates (#1178)
The SVBC record didn't have a class, so add that and use struct literal
to put it all on 1 one. Use `s` for SVCB records, and `h` for HTTPS to
be more consistent.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-17 10:00:13 +02:00
Miek Gieben 95dddd3867
Make the 900 number lower in this test (#1176)
Original PR doesn't make clear why this is 900-now assuming we want to
cross the 14 bit length boundary.

Up to 900 creates a super large (>2^16) message. Not sure why that needs
testing.

Also remove the packs at lower sizes.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-16 11:55:29 +02:00
Miek Gieben 3b0ffe413f
tests: reduce timeouts and iterations (#1175)
This reduces the time it takes to run the test. Shorter timeouts on
clients to avoid awaiting for the detault timeouts.

It's also reduces the iterations in some test functions, this doesn't
seem to impact the tests indicating those numbers where random to begin
with.

Use shorter crypto keys, as we don't need to strength in tests.

Stop using Google Public DNS and other remotes in tests as well: it's
faster, keeps things local and avoids spilling info to Google.

This brings the test duration down from ~8s to ~2s on my machine, a 4x
reduction.

~~~
PASS
ok  	github.com/miekg/dns	2.046s

Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
PASS
ok  	github.com/miekg/dns	7.915s
~~~

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-16 09:10:36 +02:00
Miek Gieben 10e0aeedbe Release 1.1.33 2020-10-14 08:44:55 +02:00
Miek Gieben ef286f8f39
Update doc for Truncate (#1173)
Follow up after #1171, update the docs about TC and use the MinMsgSize
constant for 512 in the code.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-14 08:42:57 +02:00
Chris O'Haver 5579226123
dont unset TC on a message that is already truncated (#1171)
Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2020-10-14 07:18:59 +02:00
Tom Thorogood 08cf611c2b
Bump CI tested go versions (#1172)
This bumps Travis CI to the last two supported golang releases, as
documented in the readme: go1.14 and go1.15.

It also bumps the GitHub Code Action CI to go1.14 as it doesn't yet
supported go1.15 (see actions/setup-go#74).
2020-10-14 07:16:31 +02:00
Miek Gieben eaab7b7e85 Release 1.1.32 2020-10-11 14:29:24 +02:00
DesWurstes 0972db6834
Implement SVCB (#1067)
* Implement SVCB

* Fix serialization and deserialization of double quotes

* More effort (?)

4 months old commit

* DEBUG

* _

* Presentation format serialization/deserialization

* _

Remove generated

* Progress on presentation format parse & write

* _

* Finish parsing presentation format

* Regenerate

* Pack unpack

* Move to svcb.go

Scan_rr.go and types.go should be untouched now

* 🐛

Thanks ghedo

* Definitions

* TypeHTTPSSVC

* Generated

and isDuplicate

* Goodbye lenient functions

Now private key=value pairs have to be defined as structs too. They are no longer automatically named as KeyNNNNN

* Encode/decode

* Experimental svc

* Read method

* Implement some of the methods, use trick...

to  report where the error is while reading it. This should be applied to EDNS too. Todo: Find if case can only contain e := new(SVC_ALPN) and rest moved out

Also fix two compile errors

* Add SVC_LOCAL methods, reorder, remove alpn value, bugs

* Errors

* Alpn, make it build

* Correct testsuite

* Fully implement parser

Change from keeping a state variable to reading in one iteration until the key=value pair is fully consumed

* Simplify and document

EDNS should be simplified too

* Attempt to fix fuzzer

And Alpn bug

* A bug and change type values to match @ghedo's implementation

* IP bug

Also there are two ip duplicating patterns, one with copy, one with append. Maybe change it to be consistent.

* Check for strictly increasing keys as required

* Don't panic on invalid alpn

* Redundant check, don't modify original array

* Size calculation

* Fix the fuzzer, match the style

* 65535 is reserved too, don't delay errors

* Check keyNNN, check for aliasform having values

* IPvNHint is an array

* Fix ipvNHint

* Rename everything

* Unrecognized keys according to the updated specification

* Skip zero-length structs in generators. Fix CI

* Doc cleanup

* Off by one

* Add parse tests

* Check if private key doesn't collide with known key, invalid tests

* Disallow IPv4 as IPv6. More tests.

Related #1107

* Style fixes

* More consistency, more tests

* 🐛 Deep copy as in the documentation

	a := make([]net.IP, 1)
	a[0] = net.ParseIP("1.1.1.1").To4()
	b := append(make([]net.IP, 0, 1), a...)
	b[0] = net.ParseIP("3.1.1.1").To4()
	fmt.Println(a[0][0])

* Make tests readable

* Move valid parse tests to different file

* 🐛 One of previous commits not fully committed

* Test binary single value encoding/decoding and full encode/decode

* Add worst-case grows to builders, 🐛 Wrong visible character range, redundant tests

* Testing improvements

And don't convert to IPv4 twice

* Doc update only

* Document worst case allocations

and ipv6 can be at most of length 39, not 40

* Redundant IP copy, consistent IPv6 behavior, fix deep copy

* isDuplicate for SVCB

* Optimizations

* echoconfig

* Svc => SVCB

* Fix CI

* Regenerate after REBASE (2)

Rebased twice on 15th and 20th May

* Rename svc, use escapeByte.

* Fix parsing whitespaces between quotes, rename ECHOHOConfig

* resolve

Remove svcbFieldLen
Use reverseInt
Uppercase SVCB
Rename key_value
"invalid" => bad
Alpn comments
> 65535 check
Unneeded slices

* a little more

read => parse
IP array meaning
Force pushed because forgot to change read in svcb_test.go

* HTTPSSVC -> HTTPS

* Use new values

* mandatory code

https://github.com/MikeBishop/dns-alt-svc/pull/205

* Resolve comments

Rename svcb-pairs
Remove SVCB_PRIVATE ranges
Comment on SVCB_KEY65535
ParseError return l.token
rename svcbKeyToString and svcbStringToKey
privatize SVCBKeyToString, SVCBStringToKey

* Refactor 1

Rename sorted, originalPairs
Use append instead of copy
Use svcb_RESERVED instead of 65535, with it now being private
"type SVCBKey uint16"

* Refactor 2

svcbKeyToString as method
svcbStringToKey updated after key 0
🐛 mandatory has missing key
Rename str
idx < 0

* Refactor 3

Use l.token as z
var key, value string
Comment wrap
0:
Sentences with '.'
keyValue => kv

* Refactor 4

* Refactor 5

len() int

* Refactor 6

* Refactor 7

* Test remove parsing

* Error messages

* Rewrite two estimate comments

* parse shouldn't modify original array 🐛

* Remove two unneeded comments

* Address review comments

Push 2 because can't build fuzzer python
Push 3 to try again

* Simplify argument duplication as per tmthrgd's suggestion

And add the relevant test
Force push edit: Make sorting code fit into one line

* Rewrite ECHConfig and address the review

* Remove the optional tab

* Add To4() Check

* More cleanup and fix mandatory not sorting bug
2020-10-11 09:09:36 +02:00
Frank Olbricht cec9156531
Set UDPSize in connections created with client.Dial() (#1165) 2020-10-11 09:06:33 +02:00
Miek Gieben 68df4402de
readme: remove too generic users (#1164)
These domain either nxdomain/404 or just generic sites selling some
service.

Remove them from the readme.

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-10-05 09:13:52 +02:00
reuben honigwachs 7a5f1127f7
Update README.md (#1160)
Not sure whether router7 makes the cut for your impressive list, but it's worth a "go" I guess. Thanks.
2020-09-16 07:57:26 +02:00
Jacob Hoffman-Andrews efdec21496
Remove comment saying ExchangeContext is deprecated. (#1154) 2020-08-26 07:58:07 +02:00
Brian Shea 034f791cf8
answer queries with no matching handler with RcodeRefused (#1151)
* answer queries with no matching handler with RcodeRefused

* update documentation

* mark HandleFailed deprecated

* add handleRefused and use it to answer requests matching no handler

* silence noise maker

Co-authored-by: Brian <brian@pop-os.localdomain>
2020-08-20 08:41:45 +02:00
JINMEI Tatuya 9df839b2b4
make sure removing trailing zero octets in APL AFDPART (#1150)
* make sure removing trailing zero octets in APL AFDPART

* update code comment with a reference to RFC3123.
2020-08-17 19:51:22 +01:00
JINMEI Tatuya da812eed45
fix and enhance stringToCm to parse LOC RR optional fields (#1148)
Automatically submitted.
2020-08-17 07:08:03 +00:00
JINMEI Tatuya 81df27db17
validate LOC's lat/long field values not to be out of range (#1149)
Automatically submitted.
2020-08-17 07:07:46 +00:00
Disconnect3d 86044e4e05
Fixes a TODO to "error out on > MAX_UINT32" (#1147)
Automatically submitted.
2020-08-17 05:59:54 +00:00
Miek Gieben 34cecfe1b4 Release 1.1.31 2020-08-01 06:57:59 +02:00
JINMEI Tatuya de1def76d8
Add support for HMAC-SHA224 and HMAC-SHA384 TSIG algorithms (#1139) 2020-07-22 13:59:04 +09:30
JINMEI Tatuya f3da20bc00
fix TsigGenerate for non-0 TSIG error or non-empty other data (#1138)
Automatically submitted.
2020-07-21 15:55:03 +00:00
JINMEI Tatuya a7a0eafd7a
catch error from tsigBuffer, mainly to detect other data overflow (#1136)
* catch error from tsigBuffer, mainly to detect other data overflow

* hardcoded a constant string instead of a const var
2020-07-21 08:04:57 +02:00
JINMEI Tatuya 9093928550
make TsigVerify check time after signature per rfc2845bis (#1135)
Automatically submitted.
2020-07-18 06:06:18 +00:00
Eric Case 50b4756e47
Add domainr.com & zonedb.org to the Users list (#1134)
Thanks for making this great library, Miek!
2020-07-08 21:09:04 +02:00
Miek Gieben 54ab126a04
Create codeql-analysis.yml
Add codescanning - we're in the beta.

This is to try it out, this commit adds the default github comes up with
2020-07-08 09:23:39 +02:00
Miek Gieben f17e6c7171 Release 1.1.30 2020-07-06 22:17:46 +02:00
Richard Gibson 978b9a827a
Be consistent about domain name label character escaping (#1122)
* Improve sprintName tests

* Fix sprintName handling of escaped dots

* Make sprintName consistently drop dangling incomplete escapes

* Be consistent about domain name label character escaping

Fixes #1121

* Replace strings.IndexByte with faster special-purpose function
2020-07-06 10:07:56 +02:00
Michael Hudson-Doyle 064ba4b789
fix failing tests on 32 bit platforms (#1130)
* fix check for bad offset on 32 bit systems

* parse integers into int64 rather than platform dependent ints

Co-authored-by: Michael Hudson-Doyle <Michael Hudson-Doyle michael.hudson@ubuntu.com>
2020-07-02 09:54:07 +02:00
Richard Gibson 203ad2480b
Add test for forward compression pointer (#1123)
Automatically submitted.
2020-05-27 08:05:25 +00:00
DesWurstes 0ffcea3295
Generate copy() for derived types (#1118)
Automatically submitted.
2020-05-18 12:54:09 +00:00
Miek Gieben b7da9d95e0
Remove string(n) (#1117)
Automatically submitted.
2020-05-14 10:50:37 +00:00
Alex Fattouche b28dcc1849
Fix URI and CAA parsing on quotes and backslashes. (#1101) (#1104)
Automatically submitted.
2020-05-13 19:24:22 +00:00
DesWurstes 8f63c2d20c
Generate isDuplicate for derivatives (#1114) 2020-05-11 09:16:21 +02:00
DesWurstes b7703d0fa0
Cleanup EDNS (#1112) 2020-05-06 15:41:54 +02:00
yaakov kuperman 1fc9fa1db0
Adds function ExchangeWithConn (#1110)
* Implements ExchangeWithConn, a function that allows callers to pass in a connection instead of having the library create a new one for them.  Exchange now wraps around this, implementing the existing behavior by creating a new connection and passing it to ExchangeWithConn.  c.exchange has been updated to support this behavior as well.

* adding tab

* formatting problem

* adds test case for ExchangeWithConn
2020-05-04 10:22:21 +02:00
taciomcosta d128d10d17
refactor: remove ParseZone and parseZone (#1099) 2020-04-28 09:24:18 +02:00
Catena cyber 5bfe94bb6e
Efficient string concatenation (#1105)
Found by oss-fuzz
2020-04-28 09:21:06 +02:00
Manabu Sonoda 67373879ce
fix APL address length check. (#1095)
* fix APL address length check.

* add afdlen check, update check APL address bits

* revert error message

* revert error message
2020-04-10 21:20:01 +02:00
Catena cyber 2c9b7cfbaa
Continuous integration with GitHub workflow (#1091)
* Adds github workflow

* Add CIFuzz github workflow

* remove Gopkg.toml stuff
2020-04-09 08:50:30 +02:00
Adam Chalkley fd9c7eb788
RFCs allow multiple questions, but not in practice (#1097)
Paraphrase @miekg's response to emphasize that multiple
questions in the question section of a DNS message
is not supported in practice.

refs miekg/dns#1092

Co-authored-by: Adam Chalkley <atc0005@users.noreply.github.com>
2020-03-29 19:46:09 +02:00
Sijie Yang 923fc6bc72
Update README.md (#1096) 2020-03-26 17:24:37 +01:00
Miek Gieben f515aa579d Release 1.1.29 2020-03-18 11:22:29 +01:00
Jan Včelák 524a80c35d
CanonicalName function to return domain name in canonical form (#1073)
* add Canonical function to get name in canonical form

* replace strings.ToLower with Canonical

* rename Canonical to CanonicalName

* replace Fqdn with CanonicalName in ServeMux
2020-03-18 11:21:59 +01:00
Dominik Menke 438e446f5c
Ensure TSIG state is verified in TestServerRoundtripTsig (#1085)
Automatically submitted.
2020-03-11 14:18:07 +00:00
Miek Gieben 40ecd66164 Release 1.1.28 2020-03-11 10:25:26 +01:00
Manabu Sonoda 1d3a971542
Fix NSEC3PARAM SaltLength when parsing (#1088)
* fix parse nsec3param saltLength

* division inside into cast
2020-03-11 10:24:25 +01:00
Miek Gieben f0dca1ef05
Fix all cases of error halding (#1087)
Automatically submitted.
2020-03-10 06:42:28 +00:00
Pavel Rybintsev 418631f446
correct default values fields in LOC record (#1084)
* Fixed the default values of HorizPre and VertPre

According to RFC-1876 those fields should be:

"a pair of four-bit unsigned
integers, each ranging from zero to nine, with the most
significant four bits representing the base and the second
number representing the power of ten by which to multiply
the base.  This allows sizes from 0e0 (<1cm) to 9e9
(90,000km) to be expressed"

Current values for HorizPre and VertPre (165=0xA5 and 162=0xA2)
are incorrect because the first HEX digit is greater then 9

The default values should be:

HorizPre = 10000m = 10000 * 100 cm = 10^6 = 0x16
VertPre  = 10m    = 10 * 100 cm    = 10^3 = 0x13
Size     = 1m     = 1 * 100 cm     = 10^2 = 0x12

The value of Size was correct, but this PR changes it to HEX
representation to be more readable

* Informative comments

Made comments on LOC record default field values more informative

Co-Authored-By: Richard Gibson <richard.gibson@gmail.com>

Co-authored-by: Richard Gibson <richard.gibson@gmail.com>
2020-03-02 08:48:01 +00:00
Miek Gieben 9dcf47a409
Doc updates (#1075)
* Doc updates

Was reading https://pkg.go.dev/github.com/miekg/dns?tab=doc and spotted
some types and things to could be slightly better.

Make v unexported, as this version stuff should not be part of the
public API.

Signed-off-by: Miek Gieben <miek@miek.nl>

* fix test

Signed-off-by: Miek Gieben <miek@miek.nl>
2020-02-14 22:47:21 +01:00
Florian Lehner 7963800469
l is never used (#1071)
Signed-off-by: Lehner Florian <dev@der-flo.net>
2020-02-03 21:10:40 +01:00
Miek Gieben 6c0c4e6581 Release 1.1.27 2020-01-03 13:46:28 +01:00
Jan Včelák c9b62b4215 APL record support (#1058)
* APL record: add structure and code point

* APL record: add wire format support

* APL record: add presentation format support

* APL record: add isDuplicate implementation

* APL record: add copy implementation

* APL record: add len implementation

* APL record: run go generate

* APL record: fix condition checking for equality

* APL record: use switches to map family to address length

* APL record: check bounds of individual fields rather than whole header

* APL record: stylistic changes

* APL record: remove APLPrefix methods from public interface

* APL record: update README

* APL record: additional cleanup for code review

* APL record: change return type from pointer to struct

* APL record: refactor of pack and unpack to eliminate extra variables
2020-01-03 13:41:45 +01:00
Ask Bjørn Hansen e636c10380 Support the zero length EDNS0 EXPIRE option (#1065)
* Support the zero length EDNS0 EXPIRE option

* EDNS0 EXPIRE: Just reference the RFC, don't link to it

Co-Authored-By: Miek Gieben <miek@miek.nl>

Co-authored-by: Miek Gieben <miek@miek.nl>
2019-12-30 14:42:48 +01:00
Jan Včelák ba5b1f0bae code generation compatible with go modules (#1050)
* code generation compatible with go modules

* build: ensure go generate makes no changes
2019-12-30 12:25:57 +01:00
Miek Gieben eda228adcf Release 1.1.26 2019-12-20 14:31:18 +00:00
Miek Gieben 711e0fd90d
doc: fix xfr example. (#1062)
* doc: fix xfr example.

The currently example code has a data race, put in the proper code.

Fixes: #1061

Signed-off-by: Miek Gieben <miek@miek.nl>

* Feedback

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-12-19 13:11:22 +00:00
Miek Gieben bfd8601222
Doc fixes (#1060)
* Doc fixes

Polish the docs a bit; fix a link to miek.nl, remove edns0client subnet
draft link and point to the RFC. Some layout fixes and pull GOPATH from
the readme as we do go modules now.

Signed-off-by: Miek Gieben <miek@miek.nl>

* review comments

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-12-19 09:28:37 +00:00
Austin Oh b3cafcb268 Add missing EDNS0EXPIRE data unpack (#1054)
Automatically submitted.
2019-12-19 07:52:02 +00:00
Miek Gieben a72e5ceb18
Put added license bit at the bottom (#1056)
This license file is not being recognized by Github, nor by the new
google golang thingy recently launched. Don't remove those lines just
yet, but put them at the bottom

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-12-18 06:58:51 +00:00
Miek Gieben bd4ba36771 Add ; before printing TSIG (#1051)
Automatically submitted.
2019-12-17 15:18:05 +00:00
Miek Gieben aae7df65e6 Release 1.1.25 2019-12-11 07:31:45 +00:00
Jacob Hoffman-Andrews 8ebf2e419d Use crypto/rand for random id generation. (#1044)
* Use crypto/rand for random id generation.

Fixes #1043 and #1037

* Panic on rare crypto/rand error.

* Fixes in response to review.
2019-12-11 07:31:09 +00:00
Miek Gieben 6d0449f981
Add CODEOWNERS (#1042)
git shows:

 git shortlog -sne | head
  3311	Miek Gieben <miek@miek.nl>
   157	Tom Thorogood <me+github@tomthorogood.co.uk>
    39	Alex Sergeyev <asergeyev@dyn.com>
    37	Andrew Tunnell-Jones <andrew@tj.id.au>
    34	Filippo Valsorda <filippo@cloudflare.com>
    21	Rafael Dantas Justo <rafael@registro.br>
    19	Michael Haro <mharo@google.com>
    14	Alex Sergeyev <abc@alexsergeyev.com>
    13	chantra <chantra@users.noreply.github.com>
    11	Alex Ciuba <alexciuba@gmail.com>

I took the top 2, but happy to extend this obvs.

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-12-09 11:50:19 +00:00
Miek Gieben 0788ed5f4e Release 1.1.24 2019-12-06 21:24:08 +00:00
Miek Gieben 730ff1f016
Revert "Export EDNS0 interface (#1041)" (#1046)
This reverts commit a98e771ba5.

This is breaking people
2019-12-06 21:23:18 +00:00
Miek Gieben 78ecb5db60 Release 1.1.23 2019-12-06 15:22:00 +00:00
Omer Anson a98e771ba5 Export EDNS0 interface (#1041)
Replace all the private methods in the EDNS0 with public methods.
Additionally, as suggested in issue #857, made Pack receive a
pre-allocated byte array, introduce a Len method, and have Pack
and Unpack return the number of octets written and read (respectively)
if there was no error.

Closes #857
2019-12-06 10:56:57 +00:00
Julian Picht 22cda6dc4f Speed up NextLabel and PrevLabel (#1039)
* change NextLabel and PrevLabel to be faster

This reduces readability, but they are in the hot path of coredns.

* @redyeti pointed out, that my implementation disregarded triple backslashes

* add synthetic benchmark-tests for PrevLabel and NextLabel

* rename ii -> j

* invert compare

* PrevLabel: add empty string check + test case

* NextLabel: fix and add testcase for NextLabel("", offset>0)
2019-12-04 07:25:08 +00:00
chantra 9b7437f11d [zone parser] disallow nested $GENERATE directive (#1033)
While the range number of GENERATE is now limited, one can pass
a line with 2 $GENERATE directive that will exponentially increase the
time spent generating RRs.
Limit to only one per line.
Fixes #1020
2019-10-23 10:41:32 +01:00
Miek Gieben 4d4363a5dc
build: reduce testing output (#1031)
Use a better name in the fuzzing test to not spam the travis output,
move to Go 1.13.x in travis.yaml

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-10-20 07:12:43 +01:00
Andrew Tunnell-Jones 4334efe802 Update EDNS0_UL to draft-sekar-dns-ul-02 (#1028) 2019-10-14 09:29:56 +01:00
chantra 40eab7a196 [fuzzer] Avoid fuzzing parser with line that contains "$INCLUDE" (#1026)
Fixes #1025

```
GO111MODULE=off make -f Makefile.fuzz build
go-fuzz -bin=dns-fuzz.zip -workdir=fuzz -func Fuzz
GO111MODULE=off make -f Makefile.fuzz build-rr
go-fuzz -bin=dns-fuzz.zip -workdir=fuzz -func FuzzNewRR
```
2019-10-10 07:12:53 +01:00
Miek Gieben 997f079b75
Run gofmt (#1024)
Periodic go-fmt-ing.

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-10-07 10:33:11 +01:00
Florian Lehner 58a17b97a1 simplify loop (#1023)
Signed-off-by: Lehner Florian <dev@der-flo.net>
2019-10-05 14:24:46 +01:00
Miek Gieben 1e224ff5de Release 1.1.22 2019-10-04 10:33:17 +01:00
Miek Gieben 1cd342c79a
Revert "labels: eliminate most allocations and improve perf by 15-65% (#1007)" (#1022)
This reverts commit ab6ac402ba.

This break CoreDNS tests and probably a lot of other apps as well.
Reverted
2019-10-04 10:26:59 +01:00
Miek Gieben 041b4bc010 Release 1.1.21 2019-10-04 07:36:49 +01:00
Miek Gieben 76b57d0384
Limit $GENERATE range to 65535 steps (#1020)
* Limit $GENERATE range to 65535 steps

Having these checks means all test in TestCrasherString() are not
reached because we bail out earlier - removed that test all together.

Fixes #1019

Signed-off-by: Miek Gieben <miek@miek.nl>

* bring back testcase

Signed-off-by: Miek Gieben <miek@miek.nl>

* bring back crash test

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-10-03 20:01:28 +01:00
chantra 557870346a [scan] fix crashers when parsing comment (#1018)
* [scan] fix crashers when parsing comment

When dealing with comments the parsers was potentially incrementing comi
variable twice. During the second access to com[], comi was possibly
longer than maxTok, causing an out of bound error:
panic: runtime error: index out of range [2048] with length 2048

* * Keep only 1 crasher test string.
* move tests from scan_test.go to fuzz_test.go
2019-10-03 19:09:39 +01:00
Miek Gieben 046ae4ead6 Release 1.1.20 2019-10-03 10:08:22 +01:00
chantra 8ebfd8abbb [fuzz] Fix crashes when parsing GENERATE (#1016)
* [fuzz] Fix crashes when parsing GENERATE

Running the fuzzer on NewRR, some crashes came up that could be
prevented by checking that the token after the range is a Blank.
This diff checks that and return an error when the blank is not found.

* * s/Expect blank /garbage /
* get rid of if/else
2019-10-03 07:37:56 +01:00
Miek Gieben 93f749db12
Revert "pool the transient maps used for Msg Pack, Truncate and Len (#1006)" (#1017)
This reverts #1006, see discussion on the PR. Def. worth exploring this
furhter and pushing a more correct approach.

This reverts commit 9578caeab0.
2019-10-03 07:36:27 +01:00
Miek Gieben 1208fbdde0 Release 1.1.19 2019-09-27 18:04:44 +01:00
Miek Gieben bb79ca102d
Update deps (#1013)
Signed-off-by: Miek Gieben <miek@miek.nl>
2019-09-25 15:51:31 +01:00
80 changed files with 6110 additions and 1673 deletions

32
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@ -0,0 +1,32 @@
name: "Code scanning - action"
on:
push:
branches: [master, ]
pull_request:
branches: [master]
schedule:
- cron: '0 23 * * 5'
jobs:
CodeQL-Build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
fetch-depth: 2
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

25
.github/workflows/go.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Go
on: [push, pull_request]
jobs:
build:
name: Build and Test
runs-on: ubuntu-latest
strategy:
matrix:
go: [ 1.19.x, 1.20.x ]
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go }}
- name: Check out code
uses: actions/checkout@v3
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...

View File

@ -1,16 +0,0 @@
language: go
sudo: false
go:
- 1.11.x
- 1.12.x
- tip
env:
- GO111MODULE=on
script:
- go test -race -v -bench=. -coverprofile=coverage.txt -covermode=atomic ./...
after_success:
- bash <(curl -s https://codecov.io/bash)

1
CODEOWNERS Normal file
View File

@ -0,0 +1 @@
* @miekg @tmthrgd

49
LICENSE
View File

@ -1,32 +1,29 @@
Extensions of the original work are copyright (c) 2011 Miek Gieben
BSD 3-Clause License
As this is fork of the official Go code the same license applies:
Copyright (c) 2009 The Go Authors. All rights reserved.
Copyright (c) 2009, The Go Authors. Extensions copyright (c) 2011, Miek Gieben.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,7 +1,7 @@
# Makefile for releasing.
#
# The release is controlled from version.go. The version found there is
# used to tag the git repo, we're not building any artifects so there is nothing
# used to tag the git repo, we're not building any artifacts so there is nothing
# to upload to github.
#
# * Up the version in version.go

View File

@ -26,8 +26,8 @@ avoiding breaking changes wherever reasonable. We support the last two versions
A not-so-up-to-date-list-that-may-be-actually-current:
* https://github.com/coredns/coredns
* https://cloudflare.com
* https://github.com/abh/geodns
* https://github.com/baidu/bfe
* http://www.statdns.com/
* http://www.dnsinspect.com/
* https://github.com/chuangbo/jianbing-dictionary-dns
@ -41,11 +41,9 @@ A not-so-up-to-date-list-that-may-be-actually-current:
* https://github.com/StalkR/dns-reverse-proxy
* https://github.com/tianon/rawdns
* https://mesosphere.github.io/mesos-dns/
* https://pulse.turbobytes.com/
* https://github.com/fcambus/statzone
* https://github.com/benschw/dns-clb-go
* https://github.com/corny/dnscheck for <http://public-dns.info/>
* https://namesmith.io
* https://github.com/miekg/unbound
* https://github.com/miekg/exdns
* https://dnslookup.org
@ -54,22 +52,35 @@ A not-so-up-to-date-list-that-may-be-actually-current:
* https://github.com/mehrdadrad/mylg
* https://github.com/bamarni/dockness
* https://github.com/fffaraz/microdns
* http://kelda.io
* https://github.com/ipdcode/hades <https://jd.com>
* https://github.com/StackExchange/dnscontrol/
* https://www.dnsperf.com/
* https://dnssectest.net/
* https://dns.apebits.com
* https://github.com/oif/apex
* https://github.com/jedisct1/dnscrypt-proxy
* https://github.com/jedisct1/rpdns
* https://github.com/xor-gate/sshfp
* https://github.com/rs/dnstrace
* https://blitiri.com.ar/p/dnss ([github mirror](https://github.com/albertito/dnss))
* https://github.com/semihalev/sdns
* https://render.com
* https://github.com/peterzen/goresolver
* https://github.com/folbricht/routedns
* https://domainr.com/
* https://zonedb.org/
* https://router7.org/
* https://github.com/fortio/dnsping
* https://github.com/Luzilla/dnsbl_exporter
* https://github.com/bodgit/tsig
* https://github.com/v2fly/v2ray-core (test only)
* https://kuma.io/
* https://www.misaka.io/services/dns
* https://ping.sx/dig
* https://fleetdeck.io/
* https://github.com/markdingo/autoreverse
* https://github.com/slackhq/nebula
* https://github.com/dnschecktool/dow-proxy
* https://dnscheck.tools/
Send pull request if you want to be listed here.
@ -94,8 +105,8 @@ DNS Authors 2012-
# Building
Building is done with the `go` tool. If you have setup your GOPATH correctly, the following should
work:
This library uses Go modules and uses semantic versioning. Building is done with the `go` tool, so
the following should work:
go get github.com/miekg/dns
go build github.com/miekg/dns
@ -127,6 +138,7 @@ Example programs can be found in the `github.com/miekg/exdns` repository.
* 2915 - NAPTR record
* 2929 - DNS IANA Considerations
* 3110 - RSASHA1 DNS keys
* 3123 - APL record
* 3225 - DO bit (DNSSEC OK)
* 340{1,2,3} - NAPTR record
* 3445 - Limiting the scope of (DNS)KEY
@ -165,6 +177,9 @@ Example programs can be found in the `github.com/miekg/exdns` repository.
* 7873 - Domain Name System (DNS) Cookies
* 8080 - EdDSA for DNSSEC
* 8499 - DNS Terminology
* 8659 - DNS Certification Authority Authorization (CAA) Resource Record
* 8914 - Extended DNS Errors
* 8976 - Message Digest for DNS Zones (ZONEMD RR)
## Loosely Based Upon

View File

@ -6,22 +6,29 @@ type MsgAcceptFunc func(dh Header) MsgAcceptAction
// DefaultMsgAcceptFunc checks the request and will reject if:
//
// * isn't a request (don't respond in that case).
// * isn't a request (don't respond in that case)
//
// * opcode isn't OpcodeQuery or OpcodeNotify
//
// * Zero bit isn't zero
// * has more than 1 question in the question section
//
// * does not have exactly 1 question in the question section
//
// * has more than 1 RR in the Answer section
//
// * has more than 0 RRs in the Authority section
//
// * has more than 2 RRs in the Additional section
var DefaultMsgAcceptFunc MsgAcceptFunc = defaultMsgAcceptFunc
// MsgAcceptAction represents the action to be taken.
type MsgAcceptAction int
// Allowed returned values from a MsgAcceptFunc.
const (
MsgAccept MsgAcceptAction = iota // Accept the message
MsgReject // Reject the message with a RcodeFormatError
MsgIgnore // Ignore the error and send nothing back.
MsgAccept MsgAcceptAction = iota // Accept the message
MsgReject // Reject the message with a RcodeFormatError
MsgIgnore // Ignore the error and send nothing back.
MsgRejectNotImplemented // Reject the message with a RcodeNotImplemented
)

View File

@ -6,7 +6,7 @@ import (
func TestAcceptNotify(t *testing.T) {
HandleFunc("example.org.", handleNotify)
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}

174
client.go
View File

@ -18,14 +18,35 @@ const (
tcpIdleTimeout time.Duration = 8 * time.Second
)
func isPacketConn(c net.Conn) bool {
if _, ok := c.(net.PacketConn); !ok {
return false
}
if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
return ua.Net == "unixgram" || ua.Net == "unixpacket"
}
return true
}
// A Conn represents a connection to a DNS server.
type Conn struct {
net.Conn // a net.Conn holding the connection
UDPSize uint16 // minimum receive buffer for UDP messages
TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
tsigRequestMAC string
}
func (co *Conn) tsigProvider() TsigProvider {
if co.TsigProvider != nil {
return co.TsigProvider
}
// tsigSecretProvider will return ErrSecret if co.TsigSecret is nil.
return tsigSecretProvider(co.TsigSecret)
}
// A Client defines parameters for a DNS client.
type Client struct {
Net string // if "tcp" or "tcp-tls" (DNS over TLS) a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
@ -34,12 +55,13 @@ type Client struct {
Dialer *net.Dialer // a net.Dialer used to set local address, timeouts and more
// Timeout is a cumulative timeout for dial, write and read, defaults to 0 (disabled) - overrides DialTimeout, ReadTimeout,
// WriteTimeout when non-zero. Can be overridden with net.Dialer.Timeout (see Client.ExchangeWithDialer and
// Client.Dialer) or context.Context.Deadline (see the deprecated ExchangeContext)
// Client.Dialer) or context.Context.Deadline (see ExchangeContext)
Timeout time.Duration
DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds, or net.Dialer.Timeout if expiring earlier - overridden by Timeout when that value is non-zero
ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds - overridden by Timeout when that value is non-zero
TsigSecret map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
group singleflight
}
@ -80,6 +102,12 @@ func (c *Client) writeTimeout() time.Duration {
// Dial connects to the address on the named network.
func (c *Client) Dial(address string) (conn *Conn, err error) {
return c.DialContext(context.Background(), address)
}
// DialContext connects to the address on the named network, with a context.Context.
// For TLS over TCP (DoT) the context isn't used yet. This will be enabled when Go 1.18 is released.
func (c *Client) DialContext(ctx context.Context, address string) (conn *Conn, err error) {
// create a new dialer with the appropriate timeout
var d net.Dialer
if c.Dialer == nil {
@ -99,14 +127,22 @@ func (c *Client) Dial(address string) (conn *Conn, err error) {
if useTLS {
network = strings.TrimSuffix(network, "-tls")
// TODO(miekg): Enable after Go 1.18 is released, to be able to support two prev. releases.
/*
tlsDialer := tls.Dialer{
NetDialer: &d,
Config: c.TLSConfig,
}
conn.Conn, err = tlsDialer.DialContext(ctx, network, address)
*/
conn.Conn, err = tls.DialWithDialer(&d, network, address, c.TLSConfig)
} else {
conn.Conn, err = d.Dial(network, address)
conn.Conn, err = d.DialContext(ctx, network, address)
}
if err != nil {
return nil, err
}
conn.UDPSize = c.UDPSize
return conn, nil
}
@ -125,14 +161,46 @@ func (c *Client) Dial(address string) (conn *Conn, err error) {
// To specify a local address or a timeout, the caller has to set the `Client.Dialer`
// attribute appropriately
func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, err error) {
co, err := c.Dial(address)
if err != nil {
return nil, 0, err
}
defer co.Close()
return c.ExchangeWithConn(m, co)
}
// ExchangeWithConn has the same behavior as Exchange, just with a predetermined connection
// that will be used instead of creating a new one.
// Usage pattern with a *dns.Client:
//
// c := new(dns.Client)
// // connection management logic goes here
//
// conn := c.Dial(address)
// in, rtt, err := c.ExchangeWithConn(message, conn)
//
// This allows users of the library to implement their own connection management,
// as opposed to Exchange, which will always use new connections and incur the added overhead
// that entails when using "tcp" and especially "tcp-tls" clients.
//
// When the singleflight is set for this client the context is _not_ forwarded to the (shared) exchange, to
// prevent one cancellation from canceling all outstanding requests.
func (c *Client) ExchangeWithConn(m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
return c.exchangeWithConnContext(context.Background(), m, conn)
}
func (c *Client) exchangeWithConnContext(ctx context.Context, m *Msg, conn *Conn) (r *Msg, rtt time.Duration, err error) {
if !c.SingleInflight {
return c.exchange(m, address)
return c.exchangeContext(ctx, m, conn)
}
q := m.Question[0]
key := fmt.Sprintf("%s:%d:%d", q.Name, q.Qtype, q.Qclass)
r, rtt, err, shared := c.group.Do(key, func() (*Msg, time.Duration, error) {
return c.exchange(m, address)
// When we're doing singleflight we don't want one context cancellation, cancel _all_ outstanding queries.
// Hence we ignore the context and use Background().
return c.exchangeContext(context.Background(), m, conn)
})
if r != nil && shared {
r = r.Copy()
@ -141,16 +209,7 @@ func (c *Client) Exchange(m *Msg, address string) (r *Msg, rtt time.Duration, er
return r, rtt, err
}
func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
var co *Conn
co, err = c.Dial(a)
if err != nil {
return nil, 0, err
}
defer co.Close()
func (c *Client) exchangeContext(ctx context.Context, m *Msg, co *Conn) (r *Msg, rtt time.Duration, err error) {
opt := m.IsEdns0()
// If EDNS0 is used use that for size.
if opt != nil && opt.UDPSize() >= MinMsgSize {
@ -161,18 +220,41 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro
co.UDPSize = c.UDPSize
}
co.TsigSecret = c.TsigSecret
t := time.Now()
// write with the appropriate write timeout
co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
t := time.Now()
writeDeadline := t.Add(c.getTimeoutForRequest(c.writeTimeout()))
readDeadline := t.Add(c.getTimeoutForRequest(c.readTimeout()))
if deadline, ok := ctx.Deadline(); ok {
if deadline.Before(writeDeadline) {
writeDeadline = deadline
}
if deadline.Before(readDeadline) {
readDeadline = deadline
}
}
co.SetWriteDeadline(writeDeadline)
co.SetReadDeadline(readDeadline)
co.TsigSecret, co.TsigProvider = c.TsigSecret, c.TsigProvider
if err = co.WriteMsg(m); err != nil {
return nil, 0, err
}
co.SetReadDeadline(time.Now().Add(c.getTimeoutForRequest(c.readTimeout())))
r, err = co.ReadMsg()
if err == nil && r.Id != m.Id {
err = ErrId
if isPacketConn(co.Conn) {
for {
r, err = co.ReadMsg()
// Ignore replies with mismatched IDs because they might be
// responses to earlier queries that timed out.
if err != nil || r.Id == m.Id {
break
}
}
} else {
r, err = co.ReadMsg()
if err == nil && r.Id != m.Id {
err = ErrId
}
}
rtt = time.Since(t)
return r, rtt, err
@ -197,11 +279,8 @@ func (co *Conn) ReadMsg() (*Msg, error) {
return m, err
}
if t := m.IsTsig(); t != nil {
if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
return m, ErrSecret
}
// Need to work on the original message p, as that was used to calculate the tsig.
err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
err = TsigVerifyWithProvider(p, co.tsigProvider(), co.tsigRequestMAC, false)
}
return m, err
}
@ -216,7 +295,7 @@ func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
err error
)
if _, ok := co.Conn.(net.PacketConn); ok {
if isPacketConn(co.Conn) {
if co.UDPSize > MinMsgSize {
p = make([]byte, co.UDPSize)
} else {
@ -256,7 +335,7 @@ func (co *Conn) Read(p []byte) (n int, err error) {
return 0, ErrConnEmpty
}
if _, ok := co.Conn.(net.PacketConn); ok {
if isPacketConn(co.Conn) {
// UDP connection
return co.Conn.Read(p)
}
@ -278,13 +357,8 @@ func (co *Conn) Read(p []byte) (n int, err error) {
func (co *Conn) WriteMsg(m *Msg) (err error) {
var out []byte
if t := m.IsTsig(); t != nil {
mac := ""
if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
return ErrSecret
}
out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
// Set for the next read, although only used in zone transfers
co.tsigRequestMAC = mac
// Set tsigRequestMAC for the next read, although only used in zone transfers.
out, co.tsigRequestMAC, err = TsigGenerateWithProvider(m, co.tsigProvider(), co.tsigRequestMAC, false)
} else {
out, err = m.Pack()
}
@ -301,15 +375,14 @@ func (co *Conn) Write(p []byte) (int, error) {
return 0, &Error{err: "message too large"}
}
if _, ok := co.Conn.(net.PacketConn); ok {
if isPacketConn(co.Conn) {
return co.Conn.Write(p)
}
l := make([]byte, 2)
binary.BigEndian.PutUint16(l, uint16(len(p)))
n, err := (&net.Buffers{l, p}).WriteTo(co.Conn)
return int(n), err
msg := make([]byte, 2+len(p))
binary.BigEndian.PutUint16(msg, uint16(len(p)))
copy(msg[2:], p)
return co.Conn.Write(msg)
}
// Return the appropriate timeout for a specific request
@ -345,7 +418,7 @@ func Dial(network, address string) (conn *Conn, err error) {
func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) {
client := Client{Net: "udp"}
r, _, err = client.ExchangeContext(ctx, m, a)
// ignorint rtt to leave the original ExchangeContext API unchanged, but
// ignoring rtt to leave the original ExchangeContext API unchanged, but
// this function will go away
return r, err
}
@ -358,7 +431,6 @@ func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error)
// co.WriteMsg(m)
// in, _ := co.ReadMsg()
// co.Close()
//
func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
println("dns: ExchangeConn: this function is deprecated")
co := new(Conn)
@ -401,15 +473,11 @@ func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout
// context, if present. If there is both a context deadline and a configured
// timeout on the client, the earliest of the two takes effect.
func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
var timeout time.Duration
if deadline, ok := ctx.Deadline(); !ok {
timeout = 0
} else {
timeout = time.Until(deadline)
conn, err := c.DialContext(ctx, a)
if err != nil {
return nil, 0, err
}
// not passing the context to the underlying calls, as the API does not support
// context. For timeouts you should set up Client.Dialer and call Client.Exchange.
// TODO(tmthrgd,miekg): this is a race condition.
c.Dialer = &net.Dialer{Timeout: timeout}
return c.Exchange(m, a)
defer conn.Close()
return c.exchangeWithConnContext(ctx, m, conn)
}

View File

@ -3,19 +3,116 @@ package dns
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
func TestIsPacketConn(t *testing.T) {
// UDP
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
c, err := net.Dial("udp", addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer c.Close()
if !isPacketConn(c) {
t.Error("UDP connection should be a packet conn")
}
if !isPacketConn(struct{ *net.UDPConn }{c.(*net.UDPConn)}) {
t.Error("UDP connection (wrapped type) should be a packet conn")
}
// TCP
s, addrstr, _, err = RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
c, err = net.Dial("tcp", addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer c.Close()
if isPacketConn(c) {
t.Error("TCP connection should not be a packet conn")
}
if isPacketConn(struct{ *net.TCPConn }{c.(*net.TCPConn)}) {
t.Error("TCP connection (wrapped type) should not be a packet conn")
}
// Unix datagram
s, addrstr, _, err = RunLocalUnixGramServer(filepath.Join(t.TempDir(), "unixgram.sock"))
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
c, err = net.Dial("unixgram", addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer c.Close()
if !isPacketConn(c) {
t.Error("Unix datagram connection should be a packet conn")
}
if !isPacketConn(struct{ *net.UnixConn }{c.(*net.UnixConn)}) {
t.Error("Unix datagram connection (wrapped type) should be a packet conn")
}
// Unix Seqpacket
shutChan, addrstr, err := RunLocalUnixSeqPacketServer(filepath.Join(t.TempDir(), "unixpacket.sock"))
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer func() {
shutChan <- &struct{}{}
}()
c, err = net.Dial("unixpacket", addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer c.Close()
if !isPacketConn(c) {
t.Error("Unix datagram connection should be a packet conn")
}
if !isPacketConn(struct{ *net.UnixConn }{c.(*net.UnixConn)}) {
t.Error("Unix datagram connection (wrapped type) should be a packet conn")
}
// Unix stream
s, addrstr, _, err = RunLocalUnixServer(filepath.Join(t.TempDir(), "unixstream.sock"))
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
c, err = net.Dial("unix", addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
defer c.Close()
if isPacketConn(c) {
t.Error("Unix stream connection should not be a packet conn")
}
if isPacketConn(struct{ *net.UnixConn }{c.(*net.UnixConn)}) {
t.Error("Unix stream connection (wrapped type) should not be a packet conn")
}
}
func TestDialUDP(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -38,7 +135,7 @@ func TestClientSync(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -72,7 +169,7 @@ func TestClientLocalAddress(t *testing.T) {
HandleFunc("miek.nl.", HelloServerEchoAddrPort)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -116,7 +213,7 @@ func TestClientTLSSyncV4(t *testing.T) {
Certificates: []tls.Certificate{cert},
}
s, addrstr, err := RunLocalTLSServer(":0", &config)
s, addrstr, _, err := RunLocalTLSServer(":0", &config)
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -162,11 +259,40 @@ func TestClientTLSSyncV4(t *testing.T) {
}
}
func isNetworkTimeout(err error) bool {
// TODO: when Go 1.14 support is dropped, do this: https://golang.org/doc/go1.15#net
var netError net.Error
return errors.As(err, &netError) && netError.Timeout()
}
func TestClientSyncBadID(t *testing.T) {
HandleFunc("miek.nl.", HelloServerBadID)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
m := new(Msg)
m.SetQuestion("miek.nl.", TypeSOA)
// Test with client.Exchange, the plain Exchange function is just a wrapper, so
// we don't need to test that separately.
c := &Client{
Timeout: 10 * time.Millisecond,
}
if _, _, err := c.Exchange(m, addrstr); err == nil || !isNetworkTimeout(err) {
t.Errorf("query did not time out")
}
}
func TestClientSyncBadThenGoodID(t *testing.T) {
HandleFunc("miek.nl.", HelloServerBadThenGoodID)
defer HandleRemove("miek.nl.")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -176,11 +302,32 @@ func TestClientSyncBadID(t *testing.T) {
m.SetQuestion("miek.nl.", TypeSOA)
c := new(Client)
if _, _, err := c.Exchange(m, addrstr); err != ErrId {
t.Errorf("did not find a bad Id")
r, _, err := c.Exchange(m, addrstr)
if err != nil {
t.Errorf("failed to exchange: %v", err)
}
// And now with plain Exchange().
if _, err := Exchange(m, addrstr); err != ErrId {
if r.Id != m.Id {
t.Errorf("failed to get response with expected Id")
}
}
func TestClientSyncTCPBadID(t *testing.T) {
HandleFunc("miek.nl.", HelloServerBadID)
defer HandleRemove("miek.nl.")
s, addrstr, _, err := RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
m := new(Msg)
m.SetQuestion("miek.nl.", TypeSOA)
c := &Client{
Net: "tcp",
}
if _, _, err := c.Exchange(m, addrstr); err != ErrId {
t.Errorf("did not find a bad Id")
}
}
@ -189,7 +336,7 @@ func TestClientEDNS0(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -236,7 +383,7 @@ func TestClientEDNS0Local(t *testing.T) {
HandleFunc("miek.nl.", handler)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
@ -286,7 +433,7 @@ func TestClientConn(t *testing.T) {
defer HandleRemove("miek.nl.")
// This uses TCP just to make it slightly different than TestClientSync
s, addrstr, err := RunLocalTCPServer(":0")
s, addrstr, _, err := RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -335,6 +482,24 @@ func TestClientConn(t *testing.T) {
}
}
func TestClientConnWriteSinglePacket(t *testing.T) {
c := &countingConn{}
conn := Conn{
Conn: c,
}
m := new(Msg)
m.SetQuestion("miek.nl.", TypeTXT)
err := conn.WriteMsg(m)
if err != nil {
t.Fatalf("failed to write: %v", err)
}
if c.writes != 1 {
t.Fatalf("incorrect number of Write calls")
}
}
func TestTruncatedMsg(t *testing.T) {
m := new(Msg)
m.SetQuestion("miek.nl.", TypeSRV)
@ -533,7 +698,7 @@ func TestConcurrentExchanges(t *testing.T) {
HandleFunc("miek.nl.", handler)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
@ -565,3 +730,34 @@ func TestConcurrentExchanges(t *testing.T) {
}
}
}
func TestExchangeWithConn(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
defer HandleRemove("miek.nl.")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
m := new(Msg)
m.SetQuestion("miek.nl.", TypeSOA)
c := new(Client)
conn, err := c.Dial(addrstr)
if err != nil {
t.Fatalf("failed to dial: %v", err)
}
r, _, err := c.ExchangeWithConn(m, conn)
if err != nil {
t.Fatalf("failed to exchange: %v", err)
}
if r == nil {
t.Fatal("response is nil")
}
if r.Rcode != RcodeSuccess {
t.Errorf("failed to get an valid answer\n%v", r)
}
}

View File

@ -105,7 +105,7 @@ func (dns *Msg) SetAxfr(z string) *Msg {
// SetTsig appends a TSIG RR to the message.
// This is only a skeleton TSIG RR that is added as the last RR in the
// additional section. The Tsig is calculated when the message is being send.
// additional section. The TSIG is calculated when the message is being send.
func (dns *Msg) SetTsig(z, algo string, fudge uint16, timesigned int64) *Msg {
t := new(TSIG)
t.Hdr = RR_Header{z, TypeTSIG, ClassANY, 0, 0}
@ -218,6 +218,11 @@ func IsDomainName(s string) (labels int, ok bool) {
wasDot = false
case '.':
if i == 0 && len(s) > 1 {
// leading dots are not legal except for the root zone
return labels, false
}
if wasDot {
// two dots back to back is not legal
return labels, false
@ -317,6 +322,12 @@ func Fqdn(s string) string {
return s + "."
}
// CanonicalName returns the domain name in canonical form. A name in canonical
// form is lowercase and fully qualified. See Section 6.2 in RFC 4034.
func CanonicalName(s string) string {
return strings.ToLower(Fqdn(s))
}
// Copied from the official Go code.
// ReverseAddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
@ -343,10 +354,7 @@ func ReverseAddr(addr string) (arpa string, err error) {
// Add it, in reverse, to the buffer
for i := len(ip) - 1; i >= 0; i-- {
v := ip[i]
buf = append(buf, hexDigit[v&0xF])
buf = append(buf, '.')
buf = append(buf, hexDigit[v>>4])
buf = append(buf, '.')
buf = append(buf, hexDigit[v&0xF], '.', hexDigit[v>>4], '.')
}
// Append "ip6.arpa." and return (buf already has the final .)
buf = append(buf, "ip6.arpa."...)
@ -364,7 +372,7 @@ func (t Type) String() string {
// String returns the string representation for the class c.
func (c Class) String() string {
if s, ok := ClassToString[uint16(c)]; ok {
// Only emit mnemonics when they are unambiguous, specically ANY is in both.
// Only emit mnemonics when they are unambiguous, specially ANY is in both.
if _, ok := StringToType[s]; !ok {
return s
}

30
dns.go
View File

@ -1,6 +1,9 @@
package dns
import "strconv"
import (
"encoding/hex"
"strconv"
)
const (
year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits.
@ -111,7 +114,7 @@ func (h *RR_Header) parse(c *zlexer, origin string) *ParseError {
// ToRFC3597 converts a known RR to the unknown RR representation from RFC 3597.
func (rr *RFC3597) ToRFC3597(r RR) error {
buf := make([]byte, Len(r)*2)
buf := make([]byte, Len(r))
headerEnd, off, err := packRR(r, buf, 0, compressionMap{}, false)
if err != nil {
return err
@ -126,9 +129,30 @@ func (rr *RFC3597) ToRFC3597(r RR) error {
}
_, err = rr.unpack(buf, headerEnd)
return err
}
// fromRFC3597 converts an unknown RR representation from RFC 3597 to the known RR type.
func (rr *RFC3597) fromRFC3597(r RR) error {
hdr := r.Header()
*hdr = rr.Hdr
// Can't overflow uint16 as the length of Rdata is validated in (*RFC3597).parse.
// We can only get here when rr was constructed with that method.
hdr.Rdlength = uint16(hex.DecodedLen(len(rr.Rdata)))
if noRdata(*hdr) {
// Dynamic update.
return nil
}
// rr.pack requires an extra allocation and a copy so we just decode Rdata
// manually, it's simpler anyway.
msg, err := hex.DecodeString(rr.Rdata)
if err != nil {
return err
}
return nil
_, err = r.unpack(msg, 0)
return err
}

167
dnssec.go
View File

@ -3,15 +3,14 @@ package dns
import (
"bytes"
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
_ "crypto/md5"
"crypto/rand"
"crypto/rsa"
_ "crypto/sha1"
_ "crypto/sha256"
_ "crypto/sha512"
_ "crypto/sha1" // need its init function
_ "crypto/sha256" // need its init function
_ "crypto/sha512" // need its init function
"encoding/asn1"
"encoding/binary"
"encoding/hex"
@ -19,8 +18,6 @@ import (
"sort"
"strings"
"time"
"golang.org/x/crypto/ed25519"
)
// DNSSEC encryption algorithm codes.
@ -68,6 +65,9 @@ var AlgorithmToString = map[uint8]string{
}
// AlgorithmToHash is a map of algorithm crypto hash IDs to crypto.Hash's.
// For newer algorithm that do their own hashing (i.e. ED25519) the returned value
// is 0, implying no (external) hashing should occur. The non-exported identityHash is then
// used.
var AlgorithmToHash = map[uint8]crypto.Hash{
RSAMD5: crypto.MD5, // Deprecated in RFC 6725
DSA: crypto.SHA1,
@ -77,7 +77,7 @@ var AlgorithmToHash = map[uint8]crypto.Hash{
ECDSAP256SHA256: crypto.SHA256,
ECDSAP384SHA384: crypto.SHA384,
RSASHA512: crypto.SHA512,
ED25519: crypto.Hash(0),
ED25519: 0,
}
// DNSSEC hashing algorithm codes.
@ -140,12 +140,12 @@ func (k *DNSKEY) KeyTag() uint16 {
var keytag int
switch k.Algorithm {
case RSAMD5:
// Look at the bottom two bytes of the modules, which the last
// item in the pubkey.
// This algorithm has been deprecated, but keep this key-tag calculation.
// Look at the bottom two bytes of the modules, which the last item in the pubkey.
// See https://www.rfc-editor.org/errata/eid193 .
modulus, _ := fromBase64([]byte(k.PublicKey))
if len(modulus) > 1 {
x := binary.BigEndian.Uint16(modulus[len(modulus)-2:])
x := binary.BigEndian.Uint16(modulus[len(modulus)-3:])
keytag = int(x)
}
default:
@ -200,7 +200,7 @@ func (k *DNSKEY) ToDS(h uint8) *DS {
wire = wire[:n]
owner := make([]byte, 255)
off, err1 := PackDomainName(strings.ToLower(k.Hdr.Name), owner, 0, nil, false)
off, err1 := PackDomainName(CanonicalName(k.Hdr.Name), owner, 0, nil, false)
if err1 != nil {
return nil
}
@ -285,7 +285,7 @@ func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error {
sigwire.Inception = rr.Inception
sigwire.KeyTag = rr.KeyTag
// For signing, lowercase this name
sigwire.SignerName = strings.ToLower(rr.SignerName)
sigwire.SignerName = CanonicalName(rr.SignerName)
// Create the desired binary blob
signdata := make([]byte, DefaultMsgSize)
@ -299,42 +299,27 @@ func (rr *RRSIG) Sign(k crypto.Signer, rrset []RR) error {
return err
}
hash, ok := AlgorithmToHash[rr.Algorithm]
if !ok {
return ErrAlg
h, cryptohash, err := hashFromAlgorithm(rr.Algorithm)
if err != nil {
return err
}
switch rr.Algorithm {
case ED25519:
// ed25519 signs the raw message and performs hashing internally.
// All other supported signature schemes operate over the pre-hashed
// message, and thus ed25519 must be handled separately here.
//
// The raw message is passed directly into sign and crypto.Hash(0) is
// used to signal to the crypto.Signer that the data has not been hashed.
signature, err := sign(k, append(signdata, wire...), crypto.Hash(0), rr.Algorithm)
if err != nil {
return err
}
rr.Signature = toBase64(signature)
case RSAMD5, DSA, DSANSEC3SHA1:
// See RFC 6944.
return ErrAlg
default:
h := hash.New()
h.Write(signdata)
h.Write(wire)
signature, err := sign(k, h.Sum(nil), hash, rr.Algorithm)
signature, err := sign(k, h.Sum(nil), cryptohash, rr.Algorithm)
if err != nil {
return err
}
rr.Signature = toBase64(signature)
return nil
}
return nil
}
func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte, error) {
@ -344,9 +329,8 @@ func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte,
}
switch alg {
case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512:
case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, ED25519:
return signature, nil
case ECDSAP256SHA256, ECDSAP384SHA384:
ecdsaSignature := &struct {
R, S *big.Int
@ -366,25 +350,16 @@ func sign(k crypto.Signer, hashed []byte, hash crypto.Hash, alg uint8) ([]byte,
signature := intToBytes(ecdsaSignature.R, intlen)
signature = append(signature, intToBytes(ecdsaSignature.S, intlen)...)
return signature, nil
// There is no defined interface for what a DSA backed crypto.Signer returns
case DSA, DSANSEC3SHA1:
// t := divRoundUp(divRoundUp(p.PublicKey.Y.BitLen(), 8)-64, 8)
// signature := []byte{byte(t)}
// signature = append(signature, intToBytes(r1, 20)...)
// signature = append(signature, intToBytes(s1, 20)...)
// rr.Signature = signature
case ED25519:
return signature, nil
default:
return nil, ErrAlg
}
return nil, ErrAlg
}
// 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).
func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
// First the easy checks
if !IsRRset(rrset) {
@ -405,6 +380,12 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
if k.Protocol != 3 {
return ErrKey
}
// RFC 4034 2.1.1 If bit 7 has value 0, then the DNSKEY record holds some
// other type of DNS public key and MUST NOT be used to verify RRSIGs that
// cover RRsets.
if k.Flags&ZONE == 0 {
return ErrKey
}
// IsRRset checked that we have at least one RR and that the RRs in
// the set have consistent type, class, and name. Also check that type and
@ -423,7 +404,7 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
sigwire.Expiration = rr.Expiration
sigwire.Inception = rr.Inception
sigwire.KeyTag = rr.KeyTag
sigwire.SignerName = strings.ToLower(rr.SignerName)
sigwire.SignerName = CanonicalName(rr.SignerName)
// Create the desired binary blob
signeddata := make([]byte, DefaultMsgSize)
n, err := packSigWire(sigwire, signeddata)
@ -442,23 +423,22 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
// remove the domain name and assume its ours?
}
hash, ok := AlgorithmToHash[rr.Algorithm]
if !ok {
return ErrAlg
h, cryptohash, err := hashFromAlgorithm(rr.Algorithm)
if err != nil {
return err
}
switch rr.Algorithm {
case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, RSAMD5:
case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512:
// TODO(mg): this can be done quicker, ie. cache the pubkey data somewhere??
pubkey := k.publicKeyRSA() // Get the key
if pubkey == nil {
return ErrKey
}
h := hash.New()
h.Write(signeddata)
h.Write(wire)
return rsa.VerifyPKCS1v15(pubkey, hash, h.Sum(nil), sigbuf)
return rsa.VerifyPKCS1v15(pubkey, cryptohash, h.Sum(nil), sigbuf)
case ECDSAP256SHA256, ECDSAP384SHA384:
pubkey := k.publicKeyECDSA()
@ -470,7 +450,6 @@ func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
r := new(big.Int).SetBytes(sigbuf[:len(sigbuf)/2])
s := new(big.Int).SetBytes(sigbuf[len(sigbuf)/2:])
h := hash.New()
h.Write(signeddata)
h.Write(wire)
if ecdsa.Verify(pubkey, h.Sum(nil), r, s) {
@ -512,7 +491,7 @@ func (rr *RRSIG) ValidityPeriod(t time.Time) bool {
return ti <= utc && utc <= te
}
// Return the signatures base64 encodedig sigdata as a byte slice.
// Return the signatures base64 encoding sigdata as a byte slice.
func (rr *RRSIG) sigBuf() []byte {
sigbuf, err := fromBase64([]byte(rr.Signature))
if err != nil {
@ -600,30 +579,6 @@ func (k *DNSKEY) publicKeyECDSA() *ecdsa.PublicKey {
return pubkey
}
func (k *DNSKEY) publicKeyDSA() *dsa.PublicKey {
keybuf, err := fromBase64([]byte(k.PublicKey))
if err != nil {
return nil
}
if len(keybuf) < 22 {
return nil
}
t, keybuf := int(keybuf[0]), keybuf[1:]
size := 64 + t*8
q, keybuf := keybuf[:20], keybuf[20:]
if len(keybuf) != 3*size {
return nil
}
p, keybuf := keybuf[:size], keybuf[size:]
g, y := keybuf[:size], keybuf[size:]
pubkey := new(dsa.PublicKey)
pubkey.Parameters.Q = new(big.Int).SetBytes(q)
pubkey.Parameters.P = new(big.Int).SetBytes(p)
pubkey.Parameters.G = new(big.Int).SetBytes(g)
pubkey.Y = new(big.Int).SetBytes(y)
return pubkey
}
func (k *DNSKEY) publicKeyED25519() ed25519.PublicKey {
keybuf, err := fromBase64([]byte(k.PublicKey))
if err != nil {
@ -659,7 +614,7 @@ func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) {
h.Name = "*." + strings.Join(labels[len(labels)-int(s.Labels):], ".") + "."
}
// RFC 4034: 6.2. Canonical RR Form. (2) - domain name to lowercase
h.Name = strings.ToLower(h.Name)
h.Name = CanonicalName(h.Name)
// 6.2. Canonical RR Form. (3) - domain rdata to lowercase.
// NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR,
// HINFO, MINFO, MX, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX,
@ -672,49 +627,49 @@ func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) {
// conversion.
switch x := r1.(type) {
case *NS:
x.Ns = strings.ToLower(x.Ns)
x.Ns = CanonicalName(x.Ns)
case *MD:
x.Md = strings.ToLower(x.Md)
x.Md = CanonicalName(x.Md)
case *MF:
x.Mf = strings.ToLower(x.Mf)
x.Mf = CanonicalName(x.Mf)
case *CNAME:
x.Target = strings.ToLower(x.Target)
x.Target = CanonicalName(x.Target)
case *SOA:
x.Ns = strings.ToLower(x.Ns)
x.Mbox = strings.ToLower(x.Mbox)
x.Ns = CanonicalName(x.Ns)
x.Mbox = CanonicalName(x.Mbox)
case *MB:
x.Mb = strings.ToLower(x.Mb)
x.Mb = CanonicalName(x.Mb)
case *MG:
x.Mg = strings.ToLower(x.Mg)
x.Mg = CanonicalName(x.Mg)
case *MR:
x.Mr = strings.ToLower(x.Mr)
x.Mr = CanonicalName(x.Mr)
case *PTR:
x.Ptr = strings.ToLower(x.Ptr)
x.Ptr = CanonicalName(x.Ptr)
case *MINFO:
x.Rmail = strings.ToLower(x.Rmail)
x.Email = strings.ToLower(x.Email)
x.Rmail = CanonicalName(x.Rmail)
x.Email = CanonicalName(x.Email)
case *MX:
x.Mx = strings.ToLower(x.Mx)
x.Mx = CanonicalName(x.Mx)
case *RP:
x.Mbox = strings.ToLower(x.Mbox)
x.Txt = strings.ToLower(x.Txt)
x.Mbox = CanonicalName(x.Mbox)
x.Txt = CanonicalName(x.Txt)
case *AFSDB:
x.Hostname = strings.ToLower(x.Hostname)
x.Hostname = CanonicalName(x.Hostname)
case *RT:
x.Host = strings.ToLower(x.Host)
x.Host = CanonicalName(x.Host)
case *SIG:
x.SignerName = strings.ToLower(x.SignerName)
x.SignerName = CanonicalName(x.SignerName)
case *PX:
x.Map822 = strings.ToLower(x.Map822)
x.Mapx400 = strings.ToLower(x.Mapx400)
x.Map822 = CanonicalName(x.Map822)
x.Mapx400 = CanonicalName(x.Mapx400)
case *NAPTR:
x.Replacement = strings.ToLower(x.Replacement)
x.Replacement = CanonicalName(x.Replacement)
case *KX:
x.Exchanger = strings.ToLower(x.Exchanger)
x.Exchanger = CanonicalName(x.Exchanger)
case *SRV:
x.Target = strings.ToLower(x.Target)
x.Target = CanonicalName(x.Target)
case *DNAME:
x.Target = strings.ToLower(x.Target)
x.Target = CanonicalName(x.Target)
}
// 6.2. Canonical RR Form. (5) - origTTL
wire := make([]byte, Len(r1)+1) // +1 to be safe(r)

View File

@ -3,12 +3,11 @@ package dns
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"math/big"
"golang.org/x/crypto/ed25519"
)
// Generate generates a DNSKEY of the given bit size.
@ -19,8 +18,6 @@ import (
// bits should be set to the size of the algorithm.
func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error) {
switch k.Algorithm {
case RSAMD5, DSA, DSANSEC3SHA1:
return nil, ErrAlg
case RSASHA1, RSASHA256, RSASHA1NSEC3SHA1:
if bits < 512 || bits > 4096 {
return nil, ErrKeySize
@ -41,6 +38,8 @@ func (k *DNSKEY) Generate(bits int) (crypto.PrivateKey, error) {
if bits != 256 {
return nil, ErrKeySize
}
default:
return nil, ErrAlg
}
switch k.Algorithm {

View File

@ -4,13 +4,12 @@ import (
"bufio"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"io"
"math/big"
"strconv"
"strings"
"golang.org/x/crypto/ed25519"
)
// NewPrivateKey returns a PrivateKey by parsing the string s.
@ -43,15 +42,7 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er
return nil, ErrPrivKey
}
switch uint8(algo) {
case RSAMD5, DSA, DSANSEC3SHA1:
return nil, ErrAlg
case RSASHA1:
fallthrough
case RSASHA1NSEC3SHA1:
fallthrough
case RSASHA256:
fallthrough
case RSASHA512:
case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512:
priv, err := readPrivateKeyRSA(m)
if err != nil {
return nil, err
@ -62,11 +53,7 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er
}
priv.PublicKey = *pub
return priv, nil
case ECCGOST:
return nil, ErrPrivKey
case ECDSAP256SHA256:
fallthrough
case ECDSAP384SHA384:
case ECDSAP256SHA256, ECDSAP384SHA384:
priv, err := readPrivateKeyECDSA(m)
if err != nil {
return nil, err
@ -80,7 +67,7 @@ func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (crypto.PrivateKey, er
case ED25519:
return readPrivateKeyED25519(m)
default:
return nil, ErrPrivKey
return nil, ErrAlg
}
}

View File

@ -2,13 +2,11 @@ package dns
import (
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"math/big"
"strconv"
"golang.org/x/crypto/ed25519"
)
const format = "Private-key-format: v1.3\n"
@ -17,8 +15,8 @@ var bigIntOne = big.NewInt(1)
// 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 dsa.PrivateKey
// 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.
func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string {
algorithm := strconv.Itoa(int(r.Algorithm))
algorithm += " (" + AlgorithmToString[r.Algorithm] + ")"
@ -67,21 +65,6 @@ func (r *DNSKEY) PrivateKeyString(p crypto.PrivateKey) string {
"Algorithm: " + algorithm + "\n" +
"PrivateKey: " + private + "\n"
case *dsa.PrivateKey:
T := divRoundUp(divRoundUp(p.PublicKey.Parameters.G.BitLen(), 8)-64, 8)
prime := toBase64(intToBytes(p.PublicKey.Parameters.P, 64+T*8))
subprime := toBase64(intToBytes(p.PublicKey.Parameters.Q, 20))
base := toBase64(intToBytes(p.PublicKey.Parameters.G, 64+T*8))
priv := toBase64(intToBytes(p.X, 20))
pub := toBase64(intToBytes(p.PublicKey.Y, 64+T*8))
return format +
"Algorithm: " + algorithm + "\n" +
"Prime(p): " + prime + "\n" +
"Subprime(q): " + subprime + "\n" +
"Base(g): " + base + "\n" +
"Private_value(x): " + priv + "\n" +
"Public_value(y): " + pub + "\n"
case ed25519.PrivateKey:
private := toBase64(p.Seed())
return format +

View File

@ -3,13 +3,12 @@ package dns
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/crypto/ed25519"
)
func getSoa() *SOA {
@ -168,7 +167,7 @@ func Test65534(t *testing.T) {
key.Flags = 256
key.Protocol = 3
key.Algorithm = RSASHA256
privkey, _ := key.Generate(1024)
privkey, _ := key.Generate(512)
sig := new(RRSIG)
sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
@ -251,7 +250,7 @@ func TestKeyRSA(t *testing.T) {
key.Flags = 256
key.Protocol = 3
key.Algorithm = RSASHA256
priv, _ := key.Generate(2048)
priv, _ := key.Generate(512)
soa := new(SOA)
soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0}
@ -325,7 +324,7 @@ Activate: 20110302104537`
}
switch priv := p.(type) {
case *rsa.PrivateKey:
if 65537 != priv.PublicKey.E {
if priv.PublicKey.E != 65537 {
t.Error("exponenent should be 65537")
}
default:
@ -856,3 +855,16 @@ func TestParseKeyReadError(t *testing.T) {
t.Errorf("expected a nil map, but got %v", m)
}
}
func TestRSAMD5KeyTag(t *testing.T) {
rr1, _ := NewRR("test. IN DNSKEY 257 3 1 AwEAAcntNdoMnY8pvyPcpDTAaiqHyAhf53XUBANq166won/fjBFvmuzhTuP5r4el/pV0tzEBL73zpoU48BqF66uiL+qRijXCySJiaBUvLNll5rpwuduAOoVpmwOmkC4fV6izHOAx/Uy8c+pYP0YR8+1P7GuTFxgnMmt9sUGtoe+la0X/ ;{id = 27461 (ksk), size = 1024b}")
rr2, _ := NewRR("test. IN DNSKEY 257 3 1 AwEAAf0bKO/m45ylk5BlSLmQHQRBLx1m/ZUXvyPFB387bJXxnTk6so3ub97L1RQ+8bOoiRh3Qm5EaYihjco7J8b/W5WbS3tVsE79nY584RfTKT2zcZ9AoFP2XLChXxPIf/6l0H9n6sH0aBjsG8vabEIp8e06INM3CXVPiMRPPeGNa0Ub ;{id = 27461 (ksk), size = 1024b}")
exp := uint16(27461)
if x := rr1.(*DNSKEY).KeyTag(); x != exp {
t.Errorf("expected %d, got %d, as keytag for rr1", exp, x)
}
if x := rr2.(*DNSKEY).KeyTag(); x != exp { // yes, same key tag
t.Errorf("expected %d, got %d, as keytag for rr2", exp, x)
}
}

View File

@ -30,10 +30,10 @@ func AddOrigin(s, origin string) string {
if dns.IsFqdn(s) {
return s // s is already a FQDN, no need to mess with it.
}
if len(origin) == 0 {
if origin == "" {
return s // Nothing to append.
}
if s == "@" || len(s) == 0 {
if s == "@" || s == "" {
return origin // Expand apex.
}
if origin == "." {
@ -50,7 +50,7 @@ func TrimDomainName(s, origin string) string {
// If the return value ends in a ".", the domain was not the suffix.
// origin can end in "." or not. Either way the results should be the same.
if len(s) == 0 {
if s == "" {
return "@"
}
// Someone is using TrimDomainName(s, ".") to remove a dot if it exists.

View File

@ -63,7 +63,7 @@ func TestTrimDomainName(t *testing.T) {
// Paranoid tests.
// These test shouldn't be needed but I was weary of off-by-one errors.
// In theory, these can't happen because there are no single-letter TLDs,
// but it is good to exercize the code this way.
// but it is good to exercise the code this way.
tests := []struct{ experiment, expected string }{
{"", "@"},
{".", "."},

133
doc.go
View File

@ -13,28 +13,28 @@ names in a message will result in a packing failure.
Resource records are native types. They are not stored in wire format. Basic
usage pattern for creating a new resource record:
r := new(dns.MX)
r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 3600}
r.Preference = 10
r.Mx = "mx.miek.nl."
r := new(dns.MX)
r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 3600}
r.Preference = 10
r.Mx = "mx.miek.nl."
Or directly from a string:
mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.")
mx, err := dns.NewRR("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.NewRR("miek.nl MX 10 mx.miek.nl")
mx, err := dns.NewRR("miek.nl MX 10 mx.miek.nl")
Or even:
mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
In the DNS messages are exchanged, these messages contain resource records
(sets). Use pattern for creating a message:
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
Or when not certain if the domain name is fully qualified:
@ -45,17 +45,17 @@ records for the miek.nl. zone.
The following is slightly more verbose, but more flexible:
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}
m1 := new(dns.Msg)
m1.Id = dns.Id()
m1.RecursionDesired = true
m1.Question = make([]dns.Question, 1)
m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}
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:
c := new(dns.Client)
in, rtt, err := c.Exchange(m1, "127.0.0.1:53")
c := new(dns.Client)
in, rtt, err := c.Exchange(m1, "127.0.0.1:53")
Suppressing multiple outstanding queries (with the same question, type and
class) is as easy as setting:
@ -72,7 +72,7 @@ and port to use for the connection:
Port: 12345,
Zone: "",
}
c.Dialer := &net.Dialer{
c.Dialer = &net.Dialer{
Timeout: 200 * time.Millisecond,
LocalAddr: &laddr,
}
@ -83,7 +83,7 @@ with:
in, err := dns.Exchange(m1, "127.0.0.1:53")
When this functions returns you will get dns message. A dns message consists
When this functions returns you will get DNS message. A DNS message consists
out of four sections.
The question section: in.Question, the answer section: in.Answer,
the authority section: in.Ns and the additional section: in.Extra.
@ -96,7 +96,7 @@ the Answer section:
// do something with t.Txt
}
Domain Name and TXT Character String Representations
# 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.
@ -108,7 +108,7 @@ 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
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
@ -117,12 +117,12 @@ 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.SetEdns0(4096, true)
m := new(dns.Msg)
m.SetEdns0(4096, true)
Signature generation, signature verification and key generation are all supported.
DYNAMIC UPDATES
# DYNAMIC UPDATES
Dynamic updates reuses the DNS message format, but renames three of the
sections. Question is Zone, Answer is Prerequisite, Authority is Update, only
@ -133,33 +133,33 @@ certain resource records or names in a zone to specify if resource records
should be added or removed. The table from RFC 2136 supplemented with the Go
DNS function shows which functions exist to specify the prerequisites.
3.2.4 - Table Of Metavalues Used In Prerequisite Section
3.2.4 - Table Of Metavalues Used In Prerequisite Section
CLASS TYPE RDATA Meaning Function
--------------------------------------------------------------
ANY ANY empty Name is in use dns.NameUsed
ANY rrset empty RRset exists (value indep) dns.RRsetUsed
NONE ANY empty Name is not in use dns.NameNotUsed
NONE rrset empty RRset does not exist dns.RRsetNotUsed
zone rrset rr RRset exists (value dep) dns.Used
CLASS TYPE RDATA Meaning Function
--------------------------------------------------------------
ANY ANY empty Name is in use dns.NameUsed
ANY rrset empty RRset exists (value indep) dns.RRsetUsed
NONE ANY empty Name is not in use dns.NameNotUsed
NONE rrset empty RRset does not exist dns.RRsetNotUsed
zone rrset rr RRset exists (value dep) dns.Used
The prerequisite section can also be left empty. If you have decided on the
prerequisites you can tell what RRs should be added or deleted. The next table
shows the options you have and what functions to call.
3.4.2.6 - Table Of Metavalues Used In Update Section
3.4.2.6 - Table Of Metavalues Used In Update Section
CLASS TYPE RDATA Meaning Function
---------------------------------------------------------------
ANY ANY empty Delete all RRsets from name dns.RemoveName
ANY rrset empty Delete an RRset dns.RemoveRRset
NONE rrset rr Delete an RR from RRset dns.Remove
zone rrset rr Add to an RRset dns.Insert
CLASS TYPE RDATA Meaning Function
---------------------------------------------------------------
ANY ANY empty Delete all RRsets from name dns.RemoveName
ANY rrset empty Delete an RRset dns.RemoveRRset
NONE rrset rr Delete an RR from RRset dns.Remove
zone rrset rr Add to an RRset dns.Insert
TRANSACTION SIGNATURE
# TRANSACTION SIGNATURE
An TSIG or transaction signature adds a HMAC TSIG record to each message sent.
The supported algorithms include: HmacMD5, HmacSHA1, HmacSHA256 and HmacSHA512.
The supported algorithms include: HmacSHA1, HmacSHA256 and HmacSHA512.
Basic use pattern when querying with a TSIG name "axfr." (note that these key names
must be fully qualified - as they are domain names) and the base64 secret
@ -174,7 +174,7 @@ changes to the RRset after calling SetTsig() the signature will be incorrect.
c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
...
// When sending the TSIG RR is calculated and filled in before sending
@ -187,13 +187,37 @@ request an AXFR for miek.nl. with TSIG key named "axfr." and secret
m := new(dns.Msg)
t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
m.SetAxfr("miek.nl.")
m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
c, err := t.In(m, "176.58.119.54:53")
for r := range c { ... }
You can now read the records from the transfer as they come in. Each envelope
is checked with TSIG. If something is not correct an error is returned.
A custom TSIG implementation can be used. This requires additional code to
perform any session establishment and signature generation/verification. The
client must be configured with an implementation of the TsigProvider interface:
type Provider struct{}
func (*Provider) Generate(msg []byte, tsig *dns.TSIG) ([]byte, error) {
// Use tsig.Hdr.Name and tsig.Algorithm in your code to
// generate the MAC using msg as the payload.
}
func (*Provider) Verify(msg []byte, tsig *dns.TSIG) error {
// Use tsig.Hdr.Name and tsig.Algorithm in your code to verify
// that msg matches the value in tsig.MAC.
}
c := new(dns.Client)
c.TsigProvider = new(Provider)
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.SetTsig(keyname, dns.HmacSHA256, 300, time.Now().Unix())
...
// TSIG RR is calculated by calling your Generate method
Basic use pattern validating and replying to a message that has TSIG set.
server := &dns.Server{Addr: ":53", Net: "udp"}
@ -207,27 +231,27 @@ Basic use pattern validating and replying to a message that has TSIG set.
if r.IsTsig() != nil {
if w.TsigStatus() == nil {
// *Msg r has an TSIG record and it was validated
m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
m.SetTsig("axfr.", dns.HmacSHA256, 300, time.Now().Unix())
} else {
// *Msg r has an TSIG records and it was not valided
// *Msg r has an TSIG records and it was not validated
}
}
w.WriteMsg(m)
}
PRIVATE RRS
# PRIVATE RRS
RFC 6895 sets aside a range of type codes for private use. This range is 65,280
- 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these
can be used, before requesting an official type code from IANA.
See https://miek.nl/2014/September/21/idn-and-private-rr-in-go-dns/ for more
See https://miek.nl/2014/september/21/idn-and-private-rr-in-go-dns/ for more
information.
EDNS0
# EDNS0
EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated by
RFC 6891. It defines an new RR type, the OPT RR, which is then completely
RFC 6891. It defines a new RR type, the OPT RR, which is then completely
abused.
Basic use pattern for creating an (empty) OPT RR:
@ -238,9 +262,8 @@ Basic use pattern for creating an (empty) OPT RR:
The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891) interfaces.
Currently only a few have been standardized: EDNS0_NSID (RFC 5001) and
EDNS0_SUBNET (draft-vandergaast-edns-client-subnet-02). Note that these options
may be combined in an OPT RR. Basic use pattern for a server to check if (and
which) options are set:
EDNS0_SUBNET (RFC 7871). Note that these options may be combined in an OPT RR.
Basic use pattern for a server to check if (and which) options are set:
// o is a dns.OPT
for _, s := range o.Option {
@ -256,12 +279,12 @@ SIG(0)
From RFC 2931:
SIG(0) provides protection for DNS transactions and requests ....
... protection for glue records, DNS requests, protection for message headers
on requests and responses, and protection of the overall integrity of a response.
SIG(0) provides protection for DNS transactions and requests ....
... protection for glue records, DNS requests, protection for message headers
on requests and responses, and protection of the overall integrity of a response.
It works like TSIG, except that SIG(0) uses public key cryptography, instead of
the shared secret approach in TSIG. Supported algorithms: DSA, ECDSAP256SHA256,
the shared secret approach in TSIG. Supported algorithms: ECDSAP256SHA256,
ECDSAP384SHA384, RSASHA1, RSASHA256 and RSASHA512.
Signing subsequent messages in multi-message sessions is not implemented.

View File

@ -3,9 +3,8 @@ package dns
//go:generate go run duplicate_generate.go
// IsDuplicate checks of r1 and r2 are duplicates of each other, excluding the TTL.
// So this means the header data is equal *and* the RDATA is the same. Return true
// is so, otherwise false.
// It's is a protocol violation to have identical RRs in a message.
// So this means the header data is equal *and* the RDATA is the same. Returns true
// if so, otherwise false. It's a protocol violation to have identical RRs in a message.
func IsDuplicate(r1, r2 RR) bool {
// Check whether the record header is identical.
if !r1.Header().isDuplicate(r2.Header()) {

View File

@ -1,4 +1,5 @@
//+build ignore
//go:build ignore
// +build ignore
// types_generate.go is meant to run with go generate. It will use
// go/{importer,types} to track down all the RR struct types. Then for each type
@ -11,10 +12,11 @@ import (
"bytes"
"fmt"
"go/format"
"go/importer"
"go/types"
"log"
"os"
"golang.org/x/tools/go/packages"
)
var packageHdr = `
@ -29,6 +31,9 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
if !ok {
return nil, false
}
if st.NumFields() == 0 {
return nil, false
}
if st.Field(0).Type() == scope.Lookup("RR_Header").Type() {
return st, false
}
@ -39,9 +44,19 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
return nil, false
}
// loadModule retrieves package description for a given module.
func loadModule(name string) (*types.Package, error) {
conf := packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo}
pkgs, err := packages.Load(&conf, name)
if err != nil {
return nil, err
}
return pkgs[0].Types, nil
}
func main() {
// Import and type-check the package
pkg, err := importer.Default().Import("github.com/miekg/dns")
pkg, err := loadModule("github.com/miekg/dns")
fatalIfErr(err)
scope := pkg.Scope()
@ -72,10 +87,7 @@ func main() {
for _, name := range namedTypes {
o := scope.Lookup(name)
st, isEmbedded := getTypeStruct(o.Type(), scope)
if isEmbedded {
continue
}
st, _ := getTypeStruct(o.Type(), scope)
fmt.Fprintf(b, "func (r1 *%s) isDuplicate(_r2 RR) bool {\n", name)
fmt.Fprintf(b, "r2, ok := _r2.(*%s)\n", name)
fmt.Fprint(b, "if !ok { return false }\n")
@ -100,6 +112,24 @@ func main() {
continue
}
if st.Tag(i) == `dns:"apl"` {
o3(`for i := 0; i < len(r1.%s); i++ {
if !r1.%s[i].equals(&r2.%s[i]) {
return false
}
}`)
continue
}
if st.Tag(i) == `dns:"pairs"` {
o2(`if !areSVCBPairArraysEqual(r1.%s, r2.%s) {
return false
}`)
continue
}
o3(`for i := 0; i < len(r1.%s); i++ {
if r1.%s[i] != r2.%s[i] {
return false

View File

@ -34,6 +34,39 @@ func TestDuplicateTXT(t *testing.T) {
}
}
func TestDuplicateSVCB(t *testing.T) {
a1, _ := NewRR(`example.com. 3600 IN SVCB 1 . ipv6hint=1::3:3:3:3 key65300=\254\032\030\000\ \043,\;`)
a2, _ := NewRR(`example.com. 3600 IN SVCB 1 . ipv6hint=1:0::3:3:3:3 key65300="\254\ \030\000 +\,;"`)
if !IsDuplicate(a1, a2) {
t.Errorf("expected %s/%s to be duplicates, but got false", a1.String(), a2.String())
}
a2, _ = NewRR(`example.com. 3600 IN SVCB 1 . ipv6hint=1::3:3:3:3 key65300="\255\ \030\000 +\,;"`)
if IsDuplicate(a1, a2) {
t.Errorf("expected %s/%s not to be duplicates, but got true", a1.String(), a2.String())
}
a1, _ = NewRR(`example.com. 3600 IN SVCB 1 . ipv6hint=1::3:3:3:3`)
if IsDuplicate(a1, a2) {
t.Errorf("expected %s/%s not to be duplicates, but got true", a1.String(), a2.String())
}
a2, _ = NewRR(`example.com. 3600 IN SVCB 1 . ipv4hint=1.1.1.1`)
if IsDuplicate(a1, a2) {
t.Errorf("expected %s/%s not to be duplicates, but got true", a1.String(), a2.String())
}
a1, _ = NewRR(`example.com. 3600 IN SVCB 1 . ipv4hint=1.1.1.1,1.0.2.1`)
if IsDuplicate(a1, a2) {
t.Errorf("expected %s/%s not to be duplicates, but got true", a1.String(), a2.String())
}
}
func TestDuplicateOwner(t *testing.T) {
a1, _ := NewRR("www.example.org. IN A 127.0.0.1")
a2, _ := NewRR("www.example.org. IN A 127.0.0.1")

293
edns.go
View File

@ -14,6 +14,7 @@ const (
EDNS0LLQ = 0x1 // long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
EDNS0UL = 0x2 // update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt
EDNS0NSID = 0x3 // nsid (See RFC 5001)
EDNS0ESU = 0x4 // ENUM Source-URI draft: https://datatracker.ietf.org/doc/html/draft-kaplan-enum-source-uri-00
EDNS0DAU = 0x5 // DNSSEC Algorithm Understood
EDNS0DHU = 0x6 // DS Hash Understood
EDNS0N3U = 0x7 // NSEC3 Hash Understood
@ -22,11 +23,49 @@ const (
EDNS0COOKIE = 0xa // EDNS0 Cookie
EDNS0TCPKEEPALIVE = 0xb // EDNS0 tcp keep alive (See RFC 7828)
EDNS0PADDING = 0xc // EDNS0 padding (See RFC 7830)
EDNS0EDE = 0xf // EDNS0 extended DNS errors (See RFC 8914)
EDNS0LOCALSTART = 0xFDE9 // Beginning of range reserved for local/experimental use (See RFC 6891)
EDNS0LOCALEND = 0xFFFE // End of range reserved for local/experimental use (See RFC 6891)
_DO = 1 << 15 // DNSSEC OK
)
// makeDataOpt is used to unpack the EDNS0 option(s) from a message.
func makeDataOpt(code uint16) EDNS0 {
// All the EDNS0.* constants above need to be in this switch.
switch code {
case EDNS0LLQ:
return new(EDNS0_LLQ)
case EDNS0UL:
return new(EDNS0_UL)
case EDNS0NSID:
return new(EDNS0_NSID)
case EDNS0DAU:
return new(EDNS0_DAU)
case EDNS0DHU:
return new(EDNS0_DHU)
case EDNS0N3U:
return new(EDNS0_N3U)
case EDNS0SUBNET:
return new(EDNS0_SUBNET)
case EDNS0EXPIRE:
return new(EDNS0_EXPIRE)
case EDNS0COOKIE:
return new(EDNS0_COOKIE)
case EDNS0TCPKEEPALIVE:
return new(EDNS0_TCP_KEEPALIVE)
case EDNS0PADDING:
return new(EDNS0_PADDING)
case EDNS0EDE:
return new(EDNS0_EDE)
case EDNS0ESU:
return &EDNS0_ESU{Code: EDNS0ESU}
default:
e := new(EDNS0_LOCAL)
e.Code = code
return e
}
}
// OPT is the EDNS0 RR appended to messages to convey extra (meta) information.
// See RFC 6891.
type OPT struct {
@ -39,7 +78,10 @@ func (rr *OPT) String() string {
if rr.Do() {
s += "flags: do; "
} else {
s += "flags: ; "
s += "flags:; "
}
if rr.Hdr.Ttl&0x7FFF != 0 {
s += fmt.Sprintf("MBZ: 0x%04x, ", rr.Hdr.Ttl&0x7FFF)
}
s += "udp: " + strconv.Itoa(int(rr.UDPSize()))
@ -59,6 +101,10 @@ func (rr *OPT) String() string {
s += "\n; SUBNET: " + o.String()
case *EDNS0_COOKIE:
s += "\n; COOKIE: " + o.String()
case *EDNS0_EXPIRE:
s += "\n; EXPIRE: " + o.String()
case *EDNS0_TCP_KEEPALIVE:
s += "\n; KEEPALIVE: " + o.String()
case *EDNS0_UL:
s += "\n; UPDATE LEASE: " + o.String()
case *EDNS0_LLQ:
@ -73,6 +119,10 @@ func (rr *OPT) String() string {
s += "\n; LOCAL OPT: " + o.String()
case *EDNS0_PADDING:
s += "\n; PADDING: " + o.String()
case *EDNS0_EDE:
s += "\n; EDE: " + o.String()
case *EDNS0_ESU:
s += "\n; ESU: " + o.String()
}
}
return s
@ -88,11 +138,11 @@ func (rr *OPT) len(off int, compression map[string]struct{}) int {
return l
}
func (rr *OPT) parse(c *zlexer, origin string) *ParseError {
panic("dns: internal error: parse should never be called on OPT")
func (*OPT) parse(c *zlexer, origin string) *ParseError {
return &ParseError{err: "OPT records do not have a presentation format"}
}
func (r1 *OPT) isDuplicate(r2 RR) bool { return false }
func (rr *OPT) isDuplicate(r2 RR) bool { return false }
// return the old value -> delete SetVersion?
@ -148,6 +198,16 @@ func (rr *OPT) SetDo(do ...bool) {
}
}
// Z returns the Z part of the OPT RR as a uint16 with only the 15 least significant bits used.
func (rr *OPT) Z() uint16 {
return uint16(rr.Hdr.Ttl & 0x7FFF)
}
// SetZ sets the Z part of the OPT RR, note only the 15 least significant bits of z are used.
func (rr *OPT) SetZ(z uint16) {
rr.Hdr.Ttl = rr.Hdr.Ttl&^0x7FFF | uint32(z&0x7FFF)
}
// EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to it.
type EDNS0 interface {
// Option returns the option code for the option.
@ -203,7 +263,7 @@ func (e *EDNS0_NSID) copy() EDNS0 { return &EDNS0_NSID{e.Code, e.Nsid}
// o.Hdr.Name = "."
// o.Hdr.Rrtype = dns.TypeOPT
// e := new(dns.EDNS0_SUBNET)
// e.Code = dns.EDNS0SUBNET
// e.Code = dns.EDNS0SUBNET // by default this is filled in through unpacking OPT packets (unpackDataOpt)
// e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
// e.SourceNetmask = 32 // 32 for IPV4, 128 for IPv6
// e.SourceScope = 0
@ -360,7 +420,7 @@ func (e *EDNS0_COOKIE) copy() EDNS0 { return &EDNS0_COOKIE{e.Code, e.C
// The EDNS0_UL (Update Lease) (draft RFC) option is used to tell the server to set
// an expiration on an update RR. This is helpful for clients that cannot clean
// up after themselves. This is a draft RFC and more information can be found at
// http://files.dns-sd.org/draft-sekar-dns-ul.txt
// https://tools.ietf.org/html/draft-sekar-dns-ul-02
//
// o := new(dns.OPT)
// o.Hdr.Name = "."
@ -370,24 +430,36 @@ func (e *EDNS0_COOKIE) copy() EDNS0 { return &EDNS0_COOKIE{e.Code, e.C
// e.Lease = 120 // in seconds
// o.Option = append(o.Option, e)
type EDNS0_UL struct {
Code uint16 // Always EDNS0UL
Lease uint32
Code uint16 // Always EDNS0UL
Lease uint32
KeyLease uint32
}
// Option implements the EDNS0 interface.
func (e *EDNS0_UL) Option() uint16 { return EDNS0UL }
func (e *EDNS0_UL) String() string { return strconv.FormatUint(uint64(e.Lease), 10) }
func (e *EDNS0_UL) copy() EDNS0 { return &EDNS0_UL{e.Code, e.Lease} }
func (e *EDNS0_UL) String() string { return fmt.Sprintf("%d %d", e.Lease, e.KeyLease) }
func (e *EDNS0_UL) copy() EDNS0 { return &EDNS0_UL{e.Code, e.Lease, e.KeyLease} }
// Copied: http://golang.org/src/pkg/net/dnsmsg.go
func (e *EDNS0_UL) pack() ([]byte, error) {
b := make([]byte, 4)
var b []byte
if e.KeyLease == 0 {
b = make([]byte, 4)
} else {
b = make([]byte, 8)
binary.BigEndian.PutUint32(b[4:], e.KeyLease)
}
binary.BigEndian.PutUint32(b, e.Lease)
return b, nil
}
func (e *EDNS0_UL) unpack(b []byte) error {
if len(b) < 4 {
switch len(b) {
case 4:
e.KeyLease = 0
case 8:
e.KeyLease = binary.BigEndian.Uint32(b[4:])
default:
return ErrBuf
}
e.Lease = binary.BigEndian.Uint32(b)
@ -440,7 +512,7 @@ func (e *EDNS0_LLQ) copy() EDNS0 {
return &EDNS0_LLQ{e.Code, e.Version, e.Opcode, e.Error, e.Id, e.LeaseLife}
}
// EDNS0_DUA implements the EDNS0 "DNSSEC Algorithm Understood" option. See RFC 6975.
// EDNS0_DAU implements the EDNS0 "DNSSEC Algorithm Understood" option. See RFC 6975.
type EDNS0_DAU struct {
Code uint16 // Always EDNS0DAU
AlgCode []uint8
@ -513,31 +585,47 @@ func (e *EDNS0_N3U) String() string {
}
func (e *EDNS0_N3U) copy() EDNS0 { return &EDNS0_N3U{e.Code, e.AlgCode} }
// EDNS0_EXPIRE implementes the EDNS0 option as described in RFC 7314.
// EDNS0_EXPIRE implements the EDNS0 option as described in RFC 7314.
type EDNS0_EXPIRE struct {
Code uint16 // Always EDNS0EXPIRE
Expire uint32
Empty bool // Empty is used to signal an empty Expire option in a backwards compatible way, it's not used on the wire.
}
// Option implements the EDNS0 interface.
func (e *EDNS0_EXPIRE) Option() uint16 { return EDNS0EXPIRE }
func (e *EDNS0_EXPIRE) String() string { return strconv.FormatUint(uint64(e.Expire), 10) }
func (e *EDNS0_EXPIRE) copy() EDNS0 { return &EDNS0_EXPIRE{e.Code, e.Expire} }
func (e *EDNS0_EXPIRE) copy() EDNS0 { return &EDNS0_EXPIRE{e.Code, e.Expire, e.Empty} }
func (e *EDNS0_EXPIRE) pack() ([]byte, error) {
if e.Empty {
return []byte{}, nil
}
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, e.Expire)
return b, nil
}
func (e *EDNS0_EXPIRE) unpack(b []byte) error {
if len(b) == 0 {
// zero-length EXPIRE query, see RFC 7314 Section 2
e.Empty = true
return nil
}
if len(b) < 4 {
return ErrBuf
}
e.Expire = binary.BigEndian.Uint32(b)
e.Empty = false
return nil
}
func (e *EDNS0_EXPIRE) String() (s string) {
if e.Empty {
return ""
}
return strconv.FormatUint(uint64(e.Expire), 10)
}
// The EDNS0_LOCAL option is used for local/experimental purposes. The option
// code is recommended to be within the range [EDNS0LOCALSTART, EDNS0LOCALEND]
// (RFC6891), although any unassigned code can actually be used. The content of
@ -588,57 +676,52 @@ func (e *EDNS0_LOCAL) unpack(b []byte) error {
// EDNS0_TCP_KEEPALIVE is an EDNS0 option that instructs the server to keep
// the TCP connection alive. See RFC 7828.
type EDNS0_TCP_KEEPALIVE struct {
Code uint16 // Always EDNSTCPKEEPALIVE
Length uint16 // the value 0 if the TIMEOUT is omitted, the value 2 if it is present;
Timeout uint16 // an idle timeout value for the TCP connection, specified in units of 100 milliseconds, encoded in network byte order.
Code uint16 // Always EDNSTCPKEEPALIVE
// 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 slice.
Timeout uint16
// Length is the option's length.
// Deprecated: this field is deprecated and is always equal to 0.
Length uint16
}
// Option implements the EDNS0 interface.
func (e *EDNS0_TCP_KEEPALIVE) Option() uint16 { return EDNS0TCPKEEPALIVE }
func (e *EDNS0_TCP_KEEPALIVE) pack() ([]byte, error) {
if e.Timeout != 0 && e.Length != 2 {
return nil, errors.New("dns: timeout specified but length is not 2")
if e.Timeout > 0 {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, e.Timeout)
return b, nil
}
if e.Timeout == 0 && e.Length != 0 {
return nil, errors.New("dns: timeout not specified but length is not 0")
}
b := make([]byte, 4+e.Length)
binary.BigEndian.PutUint16(b[0:], e.Code)
binary.BigEndian.PutUint16(b[2:], e.Length)
if e.Length == 2 {
binary.BigEndian.PutUint16(b[4:], e.Timeout)
}
return b, nil
return nil, nil
}
func (e *EDNS0_TCP_KEEPALIVE) unpack(b []byte) error {
if len(b) < 4 {
return ErrBuf
}
e.Length = binary.BigEndian.Uint16(b[2:4])
if e.Length != 0 && e.Length != 2 {
return errors.New("dns: length mismatch, want 0/2 but got " + strconv.FormatUint(uint64(e.Length), 10))
}
if e.Length == 2 {
if len(b) < 6 {
return ErrBuf
}
e.Timeout = binary.BigEndian.Uint16(b[4:6])
switch len(b) {
case 0:
case 2:
e.Timeout = binary.BigEndian.Uint16(b)
default:
return fmt.Errorf("dns: length mismatch, want 0/2 but got %d", len(b))
}
return nil
}
func (e *EDNS0_TCP_KEEPALIVE) String() (s string) {
s = "use tcp keep-alive"
if e.Length == 0 {
func (e *EDNS0_TCP_KEEPALIVE) String() string {
s := "use tcp keep-alive"
if e.Timeout == 0 {
s += ", timeout omitted"
} else {
s += fmt.Sprintf(", timeout %dms", e.Timeout*100)
}
return
return s
}
func (e *EDNS0_TCP_KEEPALIVE) copy() EDNS0 { return &EDNS0_TCP_KEEPALIVE{e.Code, e.Length, e.Timeout} }
func (e *EDNS0_TCP_KEEPALIVE) copy() EDNS0 { return &EDNS0_TCP_KEEPALIVE{e.Code, e.Timeout, e.Length} }
// EDNS0_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, for instance if
@ -657,3 +740,117 @@ func (e *EDNS0_PADDING) copy() EDNS0 {
copy(b, e.Padding)
return &EDNS0_PADDING{b}
}
// Extended DNS Error Codes (RFC 8914).
const (
ExtendedErrorCodeOther uint16 = iota
ExtendedErrorCodeUnsupportedDNSKEYAlgorithm
ExtendedErrorCodeUnsupportedDSDigestType
ExtendedErrorCodeStaleAnswer
ExtendedErrorCodeForgedAnswer
ExtendedErrorCodeDNSSECIndeterminate
ExtendedErrorCodeDNSBogus
ExtendedErrorCodeSignatureExpired
ExtendedErrorCodeSignatureNotYetValid
ExtendedErrorCodeDNSKEYMissing
ExtendedErrorCodeRRSIGsMissing
ExtendedErrorCodeNoZoneKeyBitSet
ExtendedErrorCodeNSECMissing
ExtendedErrorCodeCachedError
ExtendedErrorCodeNotReady
ExtendedErrorCodeBlocked
ExtendedErrorCodeCensored
ExtendedErrorCodeFiltered
ExtendedErrorCodeProhibited
ExtendedErrorCodeStaleNXDOMAINAnswer
ExtendedErrorCodeNotAuthoritative
ExtendedErrorCodeNotSupported
ExtendedErrorCodeNoReachableAuthority
ExtendedErrorCodeNetworkError
ExtendedErrorCodeInvalidData
)
// ExtendedErrorCodeToString maps extended error info codes to a human readable
// description.
var ExtendedErrorCodeToString = map[uint16]string{
ExtendedErrorCodeOther: "Other",
ExtendedErrorCodeUnsupportedDNSKEYAlgorithm: "Unsupported DNSKEY Algorithm",
ExtendedErrorCodeUnsupportedDSDigestType: "Unsupported DS Digest Type",
ExtendedErrorCodeStaleAnswer: "Stale Answer",
ExtendedErrorCodeForgedAnswer: "Forged Answer",
ExtendedErrorCodeDNSSECIndeterminate: "DNSSEC Indeterminate",
ExtendedErrorCodeDNSBogus: "DNSSEC Bogus",
ExtendedErrorCodeSignatureExpired: "Signature Expired",
ExtendedErrorCodeSignatureNotYetValid: "Signature Not Yet Valid",
ExtendedErrorCodeDNSKEYMissing: "DNSKEY Missing",
ExtendedErrorCodeRRSIGsMissing: "RRSIGs Missing",
ExtendedErrorCodeNoZoneKeyBitSet: "No Zone Key Bit Set",
ExtendedErrorCodeNSECMissing: "NSEC Missing",
ExtendedErrorCodeCachedError: "Cached Error",
ExtendedErrorCodeNotReady: "Not Ready",
ExtendedErrorCodeBlocked: "Blocked",
ExtendedErrorCodeCensored: "Censored",
ExtendedErrorCodeFiltered: "Filtered",
ExtendedErrorCodeProhibited: "Prohibited",
ExtendedErrorCodeStaleNXDOMAINAnswer: "Stale NXDOMAIN Answer",
ExtendedErrorCodeNotAuthoritative: "Not Authoritative",
ExtendedErrorCodeNotSupported: "Not Supported",
ExtendedErrorCodeNoReachableAuthority: "No Reachable Authority",
ExtendedErrorCodeNetworkError: "Network Error",
ExtendedErrorCodeInvalidData: "Invalid Data",
}
// StringToExtendedErrorCode is a map from human readable descriptions to
// extended error info codes.
var StringToExtendedErrorCode = reverseInt16(ExtendedErrorCodeToString)
// EDNS0_EDE option is used to return additional information about the cause of
// DNS errors.
type EDNS0_EDE struct {
InfoCode uint16
ExtraText string
}
// Option implements the EDNS0 interface.
func (e *EDNS0_EDE) Option() uint16 { return EDNS0EDE }
func (e *EDNS0_EDE) copy() EDNS0 { return &EDNS0_EDE{e.InfoCode, e.ExtraText} }
func (e *EDNS0_EDE) String() string {
info := strconv.FormatUint(uint64(e.InfoCode), 10)
if s, ok := ExtendedErrorCodeToString[e.InfoCode]; ok {
info += fmt.Sprintf(" (%s)", s)
}
return fmt.Sprintf("%s: (%s)", info, e.ExtraText)
}
func (e *EDNS0_EDE) pack() ([]byte, error) {
b := make([]byte, 2+len(e.ExtraText))
binary.BigEndian.PutUint16(b[0:], e.InfoCode)
copy(b[2:], []byte(e.ExtraText))
return b, nil
}
func (e *EDNS0_EDE) unpack(b []byte) error {
if len(b) < 2 {
return ErrBuf
}
e.InfoCode = binary.BigEndian.Uint16(b[0:])
e.ExtraText = string(b[2:])
return nil
}
// The EDNS0_ESU option for ENUM Source-URI Extension
type EDNS0_ESU struct {
Code uint16
Uri string
}
// Option implements the EDNS0 interface.
func (e *EDNS0_ESU) Option() uint16 { return EDNS0ESU }
func (e *EDNS0_ESU) String() string { return e.Uri }
func (e *EDNS0_ESU) copy() EDNS0 { return &EDNS0_ESU{e.Code, e.Uri} }
func (e *EDNS0_ESU) pack() ([]byte, error) { return []byte(e.Uri), nil }
func (e *EDNS0_ESU) unpack(b []byte) error {
e.Uri = string(b)
return nil
}

View File

@ -1,6 +1,7 @@
package dns
import (
"bytes"
"net"
"testing"
)
@ -109,3 +110,170 @@ func TestEDNS0_SUBNETUnpack(t *testing.T) {
}
}
}
func TestEDNS0_UL(t *testing.T) {
cases := []struct {
l uint32
kl uint32
}{
{0x01234567, 0},
{0x76543210, 0xFEDCBA98},
}
for _, c := range cases {
expect := EDNS0_UL{EDNS0UL, c.l, c.kl}
b, err := expect.pack()
if err != nil {
t.Fatalf("failed to pack: %v", err)
}
actual := EDNS0_UL{EDNS0UL, ^uint32(0), ^uint32(0)}
if err := actual.unpack(b); err != nil {
t.Fatalf("failed to unpack: %v", err)
}
if expect != actual {
t.Errorf("unpacked option is different; expected %v, got %v", expect, actual)
}
}
}
func TestZ(t *testing.T) {
e := &OPT{}
e.Hdr.Name = "."
e.Hdr.Rrtype = TypeOPT
e.SetVersion(8)
e.SetDo()
if e.Z() != 0 {
t.Errorf("expected Z of 0, got %d", e.Z())
}
e.SetZ(5)
if e.Z() != 5 {
t.Errorf("expected Z of 5, got %d", e.Z())
}
e.SetZ(0xFFFF)
if e.Z() != 0x7FFF {
t.Errorf("expected Z of 0x7FFFF, got %d", e.Z())
}
if e.Version() != 8 {
t.Errorf("expected version to still be 8, got %d", e.Version())
}
if !e.Do() {
t.Error("expected DO to be set")
}
}
func TestEDNS0_ESU(t *testing.T) {
p := []byte{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x29, 0x04,
0xC4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00,
0x04, 0x00, 0x24, 0x73, 0x69, 0x70, 0x3A, 0x2B,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x40, 0x74, 0x65, 0x73, 0x74, 0x2E, 0x63,
0x6F, 0x6D, 0x3B, 0x75, 0x73, 0x65, 0x72, 0x3D,
0x63, 0x67, 0x72, 0x61, 0x74, 0x65, 0x73,
}
m := new(Msg)
if err := m.Unpack(p); err != nil {
t.Fatalf("failed to unpack: %v", err)
}
opt := m.IsEdns0()
if opt == nil {
t.Fatalf("expected edns0 option")
}
if len(opt.Option) != 1 {
t.Fatalf("expected only one option: %v", opt.Option)
}
edns0 := opt.Option[0]
esu, ok := edns0.(*EDNS0_ESU)
if !ok {
t.Fatalf("expected option of type EDNS0_ESU, got %t", edns0)
}
expect := "sip:+123456789@test.com;user=cgrates"
if esu.Uri != expect {
t.Errorf("unpacked option is different; expected %v, got %v", expect, esu.Uri)
}
}
func TestEDNS0_TCP_KEEPALIVE_unpack(t *testing.T) {
cases := []struct {
name string
b []byte
expected uint16
expectedErr bool
}{
{
name: "empty",
b: []byte{},
expected: 0,
},
{
name: "timeout 1",
b: []byte{0, 1},
expected: 1,
},
{
name: "invalid",
b: []byte{0, 1, 3},
expectedErr: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
e := &EDNS0_TCP_KEEPALIVE{}
err := e.unpack(tc.b)
if err != nil && !tc.expectedErr {
t.Error("failed to unpack, expected no error")
}
if err == nil && tc.expectedErr {
t.Error("unpacked, but expected an error")
}
if e.Timeout != tc.expected {
t.Errorf("invalid timeout, actual: %d, expected: %d", e.Timeout, tc.expected)
}
})
}
}
func TestEDNS0_TCP_KEEPALIVE_pack(t *testing.T) {
cases := []struct {
name string
edns *EDNS0_TCP_KEEPALIVE
expected []byte
}{
{
name: "empty",
edns: &EDNS0_TCP_KEEPALIVE{
Code: EDNS0TCPKEEPALIVE,
Timeout: 0,
},
expected: nil,
},
{
name: "timeout 1",
edns: &EDNS0_TCP_KEEPALIVE{
Code: EDNS0TCPKEEPALIVE,
Timeout: 1,
},
expected: []byte{0, 1},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
b, err := tc.edns.pack()
if err != nil {
t.Error("expected no error")
}
if tc.expected == nil && b != nil {
t.Errorf("invalid result, expected nil")
}
res := bytes.Compare(b, tc.expected)
if res != 0 {
t.Errorf("invalid result, expected: %v, actual: %v", tc.expected, b)
}
})
}
}

View File

@ -16,7 +16,7 @@ func ExampleMX() {
m := new(dns.Msg)
m.SetQuestion("miek.nl.", dns.TypeMX)
m.RecursionDesired = true
r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
r, _, err := c.Exchange(m, net.JoinHostPort(config.Servers[0], config.Port))
if err != nil {
return
}
@ -39,7 +39,7 @@ func ExampleDS() {
zone := "miek.nl"
m.SetQuestion(dns.Fqdn(zone), dns.TypeDNSKEY)
m.SetEdns0(4096, true)
r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
r, _, err := c.Exchange(m, net.JoinHostPort(config.Servers[0], config.Port))
if err != nil {
return
}
@ -64,6 +64,7 @@ type APAIR struct {
func NewAPAIR() dns.PrivateRdata { return new(APAIR) }
func (rd *APAIR) String() string { return rd.addr[0].String() + " " + rd.addr[1].String() }
func (rd *APAIR) Parse(txt []string) error {
if len(txt) != 2 {
return errors.New("two addresses required for APAIR")
@ -121,21 +122,23 @@ func (rd *APAIR) Len() int {
func ExamplePrivateHandle() {
dns.PrivateHandle("APAIR", TypeAPAIR, NewAPAIR)
defer dns.PrivateHandleRemove(TypeAPAIR)
var oldId = dns.Id
dns.Id = func() uint16 { return 3 }
defer func() { dns.Id = oldId }()
rr, err := dns.NewRR("miek.nl. APAIR (1.2.3.4 1.2.3.5)")
if err != nil {
log.Fatal("could not parse APAIR record: ", err)
}
fmt.Println(rr)
// Output: miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5
fmt.Println(rr) // see first line of Output below
m := new(dns.Msg)
m.Id = 12345
m.SetQuestion("miek.nl.", TypeAPAIR)
m.Answer = append(m.Answer, rr)
fmt.Println(m)
// ;; opcode: QUERY, status: NOERROR, id: 12345
// Output: miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5
// ;; opcode: QUERY, status: NOERROR, id: 3
// ;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
//
// ;; QUESTION SECTION:

12
fuzz.go
View File

@ -1,7 +1,10 @@
//go:build fuzz
// +build fuzz
package dns
import "strings"
func Fuzz(data []byte) int {
msg := new(Msg)
@ -16,7 +19,14 @@ func Fuzz(data []byte) int {
}
func FuzzNewRR(data []byte) int {
if _, err := NewRR(string(data)); err != nil {
str := string(data)
// Do not fuzz lines that include the $INCLUDE keyword and hint the fuzzer
// at avoiding them.
// See GH#1025 for context.
if strings.Contains(strings.ToUpper(str), "$INCLUDE") {
return -1
}
if _, err := NewRR(str); err != nil {
return 0
}
return 1

View File

@ -78,7 +78,7 @@ func TestPackDataOpt(t *testing.T) {
// "0\x00\v\x00#\b00000\x00\x00\x00\x00\x00\x1a000" +
// "000\x00\x00\x00\x00\x1a000000\x00\x00\x00\x00\x1a0" +
// "00000\x00\v00\a0000000\x00"
// That byte sequence, when Unpack() and subsequential Pack() created a
// That byte sequence, when Unpack() and subsequent Pack() created a
// panic: runtime error: slice bounds out of range
// which was attributed to the fact that NSEC RR length computation was different (and smaller)
// then when within packDataNsec.
@ -111,7 +111,7 @@ func TestCrashNSEC(t *testing.T) {
// "0000\x00\x00000000\x00\x00200000" +
// "0\x00\v0000\x00\x00#\x0300\x00\x00\x00\x1a000" +
// "000\x00\v00\x0200\x00\x03000\x00"
// That byte sequence, when Unpack() and subsequential Pack() created a
// That byte sequence, when Unpack() and subsequent Pack() created a
// panic: runtime error: slice bounds out of range
// which was attributed to the fact that NSEC3 RR length computation was
// different (and smaller) then within NSEC3.pack (which relies on
@ -143,3 +143,127 @@ func TestCrashNSEC3(t *testing.T) {
t.Fatalf("expected length of %d, got %d", expectedLength, l)
}
}
// TestNewRRCommentLengthCrasherString test inputs to NewRR that generated crashes.
func TestNewRRCommentLengthCrasherString(t *testing.T) {
tests := []struct {
name string
in string
err string
}{
{
"HINFO1", " HINFO ;;;;;;;;;;;;;" +
";;;;;;;;\x00\x19;;;;;;;;;;" +
";\u007f;;;;;;;;;;;;;;;;;;" +
";;}mP_Qq_3sJ_1_84X_5" +
"45iW_3K4p8J8_v9_LT3_" +
"6_0l_3D4VT3xq6N_3K__" +
"_U_xX2m;;;;;;(;;;;;;" +
";;;;;;;;;;;;;;;\x1d;;;;" +
";;;;;;-0x804dBDe8ba " +
"\t \t\tr HINFO \" \t\t\tve" +
"k1xH11e__P6_dk1_51bo" +
"g8gJK1V_O_v84_Bw4_1_" +
"72jQ3_0J3V_S5iYn4h5X" +
"R_2n___51J nN_ \t\tm " +
"aa_XO4_5\t \t\t \t\tg6b" +
"p_KI_1_YWc_K8c2b___A" +
"e_Y1m__4Y_R_avy6t08x" +
"b5Cp9_7uS_yLa\t\t\t d " +
"EKe1Q83vS___ a \t\t " +
"\tmP_Qq_3sJ_1_84X_545" +
"iW_3K4p8J8_v9_LT3_6_" +
"0l_3D4VT3xq6N_3K___U" +
"_xX2\"\" \t \t_fL Ogl5" +
"_09i_9__3O7C__QMAG2U" +
"35IO8RRU6aJ9_6_57_6_" +
"b05BMoX5I__4833_____" +
"yfD_2_OPs__sqzM_pqQi" +
"_\t\t \tN__GuY4_Trath_0" +
"yy___cAK_a__0J0q5 L_" +
"p63Fzdva_Lb_29V7_R__" +
"Go_H2_8m_4__FJM5B_Y5" +
"Slw_ghp_55l_X2_Pnt6Y" +
"_Wd_hM7jRZ_\t\t \tm \t" +
" \t\ta md rK \x00 7_\"sr " +
"- sg o -0x804dBDe8b" +
"a \t \t\tN_W6J3PBS_W__C" +
"yJu__k6F_jY0INI_LC27" +
"7x14b_1b___Y8f_K_3y_" +
"0055yaP_LKu_72g_T_32" +
"iBk1Zm_o 9i1P44_S0_" +
"_4AXUpo2__H55tL_g78_" +
"8V_8l0yg6bp_KI_1_YWc" +
"_K8c2b \t \tmaa_XO4_5" +
"rg6bp_KI_1_YWc_K8c2b" +
" _C20w i_4 \t\t u_k d" +
" rKsg09099 \"\"2335779" +
"05047986112651e025 \t" +
" \t\tN_W6J3PBS_W__CyJu" +
"__k6F_jY0INI_LC277x1" +
"4b_1b___Y8f_K_3y_005" +
"5yaP_LKu_72g_T_32iBk" +
"1Zm_o 9i1P44_S0__4A" +
"XUpo2__H55tL_g78_8V_" +
"8l0y_9K9_C__6af__wj_" +
"UbSYy_ge29S_s_Qe259q" +
"_kGod \t\t\t\t :0xb1AF1F" +
"b71D2ACeaB3FEce2ssg " +
"o dr-0x804dBDe8ba \t " +
"\t\t$ Y5 _BzOc6S_Lk0K" +
"y43j1TzV__9367tbX56_" +
"6B3__q6_v8_4_0_t_2q_" +
"nJ2gV3j9_tkOrx_H__a}" +
"mT 0g6bp_KI_1_YWc_K8" +
"c2b\t_ a\t \t54KM8f9_63" +
"zJ2Q_c1_C_Zf4ICF4m0q" +
"_RVm_3Zh4vr7yI_H2 a" +
" m 0yq__TiqA_FQBv_SS" +
"_Hm_8T8__M8F2_53TTo_" +
"k_o2__u_W6Vr__524q9l" +
"9CQsC_kOU___g_94 \"" +
" ~a_j_16_6iUSu_96V1W" +
"5r01j____gn157__8_LO" +
"0y_08Jr6OR__WF8__JK_" +
"N_wx_k_CGB_SjJ9R74i_" +
"7_1t_6 m NULLNULLNUL" +
"L \t \t\t\t drK\t\x00 7_\"\" 5" +
"_5_y732S43__D_8U9FX2" +
"27_k\t\tg6bp_KI_1_YWc_" +
"K8c2b_J_wx8yw1CMw27j" +
"___f_a8uw_ Er9gB_L2 " +
"\t\t \t\t\tm aa_XO4_5 Y_" +
" I_T7762_zlMi_n8_FjH" +
"vy62p__M4S_8__r092af" +
"P_T_vhp6__SA_jVF13c5" +
"2__8J48K__S4YcjoY91X" +
"_iNf06 am aa_XO4_5\t" +
" d _ am_SYY4G__2h4QL" +
"iUIDd \t\t \tXXp__KFjR" +
"V__JU3o\"\" d \t_Iks_ " +
"aa_XO4_5<g6bp_KI_1_Y" +
"Wc_K8c2b _BzOc6S_Lk0" +
"Ky43j1TzV__9367tbX56" +
"_6B3__q6_v8_4_0_t_2q" +
"_nJ2gV3j9_tkOrx_H__ " +
"a\t_Iks_ \\ ma 0_58_r1" +
"y8jib_FaV_C_e \t \td\"\"" +
" ^Dy_0 \t\t \t ;;;;;;;" +
";;;;;;;;;;;",
`dns: bad HINFO Fields: "comment length insufficient for parsing" at line: 1:1951`,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := NewRR(tc.in)
if err == nil {
t.Errorf("Expecting error for crasher line %s", tc.in)
}
if tc.err != err.Error() {
t.Errorf("Expecting error %s, got %s", tc.err, err.Error())
}
})
}
}

View File

@ -20,13 +20,13 @@ import (
// of $ after that are interpreted.
func (zp *ZoneParser) generate(l lex) (RR, bool) {
token := l.token
step := 1
step := int64(1)
if i := strings.IndexByte(token, '/'); i >= 0 {
if i+1 == len(token) {
return zp.setParseError("bad step in $GENERATE range", l)
}
s, err := strconv.Atoi(token[i+1:])
s, err := strconv.ParseInt(token[i+1:], 10, 64)
if err != nil || s <= 0 {
return zp.setParseError("bad step in $GENERATE range", l)
}
@ -40,20 +40,24 @@ func (zp *ZoneParser) generate(l lex) (RR, bool) {
return zp.setParseError("bad start-stop in $GENERATE range", l)
}
start, err := strconv.Atoi(sx[0])
start, err := strconv.ParseInt(sx[0], 10, 64)
if err != nil {
return zp.setParseError("bad start in $GENERATE range", l)
}
end, err := strconv.Atoi(sx[1])
end, err := strconv.ParseInt(sx[1], 10, 64)
if err != nil {
return zp.setParseError("bad stop in $GENERATE range", l)
}
if end < 0 || start < 0 || end < start {
if end < 0 || start < 0 || end < start || (end-start)/step > 65535 {
return zp.setParseError("bad range in $GENERATE range", l)
}
zp.c.Next() // _BLANK
// _BLANK
l, ok := zp.c.Next()
if !ok || l.value != zBlank {
return zp.setParseError("garbage after $GENERATE range", l)
}
// Create a complete new string, which we then parse again.
var s string
@ -81,6 +85,7 @@ func (zp *ZoneParser) generate(l lex) (RR, bool) {
}
zp.sub = NewZoneParser(r, zp.origin, zp.file)
zp.sub.includeDepth, zp.sub.includeAllowed = zp.includeDepth, zp.includeAllowed
zp.sub.generateDisallowed = true
zp.sub.SetDefaultTTL(defaultTtl)
return zp.subNext()
}
@ -89,10 +94,10 @@ type generateReader struct {
s string
si int
cur int
start int
end int
step int
cur int64
start int64
end int64
step int64
mod bytes.Buffer
@ -168,7 +173,7 @@ func (r *generateReader) ReadByte() (byte, error) {
return '$', nil
}
var offset int
var offset int64
// Search for { and }
if r.s[si+1] == '{' {
@ -203,7 +208,7 @@ func (r *generateReader) ReadByte() (byte, error) {
}
// Convert a $GENERATE modifier 0,0,d to something Printf can deal with.
func modToPrintf(s string) (string, int, string) {
func modToPrintf(s string) (string, int64, string) {
// Modifier is { offset [ ,width [ ,base ] ] } - provide default
// values for optional width and type, if necessary.
var offStr, widthStr, base string
@ -224,12 +229,12 @@ func modToPrintf(s string) (string, int, string) {
return "", 0, "bad base in $GENERATE"
}
offset, err := strconv.Atoi(offStr)
offset, err := strconv.ParseInt(offStr, 10, 64)
if err != nil {
return "", 0, "bad offset in $GENERATE"
}
width, err := strconv.Atoi(widthStr)
width, err := strconv.ParseInt(widthStr, 10, 64)
if err != nil || width < 0 || width > 255 {
return "", 0, "bad width in $GENERATE"
}

View File

@ -61,19 +61,24 @@ $GENERATE 0-1/0 dhcp-${0,4,d} A 10.0.0.$
`, true},
{`@ IN SOA ns.test. hostmaster.test. ( 1 8h 2h 7d 1d )
$GENERATE 0-1 $$INCLUDE ` + tmpdir + string(filepath.Separator) + `${0,4,d}.conf
`, false},
{`@ IN SOA ns.test. hostmaster.test. ( 1 8h 2h 7d 1d )
$GENERATE 0-1 dhcp-${0,4,d} A 10.0.0.$
$GENERATE 0-2 dhcp-${0,4,d} A 10.1.0.$
`, false},
}
Outer:
for i := range tests {
for tok := range ParseZone(strings.NewReader(tests[i].zone), "test.", "test") {
if tok.Error != nil {
if !tests[i].fail {
t.Errorf("expected \n\n%s\nto be parsed, but got %v", tests[i].zone, tok.Error)
}
continue Outer
}
z := NewZoneParser(strings.NewReader(tests[i].zone), "test.", "test")
z.SetIncludeAllowed(true)
for _, ok := z.Next(); ok; _, ok = z.Next() {
}
if tests[i].fail {
err := z.Err()
if err != nil && !tests[i].fail {
t.Errorf("expected \n\n%s\nto be parsed, but got %v", tests[i].zone, err)
} else if err == nil && tests[i].fail {
t.Errorf("expected \n\n%s\nto fail, but got no error", tests[i].zone)
}
}
@ -157,7 +162,7 @@ func TestGenerateModToPrintf(t *testing.T) {
tests := []struct {
mod string
wantFmt string
wantOffset int
wantOffset int64
wantErr bool
}{
{"0,0,d", "%d", 0, false},
@ -204,3 +209,27 @@ $GENERATE 32-158 dhcp-${-32,4,d} A 10.0.0.$
}
}
}
func TestCrasherString(t *testing.T) {
tests := []struct {
in string
err string
}{
{"$GENERATE 0-300103\"$$GENERATE 2-2", "bad range in $GENERATE"},
{"$GENERATE 0-5414137360", "bad range in $GENERATE"},
{"$GENERATE 11522-3668518066406258", "bad range in $GENERATE"},
{"$GENERATE 0-200\"(;00000000000000\n$$GENERATE 0-0", "dns: garbage after $GENERATE range: \"\\\"\" at line: 1:16"},
{"$GENERATE 6-2048 $$GENERATE 6-036160 $$$$ORIGIN \\$", `dns: nested $GENERATE directive not allowed: "6-036160" at line: 1:19`},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
_, err := NewRR(tc.in)
if err == nil {
t.Errorf("Expecting error for crasher line %s", tc.in)
}
if !strings.Contains(err.Error(), tc.err) {
t.Errorf("Expecting error %s, got %s", tc.err, err.Error())
}
})
}
}

12
go.mod
View File

@ -1,12 +1,10 @@
module github.com/miekg/dns
go 1.12
go 1.14
require (
golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297
golang.org/x/sync v0.0.0-20190423024810-112230192c58
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd
golang.org/x/text v0.3.2 // indirect
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18 // indirect
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2
)

41
go.sum
View File

@ -1,26 +1,33 @@
golang.org/x/crypto v0.0.0-20181001203147-e3636079e1a4 h1:Vk3wNqEZwyGyei9yq5ekj7frek2u7HUfffJ1/opblzc=
golang.org/x/crypto v0.0.0-20181001203147-e3636079e1a4/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472 h1:Gv7RPwsi3eZ2Fgewe3CBsuOebPwO27PoXzRpJPsvSSM=
golang.org/x/crypto v0.0.0-20190829043050-9756ffdc2472/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3 h1:dgd4x4kJt7G4k4m93AYLzM8Ni6h2qLTfh9n9vXJT3/0=
golang.org/x/net v0.0.0-20180926154720-4dfa2610cdf3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297 h1:k7pJ2yAPLPgbskkFdhRCsA77k2fySZ1zf2zCjvQCiIM=
golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985 h1:4CSI6oo7cOjJKajidEljs9h+uP0rRZBPPPhcCbj5mw8=
golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611 h1:O33LKL7WyJgjN9CvxfTIomjIClbd/Kq86/iipowHQU0=
golang.org/x/sys v0.0.0-20180928133829-e4b3c5e90611/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd h1:DBH9mDw0zluJT/R+nGuV3jWFWLFaHyYZWD4tOT+cjn0=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2 h1:BonxutuHCTL0rBDnZlKjpGIQFTjyUVTexFOdWkB6Fg0=
golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

31
hash.go Normal file
View File

@ -0,0 +1,31 @@
package dns
import (
"bytes"
"crypto"
"hash"
)
// identityHash will not hash, it only buffers the data written into it and returns it as-is.
type identityHash struct {
b *bytes.Buffer
}
// Implement the hash.Hash interface.
func (i identityHash) Write(b []byte) (int, error) { return i.b.Write(b) }
func (i identityHash) Size() int { return i.b.Len() }
func (i identityHash) BlockSize() int { return 1024 }
func (i identityHash) Reset() { i.b.Reset() }
func (i identityHash) Sum(b []byte) []byte { return append(b, i.b.Bytes()...) }
func hashFromAlgorithm(alg uint8) (hash.Hash, crypto.Hash, error) {
hashnumber, ok := AlgorithmToHash[alg]
if !ok {
return nil, 0, ErrAlg
}
if hashnumber == 0 {
return identityHash{b: &bytes.Buffer{}}, hashnumber, nil
}
return hashnumber.New(), hashnumber, nil
}

View File

@ -7,24 +7,6 @@ import (
"testing"
)
func TestTCPRtt(t *testing.T) {
m := new(Msg)
m.RecursionDesired = true
m.SetQuestion("example.org.", TypeA)
c := &Client{}
for _, proto := range []string{"udp", "tcp"} {
c.Net = proto
_, rtt, err := c.Exchange(m, "8.8.4.4:53")
if err != nil {
t.Fatal(err)
}
if rtt == 0 {
t.Fatalf("expecting non zero rtt %s, got zero", c.Net)
}
}
}
func TestNSEC3MissingSalt(t *testing.T) {
rr := testRR("ji6neoaepv8b5o6k4ev33abha8ht9fgc.example. NSEC3 1 1 12 aabbccdd K8UDEMVP1J2F7EG6JEBPS17VP3N8I58H")
m := new(Msg)

199
labels.go
View File

@ -10,32 +10,30 @@ package dns
// escaped dots (\.) for instance.
// s must be a syntactically valid domain name, see IsDomainName.
func SplitDomainName(s string) (labels []string) {
if len(s) == 0 {
if s == "" {
return nil
}
if s == "." {
return nil
}
// offset of the final '.' or the length of the name
var fqdnEnd int
fqdnEnd := 0 // offset of the final '.' or the length of the name
idx := Split(s)
begin := 0
if IsFqdn(s) {
fqdnEnd = len(s) - 1
} else {
fqdnEnd = len(s)
}
var (
begin int
off int
end bool
)
for {
off, end = NextLabel(s, off)
if end {
break
switch len(idx) {
case 0:
return nil
case 1:
// no-op
default:
for _, end := range idx[1:] {
labels = append(labels, s[begin:end-1])
begin = end
}
labels = append(labels, s[begin:off-1])
begin = off
}
return append(labels, s[begin:fqdnEnd])
}
@ -54,50 +52,52 @@ func CompareDomainName(s1, s2 string) (n int) {
return 0
}
j1 := len(s1)
if s1[j1-1] == '.' {
j1--
l1 := Split(s1)
l2 := Split(s2)
j1 := len(l1) - 1 // end
i1 := len(l1) - 2 // start
j2 := len(l2) - 1
i2 := len(l2) - 2
// the second check can be done here: last/only label
// before we fall through into the for-loop below
if equal(s1[l1[j1]:], s2[l2[j2]:]) {
n++
} else {
return
}
j2 := len(s2)
if s2[j2-1] == '.' {
j2--
}
var i1, i2 int
for {
i1 = prevLabel(s1, j1-1)
i2 = prevLabel(s2, j2-1)
if equal(s1[i1:j1], s2[i2:j2]) {
if i1 < 0 || i2 < 0 {
break
}
if equal(s1[l1[i1]:l1[j1]], s2[l2[i2]:l2[j2]]) {
n++
} else {
break
}
if i1 == 0 || i2 == 0 {
break
}
j1 = i1 - 2
j2 = i2 - 2
j1--
i1--
j2--
i2--
}
return
}
// CountLabel counts the the number of labels in the string s.
// CountLabel counts the number of labels in the string s.
// s must be a syntactically valid domain name.
func CountLabel(s string) int {
func CountLabel(s string) (labels int) {
if s == "." {
return 0
return
}
labels := 1
for i := 0; i < len(s)-1; i++ {
c := s[i]
if c == '\\' {
i++
continue
}
if c == '.' {
labels++
off := 0
end := false
for {
off, end = NextLabel(s, off)
labels++
if end {
return
}
}
return labels
}
// Split splits a name s into its label indexes.
@ -122,74 +122,68 @@ func Split(s string) []int {
}
// NextLabel returns the index of the start of the next label in the
// string s starting at offset.
// string s starting at offset. A negative offset will cause a panic.
// The bool end is true when the end of the string has been reached.
// Also see PrevLabel.
func NextLabel(s string, offset int) (i int, end bool) {
if s == "" {
return 0, true
}
for i = offset; i < len(s)-1; i++ {
c := s[i]
if c == '\\' {
i++
if s[i] != '.' {
continue
}
if c == '.' {
return i + 1, false
j := i - 1
for j >= 0 && s[j] == '\\' {
j--
}
if (j-i)%2 == 0 {
continue
}
return i + 1, false
}
return i + 1, true
}
func prevLabel(s string, offset int) int {
for i := offset; i >= 0; i-- {
if s[i] == '.' {
if i == 0 || s[i-1] != '\\' {
return i + 1 // the '.' is not escaped
}
// We are at '\.' and need to check if the '\' itself is escaped.
// We do this by walking backwards from '\.' and counting the
// number of '\' we encounter. If the number of '\' is even
// (though here it's actually odd since we start at '\.') the '\'
// is escaped.
j := i - 2
for ; j >= 0 && s[j] == '\\'; j-- {
}
// An odd number here indicates that the '\' preceding the '.'
// is escaped.
if (i-j)&1 == 1 {
return i + 1
}
i = j + 1
}
}
return 0
}
// PrevLabel returns the index of the label when starting from the right and
// jumping n labels to the left.
// The bool start is true when the start of the string has been overshot.
// Also see NextLabel.
func PrevLabel(s string, n int) (i int, start bool) {
if s == "." {
if s == "" {
return 0, true
}
if n == 0 {
return len(s), false
}
i = len(s) - 1
if s[i] == '.' {
i--
l := len(s) - 1
if s[l] == '.' {
l--
}
for ; n > 0; n-- {
i = prevLabel(s, i)
if i == 0 {
break
for ; l >= 0 && n > 0; l-- {
if s[l] != '.' {
continue
}
j := l - 1
for j >= 0 && s[j] == '\\' {
j--
}
if (j-l)%2 == 0 {
continue
}
n--
if n == 0 {
return l + 1, false
}
i -= 2
}
if n > 0 {
return 0, true
}
return i + 2, false
return 0, n > 1
}
// equal compares a and b while ignoring case. It returns true when equal otherwise false.
@ -200,19 +194,18 @@ func equal(a, b string) bool {
if la != lb {
return false
}
if a != b {
// case-insensitive comparison
for i := la - 1; i >= 0; i-- {
ai := a[i]
bi := b[i]
if ai != bi {
if bi < ai {
bi, ai = ai, bi
}
if !('A' <= ai && ai <= 'Z' && bi == ai+'a'-'A') {
return false
}
}
for i := la - 1; i >= 0; i-- {
ai := a[i]
bi := b[i]
if ai >= 'A' && ai <= 'Z' {
ai |= 'a' - 'A'
}
if bi >= 'A' && bi <= 'Z' {
bi |= 'a' - 'A'
}
if ai != bi {
return false
}
}
return true

View File

@ -1,50 +1,56 @@
package dns
import (
"strings"
"testing"
)
import "testing"
func TestCompareDomainName(t *testing.T) {
tests := []struct {
s1, s2 string
expected int
}{
{"www.miek.nl.", "miek.nl.", 2},
{"miek.nl.", "www.bla.nl.", 1},
{"www.bla.nl.", "nl.www.bla.", 0},
{"www.miek.nl.", "nl.", 1},
{"www.miek.nl.", "miek.nl.", 2},
{"www.miek.nl.", ".", 0},
{".", ".", 0},
{"test.com.", "TEST.COM.", 2},
{"a.b.c.d.e.f.", "a.b.c.d.e.", 0},
{"a.b.c.d.e.", "a.b.c.d.e.", 5},
s1 := "www.miek.nl."
s2 := "miek.nl."
s3 := "www.bla.nl."
s4 := "nl.www.bla."
s5 := "nl."
s6 := "miek.nl."
if CompareDomainName(s1, s2) != 2 {
t.Errorf("%s with %s should be %d", s1, s2, 2)
}
for _, x := range tests {
if i := CompareDomainName(x.s1, x.s2); i != x.expected {
t.Errorf("%s with %s should be %d got: %d", x.s1, x.s2, x.expected, i)
}
if CompareDomainName(s1, s3) != 1 {
t.Errorf("%s with %s should be %d", s1, s3, 1)
}
if CompareDomainName(s3, s4) != 0 {
t.Errorf("%s with %s should be %d", s3, s4, 0)
}
// Non qualified tests
if CompareDomainName(s1, s5) != 1 {
t.Errorf("%s with %s should be %d", s1, s5, 1)
}
if CompareDomainName(s1, s6) != 2 {
t.Errorf("%s with %s should be %d", s1, s5, 2)
}
if CompareDomainName(s1, ".") != 0 {
t.Errorf("%s with %s should be %d", s1, s5, 0)
}
if CompareDomainName(".", ".") != 0 {
t.Errorf("%s with %s should be %d", ".", ".", 0)
}
if CompareDomainName("test.com.", "TEST.COM.") != 2 {
t.Errorf("test.com. and TEST.COM. should be an exact match")
}
}
func TestSplit(t *testing.T) {
splitter := map[string]int{
"www.miek.nl.": 3,
"www.miek.nl": 3,
"www..miek.nl": 4,
`www\.miek.nl.`: 2,
`www\\.miek.nl.`: 3,
`\\.miek.nl.`: 3,
`\\\.miek.nl.`: 2,
`\\\\.miek.nl.`: 3,
`www.miek\\\\.nl.`: 3,
`www.miek\\\.nl.`: 2,
".": 0,
"nl.": 1,
"nl": 1,
"com.": 1,
".com.": 2,
"www.miek.nl.": 3,
"www.miek.nl": 3,
"www..miek.nl": 4,
`www\.miek.nl.`: 2,
`www\\.miek.nl.`: 3,
`www\\\.miek.nl.`: 2,
".": 0,
"nl.": 1,
"nl": 1,
"com.": 1,
".com.": 2,
}
for s, i := range splitter {
if x := len(Split(s)); x != i {
@ -74,12 +80,32 @@ func TestSplit2(t *testing.T) {
}
}
func TestNextLabel(t *testing.T) {
type next struct {
string
int
}
nexts := map[next]int{
{"", 1}: 0,
{"www.miek.nl.", 0}: 4,
{"www.miek.nl.", 4}: 9,
{"www.miek.nl.", 9}: 12,
}
for s, i := range nexts {
x, ok := NextLabel(s.string, s.int)
if i != x {
t.Errorf("label should be %d, got %d, %t: next %d, %s", i, x, ok, s.int, s.string)
}
}
}
func TestPrevLabel(t *testing.T) {
type prev struct {
string
int
}
prever := map[prev]int{
{"", 1}: 0,
{"www.miek.nl.", 0}: 12,
{"www.miek.nl.", 1}: 9,
{"www.miek.nl.", 2}: 4,
@ -93,21 +119,11 @@ func TestPrevLabel(t *testing.T) {
{"www.miek.nl.", 3}: 0,
{"www.miek.nl", 3}: 0,
{"a.b.c.", 1}: 4,
{"a.b.c", 1}: 4,
}
// make sure we are safe when the label begins with a possibly escaped '.'
for i := 1; i < 8; i++ {
s := strings.Repeat(`\`, i) + "."
prever[prev{s, 0}] = i + 1
}
for s, i := range prever {
x, ok := PrevLabel(s.string, s.int)
if i != x {
t.Errorf("label should be %d, got %d, %t: preving %d, %s", i, x, ok, s.int, s.string)
t.Errorf("label should be %d, got %d, %t: previous %d, %s", i, x, ok, s.int, s.string)
}
}
}
@ -160,7 +176,10 @@ func TestIsDomainName(t *testing.T) {
lab int
}
names := map[string]*ret{
"..": {false, 1},
".": {true, 1},
"..": {false, 0},
"double-dot..test": {false, 1},
".leading-dot.test": {false, 0},
"@.": {true, 1},
"www.example.com": {true, 3},
"www.e%ample.com": {true, 3},
@ -215,23 +234,18 @@ func TestIsFqdnEscaped(t *testing.T) {
}
}
func TestEqual(t *testing.T) {
type testcase struct {
a, b string
match bool
}
tests := []testcase{
{"a", "a", true},
{"a", "A", true},
{"A", "a", true},
{"A", "b", false},
{"www.example.com.", "www.exAmpLe.com.", true},
{"www.example.com.", "www.exAmpLe.org.", false},
}
for _, x := range tests {
eq := equal(x.a, x.b)
if eq != x.match {
t.Errorf("%+v: want: %t got: %t", x, x.match, eq)
func TestCanonicalName(t *testing.T) {
for s, expect := range map[string]string{
"": ".",
".": ".",
"tld": "tld.",
"tld.": "tld.",
"example.test": "example.test.",
"Lower.CASE.test.": "lower.case.test.",
"*.Test": "*.test.",
} {
if got := CanonicalName(s); got != expect {
t.Errorf("CanonicalName(%q) = %q, expected %q", s, got, expect)
}
}
}
@ -263,3 +277,63 @@ func BenchmarkIsSubDomain(b *testing.B) {
IsSubDomain("miek.nl.", "aa.example.com.")
}
}
func BenchmarkNextLabelSimple(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
NextLabel("www.example.com", 0)
NextLabel("www.example.com", 5)
NextLabel("www.example.com", 12)
}
}
func BenchmarkPrevLabelSimple(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
PrevLabel("www.example.com", 0)
PrevLabel("www.example.com", 5)
PrevLabel("www.example.com", 12)
}
}
func BenchmarkNextLabelComplex(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
NextLabel(`www\.example.com`, 0)
NextLabel(`www\\.example.com`, 0)
NextLabel(`www\\\.example.com`, 0)
}
}
func BenchmarkPrevLabelComplex(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
PrevLabel(`www\.example.com`, 10)
PrevLabel(`www\\.example.com`, 10)
PrevLabel(`www\\\.example.com`, 10)
}
}
func BenchmarkNextLabelMixed(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
NextLabel("www.example.com", 0)
NextLabel(`www\.example.com`, 0)
NextLabel("www.example.com", 5)
NextLabel(`www\\.example.com`, 0)
NextLabel("www.example.com", 12)
NextLabel(`www\\\.example.com`, 0)
}
}
func BenchmarkPrevLabelMixed(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
PrevLabel("www.example.com", 0)
PrevLabel(`www\.example.com`, 10)
PrevLabel("www.example.com", 5)
PrevLabel(`www\\.example.com`, 10)
PrevLabel("www.example.com", 12)
PrevLabel(`www\\\.example.com`, 10)
}
}

View File

@ -396,10 +396,19 @@ func TestMsgCompressLengthLargeRecordsWithPaddingPermutation(t *testing.T) {
}
func TestMsgCompressLengthLargeRecordsAllValues(t *testing.T) {
// we want to cross the 14 (16384) bit boundary here, so we build it up to just below and go slightly over.
msg := new(Msg)
msg.Compress = true
msg.SetQuestion("redis.service.consul.", TypeSRV)
for i := 0; i < 900; i++ {
for i := 0; i < 170; i++ {
target := fmt.Sprintf("host-redis-%d-%d.test.acme.com.node.dc1.consul.", i/256, i%256)
msg.Answer = append(msg.Answer, &SRV{Hdr: RR_Header{Name: "redis.service.consul.", Class: 1, Rrtype: TypeSRV, Ttl: 0x3c}, Port: 0x4c57, Target: target})
msg.Extra = append(msg.Extra, &CNAME{Hdr: RR_Header{Name: target, Class: ClassINET, Rrtype: TypeCNAME, Ttl: 0x3c}, Target: fmt.Sprintf("fx.168.%d.%d.", i/256, i%256)})
}
// msg.Len() == 15458
// msg.Len() == 16470 at 180
for i := 170; i < 181; i++ {
target := fmt.Sprintf("host-redis-%d-%d.test.acme.com.node.dc1.consul.", i/256, i%256)
msg.Answer = append(msg.Answer, &SRV{Hdr: RR_Header{Name: "redis.service.consul.", Class: 1, Rrtype: TypeSRV, Ttl: 0x3c}, Port: 0x4c57, Target: target})
msg.Extra = append(msg.Extra, &CNAME{Hdr: RR_Header{Name: target, Class: ClassINET, Rrtype: TypeCNAME, Ttl: 0x3c}, Target: fmt.Sprintf("fx.168.%d.%d.", i/256, i%256)})

View File

@ -1,3 +1,4 @@
//go:build !go1.11 || (!aix && !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd)
// +build !go1.11 !aix,!darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd
package dns

View File

@ -1,3 +1,4 @@
//go:build go1.11 && (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd)
// +build go1.11
// +build aix darwin dragonfly freebsd linux netbsd openbsd

129
msg.go
View File

@ -11,14 +11,12 @@ package dns
//go:generate go run msg_generate.go
import (
crand "crypto/rand"
"crypto/rand"
"encoding/binary"
"fmt"
"math/big"
"math/rand"
"strconv"
"strings"
"sync"
)
const (
@ -73,53 +71,23 @@ var (
ErrTime error = &Error{err: "bad time"} // ErrTime indicates a timing error in TSIG authentication.
)
// Id by default, returns a 16 bits random number to be used as a
// message id. The random provided should be good enough. This being a
// variable the function can be reassigned to a custom function.
// For instance, to make it return a static value:
// 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 Id = id
var (
idLock sync.Mutex
idRand *rand.Rand
)
// id returns a 16 bits random number to be used as a
// message id. The random provided should be good enough.
func id() uint16 {
idLock.Lock()
if idRand == nil {
// This (partially) works around
// https://github.com/golang/go/issues/11833 by only
// seeding idRand upon the first call to id.
var seed int64
var buf [8]byte
if _, err := crand.Read(buf[:]); err == nil {
seed = int64(binary.LittleEndian.Uint64(buf[:]))
} else {
seed = rand.Int63()
}
idRand = rand.New(rand.NewSource(seed))
var output uint16
err := binary.Read(rand.Reader, binary.BigEndian, &output)
if err != nil {
panic("dns: reading random id failed: " + err.Error())
}
// The call to idRand.Uint32 must be within the
// mutex lock because *rand.Rand is not safe for
// concurrent use.
//
// There is no added performance overhead to calling
// idRand.Uint32 inside a mutex lock over just
// calling rand.Uint32 as the global math/rand rng
// is internally protected by a sync.Mutex.
id := uint16(idRand.Uint32())
idLock.Unlock()
return id
return output
}
// MsgHdr is a a manually-unpacked version of (id, bits).
@ -297,6 +265,11 @@ loop:
wasDot = false
case '.':
if i == 0 && len(s) > 1 {
// leading dots are not legal except for the root zone
return len(msg), ErrRdata
}
if wasDot {
// two dots back to back is not legal
return len(msg), ErrRdata
@ -430,17 +403,12 @@ Loop:
return "", lenmsg, ErrLongDomain
}
for _, b := range msg[off : off+c] {
switch b {
case '.', '(', ')', ';', ' ', '@':
fallthrough
case '"', '\\':
if isDomainNameLabelSpecial(b) {
s = append(s, '\\', b)
default:
if b < ' ' || b > '~' { // unprintable, use \DDD
s = append(s, escapeByte(b)...)
} else {
s = append(s, b)
}
} else if b < ' ' || b > '~' {
s = append(s, escapeByte(b)...)
} else {
s = append(s, b)
}
}
s = append(s, '.')
@ -661,11 +629,18 @@ func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err
rr = &RFC3597{Hdr: h}
}
if noRdata(h) {
return rr, off, nil
if off < 0 || off > len(msg) {
return &h, off, &Error{err: "bad off"}
}
end := off + int(h.Rdlength)
if end < off || end > len(msg) {
return &h, end, &Error{err: "bad rdlength"}
}
if noRdata(h) {
return rr, off, nil
}
off, err = rr.unpack(msg, off)
if err != nil {
@ -693,7 +668,6 @@ func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error)
}
// If offset does not increase anymore, l is a lie
if off1 == off {
l = i
break
}
dst = append(dst, r)
@ -706,9 +680,9 @@ func unpackRRslice(l int, msg []byte, off int) (dst1 []RR, off1 int, err error)
// Convert a MsgHdr to a string, with dig-like headers:
//
//;; opcode: QUERY, status: NOERROR, id: 48404
// ;; opcode: QUERY, status: NOERROR, id: 48404
//
//;; flags: qr aa rd ra;
// ;; flags: qr aa rd ra;
func (h *MsgHdr) String() string {
if h == nil {
return "<nil> MsgHdr"
@ -754,24 +728,13 @@ func (dns *Msg) Pack() (msg []byte, err error) {
return dns.PackBuffer(nil)
}
var compressionPackPool = sync.Pool{
New: func() interface{} {
return make(map[string]uint16)
},
}
// PackBuffer packs a Msg, using the given buffer buf. If buf is too small a new buffer is allocated.
func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
// If this message can't be compressed, avoid filling the
// compression map and creating garbage.
if dns.Compress && dns.isCompressible() {
compression := compressionPackPool.Get().(map[string]uint16)
msg, err := dns.packBufferWithCompressionMap(buf, compressionMap{int: compression}, true)
for k := range compression {
delete(compression, k)
}
compressionPackPool.Put(compression)
return msg, err
compression := make(map[string]uint16) // Compression pointer mappings.
return dns.packBufferWithCompressionMap(buf, compressionMap{int: compression}, true)
}
return dns.packBufferWithCompressionMap(buf, compressionMap{}, false)
@ -784,7 +747,7 @@ func (dns *Msg) packBufferWithCompressionMap(buf []byte, compression compression
}
// Set extended rcode unconditionally if we have an opt, this will allow
// reseting the extended rcode bits if they need to.
// resetting the extended rcode bits if they need to.
if opt := dns.IsEdns0(); opt != nil {
opt.SetExtendedRcode(uint16(dns.Rcode))
} else if dns.Rcode > 0xF {
@ -943,6 +906,11 @@ func (dns *Msg) String() string {
s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
opt := dns.IsEdns0()
if opt != nil {
// OPT PSEUDOSECTION
s += opt.String() + "\n"
}
if len(dns.Question) > 0 {
s += "\n;; QUESTION SECTION:\n"
for _, r := range dns.Question {
@ -965,10 +933,10 @@ func (dns *Msg) String() string {
}
}
}
if len(dns.Extra) > 0 {
if len(dns.Extra) > 0 && (opt == nil || len(dns.Extra) > 1) {
s += "\n;; ADDITIONAL SECTION:\n"
for _, r := range dns.Extra {
if r != nil {
if r != nil && r.Header().Rrtype != TypeOPT {
s += r.String() + "\n"
}
}
@ -983,12 +951,6 @@ func (dns *Msg) isCompressible() bool {
len(dns.Ns) > 0 || len(dns.Extra) > 0
}
var compressionPool = sync.Pool{
New: func() interface{} {
return make(map[string]struct{})
},
}
// Len returns the message length when in (un)compressed wire format.
// If dns.Compress is true compression it is taken into account. Len()
// is provided to be a faster way to get the size of the resulting packet,
@ -997,13 +959,8 @@ func (dns *Msg) Len() int {
// If this message can't be compressed, avoid filling the
// compression map and creating garbage.
if dns.Compress && dns.isCompressible() {
compression := compressionPool.Get().(map[string]struct{})
n := msgLenWithCompressionMap(dns, compression)
for k := range compression {
delete(compression, k)
}
compressionPool.Put(compression)
return n
compression := make(map[string]struct{})
return msgLenWithCompressionMap(dns, compression)
}
return msgLenWithCompressionMap(dns, nil)

View File

@ -1,4 +1,5 @@
//+build ignore
//go:build ignore
// +build ignore
// msg_generate.go is meant to run with go generate. It will use
// go/{importer,types} to track down all the RR struct types. Then for each type
@ -10,11 +11,12 @@ import (
"bytes"
"fmt"
"go/format"
"go/importer"
"go/types"
"log"
"os"
"strings"
"golang.org/x/tools/go/packages"
)
var packageHdr = `
@ -34,6 +36,9 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
if !ok {
return nil, false
}
if st.NumFields() == 0 {
return nil, false
}
if st.Field(0).Type() == scope.Lookup("RR_Header").Type() {
return st, false
}
@ -44,9 +49,19 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
return nil, false
}
// loadModule retrieves package description for a given module.
func loadModule(name string) (*types.Package, error) {
conf := packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo}
pkgs, err := packages.Load(&conf, name)
if err != nil {
return nil, err
}
return pkgs[0].Types, nil
}
func main() {
// Import and type-check the package
pkg, err := importer.Default().Import("github.com/miekg/dns")
pkg, err := loadModule("github.com/miekg/dns")
fatalIfErr(err)
scope := pkg.Scope()
@ -99,8 +114,12 @@ return off, err
o("off, err = packDataOpt(rr.%s, msg, off)\n")
case `dns:"nsec"`:
o("off, err = packDataNsec(rr.%s, msg, off)\n")
case `dns:"pairs"`:
o("off, err = packDataSVCB(rr.%s, msg, off)\n")
case `dns:"domain-name"`:
o("off, err = packDataDomainNames(rr.%s, msg, off, compression, false)\n")
case `dns:"apl"`:
o("off, err = packDataApl(rr.%s, msg, off)\n")
default:
log.Fatalln(name, st.Field(i).Name(), st.Tag(i))
}
@ -223,8 +242,12 @@ return off, err
o("rr.%s, off, err = unpackDataOpt(msg, off)\n")
case `dns:"nsec"`:
o("rr.%s, off, err = unpackDataNsec(msg, off)\n")
case `dns:"pairs"`:
o("rr.%s, off, err = unpackDataSVCB(msg, off)\n")
case `dns:"domain-name"`:
o("rr.%s, off, err = unpackDataDomainNames(msg, off, rdStart + int(rr.Hdr.Rdlength))\n")
case `dns:"apl"`:
o("rr.%s, off, err = unpackDataApl(msg, off)\n")
default:
log.Fatalln(name, st.Field(i).Name(), st.Tag(i))
}

View File

@ -6,6 +6,7 @@ import (
"encoding/binary"
"encoding/hex"
"net"
"sort"
"strings"
)
@ -423,79 +424,12 @@ Option:
if off+int(optlen) > len(msg) {
return nil, len(msg), &Error{err: "overflow unpacking opt"}
}
switch code {
case EDNS0NSID:
e := new(EDNS0_NSID)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0SUBNET:
e := new(EDNS0_SUBNET)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0COOKIE:
e := new(EDNS0_COOKIE)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0UL:
e := new(EDNS0_UL)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0LLQ:
e := new(EDNS0_LLQ)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0DAU:
e := new(EDNS0_DAU)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0DHU:
e := new(EDNS0_DHU)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0N3U:
e := new(EDNS0_N3U)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
case EDNS0PADDING:
e := new(EDNS0_PADDING)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
default:
e := new(EDNS0_LOCAL)
e.Code = code
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
e := makeDataOpt(code)
if err := e.unpack(msg[off : off+int(optlen)]); err != nil {
return nil, len(msg), err
}
edns = append(edns, e)
off += int(optlen)
if off < len(msg) {
goto Option
@ -514,9 +448,7 @@ func packDataOpt(options []EDNS0, msg []byte, off int) (int, error) {
binary.BigEndian.PutUint16(msg[off+2:], uint16(len(b))) // Length
off += 4
if off+len(b) > len(msg) {
copy(msg[off:], b)
off = len(msg)
continue
return len(msg), &Error{err: "overflow packing opt"}
}
// Actual data
copy(msg[off:off+len(b)], b)
@ -544,7 +476,7 @@ func unpackDataNsec(msg []byte, off int) ([]uint16, int, error) {
length, window, lastwindow := 0, 0, -1
for off < len(msg) {
if off+2 > len(msg) {
return nsec, len(msg), &Error{err: "overflow unpacking nsecx"}
return nsec, len(msg), &Error{err: "overflow unpacking NSEC(3)"}
}
window = int(msg[off])
length = int(msg[off+1])
@ -552,17 +484,17 @@ func unpackDataNsec(msg []byte, off int) ([]uint16, int, error) {
if window <= lastwindow {
// RFC 4034: Blocks are present in the NSEC RR RDATA in
// increasing numerical order.
return nsec, len(msg), &Error{err: "out of order NSEC block"}
return nsec, len(msg), &Error{err: "out of order NSEC(3) block in type bitmap"}
}
if length == 0 {
// RFC 4034: Blocks with no types present MUST NOT be included.
return nsec, len(msg), &Error{err: "empty NSEC block"}
return nsec, len(msg), &Error{err: "empty NSEC(3) block in type bitmap"}
}
if length > 32 {
return nsec, len(msg), &Error{err: "NSEC block too long"}
return nsec, len(msg), &Error{err: "NSEC(3) block too long in type bitmap"}
}
if off+length > len(msg) {
return nsec, len(msg), &Error{err: "overflowing NSEC block"}
return nsec, len(msg), &Error{err: "overflowing NSEC(3) block in type bitmap"}
}
// Walk the bytes in the window and extract the type bits
@ -626,6 +558,16 @@ func packDataNsec(bitmap []uint16, msg []byte, off int) (int, error) {
if len(bitmap) == 0 {
return off, nil
}
if off > len(msg) {
return off, &Error{err: "overflow packing nsec"}
}
toZero := msg[off:]
if maxLen := typeBitMapLen(bitmap); maxLen < len(toZero) {
toZero = toZero[:maxLen]
}
for i := range toZero {
toZero[i] = 0
}
var lastwindow, lastlength uint16
for _, t := range bitmap {
window := t / 256
@ -652,6 +594,65 @@ func packDataNsec(bitmap []uint16, msg []byte, off int) (int, error) {
return off, nil
}
func unpackDataSVCB(msg []byte, off int) ([]SVCBKeyValue, int, error) {
var xs []SVCBKeyValue
var code uint16
var length uint16
var err error
for off < len(msg) {
code, off, err = unpackUint16(msg, off)
if err != nil {
return nil, len(msg), &Error{err: "overflow unpacking SVCB"}
}
length, off, err = unpackUint16(msg, off)
if err != nil || off+int(length) > len(msg) {
return nil, len(msg), &Error{err: "overflow unpacking SVCB"}
}
e := makeSVCBKeyValue(SVCBKey(code))
if e == nil {
return nil, len(msg), &Error{err: "bad SVCB key"}
}
if err := e.unpack(msg[off : off+int(length)]); err != nil {
return nil, len(msg), err
}
if len(xs) > 0 && e.Key() <= xs[len(xs)-1].Key() {
return nil, len(msg), &Error{err: "SVCB keys not in strictly increasing order"}
}
xs = append(xs, e)
off += int(length)
}
return xs, off, nil
}
func packDataSVCB(pairs []SVCBKeyValue, msg []byte, off int) (int, error) {
pairs = append([]SVCBKeyValue(nil), pairs...)
sort.Slice(pairs, func(i, j int) bool {
return pairs[i].Key() < pairs[j].Key()
})
prev := svcb_RESERVED
for _, el := range pairs {
if el.Key() == prev {
return len(msg), &Error{err: "repeated SVCB keys are not allowed"}
}
prev = el.Key()
packed, err := el.pack()
if err != nil {
return len(msg), err
}
off, err = packUint16(uint16(el.Key()), msg, off)
if err != nil {
return len(msg), &Error{err: "overflow packing SVCB"}
}
off, err = packUint16(uint16(len(packed)), msg, off)
if err != nil || off+len(packed) > len(msg) {
return len(msg), &Error{err: "overflow packing SVCB"}
}
copy(msg[off:off+len(packed)], packed)
off += len(packed)
}
return off, nil
}
func unpackDataDomainNames(msg []byte, off, end int) ([]string, int, error) {
var (
servers []string
@ -681,3 +682,131 @@ func packDataDomainNames(names []string, msg []byte, off int, compression compre
}
return off, nil
}
func packDataApl(data []APLPrefix, msg []byte, off int) (int, error) {
var err error
for i := range data {
off, err = packDataAplPrefix(&data[i], msg, off)
if err != nil {
return len(msg), err
}
}
return off, nil
}
func packDataAplPrefix(p *APLPrefix, msg []byte, off int) (int, error) {
if len(p.Network.IP) != len(p.Network.Mask) {
return len(msg), &Error{err: "address and mask lengths don't match"}
}
var err error
prefix, _ := p.Network.Mask.Size()
addr := p.Network.IP.Mask(p.Network.Mask)[:(prefix+7)/8]
switch len(p.Network.IP) {
case net.IPv4len:
off, err = packUint16(1, msg, off)
case net.IPv6len:
off, err = packUint16(2, msg, off)
default:
err = &Error{err: "unrecognized address family"}
}
if err != nil {
return len(msg), err
}
off, err = packUint8(uint8(prefix), msg, off)
if err != nil {
return len(msg), err
}
var n uint8
if p.Negation {
n = 0x80
}
// trim trailing zero bytes as specified in RFC3123 Sections 4.1 and 4.2.
i := len(addr) - 1
for ; i >= 0 && addr[i] == 0; i-- {
}
addr = addr[:i+1]
adflen := uint8(len(addr)) & 0x7f
off, err = packUint8(n|adflen, msg, off)
if err != nil {
return len(msg), err
}
if off+len(addr) > len(msg) {
return len(msg), &Error{err: "overflow packing APL prefix"}
}
off += copy(msg[off:], addr)
return off, nil
}
func unpackDataApl(msg []byte, off int) ([]APLPrefix, int, error) {
var result []APLPrefix
for off < len(msg) {
prefix, end, err := unpackDataAplPrefix(msg, off)
if err != nil {
return nil, len(msg), err
}
off = end
result = append(result, prefix)
}
return result, off, nil
}
func unpackDataAplPrefix(msg []byte, off int) (APLPrefix, int, error) {
family, off, err := unpackUint16(msg, off)
if err != nil {
return APLPrefix{}, len(msg), &Error{err: "overflow unpacking APL prefix"}
}
prefix, off, err := unpackUint8(msg, off)
if err != nil {
return APLPrefix{}, len(msg), &Error{err: "overflow unpacking APL prefix"}
}
nlen, off, err := unpackUint8(msg, off)
if err != nil {
return APLPrefix{}, len(msg), &Error{err: "overflow unpacking APL prefix"}
}
var ip []byte
switch family {
case 1:
ip = make([]byte, net.IPv4len)
case 2:
ip = make([]byte, net.IPv6len)
default:
return APLPrefix{}, len(msg), &Error{err: "unrecognized APL address family"}
}
if int(prefix) > 8*len(ip) {
return APLPrefix{}, len(msg), &Error{err: "APL prefix too long"}
}
afdlen := int(nlen & 0x7f)
if afdlen > len(ip) {
return APLPrefix{}, len(msg), &Error{err: "APL length too long"}
}
if off+afdlen > len(msg) {
return APLPrefix{}, len(msg), &Error{err: "overflow unpacking APL address"}
}
// Address MUST NOT contain trailing zero bytes per RFC3123 Sections 4.1 and 4.2.
off += copy(ip, msg[off:off+afdlen])
if afdlen > 0 {
last := ip[afdlen-1]
if last == 0 {
return APLPrefix{}, len(msg), &Error{err: "extra APL address bits"}
}
}
ipnet := net.IPNet{
IP: ip,
Mask: net.CIDRMask(int(prefix), 8*len(ip)),
}
return APLPrefix{
Negation: (nlen & 0x80) != 0,
Network: ipnet,
}, off, nil
}

View File

@ -1,6 +1,10 @@
package dns
import "testing"
import (
"bytes"
"net"
"testing"
)
// TestPacketDataNsec tests generated using fuzz.go and with a message pack
// containing the following bytes: 0000\x00\x00000000\x00\x002000000\x0060000\x00\x130000000000000000000"
@ -15,7 +19,8 @@ func TestPackDataNsec(t *testing.T) {
tests := []struct {
name string
args args
want int
wantOff int
wantBytes []byte
wantErr bool
wantErrMsg string
}{
@ -40,14 +45,14 @@ func TestPackDataNsec(t *testing.T) {
},
wantErr: true,
wantErrMsg: "dns: overflow packing nsec",
want: 31,
wantOff: 48,
},
{
name: "disordered nsec bits",
args: args{
bitmap: []uint16{
8962,
0,
1,
},
msg: []byte{
48, 48, 48, 48, 0, 0, 0, 1, 0, 0, 0, 0,
@ -68,13 +73,13 @@ func TestPackDataNsec(t *testing.T) {
},
wantErr: true,
wantErrMsg: "dns: nsec bits out of order",
want: 155,
wantOff: 155,
},
{
name: "simple message with only one window",
args: args{
bitmap: []uint16{
0,
1,
},
msg: []byte{
48, 48, 48, 48, 0, 0,
@ -85,13 +90,33 @@ func TestPackDataNsec(t *testing.T) {
},
off: 0,
},
wantErr: false,
want: 3,
wantErr: false,
wantOff: 3,
wantBytes: []byte{0, 1, 64},
},
{
name: "multiple types",
args: args{
bitmap: []uint16{
TypeNS, TypeSOA, TypeRRSIG, TypeDNSKEY, TypeNSEC3PARAM,
},
msg: []byte{
48, 48, 48, 48, 0, 0,
0, 1, 0, 0, 0, 0,
0, 0, 50, 48, 48, 48,
48, 48, 48, 0, 54, 48,
48, 48, 48, 0, 19, 48, 48,
},
off: 0,
},
wantErr: false,
wantOff: 9,
wantBytes: []byte{0, 7, 34, 0, 0, 0, 0, 2, 144},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := packDataNsec(tt.args.bitmap, tt.args.msg, tt.args.off)
gotOff, err := packDataNsec(tt.args.bitmap, tt.args.msg, tt.args.off)
if (err != nil) != tt.wantErr {
t.Errorf("packDataNsec() error = %v, wantErr %v", err, tt.wantErr)
return
@ -100,13 +125,49 @@ func TestPackDataNsec(t *testing.T) {
t.Errorf("packDataNsec() error msg = %v, wantErrMsg %v", err.Error(), tt.wantErrMsg)
return
}
if got != tt.want {
t.Errorf("packDataNsec() = %v, want %v", got, tt.want)
if gotOff != tt.wantOff {
t.Errorf("packDataNsec() = %v, want off %v", gotOff, tt.wantOff)
}
if err == nil && tt.args.off < len(tt.args.msg) && gotOff < len(tt.args.msg) {
if want, got := tt.wantBytes, tt.args.msg[tt.args.off:gotOff]; !bytes.Equal(got, want) {
t.Errorf("packDataNsec() = %v, want bytes %v", got, want)
}
}
})
}
}
func TestPackDataNsecDirtyBuffer(t *testing.T) {
zeroBuf := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0}
dirtyBuf := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9}
off1, _ := packDataNsec([]uint16{TypeNS, TypeSOA, TypeRRSIG}, zeroBuf, 0)
off2, _ := packDataNsec([]uint16{TypeNS, TypeSOA, TypeRRSIG}, dirtyBuf, 0)
if off1 != off2 {
t.Errorf("off1 %v != off2 %v", off1, off2)
}
if !bytes.Equal(zeroBuf[:off1], dirtyBuf[:off2]) {
t.Errorf("dirty buffer differs from zero buffer: %v, %v", zeroBuf[:off1], dirtyBuf[:off2])
}
}
func BenchmarkPackDataNsec(b *testing.B) {
benches := []struct {
name string
types []uint16
}{
{"empty", nil},
{"typical", []uint16{TypeNS, TypeSOA, TypeRRSIG, TypeDNSKEY, TypeNSEC3PARAM}},
{"multiple_windows", []uint16{1, 300, 350, 10000, 20000}},
}
for _, bb := range benches {
b.Run(bb.name, func(b *testing.B) {
buf := make([]byte, 100)
for n := 0; n < b.N; n++ {
packDataNsec(bb.types, buf, 0)
}
})
}
}
func TestUnpackString(t *testing.T) {
msg := []byte("\x00abcdef\x0f\\\"ghi\x04mmm\x7f")
msg[0] = byte(len(msg) - 1)
@ -153,3 +214,380 @@ func BenchmarkUnpackString(b *testing.B) {
}
})
}
func TestPackDataAplPrefix(t *testing.T) {
tests := []struct {
name string
negation bool
ip net.IP
mask net.IPMask
expect []byte
}{
{
"1:192.0.2.0/24",
false,
net.ParseIP("192.0.2.0").To4(),
net.CIDRMask(24, 32),
[]byte{0x00, 0x01, 0x18, 0x03, 192, 0, 2},
},
{
"2:2001:db8:cafe::0/48",
false,
net.ParseIP("2001:db8:cafe::"),
net.CIDRMask(48, 128),
[]byte{0x00, 0x02, 0x30, 0x06, 0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe},
},
{
"with trailing zero bytes 2:2001:db8:cafe::0/64",
false,
net.ParseIP("2001:db8:cafe::"),
net.CIDRMask(64, 128),
[]byte{0x00, 0x02, 0x40, 0x06, 0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe},
},
{
"no non-zero bytes 2::/16",
false,
net.ParseIP("::"),
net.CIDRMask(16, 128),
[]byte{0x00, 0x02, 0x10, 0x00},
},
{
"!2:2001:db8::/32",
true,
net.ParseIP("2001:db8::"),
net.CIDRMask(32, 128),
[]byte{0x00, 0x02, 0x20, 0x84, 0x20, 0x01, 0x0d, 0xb8},
},
{
"normalize 1:198.51.103.255/22",
false,
net.ParseIP("198.51.103.255").To4(),
net.CIDRMask(22, 32),
[]byte{0x00, 0x01, 0x16, 0x03, 198, 51, 100}, // 1:198.51.100.0/22
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ap := &APLPrefix{
Negation: tt.negation,
Network: net.IPNet{IP: tt.ip, Mask: tt.mask},
}
out := make([]byte, 16)
off, err := packDataAplPrefix(ap, out, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
if !bytes.Equal(tt.expect, out[:off]) {
t.Fatalf("expected output %02x, got %02x", tt.expect, out[:off])
}
// Make sure the packed bytes would be accepted by its own unpack
_, _, err = unpackDataAplPrefix(out, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
})
}
}
func TestPackDataAplPrefix_Failures(t *testing.T) {
tests := []struct {
name string
ip net.IP
mask net.IPMask
}{
{
"family mismatch",
net.ParseIP("2001:db8::"),
net.CIDRMask(24, 32),
},
{
"unrecognized family",
[]byte{0x42},
[]byte{0xff},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ap := &APLPrefix{Network: net.IPNet{IP: tt.ip, Mask: tt.mask}}
msg := make([]byte, 16)
off, err := packDataAplPrefix(ap, msg, 0)
if err == nil {
t.Fatal("expected error, got none")
}
if off != len(msg) {
t.Fatalf("expected %d, got %d", len(msg), off)
}
})
}
}
func TestPackDataAplPrefix_BufferBounds(t *testing.T) {
ap := &APLPrefix{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("2001:db8::"),
Mask: net.CIDRMask(32, 128),
},
}
wire := []byte{0x00, 0x02, 0x20, 0x04, 0x20, 0x01, 0x0d, 0xb8}
t.Run("small", func(t *testing.T) {
msg := make([]byte, len(wire))
_, err := packDataAplPrefix(ap, msg, 1) // offset
if err == nil {
t.Fatal("expected error, got none")
}
})
t.Run("exact fit", func(t *testing.T) {
msg := make([]byte, len(wire))
off, err := packDataAplPrefix(ap, msg, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
if !bytes.Equal(wire, msg[:off]) {
t.Fatalf("expected %02x, got %02x", wire, msg[:off])
}
})
}
func TestPackDataApl(t *testing.T) {
in := []APLPrefix{
{
Negation: true,
Network: net.IPNet{
IP: net.ParseIP("198.51.0.0").To4(),
Mask: net.CIDRMask(16, 32),
},
},
{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("2001:db8:beef::"),
Mask: net.CIDRMask(48, 128),
},
},
}
expect := []byte{
// 1:192.51.0.0/16
0x00, 0x01, 0x10, 0x82, 0xc6, 0x33,
// 2:2001:db8:beef::0/48
0x00, 0x02, 0x30, 0x06, 0x20, 0x01, 0x0d, 0xb8, 0xbe, 0xef,
}
msg := make([]byte, 32)
off, err := packDataApl(in, msg, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
if !bytes.Equal(expect, msg[:off]) {
t.Fatalf("expected %02x, got %02x", expect, msg[:off])
}
}
func TestUnpackDataAplPrefix(t *testing.T) {
tests := []struct {
name string
wire []byte
negation bool
ip net.IP
mask net.IPMask
}{
{
"1:192.0.2.0/24",
[]byte{0x00, 0x01, 0x18, 0x03, 192, 0, 2},
false,
net.ParseIP("192.0.2.0").To4(),
net.CIDRMask(24, 32),
},
{
"2:2001:db8::/32",
[]byte{0x00, 0x02, 0x20, 0x04, 0x20, 0x01, 0x0d, 0xb8},
false,
net.ParseIP("2001:db8::"),
net.CIDRMask(32, 128),
},
{
"!2:2001:db8:8000::/33",
[]byte{0x00, 0x02, 0x21, 0x85, 0x20, 0x01, 0x0d, 0xb8, 0x80},
true,
net.ParseIP("2001:db8:8000::"),
net.CIDRMask(33, 128),
},
{
"1:0.0.0.0/0",
[]byte{0x00, 0x01, 0x00, 0x00},
false,
net.ParseIP("0.0.0.0").To4(),
net.CIDRMask(0, 32),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, off, err := unpackDataAplPrefix(tt.wire, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
if off != len(tt.wire) {
t.Fatalf("expected offset %d, got %d", len(tt.wire), off)
}
if got.Negation != tt.negation {
t.Errorf("expected negation %v, got %v", tt.negation, got.Negation)
}
if !bytes.Equal(got.Network.IP, tt.ip) {
t.Errorf("expected IP %02x, got %02x", tt.ip, got.Network.IP)
}
if !bytes.Equal(got.Network.Mask, tt.mask) {
t.Errorf("expected mask %02x, got %02x", tt.mask, got.Network.Mask)
}
})
}
}
func TestUnpackDataAplPrefix_Errors(t *testing.T) {
tests := []struct {
name string
wire []byte
want string
}{
{
"incomplete header",
[]byte{0x00, 0x01, 0x18},
"dns: overflow unpacking APL prefix",
},
{
"unrecognized family",
[]byte{0x00, 0x03, 0x00, 0x00},
"dns: unrecognized APL address family",
},
{
"prefix too large for family IPv4",
[]byte{0x00, 0x01, 0x21, 0x04, 192, 0, 2, 0},
"dns: APL prefix too long",
},
{
"prefix too large for family IPv6",
[]byte{0x00, 0x02, 0x81, 0x85, 0x20, 0x01, 0x0d, 0xb8, 0x80},
"dns: APL prefix too long",
},
{
"afdlen too long for address family IPv4",
[]byte{0x00, 0x01, 22, 0x05, 192, 0, 2, 0, 0},
"dns: APL length too long",
},
{
"overflow unpacking APL address",
[]byte{0x00, 0x01, 0x10, 0x02, 192},
"dns: overflow unpacking APL address",
},
{
"address included trailing zeros",
[]byte{0x00, 0x01, 0x10, 0x04, 192, 0, 2, 0},
"dns: extra APL address bits",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, _, err := unpackDataAplPrefix(tt.wire, 0)
if err == nil {
t.Fatal("expected error, got none")
}
if err.Error() != tt.want {
t.Errorf("expected %s, got %s", tt.want, err.Error())
}
})
}
}
func TestUnpackDataApl(t *testing.T) {
wire := []byte{
// 2:2001:db8:cafe:4200:0/56
0x00, 0x02, 0x38, 0x07, 0x20, 0x01, 0x0d, 0xb8, 0xca, 0xfe, 0x42,
// 1:192.0.2.0/24
0x00, 0x01, 0x18, 0x03, 192, 0, 2,
// !1:192.0.2.128/25
0x00, 0x01, 0x19, 0x84, 192, 0, 2, 128,
// 1:10.0.0.0/24
0x00, 0x01, 0x18, 0x01, 0x0a,
// !1:10.0.0.1/32
0x00, 0x01, 0x20, 0x84, 0x0a, 0, 0, 1,
// !1:0.0.0.0/0
0x00, 0x01, 0x00, 0x80,
// 2::0/0
0x00, 0x02, 0x00, 0x00,
}
expect := []APLPrefix{
{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("2001:db8:cafe:4200::"),
Mask: net.CIDRMask(56, 128),
},
},
{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("192.0.2.0").To4(),
Mask: net.CIDRMask(24, 32),
},
},
{
Negation: true,
Network: net.IPNet{
IP: net.ParseIP("192.0.2.128").To4(),
Mask: net.CIDRMask(25, 32),
},
},
{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("10.0.0.0").To4(),
Mask: net.CIDRMask(24, 32),
},
},
{
Negation: true,
Network: net.IPNet{
IP: net.ParseIP("10.0.0.1").To4(),
Mask: net.CIDRMask(32, 32),
},
},
{
Negation: true,
Network: net.IPNet{
IP: net.ParseIP("0.0.0.0").To4(),
Mask: net.CIDRMask(0, 32),
},
},
{
Negation: false,
Network: net.IPNet{
IP: net.ParseIP("::").To16(),
Mask: net.CIDRMask(0, 128),
},
},
}
got, off, err := unpackDataApl(wire, 0)
if err != nil {
t.Fatalf("expected no error, got %q", err)
}
if off != len(wire) {
t.Fatalf("expected offset %d, got %d", len(wire), off)
}
if len(got) != len(expect) {
t.Fatalf("expected %d prefixes, got %d", len(expect), len(got))
}
for i, exp := range expect {
if got[i].Negation != exp.Negation {
t.Errorf("[%d] expected negation %v, got %v", i, exp.Negation, got[i].Negation)
}
if !bytes.Equal(got[i].Network.IP, exp.Network.IP) {
t.Errorf("[%d] expected IP %02x, got %02x", i, exp.Network.IP, got[i].Network.IP)
}
if !bytes.Equal(got[i].Network.Mask, exp.Network.Mask) {
t.Errorf("[%d] expected mask %02x, got %02x", i, exp.Network.Mask, got[i].Network.Mask)
}
}
}

View File

@ -133,19 +133,19 @@ func TestUnpackDomainName(t *testing.T) {
".",
""},
{"long label",
string(63) + maxPrintableLabel + "\x00",
"?" + maxPrintableLabel + "\x00",
maxPrintableLabel + ".",
""},
{"unprintable label",
string(63) + regexp.MustCompile(`\\[0-9]+`).ReplaceAllStringFunc(maxUnprintableLabel,
"?" + regexp.MustCompile(`\\[0-9]+`).ReplaceAllStringFunc(maxUnprintableLabel,
func(escape string) string {
n, _ := strconv.ParseInt(escape[1:], 10, 8)
return string(n)
return string(rune(n))
}) + "\x00",
maxUnprintableLabel + ".",
""},
{"long domain",
string(53) + strings.Replace(longDomain, ".", string(49), -1) + "\x00",
"5" + strings.Replace(longDomain, ".", "1", -1) + "\x00",
longDomain + ".",
""},
{"compression pointer",
@ -154,7 +154,7 @@ func TestUnpackDomainName(t *testing.T) {
"foo.\\003com\\000.example.com.",
""},
{"too long domain",
string(54) + "x" + strings.Replace(longDomain, ".", string(49), -1) + "\x00",
"6" + "x" + strings.Replace(longDomain, ".", "1", -1) + "\x00",
"",
ErrLongDomain.Error()},
{"too long by pointer",
@ -202,6 +202,7 @@ func TestUnpackDomainName(t *testing.T) {
"\x03foo" + "\x03bar" + "\x07example" + "\xC0\x04",
"",
ErrLongDomain.Error()},
{"forward compression pointer", "\x02\xC0\xFF\xC0\x01", "", ErrBuf.Error()},
{"reserved compression pointer 0b10", "\x07example\x80", "", "dns: bad rdata"},
{"reserved compression pointer 0b01", "\x07example\x40", "", "dns: bad rdata"},
}

View File

@ -8,8 +8,14 @@ package dns
// record adding as many records as possible without exceeding the
// requested buffer size.
//
// If the message fits within the requested size without compression,
// Truncate will set the message's Compress attribute to false. It is
// the caller's responsibility to set it back to true if they wish to
// compress the payload regardless of size.
//
// The TC bit will be set if any records were excluded from the message.
// This indicates to that the client should retry over TCP.
// If the TC bit is already set on the message it will be retained.
// TC indicates that the client should retry over TCP.
//
// According to RFC 2181, the TC bit should only be set if not all of the
// "required" RRs can be included in the response. Unfortunately, we have
@ -28,11 +34,11 @@ func (dns *Msg) Truncate(size int) {
}
// RFC 6891 mandates that the payload size in an OPT record
// less than 512 bytes must be treated as equal to 512 bytes.
// less than 512 (MinMsgSize) bytes must be treated as equal to 512 bytes.
//
// For ease of use, we impose that restriction here.
if size < 512 {
size = 512
if size < MinMsgSize {
size = MinMsgSize
}
l := msgLenWithCompressionMap(dns, nil) // uncompressed length
@ -54,7 +60,7 @@ func (dns *Msg) Truncate(size int) {
size -= Len(edns0)
}
compression := compressionPool.Get().(map[string]struct{})
compression := make(map[string]struct{})
l = headerSize
for _, r := range dns.Question {
@ -73,11 +79,11 @@ func (dns *Msg) Truncate(size int) {
var numExtra int
if l < size {
l, numExtra = truncateLoop(dns.Extra, size, l, compression)
_, numExtra = truncateLoop(dns.Extra, size, l, compression)
}
// See the function documentation for when we set this.
dns.Truncated = len(dns.Answer) > numAnswer ||
dns.Truncated = dns.Truncated || len(dns.Answer) > numAnswer ||
len(dns.Ns) > numNS || len(dns.Extra) > numExtra
dns.Answer = dns.Answer[:numAnswer]
@ -88,11 +94,6 @@ func (dns *Msg) Truncate(size int) {
// Add the OPT record back onto the additional section.
dns.Extra = append(dns.Extra, edns0)
}
for k := range compression {
delete(compression, k)
}
compressionPool.Put(compression)
}
func truncateLoop(rrs []RR, size, l int, compression map[string]struct{}) (int, int) {

View File

@ -18,7 +18,7 @@ func TestRequestTruncateAnswer(t *testing.T) {
reply.Truncate(MinMsgSize)
if want, got := MinMsgSize, reply.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
if !reply.Truncated {
t.Errorf("truncated bit should be set")
@ -38,7 +38,7 @@ func TestRequestTruncateExtra(t *testing.T) {
reply.Truncate(MinMsgSize)
if want, got := MinMsgSize, reply.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
if !reply.Truncated {
t.Errorf("truncated bit should be set")
@ -62,7 +62,7 @@ func TestRequestTruncateExtraEdns0(t *testing.T) {
reply.Truncate(size)
if want, got := size, reply.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
if !reply.Truncated {
t.Errorf("truncated bit should be set")
@ -94,7 +94,7 @@ func TestRequestTruncateExtraRegression(t *testing.T) {
reply.Truncate(size)
if want, got := size, reply.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
if !reply.Truncated {
t.Errorf("truncated bit should be set")
@ -130,7 +130,7 @@ func TestTruncation(t *testing.T) {
copy.Truncate(bufsize)
if want, got := bufsize, copy.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
}
}
@ -150,7 +150,7 @@ func TestRequestTruncateAnswerExact(t *testing.T) {
reply.Truncate(size)
if want, got := size, reply.Len(); want < got {
t.Errorf("message length should be bellow %d bytes, got %d bytes", want, got)
t.Errorf("message length should be below %d bytes, got %d bytes", want, got)
}
if expected := 52; len(reply.Answer) != expected {
t.Errorf("wrong number of answers; expected %d, got %d", expected, len(reply.Answer))

View File

@ -43,7 +43,7 @@ func HashName(label string, ha uint8, iter uint16, salt string) string {
return toBase32(nsec3)
}
// Cover returns true if a name is covered by the NSEC3 record
// Cover returns true if a name is covered by the NSEC3 record.
func (rr *NSEC3) Cover(name string) bool {
nameHash := HashName(name, rr.Hash, rr.Iterations, rr.Salt)
owner := strings.ToUpper(rr.Hdr.Name)

View File

@ -245,8 +245,7 @@ func testTXTRRQuick(t *testing.T) {
rrbytes := make([]byte, 0, len(owner)+2+2+4+2+len(rdata))
rrbytes = append(rrbytes, owner...)
rrbytes = append(rrbytes, typeAndClass...)
rrbytes = append(rrbytes, byte(len(rdata)>>8))
rrbytes = append(rrbytes, byte(len(rdata)))
rrbytes = append(rrbytes, byte(len(rdata)>>8), byte(len(rdata)))
rrbytes = append(rrbytes, rdata...)
rr, _, err := UnpackRR(rrbytes, 0)
if err != nil {
@ -267,7 +266,7 @@ func testTXTRRQuick(t *testing.T) {
return false
}
if len(rdata) == 0 {
// string'ing won't produce any data to parse
// stringifying won't produce any data to parse
return true
}
rrString := rr.String()
@ -358,12 +357,29 @@ func TestNSEC(t *testing.T) {
t.Errorf("`%s' should be equal to\n`%s', but is `%s'", i, o, rr.String())
}
}
rr, err := NewRR("nl. IN NSEC3PARAM 1 0 5 30923C44C6CBBB8F")
if err != nil {
t.Fatal("failed to parse RR: ", err)
}
if nsec3param, ok := rr.(*NSEC3PARAM); ok {
if nsec3param.SaltLength != 8 {
t.Fatalf("nsec3param saltlen %d != 8", nsec3param.SaltLength)
}
} else {
t.Fatal("not nsec3 param: ", err)
}
}
func TestParseLOC(t *testing.T) {
lt := map[string]string{
"SW1A2AA.find.me.uk. LOC 51 30 12.748 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 30 12.748 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m",
"SW1A2AA.find.me.uk. LOC 51 0 0.0 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 00 0.000 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m",
"SW1A2AA.find.me.uk. LOC 51 0 0.0 N 00 07 39.611 W 0.00m 0.00m 0.00m 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 00 0.000 N 00 07 39.611 W 0m 0.00m 0.00m 0.00m",
"SW1A2AA.find.me.uk. LOC 51 30 12.748 N 00 07 39.611 W 0.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t51 30 12.748 N 00 07 39.611 W 0m 1m 10000m 10m",
// Exercise boundary cases
"SW1A2AA.find.me.uk. LOC 90 0 0.0 N 180 0 0.0 W 42849672.95 90000000.00m 90000000.00m 90000000.00m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t90 00 0.000 N 180 00 0.000 W 42849672.95m 90000000m 90000000m 90000000m",
"SW1A2AA.find.me.uk. LOC 89 59 59.999 N 179 59 59.999 W -100000 90000000.00m 90000000.00m 90000000m": "SW1A2AA.find.me.uk.\t3600\tIN\tLOC\t89 59 59.999 N 179 59 59.999 W -100000m 90000000m 90000000m 90000000m",
// use float64 to have enough precision.
"example.com. LOC 42 21 43.952 N 71 5 6.344 W -24m 1m 200m 10m": "example.com.\t3600\tIN\tLOC\t42 21 43.952 N 71 05 6.344 W -24m 1m 200m 10m",
}
for i, o := range lt {
rr, err := NewRR(i)
@ -375,6 +391,90 @@ func TestParseLOC(t *testing.T) {
t.Errorf("`%s' should be equal to\n`%s', but is `%s'", i, o, rr.String())
}
}
// Invalid cases (out of range values)
lt = map[string]string{ // Pair of (invalid) RDATA and the bad field name
// One of the subfields is out of range.
"91 0 0.0 N 00 07 39.611 W 0m": "Latitude",
"89 60 0.0 N 00 07 39.611 W 0m": "Latitude",
"89 00 60.0 N 00 07 39.611 W 0m": "Latitude",
"1 00 -1 N 00 07 39.611 W 0m": "Latitude",
"0 0 0.0 N 181 00 0.0 W 0m": "Longitude",
"0 0 0.0 N 179 60 0.0 W 0m": "Longitude",
"0 0 0.0 N 179 00 60.0 W 0m": "Longitude",
"0 0 0.0 N 1 00 -1 W 0m": "Longitude",
// Each subfield is valid, but resulting latitude would be out of range.
"90 01 00.0 N 00 07 39.611 W 0m": "Latitude",
"0 0 0.0 N 180 01 0.0 W 0m": "Longitude",
}
for rdata, field := range lt {
_, err := NewRR(fmt.Sprintf("example.com. LOC %s", rdata))
if err == nil || !strings.Contains(err.Error(), field) {
t.Errorf("expected error to contain %q, but got %v", field, err)
}
}
}
// this tests a subroutine for the LOC RR parser. It's complicated enough to test separately.
func TestStringToCm(t *testing.T) {
tests := []struct {
// Test description: the input token and the expected return values from stringToCm.
token string
e uint8
m uint8
ok bool
}{
{"100", 4, 1, true},
{"0100", 4, 1, true}, // leading 0 (allowed)
{"100.99", 4, 1, true},
{"90000000", 9, 9, true},
{"90000000.00", 9, 9, true},
{"0", 0, 0, true},
{"0.00", 0, 0, true},
{"0.01", 0, 1, true},
{".01", 0, 1, true}, // empty 'meter' part (allowed)
{"0.1", 1, 1, true},
// out of range (too large)
{"90000001", 0, 0, false},
{"90000000.01", 0, 0, false},
// more than 2 digits in 'cmeter' part
{"0.000", 0, 0, false},
{"0.001", 0, 0, false},
{"0.999", 0, 0, false},
// with plus or minus sign (disallowed)
{"-100", 0, 0, false},
{"+100", 0, 0, false},
{"0.-10", 0, 0, false},
{"0.+10", 0, 0, false},
{"0a.00", 0, 0, false}, // invalid string for 'meter' part
{".1x", 0, 0, false}, // invalid string for 'cmeter' part
{".", 0, 0, false}, // empty 'cmeter' part (disallowed)
{"1.", 0, 0, false}, // ditto
{"m", 0, 0, false}, // only the "m" suffix
}
for _, tc := range tests {
tc := tc
t.Run(tc.token, func(t *testing.T) {
// In all cases the expected result is the same with or without the 'm' suffix.
// So we test both cases using the same test code.
for _, sfx := range []string{"", "m"} {
token := tc.token + sfx
e, m, ok := stringToCm(token)
if ok != tc.ok {
t.Fatal("unexpected validation result")
}
if m != tc.m {
t.Fatalf("Expected %d, got %d", tc.m, m)
}
if e != tc.e {
t.Fatalf("Expected %d, got %d", tc.e, e)
}
}
})
}
}
func TestParseDS(t *testing.T) {
@ -432,7 +532,7 @@ func TestParseClass(t *testing.T) {
"t.example.com. CH A 127.0.0.1": "t.example.com. 3600 CH A 127.0.0.1",
// ClassANY can not occur in zone files
// "t.example.com. ANY A 127.0.0.1": "t.example.com. 3600 ANY A 127.0.0.1",
"t.example.com. NONE A 127.0.0.1": "t.example.com. 3600 NONE A 127.0.0.1",
"t.example.com. NONE A 127.0.0.1": "t.example.com. 3600 NONE A 127.0.0.1",
"t.example.com. CLASS255 A 127.0.0.1": "t.example.com. 3600 CLASS255 A 127.0.0.1",
}
for i, o := range tests {
@ -534,25 +634,25 @@ $TTL 314
example.com. DNAME 10 ; TTL=314 after second $TTL
`
reCaseFromComment := regexp.MustCompile(`TTL=(\d+)\s+(.*)`)
records := ParseZone(strings.NewReader(zone), "", "")
z := NewZoneParser(strings.NewReader(zone), "", "")
var i int
for record := range records {
for rr, ok := z.Next(); ok; rr, ok = z.Next() {
i++
if record.Error != nil {
t.Error(record.Error)
continue
}
expected := reCaseFromComment.FindStringSubmatch(record.Comment)
expected := reCaseFromComment.FindStringSubmatch(z.Comment())
if len(expected) != 3 {
t.Errorf("regexp didn't match for record %d", i)
continue
}
expectedTTL, _ := strconv.ParseUint(expected[1], 10, 32)
ttl := record.RR.Header().Ttl
ttl := rr.Header().Ttl
if ttl != uint32(expectedTTL) {
t.Errorf("%s: expected TTL %d, got %d", expected[2], expectedTTL, ttl)
}
}
if err := z.Err(); err != nil {
t.Error(err)
}
if i != 10 {
t.Errorf("expected %d records, got %d", 5, i)
}
@ -591,16 +691,12 @@ func TestRelativeNameErrors(t *testing.T) {
},
}
for _, errorCase := range badZones {
entries := ParseZone(strings.NewReader(errorCase.zoneContents), "", "")
for entry := range entries {
if entry.Error == nil {
t.Errorf("%s: expected error, got nil", errorCase.label)
continue
}
err := entry.Error.err
if err != errorCase.expectedErr {
t.Errorf("%s: expected error `%s`, got `%s`", errorCase.label, errorCase.expectedErr, err)
}
z := NewZoneParser(strings.NewReader(errorCase.zoneContents), "", "")
z.Next()
if err := z.Err(); err == nil {
t.Errorf("%s: expected error, got nil", errorCase.label)
} else if !strings.Contains(err.Error(), errorCase.expectedErr) {
t.Errorf("%s: expected error `%s`, got `%s`", errorCase.label, errorCase.expectedErr, err)
}
}
}
@ -707,9 +803,13 @@ func TestRfc1982(t *testing.T) {
}
func TestEmpty(t *testing.T) {
for range ParseZone(strings.NewReader(""), "", "") {
z := NewZoneParser(strings.NewReader(""), "", "")
for _, ok := z.Next(); ok; _, ok = z.Next() {
t.Errorf("should be empty")
}
if err := z.Err(); err != nil {
t.Error("got an error when it shouldn't")
}
}
func TestLowercaseTokens(t *testing.T) {
@ -877,18 +977,20 @@ foo. IN DNSKEY 256 3 5 AwEAAb+8l ; this is comment 6
foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7
foo. IN TXT "THIS IS TEXT MAN"; this is comment 8
`
for x := range ParseZone(strings.NewReader(zone), ".", "") {
if x.Error == nil {
if x.Comment != "" {
if _, ok := comments[x.Comment]; !ok {
t.Errorf("wrong comment %q", x.Comment)
}
z := NewZoneParser(strings.NewReader(zone), ".", "")
for _, ok := z.Next(); ok; _, ok = z.Next() {
if z.Comment() != "" {
if _, okC := comments[z.Comment()]; !okC {
t.Errorf("wrong comment %q", z.Comment())
}
}
}
if err := z.Err(); err != nil {
t.Error("got an error when it shouldn't")
}
}
func TestParseZoneComments(t *testing.T) {
func TestZoneParserComments(t *testing.T) {
for i, test := range []struct {
zone string
comments []string
@ -963,24 +1065,25 @@ func TestParseZoneComments(t *testing.T) {
r := strings.NewReader(test.zone)
var j int
for r := range ParseZone(r, "", "") {
if r.Error != nil {
t.Fatal(r.Error)
}
z := NewZoneParser(r, "", "")
for rr, ok := z.Next(); ok; rr, ok = z.Next() {
if j >= len(test.comments) {
t.Fatalf("too many records for zone %d at %d record, expected %d", i, j+1, len(test.comments))
}
if r.Comment != test.comments[j] {
t.Errorf("invalid comment for record %d:%d %v / %v", i, j, r.RR, r.Error)
if z.Comment() != test.comments[j] {
t.Errorf("invalid comment for record %d:%d %v", i, j, rr)
t.Logf("expected %q", test.comments[j])
t.Logf("got %q", r.Comment)
t.Logf("got %q", z.Comment())
}
j++
}
if err := z.Err(); err != nil {
t.Fatal(err)
}
if j != len(test.comments) {
t.Errorf("too few records for zone %d, got %d, expected %d", i, j, len(test.comments))
}
@ -1106,8 +1209,8 @@ func TestTypeXXXX(t *testing.T) {
t.Errorf("this should not work, for TYPE655341")
}
_, err = NewRR("example.com IN TYPE1 \\# 4 0a000001")
if err == nil {
t.Errorf("this should not work")
if err != nil {
t.Errorf("failed to parse TYPE1 RR: %v", err)
}
}
@ -1210,8 +1313,8 @@ func TestNewPrivateKey(t *testing.T) {
algorithms := []algorithm{
{ECDSAP256SHA256, 256},
{ECDSAP384SHA384, 384},
{RSASHA1, 1024},
{RSASHA256, 2048},
{RSASHA1, 512},
{RSASHA256, 512},
{ED25519, 256},
}
@ -1412,10 +1515,10 @@ func TestParseSSHFP(t *testing.T) {
func TestParseHINFO(t *testing.T) {
dt := map[string]string{
"example.net. HINFO A B": "example.net. 3600 IN HINFO \"A\" \"B\"",
"example.net. HINFO A B": "example.net. 3600 IN HINFO \"A\" \"B\"",
"example.net. HINFO \"A\" \"B\"": "example.net. 3600 IN HINFO \"A\" \"B\"",
"example.net. HINFO A B C D E F": "example.net. 3600 IN HINFO \"A\" \"B C D E F\"",
"example.net. HINFO AB": "example.net. 3600 IN HINFO \"AB\" \"\"",
"example.net. HINFO AB": "example.net. 3600 IN HINFO \"AB\" \"\"",
// "example.net. HINFO PC-Intel-700mhz \"Redhat Linux 7.1\"": "example.net. 3600 IN HINFO \"PC-Intel-700mhz\" \"Redhat Linux 7.1\"",
// This one is recommended in Pro Bind book http://www.zytrax.com/books/dns/ch8/hinfo.html
// but effectively, even Bind would replace it to correctly formed text when you AXFR
@ -1435,9 +1538,9 @@ func TestParseHINFO(t *testing.T) {
func TestParseCAA(t *testing.T) {
lt := map[string]string{
"example.net. CAA 0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
"example.net. CAA 0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
"example.net. CAA 0 issuewild \"symantec.com; stuff\"": "example.net.\t3600\tIN\tCAA\t0 issuewild \"symantec.com; stuff\"",
"example.net. CAA 128 tbs \"critical\"": "example.net.\t3600\tIN\tCAA\t128 tbs \"critical\"",
"example.net. CAA 128 tbs \"critical\"": "example.net.\t3600\tIN\tCAA\t128 tbs \"critical\"",
"example.net. CAA 2 auth \"0>09\\006\\010+\\006\\001\\004\\001\\214y\\002\\003\\001\\006\\009`\\134H\\001e\\003\\004\\002\\001\\004 y\\209\\012\\221r\\220\\156Q\\218\\150\\150{\\166\\245:\\231\\182%\\157:\\133\\179}\\1923r\\238\\151\\255\\128q\\145\\002\\001\\000\"": "example.net.\t3600\tIN\tCAA\t2 auth \"0>09\\006\\010+\\006\\001\\004\\001\\214y\\002\\003\\001\\006\\009`\\134H\\001e\\003\\004\\002\\001\\004 y\\209\\012\\221r\\220\\156Q\\218\\150\\150{\\166\\245:\\231\\182%\\157:\\133\\179}\\1923r\\238\\151\\255\\128q\\145\\002\\001\\000\"",
"example.net. TYPE257 0 issue \"symantec.com\"": "example.net.\t3600\tIN\tCAA\t0 issue \"symantec.com\"",
}
@ -1531,6 +1634,91 @@ func TestParseCSYNC(t *testing.T) {
}
}
func TestParseSVCB(t *testing.T) {
svcbs := map[string]string{
`example.com. 3600 IN SVCB 0 cloudflare.com.`: `example.com. 3600 IN SVCB 0 cloudflare.com.`,
`example.com. 3600 IN SVCB 65000 cloudflare.com. alpn=h2 ipv4hint=3.4.3.2`: `example.com. 3600 IN SVCB 65000 cloudflare.com. alpn="h2" ipv4hint="3.4.3.2"`,
`example.com. 3600 IN SVCB 65000 cloudflare.com. key65000=4\ 3 key65001="\" " key65002 key65003= key65004="" key65005== key65006==\"\" key65007=\254 key65008=\032`: `example.com. 3600 IN SVCB 65000 cloudflare.com. key65000="4\ 3" key65001="\"\ " key65002="" key65003="" key65004="" key65005="=" key65006="=\"\"" key65007="\254" key65008="\ "`,
// Explained in svcb.go "In AliasMode, records SHOULD NOT include any SvcParams,"
`example.com. 3600 IN SVCB 0 no-default-alpn`: `example.com. 3600 IN SVCB 0 no-default-alpn.`,
// From the specification
`example.com. HTTPS 0 foo.example.com.`: `example.com. 3600 IN HTTPS 0 foo.example.com.`,
`example.com. SVCB 1 .`: `example.com. 3600 IN SVCB 1 .`,
`example.com. SVCB 16 foo.example.com. port=53`: `example.com. 3600 IN SVCB 16 foo.example.com. port="53"`,
`example.com. SVCB 1 foo.example.com. key667=hello`: `example.com. 3600 IN SVCB 1 foo.example.com. key667="hello"`,
`example.com. SVCB 1 foo.example.com. key667="hello\210qoo"`: `example.com. 3600 IN SVCB 1 foo.example.com. key667="hello\210qoo"`,
`example.com. SVCB 1 foo.example.com. ipv6hint="2001:db8::1,2001:db8::53:1"`: `example.com. 3600 IN SVCB 1 foo.example.com. ipv6hint="2001:db8::1,2001:db8::53:1"`,
`example.com. SVCB 1 example.com. ipv6hint="2001:db8::198.51.100.100"`: `example.com. 3600 IN SVCB 1 example.com. ipv6hint="2001:db8::c633:6464"`,
`example.com. SVCB 16 foo.example.org. alpn=h2,h3-19 mandatory=ipv4hint,alpn ipv4hint=192.0.2.1`: `example.com. 3600 IN SVCB 16 foo.example.org. alpn="h2,h3-19" mandatory="ipv4hint,alpn" ipv4hint="192.0.2.1"`,
`example.com. SVCB 16 foo.example.org. alpn="f\\\\oo\\,bar,h2"`: `example.com. 3600 IN SVCB 16 foo.example.org. alpn="f\\\092oo\\\044bar,h2"`,
`example.com. SVCB 16 foo.example.org. alpn=f\\\092oo\092,bar,h2`: `example.com. 3600 IN SVCB 16 foo.example.org. alpn="f\\\092oo\\\044bar,h2"`,
// From draft-ietf-add-ddr-06
`_dns.example.net. SVCB 1 example.net. alpn=h2 dohpath=/dns-query{?dns}`: `_dns.example.net. 3600 IN SVCB 1 example.net. alpn="h2" dohpath="/dns-query{?dns}"`,
`_dns.example.net. SVCB 1 example.net. alpn=h2 dohpath=/dns\045query{\?dns}`: `_dns.example.net. 3600 IN SVCB 1 example.net. alpn="h2" dohpath="/dns-query{?dns}"`,
}
for s, o := range svcbs {
rr, err := NewRR(s)
if err != nil {
t.Error("failed to parse RR: ", err)
continue
}
if rr.String() != o {
t.Errorf("`%s' should be equal to\n`%s', but is `%s'", s, o, rr.String())
}
}
}
func TestParseBadSVCB(t *testing.T) {
header := `example.com. 3600 IN HTTPS `
evils := []string{
`65536 . no-default-alpn`, // bad priority
`1 ..`, // bad domain
`1 . no-default-alpn=1`, // value illegal
`1 . key`, // invalid key
`1 . key=`, // invalid key
`1 . =`, // invalid key
`1 . ==`, // invalid key
`1 . =a`, // invalid key
`1 . ""`, // invalid key
`1 . ""=`, // invalid key
`1 . "a"`, // invalid key
`1 . "a"=`, // invalid key
`1 . key1=`, // we know that key
`1 . key65535`, // key reserved
`1 . key065534`, // key can't be padded
`1 . key65534="f`, // unterminated value
`1 . key65534="`, // unterminated value
`1 . key65534=\2`, // invalid numeric escape
`1 . key65534=\24`, // invalid numeric escape
`1 . key65534=\256`, // invalid numeric escape
`1 . key65534=\`, // invalid numeric escape
`1 . key65534=""alpn`, // zQuote ending needs whitespace
`1 . key65534="a"alpn`, // zQuote ending needs whitespace
`1 . ipv6hint=1.1.1.1`, // not ipv6
`1 . ipv6hint=1:1:1:1`, // not ipv6
`1 . ipv6hint=a`, // not ipv6
`1 . ipv6hint=`, // empty ipv6
`1 . ipv4hint=1.1.1.1.1`, // not ipv4
`1 . ipv4hint=::fc`, // not ipv4
`1 . ipv4hint=..11`, // not ipv4
`1 . ipv4hint=a`, // not ipv4
`1 . ipv4hint=`, // empty ipv4
`1 . port=`, // empty port
`1 . echconfig=YUd`, // bad base64
`1 . alpn=h\`, // unterminated escape
`1 . alpn=h2\\.h3`, // comma-separated list with bad character
`1 . alpn=h2,,h3`, // empty protocol identifier
`1 . alpn=h3,`, // final protocol identifier empty
}
for _, o := range evils {
_, err := NewRR(header + o)
if err == nil {
t.Error("failed to reject invalid RR: ", header+o)
continue
}
}
}
func TestParseBadNAPTR(t *testing.T) {
// Should look like: mplus.ims.vodafone.com. 3600 IN NAPTR 10 100 "S" "SIP+D2U" "" _sip._udp.mplus.ims.vodafone.com.
naptr := `mplus.ims.vodafone.com. 3600 IN NAPTR 10 100 S SIP+D2U _sip._udp.mplus.ims.vodafone.com.`
@ -1584,3 +1772,246 @@ func TestNULLRecord(t *testing.T) {
t.Fatalf("Expected packet to contain NULL record")
}
}
func TestParseAPL(t *testing.T) {
tests := []struct {
name string
in string
expect string
}{
{
"v4",
". APL 1:192.0.2.0/24",
".\t3600\tIN\tAPL\t1:192.0.2.0/24",
},
{
"v6",
". APL 2:2001:db8::/32",
".\t3600\tIN\tAPL\t2:2001:db8::/32",
},
{
"null v6",
". APL 2:::/0",
".\t3600\tIN\tAPL\t2:::/0",
},
{
"null v4",
". APL 1:0.0.0.0/0",
".\t3600\tIN\tAPL\t1:0.0.0.0/0",
},
{
"full v6",
". APL 2:::/0",
".\t3600\tIN\tAPL\t2:::/0",
},
{
"full v4",
". APL 1:192.0.2.1/32",
".\t3600\tIN\tAPL\t1:192.0.2.1/32",
},
{
"full v6",
". APL 2:2001:0db8:d2b4:b6ba:50db:49cc:a8d1:5bb1/128",
".\t3600\tIN\tAPL\t2:2001:db8:d2b4:b6ba:50db:49cc:a8d1:5bb1/128",
},
{
"v4in6",
". APL 2:::ffff:192.0.2.0/120",
".\t3600\tIN\tAPL\t2:::ffff:192.0.2.0/120",
},
{
"v4in6 v6 syntax",
". APL 2:::ffff:c000:0200/120",
".\t3600\tIN\tAPL\t2:::ffff:192.0.2.0/120",
},
{
"negate",
". APL !1:192.0.2.0/24",
".\t3600\tIN\tAPL\t!1:192.0.2.0/24",
},
{
"multiple",
". APL 1:192.0.2.0/24 !1:192.0.2.1/32 2:2001:db8::/32 !2:2001:db8:1::0/48",
".\t3600\tIN\tAPL\t1:192.0.2.0/24 !1:192.0.2.1/32 2:2001:db8::/32 !2:2001:db8:1::/48",
},
{
"no address",
". APL",
".\t3600\tIN\tAPL\t",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
rr, err := NewRR(tc.in)
if err != nil {
t.Fatalf("failed to parse RR: %s", err)
}
got := rr.String()
if got != tc.expect {
t.Errorf("expected %q, got %q", tc.expect, got)
}
})
}
}
func TestParseAPLErrors(t *testing.T) {
tests := []struct {
name string
in string
}{
{
"unexpected",
`. APL ""`,
},
{
"unrecognized family",
". APL 3:0.0.0.0/0",
},
{
"malformed family",
". APL foo:0.0.0.0/0",
},
{
"malformed address",
". APL 1:192.0.2/16",
},
{
"extra bits",
". APL 2:2001:db8::/0",
},
{
"address mismatch v2",
". APL 1:2001:db8::/64",
},
{
"address mismatch v6",
". APL 2:192.0.2.1/32",
},
{
"no prefix",
". APL 1:192.0.2.1",
},
{
"no family",
". APL 0.0.0.0/0",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := NewRR(tc.in)
if err == nil {
t.Fatal("expected error, got none")
}
})
}
}
func TestUnpackRRWithHeaderInvalidLengths(t *testing.T) {
rr, err := NewRR("test.example.org. 300 IN SSHFP 1 2 BC6533CDC95A79078A39A56EA7635984ED655318ADA9B6159E30723665DA95BB")
if err != nil {
t.Fatalf("failed to parse SSHFP record: %v", err)
}
buf := make([]byte, Len(rr))
headerEnd, end, err := packRR(rr, buf, 0, compressionMap{}, false)
if err != nil {
t.Fatalf("failed to pack A record: %v", err)
}
rr.Header().Rdlength = uint16(end - headerEnd)
for _, off := range []int{
-1,
end + 1,
1<<16 - 1,
} {
_, _, err := UnpackRRWithHeader(*rr.Header(), buf, off)
if de, ok := err.(*Error); !ok || de.err != "bad off" {
t.Errorf("UnpackRRWithHeader with bad offset (%d) returned wrong or no error: %v", off, err)
}
}
for _, rdlength := range []uint16{
uint16(end - headerEnd + 1),
uint16(end),
1<<16 - 1,
} {
rr.Header().Rdlength = rdlength
_, _, err := UnpackRRWithHeader(*rr.Header(), buf, headerEnd)
if de, ok := err.(*Error); !ok || de.err != "bad rdlength" {
t.Errorf("UnpackRRWithHeader with bad rdlength (%d) returned wrong or no error: %v", rdlength, err)
}
}
}
func TestParseZONEMD(t *testing.T) {
// Uses examples from https://tools.ietf.org/html/rfc8976
dt := map[string]string{
// Simple Zone
`example. 86400 IN ZONEMD 2018031900 1 1 (
c68090d90a7aed71
6bc459f9340e3d7c
1370d4d24b7e2fc3
a1ddc0b9a87153b9
a9713b3c9ae5cc27
777f98b8e730044c )
`: "example.\t86400\tIN\tZONEMD\t2018031900 1 1 c68090d90a7aed716bc459f9340e3d7c1370d4d24b7e2fc3a1ddc0b9a87153b9a9713b3c9ae5cc27777f98b8e730044c",
// Complex Zone
`example. 86400 IN ZONEMD 2018031900 1 1 (
a3b69bad980a3504
e1cffcb0fd6397f9
3848071c93151f55
2ae2f6b1711d4bd2
d8b39808226d7b9d
b71e34b72077f8fe )
`: "example.\t86400\tIN\tZONEMD\t2018031900 1 1 a3b69bad980a3504e1cffcb0fd6397f93848071c93151f552ae2f6b1711d4bd2d8b39808226d7b9db71e34b72077f8fe",
// Multiple Digests Zone
`example. 86400 IN ZONEMD 2018031900 1 1 (
62e6cf51b02e54b9
b5f967d547ce4313
6792901f9f88e637
493daaf401c92c27
9dd10f0edb1c56f8
080211f8480ee306 )
`: "example.\t86400\tIN\tZONEMD\t2018031900 1 1 62e6cf51b02e54b9b5f967d547ce43136792901f9f88e637493daaf401c92c279dd10f0edb1c56f8080211f8480ee306",
`example. 86400 IN ZONEMD 2018031900 1 2 (
08cfa1115c7b948c
4163a901270395ea
226a930cd2cbcf2f
a9a5e6eb85f37c8a
4e114d884e66f176
eab121cb02db7d65
2e0cc4827e7a3204
f166b47e5613fd27 )
`: "example.\t86400\tIN\tZONEMD\t2018031900 1 2 08cfa1115c7b948c4163a901270395ea226a930cd2cbcf2fa9a5e6eb85f37c8a4e114d884e66f176eab121cb02db7d652e0cc4827e7a3204f166b47e5613fd27",
`example. 86400 IN ZONEMD 2018031900 1 240 (
e2d523f654b9422a
96c5a8f44607bbee )
`: "example. 86400 IN ZONEMD 2018031900 1 240 e2d523f654b9422a96c5a8f44607bbee",
`example. 86400 IN ZONEMD 2018031900 241 1 (
e1846540e33a9e41
89792d18d5d131f6
05fc283e )
`: "example. 86400 IN ZONEMD 2018031900 241 1 e1846540e33a9e4189792d18d5d131f605fc283e",
// URI.ARPA zone
`uri.arpa. 3600 IN ZONEMD 2018100702 1 1 (
0dbc3c4dbfd75777c12ca19c337854b1577799901307c482e9d91d5d15
cd934d16319d98e30c4201cf25a1d5a0254960 )`: "uri.arpa.\t3600\tIN\tZONEMD\t2018100702 1 1 0dbc3c4dbfd75777c12ca19c337854b1577799901307c482e9d91d5d15cd934d16319d98e30c4201cf25a1d5a0254960",
// ROOT-SERVERS.NET Zone
`root-servers.net. 3600000 IN ZONEMD 2018091100 1 1 (
f1ca0ccd91bd5573d9f431c00ee0101b2545c97602be0a97
8a3b11dbfc1c776d5b3e86ae3d973d6b5349ba7f04340f79 )
`: "root-servers.net.\t3600000\tIN\tZONEMD\t2018091100 1 1 f1ca0ccd91bd5573d9f431c00ee0101b2545c97602be0a978a3b11dbfc1c776d5b3e86ae3d973d6b5349ba7f04340f79",
}
for i, o := range dt {
rr, err := NewRR(i)
if err != nil {
t.Error("failed to parse RR: ", err)
continue
}
if rr.String() != o {
t.Errorf("`%s' should be equal to\n`%s', but is `%s'", i, o, rr.String())
}
}
}

View File

@ -6,14 +6,13 @@ import "strings"
// RFC 6895. This allows one to experiment with new RR types, without requesting an
// official type code. Also see dns.PrivateHandle and dns.PrivateHandleRemove.
type PrivateRdata interface {
// String returns the text presentaton of the Rdata of the Private RR.
// String returns the text presentation of the Rdata of the Private RR.
String() string
// Parse parses the Rdata of the private RR.
Parse([]string) error
// Pack is used when packing a private RR into a buffer.
Pack([]byte) (int, error)
// Unpack is used when unpacking a private RR from a buffer.
// TODO(miek): diff. signature than Pack, see edns0.go for instance.
Unpack([]byte) (int, error)
// Copy copies the Rdata into the PrivateRdata argument.
Copy(PrivateRdata) error
@ -91,7 +90,7 @@ Fetch:
return nil
}
func (r1 *PrivateRR) isDuplicate(r2 RR) bool { return false }
func (r *PrivateRR) isDuplicate(r2 RR) bool { return false }
// PrivateHandle registers a private resource record type. It requires
// string and numeric representation of private RR type and generator function as argument.

View File

@ -158,9 +158,11 @@ func TestPrivateZoneParser(t *testing.T) {
defer dns.PrivateHandleRemove(TypeVERSION)
r := strings.NewReader(smallzone)
for x := range dns.ParseZone(r, ".", "") {
if err := x.Error; err != nil {
t.Fatal(err)
}
z := dns.NewZoneParser(r, ".", "")
for _, ok := z.Next(); ok; _, ok = z.Next() {
}
if err := z.Err(); err != nil {
t.Fatal(err)
}
}

View File

@ -1,19 +0,0 @@
package dns
import "testing"
const LinodeAddr = "176.58.119.54:53"
func TestClientRemote(t *testing.T) {
m := new(Msg)
m.SetQuestion("go.dns.miek.nl.", TypeTXT)
c := new(Client)
r, _, err := c.Exchange(m, LinodeAddr)
if err != nil {
t.Errorf("failed to exchange: %v", err)
}
if r != nil && r.Rcode != RcodeSuccess {
t.Errorf("failed to get an valid answer\n%v", r)
}
}

179
scan.go
View File

@ -87,31 +87,18 @@ type lex struct {
column int // column in the file
}
// Token holds the token that are returned when a zone file is parsed.
type Token struct {
// The scanned resource record when error is not nil.
RR
// When an error occurred, this has the error specifics.
Error *ParseError
// A potential comment positioned after the RR and on the same line.
Comment string
}
// ttlState describes the state necessary to fill in an omitted RR TTL
type ttlState struct {
ttl uint32 // ttl is the current default TTL
isByDirective bool // isByDirective indicates whether ttl was set by a $TTL directive
}
// NewRR reads the RR contained in the string s. Only the first RR is
// returned. If s contains no records, NewRR will return nil with no
// error.
// NewRR reads the RR contained in the string s. Only the first RR is returned.
// If s contains no records, NewRR will return nil with no error.
//
// The class defaults to IN and TTL defaults to 3600. The full zone
// file syntax like $TTL, $ORIGIN, etc. is supported.
//
// All fields of the returned RR are set, except RR.Header().Rdlength
// which is set to 0.
// The class defaults to IN and TTL defaults to 3600. The full zone file syntax
// like $TTL, $ORIGIN, etc. is supported. All fields of the returned RR are
// set, except RR.Header().Rdlength which is set to 0.
func NewRR(s string) (RR, error) {
if len(s) > 0 && s[len(s)-1] != '\n' { // We need a closing newline
return ReadRR(strings.NewReader(s+"\n"), "")
@ -133,69 +120,6 @@ func ReadRR(r io.Reader, file string) (RR, error) {
return rr, zp.Err()
}
// ParseZone reads a RFC 1035 style zonefile from r. It returns
// *Tokens on the returned channel, each consisting of either a
// parsed RR and optional comment or a nil RR and an error. The
// channel is closed by ParseZone when the end of r is reached.
//
// 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.
//
// The directives $INCLUDE, $ORIGIN, $TTL and $GENERATE are all
// supported.
//
// Basic usage pattern when reading from a string (z) containing the
// zone data:
//
// for x := range dns.ParseZone(strings.NewReader(z), "", "") {
// if x.Error != nil {
// // log.Println(x.Error)
// } else {
// // Do something with x.RR
// }
// }
//
// 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 in Token.Comment.
// Comments inside the RR are returned concatenated along with the
// RR. Comments on a line by themselves are discarded.
//
// To prevent memory leaks it is important to always fully drain the
// returned channel. If an error occurs, it will always be the last
// Token sent on the channel.
//
// Deprecated: New users should prefer the ZoneParser API.
func ParseZone(r io.Reader, origin, file string) chan *Token {
t := make(chan *Token, 10000)
go parseZone(r, origin, file, t)
return t
}
func parseZone(r io.Reader, origin, file string, t chan *Token) {
defer close(t)
zp := NewZoneParser(r, origin, file)
zp.SetIncludeAllowed(true)
for rr, ok := zp.Next(); ok; rr, ok = zp.Next() {
t <- &Token{RR: rr, Comment: zp.Comment()}
}
if err := zp.Err(); err != nil {
pe, ok := err.(*ParseError)
if !ok {
pe = &ParseError{file: file, err: err.Error()}
}
t <- &Token{Error: pe}
}
}
// ZoneParser is a parser for an RFC 1035 style zonefile.
//
// Each parsed RR in the zone is returned sequentially from Next. An
@ -203,6 +127,7 @@ func parseZone(r io.Reader, origin, file string, t chan *Token) {
//
// 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:
@ -225,6 +150,9 @@ func parseZone(r io.Reader, origin, file string, t chan *Token) {
// 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 an Resource Record is
// syntactically correct, e.g. illegal base64 in RRSIGs will be returned as-is.
type ZoneParser struct {
c *zlexer
@ -245,7 +173,8 @@ type ZoneParser struct {
includeDepth uint8
includeAllowed bool
includeAllowed bool
generateDisallowed bool
}
// NewZoneParser returns an RFC 1035 style zonefile parser that reads
@ -545,6 +474,9 @@ func (zp *ZoneParser) Next() (RR, bool) {
st = zExpectDirGenerate
case zExpectDirGenerate:
if zp.generateDisallowed {
return zp.setParseError("nested $GENERATE directive not allowed", l)
}
if l.value != zString {
return zp.setParseError("expecting $GENERATE value, not this...", l)
}
@ -648,10 +580,23 @@ func (zp *ZoneParser) Next() (RR, bool) {
st = zExpectRdata
case zExpectRdata:
var rr RR
if newFn, ok := TypeToRR[h.Rrtype]; ok && canParseAsRR(h.Rrtype) {
var (
rr RR
parseAsRFC3597 bool
)
if newFn, ok := TypeToRR[h.Rrtype]; ok {
rr = newFn()
*rr.Header() = *h
// We may be parsing a known RR type using the RFC3597 format.
// If so, we handle that here in a generic way.
//
// This is also true for PrivateRR types which will have the
// RFC3597 parsing done for them and the Unpack method called
// to populate the RR instead of simply deferring to Parse.
if zp.c.Peek().token == "\\#" {
parseAsRFC3597 = true
}
} else {
rr = &RFC3597{Hdr: *h}
}
@ -671,13 +616,18 @@ func (zp *ZoneParser) Next() (RR, bool) {
return zp.setParseError("unexpected newline", l)
}
if err := rr.parse(zp.c, zp.origin); err != nil {
parseAsRR := rr
if parseAsRFC3597 {
parseAsRR = &RFC3597{Hdr: *h}
}
if err := parseAsRR.parse(zp.c, zp.origin); err != nil {
// err is a concrete *ParseError without the file field set.
// The setParseError call below will construct a new
// *ParseError with file set to zp.file.
// If err.lex is nil than we have encounter an unknown RR type
// in that case we substitute our current lex token.
// err.lex may be nil in which case we substitute our current
// lex token.
if err.lex == (lex{}) {
return zp.setParseError(err.err, l)
}
@ -685,6 +635,13 @@ func (zp *ZoneParser) Next() (RR, bool) {
return zp.setParseError(err.err, err.lex)
}
if parseAsRFC3597 {
err := parseAsRR.(*RFC3597).fromRFC3597(rr)
if err != nil {
return zp.setParseError(err.Error(), l)
}
}
return rr, true
}
}
@ -694,18 +651,6 @@ func (zp *ZoneParser) Next() (RR, bool) {
return nil, false
}
// canParseAsRR returns true if the record type can be parsed as a
// concrete RR. It blacklists certain record types that must be parsed
// according to RFC 3597 because they lack a presentation format.
func canParseAsRR(rrtype uint16) bool {
switch rrtype {
case TypeANY, TypeNULL, TypeOPT, TypeTSIG:
return false
default:
return true
}
}
type zlexer struct {
br io.ByteReader
@ -968,6 +913,11 @@ func (zl *zlexer) Next() (lex, bool) {
// was inside braces and we delayed adding it until now.
com[comi] = ' ' // convert newline to space
comi++
if comi >= len(com) {
l.token = "comment length insufficient for parsing"
l.err = true
return *l, true
}
}
com[comi] = ';'
@ -1276,11 +1226,29 @@ func stringToCm(token string) (e, m uint8, ok bool) {
if cmeters, err = strconv.Atoi(s[1]); err != nil {
return
}
// There's no point in having more than 2 digits in this part, and would rather make the implementation complicated ('123' should be treated as '12').
// So we simply reject it.
// We also make sure the first character is a digit to reject '+-' signs.
if len(s[1]) > 2 || s[1][0] < '0' || s[1][0] > '9' {
return
}
if len(s[1]) == 1 {
// 'nn.1' must be treated as 'nn-meters and 10cm, not 1cm.
cmeters *= 10
}
if s[0] == "" {
// This will allow omitting the 'meter' part, like .01 (meaning 0.01m = 1cm).
break
}
fallthrough
case 1:
if meters, err = strconv.Atoi(s[0]); err != nil {
return
}
// RFC1876 states the max value is 90000000.00. The latter two conditions enforce it.
if s[0][0] < '0' || s[0][0] > '9' || meters > 90000000 || (meters == 90000000 && cmeters != 0) {
return
}
case 0:
// huh?
return 0, 0, false
@ -1293,13 +1261,10 @@ func stringToCm(token string) (e, m uint8, ok bool) {
e = 0
val = cmeters
}
for val > 10 {
for val >= 10 {
e++
val /= 10
}
if e > 9 {
ok = false
}
m = uint8(val)
return
}
@ -1341,6 +1306,9 @@ func appendOrigin(name, origin string) string {
// LOC record helper function
func locCheckNorth(token string, latitude uint32) (uint32, bool) {
if latitude > 90*1000*60*60 {
return latitude, false
}
switch token {
case "n", "N":
return LOC_EQUATOR + latitude, true
@ -1352,6 +1320,9 @@ func locCheckNorth(token string, latitude uint32) (uint32, bool) {
// LOC record helper function
func locCheckEast(token string, longitude uint32) (uint32, bool) {
if longitude > 180*1000*60*60 {
return longitude, false
}
switch token {
case "e", "E":
return LOC_EQUATOR + longitude, true
@ -1384,7 +1355,7 @@ func stringToNodeID(l lex) (uint64, *ParseError) {
if len(l.token) < 19 {
return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l}
}
// There must be three colons at fixes postitions, if not its a parse error
// There must be three colons at fixes positions, if not its a parse error
if l.token[4] != ':' && l.token[9] != ':' && l.token[14] != ':' {
return 0, &ParseError{l.token, "bad NID/L64 NodeID/Locator64", l}
}

View File

@ -1,6 +1,7 @@
package dns
import (
"bytes"
"encoding/base64"
"net"
"strconv"
@ -10,15 +11,15 @@ import (
// A remainder of the rdata with embedded spaces, return the parsed string (sans the spaces)
// or an error
func endingToString(c *zlexer, errstr string) (string, *ParseError) {
var s string
var buffer bytes.Buffer
l, _ := c.Next() // zString
for l.value != zNewline && l.value != zEOF {
if l.err {
return s, &ParseError{"", errstr, l}
return buffer.String(), &ParseError{"", errstr, l}
}
switch l.value {
case zString:
s += l.token
buffer.WriteString(l.token)
case zBlank: // Ok
default:
return "", &ParseError{"", errstr, l}
@ -26,7 +27,7 @@ func endingToString(c *zlexer, errstr string) (string, *ParseError) {
l, _ = c.Next()
}
return s, nil
return buffer.String(), nil
}
// A remainder of the rdata with embedded spaces, split on unquoted whitespace
@ -403,7 +404,7 @@ func (rr *SOA) parse(c *zlexer, o string) *ParseError {
if l.err {
return &ParseError{"", "bad SOA zone parameter", l}
}
if j, e := strconv.ParseUint(l.token, 10, 32); e != nil {
if j, err := strconv.ParseUint(l.token, 10, 32); err != nil {
if i == 0 {
// Serial must be a number
return &ParseError{"", "bad SOA zone parameter", l}
@ -446,16 +447,16 @@ func (rr *SRV) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 16)
if e1 != nil || l.err {
return &ParseError{"", "bad SRV Weight", l}
}
rr.Weight = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 16)
if e2 != nil || l.err {
return &ParseError{"", "bad SRV Port", l}
}
rr.Port = uint16(i)
@ -482,8 +483,8 @@ func (rr *NAPTR) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 16)
if e1 != nil || l.err {
return &ParseError{"", "bad NAPTR Preference", l}
}
rr.Preference = uint16(i)
@ -581,15 +582,15 @@ func (rr *TALINK) parse(c *zlexer, o string) *ParseError {
func (rr *LOC) parse(c *zlexer, o string) *ParseError {
// Non zero defaults for LOC record, see RFC 1876, Section 3.
rr.HorizPre = 165 // 10000
rr.VertPre = 162 // 10
rr.Size = 18 // 1
rr.Size = 0x12 // 1e2 cm (1m)
rr.HorizPre = 0x16 // 1e6 cm (10000m)
rr.VertPre = 0x13 // 1e3 cm (10m)
ok := false
// North
l, _ := c.Next()
i, e := strconv.ParseUint(l.token, 10, 32)
if e != nil || l.err {
if e != nil || l.err || i > 90 {
return &ParseError{"", "bad LOC Latitude", l}
}
rr.Latitude = 1000 * 60 * 60 * uint32(i)
@ -600,15 +601,15 @@ func (rr *LOC) parse(c *zlexer, o string) *ParseError {
if rr.Latitude, ok = locCheckNorth(l.token, rr.Latitude); ok {
goto East
}
i, e = strconv.ParseUint(l.token, 10, 32)
if e != nil || l.err {
if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 59 {
return &ParseError{"", "bad LOC Latitude minutes", l}
} else {
rr.Latitude += 1000 * 60 * uint32(i)
}
rr.Latitude += 1000 * 60 * uint32(i)
c.Next() // zBlank
l, _ = c.Next()
if i, e := strconv.ParseFloat(l.token, 32); e != nil || l.err {
if i, err := strconv.ParseFloat(l.token, 64); err != nil || l.err || i < 0 || i >= 60 {
return &ParseError{"", "bad LOC Latitude seconds", l}
} else {
rr.Latitude += uint32(1000 * i)
@ -626,7 +627,7 @@ East:
// East
c.Next() // zBlank
l, _ = c.Next()
if i, e := strconv.ParseUint(l.token, 10, 32); e != nil || l.err {
if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 180 {
return &ParseError{"", "bad LOC Longitude", l}
} else {
rr.Longitude = 1000 * 60 * 60 * uint32(i)
@ -637,14 +638,14 @@ East:
if rr.Longitude, ok = locCheckEast(l.token, rr.Longitude); ok {
goto Altitude
}
if i, e := strconv.ParseUint(l.token, 10, 32); e != nil || l.err {
if i, err := strconv.ParseUint(l.token, 10, 32); err != nil || l.err || i > 59 {
return &ParseError{"", "bad LOC Longitude minutes", l}
} else {
rr.Longitude += 1000 * 60 * uint32(i)
}
c.Next() // zBlank
l, _ = c.Next()
if i, e := strconv.ParseFloat(l.token, 32); e != nil || l.err {
if i, err := strconv.ParseFloat(l.token, 64); err != nil || l.err || i < 0 || i >= 60 {
return &ParseError{"", "bad LOC Longitude seconds", l}
} else {
rr.Longitude += uint32(1000 * i)
@ -661,13 +662,13 @@ East:
Altitude:
c.Next() // zBlank
l, _ = c.Next()
if len(l.token) == 0 || l.err {
if l.token == "" || l.err {
return &ParseError{"", "bad LOC Altitude", l}
}
if l.token[len(l.token)-1] == 'M' || l.token[len(l.token)-1] == 'm' {
l.token = l.token[0 : len(l.token)-1]
}
if i, e := strconv.ParseFloat(l.token, 32); e != nil {
if i, err := strconv.ParseFloat(l.token, 64); err != nil {
return &ParseError{"", "bad LOC Altitude", l}
} else {
rr.Altitude = uint32(i*100.0 + 10000000.0 + 0.5)
@ -681,23 +682,23 @@ Altitude:
case zString:
switch count {
case 0: // Size
e, m, ok := stringToCm(l.token)
exp, m, ok := stringToCm(l.token)
if !ok {
return &ParseError{"", "bad LOC Size", l}
}
rr.Size = e&0x0f | m<<4&0xf0
rr.Size = exp&0x0f | m<<4&0xf0
case 1: // HorizPre
e, m, ok := stringToCm(l.token)
exp, m, ok := stringToCm(l.token)
if !ok {
return &ParseError{"", "bad LOC HorizPre", l}
}
rr.HorizPre = e&0x0f | m<<4&0xf0
rr.HorizPre = exp&0x0f | m<<4&0xf0
case 2: // VertPre
e, m, ok := stringToCm(l.token)
exp, m, ok := stringToCm(l.token)
if !ok {
return &ParseError{"", "bad LOC VertPre", l}
}
rr.VertPre = e&0x0f | m<<4&0xf0
rr.VertPre = exp&0x0f | m<<4&0xf0
}
count++
case zBlank:
@ -721,7 +722,7 @@ func (rr *HIP) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next() // zString
if len(l.token) == 0 || l.err {
if l.token == "" || l.err {
return &ParseError{"", "bad HIP Hit", l}
}
rr.Hit = l.token // This can not contain spaces, see RFC 5205 Section 6.
@ -729,11 +730,15 @@ func (rr *HIP) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next() // zString
if len(l.token) == 0 || l.err {
if l.token == "" || l.err {
return &ParseError{"", "bad HIP PublicKey", l}
}
rr.PublicKey = l.token // This cannot contain spaces
rr.PublicKeyLength = uint16(base64.StdEncoding.DecodedLen(len(rr.PublicKey)))
decodedPK, decodedPKerr := base64.StdEncoding.DecodeString(rr.PublicKey)
if decodedPKerr != nil {
return &ParseError{"", "bad HIP PublicKey", l}
}
rr.PublicKeyLength = uint16(len(decodedPK))
// RendezvousServers (if any)
l, _ = c.Next()
@ -762,7 +767,7 @@ func (rr *CERT) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
if v, ok := StringToCertType[l.token]; ok {
rr.Type = v
} else if i, e := strconv.ParseUint(l.token, 10, 16); e != nil {
} else if i, err := strconv.ParseUint(l.token, 10, 16); err != nil {
return &ParseError{"", "bad CERT Type", l}
} else {
rr.Type = uint16(i)
@ -778,7 +783,7 @@ func (rr *CERT) parse(c *zlexer, o string) *ParseError {
l, _ = c.Next() // zString
if v, ok := StringToAlgorithm[l.token]; ok {
rr.Algorithm = v
} else if i, e := strconv.ParseUint(l.token, 10, 8); e != nil {
} else if i, err := strconv.ParseUint(l.token, 10, 8); err != nil {
return &ParseError{"", "bad CERT Algorithm", l}
} else {
rr.Algorithm = uint8(i)
@ -812,8 +817,8 @@ func (rr *CSYNC) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next()
j, e = strconv.ParseUint(l.token, 10, 16)
if e != nil {
j, e1 := strconv.ParseUint(l.token, 10, 16)
if e1 != nil {
// Serial must be a number
return &ParseError{"", "bad CSYNC flags", l}
}
@ -845,10 +850,40 @@ func (rr *CSYNC) parse(c *zlexer, o string) *ParseError {
return nil
}
func (rr *SIG) parse(c *zlexer, o string) *ParseError {
return rr.RRSIG.parse(c, o)
func (rr *ZONEMD) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
i, e := strconv.ParseUint(l.token, 10, 32)
if e != nil || l.err {
return &ParseError{"", "bad ZONEMD Serial", l}
}
rr.Serial = uint32(i)
c.Next() // zBlank
l, _ = c.Next()
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad ZONEMD Scheme", l}
}
rr.Scheme = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, err := strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
return &ParseError{"", "bad ZONEMD Hash Algorithm", l}
}
rr.Hash = uint8(i)
s, e2 := endingToString(c, "bad ZONEMD Digest")
if e2 != nil {
return e2
}
rr.Digest = s
return nil
}
func (rr *SIG) parse(c *zlexer, o string) *ParseError { return rr.RRSIG.parse(c, o) }
func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
tokenUpper := strings.ToUpper(l.token)
@ -868,24 +903,24 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next()
i, err := strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
i, e := strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
return &ParseError{"", "bad RRSIG Algorithm", l}
}
rr.Algorithm = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, err = strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad RRSIG Labels", l}
}
rr.Labels = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, err = strconv.ParseUint(l.token, 10, 32)
if err != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 32)
if e2 != nil || l.err {
return &ParseError{"", "bad RRSIG OrigTtl", l}
}
rr.OrigTtl = uint32(i)
@ -894,8 +929,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
l, _ = c.Next()
if i, err := StringToTime(l.token); err != nil {
// Try to see if all numeric and use it as epoch
if i, err := strconv.ParseInt(l.token, 10, 64); err == nil {
// TODO(miek): error out on > MAX_UINT32, same below
if i, err := strconv.ParseUint(l.token, 10, 32); err == nil {
rr.Expiration = uint32(i)
} else {
return &ParseError{"", "bad RRSIG Expiration", l}
@ -907,7 +941,7 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next()
if i, err := StringToTime(l.token); err != nil {
if i, err := strconv.ParseInt(l.token, 10, 64); err == nil {
if i, err := strconv.ParseUint(l.token, 10, 32); err == nil {
rr.Inception = uint32(i)
} else {
return &ParseError{"", "bad RRSIG Inception", l}
@ -918,8 +952,8 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next()
i, err = strconv.ParseUint(l.token, 10, 16)
if err != nil || l.err {
i, e3 := strconv.ParseUint(l.token, 10, 16)
if e3 != nil || l.err {
return &ParseError{"", "bad RRSIG KeyTag", l}
}
rr.KeyTag = uint16(i)
@ -933,9 +967,9 @@ func (rr *RRSIG) parse(c *zlexer, o string) *ParseError {
}
rr.SignerName = name
s, e := endingToString(c, "bad RRSIG Signature")
if e != nil {
return e
s, e4 := endingToString(c, "bad RRSIG Signature")
if e4 != nil {
return e4
}
rr.Signature = s
@ -985,21 +1019,21 @@ func (rr *NSEC3) parse(c *zlexer, o string) *ParseError {
rr.Hash = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad NSEC3 Flags", l}
}
rr.Flags = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 16)
if e2 != nil || l.err {
return &ParseError{"", "bad NSEC3 Iterations", l}
}
rr.Iterations = uint16(i)
c.Next()
l, _ = c.Next()
if len(l.token) == 0 || l.err {
if l.token == "" || l.err {
return &ParseError{"", "bad NSEC3 Salt", l}
}
if l.token != "-" {
@ -1009,7 +1043,7 @@ func (rr *NSEC3) parse(c *zlexer, o string) *ParseError {
c.Next()
l, _ = c.Next()
if len(l.token) == 0 || l.err {
if l.token == "" || l.err {
return &ParseError{"", "bad NSEC3 NextDomain", l}
}
rr.HashLength = 20 // Fix for NSEC3 (sha1 160 bits)
@ -1050,22 +1084,22 @@ func (rr *NSEC3PARAM) parse(c *zlexer, o string) *ParseError {
rr.Hash = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad NSEC3PARAM Flags", l}
}
rr.Flags = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 16)
if e2 != nil || l.err {
return &ParseError{"", "bad NSEC3PARAM Iterations", l}
}
rr.Iterations = uint16(i)
c.Next()
l, _ = c.Next()
if l.token != "-" {
rr.SaltLength = uint8(len(l.token))
rr.SaltLength = uint8(len(l.token) / 2)
rr.Salt = l.token
}
return slurpRemainder(c)
@ -1132,15 +1166,15 @@ func (rr *SSHFP) parse(c *zlexer, o string) *ParseError {
rr.Algorithm = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad SSHFP Type", l}
}
rr.Type = uint8(i)
c.Next() // zBlank
s, e1 := endingToString(c, "bad SSHFP Fingerprint")
if e1 != nil {
return e1
s, e2 := endingToString(c, "bad SSHFP Fingerprint")
if e2 != nil {
return e2
}
rr.FingerPrint = s
return nil
@ -1155,37 +1189,32 @@ func (rr *DNSKEY) parseDNSKEY(c *zlexer, o, typ string) *ParseError {
rr.Flags = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad " + typ + " Protocol", l}
}
rr.Protocol = uint8(i)
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 8)
if e2 != nil || l.err {
return &ParseError{"", "bad " + typ + " Algorithm", l}
}
rr.Algorithm = uint8(i)
s, e1 := endingToString(c, "bad "+typ+" PublicKey")
if e1 != nil {
return e1
s, e3 := endingToString(c, "bad "+typ+" PublicKey")
if e3 != nil {
return e3
}
rr.PublicKey = s
return nil
}
func (rr *DNSKEY) parse(c *zlexer, o string) *ParseError {
return rr.parseDNSKEY(c, o, "DNSKEY")
}
func (rr *KEY) parse(c *zlexer, o string) *ParseError {
return rr.parseDNSKEY(c, o, "KEY")
}
func (rr *CDNSKEY) parse(c *zlexer, o string) *ParseError {
return rr.parseDNSKEY(c, o, "CDNSKEY")
}
func (rr *DNSKEY) parse(c *zlexer, o string) *ParseError { return rr.parseDNSKEY(c, o, "DNSKEY") }
func (rr *KEY) parse(c *zlexer, o string) *ParseError { return rr.parseDNSKEY(c, o, "KEY") }
func (rr *CDNSKEY) parse(c *zlexer, o string) *ParseError { return rr.parseDNSKEY(c, o, "CDNSKEY") }
func (rr *DS) parse(c *zlexer, o string) *ParseError { return rr.parseDS(c, o, "DS") }
func (rr *DLV) parse(c *zlexer, o string) *ParseError { return rr.parseDS(c, o, "DLV") }
func (rr *CDS) parse(c *zlexer, o string) *ParseError { return rr.parseDS(c, o, "CDS") }
func (rr *RKEY) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
@ -1196,21 +1225,21 @@ func (rr *RKEY) parse(c *zlexer, o string) *ParseError {
rr.Flags = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad RKEY Protocol", l}
}
rr.Protocol = uint8(i)
c.Next() // zBlank
l, _ = c.Next() // zString
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 8)
if e2 != nil || l.err {
return &ParseError{"", "bad RKEY Algorithm", l}
}
rr.Algorithm = uint8(i)
s, e1 := endingToString(c, "bad RKEY PublicKey")
if e1 != nil {
return e1
s, e3 := endingToString(c, "bad RKEY PublicKey")
if e3 != nil {
return e3
}
rr.PublicKey = s
return nil
@ -1243,15 +1272,15 @@ func (rr *GPOS) parse(c *zlexer, o string) *ParseError {
rr.Longitude = l.token
c.Next() // zBlank
l, _ = c.Next()
_, e = strconv.ParseFloat(l.token, 64)
if e != nil || l.err {
_, e1 := strconv.ParseFloat(l.token, 64)
if e1 != nil || l.err {
return &ParseError{"", "bad GPOS Latitude", l}
}
rr.Latitude = l.token
c.Next() // zBlank
l, _ = c.Next()
_, e = strconv.ParseFloat(l.token, 64)
if e != nil || l.err {
_, e2 := strconv.ParseFloat(l.token, 64)
if e2 != nil || l.err {
return &ParseError{"", "bad GPOS Altitude", l}
}
rr.Altitude = l.token
@ -1267,7 +1296,7 @@ func (rr *DS) parseDS(c *zlexer, o, typ string) *ParseError {
rr.KeyTag = uint16(i)
c.Next() // zBlank
l, _ = c.Next()
if i, e = strconv.ParseUint(l.token, 10, 8); e != nil {
if i, err := strconv.ParseUint(l.token, 10, 8); err != nil {
tokenUpper := strings.ToUpper(l.token)
i, ok := StringToAlgorithm[tokenUpper]
if !ok || l.err {
@ -1279,31 +1308,19 @@ func (rr *DS) parseDS(c *zlexer, o, typ string) *ParseError {
}
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad " + typ + " DigestType", l}
}
rr.DigestType = uint8(i)
s, e1 := endingToString(c, "bad "+typ+" Digest")
if e1 != nil {
return e1
s, e2 := endingToString(c, "bad "+typ+" Digest")
if e2 != nil {
return e2
}
rr.Digest = s
return nil
}
func (rr *DS) parse(c *zlexer, o string) *ParseError {
return rr.parseDS(c, o, "DS")
}
func (rr *DLV) parse(c *zlexer, o string) *ParseError {
return rr.parseDS(c, o, "DLV")
}
func (rr *CDS) parse(c *zlexer, o string) *ParseError {
return rr.parseDS(c, o, "CDS")
}
func (rr *TA) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
i, e := strconv.ParseUint(l.token, 10, 16)
@ -1313,7 +1330,7 @@ func (rr *TA) parse(c *zlexer, o string) *ParseError {
rr.KeyTag = uint16(i)
c.Next() // zBlank
l, _ = c.Next()
if i, e := strconv.ParseUint(l.token, 10, 8); e != nil {
if i, err := strconv.ParseUint(l.token, 10, 8); err != nil {
tokenUpper := strings.ToUpper(l.token)
i, ok := StringToAlgorithm[tokenUpper]
if !ok || l.err {
@ -1325,14 +1342,14 @@ func (rr *TA) parse(c *zlexer, o string) *ParseError {
}
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad TA DigestType", l}
}
rr.DigestType = uint8(i)
s, err := endingToString(c, "bad TA Digest")
if err != nil {
return err
s, e2 := endingToString(c, "bad TA Digest")
if e2 != nil {
return e2
}
rr.Digest = s
return nil
@ -1347,22 +1364,22 @@ func (rr *TLSA) parse(c *zlexer, o string) *ParseError {
rr.Usage = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad TLSA Selector", l}
}
rr.Selector = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 8)
if e2 != nil || l.err {
return &ParseError{"", "bad TLSA MatchingType", l}
}
rr.MatchingType = uint8(i)
// So this needs be e2 (i.e. different than e), because...??t
s, e2 := endingToString(c, "bad TLSA Certificate")
if e2 != nil {
return e2
s, e3 := endingToString(c, "bad TLSA Certificate")
if e3 != nil {
return e3
}
rr.Certificate = s
return nil
@ -1377,22 +1394,22 @@ func (rr *SMIMEA) parse(c *zlexer, o string) *ParseError {
rr.Usage = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad SMIMEA Selector", l}
}
rr.Selector = uint8(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
i, e2 := strconv.ParseUint(l.token, 10, 8)
if e2 != nil || l.err {
return &ParseError{"", "bad SMIMEA MatchingType", l}
}
rr.MatchingType = uint8(i)
// So this needs be e2 (i.e. different than e), because...??t
s, e2 := endingToString(c, "bad SMIMEA Certificate")
if e2 != nil {
return e2
s, e3 := endingToString(c, "bad SMIMEA Certificate")
if e3 != nil {
return e3
}
rr.Certificate = s
return nil
@ -1406,7 +1423,7 @@ func (rr *RFC3597) parse(c *zlexer, o string) *ParseError {
c.Next() // zBlank
l, _ = c.Next()
rdlength, e := strconv.Atoi(l.token)
rdlength, e := strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
return &ParseError{"", "bad RFC3597 Rdata ", l}
}
@ -1415,7 +1432,7 @@ func (rr *RFC3597) parse(c *zlexer, o string) *ParseError {
if e1 != nil {
return e1
}
if rdlength*2 != len(s) {
if int(rdlength)*2 != len(s) {
return &ParseError{"", "bad RFC3597 Rdata", l}
}
rr.Rdata = s
@ -1469,16 +1486,16 @@ func (rr *URI) parse(c *zlexer, o string) *ParseError {
rr.Priority = uint16(i)
c.Next() // zBlank
l, _ = c.Next()
i, e = strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 16)
if e1 != nil || l.err {
return &ParseError{"", "bad URI Weight", l}
}
rr.Weight = uint16(i)
c.Next() // zBlank
s, err := endingToTxtSlice(c, "bad URI Target")
if err != nil {
return err
s, e2 := endingToTxtSlice(c, "bad URI Target")
if e2 != nil {
return e2
}
if len(s) != 1 {
return &ParseError{"", "bad URI Target", l}
@ -1506,9 +1523,9 @@ func (rr *NID) parse(c *zlexer, o string) *ParseError {
rr.Preference = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
u, err := stringToNodeID(l)
if err != nil || l.err {
return err
u, e1 := stringToNodeID(l)
if e1 != nil || l.err {
return e1
}
rr.NodeID = u
return slurpRemainder(c)
@ -1546,7 +1563,6 @@ func (rr *LP) parse(c *zlexer, o string) *ParseError {
return &ParseError{"", "bad LP Fqdn", l}
}
rr.Fqdn = name
return slurpRemainder(c)
}
@ -1559,9 +1575,9 @@ func (rr *L64) parse(c *zlexer, o string) *ParseError {
rr.Preference = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
u, err := stringToNodeID(l)
if err != nil || l.err {
return err
u, e1 := stringToNodeID(l)
if e1 != nil || l.err {
return e1
}
rr.Locator64 = u
return slurpRemainder(c)
@ -1624,14 +1640,13 @@ func (rr *PX) parse(c *zlexer, o string) *ParseError {
return &ParseError{"", "bad PX Mapx400", l}
}
rr.Mapx400 = mapx400
return slurpRemainder(c)
}
func (rr *CAA) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
i, err := strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
i, e := strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
return &ParseError{"", "bad CAA Flag", l}
}
rr.Flag = uint8(i)
@ -1644,9 +1659,9 @@ func (rr *CAA) parse(c *zlexer, o string) *ParseError {
rr.Tag = l.token
c.Next() // zBlank
s, e := endingToTxtSlice(c, "bad CAA Value")
if e != nil {
return e
s, e1 := endingToTxtSlice(c, "bad CAA Value")
if e1 != nil {
return e1
}
if len(s) != 1 {
return &ParseError{"", "bad CAA Value", l}
@ -1667,8 +1682,8 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError {
// Get the key length and key values
l, _ = c.Next()
i, err := strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
i, e := strconv.ParseUint(l.token, 10, 8)
if e != nil || l.err {
return &ParseError{"", "bad TKEY key length", l}
}
rr.KeySize = uint16(i)
@ -1682,8 +1697,8 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError {
// Get the otherdata length and string data
l, _ = c.Next()
i, err = strconv.ParseUint(l.token, 10, 8)
if err != nil || l.err {
i, e1 := strconv.ParseUint(l.token, 10, 8)
if e1 != nil || l.err {
return &ParseError{"", "bad TKEY otherdata length", l}
}
rr.OtherLen = uint16(i)
@ -1693,6 +1708,71 @@ func (rr *TKEY) parse(c *zlexer, o string) *ParseError {
return &ParseError{"", "bad TKEY otherday", l}
}
rr.OtherData = l.token
return nil
}
func (rr *APL) parse(c *zlexer, o string) *ParseError {
var prefixes []APLPrefix
for {
l, _ := c.Next()
if l.value == zNewline || l.value == zEOF {
break
}
if l.value == zBlank && prefixes != nil {
continue
}
if l.value != zString {
return &ParseError{"", "unexpected APL field", l}
}
// Expected format: [!]afi:address/prefix
colon := strings.IndexByte(l.token, ':')
if colon == -1 {
return &ParseError{"", "missing colon in APL field", l}
}
family, cidr := l.token[:colon], l.token[colon+1:]
var negation bool
if family != "" && family[0] == '!' {
negation = true
family = family[1:]
}
afi, e := strconv.ParseUint(family, 10, 16)
if e != nil {
return &ParseError{"", "failed to parse APL family: " + e.Error(), l}
}
var addrLen int
switch afi {
case 1:
addrLen = net.IPv4len
case 2:
addrLen = net.IPv6len
default:
return &ParseError{"", "unrecognized APL family", l}
}
ip, subnet, e1 := net.ParseCIDR(cidr)
if e1 != nil {
return &ParseError{"", "failed to parse APL address: " + e1.Error(), l}
}
if !ip.Equal(subnet.IP) {
return &ParseError{"", "extra bits in APL address", l}
}
if len(subnet.IP) != addrLen {
return &ParseError{"", "address mismatch with the APL family", l}
}
prefixes = append(prefixes, APLPrefix{
Negation: negation,
Network: *subnet,
})
}
rr.Prefixes = prefixes
return nil
}

View File

@ -9,7 +9,7 @@ import (
"testing"
)
func TestParseZoneGenerate(t *testing.T) {
func TestZoneParserGenerate(t *testing.T) {
zone := "$ORIGIN example.org.\n$GENERATE 10-12 foo${2,3,d} IN A 127.0.0.$"
wantRRs := []RR{
@ -17,22 +17,21 @@ func TestParseZoneGenerate(t *testing.T) {
&A{Hdr: RR_Header{Name: "foo013.example.org."}, A: net.ParseIP("127.0.0.11")},
&A{Hdr: RR_Header{Name: "foo014.example.org."}, A: net.ParseIP("127.0.0.12")},
}
wantIdx := 0
tok := ParseZone(strings.NewReader(zone), "", "")
for x := range tok {
z := NewZoneParser(strings.NewReader(zone), "", "")
for rr, ok := z.Next(); ok; rr, ok = z.Next() {
if wantIdx >= len(wantRRs) {
t.Fatalf("expected %d RRs, but got more", len(wantRRs))
}
if x.Error != nil {
t.Fatalf("expected no error, but got %s", x.Error)
}
if got, want := x.RR.Header().Name, wantRRs[wantIdx].Header().Name; got != want {
if got, want := rr.Header().Name, wantRRs[wantIdx].Header().Name; got != want {
t.Fatalf("expected name %s, but got %s", want, got)
}
a, ok := x.RR.(*A)
if !ok {
t.Fatalf("expected *A RR, but got %T", x.RR)
a, okA := rr.(*A)
if !okA {
t.Fatalf("expected *A RR, but got %T", rr)
}
if got, want := a.A, wantRRs[wantIdx].(*A).A; !got.Equal(want) {
t.Fatalf("expected A with IP %v, but got %v", got, want)
@ -40,12 +39,16 @@ func TestParseZoneGenerate(t *testing.T) {
wantIdx++
}
if err := z.Err(); err != nil {
t.Fatalf("expected no error, but got %s", err)
}
if wantIdx != len(wantRRs) {
t.Errorf("too few records, expected %d, got %d", len(wantRRs), wantIdx)
}
}
func TestParseZoneInclude(t *testing.T) {
func TestZoneParserInclude(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "dns")
if err != nil {
@ -63,18 +66,19 @@ func TestParseZoneInclude(t *testing.T) {
zone := "$ORIGIN example.org.\n$INCLUDE " + tmpfile.Name() + "\nbar\tIN\tA\t127.0.0.2"
var got int
tok := ParseZone(strings.NewReader(zone), "", "")
for x := range tok {
if x.Error != nil {
t.Fatalf("expected no error, but got %s", x.Error)
}
switch x.RR.Header().Name {
z := NewZoneParser(strings.NewReader(zone), "", "")
z.SetIncludeAllowed(true)
for rr, ok := z.Next(); ok; _, ok = z.Next() {
switch rr.Header().Name {
case "foo.example.org.", "bar.example.org.":
default:
t.Fatalf("expected foo.example.org. or bar.example.org., but got %s", x.RR.Header().Name)
t.Fatalf("expected foo.example.org. or bar.example.org., but got %s", rr.Header().Name)
}
got++
}
if err := z.Err(); err != nil {
t.Fatalf("expected no error, but got %s", err)
}
if expected := 2; got != expected {
t.Errorf("failed to parse zone after include, expected %d records, got %d", expected, got)
@ -82,17 +86,15 @@ func TestParseZoneInclude(t *testing.T) {
os.Remove(tmpfile.Name())
tok = ParseZone(strings.NewReader(zone), "", "")
for x := range tok {
if x.Error == nil {
t.Fatalf("expected first token to contain an error but it didn't")
}
if !strings.Contains(x.Error.Error(), "failed to open") ||
!strings.Contains(x.Error.Error(), tmpfile.Name()) ||
!strings.Contains(x.Error.Error(), "no such file or directory") {
t.Fatalf(`expected error to contain: "failed to open", %q and "no such file or directory" but got: %s`,
tmpfile.Name(), x.Error)
}
z = NewZoneParser(strings.NewReader(zone), "", "")
z.SetIncludeAllowed(true)
z.Next()
if err := z.Err(); err == nil ||
!strings.Contains(err.Error(), "failed to open") ||
!strings.Contains(err.Error(), tmpfile.Name()) ||
!strings.Contains(err.Error(), "no such file or directory") {
t.Fatalf(`expected error to contain: "failed to open", %q and "no such file or directory" but got: %s`,
tmpfile.Name(), err)
}
}
@ -143,10 +145,10 @@ func TestZoneParserAddressAAAA(t *testing.T) {
}
aaaa, ok := got.(*AAAA)
if !ok {
t.Fatalf("expected *AAAA RR, but got %T", aaaa)
t.Fatalf("expected *AAAA RR, but got %T", got)
}
if g, w := aaaa.AAAA, tc.want.AAAA; !g.Equal(w) {
t.Fatalf("expected AAAA with IP %v, but got %v", g, w)
if !aaaa.AAAA.Equal(tc.want.AAAA) {
t.Fatalf("expected AAAA with IP %v, but got %v", tc.want.AAAA, aaaa.AAAA)
}
}
}
@ -227,6 +229,63 @@ example.com. 60 PX (
}
}
func TestParseRFC3597InvalidLength(t *testing.T) {
// We need to space separate the 00s otherwise it will exceed the maximum token size
// of the zone lexer.
_, err := NewRR("example. 3600 CLASS1 TYPE1 \\# 65536 " + strings.Repeat("00 ", 65536))
if err == nil {
t.Error("should not have parsed excessively long RFC3579 record")
}
}
func TestParseKnownRRAsRFC3597(t *testing.T) {
t.Run("with RDATA", func(t *testing.T) {
// This was found by oss-fuzz.
_, err := NewRR("example. 3600 tYpe44 \\# 03 75 0100")
if err != nil {
t.Errorf("failed to parse RFC3579 format: %v", err)
}
rr, err := NewRR("example. 3600 CLASS1 TYPE1 \\# 4 7f000001")
if err != nil {
t.Fatalf("failed to parse RFC3579 format: %v", err)
}
if rr.Header().Rrtype != TypeA {
t.Errorf("expected TypeA (1) Rrtype, but got %v", rr.Header().Rrtype)
}
a, ok := rr.(*A)
if !ok {
t.Fatalf("expected *A RR, but got %T", rr)
}
localhost := net.IPv4(127, 0, 0, 1)
if !a.A.Equal(localhost) {
t.Errorf("expected A with IP %v, but got %v", localhost, a.A)
}
})
t.Run("without RDATA", func(t *testing.T) {
rr, err := NewRR("example. 3600 CLASS1 TYPE1 \\# 0")
if err != nil {
t.Fatalf("failed to parse RFC3579 format: %v", err)
}
if rr.Header().Rrtype != TypeA {
t.Errorf("expected TypeA (1) Rrtype, but got %v", rr.Header().Rrtype)
}
a, ok := rr.(*A)
if !ok {
t.Fatalf("expected *A RR, but got %T", rr)
}
if len(a.A) != 0 {
t.Errorf("expected A with empty IP, but got %v", a.A)
}
})
}
func BenchmarkNewRR(b *testing.B) {
const name1 = "12345678901234567890123456789012345.12345678.123."
const s = name1 + " 3600 IN MX 10 " + name1
@ -274,16 +333,6 @@ foo. IN NSEC miek.nl. TXT RRSIG NSEC; this is comment 7
foo. IN TXT "THIS IS TEXT MAN"; this is comment 8
`
func BenchmarkParseZone(b *testing.B) {
for n := 0; n < b.N; n++ {
for tok := range ParseZone(strings.NewReader(benchZone), "example.org.", "") {
if tok.Error != nil {
b.Fatal(tok.Error)
}
}
}
}
func BenchmarkZoneParser(b *testing.B) {
for n := 0; n < b.N; n++ {
zp := NewZoneParser(strings.NewReader(benchZone), "example.org.", "")

View File

@ -1,7 +1,6 @@
package dns
import (
"strings"
"sync"
)
@ -36,7 +35,7 @@ func (mux *ServeMux) match(q string, t uint16) Handler {
return nil
}
q = strings.ToLower(q)
q = CanonicalName(q)
var handler Handler
for off, end := 0, false; !end; off, end = NextLabel(q, off) {
@ -66,7 +65,7 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) {
if mux.z == nil {
mux.z = make(map[string]Handler)
}
mux.z[Fqdn(pattern)] = handler
mux.z[CanonicalName(pattern)] = handler
mux.m.Unlock()
}
@ -81,7 +80,7 @@ func (mux *ServeMux) HandleRemove(pattern string) {
panic("dns: invalid pattern " + pattern)
}
mux.m.Lock()
delete(mux.z, Fqdn(pattern))
delete(mux.z, CanonicalName(pattern))
mux.m.Unlock()
}
@ -92,7 +91,7 @@ func (mux *ServeMux) HandleRemove(pattern string) {
// are redirected to the parent zone (if that is also registered),
// otherwise the child gets the query.
//
// If no handler is found, or there is no question, a standard SERVFAIL
// If no handler is found, or there is no question, a standard REFUSED
// message is returned
func (mux *ServeMux) ServeDNS(w ResponseWriter, req *Msg) {
var h Handler
@ -103,7 +102,7 @@ func (mux *ServeMux) ServeDNS(w ResponseWriter, req *Msg) {
if h != nil {
h.ServeDNS(w, req)
} else {
HandleFailed(w, req)
handleRefused(w, req)
}
}

160
server.go
View File

@ -18,7 +18,7 @@ import (
const maxTCPQueries = 128
// aLongTimeAgo is a non-zero time, far in the past, used for
// immediate cancelation of network operations.
// immediate cancellation of network operations.
var aLongTimeAgo = time.Unix(1, 0)
// Handler is implemented by any value that implements ServeDNS.
@ -71,14 +71,23 @@ type response struct {
tsigTimersOnly bool
tsigStatus error
tsigRequestMAC string
tsigSecret map[string]string // the tsig secrets
udp *net.UDPConn // i/o connection if UDP was used
tcp net.Conn // i/o connection if TCP was used
udpSession *SessionUDP // oob data to get egress interface right
writer Writer // writer to output the raw DNS bits
tsigProvider TsigProvider
udp net.PacketConn // i/o connection if UDP was used
tcp net.Conn // i/o connection if TCP was used
udpSession *SessionUDP // oob data to get egress interface right
pcSession net.Addr // address to use when writing to a generic net.PacketConn
writer Writer // writer to output the raw DNS bits
}
// handleRefused returns a HandlerFunc that returns REFUSED for every request it gets.
func handleRefused(w ResponseWriter, r *Msg) {
m := new(Msg)
m.SetRcode(r, RcodeRefused)
w.WriteMsg(m)
}
// HandleFailed returns a HandlerFunc that returns SERVFAIL for every request it gets.
// Deprecated: This function is going away.
func HandleFailed(w ResponseWriter, r *Msg) {
m := new(Msg)
m.SetRcode(r, RcodeServerFailure)
@ -139,12 +148,24 @@ type Reader interface {
ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *SessionUDP, error)
}
// defaultReader is an adapter for the Server struct that implements the Reader interface
// using the readTCP and readUDP func of the embedded Server.
// PacketConnReader is an optional interface that Readers can implement to support using generic net.PacketConns.
type PacketConnReader interface {
Reader
// ReadPacketConn reads a raw message from a generic net.PacketConn UDP connection. Implementations may
// alter connection properties, for example the read-deadline.
ReadPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error)
}
// defaultReader is an adapter for the Server struct that implements the Reader and
// PacketConnReader interfaces using the readTCP, readUDP and readPacketConn funcs
// of the embedded Server.
type defaultReader struct {
*Server
}
var _ PacketConnReader = defaultReader{}
func (dr defaultReader) ReadTCP(conn net.Conn, timeout time.Duration) ([]byte, error) {
return dr.readTCP(conn, timeout)
}
@ -153,8 +174,14 @@ func (dr defaultReader) ReadUDP(conn *net.UDPConn, timeout time.Duration) ([]byt
return dr.readUDP(conn, timeout)
}
func (dr defaultReader) ReadPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error) {
return dr.readPacketConn(conn, timeout)
}
// DecorateReader is a decorator hook for extending or supplanting the functionality of a Reader.
// Implementations should never return a nil Reader.
// Readers should also implement the optional PacketConnReader interface.
// PacketConnReader is required to use a generic net.PacketConn.
type DecorateReader func(Reader) Reader
// DecorateWriter is a decorator hook for extending or supplanting the functionality of a Writer.
@ -184,6 +211,8 @@ type Server struct {
WriteTimeout time.Duration
// TCP idle timeout for multiple queries, if nil, defaults to 8 * time.Second (RFC 5966).
IdleTimeout func() time.Duration
// An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
TsigProvider TsigProvider
// Secret(s) for Tsig map[<zonename>]<base64 secret>. The zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2).
TsigSecret map[string]string
// If NotifyStartedFunc is set it is called once the server has started listening.
@ -211,6 +240,16 @@ type Server struct {
udpPool sync.Pool
}
func (srv *Server) tsigProvider() TsigProvider {
if srv.TsigProvider != nil {
return srv.TsigProvider
}
if srv.TsigSecret != nil {
return tsigSecretProvider(srv.TsigSecret)
}
return nil
}
func (srv *Server) isStarted() bool {
srv.lock.RLock()
started := srv.started
@ -294,6 +333,7 @@ func (srv *Server) ListenAndServe() error {
}
u := l.(*net.UDPConn)
if e := setUDPSocketOptions(u); e != nil {
u.Close()
return e
}
srv.PacketConn = l
@ -317,24 +357,22 @@ func (srv *Server) ActivateAndServe() error {
srv.init()
pConn := srv.PacketConn
l := srv.Listener
if pConn != nil {
if srv.PacketConn != nil {
// Check PacketConn interface's type is valid and value
// is not nil
if t, ok := pConn.(*net.UDPConn); ok && t != nil {
if t, ok := srv.PacketConn.(*net.UDPConn); ok && t != nil {
if e := setUDPSocketOptions(t); e != nil {
return e
}
srv.started = true
unlock()
return srv.serveUDP(t)
}
}
if l != nil {
srv.started = true
unlock()
return srv.serveTCP(l)
return srv.serveUDP(srv.PacketConn)
}
if srv.Listener != nil {
srv.started = true
unlock()
return srv.serveTCP(srv.Listener)
}
return &Error{err: "bad listeners"}
}
@ -438,18 +476,24 @@ func (srv *Server) serveTCP(l net.Listener) error {
}
// serveUDP starts a UDP listener for the server.
func (srv *Server) serveUDP(l *net.UDPConn) error {
func (srv *Server) serveUDP(l net.PacketConn) error {
defer l.Close()
if srv.NotifyStartedFunc != nil {
srv.NotifyStartedFunc()
}
reader := Reader(defaultReader{srv})
if srv.DecorateReader != nil {
reader = srv.DecorateReader(reader)
}
lUDP, isUDP := l.(*net.UDPConn)
readerPC, canPacketConn := reader.(PacketConnReader)
if !isUDP && !canPacketConn {
return &Error{err: "PacketConnReader was not implemented on Reader returned from DecorateReader but is required for net.PacketConn"}
}
if srv.NotifyStartedFunc != nil {
srv.NotifyStartedFunc()
}
var wg sync.WaitGroup
defer func() {
wg.Wait()
@ -459,7 +503,17 @@ func (srv *Server) serveUDP(l *net.UDPConn) error {
rtimeout := srv.getReadTimeout()
// deadline is not used here
for srv.isStarted() {
m, s, err := reader.ReadUDP(l, rtimeout)
var (
m []byte
sPC net.Addr
sUDP *SessionUDP
err error
)
if isUDP {
m, sUDP, err = reader.ReadUDP(lUDP, rtimeout)
} else {
m, sPC, err = readerPC.ReadPacketConn(l, rtimeout)
}
if err != nil {
if !srv.isStarted() {
return nil
@ -476,7 +530,7 @@ func (srv *Server) serveUDP(l *net.UDPConn) error {
continue
}
wg.Add(1)
go srv.serveUDPPacket(&wg, m, l, s)
go srv.serveUDPPacket(&wg, m, l, sUDP, sPC)
}
return nil
@ -484,7 +538,7 @@ func (srv *Server) serveUDP(l *net.UDPConn) error {
// Serve a new TCP connection.
func (srv *Server) serveTCPConn(wg *sync.WaitGroup, rw net.Conn) {
w := &response{tsigSecret: srv.TsigSecret, tcp: rw}
w := &response{tsigProvider: srv.tsigProvider(), tcp: rw}
if srv.DecorateWriter != nil {
w.writer = srv.DecorateWriter(w)
} else {
@ -538,8 +592,8 @@ func (srv *Server) serveTCPConn(wg *sync.WaitGroup, rw net.Conn) {
}
// Serve a new UDP request.
func (srv *Server) serveUDPPacket(wg *sync.WaitGroup, m []byte, u *net.UDPConn, s *SessionUDP) {
w := &response{tsigSecret: srv.TsigSecret, udp: u, udpSession: s}
func (srv *Server) serveUDPPacket(wg *sync.WaitGroup, m []byte, u net.PacketConn, udpSession *SessionUDP, pcSession net.Addr) {
w := &response{tsigProvider: srv.tsigProvider(), udp: u, udpSession: udpSession, pcSession: pcSession}
if srv.DecorateWriter != nil {
w.writer = srv.DecorateWriter(w)
} else {
@ -590,15 +644,11 @@ func (srv *Server) serveDNS(m []byte, w *response) {
}
w.tsigStatus = nil
if w.tsigSecret != nil {
if w.tsigProvider != nil {
if t := req.IsTsig(); t != nil {
if secret, ok := w.tsigSecret[t.Hdr.Name]; ok {
w.tsigStatus = TsigVerify(m, secret, "", false)
} else {
w.tsigStatus = ErrSecret
}
w.tsigStatus = TsigVerifyWithProvider(m, w.tsigProvider, "", false)
w.tsigTimersOnly = false
w.tsigRequestMAC = req.Extra[len(req.Extra)-1].(*TSIG).MAC
w.tsigRequestMAC = t.MAC
}
}
@ -651,6 +701,24 @@ func (srv *Server) readUDP(conn *net.UDPConn, timeout time.Duration) ([]byte, *S
return m, s, nil
}
func (srv *Server) readPacketConn(conn net.PacketConn, timeout time.Duration) ([]byte, net.Addr, error) {
srv.lock.RLock()
if srv.started {
// See the comment in readTCP above.
conn.SetReadDeadline(time.Now().Add(timeout))
}
srv.lock.RUnlock()
m := srv.udpPool.Get().([]byte)
n, addr, err := conn.ReadFrom(m)
if err != nil {
srv.udpPool.Put(m)
return nil, nil, err
}
m = m[:n]
return m, addr, nil
}
// WriteMsg implements the ResponseWriter.WriteMsg method.
func (w *response) WriteMsg(m *Msg) (err error) {
if w.closed {
@ -658,9 +726,9 @@ func (w *response) WriteMsg(m *Msg) (err error) {
}
var data []byte
if w.tsigSecret != nil { // if no secrets, dont check for the tsig (which is a longer check)
if w.tsigProvider != nil { // if no provider, dont check for the tsig (which is a longer check)
if t := m.IsTsig(); t != nil {
data, w.tsigRequestMAC, err = TsigGenerate(m, w.tsigSecret[t.Hdr.Name], w.tsigRequestMAC, w.tsigTimersOnly)
data, w.tsigRequestMAC, err = TsigGenerateWithProvider(m, w.tsigProvider, w.tsigRequestMAC, w.tsigTimersOnly)
if err != nil {
return err
}
@ -684,17 +752,19 @@ func (w *response) Write(m []byte) (int, error) {
switch {
case w.udp != nil:
return WriteToSessionUDP(w.udp, m, w.udpSession)
if u, ok := w.udp.(*net.UDPConn); ok {
return WriteToSessionUDP(u, m, w.udpSession)
}
return w.udp.WriteTo(m, w.pcSession)
case w.tcp != nil:
if len(m) > MaxMsgSize {
return 0, &Error{err: "message too large"}
}
l := make([]byte, 2)
binary.BigEndian.PutUint16(l, uint16(len(m)))
n, err := (&net.Buffers{l, m}).WriteTo(w.tcp)
return int(n), err
msg := make([]byte, 2+len(m))
binary.BigEndian.PutUint16(msg, uint16(len(m)))
copy(msg[2:], m)
return w.tcp.Write(msg)
default:
panic("dns: internal error: udp and tcp both nil")
}
@ -717,10 +787,12 @@ func (w *response) RemoteAddr() net.Addr {
switch {
case w.udpSession != nil:
return w.udpSession.RemoteAddr()
case w.pcSession != nil:
return w.pcSession
case w.tcp != nil:
return w.tcp.RemoteAddr()
default:
panic("dns: internal error: udpSession and tcp both nil")
panic("dns: internal error: udpSession, pcSession and tcp are all nil")
}
}

View File

@ -35,6 +35,19 @@ func HelloServerBadID(w ResponseWriter, req *Msg) {
w.WriteMsg(m)
}
func HelloServerBadThenGoodID(w ResponseWriter, req *Msg) {
m := new(Msg)
m.SetReply(req)
m.Id++
m.Extra = make([]RR, 1)
m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello world"}}
w.WriteMsg(m)
m.Id--
w.WriteMsg(m)
}
func HelloServerEchoAddrPort(w ResponseWriter, req *Msg) {
m := new(Msg)
m.SetReply(req)
@ -54,136 +67,170 @@ func AnotherHelloServer(w ResponseWriter, req *Msg) {
w.WriteMsg(m)
}
func RunLocalUDPServer(laddr string) (*Server, string, error) {
server, l, _, err := RunLocalUDPServerWithFinChan(laddr)
func RunLocalServer(pc net.PacketConn, l net.Listener, opts ...func(*Server)) (*Server, string, chan error, error) {
server := &Server{
PacketConn: pc,
Listener: l,
return server, l, err
}
func RunLocalUDPServerWithFinChan(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
pc, err := net.ListenPacket("udp", laddr)
if err != nil {
return nil, "", nil, err
ReadTimeout: time.Hour,
WriteTimeout: time.Hour,
}
server := &Server{PacketConn: pc, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = waitLock.Unlock
// fin must be buffered so the goroutine below won't block
// forever if fin is never read from. This always happens
// in RunLocalUDPServer and can happen in TestShutdownUDP.
fin := make(chan error, 1)
for _, opt := range opts {
opt(server)
}
var (
addr string
closer io.Closer
)
if l != nil {
addr = l.Addr().String()
closer = l
} else {
addr = pc.LocalAddr().String()
closer = pc
}
// fin must be buffered so the goroutine below won't block
// forever if fin is never read from. This always happens
// if the channel is discarded and can happen in TestShutdownUDP.
fin := make(chan error, 1)
go func() {
fin <- server.ActivateAndServe()
pc.Close()
closer.Close()
}()
waitLock.Lock()
return server, pc.LocalAddr().String(), fin, nil
return server, addr, fin, nil
}
func RunLocalTCPServer(laddr string) (*Server, string, error) {
server, l, _, err := RunLocalTCPServerWithFinChan(laddr)
func RunLocalUDPServer(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
pc, err := net.ListenPacket("udp", laddr)
if err != nil {
return nil, "", nil, err
}
return server, l, err
return RunLocalServer(pc, nil, opts...)
}
func RunLocalTCPServerWithFinChan(laddr string) (*Server, string, chan error, error) {
func RunLocalPacketConnServer(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
return RunLocalUDPServer(laddr, append(opts, func(srv *Server) {
// Make srv.PacketConn opaque to trigger the generic code paths.
srv.PacketConn = struct{ net.PacketConn }{srv.PacketConn}
})...)
}
func RunLocalTCPServer(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
l, err := net.Listen("tcp", laddr)
if err != nil {
return nil, "", nil, err
}
server := &Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = waitLock.Unlock
// See the comment in RunLocalUDPServerWithFinChan as to
// why fin must be buffered.
fin := make(chan error, 1)
go func() {
fin <- server.ActivateAndServe()
l.Close()
}()
waitLock.Lock()
return server, l.Addr().String(), fin, nil
return RunLocalServer(nil, l, opts...)
}
func RunLocalTLSServer(laddr string, config *tls.Config) (*Server, string, error) {
l, err := tls.Listen("tcp", laddr, config)
func RunLocalTLSServer(laddr string, config *tls.Config) (*Server, string, chan error, error) {
return RunLocalTCPServer(laddr, func(srv *Server) {
srv.Listener = tls.NewListener(srv.Listener, config)
})
}
func RunLocalUnixServer(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
l, err := net.Listen("unix", laddr)
if err != nil {
return nil, "", nil, err
}
return RunLocalServer(nil, l, opts...)
}
func RunLocalUnixGramServer(laddr string, opts ...func(*Server)) (*Server, string, chan error, error) {
pc, err := net.ListenPacket("unixgram", laddr)
if err != nil {
return nil, "", nil, err
}
return RunLocalServer(pc, nil, opts...)
}
func RunLocalUnixSeqPacketServer(laddr string) (chan interface{}, string, error) {
pc, err := net.Listen("unixpacket", laddr)
if err != nil {
return nil, "", err
}
server := &Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = waitLock.Unlock
shutdownChan := make(chan interface{})
go func() {
server.ActivateAndServe()
l.Close()
pc.Accept()
<-shutdownChan
}()
waitLock.Lock()
return server, l.Addr().String(), nil
return shutdownChan, pc.Addr().String(), nil
}
func TestServing(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
HandleFunc("example.com.", AnotherHelloServer)
defer HandleRemove("miek.nl.")
defer HandleRemove("example.com.")
for _, tc := range []struct {
name string
network string
runServer func(laddr string, opts ...func(*Server)) (*Server, string, chan error, error)
}{
{"udp", "udp", RunLocalUDPServer},
{"tcp", "tcp", RunLocalTCPServer},
{"PacketConn", "udp", RunLocalPacketConnServer},
} {
t.Run(tc.name, func(t *testing.T) {
HandleFunc("miek.nl.", HelloServer)
HandleFunc("example.com.", AnotherHelloServer)
defer HandleRemove("miek.nl.")
defer HandleRemove("example.com.")
s, addrstr, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
s, addrstr, _, err := tc.runServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
c := new(Client)
m := new(Msg)
m.SetQuestion("miek.nl.", TypeTXT)
r, _, err := c.Exchange(m, addrstr)
if err != nil || len(r.Extra) == 0 {
t.Fatal("failed to exchange miek.nl", err)
}
txt := r.Extra[0].(*TXT).Txt[0]
if txt != "Hello world" {
t.Error("unexpected result for miek.nl", txt, "!= Hello world")
}
c := &Client{
Net: tc.network,
}
m := new(Msg)
m.SetQuestion("miek.nl.", TypeTXT)
r, _, err := c.Exchange(m, addrstr)
if err != nil || len(r.Extra) == 0 {
t.Fatal("failed to exchange miek.nl", err)
}
txt := r.Extra[0].(*TXT).Txt[0]
if txt != "Hello world" {
t.Error("unexpected result for miek.nl", txt, "!= Hello world")
}
m.SetQuestion("example.com.", TypeTXT)
r, _, err = c.Exchange(m, addrstr)
if err != nil {
t.Fatal("failed to exchange example.com", err)
}
txt = r.Extra[0].(*TXT).Txt[0]
if txt != "Hello example" {
t.Error("unexpected result for example.com", txt, "!= Hello example")
}
m.SetQuestion("example.com.", TypeTXT)
r, _, err = c.Exchange(m, addrstr)
if err != nil {
t.Fatal("failed to exchange example.com", err)
}
txt = r.Extra[0].(*TXT).Txt[0]
if txt != "Hello example" {
t.Error("unexpected result for example.com", txt, "!= Hello example")
}
// Test Mixes cased as noticed by Ask.
m.SetQuestion("eXaMplE.cOm.", TypeTXT)
r, _, err = c.Exchange(m, addrstr)
if err != nil {
t.Error("failed to exchange eXaMplE.cOm", err)
}
txt = r.Extra[0].(*TXT).Txt[0]
if txt != "Hello example" {
t.Error("unexpected result for example.com", txt, "!= Hello example")
// Test Mixes cased as noticed by Ask.
m.SetQuestion("eXaMplE.cOm.", TypeTXT)
r, _, err = c.Exchange(m, addrstr)
if err != nil {
t.Error("failed to exchange eXaMplE.cOm", err)
}
txt = r.Extra[0].(*TXT).Txt[0]
if txt != "Hello example" {
t.Error("unexpected result for example.com", txt, "!= Hello example")
}
})
}
}
@ -191,7 +238,7 @@ func TestServing(t *testing.T) {
func TestServeIgnoresZFlag(t *testing.T) {
HandleFunc("example.com.", AnotherHelloServer)
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -220,7 +267,7 @@ func TestServeNotImplemented(t *testing.T) {
HandleFunc("example.com.", AnotherHelloServer)
opcode := 15
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -229,7 +276,7 @@ func TestServeNotImplemented(t *testing.T) {
c := new(Client)
m := new(Msg)
// Test that Opcode is like the unchanged from request Opcode and that Rcode is set to NotImplemnented
// Test that Opcode is like the unchanged from request Opcode and that Rcode is set to NotImplemented
m.SetQuestion("example.com.", TypeTXT)
m.Opcode = opcode
r, _, err := c.Exchange(m, addrstr)
@ -259,7 +306,7 @@ func TestServingTLS(t *testing.T) {
Certificates: []tls.Certificate{cert},
}
s, addrstr, err := RunLocalTLSServer(":0", &config)
s, addrstr, _, err := RunLocalTLSServer(":0", &config)
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -345,7 +392,7 @@ func TestServingTLSConnectionState(t *testing.T) {
Certificates: []tls.Certificate{cert},
}
s, addrstr, err := RunLocalTLSServer(":0", &config)
s, addrstr, _, err := RunLocalTLSServer(":0", &config)
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -368,7 +415,7 @@ func TestServingTLSConnectionState(t *testing.T) {
// UDP DNS Server
HandleFunc(".", tlsHandlerTLS(false))
defer HandleRemove(".")
s, addrstr, err = RunLocalUDPServer(":0")
s, addrstr, _, err = RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -382,7 +429,7 @@ func TestServingTLSConnectionState(t *testing.T) {
}
// TCP DNS Server
s, addrstr, err = RunLocalTCPServer(":0")
s, addrstr, _, err = RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -466,7 +513,7 @@ func BenchmarkServe(b *testing.B) {
defer HandleRemove("miek.nl.")
a := runtime.GOMAXPROCS(4)
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
b.Fatalf("unable to run test server: %v", err)
}
@ -491,7 +538,7 @@ func BenchmarkServe6(b *testing.B) {
HandleFunc("miek.nl.", HelloServer)
defer HandleRemove("miek.nl.")
a := runtime.GOMAXPROCS(4)
s, addrstr, err := RunLocalUDPServer("[::1]:0")
s, addrstr, _, err := RunLocalUDPServer("[::1]:0")
if err != nil {
if strings.Contains(err.Error(), "bind: cannot assign requested address") {
b.Skip("missing IPv6 support")
@ -528,7 +575,7 @@ func BenchmarkServeCompress(b *testing.B) {
HandleFunc("miek.nl.", HelloServerCompress)
defer HandleRemove("miek.nl.")
a := runtime.GOMAXPROCS(4)
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
b.Fatalf("unable to run test server: %v", err)
}
@ -581,7 +628,7 @@ func TestServingLargeResponses(t *testing.T) {
HandleFunc("example.", HelloServerLargeResponse)
defer HandleRemove("example.")
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -621,7 +668,7 @@ func TestServingResponse(t *testing.T) {
t.Skip("skipping test in short mode.")
}
HandleFunc("miek.nl.", HelloServer)
s, addrstr, err := RunLocalUDPServer(":0")
s, addrstr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -635,7 +682,8 @@ func TestServingResponse(t *testing.T) {
if err != nil {
t.Fatal("failed to exchange", err)
}
m.Response = true
m.Response = true // this holds up the reply, set short read time out to avoid waiting too long
c.ReadTimeout = 100 * time.Millisecond
_, _, err = c.Exchange(m, addrstr)
if err == nil {
t.Fatal("exchanged response message")
@ -643,7 +691,7 @@ func TestServingResponse(t *testing.T) {
}
func TestShutdownTCP(t *testing.T) {
s, _, fin, err := RunLocalTCPServerWithFinChan(":0")
s, _, fin, err := RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -668,7 +716,7 @@ func init() {
}
func checkInProgressQueriesAtShutdownServer(t *testing.T, srv *Server, addr string, client *Client) {
const requests = 100
const requests = 15 // enough to make this interesting? TODO: find a proper value
var errOnce sync.Once
// t.Fail will panic if it's called after the test function has
@ -698,7 +746,7 @@ func checkInProgressQueriesAtShutdownServer(t *testing.T, srv *Server, addr stri
})
defer HandleRemove("example.com.")
client.Timeout = 10 * time.Second
client.Timeout = 1 * time.Second
conns := make([]*Conn, requests)
eg := new(errgroup.Group)
@ -774,7 +822,7 @@ func checkInProgressQueriesAtShutdownServer(t *testing.T, srv *Server, addr stri
}
func TestInProgressQueriesAtShutdownTCP(t *testing.T) {
s, addr, _, err := RunLocalTCPServerWithFinChan(":0")
s, addr, _, err := RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -793,7 +841,7 @@ func TestShutdownTLS(t *testing.T) {
Certificates: []tls.Certificate{cert},
}
s, _, err := RunLocalTLSServer(":0", &config)
s, _, _, err := RunLocalTLSServer(":0", &config)
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -813,7 +861,7 @@ func TestInProgressQueriesAtShutdownTLS(t *testing.T) {
Certificates: []tls.Certificate{cert},
}
s, addr, err := RunLocalTLSServer(":0", &config)
s, addr, _, err := RunLocalTLSServer(":0", &config)
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -828,7 +876,6 @@ func TestInProgressQueriesAtShutdownTLS(t *testing.T) {
}
func TestHandlerCloseTCP(t *testing.T) {
ln, err := net.Listen("tcp", ":0")
if err != nil {
panic(err)
@ -873,7 +920,26 @@ func TestHandlerCloseTCP(t *testing.T) {
}
func TestShutdownUDP(t *testing.T) {
s, _, fin, err := RunLocalUDPServerWithFinChan(":0")
s, _, fin, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
err = s.Shutdown()
if err != nil {
t.Errorf("could not shutdown test UDP server, %v", err)
}
select {
case err := <-fin:
if err != nil {
t.Errorf("error returned from ActivateAndServe, %v", err)
}
case <-time.After(2 * time.Second):
t.Error("could not shutdown test UDP server. Gave up waiting")
}
}
func TestShutdownPacketConn(t *testing.T) {
s, _, fin, err := RunLocalPacketConnServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -892,7 +958,17 @@ func TestShutdownUDP(t *testing.T) {
}
func TestInProgressQueriesAtShutdownUDP(t *testing.T) {
s, addr, _, err := RunLocalUDPServerWithFinChan(":0")
s, addr, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
c := &Client{Net: "udp"}
checkInProgressQueriesAtShutdownServer(t, s, addr, c)
}
func TestInProgressQueriesAtShutdownPacketConn(t *testing.T) {
s, addr, _, err := RunLocalPacketConnServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
@ -905,7 +981,7 @@ func TestServerStartStopRace(t *testing.T) {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
s, _, _, err := RunLocalUDPServerWithFinChan(":0")
s, _, _, err := RunLocalUDPServer(":0")
if err != nil {
t.Fatalf("could not start server: %s", err)
}
@ -968,30 +1044,39 @@ func TestServerReuseport(t *testing.T) {
func TestServerRoundtripTsig(t *testing.T) {
secret := map[string]string{"test.": "so6ZGir4GPAqINNh9U5c3A=="}
s, addrstr, _, err := RunLocalUDPServerWithFinChan(":0", func(srv *Server) {
s, addrstr, _, err := RunLocalUDPServer(":0", func(srv *Server) {
srv.TsigSecret = secret
srv.MsgAcceptFunc = func(dh Header) MsgAcceptAction {
// defaultMsgAcceptFunc does reject UPDATE queries
return MsgAccept
}
})
if err != nil {
t.Fatalf("unable to run test server: %v", err)
}
defer s.Shutdown()
handlerFired := make(chan struct{})
HandleFunc("example.com.", func(w ResponseWriter, r *Msg) {
close(handlerFired)
m := new(Msg)
m.SetReply(r)
if r.IsTsig() != nil {
status := w.TsigStatus()
if status == nil {
// *Msg r has an TSIG record and it was validated
m.SetTsig("test.", HmacMD5, 300, time.Now().Unix())
m.SetTsig("test.", HmacSHA256, 300, time.Now().Unix())
} else {
// *Msg r has an TSIG records and it was not valided
// *Msg r has an TSIG records and it was not validated
t.Errorf("invalid TSIG: %v", status)
}
} else {
t.Error("missing TSIG")
}
w.WriteMsg(m)
if err := w.WriteMsg(m); err != nil {
t.Error("writemsg failed", err)
}
})
c := new(Client)
@ -1008,11 +1093,17 @@ func TestServerRoundtripTsig(t *testing.T) {
Target: "bar.example.com.",
}}
c.TsigSecret = secret
m.SetTsig("test.", HmacMD5, 300, time.Now().Unix())
m.SetTsig("test.", HmacSHA256, 300, time.Now().Unix())
_, _, err = c.Exchange(m, addrstr)
if err != nil {
t.Fatal("failed to exchange", err)
}
select {
case <-handlerFired:
// ok, handler was actually called
default:
t.Error("handler was not called")
}
}
func TestResponseAfterClose(t *testing.T) {
@ -1046,6 +1137,37 @@ func TestResponseDoubleClose(t *testing.T) {
}
}
type countingConn struct {
net.Conn
writes int
}
func (c *countingConn) Write(p []byte) (int, error) {
c.writes++
return len(p), nil
}
func TestResponseWriteSinglePacket(t *testing.T) {
c := &countingConn{}
rw := &response{
tcp: c,
}
rw.writer = rw
m := new(Msg)
m.SetQuestion("miek.nl.", TypeTXT)
m.Response = true
err := rw.WriteMsg(m)
if err != nil {
t.Fatalf("failed to write: %v", err)
}
if c.writes != 1 {
t.Fatalf("incorrect number of Write calls")
}
}
type ExampleFrameLengthWriter struct {
Writer
}

67
sig0.go
View File

@ -2,8 +2,8 @@ package dns
import (
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"encoding/binary"
"math/big"
@ -18,7 +18,7 @@ func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error) {
if k == nil {
return nil, ErrPrivKey
}
if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
if rr.KeyTag == 0 || rr.SignerName == "" || rr.Algorithm == 0 {
return nil, ErrKey
}
@ -39,18 +39,17 @@ func (rr *SIG) Sign(k crypto.Signer, m *Msg) ([]byte, error) {
}
buf = buf[:off:cap(buf)]
hash, ok := AlgorithmToHash[rr.Algorithm]
if !ok {
return nil, ErrAlg
h, cryptohash, err := hashFromAlgorithm(rr.Algorithm)
if err != nil {
return nil, err
}
hasher := hash.New()
// Write SIG rdata
hasher.Write(buf[len(mbuf)+1+2+2+4+2:])
h.Write(buf[len(mbuf)+1+2+2+4+2:])
// Write message
hasher.Write(buf[:len(mbuf)])
h.Write(buf[:len(mbuf)])
signature, err := sign(k, hasher.Sum(nil), hash, rr.Algorithm)
signature, err := sign(k, h.Sum(nil), cryptohash, rr.Algorithm)
if err != nil {
return nil, err
}
@ -79,24 +78,14 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error {
if k == nil {
return ErrKey
}
if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
if rr.KeyTag == 0 || rr.SignerName == "" || rr.Algorithm == 0 {
return ErrKey
}
var hash crypto.Hash
switch rr.Algorithm {
case DSA, RSASHA1:
hash = crypto.SHA1
case RSASHA256, ECDSAP256SHA256:
hash = crypto.SHA256
case ECDSAP384SHA384:
hash = crypto.SHA384
case RSASHA512:
hash = crypto.SHA512
default:
return ErrAlg
h, cryptohash, err := hashFromAlgorithm(rr.Algorithm)
if err != nil {
return err
}
hasher := hash.New()
buflen := len(buf)
qdc := binary.BigEndian.Uint16(buf[4:])
@ -104,7 +93,6 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error {
auc := binary.BigEndian.Uint16(buf[8:])
adc := binary.BigEndian.Uint16(buf[10:])
offset := headerSize
var err error
for i := uint16(0); i < qdc && offset < buflen; i++ {
_, offset, err = UnpackDomainName(buf, offset)
if err != nil {
@ -167,32 +155,21 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error {
return &Error{err: "signer name doesn't match key name"}
}
sigend := offset
hasher.Write(buf[sigstart:sigend])
hasher.Write(buf[:10])
hasher.Write([]byte{
h.Write(buf[sigstart:sigend])
h.Write(buf[:10])
h.Write([]byte{
byte((adc - 1) << 8),
byte(adc - 1),
})
hasher.Write(buf[12:bodyend])
h.Write(buf[12:bodyend])
hashed := hasher.Sum(nil)
hashed := h.Sum(nil)
sig := buf[sigend:]
switch k.Algorithm {
case DSA:
pk := k.publicKeyDSA()
sig = sig[1:]
r := new(big.Int).SetBytes(sig[:len(sig)/2])
s := new(big.Int).SetBytes(sig[len(sig)/2:])
if pk != nil {
if dsa.Verify(pk, hashed, r, s) {
return nil
}
return ErrSig
}
case RSASHA1, RSASHA256, RSASHA512:
pk := k.publicKeyRSA()
if pk != nil {
return rsa.VerifyPKCS1v15(pk, hash, hashed, sig)
return rsa.VerifyPKCS1v15(pk, cryptohash, hashed, sig)
}
case ECDSAP256SHA256, ECDSAP384SHA384:
pk := k.publicKeyECDSA()
@ -204,6 +181,14 @@ func (rr *SIG) Verify(k *KEY, buf []byte) error {
}
return ErrSig
}
case ED25519:
pk := k.publicKeyED25519()
if pk != nil {
if ed25519.Verify(pk, hashed, sig) {
return nil
}
return ErrSig
}
}
return ErrKeyAlg
}

View File

@ -12,23 +12,25 @@ func TestSIG0(t *testing.T) {
}
m := new(Msg)
m.SetQuestion("example.org.", TypeSOA)
for _, alg := range []uint8{ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256, RSASHA512} {
for _, alg := range []uint8{ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256, RSASHA512, ED25519} {
algstr := AlgorithmToString[alg]
keyrr := new(KEY)
keyrr.Hdr.Name = algstr + "."
keyrr.Hdr.Rrtype = TypeKEY
keyrr.Hdr.Class = ClassINET
keyrr.Algorithm = alg
keysize := 1024
keysize := 512
switch alg {
case ECDSAP256SHA256:
case ECDSAP256SHA256, ED25519:
keysize = 256
case ECDSAP384SHA384:
keysize = 384
case RSASHA512:
keysize = 1024
}
pk, err := keyrr.Generate(keysize)
if err != nil {
t.Errorf("failed to generate key for “%s”: %v", algstr, err)
t.Errorf("failed to generate key for %q: %v", algstr, err)
continue
}
now := uint32(time.Now().Unix())
@ -43,16 +45,16 @@ func TestSIG0(t *testing.T) {
sigrr.SignerName = keyrr.Hdr.Name
mb, err := sigrr.Sign(pk.(crypto.Signer), m)
if err != nil {
t.Errorf("failed to sign message using “%s”: %v", algstr, err)
t.Errorf("failed to sign message using %q: %v", algstr, err)
continue
}
m := new(Msg)
if err := m.Unpack(mb); err != nil {
t.Errorf("failed to unpack message signed using “%s”: %v", algstr, err)
t.Errorf("failed to unpack message signed using %q: %v", algstr, err)
continue
}
if len(m.Extra) != 1 {
t.Errorf("missing SIG for message signed using “%s”", algstr)
t.Errorf("missing SIG for message signed using %q", algstr)
continue
}
var sigrrwire *SIG
@ -69,20 +71,20 @@ func TestSIG0(t *testing.T) {
id = "sigrrwire"
}
if err := rr.Verify(keyrr, mb); err != nil {
t.Errorf("failed to verify “%s” signed SIG(%s): %v", algstr, id, err)
t.Errorf("failed to verify %q signed SIG(%s): %v", algstr, id, err)
continue
}
}
mb[13]++
if err := sigrr.Verify(keyrr, mb); err == nil {
t.Errorf("verify succeeded on an altered message using “%s”", algstr)
t.Errorf("verify succeeded on an altered message using %q", algstr)
continue
}
sigrr.Expiration = 2
sigrr.Inception = 1
mb, _ = sigrr.Sign(pk.(crypto.Signer), m)
if err := sigrr.Verify(keyrr, mb); err == nil {
t.Errorf("verify succeeded on an expired message using “%s”", algstr)
t.Errorf("verify succeeded on an expired message using %q", algstr)
continue
}
}

935
svcb.go Normal file
View File

@ -0,0 +1,935 @@
package dns
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"sort"
"strconv"
"strings"
)
// SVCBKey is the type of the keys used in the SVCB RR.
type SVCBKey uint16
// Keys defined in draft-ietf-dnsop-svcb-https-08 Section 14.3.2.
const (
SVCB_MANDATORY SVCBKey = iota
SVCB_ALPN
SVCB_NO_DEFAULT_ALPN
SVCB_PORT
SVCB_IPV4HINT
SVCB_ECHCONFIG
SVCB_IPV6HINT
SVCB_DOHPATH // draft-ietf-add-svcb-dns-02 Section 9
svcb_RESERVED SVCBKey = 65535
)
var svcbKeyToStringMap = map[SVCBKey]string{
SVCB_MANDATORY: "mandatory",
SVCB_ALPN: "alpn",
SVCB_NO_DEFAULT_ALPN: "no-default-alpn",
SVCB_PORT: "port",
SVCB_IPV4HINT: "ipv4hint",
SVCB_ECHCONFIG: "ech",
SVCB_IPV6HINT: "ipv6hint",
SVCB_DOHPATH: "dohpath",
}
var svcbStringToKeyMap = reverseSVCBKeyMap(svcbKeyToStringMap)
func reverseSVCBKeyMap(m map[SVCBKey]string) map[string]SVCBKey {
n := make(map[string]SVCBKey, len(m))
for u, s := range m {
n[s] = u
}
return n
}
// String takes the numerical code of an SVCB key and returns its name.
// Returns an empty string for reserved keys.
// Accepts unassigned keys as well as experimental/private keys.
func (key SVCBKey) String() string {
if x := svcbKeyToStringMap[key]; x != "" {
return x
}
if key == svcb_RESERVED {
return ""
}
return "key" + strconv.FormatUint(uint64(key), 10)
}
// svcbStringToKey returns the numerical code of an SVCB key.
// Returns svcb_RESERVED for reserved/invalid keys.
// Accepts unassigned keys as well as experimental/private keys.
func svcbStringToKey(s string) SVCBKey {
if strings.HasPrefix(s, "key") {
a, err := strconv.ParseUint(s[3:], 10, 16)
// no leading zeros
// key shouldn't be registered
if err != nil || a == 65535 || s[3] == '0' || svcbKeyToStringMap[SVCBKey(a)] != "" {
return svcb_RESERVED
}
return SVCBKey(a)
}
if key, ok := svcbStringToKeyMap[s]; ok {
return key
}
return svcb_RESERVED
}
func (rr *SVCB) parse(c *zlexer, o string) *ParseError {
l, _ := c.Next()
i, e := strconv.ParseUint(l.token, 10, 16)
if e != nil || l.err {
return &ParseError{l.token, "bad SVCB priority", l}
}
rr.Priority = uint16(i)
c.Next() // zBlank
l, _ = c.Next() // zString
rr.Target = l.token
name, nameOk := toAbsoluteName(l.token, o)
if l.err || !nameOk {
return &ParseError{l.token, "bad SVCB Target", l}
}
rr.Target = name
// Values (if any)
l, _ = c.Next()
var xs []SVCBKeyValue
// Helps require whitespace between pairs.
// Prevents key1000="a"key1001=...
canHaveNextKey := true
for l.value != zNewline && l.value != zEOF {
switch l.value {
case zString:
if !canHaveNextKey {
// The key we can now read was probably meant to be
// a part of the last value.
return &ParseError{l.token, "bad SVCB value quotation", l}
}
// In key=value pairs, value does not have to be quoted unless value
// contains whitespace. And keys don't need to have values.
// Similarly, keys with an equality signs after them don't need values.
// l.token includes at least up to the first equality sign.
idx := strings.IndexByte(l.token, '=')
var key, value string
if idx < 0 {
// Key with no value and no equality sign
key = l.token
} else if idx == 0 {
return &ParseError{l.token, "bad SVCB key", l}
} else {
key, value = l.token[:idx], l.token[idx+1:]
if value == "" {
// We have a key and an equality sign. Maybe we have nothing
// after "=" or we have a double quote.
l, _ = c.Next()
if l.value == zQuote {
// Only needed when value ends with double quotes.
// Any value starting with zQuote ends with it.
canHaveNextKey = false
l, _ = c.Next()
switch l.value {
case zString:
// We have a value in double quotes.
value = l.token
l, _ = c.Next()
if l.value != zQuote {
return &ParseError{l.token, "SVCB unterminated value", l}
}
case zQuote:
// There's nothing in double quotes.
default:
return &ParseError{l.token, "bad SVCB value", l}
}
}
}
}
kv := makeSVCBKeyValue(svcbStringToKey(key))
if kv == nil {
return &ParseError{l.token, "bad SVCB key", l}
}
if err := kv.parse(value); err != nil {
return &ParseError{l.token, err.Error(), l}
}
xs = append(xs, kv)
case zQuote:
return &ParseError{l.token, "SVCB key can't contain double quotes", l}
case zBlank:
canHaveNextKey = true
default:
return &ParseError{l.token, "bad SVCB values", l}
}
l, _ = c.Next()
}
// "In AliasMode, records SHOULD NOT include any SvcParams, and recipients MUST
// ignore any SvcParams that are present."
// However, we don't check rr.Priority == 0 && len(xs) > 0 here
// It is the responsibility of the user of the library to check this.
// This is to encourage the fixing of the source of this error.
rr.Value = xs
return nil
}
// makeSVCBKeyValue returns an SVCBKeyValue struct with the key or nil for reserved keys.
func makeSVCBKeyValue(key SVCBKey) SVCBKeyValue {
switch key {
case SVCB_MANDATORY:
return new(SVCBMandatory)
case SVCB_ALPN:
return new(SVCBAlpn)
case SVCB_NO_DEFAULT_ALPN:
return new(SVCBNoDefaultAlpn)
case SVCB_PORT:
return new(SVCBPort)
case SVCB_IPV4HINT:
return new(SVCBIPv4Hint)
case SVCB_ECHCONFIG:
return new(SVCBECHConfig)
case SVCB_IPV6HINT:
return new(SVCBIPv6Hint)
case SVCB_DOHPATH:
return new(SVCBDoHPath)
case svcb_RESERVED:
return nil
default:
e := new(SVCBLocal)
e.KeyCode = key
return e
}
}
// SVCB RR. See RFC xxxx (https://tools.ietf.org/html/draft-ietf-dnsop-svcb-https-08).
//
// NOTE: The HTTPS/SVCB RFCs are in the draft stage.
// The API, including constants and types related to SVCBKeyValues, may
// change in future versions in accordance with the latest drafts.
type SVCB struct {
Hdr RR_Header
Priority uint16 // If zero, Value must be empty or discarded by the user of this library
Target string `dns:"domain-name"`
Value []SVCBKeyValue `dns:"pairs"`
}
// HTTPS RR. Everything valid for SVCB applies to HTTPS as well.
// Except that the HTTPS record is intended for use with the HTTP and HTTPS protocols.
//
// NOTE: The HTTPS/SVCB RFCs are in the draft stage.
// The API, including constants and types related to SVCBKeyValues, may
// change in future versions in accordance with the latest drafts.
type HTTPS struct {
SVCB
}
func (rr *HTTPS) String() string {
return rr.SVCB.String()
}
func (rr *HTTPS) parse(c *zlexer, o string) *ParseError {
return rr.SVCB.parse(c, o)
}
// SVCBKeyValue defines a key=value pair for the SVCB RR type.
// An SVCB RR can have multiple SVCBKeyValues appended to it.
type SVCBKeyValue interface {
Key() SVCBKey // Key returns the numerical key code.
pack() ([]byte, error) // pack returns the encoded value.
unpack([]byte) error // unpack sets the value.
String() string // String returns the string representation of the value.
parse(string) error // parse sets the value to the given string representation of the value.
copy() SVCBKeyValue // copy returns a deep-copy of the pair.
len() int // len returns the length of value in the wire format.
}
// SVCBMandatory pair adds to required keys that must be interpreted for the RR
// to be functional. If ignored, the whole RRSet must be ignored.
// "port" and "no-default-alpn" are mandatory by default if present,
// so they shouldn't be included here.
//
// It is incumbent upon the user of this library to reject the RRSet if
// or avoid constructing such an RRSet that:
// - "mandatory" is included as one of the keys of mandatory
// - no key is listed multiple times in mandatory
// - all keys listed in mandatory are present
// - escape sequences are not used in mandatory
// - mandatory, when present, lists at least one key
//
// Basic use pattern for creating a mandatory option:
//
// s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
// e := new(dns.SVCBMandatory)
// e.Code = []uint16{dns.SVCB_ALPN}
// s.Value = append(s.Value, e)
// t := new(dns.SVCBAlpn)
// t.Alpn = []string{"xmpp-client"}
// s.Value = append(s.Value, t)
type SVCBMandatory struct {
Code []SVCBKey
}
func (*SVCBMandatory) Key() SVCBKey { return SVCB_MANDATORY }
func (s *SVCBMandatory) String() string {
str := make([]string, len(s.Code))
for i, e := range s.Code {
str[i] = e.String()
}
return strings.Join(str, ",")
}
func (s *SVCBMandatory) pack() ([]byte, error) {
codes := append([]SVCBKey(nil), s.Code...)
sort.Slice(codes, func(i, j int) bool {
return codes[i] < codes[j]
})
b := make([]byte, 2*len(codes))
for i, e := range codes {
binary.BigEndian.PutUint16(b[2*i:], uint16(e))
}
return b, nil
}
func (s *SVCBMandatory) unpack(b []byte) error {
if len(b)%2 != 0 {
return errors.New("dns: svcbmandatory: value length is not a multiple of 2")
}
codes := make([]SVCBKey, 0, len(b)/2)
for i := 0; i < len(b); i += 2 {
// We assume strictly increasing order.
codes = append(codes, SVCBKey(binary.BigEndian.Uint16(b[i:])))
}
s.Code = codes
return nil
}
func (s *SVCBMandatory) parse(b string) error {
str := strings.Split(b, ",")
codes := make([]SVCBKey, 0, len(str))
for _, e := range str {
codes = append(codes, svcbStringToKey(e))
}
s.Code = codes
return nil
}
func (s *SVCBMandatory) len() int {
return 2 * len(s.Code)
}
func (s *SVCBMandatory) copy() SVCBKeyValue {
return &SVCBMandatory{
append([]SVCBKey(nil), s.Code...),
}
}
// SVCBAlpn pair is used to list supported connection protocols.
// The user of this library must ensure that at least one protocol is listed when alpn is present.
// Protocol IDs can be found at:
// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
// Basic use pattern for creating an alpn option:
//
// h := new(dns.HTTPS)
// h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
// e := new(dns.SVCBAlpn)
// e.Alpn = []string{"h2", "http/1.1"}
// h.Value = append(h.Value, e)
type SVCBAlpn struct {
Alpn []string
}
func (*SVCBAlpn) Key() SVCBKey { return SVCB_ALPN }
func (s *SVCBAlpn) String() string {
// An ALPN value is a comma-separated list of values, each of which can be
// an arbitrary binary value. In order to allow parsing, the comma and
// backslash characters are themselves escaped.
//
// However, this escaping is done in addition to the normal escaping which
// happens in zone files, meaning that these values must be
// double-escaped. This looks terrible, so if you see a never-ending
// sequence of backslash in a zone file this may be why.
//
// https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-08#appendix-A.1
var str strings.Builder
for i, alpn := range s.Alpn {
// 4*len(alpn) is the worst case where we escape every character in the alpn as \123, plus 1 byte for the ',' separating the alpn from others
str.Grow(4*len(alpn) + 1)
if i > 0 {
str.WriteByte(',')
}
for j := 0; j < len(alpn); j++ {
e := alpn[j]
if ' ' > e || e > '~' {
str.WriteString(escapeByte(e))
continue
}
switch e {
// We escape a few characters which may confuse humans or parsers.
case '"', ';', ' ':
str.WriteByte('\\')
str.WriteByte(e)
// The comma and backslash characters themselves must be
// doubly-escaped. We use `\\` for the first backslash and
// the escaped numeric value for the other value. We especially
// don't want a comma in the output.
case ',':
str.WriteString(`\\\044`)
case '\\':
str.WriteString(`\\\092`)
default:
str.WriteByte(e)
}
}
}
return str.String()
}
func (s *SVCBAlpn) pack() ([]byte, error) {
// Liberally estimate the size of an alpn as 10 octets
b := make([]byte, 0, 10*len(s.Alpn))
for _, e := range s.Alpn {
if e == "" {
return nil, errors.New("dns: svcbalpn: empty alpn-id")
}
if len(e) > 255 {
return nil, errors.New("dns: svcbalpn: alpn-id too long")
}
b = append(b, byte(len(e)))
b = append(b, e...)
}
return b, nil
}
func (s *SVCBAlpn) unpack(b []byte) error {
// Estimate the size of the smallest alpn as 4 bytes
alpn := make([]string, 0, len(b)/4)
for i := 0; i < len(b); {
length := int(b[i])
i++
if i+length > len(b) {
return errors.New("dns: svcbalpn: alpn array overflowing")
}
alpn = append(alpn, string(b[i:i+length]))
i += length
}
s.Alpn = alpn
return nil
}
func (s *SVCBAlpn) parse(b string) error {
if len(b) == 0 {
s.Alpn = []string{}
return nil
}
alpn := []string{}
a := []byte{}
for p := 0; p < len(b); {
c, q := nextByte(b, p)
if q == 0 {
return errors.New("dns: svcbalpn: unterminated escape")
}
p += q
// If we find a comma, we have finished reading an alpn.
if c == ',' {
if len(a) == 0 {
return errors.New("dns: svcbalpn: empty protocol identifier")
}
alpn = append(alpn, string(a))
a = []byte{}
continue
}
// If it's a backslash, we need to handle a comma-separated list.
if c == '\\' {
dc, dq := nextByte(b, p)
if dq == 0 {
return errors.New("dns: svcbalpn: unterminated escape decoding comma-separated list")
}
if dc != '\\' && dc != ',' {
return errors.New("dns: svcbalpn: bad escaped character decoding comma-separated list")
}
p += dq
c = dc
}
a = append(a, c)
}
// Add the final alpn.
if len(a) == 0 {
return errors.New("dns: svcbalpn: last protocol identifier empty")
}
s.Alpn = append(alpn, string(a))
return nil
}
func (s *SVCBAlpn) len() int {
var l int
for _, e := range s.Alpn {
l += 1 + len(e)
}
return l
}
func (s *SVCBAlpn) copy() SVCBKeyValue {
return &SVCBAlpn{
append([]string(nil), s.Alpn...),
}
}
// SVCBNoDefaultAlpn pair signifies no support for default connection protocols.
// Should be used in conjunction with alpn.
// Basic use pattern for creating a no-default-alpn option:
//
// s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
// t := new(dns.SVCBAlpn)
// t.Alpn = []string{"xmpp-client"}
// s.Value = append(s.Value, t)
// e := new(dns.SVCBNoDefaultAlpn)
// s.Value = append(s.Value, e)
type SVCBNoDefaultAlpn struct{}
func (*SVCBNoDefaultAlpn) Key() SVCBKey { return SVCB_NO_DEFAULT_ALPN }
func (*SVCBNoDefaultAlpn) copy() SVCBKeyValue { return &SVCBNoDefaultAlpn{} }
func (*SVCBNoDefaultAlpn) pack() ([]byte, error) { return []byte{}, nil }
func (*SVCBNoDefaultAlpn) String() string { return "" }
func (*SVCBNoDefaultAlpn) len() int { return 0 }
func (*SVCBNoDefaultAlpn) unpack(b []byte) error {
if len(b) != 0 {
return errors.New("dns: svcbnodefaultalpn: no-default-alpn must have no value")
}
return nil
}
func (*SVCBNoDefaultAlpn) parse(b string) error {
if b != "" {
return errors.New("dns: svcbnodefaultalpn: no-default-alpn must have no value")
}
return nil
}
// SVCBPort pair defines the port for connection.
// Basic use pattern for creating a port option:
//
// s := &dns.SVCB{Hdr: dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}}
// e := new(dns.SVCBPort)
// e.Port = 80
// s.Value = append(s.Value, e)
type SVCBPort struct {
Port uint16
}
func (*SVCBPort) Key() SVCBKey { return SVCB_PORT }
func (*SVCBPort) len() int { return 2 }
func (s *SVCBPort) String() string { return strconv.FormatUint(uint64(s.Port), 10) }
func (s *SVCBPort) copy() SVCBKeyValue { return &SVCBPort{s.Port} }
func (s *SVCBPort) unpack(b []byte) error {
if len(b) != 2 {
return errors.New("dns: svcbport: port length is not exactly 2 octets")
}
s.Port = binary.BigEndian.Uint16(b)
return nil
}
func (s *SVCBPort) pack() ([]byte, error) {
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, s.Port)
return b, nil
}
func (s *SVCBPort) parse(b string) error {
port, err := strconv.ParseUint(b, 10, 16)
if err != nil {
return errors.New("dns: svcbport: port out of range")
}
s.Port = uint16(port)
return nil
}
// SVCBIPv4Hint pair suggests an IPv4 address which may be used to open connections
// if A and AAAA record responses for SVCB's Target domain haven't been received.
// In that case, optionally, A and AAAA requests can be made, after which the connection
// to the hinted IP address may be terminated and a new connection may be opened.
// Basic use pattern for creating an ipv4hint option:
//
// h := new(dns.HTTPS)
// h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
// e := new(dns.SVCBIPv4Hint)
// e.Hint = []net.IP{net.IPv4(1,1,1,1).To4()}
//
// Or
//
// e.Hint = []net.IP{net.ParseIP("1.1.1.1").To4()}
// h.Value = append(h.Value, e)
type SVCBIPv4Hint struct {
Hint []net.IP
}
func (*SVCBIPv4Hint) Key() SVCBKey { return SVCB_IPV4HINT }
func (s *SVCBIPv4Hint) len() int { return 4 * len(s.Hint) }
func (s *SVCBIPv4Hint) pack() ([]byte, error) {
b := make([]byte, 0, 4*len(s.Hint))
for _, e := range s.Hint {
x := e.To4()
if x == nil {
return nil, errors.New("dns: svcbipv4hint: expected ipv4, hint is ipv6")
}
b = append(b, x...)
}
return b, nil
}
func (s *SVCBIPv4Hint) unpack(b []byte) error {
if len(b) == 0 || len(b)%4 != 0 {
return errors.New("dns: svcbipv4hint: ipv4 address byte array length is not a multiple of 4")
}
x := make([]net.IP, 0, len(b)/4)
for i := 0; i < len(b); i += 4 {
x = append(x, net.IP(b[i:i+4]))
}
s.Hint = x
return nil
}
func (s *SVCBIPv4Hint) String() string {
str := make([]string, len(s.Hint))
for i, e := range s.Hint {
x := e.To4()
if x == nil {
return "<nil>"
}
str[i] = x.String()
}
return strings.Join(str, ",")
}
func (s *SVCBIPv4Hint) parse(b string) error {
if strings.Contains(b, ":") {
return errors.New("dns: svcbipv4hint: expected ipv4, got ipv6")
}
str := strings.Split(b, ",")
dst := make([]net.IP, len(str))
for i, e := range str {
ip := net.ParseIP(e).To4()
if ip == nil {
return errors.New("dns: svcbipv4hint: bad ip")
}
dst[i] = ip
}
s.Hint = dst
return nil
}
func (s *SVCBIPv4Hint) copy() SVCBKeyValue {
hint := make([]net.IP, len(s.Hint))
for i, ip := range s.Hint {
hint[i] = copyIP(ip)
}
return &SVCBIPv4Hint{
Hint: hint,
}
}
// SVCBECHConfig pair contains the ECHConfig structure defined in draft-ietf-tls-esni [RFC xxxx].
// Basic use pattern for creating an ech option:
//
// h := new(dns.HTTPS)
// h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
// e := new(dns.SVCBECHConfig)
// e.ECH = []byte{0xfe, 0x08, ...}
// h.Value = append(h.Value, e)
type SVCBECHConfig struct {
ECH []byte // Specifically ECHConfigList including the redundant length prefix
}
func (*SVCBECHConfig) Key() SVCBKey { return SVCB_ECHCONFIG }
func (s *SVCBECHConfig) String() string { return toBase64(s.ECH) }
func (s *SVCBECHConfig) len() int { return len(s.ECH) }
func (s *SVCBECHConfig) pack() ([]byte, error) {
return append([]byte(nil), s.ECH...), nil
}
func (s *SVCBECHConfig) copy() SVCBKeyValue {
return &SVCBECHConfig{
append([]byte(nil), s.ECH...),
}
}
func (s *SVCBECHConfig) unpack(b []byte) error {
s.ECH = append([]byte(nil), b...)
return nil
}
func (s *SVCBECHConfig) parse(b string) error {
x, err := fromBase64([]byte(b))
if err != nil {
return errors.New("dns: svcbech: bad base64 ech")
}
s.ECH = x
return nil
}
// SVCBIPv6Hint pair suggests an IPv6 address which may be used to open connections
// if A and AAAA record responses for SVCB's Target domain haven't been received.
// In that case, optionally, A and AAAA requests can be made, after which the
// connection to the hinted IP address may be terminated and a new connection may be opened.
// Basic use pattern for creating an ipv6hint option:
//
// h := new(dns.HTTPS)
// h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
// e := new(dns.SVCBIPv6Hint)
// e.Hint = []net.IP{net.ParseIP("2001:db8::1")}
// h.Value = append(h.Value, e)
type SVCBIPv6Hint struct {
Hint []net.IP
}
func (*SVCBIPv6Hint) Key() SVCBKey { return SVCB_IPV6HINT }
func (s *SVCBIPv6Hint) len() int { return 16 * len(s.Hint) }
func (s *SVCBIPv6Hint) pack() ([]byte, error) {
b := make([]byte, 0, 16*len(s.Hint))
for _, e := range s.Hint {
if len(e) != net.IPv6len || e.To4() != nil {
return nil, errors.New("dns: svcbipv6hint: expected ipv6, hint is ipv4")
}
b = append(b, e...)
}
return b, nil
}
func (s *SVCBIPv6Hint) unpack(b []byte) error {
if len(b) == 0 || len(b)%16 != 0 {
return errors.New("dns: svcbipv6hint: ipv6 address byte array length not a multiple of 16")
}
x := make([]net.IP, 0, len(b)/16)
for i := 0; i < len(b); i += 16 {
ip := net.IP(b[i : i+16])
if ip.To4() != nil {
return errors.New("dns: svcbipv6hint: expected ipv6, got ipv4")
}
x = append(x, ip)
}
s.Hint = x
return nil
}
func (s *SVCBIPv6Hint) String() string {
str := make([]string, len(s.Hint))
for i, e := range s.Hint {
if x := e.To4(); x != nil {
return "<nil>"
}
str[i] = e.String()
}
return strings.Join(str, ",")
}
func (s *SVCBIPv6Hint) parse(b string) error {
str := strings.Split(b, ",")
dst := make([]net.IP, len(str))
for i, e := range str {
ip := net.ParseIP(e)
if ip == nil {
return errors.New("dns: svcbipv6hint: bad ip")
}
if ip.To4() != nil {
return errors.New("dns: svcbipv6hint: expected ipv6, got ipv4-mapped-ipv6")
}
dst[i] = ip
}
s.Hint = dst
return nil
}
func (s *SVCBIPv6Hint) copy() SVCBKeyValue {
hint := make([]net.IP, len(s.Hint))
for i, ip := range s.Hint {
hint[i] = copyIP(ip)
}
return &SVCBIPv6Hint{
Hint: hint,
}
}
// SVCBDoHPath pair is used to indicate the URI template that the
// clients may use to construct a DNS over HTTPS URI.
//
// See RFC xxxx (https://datatracker.ietf.org/doc/html/draft-ietf-add-svcb-dns-02)
// and RFC yyyy (https://datatracker.ietf.org/doc/html/draft-ietf-add-ddr-06).
//
// A basic example of using the dohpath option together with the alpn
// option to indicate support for DNS over HTTPS on a certain path:
//
// s := new(dns.SVCB)
// s.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeSVCB, Class: dns.ClassINET}
// e := new(dns.SVCBAlpn)
// e.Alpn = []string{"h2", "h3"}
// p := new(dns.SVCBDoHPath)
// p.Template = "/dns-query{?dns}"
// s.Value = append(s.Value, e, p)
//
// The parsing currently doesn't validate that Template is a valid
// RFC 6570 URI template.
type SVCBDoHPath struct {
Template string
}
func (*SVCBDoHPath) Key() SVCBKey { return SVCB_DOHPATH }
func (s *SVCBDoHPath) String() string { return svcbParamToStr([]byte(s.Template)) }
func (s *SVCBDoHPath) len() int { return len(s.Template) }
func (s *SVCBDoHPath) pack() ([]byte, error) { return []byte(s.Template), nil }
func (s *SVCBDoHPath) unpack(b []byte) error {
s.Template = string(b)
return nil
}
func (s *SVCBDoHPath) parse(b string) error {
template, err := svcbParseParam(b)
if err != nil {
return fmt.Errorf("dns: svcbdohpath: %w", err)
}
s.Template = string(template)
return nil
}
func (s *SVCBDoHPath) copy() SVCBKeyValue {
return &SVCBDoHPath{
Template: s.Template,
}
}
// SVCBLocal pair is intended for experimental/private use. The key is recommended
// to be in the range [SVCB_PRIVATE_LOWER, SVCB_PRIVATE_UPPER].
// Basic use pattern for creating a keyNNNNN option:
//
// h := new(dns.HTTPS)
// h.Hdr = dns.RR_Header{Name: ".", Rrtype: dns.TypeHTTPS, Class: dns.ClassINET}
// e := new(dns.SVCBLocal)
// e.KeyCode = 65400
// e.Data = []byte("abc")
// h.Value = append(h.Value, e)
type SVCBLocal struct {
KeyCode SVCBKey // Never 65535 or any assigned keys.
Data []byte // All byte sequences are allowed.
}
func (s *SVCBLocal) Key() SVCBKey { return s.KeyCode }
func (s *SVCBLocal) String() string { return svcbParamToStr(s.Data) }
func (s *SVCBLocal) pack() ([]byte, error) { return append([]byte(nil), s.Data...), nil }
func (s *SVCBLocal) len() int { return len(s.Data) }
func (s *SVCBLocal) unpack(b []byte) error {
s.Data = append([]byte(nil), b...)
return nil
}
func (s *SVCBLocal) parse(b string) error {
data, err := svcbParseParam(b)
if err != nil {
return fmt.Errorf("dns: svcblocal: svcb private/experimental key %w", err)
}
s.Data = data
return nil
}
func (s *SVCBLocal) copy() SVCBKeyValue {
return &SVCBLocal{s.KeyCode,
append([]byte(nil), s.Data...),
}
}
func (rr *SVCB) String() string {
s := rr.Hdr.String() +
strconv.Itoa(int(rr.Priority)) + " " +
sprintName(rr.Target)
for _, e := range rr.Value {
s += " " + e.Key().String() + "=\"" + e.String() + "\""
}
return s
}
// areSVCBPairArraysEqual checks if SVCBKeyValue arrays are equal after sorting their
// copies. arrA and arrB have equal lengths, otherwise zduplicate.go wouldn't call this function.
func areSVCBPairArraysEqual(a []SVCBKeyValue, b []SVCBKeyValue) bool {
a = append([]SVCBKeyValue(nil), a...)
b = append([]SVCBKeyValue(nil), b...)
sort.Slice(a, func(i, j int) bool { return a[i].Key() < a[j].Key() })
sort.Slice(b, func(i, j int) bool { return b[i].Key() < b[j].Key() })
for i, e := range a {
if e.Key() != b[i].Key() {
return false
}
b1, err1 := e.pack()
b2, err2 := b[i].pack()
if err1 != nil || err2 != nil || !bytes.Equal(b1, b2) {
return false
}
}
return true
}
// svcbParamStr converts the value of an SVCB parameter into a DNS presentation-format string.
func svcbParamToStr(s []byte) string {
var str strings.Builder
str.Grow(4 * len(s))
for _, e := range s {
if ' ' <= e && e <= '~' {
switch e {
case '"', ';', ' ', '\\':
str.WriteByte('\\')
str.WriteByte(e)
default:
str.WriteByte(e)
}
} else {
str.WriteString(escapeByte(e))
}
}
return str.String()
}
// svcbParseParam parses a DNS presentation-format string into an SVCB parameter value.
func svcbParseParam(b string) ([]byte, error) {
data := make([]byte, 0, len(b))
for i := 0; i < len(b); {
if b[i] != '\\' {
data = append(data, b[i])
i++
continue
}
if i+1 == len(b) {
return nil, errors.New("escape unterminated")
}
if isDigit(b[i+1]) {
if i+3 < len(b) && isDigit(b[i+2]) && isDigit(b[i+3]) {
a, err := strconv.ParseUint(b[i+1:i+4], 10, 8)
if err == nil {
i += 4
data = append(data, byte(a))
continue
}
}
return nil, errors.New("bad escaped octet")
} else {
data = append(data, b[i+1])
i += 2
}
}
return data, nil
}

163
svcb_test.go Normal file
View File

@ -0,0 +1,163 @@
package dns
import (
"testing"
)
// This tests everything valid about SVCB but parsing.
// Parsing tests belong to parse_test.go.
func TestSVCB(t *testing.T) {
svcbs := []struct {
key string
data string
}{
{`mandatory`, `alpn,key65000`},
{`alpn`, `h2,h2c`},
{`port`, `499`},
{`ipv4hint`, `3.4.3.2,1.1.1.1`},
{`no-default-alpn`, ``},
{`ipv6hint`, `1::4:4:4:4,1::3:3:3:3`},
{`ech`, `YUdWc2JHOD0=`},
{`dohpath`, `/dns-query{?dns}`},
{`key65000`, `4\ 3`},
{`key65001`, `\"\ `},
{`key65002`, ``},
{`key65003`, `=\"\"`},
{`key65004`, `\254\ \ \030\000`},
}
for _, o := range svcbs {
keyCode := svcbStringToKey(o.key)
kv := makeSVCBKeyValue(keyCode)
if kv == nil {
t.Error("failed to parse svc key: ", o.key)
continue
}
if kv.Key() != keyCode {
t.Error("key constant is not in sync: ", keyCode)
continue
}
err := kv.parse(o.data)
if err != nil {
t.Error("failed to parse svc pair: ", o.key)
continue
}
b, err := kv.pack()
if err != nil {
t.Error("failed to pack value of svc pair: ", o.key, err)
continue
}
if len(b) != int(kv.len()) {
t.Errorf("expected packed svc value %s to be of length %d but got %d", o.key, int(kv.len()), len(b))
}
err = kv.unpack(b)
if err != nil {
t.Error("failed to unpack value of svc pair: ", o.key, err)
continue
}
if str := kv.String(); str != o.data {
t.Errorf("`%s' should be equal to\n`%s', but is `%s'", o.key, o.data, str)
}
}
}
func TestDecodeBadSVCB(t *testing.T) {
svcbs := []struct {
key SVCBKey
data []byte
}{
{
key: SVCB_ALPN,
data: []byte{3, 0, 0}, // There aren't three octets after 3
},
{
key: SVCB_NO_DEFAULT_ALPN,
data: []byte{0},
},
{
key: SVCB_PORT,
data: []byte{},
},
{
key: SVCB_IPV4HINT,
data: []byte{0, 0, 0},
},
{
key: SVCB_IPV6HINT,
data: []byte{0, 0, 0},
},
}
for _, o := range svcbs {
err := makeSVCBKeyValue(SVCBKey(o.key)).unpack(o.data)
if err == nil {
t.Error("accepted invalid svc value with key ", SVCBKey(o.key).String())
}
}
}
func TestPresentationSVCBAlpn(t *testing.T) {
tests := map[string]string{
"h2": "h2",
"http": "http",
"\xfa": `\250`,
"some\"other,chars": `some\"other\\\044chars`,
}
for input, want := range tests {
e := new(SVCBAlpn)
e.Alpn = []string{input}
if e.String() != want {
t.Errorf("improper conversion with String(), wanted %v got %v", want, e.String())
}
}
}
func TestSVCBAlpn(t *testing.T) {
tests := map[string][]string{
`. 1 IN SVCB 10 one.test. alpn=h2`: {"h2"},
`. 2 IN SVCB 20 two.test. alpn=h2,h3-19`: {"h2", "h3-19"},
`. 3 IN SVCB 30 three.test. alpn="f\\\\oo\\,bar,h2"`: {`f\oo,bar`, "h2"},
`. 4 IN SVCB 40 four.test. alpn="part1,part2,part3\\,part4\\\\"`: {"part1", "part2", `part3,part4\`},
`. 5 IN SVCB 50 five.test. alpn=part1\,\p\a\r\t2\044part3\092,part4\092\\`: {"part1", "part2", `part3,part4\`},
}
for s, v := range tests {
rr, err := NewRR(s)
if err != nil {
t.Error("failed to parse RR: ", err)
continue
}
alpn := rr.(*SVCB).Value[0].(*SVCBAlpn).Alpn
if len(v) != len(alpn) {
t.Fatalf("parsing alpn failed, wanted %v got %v", v, alpn)
}
for i := range v {
if v[i] != alpn[i] {
t.Fatalf("parsing alpn failed, wanted %v got %v", v, alpn)
}
}
}
}
func TestCompareSVCB(t *testing.T) {
val1 := []SVCBKeyValue{
&SVCBPort{
Port: 117,
},
&SVCBAlpn{
Alpn: []string{"h2", "h3"},
},
}
val2 := []SVCBKeyValue{
&SVCBAlpn{
Alpn: []string{"h2", "h3"},
},
&SVCBPort{
Port: 117,
},
}
if !areSVCBPairArraysEqual(val1, val2) {
t.Error("svcb pairs were compared without sorting")
}
if val1[0].Key() != SVCB_PORT || val2[0].Key() != SVCB_ALPN {
t.Error("original svcb pairs were reordered during comparison")
}
}

10
tools.go Normal file
View File

@ -0,0 +1,10 @@
//go:build tools
// +build tools
// We include our tool dependencies for `go generate` here to ensure they're
// properly tracked by the go tool. See the Go Wiki for the rationale behind this:
// https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module.
package dns
import _ "golang.org/x/tools/go/packages"

213
tsig.go
View File

@ -2,7 +2,6 @@ package dns
import (
"crypto/hmac"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
@ -16,12 +15,83 @@ import (
// HMAC hashing codes. These are transmitted as domain names.
const (
HmacMD5 = "hmac-md5.sig-alg.reg.int."
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.
)
// TsigProvider provides the API to plug-in a custom TSIG implementation.
type TsigProvider interface {
// Generate is passed the DNS message to be signed and the partial TSIG RR. It returns the signature and nil, otherwise an error.
Generate(msg []byte, t *TSIG) ([]byte, error)
// Verify is passed the DNS message to be verified and the TSIG RR. If the signature is valid it will return nil, otherwise an error.
Verify(msg []byte, t *TSIG) error
}
type tsigHMACProvider string
func (key tsigHMACProvider) Generate(msg []byte, t *TSIG) ([]byte, error) {
// If we barf here, the caller is to blame
rawsecret, err := fromBase64([]byte(key))
if err != nil {
return nil, err
}
var h hash.Hash
switch CanonicalName(t.Algorithm) {
case HmacSHA1:
h = hmac.New(sha1.New, rawsecret)
case HmacSHA224:
h = hmac.New(sha256.New224, rawsecret)
case HmacSHA256:
h = hmac.New(sha256.New, rawsecret)
case HmacSHA384:
h = hmac.New(sha512.New384, rawsecret)
case HmacSHA512:
h = hmac.New(sha512.New, rawsecret)
default:
return nil, ErrKeyAlg
}
h.Write(msg)
return h.Sum(nil), nil
}
func (key tsigHMACProvider) Verify(msg []byte, t *TSIG) error {
b, err := key.Generate(msg, t)
if err != nil {
return err
}
mac, err := hex.DecodeString(t.MAC)
if err != nil {
return err
}
if !hmac.Equal(b, mac) {
return ErrSig
}
return nil
}
type tsigSecretProvider map[string]string
func (ts tsigSecretProvider) Generate(msg []byte, t *TSIG) ([]byte, error) {
key, ok := ts[t.Hdr.Name]
if !ok {
return nil, ErrSecret
}
return tsigHMACProvider(key).Generate(msg, t)
}
func (ts tsigSecretProvider) Verify(msg []byte, t *TSIG) error {
key, ok := ts[t.Hdr.Name]
if !ok {
return ErrSecret
}
return tsigHMACProvider(key).Verify(msg, t)
}
// TSIG is the RR the holds the transaction signature of a message.
// See RFC 2845 and RFC 4635.
type TSIG struct {
@ -40,7 +110,7 @@ type TSIG struct {
// TSIG has no official presentation format, but this will suffice.
func (rr *TSIG) String() string {
s := "\n;; TSIG PSEUDOSECTION:\n"
s := "\n;; TSIG PSEUDOSECTION:\n; " // add another semi-colon to signify TSIG does not have a presentation format
s += rr.Hdr.String() +
" " + rr.Algorithm +
" " + tsigTimeToString(rr.TimeSigned) +
@ -54,8 +124,8 @@ func (rr *TSIG) String() string {
return s
}
func (rr *TSIG) parse(c *zlexer, origin string) *ParseError {
panic("dns: internal error: parse should never be called on TSIG")
func (*TSIG) parse(c *zlexer, origin string) *ParseError {
return &ParseError{err: "TSIG records do not have a presentation format"}
}
// The following values must be put in wireformat, so that the MAC can be calculated.
@ -88,22 +158,20 @@ type timerWireFmt struct {
}
// TsigGenerate fills out the TSIG record attached to the message.
// The message should contain
// a "stub" TSIG RR with the algorithm, key name (owner name of the RR),
// time fudge (defaults to 300 seconds) and the current time
// The TSIG MAC is saved in that Tsig RR.
// When TsigGenerate is called for the first time requestMAC is set to the empty string and
// timersOnly is false.
// If something goes wrong an error is returned, otherwise it is nil.
// The message should contain a "stub" TSIG RR with the algorithm, key name
// (owner name of the RR), time fudge (defaults to 300 seconds) and the current
// time The TSIG MAC is saved in that Tsig RR. When TsigGenerate is called for
// the first time requestMAC should be set to the empty string and timersOnly to
// false.
func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error) {
return TsigGenerateWithProvider(m, tsigHMACProvider(secret), requestMAC, timersOnly)
}
// TsigGenerateWithProvider is similar to TsigGenerate, but allows for a custom TsigProvider.
func TsigGenerateWithProvider(m *Msg, provider TsigProvider, requestMAC string, timersOnly bool) ([]byte, string, error) {
if m.IsTsig() == nil {
panic("dns: TSIG not last RR in additional")
}
// If we barf here, the caller is to blame
rawsecret, err := fromBase64([]byte(secret))
if err != nil {
return nil, "", err
}
rr := m.Extra[len(m.Extra)-1].(*TSIG)
m.Extra = m.Extra[0 : len(m.Extra)-1] // kill the TSIG from the msg
@ -111,31 +179,29 @@ func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, s
if err != nil {
return nil, "", err
}
buf := tsigBuffer(mbuf, rr, requestMAC, timersOnly)
buf, err := tsigBuffer(mbuf, rr, requestMAC, timersOnly)
if err != nil {
return nil, "", err
}
t := new(TSIG)
var h hash.Hash
switch strings.ToLower(rr.Algorithm) {
case HmacMD5:
h = hmac.New(md5.New, rawsecret)
case HmacSHA1:
h = hmac.New(sha1.New, rawsecret)
case HmacSHA256:
h = hmac.New(sha256.New, rawsecret)
case HmacSHA512:
h = hmac.New(sha512.New, rawsecret)
default:
return nil, "", ErrKeyAlg
}
h.Write(buf)
t.MAC = hex.EncodeToString(h.Sum(nil))
t.MACSize = uint16(len(t.MAC) / 2) // Size is half!
// Copy all TSIG fields except MAC, its size, and time signed which are filled when signing.
*t = *rr
t.TimeSigned = 0
t.MAC = ""
t.MACSize = 0
t.Hdr = RR_Header{Name: rr.Hdr.Name, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0}
t.Fudge = rr.Fudge
t.TimeSigned = rr.TimeSigned
t.Algorithm = rr.Algorithm
t.OrigId = m.Id
// Sign unless there is a key or MAC validation error (RFC 8945 5.3.2)
if rr.Error != RcodeBadKey && rr.Error != RcodeBadSig {
mac, err := provider.Generate(buf, rr)
if err != nil {
return nil, "", err
}
t.TimeSigned = rr.TimeSigned
t.MAC = hex.EncodeToString(mac)
t.MACSize = uint16(len(t.MAC) / 2) // Size is half!
}
tbuf := make([]byte, Len(t))
off, err := PackRR(t, tbuf, 0, nil, false)
@ -149,30 +215,39 @@ func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, s
return mbuf, t.MAC, nil
}
// TsigVerify verifies the TSIG on a message.
// If the signature does not validate err contains the
// error, otherwise it is nil.
// TsigVerify verifies the TSIG on a message. If the signature does not
// validate the returned error contains the cause. If the signature is OK, the
// error is nil.
func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
rawsecret, err := fromBase64([]byte(secret))
if err != nil {
return err
}
return tsigVerify(msg, tsigHMACProvider(secret), requestMAC, timersOnly, uint64(time.Now().Unix()))
}
// TsigVerifyWithProvider is similar to TsigVerify, but allows for a custom TsigProvider.
func TsigVerifyWithProvider(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool) error {
return tsigVerify(msg, provider, requestMAC, timersOnly, uint64(time.Now().Unix()))
}
// actual implementation of TsigVerify, taking the current time ('now') as a parameter for the convenience of tests.
func tsigVerify(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool, now uint64) error {
// Strip the TSIG from the incoming msg
stripped, tsig, err := stripTsig(msg)
if err != nil {
return err
}
msgMAC, err := hex.DecodeString(tsig.MAC)
buf, err := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
if err != nil {
return err
}
buf := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
if err := provider.Verify(buf, tsig); err != nil {
return err
}
// Fudge factor works both ways. A message can arrive before it was signed because
// of clock skew.
now := uint64(time.Now().Unix())
// We check this after verifying the signature, following draft-ietf-dnsop-rfc2845bis
// instead of RFC2845, in order to prevent a security vulnerability as reported in CVE-2017-3142/3143.
ti := now - tsig.TimeSigned
if now < tsig.TimeSigned {
ti = tsig.TimeSigned - now
@ -181,28 +256,11 @@ func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
return ErrTime
}
var h hash.Hash
switch strings.ToLower(tsig.Algorithm) {
case HmacMD5:
h = hmac.New(md5.New, rawsecret)
case HmacSHA1:
h = hmac.New(sha1.New, rawsecret)
case HmacSHA256:
h = hmac.New(sha256.New, rawsecret)
case HmacSHA512:
h = hmac.New(sha512.New, rawsecret)
default:
return ErrKeyAlg
}
h.Write(buf)
if !hmac.Equal(h.Sum(nil), msgMAC) {
return ErrSig
}
return nil
}
// Create a wiredata buffer for the MAC calculation.
func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []byte {
func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) ([]byte, error) {
var buf []byte
if rr.TimeSigned == 0 {
rr.TimeSigned = uint64(time.Now().Unix())
@ -219,7 +277,10 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b
m.MACSize = uint16(len(requestMAC) / 2)
m.MAC = requestMAC
buf = make([]byte, len(requestMAC)) // long enough
n, _ := packMacWire(m, buf)
n, err := packMacWire(m, buf)
if err != nil {
return nil, err
}
buf = buf[:n]
}
@ -228,20 +289,26 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b
tsig := new(timerWireFmt)
tsig.TimeSigned = rr.TimeSigned
tsig.Fudge = rr.Fudge
n, _ := packTimerWire(tsig, tsigvar)
n, err := packTimerWire(tsig, tsigvar)
if err != nil {
return nil, err
}
tsigvar = tsigvar[:n]
} else {
tsig := new(tsigWireFmt)
tsig.Name = strings.ToLower(rr.Hdr.Name)
tsig.Name = CanonicalName(rr.Hdr.Name)
tsig.Class = ClassANY
tsig.Ttl = rr.Hdr.Ttl
tsig.Algorithm = strings.ToLower(rr.Algorithm)
tsig.Algorithm = CanonicalName(rr.Algorithm)
tsig.TimeSigned = rr.TimeSigned
tsig.Fudge = rr.Fudge
tsig.Error = rr.Error
tsig.OtherLen = rr.OtherLen
tsig.OtherData = rr.OtherData
n, _ := packTsigWire(tsig, tsigvar)
n, err := packTsigWire(tsig, tsigvar)
if err != nil {
return nil, err
}
tsigvar = tsigvar[:n]
}
@ -251,7 +318,7 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b
} else {
buf = append(msgbuf, tsigvar...)
}
return buf
return buf, nil
}
// Strip the TSIG from the raw message.

View File

@ -2,6 +2,10 @@ package dns
import (
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"strings"
"testing"
"time"
)
@ -14,7 +18,7 @@ func newTsig(algo string) *Msg {
}
func TestTsig(t *testing.T) {
m := newTsig(HmacMD5)
m := newTsig(HmacSHA256)
buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
if err != nil {
t.Fatal(err)
@ -26,7 +30,7 @@ func TestTsig(t *testing.T) {
// TSIG accounts for ID substitution. This means if the message ID is
// changed by a forwarder, we should still be able to verify the TSIG.
m = newTsig(HmacMD5)
m = newTsig(HmacSHA256)
buf, _, err = TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
if err != nil {
t.Fatal(err)
@ -40,7 +44,7 @@ func TestTsig(t *testing.T) {
}
func TestTsigCase(t *testing.T) {
m := newTsig("HmAc-mD5.sig-ALg.rEg.int.") // HmacMD5
m := newTsig(strings.ToUpper(HmacSHA256))
buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
if err != nil {
t.Fatal(err)
@ -50,3 +54,356 @@ func TestTsigCase(t *testing.T) {
t.Fatal(err)
}
}
func TestTsigErrorResponse(t *testing.T) {
for _, rcode := range []uint16{RcodeBadSig, RcodeBadKey} {
m := newTsig(strings.ToUpper(HmacSHA256))
m.IsTsig().Error = rcode
buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
if err != nil {
t.Fatal(err)
}
err = m.Unpack(buf)
if err != nil {
t.Fatal(err)
}
mTsig := m.IsTsig()
if mTsig.MAC != "" {
t.Error("Expected empty MAC")
}
if mTsig.MACSize != 0 {
t.Error("Expected 0 MACSize")
}
if mTsig.TimeSigned != 0 {
t.Errorf("Expected TimeSigned to be 0, got %v", mTsig.TimeSigned)
}
}
}
func TestTsigBadTimeResponse(t *testing.T) {
clientTime := uint64(time.Now().Unix()) - 3600
m := newTsig(strings.ToUpper(HmacSHA256))
m.IsTsig().Error = RcodeBadTime
m.IsTsig().TimeSigned = clientTime
buf, _, err := TsigGenerate(m, "pRZgBrBvI4NAHZYhxmhs/Q==", "", false)
if err != nil {
t.Fatal(err)
}
err = m.Unpack(buf)
if err != nil {
t.Fatal(err)
}
mTsig := m.IsTsig()
if mTsig.MAC == "" {
t.Error("Expected non-empty MAC")
}
if int(mTsig.MACSize) != len(mTsig.MAC)/2 {
t.Errorf("Expected MACSize %v, got %v", len(mTsig.MAC)/2, mTsig.MACSize)
}
if mTsig.TimeSigned != clientTime {
t.Errorf("Expected TimeSigned %v to be retained, got %v", clientTime, mTsig.TimeSigned)
}
}
const (
// A template wire-format DNS message (in hex form) containing a TSIG RR.
// Its time signed field will be filled by tests.
wireMsg = "c60028000001000000010001076578616d706c6503636f6d00000600010161c00c0001000100000e100004c0000201077465" +
"73746b65790000fa00ff00000000003d0b686d61632d73686132353600" +
"%012x" + // placeholder for the "time signed" field
"012c00208cf23e0081d915478a182edcea7ff48ad102948e6c7ef8e887536957d1fa5616c60000000000"
// A secret (in base64 format) with which the TSIG in wireMsg will be validated
testSecret = "NoTCJU+DMqFWywaPyxSijrDEA/eC3nK0xi3AMEZuPVk="
// the 'time signed' field value that would make the TSIG RR valid with testSecret
timeSigned uint64 = 1594855491
)
func TestTsigErrors(t *testing.T) {
// Helper shortcut to build wire-format test message.
// TsigVerify can modify the slice, so we need to create a new one for each test case below.
buildMsgData := func(tm uint64) []byte {
msgData, err := hex.DecodeString(fmt.Sprintf(wireMsg, tm))
if err != nil {
t.Fatal(err)
}
return msgData
}
// the signature is valid but 'time signed' is too far from the "current time".
if err := tsigVerify(buildMsgData(timeSigned), tsigHMACProvider(testSecret), "", false, timeSigned+301); err != ErrTime {
t.Fatalf("expected an error '%v' but got '%v'", ErrTime, err)
}
if err := tsigVerify(buildMsgData(timeSigned), tsigHMACProvider(testSecret), "", false, timeSigned-301); err != ErrTime {
t.Fatalf("expected an error '%v' but got '%v'", ErrTime, err)
}
// the signature is invalid and 'time signed' is too far.
// the signature should be checked first, so we should see ErrSig.
if err := tsigVerify(buildMsgData(timeSigned+301), tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrSig {
t.Fatalf("expected an error '%v' but got '%v'", ErrSig, err)
}
// tweak the algorithm name in the wire data, resulting in the "unknown algorithm" error.
msgData := buildMsgData(timeSigned)
copy(msgData[67:], "bogus")
if err := tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrKeyAlg {
t.Fatalf("expected an error '%v' but got '%v'", ErrKeyAlg, err)
}
// call TsigVerify with a message that doesn't contain a TSIG
msgData, tsig, err := stripTsig(buildMsgData(timeSigned))
if err != nil {
t.Fatal(err)
}
if err := tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned); err != ErrNoSig {
t.Fatalf("expected an error '%v' but got '%v'", ErrNoSig, err)
}
// replace the test TSIG with a bogus one with large "other data", which would cause overflow in TsigVerify.
// The overflow should be caught without disruption.
tsig.OtherData = strings.Repeat("00", 4096)
tsig.OtherLen = uint16(len(tsig.OtherData) / 2)
msg := new(Msg)
if err = msg.Unpack(msgData); err != nil {
t.Fatal(err)
}
msg.Extra = append(msg.Extra, tsig)
if msgData, err = msg.Pack(); err != nil {
t.Fatal(err)
}
err = tsigVerify(msgData, tsigHMACProvider(testSecret), "", false, timeSigned)
if err == nil || !strings.Contains(err.Error(), "overflow") {
t.Errorf("expected error to contain %q, but got %v", "overflow", err)
}
}
// This test exercises some more corner cases for TsigGenerate.
func TestTsigGenerate(t *testing.T) {
// This is a template TSIG to be used for signing.
tsig := TSIG{
Hdr: RR_Header{Name: "testkey.", Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
Algorithm: HmacSHA256,
TimeSigned: timeSigned,
Fudge: 300,
OrigId: 42,
Error: RcodeBadTime, // use a non-0 value to make sure it's indeed used
}
tests := []struct {
desc string // test description
requestMAC string // request MAC to be passed to TsigGenerate (arbitrary choice)
otherData string // other data specified in the TSIG (arbitrary choice)
expectedMAC string // pre-computed expected (correct) MAC in hex form
}{
{"with request MAC", "3684c225", "",
"c110e3f62694755c10761dc8717462431ee34340b7c9d1eee09449150757c5b1"},
{"no request MAC", "", "",
"385449a425c6d52b9bf2c65c0726eefa0ad8084cdaf488f24547e686605b9610"},
{"with other data", "3684c225", "666f6f",
"15b91571ca80b3b410a77e2b44f8cc4f35ace22b26020138439dd94803e23b5d"},
}
for _, tc := range tests {
tc := tc
t.Run(tc.desc, func(t *testing.T) {
// Build TSIG for signing from the template
testTSIG := tsig
testTSIG.OtherLen = uint16(len(tc.otherData) / 2)
testTSIG.OtherData = tc.otherData
req := &Msg{
MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
Extra: []RR{&testTSIG},
}
// Call generate, and check the returned MAC against the expected value
msgData, mac, err := TsigGenerate(req, testSecret, tc.requestMAC, false)
if err != nil {
t.Error(err)
}
if mac != tc.expectedMAC {
t.Fatalf("MAC doesn't match: expected '%s', but got '%s'", tc.expectedMAC, mac)
}
// Retrieve the TSIG to be sent out, confirm the MAC in it
_, outTSIG, err := stripTsig(msgData)
if err != nil {
t.Error(err)
}
if outTSIG.MAC != tc.expectedMAC {
t.Fatalf("MAC doesn't match: expected '%s', but got '%s'", tc.expectedMAC, outTSIG.MAC)
}
// Confirm other fields of MAC.
// RDLENGTH should be valid as stripTsig succeeded, so we exclude it from comparison
outTSIG.MACSize = 0
outTSIG.MAC = ""
testTSIG.Hdr.Rdlength = outTSIG.Hdr.Rdlength
if *outTSIG != testTSIG {
t.Fatalf("TSIG RR doesn't match: expected '%v', but got '%v'", *outTSIG, testTSIG)
}
})
}
}
func TestTSIGHMAC224And384(t *testing.T) {
tests := []struct {
algorithm string // TSIG algorithm, also used as test description
secret string // (arbitrarily chosen) secret suitable for the algorithm in base64 format
expectedMAC string // pre-computed expected (correct) MAC in hex form
}{
{HmacSHA224, "hVEkQuAqnTmBuRrT9KF1Udr91gOMGWPw9LaTtw==",
"d6daf9ea189e48bc38f9aed63d6cc4140cdfa38a7a333ee2eefdbd31",
},
{HmacSHA384, "Qjer2TL2lAdpq9w6Gjs98/ClCQx/L3vtgVHCmrZ8l/oKEPjqUUMFO18gMCRwd5H4",
"89a48936d29187870c325cbdba5ad71609bd038d0459d6010c844d659c570e881d3650e4fe7310be53ebe5178d0d1001",
},
}
for _, tc := range tests {
tc := tc
t.Run(tc.algorithm, func(t *testing.T) {
// Build a DNS message with TSIG for the test scenario
tsig := TSIG{
Hdr: RR_Header{Name: "testkey.", Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
Algorithm: tc.algorithm,
TimeSigned: timeSigned,
Fudge: 300,
OrigId: 42,
}
req := &Msg{
MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
Extra: []RR{&tsig},
}
// Confirm both Generate and Verify recognize the algorithm and handle it correctly
msgData, mac, err := TsigGenerate(req, tc.secret, "", false)
if err != nil {
t.Error(err)
}
if mac != tc.expectedMAC {
t.Fatalf("MAC doesn't match: expected '%s' but got '%s'", tc.expectedMAC, mac)
}
if err = tsigVerify(msgData, tsigHMACProvider(tc.secret), "", false, timeSigned); err != nil {
t.Error(err)
}
})
}
}
const testGoodKeyName = "goodkey."
var (
errBadKey = errors.New("this is an intentional error")
testGoodMAC = []byte{0, 1, 2, 3}
)
// testProvider always generates the same MAC and only accepts the one signature
type testProvider struct {
GenerateAllKeys bool
}
func (provider *testProvider) Generate(_ []byte, t *TSIG) ([]byte, error) {
if t.Hdr.Name == testGoodKeyName || provider.GenerateAllKeys {
return testGoodMAC, nil
}
return nil, errBadKey
}
func (*testProvider) Verify(_ []byte, t *TSIG) error {
if t.Hdr.Name == testGoodKeyName {
return nil
}
return errBadKey
}
func TestTsigGenerateProvider(t *testing.T) {
tables := []struct {
keyname string
mac []byte
err error
}{
{
testGoodKeyName,
testGoodMAC,
nil,
},
{
"badkey.",
nil,
errBadKey,
},
}
for _, table := range tables {
t.Run(table.keyname, func(t *testing.T) {
tsig := TSIG{
Hdr: RR_Header{Name: table.keyname, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
Algorithm: HmacSHA1,
TimeSigned: timeSigned,
Fudge: 300,
OrigId: 42,
}
req := &Msg{
MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
Extra: []RR{&tsig},
}
_, mac, err := TsigGenerateWithProvider(req, new(testProvider), "", false)
if err != table.err {
t.Fatalf("error doesn't match: expected '%s' but got '%s'", table.err, err)
}
expectedMAC := hex.EncodeToString(table.mac)
if mac != expectedMAC {
t.Fatalf("MAC doesn't match: expected '%s' but got '%s'", table.mac, expectedMAC)
}
})
}
}
func TestTsigVerifyProvider(t *testing.T) {
tables := []struct {
keyname string
err error
}{
{
testGoodKeyName,
nil,
},
{
"badkey.",
errBadKey,
},
}
for _, table := range tables {
t.Run(table.keyname, func(t *testing.T) {
tsig := TSIG{
Hdr: RR_Header{Name: table.keyname, Rrtype: TypeTSIG, Class: ClassANY, Ttl: 0},
Algorithm: HmacSHA1,
TimeSigned: timeSigned,
Fudge: 300,
OrigId: 42,
}
req := &Msg{
MsgHdr: MsgHdr{Opcode: OpcodeUpdate},
Question: []Question{{Name: "example.com.", Qtype: TypeSOA, Qclass: ClassINET}},
Extra: []RR{&tsig},
}
provider := &testProvider{true}
msgData, _, err := TsigGenerateWithProvider(req, provider, "", false)
if err != nil {
t.Error(err)
}
if err = tsigVerify(msgData, provider, "", false, timeSigned); err != table.err {
t.Fatalf("error doesn't match: expected '%s' but got '%s'", table.err, err)
}
})
}
}

215
types.go
View File

@ -1,6 +1,7 @@
package dns
import (
"bytes"
"fmt"
"net"
"strconv"
@ -61,6 +62,7 @@ const (
TypeCERT uint16 = 37
TypeDNAME uint16 = 39
TypeOPT uint16 = 41 // EDNS
TypeAPL uint16 = 42
TypeDS uint16 = 43
TypeSSHFP uint16 = 44
TypeRRSIG uint16 = 46
@ -79,6 +81,9 @@ const (
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
@ -146,6 +151,14 @@ const (
OpcodeUpdate = 5
)
// Used in ZONEMD https://tools.ietf.org/html/rfc8976
const (
ZoneMDSchemeSimple = 1
ZoneMDHashAlgSHA384 = 1
ZoneMDHashAlgSHA512 = 2
)
// Header is the wire format for the DNS packet header.
type Header struct {
Id uint16
@ -163,11 +176,11 @@ const (
_RD = 1 << 8 // recursion desired
_RA = 1 << 7 // recursion available
_Z = 1 << 6 // Z
_AD = 1 << 5 // authticated data
_AD = 1 << 5 // authenticated data
_CD = 1 << 4 // checking disabled
)
// Various constants used in the LOC RR, See RFC 1887.
// Various constants used in the LOC RR. See RFC 1887.
const (
LOC_EQUATOR = 1 << 31 // RFC 1876, Section 2.
LOC_PRIMEMERIDIAN = 1 << 31 // RFC 1876, Section 2.
@ -207,8 +220,11 @@ var CertTypeToString = map[uint16]string{
//go:generate go run types_generate.go
// Question holds a DNS question. There can be multiple questions in the
// question section of a message. Usually there is just one.
// Question holds a DNS question. Usually there is just one. While the
// original DNS RFCs allow multiple questions in the question section of a
// message, in practice it never works. Because most DNS servers see multiple
// questions as an error, it is recommended to only have one question per
// message.
type Question struct {
Name string `dns:"cdomain-name"` // "cdomain-name" specifies encoding (and may be compressed)
Qtype uint16
@ -229,7 +245,7 @@ func (q *Question) String() (s string) {
return s
}
// ANY is a wildcard record. See RFC 1035, Section 3.2.3. ANY
// ANY is a wild card record. See RFC 1035, Section 3.2.3. ANY
// is named "*" there.
type ANY struct {
Hdr RR_Header
@ -238,8 +254,8 @@ type ANY struct {
func (rr *ANY) String() string { return rr.Hdr.String() }
func (rr *ANY) parse(c *zlexer, origin string) *ParseError {
panic("dns: internal error: parse should never be called on ANY")
func (*ANY) parse(c *zlexer, origin string) *ParseError {
return &ParseError{err: "ANY records do not have a presentation format"}
}
// NULL RR. See RFC 1035.
@ -253,8 +269,8 @@ func (rr *NULL) String() string {
return ";" + rr.Hdr.String() + rr.Data
}
func (rr *NULL) parse(c *zlexer, origin string) *ParseError {
panic("dns: internal error: parse should never be called on NULL")
func (*NULL) parse(c *zlexer, origin string) *ParseError {
return &ParseError{err: "NULL records do not have a presentation format"}
}
// CNAME RR. See RFC 1034.
@ -440,45 +456,38 @@ func sprintName(s string) string {
var dst strings.Builder
for i := 0; i < len(s); {
if i+1 < len(s) && s[i] == '\\' && s[i+1] == '.' {
if s[i] == '.' {
if dst.Len() != 0 {
dst.WriteString(s[i : i+2])
dst.WriteByte('.')
}
i += 2
i++
continue
}
b, n := nextByte(s, i)
if n == 0 {
i++
continue
}
if b == '.' {
if dst.Len() != 0 {
dst.WriteByte('.')
// Drop "dangling" incomplete escapes.
if dst.Len() == 0 {
return s[:i]
}
i += n
continue
break
}
switch b {
case ' ', '\'', '@', ';', '(', ')', '"', '\\': // additional chars to escape
if isDomainNameLabelSpecial(b) {
if dst.Len() == 0 {
dst.Grow(len(s) * 2)
dst.WriteString(s[:i])
}
dst.WriteByte('\\')
dst.WriteByte(b)
default:
if ' ' <= b && b <= '~' {
if dst.Len() != 0 {
dst.WriteByte(b)
}
} else {
if dst.Len() == 0 {
dst.Grow(len(s) * 2)
dst.WriteString(s[:i])
}
dst.WriteString(escapeByte(b))
} else if b < ' ' || b > '~' { // unprintable, use \DDD
if dst.Len() == 0 {
dst.Grow(len(s) * 2)
dst.WriteString(s[:i])
}
dst.WriteString(escapeByte(b))
} else {
if dst.Len() != 0 {
dst.WriteByte(b)
}
}
i += n
@ -501,15 +510,10 @@ func sprintTxtOctet(s string) string {
}
b, n := nextByte(s, i)
switch {
case n == 0:
if n == 0 {
i++ // dangling back slash
case b == '.':
dst.WriteByte('.')
case b < ' ' || b > '~':
dst.WriteString(escapeByte(b))
default:
dst.WriteByte(b)
} else {
writeTXTStringByte(&dst, b)
}
i += n
}
@ -585,6 +589,17 @@ func escapeByte(b byte) string {
return escapedByteLarge[int(b)*4 : int(b)*4+4]
}
// isDomainNameLabelSpecial returns true if
// a domain name label byte should be prefixed
// with an escaping backslash.
func isDomainNameLabelSpecial(b byte) bool {
switch b {
case '.', ' ', '\'', '@', ';', '(', ')', '"', '\\':
return true
}
return false
}
func nextByte(s string, offset int) (byte, int) {
if offset >= len(s) {
return 0, 0
@ -757,8 +772,8 @@ type LOC struct {
Altitude uint32
}
// cmToM takes a cm value expressed in RFC1876 SIZE mantissa/exponent
// format and returns a string in m (two decimals for the cm)
// cmToM takes a cm value expressed in RFC 1876 SIZE mantissa/exponent
// format and returns a string in m (two decimals for the cm).
func cmToM(m, e uint8) string {
if e < 2 {
if e == 1 {
@ -1116,6 +1131,7 @@ type URI struct {
Target string `dns:"octet"`
}
// rr.Target to be parsed as a sequence of character encoded octets according to RFC 3986
func (rr *URI) String() string {
return rr.Hdr.String() + strconv.Itoa(int(rr.Priority)) +
" " + strconv.Itoa(int(rr.Weight)) + " " + sprintTxtOctet(rr.Target)
@ -1277,6 +1293,7 @@ type CAA struct {
Value string `dns:"octet"`
}
// rr.Value Is the character-string encoding of the value field as specified in RFC 1035, Section 5.1.
func (rr *CAA) String() string {
return rr.Hdr.String() + strconv.Itoa(int(rr.Flag)) + " " + rr.Tag + " " + sprintTxtOctet(rr.Value)
}
@ -1353,6 +1370,105 @@ func (rr *CSYNC) len(off int, compression map[string]struct{}) int {
return l
}
// ZONEMD RR, from draft-ietf-dnsop-dns-zone-digest
type ZONEMD struct {
Hdr RR_Header
Serial uint32
Scheme uint8
Hash uint8
Digest string `dns:"hex"`
}
func (rr *ZONEMD) String() string {
return rr.Hdr.String() +
strconv.Itoa(int(rr.Serial)) +
" " + strconv.Itoa(int(rr.Scheme)) +
" " + strconv.Itoa(int(rr.Hash)) +
" " + rr.Digest
}
// APL RR. See RFC 3123.
type APL struct {
Hdr RR_Header
Prefixes []APLPrefix `dns:"apl"`
}
// APLPrefix is an address prefix hold by an APL record.
type APLPrefix struct {
Negation bool
Network net.IPNet
}
// String returns presentation form of the APL record.
func (rr *APL) String() string {
var sb strings.Builder
sb.WriteString(rr.Hdr.String())
for i, p := range rr.Prefixes {
if i > 0 {
sb.WriteByte(' ')
}
sb.WriteString(p.str())
}
return sb.String()
}
// str returns presentation form of the APL prefix.
func (a *APLPrefix) str() string {
var sb strings.Builder
if a.Negation {
sb.WriteByte('!')
}
switch len(a.Network.IP) {
case net.IPv4len:
sb.WriteByte('1')
case net.IPv6len:
sb.WriteByte('2')
}
sb.WriteByte(':')
switch len(a.Network.IP) {
case net.IPv4len:
sb.WriteString(a.Network.IP.String())
case net.IPv6len:
// add prefix for IPv4-mapped IPv6
if v4 := a.Network.IP.To4(); v4 != nil {
sb.WriteString("::ffff:")
}
sb.WriteString(a.Network.IP.String())
}
sb.WriteByte('/')
prefix, _ := a.Network.Mask.Size()
sb.WriteString(strconv.Itoa(prefix))
return sb.String()
}
// equals reports whether two APL prefixes are identical.
func (a *APLPrefix) equals(b *APLPrefix) bool {
return a.Negation == b.Negation &&
bytes.Equal(a.Network.IP, b.Network.IP) &&
bytes.Equal(a.Network.Mask, b.Network.Mask)
}
// copy returns a copy of the APL prefix.
func (a *APLPrefix) copy() APLPrefix {
return APLPrefix{
Negation: a.Negation,
Network: copyNet(a.Network),
}
}
// len returns size of the prefix in wire format.
func (a *APLPrefix) len() int {
// 4-byte header and the network address prefix (see Section 4 of RFC 3123)
prefix, _ := a.Network.Mask.Size()
return 4 + (prefix+7)/8
}
// TimeToString translates the RRSIG's incep. and expir. times to the
// string representation used when printing the record.
// It takes serial arithmetic (RFC 1982) into account.
@ -1382,7 +1498,7 @@ func StringToTime(s string) (uint32, error) {
// saltToString converts a NSECX salt to uppercase and returns "-" when it is empty.
func saltToString(s string) string {
if len(s) == 0 {
if s == "" {
return "-"
}
return strings.ToUpper(s)
@ -1409,6 +1525,17 @@ func copyIP(ip net.IP) net.IP {
return p
}
// copyNet returns a copy of a subnet.
func copyNet(n net.IPNet) net.IPNet {
m := make(net.IPMask, len(n.Mask))
copy(m, n.Mask)
return net.IPNet{
IP: copyIP(n.IP),
Mask: m,
}
}
// SplitN splits a string into N sized string chunks.
// This might become an exported function once.
func splitN(s string, n int) []string {

View File

@ -1,4 +1,5 @@
//+build ignore
//go:build ignore
// +build ignore
// types_generate.go is meant to run with go generate. It will use
// go/{importer,types} to track down all the RR struct types. Then for each type
@ -11,12 +12,13 @@ import (
"bytes"
"fmt"
"go/format"
"go/importer"
"go/types"
"log"
"os"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
var skipLen = map[string]struct{}{
@ -71,6 +73,9 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
if !ok {
return nil, false
}
if st.NumFields() == 0 {
return nil, false
}
if st.Field(0).Type() == scope.Lookup("RR_Header").Type() {
return st, false
}
@ -81,9 +86,19 @@ func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
return nil, false
}
// loadModule retrieves package description for a given module.
func loadModule(name string) (*types.Package, error) {
conf := packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo}
pkgs, err := packages.Load(&conf, name)
if err != nil {
return nil, err
}
return pkgs[0].Types, nil
}
func main() {
// Import and type-check the package
pkg, err := importer.Default().Import("github.com/miekg/dns")
pkg, err := loadModule("github.com/miekg/dns")
fatalIfErr(err)
scope := pkg.Scope()
@ -168,6 +183,10 @@ func main() {
o("for _, x := range rr.%s { l += domainNameLen(x, off+l, compression, false) }\n")
case `dns:"txt"`:
o("for _, x := range rr.%s { l += len(x) + 1 }\n")
case `dns:"apl"`:
o("for _, x := range rr.%s { l += x.len() }\n")
case `dns:"pairs"`:
o("for _, x := range rr.%s { l += 4 + int(x.len()) }\n")
default:
log.Fatalln(name, st.Field(i).Name(), st.Tag(i))
}
@ -228,11 +247,15 @@ func main() {
for _, name := range namedTypes {
o := scope.Lookup(name)
st, isEmbedded := getTypeStruct(o.Type(), scope)
if isEmbedded {
continue
}
fmt.Fprintf(b, "func (rr *%s) copy() RR {\n", name)
fields := []string{"rr.Hdr"}
fields := make([]string, 0, st.NumFields())
if isEmbedded {
a, _ := o.Type().Underlying().(*types.Struct)
parent := a.Field(0).Name()
fields = append(fields, "*rr."+parent+".copy().(*"+parent+")")
goto WriteCopy
}
fields = append(fields, "rr.Hdr")
for i := 1; i < st.NumFields(); i++ {
f := st.Field(i).Name()
if sl, ok := st.Field(i).Type().(*types.Slice); ok {
@ -249,6 +272,18 @@ func main() {
fields = append(fields, f)
continue
}
if t == "APLPrefix" {
fmt.Fprintf(b, "%s := make([]%s, len(rr.%s));\nfor i,e := range rr.%s {\n %s[i] = e.copy()\n}\n",
f, t, f, f, f)
fields = append(fields, f)
continue
}
if t == "SVCBKeyValue" {
fmt.Fprintf(b, "%s := make([]%s, len(rr.%s));\nfor i,e := range rr.%s {\n %s[i] = e.copy()\n}\n",
f, t, f, f, f)
fields = append(fields, f)
continue
}
fmt.Fprintf(b, "%s := make([]%s, len(rr.%s)); copy(%s, rr.%s)\n",
f, t, f, f, f)
fields = append(fields, f)
@ -260,6 +295,7 @@ func main() {
}
fields = append(fields, "rr."+f)
}
WriteCopy:
fmt.Fprintf(b, "return &%s{%s}\n", name, strings.Join(fields, ","))
fmt.Fprintf(b, "}\n")
}

View File

@ -74,18 +74,41 @@ func TestSplitN(t *testing.T) {
}
func TestSprintName(t *testing.T) {
got := sprintName("abc\\.def\007\"\127@\255\x05\xef\\")
tests := map[string]string{
// Non-numeric escaping of special printable characters.
" '@;()\"\\..example": `\ \'\@\;\(\)\"\..example`,
"\\032\\039\\064\\059\\040\\041\\034\\046\\092.example": `\ \'\@\;\(\)\"\.\\.example`,
if want := "abc\\.def\\007\\\"W\\@\\173\\005\\239"; got != want {
t.Errorf("expected %q, got %q", got, want)
// Numeric escaping of nonprintable characters.
"\x00\x07\x09\x0a\x1f.\x7f\x80\xad\xef\xff": `\000\007\009\010\031.\127\128\173\239\255`,
"\\000\\007\\009\\010\\031.\\127\\128\\173\\239\\255": `\000\007\009\010\031.\127\128\173\239\255`,
// No escaping of other printable characters, at least after a prior escape.
";[a-zA-Z0-9_]+/*.~": `\;[a-zA-Z0-9_]+/*.~`,
";\\091\\097\\045\\122\\065\\045\\090\\048\\045\\057\\095\\093\\043\\047\\042.\\126": `\;[a-zA-Z0-9_]+/*.~`,
// "\\091\\097\\045\\122\\065\\045\\090\\048\\045\\057\\095\\093\\043\\047\\042.\\126": `[a-zA-Z0-9_]+/*.~`,
// Incomplete "dangling" escapes are dropped regardless of prior escaping.
"a\\": `a`,
";\\": `\;`,
// Escaped dots stay escaped regardless of prior escaping.
"a\\.\\046.\\.\\046": `a\.\..\.\.`,
"a\\046\\..\\046\\.": `a\.\..\.\.`,
}
for input, want := range tests {
got := sprintName(input)
if got != want {
t.Errorf("input %q: expected %q, got %q", input, want, got)
}
}
}
func TestSprintTxtOctet(t *testing.T) {
got := sprintTxtOctet("abc\\.def\007\"\127@\255\x05\xef\\")
if want := "\"abc\\.def\\007\"W@\\173\\005\\239\""; got != want {
t.Errorf("expected %q, got %q", got, want)
if want := "\"abc\\.def\\007\\\"W@\\173\\005\\239\""; got != want {
t.Errorf("expected %q, got %q", want, got)
}
}
@ -96,7 +119,7 @@ func TestSprintTxt(t *testing.T) {
})
if want := "\"abc.def\\007\\\"W@\\173\\005\\239\" \"example.com\""; got != want {
t.Errorf("expected %q, got %q", got, want)
t.Errorf("expected %q, got %q", want, got)
}
}
@ -128,7 +151,7 @@ func BenchmarkSprintName(b *testing.B) {
got := sprintName("abc\\.def\007\"\127@\255\x05\xef\\")
if want := "abc\\.def\\007\\\"W\\@\\173\\005\\239"; got != want {
b.Fatalf("expected %q, got %q", got, want)
b.Fatalf("expected %q, got %q", want, got)
}
}
}
@ -138,7 +161,7 @@ func BenchmarkSprintName_NoEscape(b *testing.B) {
got := sprintName("large.example.com")
if want := "large.example.com"; got != want {
b.Fatalf("expected %q, got %q", got, want)
b.Fatalf("expected %q, got %q", want, got)
}
}
}
@ -147,8 +170,8 @@ func BenchmarkSprintTxtOctet(b *testing.B) {
for n := 0; n < b.N; n++ {
got := sprintTxtOctet("abc\\.def\007\"\127@\255\x05\xef\\")
if want := "\"abc\\.def\\007\"W@\\173\\005\\239\""; got != want {
b.Fatalf("expected %q, got %q", got, want)
if want := "\"abc\\.def\\007\\\"W@\\173\\005\\239\""; got != want {
b.Fatalf("expected %q, got %q", want, got)
}
}
}

1
udp.go
View File

@ -1,3 +1,4 @@
//go:build !windows
// +build !windows
package dns

View File

@ -1,3 +1,4 @@
//go:build linux && !appengine
// +build linux,!appengine
package dns

View File

@ -1,3 +1,4 @@
//go:build windows
// +build windows
package dns

View File

@ -32,7 +32,9 @@ func (u *Msg) Used(rr []RR) {
u.Answer = make([]RR, 0, len(rr))
}
for _, r := range rr {
r.Header().Class = u.Question[0].Qclass
hdr := r.Header()
hdr.Class = u.Question[0].Qclass
hdr.Ttl = 0
u.Answer = append(u.Answer, r)
}
}

View File

@ -6,15 +6,28 @@ import (
)
func TestDynamicUpdateParsing(t *testing.T) {
prefix := "example.com. IN "
for _, typ := range TypeToString {
if typ == "OPT" || typ == "AXFR" || typ == "IXFR" || typ == "ANY" || typ == "TKEY" ||
typ == "TSIG" || typ == "ISDN" || typ == "UNSPEC" || typ == "NULL" || typ == "ATMA" ||
typ == "Reserved" || typ == "None" || typ == "NXT" || typ == "MAILB" || typ == "MAILA" {
const prefix = "example.com. IN "
for typ, name := range TypeToString {
switch typ {
case TypeNone, TypeReserved:
continue
case TypeANY:
// ANY is ambiguous here and ends up parsed as a CLASS.
//
// TODO(tmthrgd): Using TYPE255 here doesn't seem to work and also
// seems to fail for some other record types. Investigate.
continue
}
if _, err := NewRR(prefix + typ); err != nil {
t.Errorf("failure to parse: %s %s: %v", prefix, typ, err)
s := prefix + name
if _, err := NewRR(s); err != nil {
t.Errorf("failure to parse: %s: %v", s, err)
}
s += " \\# 0"
if _, err := NewRR(s); err != nil {
t.Errorf("failure to parse: %s: %v", s, err)
}
}
}
@ -79,7 +92,7 @@ func TestRemoveRRset(t *testing.T) {
}
func TestPreReqAndRemovals(t *testing.T) {
// Build a list of multiple prereqs and then somes removes followed by an insert.
// Build a list of multiple prereqs and then some removes followed by an insert.
// We should be able to add multiple prereqs and updates.
m := new(Msg)
m.SetUpdate("example.org.")
@ -122,7 +135,7 @@ func TestPreReqAndRemovals(t *testing.T) {
name_used. 0 CLASS255 ANY
name_not_used. 0 NONE ANY
rrset_used1. 0 CLASS255 A
rrset_used2. 3600 IN A 127.0.0.1
rrset_used2. 0 IN A 127.0.0.1
rrset_not_used. 0 NONE A
;; AUTHORITY SECTION:

View File

@ -3,13 +3,13 @@ package dns
import "fmt"
// Version is current version of this library.
var Version = V{1, 1, 18}
var Version = v{1, 1, 50}
// V holds the version of this library.
type V struct {
// v holds the version of this library.
type v struct {
Major, Minor, Patch int
}
func (v V) String() string {
func (v v) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}

View File

@ -3,7 +3,7 @@ package dns
import "testing"
func TestVersion(t *testing.T) {
v := V{1, 0, 0}
v := v{1, 0, 0}
if x := v.String(); x != "1.0.0" {
t.Fatalf("Failed to convert version %v, got: %s", v, x)
}

41
xfr.go
View File

@ -17,11 +17,22 @@ type Transfer struct {
DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds
ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
TsigProvider TsigProvider // An implementation of the TsigProvider interface. If defined it replaces TsigSecret and is used for all TSIG operations.
TsigSecret map[string]string // Secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
tsigTimersOnly bool
}
// Think we need to away to stop the transfer
func (t *Transfer) tsigProvider() TsigProvider {
if t.TsigProvider != nil {
return t.TsigProvider
}
if t.TsigSecret != nil {
return tsigSecretProvider(t.TsigSecret)
}
return nil
}
// TODO: Think we need to away to stop the transfer
// In performs an incoming transfer with the server in a.
// If you would like to set the source IP, or some other attribute
@ -33,7 +44,6 @@ type Transfer struct {
// dnscon := &dns.Conn{Conn:con}
// transfer = &dns.Transfer{Conn: dnscon}
// channel, err := transfer.In(message, master)
//
func (t *Transfer) In(q *Msg, a string) (env chan *Envelope, err error) {
switch q.Question[0].Qtype {
case TypeAXFR, TypeIXFR:
@ -182,14 +192,17 @@ func (t *Transfer) inIxfr(q *Msg, c chan *Envelope) {
//
// ch := make(chan *dns.Envelope)
// tr := new(dns.Transfer)
// go tr.Out(w, r, ch)
// var wg sync.WaitGroup
// go func() {
// tr.Out(w, r, ch)
// wg.Done()
// }()
// ch <- &dns.Envelope{RR: []dns.RR{soa, rr1, rr2, rr3, soa}}
// close(ch)
// w.Hijack()
// // w.Close() // Client closes connection
// wg.Wait() // wait until everything is written out
// w.Close() // close connection
//
// The server is responsible for sending the correct sequence of RRs through the
// channel ch.
// The server is responsible for sending the correct sequence of RRs through the channel ch.
func (t *Transfer) Out(w ResponseWriter, q *Msg, ch chan *Envelope) error {
for x := range ch {
r := new(Msg)
@ -221,12 +234,9 @@ func (t *Transfer) ReadMsg() (*Msg, error) {
if err := m.Unpack(p); err != nil {
return nil, err
}
if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil {
if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok {
return m, ErrSecret
}
if ts, tp := m.IsTsig(), t.tsigProvider(); ts != nil && tp != nil {
// Need to work on the original message p, as that was used to calculate the tsig.
err = TsigVerify(p, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly)
err = TsigVerifyWithProvider(p, tp, t.tsigRequestMAC, t.tsigTimersOnly)
t.tsigRequestMAC = ts.MAC
}
return m, err
@ -235,11 +245,8 @@ func (t *Transfer) ReadMsg() (*Msg, error) {
// WriteMsg writes a message through the transfer connection t.
func (t *Transfer) WriteMsg(m *Msg) (err error) {
var out []byte
if ts := m.IsTsig(); ts != nil && t.TsigSecret != nil {
if _, ok := t.TsigSecret[ts.Hdr.Name]; !ok {
return ErrSecret
}
out, t.tsigRequestMAC, err = TsigGenerate(m, t.TsigSecret[ts.Hdr.Name], t.tsigRequestMAC, t.tsigTimersOnly)
if ts, tp := m.IsTsig(), t.tsigProvider(); ts != nil && tp != nil {
out, t.tsigRequestMAC, err = TsigGenerateWithProvider(m, tp, t.tsigRequestMAC, t.tsigTimersOnly)
} else {
out, err = m.Pack()
}

View File

@ -1,8 +1,6 @@
package dns
import (
"net"
"sync"
"testing"
"time"
)
@ -52,7 +50,7 @@ func TestInvalidXfr(t *testing.T) {
HandleFunc("miek.nl.", InvalidXfrServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalTCPServer(":0")
s, addrstr, _, err := RunLocalTCPServer(":0")
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
@ -78,88 +76,108 @@ func TestSingleEnvelopeXfr(t *testing.T) {
HandleFunc("miek.nl.", SingleEnvelopeXfrServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalTCPServerWithTsig(":0", tsigSecret)
s, addrstr, _, err := RunLocalTCPServer(":0", func(srv *Server) {
srv.TsigSecret = tsigSecret
})
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
defer s.Shutdown()
axfrTestingSuite(addrstr)
axfrTestingSuite(t, addrstr)
}
func TestMultiEnvelopeXfr(t *testing.T) {
HandleFunc("miek.nl.", MultipleEnvelopeXfrServer)
defer HandleRemove("miek.nl.")
s, addrstr, err := RunLocalTCPServerWithTsig(":0", tsigSecret)
s, addrstr, _, err := RunLocalTCPServer(":0", func(srv *Server) {
srv.TsigSecret = tsigSecret
})
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
defer s.Shutdown()
axfrTestingSuite(addrstr)
axfrTestingSuite(t, addrstr)
}
func RunLocalTCPServerWithTsig(laddr string, tsig map[string]string) (*Server, string, error) {
server, l, _, err := RunLocalTCPServerWithFinChanWithTsig(laddr, tsig)
func axfrTestingSuite(t *testing.T, addrstr string) {
tr := new(Transfer)
m := new(Msg)
m.SetAxfr("miek.nl.")
return server, l, err
}
func RunLocalTCPServerWithFinChanWithTsig(laddr string, tsig map[string]string) (*Server, string, chan error, error) {
l, err := net.Listen("tcp", laddr)
c, err := tr.In(m, addrstr)
if err != nil {
return nil, "", nil, err
t.Fatal("failed to zone transfer in", err)
}
server := &Server{Listener: l, ReadTimeout: time.Hour, WriteTimeout: time.Hour, TsigSecret: tsig}
waitLock := sync.Mutex{}
waitLock.Lock()
server.NotifyStartedFunc = waitLock.Unlock
// See the comment in RunLocalUDPServerWithFinChan as to
// why fin must be buffered.
fin := make(chan error, 1)
go func() {
fin <- server.ActivateAndServe()
l.Close()
}()
waitLock.Lock()
return server, l.Addr().String(), fin, nil
}
func axfrTestingSuite(addrstr string) func(*testing.T) {
return func(t *testing.T) {
tr := new(Transfer)
m := new(Msg)
m.SetAxfr("miek.nl.")
c, err := tr.In(m, addrstr)
if err != nil {
t.Fatal("failed to zone transfer in", err)
var records []RR
for msg := range c {
if msg.Error != nil {
t.Fatal(msg.Error)
}
records = append(records, msg.RR...)
}
var records []RR
for msg := range c {
if msg.Error != nil {
t.Fatal(msg.Error)
}
for _, rr := range msg.RR {
records = append(records, rr)
}
}
if len(records) != len(xfrTestData) {
t.Fatalf("bad axfr: expected %v, got %v", records, xfrTestData)
}
if len(records) != len(xfrTestData) {
for i, rr := range records {
if !IsDuplicate(rr, xfrTestData[i]) {
t.Fatalf("bad axfr: expected %v, got %v", records, xfrTestData)
}
}
}
for i := range records {
if !IsDuplicate(records[i], xfrTestData[i]) {
t.Fatalf("bad axfr: expected %v, got %v", records, xfrTestData)
}
func axfrTestingSuiteWithCustomTsig(t *testing.T, addrstr string, provider TsigProvider) {
tr := new(Transfer)
m := new(Msg)
var err error
tr.Conn, err = Dial("tcp", addrstr)
if err != nil {
t.Fatal("failed to dial", err)
}
tr.TsigProvider = provider
m.SetAxfr("miek.nl.")
m.SetTsig("axfr.", HmacSHA256, 300, time.Now().Unix())
c, err := tr.In(m, addrstr)
if err != nil {
t.Fatal("failed to zone transfer in", err)
}
var records []RR
for msg := range c {
if msg.Error != nil {
t.Fatal(msg.Error)
}
records = append(records, msg.RR...)
}
if len(records) != len(xfrTestData) {
t.Fatalf("bad axfr: expected %v, got %v", records, xfrTestData)
}
for i, rr := range records {
if !IsDuplicate(rr, xfrTestData[i]) {
t.Errorf("bad axfr: expected %v, got %v", records, xfrTestData)
}
}
}
func TestCustomTsigProvider(t *testing.T) {
HandleFunc("miek.nl.", SingleEnvelopeXfrServer)
defer HandleRemove("miek.nl.")
s, addrstr, _, err := RunLocalTCPServer(":0", func(srv *Server) {
srv.TsigProvider = tsigSecretProvider(tsigSecret)
})
if err != nil {
t.Fatalf("unable to run test server: %s", err)
}
defer s.Shutdown()
axfrTestingSuiteWithCustomTsig(t, addrstr, tsigSecretProvider(tsigSecret))
}

View File

@ -52,6 +52,23 @@ func (r1 *ANY) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *APL) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*APL)
if !ok {
return false
}
_ = r2
if len(r1.Prefixes) != len(r2.Prefixes) {
return false
}
for i := 0; i < len(r1.Prefixes); i++ {
if !r1.Prefixes[i].equals(&r2.Prefixes[i]) {
return false
}
}
return true
}
func (r1 *AVC) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*AVC)
if !ok {
@ -87,6 +104,48 @@ func (r1 *CAA) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *CDNSKEY) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*CDNSKEY)
if !ok {
return false
}
_ = r2
if r1.Flags != r2.Flags {
return false
}
if r1.Protocol != r2.Protocol {
return false
}
if r1.Algorithm != r2.Algorithm {
return false
}
if r1.PublicKey != r2.PublicKey {
return false
}
return true
}
func (r1 *CDS) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*CDS)
if !ok {
return false
}
_ = r2
if r1.KeyTag != r2.KeyTag {
return false
}
if r1.Algorithm != r2.Algorithm {
return false
}
if r1.DigestType != r2.DigestType {
return false
}
if r1.Digest != r2.Digest {
return false
}
return true
}
func (r1 *CERT) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*CERT)
if !ok {
@ -155,6 +214,27 @@ func (r1 *DHCID) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *DLV) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*DLV)
if !ok {
return false
}
_ = r2
if r1.KeyTag != r2.KeyTag {
return false
}
if r1.Algorithm != r2.Algorithm {
return false
}
if r1.DigestType != r2.DigestType {
return false
}
if r1.Digest != r2.Digest {
return false
}
return true
}
func (r1 *DNAME) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*DNAME)
if !ok {
@ -322,6 +402,48 @@ func (r1 *HIP) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *HTTPS) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*HTTPS)
if !ok {
return false
}
_ = r2
if r1.Priority != r2.Priority {
return false
}
if !isDuplicateName(r1.Target, r2.Target) {
return false
}
if len(r1.Value) != len(r2.Value) {
return false
}
if !areSVCBPairArraysEqual(r1.Value, r2.Value) {
return false
}
return true
}
func (r1 *KEY) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*KEY)
if !ok {
return false
}
_ = r2
if r1.Flags != r2.Flags {
return false
}
if r1.Protocol != r2.Protocol {
return false
}
if r1.Algorithm != r2.Algorithm {
return false
}
if r1.PublicKey != r2.PublicKey {
return false
}
return true
}
func (r1 *KX) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*KX)
if !ok {
@ -832,6 +954,42 @@ func (r1 *RT) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *SIG) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*SIG)
if !ok {
return false
}
_ = r2
if r1.TypeCovered != r2.TypeCovered {
return false
}
if r1.Algorithm != r2.Algorithm {
return false
}
if r1.Labels != r2.Labels {
return false
}
if r1.OrigTtl != r2.OrigTtl {
return false
}
if r1.Expiration != r2.Expiration {
return false
}
if r1.Inception != r2.Inception {
return false
}
if r1.KeyTag != r2.KeyTag {
return false
}
if !isDuplicateName(r1.SignerName, r2.SignerName) {
return false
}
if r1.Signature != r2.Signature {
return false
}
return true
}
func (r1 *SMIMEA) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*SMIMEA)
if !ok {
@ -939,6 +1097,27 @@ func (r1 *SSHFP) isDuplicate(_r2 RR) bool {
return true
}
func (r1 *SVCB) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*SVCB)
if !ok {
return false
}
_ = r2
if r1.Priority != r2.Priority {
return false
}
if !isDuplicateName(r1.Target, r2.Target) {
return false
}
if len(r1.Value) != len(r2.Value) {
return false
}
if !areSVCBPairArraysEqual(r1.Value, r2.Value) {
return false
}
return true
}
func (r1 *TA) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*TA)
if !ok {
@ -1138,3 +1317,24 @@ func (r1 *X25) isDuplicate(_r2 RR) bool {
}
return true
}
func (r1 *ZONEMD) isDuplicate(_r2 RR) bool {
r2, ok := _r2.(*ZONEMD)
if !ok {
return false
}
_ = r2
if r1.Serial != r2.Serial {
return false
}
if r1.Scheme != r2.Scheme {
return false
}
if r1.Hash != r2.Hash {
return false
}
if r1.Digest != r2.Digest {
return false
}
return true
}

153
zmsg.go
View File

@ -36,6 +36,14 @@ func (rr *ANY) pack(msg []byte, off int, compression compressionMap, compress bo
return off, nil
}
func (rr *APL) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packDataApl(rr.Prefixes, msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *AVC) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packStringTxt(rr.Txt, msg, off)
if err != nil {
@ -308,6 +316,22 @@ func (rr *HIP) pack(msg []byte, off int, compression compressionMap, compress bo
return off, nil
}
func (rr *HTTPS) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packUint16(rr.Priority, msg, off)
if err != nil {
return off, err
}
off, err = packDomainName(rr.Target, msg, off, compression, false)
if err != nil {
return off, err
}
off, err = packDataSVCB(rr.Value, msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *KEY) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packUint16(rr.Flags, msg, off)
if err != nil {
@ -898,6 +922,22 @@ func (rr *SSHFP) pack(msg []byte, off int, compression compressionMap, compress
return off, nil
}
func (rr *SVCB) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packUint16(rr.Priority, msg, off)
if err != nil {
return off, err
}
off, err = packDomainName(rr.Target, msg, off, compression, false)
if err != nil {
return off, err
}
off, err = packDataSVCB(rr.Value, msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *TA) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packUint16(rr.KeyTag, msg, off)
if err != nil {
@ -1078,6 +1118,26 @@ func (rr *X25) pack(msg []byte, off int, compression compressionMap, compress bo
return off, nil
}
func (rr *ZONEMD) pack(msg []byte, off int, compression compressionMap, compress bool) (off1 int, err error) {
off, err = packUint32(rr.Serial, msg, off)
if err != nil {
return off, err
}
off, err = packUint8(rr.Scheme, msg, off)
if err != nil {
return off, err
}
off, err = packUint8(rr.Hash, msg, off)
if err != nil {
return off, err
}
off, err = packStringHex(rr.Digest, msg, off)
if err != nil {
return off, err
}
return off, nil
}
// unpack*() functions
func (rr *A) unpack(msg []byte, off int) (off1 int, err error) {
@ -1127,6 +1187,17 @@ func (rr *ANY) unpack(msg []byte, off int) (off1 int, err error) {
return off, nil
}
func (rr *APL) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
rr.Prefixes, off, err = unpackDataApl(msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *AVC) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
@ -1540,6 +1611,31 @@ func (rr *HIP) unpack(msg []byte, off int) (off1 int, err error) {
return off, nil
}
func (rr *HTTPS) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
rr.Priority, off, err = unpackUint16(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Target, off, err = UnpackDomainName(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Value, off, err = unpackDataSVCB(msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *KEY) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
@ -2442,6 +2538,31 @@ func (rr *SSHFP) unpack(msg []byte, off int) (off1 int, err error) {
return off, nil
}
func (rr *SVCB) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
rr.Priority, off, err = unpackUint16(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Target, off, err = UnpackDomainName(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Value, off, err = unpackDataSVCB(msg, off)
if err != nil {
return off, err
}
return off, nil
}
func (rr *TA) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
@ -2720,3 +2841,35 @@ func (rr *X25) unpack(msg []byte, off int) (off1 int, err error) {
}
return off, nil
}
func (rr *ZONEMD) unpack(msg []byte, off int) (off1 int, err error) {
rdStart := off
_ = rdStart
rr.Serial, off, err = unpackUint32(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Scheme, off, err = unpackUint8(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Hash, off, err = unpackUint8(msg, off)
if err != nil {
return off, err
}
if off == len(msg) {
return off, nil
}
rr.Digest, off, err = unpackStringHex(msg, off, rdStart+int(rr.Hdr.Rdlength))
if err != nil {
return off, err
}
return off, nil
}

View File

@ -13,6 +13,7 @@ var TypeToRR = map[uint16]func() RR{
TypeAAAA: func() RR { return new(AAAA) },
TypeAFSDB: func() RR { return new(AFSDB) },
TypeANY: func() RR { return new(ANY) },
TypeAPL: func() RR { return new(APL) },
TypeAVC: func() RR { return new(AVC) },
TypeCAA: func() RR { return new(CAA) },
TypeCDNSKEY: func() RR { return new(CDNSKEY) },
@ -32,6 +33,7 @@ var TypeToRR = map[uint16]func() RR{
TypeGPOS: func() RR { return new(GPOS) },
TypeHINFO: func() RR { return new(HINFO) },
TypeHIP: func() RR { return new(HIP) },
TypeHTTPS: func() RR { return new(HTTPS) },
TypeKEY: func() RR { return new(KEY) },
TypeKX: func() RR { return new(KX) },
TypeL32: func() RR { return new(L32) },
@ -69,6 +71,7 @@ var TypeToRR = map[uint16]func() RR{
TypeSPF: func() RR { return new(SPF) },
TypeSRV: func() RR { return new(SRV) },
TypeSSHFP: func() RR { return new(SSHFP) },
TypeSVCB: func() RR { return new(SVCB) },
TypeTA: func() RR { return new(TA) },
TypeTALINK: func() RR { return new(TALINK) },
TypeTKEY: func() RR { return new(TKEY) },
@ -79,6 +82,7 @@ var TypeToRR = map[uint16]func() RR{
TypeUINFO: func() RR { return new(UINFO) },
TypeURI: func() RR { return new(URI) },
TypeX25: func() RR { return new(X25) },
TypeZONEMD: func() RR { return new(ZONEMD) },
}
// TypeToString is a map of strings for each RR type.
@ -87,6 +91,7 @@ var TypeToString = map[uint16]string{
TypeAAAA: "AAAA",
TypeAFSDB: "AFSDB",
TypeANY: "ANY",
TypeAPL: "APL",
TypeATMA: "ATMA",
TypeAVC: "AVC",
TypeAXFR: "AXFR",
@ -108,6 +113,7 @@ var TypeToString = map[uint16]string{
TypeGPOS: "GPOS",
TypeHINFO: "HINFO",
TypeHIP: "HIP",
TypeHTTPS: "HTTPS",
TypeISDN: "ISDN",
TypeIXFR: "IXFR",
TypeKEY: "KEY",
@ -151,6 +157,7 @@ var TypeToString = map[uint16]string{
TypeSPF: "SPF",
TypeSRV: "SRV",
TypeSSHFP: "SSHFP",
TypeSVCB: "SVCB",
TypeTA: "TA",
TypeTALINK: "TALINK",
TypeTKEY: "TKEY",
@ -162,6 +169,7 @@ var TypeToString = map[uint16]string{
TypeUNSPEC: "UNSPEC",
TypeURI: "URI",
TypeX25: "X25",
TypeZONEMD: "ZONEMD",
TypeNSAPPTR: "NSAP-PTR",
}
@ -169,6 +177,7 @@ func (rr *A) Header() *RR_Header { return &rr.Hdr }
func (rr *AAAA) Header() *RR_Header { return &rr.Hdr }
func (rr *AFSDB) Header() *RR_Header { return &rr.Hdr }
func (rr *ANY) Header() *RR_Header { return &rr.Hdr }
func (rr *APL) Header() *RR_Header { return &rr.Hdr }
func (rr *AVC) Header() *RR_Header { return &rr.Hdr }
func (rr *CAA) Header() *RR_Header { return &rr.Hdr }
func (rr *CDNSKEY) Header() *RR_Header { return &rr.Hdr }
@ -188,6 +197,7 @@ func (rr *GID) Header() *RR_Header { return &rr.Hdr }
func (rr *GPOS) Header() *RR_Header { return &rr.Hdr }
func (rr *HINFO) Header() *RR_Header { return &rr.Hdr }
func (rr *HIP) Header() *RR_Header { return &rr.Hdr }
func (rr *HTTPS) Header() *RR_Header { return &rr.Hdr }
func (rr *KEY) Header() *RR_Header { return &rr.Hdr }
func (rr *KX) Header() *RR_Header { return &rr.Hdr }
func (rr *L32) Header() *RR_Header { return &rr.Hdr }
@ -226,6 +236,7 @@ func (rr *SOA) Header() *RR_Header { return &rr.Hdr }
func (rr *SPF) Header() *RR_Header { return &rr.Hdr }
func (rr *SRV) Header() *RR_Header { return &rr.Hdr }
func (rr *SSHFP) Header() *RR_Header { return &rr.Hdr }
func (rr *SVCB) Header() *RR_Header { return &rr.Hdr }
func (rr *TA) Header() *RR_Header { return &rr.Hdr }
func (rr *TALINK) Header() *RR_Header { return &rr.Hdr }
func (rr *TKEY) Header() *RR_Header { return &rr.Hdr }
@ -236,6 +247,7 @@ func (rr *UID) Header() *RR_Header { return &rr.Hdr }
func (rr *UINFO) Header() *RR_Header { return &rr.Hdr }
func (rr *URI) Header() *RR_Header { return &rr.Hdr }
func (rr *X25) Header() *RR_Header { return &rr.Hdr }
func (rr *ZONEMD) Header() *RR_Header { return &rr.Hdr }
// len() functions
func (rr *A) len(off int, compression map[string]struct{}) int {
@ -262,6 +274,13 @@ func (rr *ANY) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
return l
}
func (rr *APL) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
for _, x := range rr.Prefixes {
l += x.len()
}
return l
}
func (rr *AVC) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
for _, x := range rr.Txt {
@ -582,6 +601,15 @@ func (rr *SSHFP) len(off int, compression map[string]struct{}) int {
l += len(rr.FingerPrint) / 2
return l
}
func (rr *SVCB) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
l += 2 // Priority
l += domainNameLen(rr.Target, off+l, compression, false)
for _, x := range rr.Value {
l += 4 + int(x.len())
}
return l
}
func (rr *TA) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
l += 2 // KeyTag
@ -659,6 +687,14 @@ func (rr *X25) len(off int, compression map[string]struct{}) int {
l += len(rr.PSDNAddress) + 1
return l
}
func (rr *ZONEMD) len(off int, compression map[string]struct{}) int {
l := rr.Hdr.len(off, compression)
l += 4 // Serial
l++ // Scheme
l++ // Hash
l += len(rr.Digest) / 2
return l
}
// copy() functions
func (rr *A) copy() RR {
@ -673,6 +709,13 @@ func (rr *AFSDB) copy() RR {
func (rr *ANY) copy() RR {
return &ANY{rr.Hdr}
}
func (rr *APL) copy() RR {
Prefixes := make([]APLPrefix, len(rr.Prefixes))
for i, e := range rr.Prefixes {
Prefixes[i] = e.copy()
}
return &APL{rr.Hdr, Prefixes}
}
func (rr *AVC) copy() RR {
Txt := make([]string, len(rr.Txt))
copy(Txt, rr.Txt)
@ -681,6 +724,12 @@ func (rr *AVC) copy() RR {
func (rr *CAA) copy() RR {
return &CAA{rr.Hdr, rr.Flag, rr.Tag, rr.Value}
}
func (rr *CDNSKEY) copy() RR {
return &CDNSKEY{*rr.DNSKEY.copy().(*DNSKEY)}
}
func (rr *CDS) copy() RR {
return &CDS{*rr.DS.copy().(*DS)}
}
func (rr *CERT) copy() RR {
return &CERT{rr.Hdr, rr.Type, rr.KeyTag, rr.Algorithm, rr.Certificate}
}
@ -695,6 +744,9 @@ func (rr *CSYNC) copy() RR {
func (rr *DHCID) copy() RR {
return &DHCID{rr.Hdr, rr.Digest}
}
func (rr *DLV) copy() RR {
return &DLV{*rr.DS.copy().(*DS)}
}
func (rr *DNAME) copy() RR {
return &DNAME{rr.Hdr, rr.Target}
}
@ -727,6 +779,12 @@ func (rr *HIP) copy() RR {
copy(RendezvousServers, rr.RendezvousServers)
return &HIP{rr.Hdr, rr.HitLength, rr.PublicKeyAlgorithm, rr.PublicKeyLength, rr.Hit, rr.PublicKey, RendezvousServers}
}
func (rr *HTTPS) copy() RR {
return &HTTPS{*rr.SVCB.copy().(*SVCB)}
}
func (rr *KEY) copy() RR {
return &KEY{*rr.DNSKEY.copy().(*DNSKEY)}
}
func (rr *KX) copy() RR {
return &KX{rr.Hdr, rr.Preference, rr.Exchanger}
}
@ -830,6 +888,9 @@ func (rr *RRSIG) copy() RR {
func (rr *RT) copy() RR {
return &RT{rr.Hdr, rr.Preference, rr.Host}
}
func (rr *SIG) copy() RR {
return &SIG{*rr.RRSIG.copy().(*RRSIG)}
}
func (rr *SMIMEA) copy() RR {
return &SMIMEA{rr.Hdr, rr.Usage, rr.Selector, rr.MatchingType, rr.Certificate}
}
@ -847,6 +908,13 @@ func (rr *SRV) copy() RR {
func (rr *SSHFP) copy() RR {
return &SSHFP{rr.Hdr, rr.Algorithm, rr.Type, rr.FingerPrint}
}
func (rr *SVCB) copy() RR {
Value := make([]SVCBKeyValue, len(rr.Value))
for i, e := range rr.Value {
Value[i] = e.copy()
}
return &SVCB{rr.Hdr, rr.Priority, rr.Target, Value}
}
func (rr *TA) copy() RR {
return &TA{rr.Hdr, rr.KeyTag, rr.Algorithm, rr.DigestType, rr.Digest}
}
@ -879,3 +947,6 @@ func (rr *URI) copy() RR {
func (rr *X25) copy() RR {
return &X25{rr.Hdr, rr.PSDNAddress}
}
func (rr *ZONEMD) copy() RR {
return &ZONEMD{rr.Hdr, rr.Serial, rr.Scheme, rr.Hash, rr.Digest}
}