-
Notifications
You must be signed in to change notification settings - Fork 2
/
mdns.go
535 lines (496 loc) · 18 KB
/
mdns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
package dns_naming
import (
"net"
"net/netip"
"strings"
"syscall"
"time"
"github.com/irai/packet"
"github.com/irai/packet/fastlog"
"golang.org/x/net/dns/dnsmessage"
)
// MDNS RFC
// see https://datatracker.ietf.org/doc/html/rfc6762
// see Apple bonjour - https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/NetServices/Introduction.html
//
// One of the motivations for DNS-based Service Discovery is to enable a
// visiting client (e.g., a Wi-Fi-equipped [IEEEW] laptop computer,
// tablet, or mobile telephone) arriving on a new network to discover
// what services are available on that network, without any manual
// configuration.
//
// This discovery is performed using DNS queries, using Unicast or
// Multicast DNS. Five special RR names are reserved for this purpose:
//
// b._dns-sd._udp.<domain>.
// db._dns-sd._udp.<domain>.
// r._dns-sd._udp.<domain>.
// dr._dns-sd._udp.<domain>.
// lb._dns-sd._udp.<domain>.
//
// TODO: investigate mdns domain resolution
// For example, if a host has the address 192.168.12.34, with
// the subnet mask 255.255.0.0, then the 'base' address of the subnet is
// 192.168.0.0, and to discover the recommended automatic browsing
// domain(s) for devices on this subnet, the host issues a DNS PTR query
// for the name "lb._dns-sd._udp.0.0.168.192.in-addr.arpa."
//
// Service Discovery RFC
// see https://datatracker.ietf.org/doc/html/rfc6763
//
// Given a type of service that a client is looking for, and a domain in which the client is
// looking for that service, this mechanism allows clients to discover a
// list of named instances of that desired service, using standard DNS
// queries. This mechanism is referred to as DNS-based Service Discovery, or DNS-SD.
const MDNSServiceDiscovery = "_services._dns-sd._udp.local."
const moduleMDNS = "mdns"
var (
LoggerMDNS = fastlog.New(moduleMDNS)
// Any DNS query for a name ending with ".local." MUST be sent to the
// mDNS IPv4 link-local multicast address 224.0.0.251 (or its IPv6 equivalent FF02::FB).
mdnsIPv4Addr = packet.Addr{MAC: packet.EthBroadcast, IP: netip.AddrFrom4([4]byte{224, 0, 0, 251}), Port: 5353}
mdnsIPv6Addr = packet.Addr{MAC: packet.EthBroadcast, IP: netip.MustParseAddr("ff02::fb"), Port: 5353}
// TODO: do we need LLMNR? perhaps useful when a new windows machine is pluggedin?
// Link Local Multicast Name Resolution
// https://datatracker.ietf.org/doc/html/rfc4795
//
// LLMNR queries are sent to and received on port 5355. The IPv4 link-
// scope multicast address a given responder listens to, and to which a
// sender sends queries, is 224.0.0.252. The IPv6 link-scope multicast
// address a given responder listens to, and to which a sender sends all
// queries, is FF02:0:0:0:0:0:1:3.
//
// Windows hosts will query a name on startup to prevent duplicates on the LAN
// https://docs.microsoft.com/en-us/previous-versions//bb878128(v=technet.10)
llmnrIPv4Addr = packet.Addr{MAC: packet.EthBroadcast, IP: netip.AddrFrom4([4]byte{224, 0, 0, 251}), Port: 5355}
llmnrIPv6Addr = packet.Addr{MAC: packet.EthBroadcast, IP: netip.MustParseAddr("FF02:0:0:0:0:0:1:3"), Port: 5355}
)
// SendMDNSQuery send a multicast DNS query
func (h *DNSHandler) SendMDNSQuery(name string) (err error) {
// When responding to queries using qtype "ANY" (255) and/or
// qclass "ANY" (255), a Multicast DNS responder MUST respond with *ALL*
// of its records that match the query.
return h.sendMDNSQuery(h.session.NICInfo.HostAddr4, mdnsIPv4Addr, dnsmessage.TypeALL, name)
}
// SendLLMNRQuery send a multicast LLMNR query
func (h *DNSHandler) SendLLMNRQuery(name string) (err error) {
return h.sendMDNSQuery(h.session.NICInfo.HostAddr4, llmnrIPv4Addr, dnsmessage.TypePTR, name)
}
func (h *DNSHandler) sendMDNSQuery(srcAddr packet.Addr, dstAddr packet.Addr, mtype dnsmessage.Type, name string) (err error) {
// TODO: mdns request unicast for response messages to minimise traffic. How???
// To avoid large floods of potentially unnecessary responses in these
// cases, Multicast DNS defines the top bit in the class field of a DNS
// question as the unicast-response bit. When this bit is set in a
// question, it indicates that the querier is willing to accept unicast
// replies in response to this specific query, as well as the usual
// multicast responses.
msg := dnsmessage.Message{
Header: dnsmessage.Header{Response: false},
Questions: []dnsmessage.Question{
{
Name: mustNewName(name),
Type: dnsmessage.TypeALL,
Class: dnsmessage.ClassANY,
},
},
Answers: []dnsmessage.Resource{},
Authorities: []dnsmessage.Resource{},
Additionals: []dnsmessage.Resource{},
}
buf, err := msg.Pack()
if err != nil {
return err
}
return h.sendMDNS(buf, srcAddr, dstAddr)
}
func (h *DNSHandler) sendMDNS(buf []byte, srcAddr packet.Addr, dstAddr packet.Addr) (err error) {
ether := packet.Ether(make([]byte, packet.EthMaxSize))
// The source UDP port in all Multicast DNS responses MUST be 5353 (the
// well-known port assigned to mDNS). Multicast DNS implementations
// MUST silently ignore any Multicast DNS responses they receive where
// the source UDP port is not 5353.
//
// The destination UDP port in all Multicast DNS responses MUST be 5353,
// and the destination address MUST be the mDNS IPv4 link-local
// multicast address 224.0.0.251 or its IPv6 equivalent FF02::FB, except
// when generating a reply to a query that explicitly requested a
// unicast response
// IP4
if srcAddr.IP.Is4() {
ether = packet.EncodeEther(ether, syscall.ETH_P_IP, h.session.NICInfo.HostAddr4.MAC, dstAddr.MAC)
ip4 := packet.EncodeIP4(ether.Payload(), 255, srcAddr.IP, dstAddr.IP)
udp := packet.EncodeUDP(ip4.Payload(), dstAddr.Port, dstAddr.Port) // same port number for src and dst
if udp, err = udp.AppendPayload(buf); err != nil {
return err
}
ip4 = ip4.SetPayload(udp, syscall.IPPROTO_UDP)
if ether, err = ether.SetPayload(ip4); err != nil {
return err
}
if _, err := h.session.Conn.WriteTo(ether, &dstAddr); err != nil {
LoggerMDNS.Msg("failed to write").Error(err).Write()
}
return err
}
// IP6
ether = packet.EncodeEther(ether, syscall.ETH_P_IPV6, h.session.NICInfo.HostAddr4.MAC, dstAddr.MAC)
ip6 := packet.EncodeIP6(ether.Payload(), 255, srcAddr.IP, dstAddr.IP)
udp := packet.EncodeUDP(ip6.Payload(), dstAddr.Port, dstAddr.Port) // same port number for src and dst
if udp, err = udp.AppendPayload(buf); err != nil {
return err
}
ip6 = ip6.SetPayload(udp, syscall.IPPROTO_UDP)
ether, _ = ether.SetPayload(ip6)
if _, err := h.session.Conn.WriteTo(ether, &dstAddr); err != nil {
LoggerMDNS.Msg("failed to write").Error(err).Write()
}
return nil
}
func (h *DNSHandler) SendSleepProxyResponse(srcAddr packet.Addr, dstAddr packet.Addr, id uint16, name string) (err error) {
if Debug {
LoggerMDNS.Msg("send sleep proxy announcement").Struct(dstAddr).Write()
}
// Server response format: See https://datatracker.ietf.org/doc/html/rfc6763
//
// see http://www.cnpbagwell.com/mac-os-x/bonjour-sleep-proxy
// Example python code: https://github.com/kfix/SleepProxyServer/blob/master/sleepproxy/manager.py
// Sleep proxy encode information in front of the name
// #<SPSType>-<SPSPortability>-<SPSMarginalPower>-<SPSTotalPower>.<SPSFeatureFlags> <nicelabel>
name = "10-34-10-70 SleepProxyServer._sleep-proxy._udp.local."
var ip4 [4]byte
copy(ip4[:], h.session.NICInfo.HostAddr4.IP.AsSlice())
msg := dnsmessage.Message{
Header: dnsmessage.Header{ID: id, Response: true},
// MDNS-SD PTR answer record
// Instead of requesting records of type "SRV" with name "_ipp._tcp.example.com.",
// the client requests records of type "PTR" (pointer from one name to
// another in the DNS namespace) [RFC1035].
// The result of this PTR lookup for the name "<Service>.<Domain>" is a
// set of zero or more PTR records giving Service Instance Names of the
// form:
// Service Instance Name = <Instance> . <Service> . <Domain>
Questions: []dnsmessage.Question{
/*
{
Name: mustNewName(name),
Type: dnsmessage.TypeALL,
Class: dnsmessage.ClassANY,
},
*/
},
Answers: []dnsmessage.Resource{
{
Header: dnsmessage.ResourceHeader{
Name: mustNewName("_sleep-proxy._udp.local."),
Type: dnsmessage.TypePTR,
Class: dnsmessage.ClassINET,
},
Body: &dnsmessage.PTRResource{PTR: mustNewName(name)},
},
{
Header: dnsmessage.ResourceHeader{
Name: mustNewName(name),
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
},
Body: &dnsmessage.AResource{A: ip4},
},
{
Header: dnsmessage.ResourceHeader{
Name: mustNewName(name),
Type: dnsmessage.TypeSRV,
Class: dnsmessage.ClassINET,
},
Body: &dnsmessage.SRVResource{Target: mustNewName(name), Port: 5353},
},
//Every DNS-SD service MUST have a TXT record in addition to its SRV
// record, with the same name, even if the service has no additional
// data to store and the TXT record contains no more than a single zero
// byte.
{
Header: dnsmessage.ResourceHeader{
Name: mustNewName(name),
Type: dnsmessage.TypeTXT,
Class: dnsmessage.ClassINET,
},
Body: &dnsmessage.TXTResource{TXT: []string{"vers=1.0"}},
},
},
Authorities: []dnsmessage.Resource{},
Additionals: []dnsmessage.Resource{},
}
buf, err := msg.Pack()
if err != nil {
return err
}
return h.sendMDNS(buf, srcAddr, dstAddr)
}
type HostName struct {
Name string
Addr packet.Addr
Attributes map[string]string
}
// cache implements a simple cache for DNS responses. Clients multicast the same answer several times
// and at least twice, once for IPv4 and once for IPv6.
type cache struct {
ipv4 []packet.IPNameEntry
ipv6 []packet.IPNameEntry
id uint16
expiry time.Time
}
func (h *DNSHandler) getMDNSCache(mac net.HardwareAddr, id uint16) (c cache, found bool) {
h.mutex.RLock()
defer h.mutex.RUnlock()
key := make([]byte, 6+2)
copy(key, mac)
key[6] = byte(id >> 8)
key[7] = byte(id)
if c, found := h.mdnsCache[string(key)]; found {
if c.expiry.After(time.Now()) {
if Debug {
l := LoggerMDNS.Msg("found in mdns chache").MAC("mac", mac).Uint16("id", id)
for _, v := range c.ipv4 {
l.Struct(v)
}
for _, v := range c.ipv6 {
l.Struct(v)
}
l.Write()
}
return c, true
}
delete(h.mdnsCache, string(key))
if Debug {
LoggerMDNS.Msg("delete from mdns chache").MAC("mac", mac).Uint16("id", id).Write()
}
}
return cache{}, false
}
func (h *DNSHandler) putMDNSCache(mac net.HardwareAddr, id uint16, ipv4 []packet.IPNameEntry, ipv6 []packet.IPNameEntry) {
if Debug {
l := LoggerMDNS.Msg("add to mdns chache").MAC("mac", mac).Uint16("id", id)
for _, v := range ipv4 {
l.Struct(v)
}
for _, v := range ipv6 {
l.Struct(v)
}
l.Write()
}
h.mutex.Lock()
key := make([]byte, 6+2)
copy(key, mac)
key[6] = byte(id >> 8)
key[7] = byte(id)
h.mdnsCache[string(key)] = cache{id: id, ipv4: ipv4, ipv6: ipv6, expiry: time.Now().Add(time.Minute * 5)}
h.mutex.Unlock()
}
// ProcesMDNS will process a multicast DNS packet.
// Note: host cannot be nil.
func (h *DNSHandler) ProcessMDNS(frame packet.Frame) (ipv4 []packet.IPNameEntry, ipv6 []packet.IPNameEntry, err error) {
var p dnsmessage.Parser
dnsHeader, err := p.Start(frame.Payload())
if err != nil {
return ipv4, ipv6, err
}
var addr packet.Addr
if frame.Host != nil {
addr = frame.Host.Addr
}
// if query, we can infer some information.
if !dnsHeader.Response {
var line *fastlog.Line
if Debug {
line = LoggerMDNS.Msg("query rcvd").Struct(addr).Struct(packet.DNS(frame.Payload()))
}
if questions, err := p.AllQuestions(); err == nil {
entry := packet.IPNameEntry{}
entry.NameEntry.Type = moduleMDNS
for _, q := range questions {
name := string(q.Name.Data[:q.Name.Length])
if Debug {
line.String("qname", name)
}
// mdns query sends the name to validate it is unique
// example: qname=Test-iPad.local.
if !strings.HasSuffix(name, "_tcp.local.") && !strings.HasSuffix(name, "_udp.local.") && strings.HasSuffix(name, ".local.") {
entry.NameEntry.Name = strings.TrimSuffix(name, ".local.")
}
if strings.Contains(name, "sleep-proxy") {
entry.NameEntry.Manufacturer = "Apple"
// Advertise that we are a SpeepProxy server
// TODO: this is not working yet - September 2021
// go h.SendSleepProxyResponse(h.session.NICInfo.HostAddr4, mdnsIPv4Addr, dnsHeader.ID, "sleepproxy")
}
}
if entry.NameEntry.Name != "" || entry.NameEntry.Manufacturer != "" {
ipv4 = append(ipv4, entry)
}
}
if Debug {
line.Write()
}
return ipv4, ipv6, nil
}
if Debug {
LoggerMDNS.Msg("response rcvd").Struct(addr).Struct(packet.DNS(frame.Payload())).Write()
}
if _, found := h.getMDNSCache(frame.SrcAddr.MAC, dnsHeader.ID); found {
return nil, nil, nil
}
// Multicast DNS responses MUST NOT contain any questions in the
// Question Section. Any questions in the Question Section of a
// received Multicast DNS response MUST be silently ignored. Multicast
// DNS queriers receiving Multicast DNS responses do not care what
// question elicited the response; they care only that the information
// in the response is true and accurate.
// see https://datatracker.ietf.org/doc/html/rfc6762 section 6
if err := p.SkipAllQuestions(); err != nil {
return ipv4, ipv6, err
}
model := ""
section := "answer"
for {
var hdr dnsmessage.ResourceHeader
switch section {
case "answer":
hdr, err = p.AnswerHeader()
if err == dnsmessage.ErrSectionDone {
section = "authority"
continue
}
case "authority":
hdr, err = p.AuthorityHeader()
if err == dnsmessage.ErrSectionDone {
section = "additional"
continue
}
case "additional":
hdr, err = p.AdditionalHeader()
if err == dnsmessage.ErrSectionDone {
// Model is saved in single ipv4 entry; copy to all IPv6 entries
// before returning
if model != "" {
for i := range ipv4 {
ipv4[i].NameEntry.Model = model
}
for i := range ipv6 {
ipv6[i].NameEntry.Model = model
}
}
// this is the last section; cache entry and return
h.putMDNSCache(frame.SrcAddr.MAC, dnsHeader.ID, ipv4, ipv6)
return ipv4, ipv6, nil
}
}
if err != nil {
return ipv4, ipv6, err
}
switch hdr.Type {
case dnsmessage.TypeA:
r, err := p.AResource()
if err != nil {
return ipv4, ipv6, err
}
entry := packet.IPNameEntry{}
entry.NameEntry.Type = moduleMDNS
entry.NameEntry.Name = strings.TrimSuffix(hdr.Name.String(), ".local.")
entry.Addr.MAC = packet.CopyMAC(frame.SrcAddr.MAC)
entry.Addr.IP = netip.AddrFrom4(r.A)
if Debug {
LoggerMDNS.Msg("A resource").String("name", entry.NameEntry.Name).Struct(entry.Addr).Write()
}
ipv4 = append(ipv4, entry)
case dnsmessage.TypeAAAA:
r, err := p.AAAAResource()
if err != nil {
return ipv4, ipv6, err
}
entry := packet.IPNameEntry{}
entry.NameEntry.Type = moduleMDNS
entry.NameEntry.Name = strings.TrimSuffix(hdr.Name.String(), ".local.")
entry.Addr.MAC = packet.CopyMAC(frame.SrcAddr.MAC)
entry.Addr.IP = netip.AddrFrom16(r.AAAA)
if Debug {
LoggerMDNS.Msg("AAAA resource").String("name", entry.NameEntry.Name).Struct(entry.Addr).Write()
}
ipv6 = append(ipv6, entry)
case dnsmessage.TypePTR:
r, err := p.PTRResource()
if err != nil {
LoggerMDNS.Msg("invalid PTR resource").String("name", hdr.Name.String()).Error(err).Write()
p.SkipAnswer()
continue
}
if Debug {
LoggerMDNS.Msg("PTR resource").String("name", hdr.Name.String()).String("ptr", r.PTR.String()).Write()
}
case dnsmessage.TypeSRV:
// Service record :
// _service._proto.name. TTL class SRV priority weight port target
// example:
// dns.SRV name=sonosB8E9372ACF56._spotify-connect._tcp.local. target=sonosB8E9372ACF56.local. port=1400
r, err := p.SRVResource()
if err != nil {
// Don't log if compressed error.
// dnsmessage package does not allow compressed SRV name which is required in Multicast DNS.
// This polutes the log with constant errors for each SRV.
// https://github.com/golang/go/issues/24870
if strings.Contains(err.Error(), "compressed name in SRV resource data") {
if Debug {
LoggerMDNS.Msg("ignore compressed name in SRV resource").String("name", hdr.Name.String()).String("message", err.Error()).Write()
}
} else {
LoggerMDNS.Msg("invalid SRV resource").String("name", hdr.Name.String()).Error(err).Write()
}
p.SkipAnswer()
continue
}
if Debug {
LoggerMDNS.Msg("SRV resource").String("name", hdr.Name.String()).String("target", r.Target.String()).Uint16("port", r.Port).Write()
}
case dnsmessage.TypeTXT:
r, err := p.TXTResource()
if err != nil {
LoggerMDNS.Msg("invalid TXT resource").String("name", hdr.Name.String()).Error(err).Write()
p.SkipAnswer()
continue
}
if m := parseTXT(r.TXT); m != "" {
model = m
}
if Debug {
LoggerMDNS.Msg("TXT resource").String("name", hdr.Name.String()).Sprintf("txt", r.TXT).String("model", model).Write()
}
case dnsmessage.TypeOPT:
r, err := p.OPTResource()
if err != nil {
// fmt.Printf("mdns : error invalid OPT resource name=%s error=[%s]\n", hdr.Name, err)
LoggerMDNS.Msg("invalid OPT resource").String("name", hdr.Name.String()).Error(err).Write()
p.SkipAnswer()
continue
}
if Debug {
// fmt.Printf("mdns : OPT name=%s options=%v\n", hdr.Name, r.Options)
LoggerMDNS.Msg("OPT resource").String("name", hdr.Name.String()).Sprintf("options", r.Options).Write()
}
case 47:
if Debug {
// fmt.Printf("mdns : NSEC resource type not implemented %+v\n", hdr)
LoggerMDNS.Msg("NSEC resource not implemented").String("name", hdr.Name.String()).Sprintf("hdr", hdr).Write()
}
p.SkipAnswer()
default:
// fmt.Printf("mdns : error unexpected resource type %+v\n", hdr)
LoggerMDNS.Msg("ignoring unexpected resource type").String("name", hdr.Name.String()).Sprintf("hdr", hdr).Write()
p.SkipAnswer()
}
}
}
func mustNewName(name string) dnsmessage.Name {
n, err := dnsmessage.NewName(name)
if err != nil {
panic(err)
}
return n
}