diff options
| author | Shulhan <ms@kilabit.info> | 2025-01-17 00:09:21 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2025-01-17 00:09:21 +0700 |
| commit | 20101c63d8cb9d5d673bbd2b93f9dfd8344f06a2 (patch) | |
| tree | 1f644467eec6b9085a873a4299ea01c85610076d /lib/dns/message_header.go | |
| parent | 01c317a295ba743c17064e4656fac22d993c1174 (diff) | |
| download | pakakeh.go-20101c63d8cb9d5d673bbd2b93f9dfd8344f06a2.tar.xz | |
lib/dns: detect invalid header earlier
Previously, we unpack the header and then question without
detecting whether the header itself is valid or not, for
example the op-code, the response code.
This cause the unpacking question return an error like
label length overflow at index xxx
One of the case is when someone sent random or HTTP request
to DoT port.
Diffstat (limited to 'lib/dns/message_header.go')
| -rw-r--r-- | lib/dns/message_header.go | 21 |
1 files changed, 18 insertions, 3 deletions
diff --git a/lib/dns/message_header.go b/lib/dns/message_header.go index c3c6f9cb..aa505aec 100644 --- a/lib/dns/message_header.go +++ b/lib/dns/message_header.go @@ -5,6 +5,9 @@ package dns import ( + "errors" + "fmt" + libbytes "git.sr.ht/~shulhan/pakakeh.go/lib/bytes" ) @@ -161,19 +164,31 @@ func (hdr *MessageHeader) pack() []byte { } // unpack the DNS header section. -func (hdr *MessageHeader) unpack(packet []byte) { +func (hdr *MessageHeader) unpack(packet []byte) (err error) { + if len(packet) < sectionHeaderSize { + return errors.New(`header too small`) + } + hdr.Op = OpCode((packet[2] & headerMaskOpCode) >> 3) + if hdr.Op < 0 || hdr.Op > OpCodeStatus { + return fmt.Errorf(`unknown op code=%d`, hdr.Op) + } + hdr.RCode = ResponseCode(headerMaskRCode & packet[3]) + if hdr.RCode < 0 || hdr.RCode > RCodeRefused { + return fmt.Errorf(`unknown response code=%d`, hdr.RCode) + } + hdr.ID = libbytes.ReadUint16(packet, 0) hdr.IsQuery = packet[2]&headerIsResponse != headerIsResponse - hdr.Op = OpCode((packet[2] & headerMaskOpCode) >> 3) hdr.IsAA = packet[2]&headerIsAA == headerIsAA hdr.IsTC = packet[2]&headerIsTC == headerIsTC hdr.IsRD = packet[2]&headerIsRD == headerIsRD hdr.IsRA = packet[3]&headerIsRA == headerIsRA - hdr.RCode = ResponseCode(headerMaskRCode & packet[3]) hdr.QDCount = libbytes.ReadUint16(packet, 4) hdr.ANCount = libbytes.ReadUint16(packet, 6) hdr.NSCount = libbytes.ReadUint16(packet, 8) hdr.ARCount = libbytes.ReadUint16(packet, 10) + + return nil } |
