DNS客户端协议详解

这个DNS系列现在有以下几篇文章
DNS EDNS DNSSEC DNS over HTTPS 完整代码请看DNS

DNS Header

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
                                1  1  1  1  1  1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ID |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|QR| Opcode |AA|TC|RD|RA| Z | RCODE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QDCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ANCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| NSCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| ARCOUNT |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

header在dns请求和应答中相同的,查询中有Query Section,应答中有answer section.

  • ID: 2字节,应答中也有ID,可以用来判断是否为我们请求的应答
  • QR:1bit,请求时为0,应答时为1
  • Opcode:4bit 通常值为0(标准查询),其他值为1(反向查询)和2(服务器状态请求),[3,15]保留值
  • AA:1bit authoritative answer,在应答中才有效
  • TC:1bit 表示可截断
  • RD:1bit 期望使用递归查询
  • RA:1bit 在应答中返回,返回服务器是否支持递归查询
  • Z: Reserved for future use.
  • RCODE:4bit,应答码,代表返回的状态
    • 0 No Error
    • 1 Format error 格式错误
    • 2 Server failure 服务器失败
    • 3 Name Error 查询域名错误
    • 4 Not Implemented 未实现的查询方式
    • 5 Refused 拒绝
    • 6-15 Reserved for future use.
  • QDCOUNT 请求的个数
  • ANCOUNT 应答的个数
  • NSCOUNT 无符号16bit整数表示报文授权段中的授权记录数。
  • ARCOUNT 无符号16bit整数表示报文附加段中的附加记录数。

查询

1
2
3
4
5
6
7
8
9
10
11
                                1  1  1  1  1  1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ QNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QTYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| QCLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  • QNAME:不定长,格式为域名以点分割的长度,末尾以0结尾,例如:

    1
    www.google.com -> 3www6google3com0
  • QTYPE:查询的类型
    常用的我们需要知道A为IPV4,AAAA为IPV6

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    TYPE            value and meaning
    A 1 a host address
    NS 2 an authoritative name server
    MD 3 a mail destination (Obsolete - use MX)
    MF 4 a mail forwarder (Obsolete - use MX)
    CNAME 5 the canonical name for an alias
    SOA 6 marks the start of a zone of authority
    MB 7 a mailbox domain name (EXPERIMENTAL)
    MG 8 a mail group member (EXPERIMENTAL)
    MR 9 a mail rename domain name (EXPERIMENTAL)
    NULL 10 a null RR (EXPERIMENTAL)
    WKS 11 a well known service description
    PTR 12 a domain name pointer
    HINFO 13 host information
    MINFO 14 mailbox or mail list information
    MX 15 mail exchange
    TXT 16 text strings

    AAAA 28 <- https://www.ietf.org/rfc/rfc3596.txt
  • QCLASS:无符号16bit整数表示查询的类,比如,IN代表Internet.

现在我们来完成生成请求的代码
使用全局变量来存储请求的类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type reqType [2]byte

var (
trueA = reqType{0b00000000, 0b00000001} // 1
trueNS = reqType{0b00000000, 0b00000010} // 2
trueMD = reqType{0b00000000, 0b00000011} // 3
trueMF = reqType{0b00000000, 0b00000100} // 3
trueCNAME = reqType{0b00000000, 0b00000101} // 5
trueSOA = reqType{0b00000000, 0b00000110} // 6
trueMB = reqType{0b00000000, 0b00000111} // 7
trueMG = reqType{0b00000000, 0b00001000} // 8
trueMR = reqType{0b00000000, 0b00001001} // 9
trueNULL = reqType{0b00000000, 0b00001010} // 10
trueWKS = reqType{0b00000000, 0b00001011} // 11
truePTR = reqType{0b00000000, 0b00001100} // 12
trueHINFO = reqType{0b00000000, 0b00001101} // 13
trueMINFO = reqType{0b00000000, 0b00001110} // 14
trueMX = reqType{0b00000000, 0b00001111} // 15
trueTXT = reqType{0b00000000, 0b00010000} // 16
trueAAAA = reqType{0b00000000, 0b00011100} // 28 https://www.ietf.org/rfc/rfc3596.txt
true// for req
trueAXFR = reqType{0b00000000, 0b11111100} // 252
trueANY = reqType{0b00000000, 0b11111111} // 255
)

这里需要注意有些字段是以位的大小来存储的,需要使用移位运算符来计算(在完成这个协议前,我写了socks5,因为socks5中全部为字节的大小,可能有人会出现与我相同的错误,所以需要注意一下)

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
func creatRequest(domain string, reqType reqType) []byte {
id := []byte{byte(rand.Intn(255)), byte(rand.Intn(255))} // id:
qr := byte(0b0) // qr 0
trueopCode := byte(0b0000) // opcode 0000
trueaa := byte(0b0) // aa 0
truetc := byte(0b0) // tc 0
truerd := byte(0b1) // rd 1
truera := byte(0b0) // ra 0
truez := byte(0b000) // z 000
truerCode := byte(0b0000) // rCode 0000
trueqr2rCode := []byte{qr<<7 + opCode<<3 + aa<<2 + tc<<1 + rd, ra<<7 + z<<4 + rCode}
trueqdCount := []byte{0b00000000, 0b00000001} // request number => bit: 00000000 00000001 -> 01
trueanCount := []byte{0b00000000, 0b00000000} // answer number(no use for req) => bit: 00000000 00000000
truensCount := []byte{0b00000000, 0b00000000} //(no use for req) => bit: 00000000 00000000
truearCount := []byte{0b00000000, 0b00000000} //(no use for req) => bit: 00000000 00000000

truevar qName []byte
truefor _, x := range strings.Split(domain, ".") {
truetrueqName = append(qName, byte(len(x)))
truetrueqName = append(qName, []byte(x)...)
true}
trueqName = append(qName, 0b00000000) // add the 0 for last of domain

trueqType := []byte{reqType[0], reqType[1]} // type:
trueqClass := []byte{0b00000000, 0b00000001} // 1 -> from internet

truereturn bytes.Join([][]byte{id, qr2rCode, qdCount, anCount, nsCount, arCount, qName, qType, qClass}, []byte{})
}

这里我们已经得到了完整的请求字节数组,然后使用UDP协议发起请求就行了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 此处以www.google.com及1111 DNS为例
req := creatRequest("www.google.com", A)
conn, err := net.DialTimeout("udp", "1.1.1.1:53", 5*time.Second)
if err != nil {
truereturn nil, err
}
defer conn.Close()
if _, err = conn.Write(req); err != nil {
truereturn nil, err
}
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
n, err := conn.Read(b[:])
if err != nil {
truereturn nil, err
}

接下来我们就需要解析应答请求了,来获取我们需要的数据.

应答

应答数据中具有header和请求字段,所以我们可以先写一个resovle header来分析header.
之前我们完成了域名编码的代码,就是3www6google3com0这个,这里我们还需要完成一个解析的.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func getName(c []byte, all []byte) (name string, x []byte) {
truefor {
truetrueif c[0]&128 == 128 && c[0]&64 == 64 { // <- 这里的这个会在下面的answer section中解释
truetruetruel := c[1]
truetruetruec = c[2:]
truetruetruetmp, _ := getName(all[l:], all)
truetruetruename += tmp
truetruetrue//log.Println(c, name)
truetruetruebreak
truetrue}
truetruename += string(c[1:int(c[0])+1]) + "."
truetruec = c[int(c[0])+1:]
truetrueif c[0] == 0 {
truetruetruec = c[1:] // lastOfDomain: one byte 0
truetruetruebreak
truetrue}
true}
truereturn name, c
}

之后就可以来分析header了:

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
func resolveHeader(req []byte, answer []byte) (anCount int, answerSection []byte, err error) {
true// resolve answer
trueif answer[0] != req[0] || answer[1] != req[1] { // compare id
truetrue// not the answer
truetruereturn 0, nil, errors.New("id not same")
true}

trueif answer[2]&8 != 0 { // check the QR is 1(Answer)
truetruereturn 0, nil, errors.New("the qr is not 1(Answer)")
true}

truerCode := fmt.Sprintf("%08b", answer[3])[4:] // check Response code(rCode)
trueswitch rCode {
truecase "0000": // no error
truetruebreak
truecase "0001": // Format error
truetruereturn 0, nil, errors.New("request format error")
truecase "0010": //Server failure
truetruereturn 0, nil, errors.New("dns Server failure")
truecase "0011": //Name Error
truetruereturn 0, nil, errors.New("no such name")
truecase "0100": // Not Implemented
truetruereturn 0, nil, errors.New("dns server not support this request")
truecase "0101": //Refused
truetruereturn 0, nil, errors.New("dns server Refuse")
truedefault: // Reserved for future use.
truetruereturn 0, nil, errors.New("other error")
true}

true//qdCountA := []byte{b[4], b[5]} // no use, for request
true//anCountA := []byte{answer[6], answer[7]}
trueanCount = int(answer[6])<<8 + int(answer[7])
true//nsCount2arCountA := []byte{b[8], b[9], b[10], b[11]} // no use

truec := answer[12:]

truevar x string
truex, c = getName(c, answer)
truelog.Println(x)
true
truelog.Println("qType:", c[:2])
truec = c[2:]
truelog.Println("qClass:", c[:2])
truec = c[2:]

truereturn anCount, c, nil
}

之后就是我们真正需要的数据,Answer section

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
                               1  1  1  1  1  1
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
/ NAME /
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| CLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TTL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RDLENGTH |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/ RDATA /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  • NAME:不定长与之前QNAME相同,这里会使用省略字段:前两bit为11表示压缩格式,而后面跟的14bit表示的是Name所在的位置相对于DNS首部的偏移值
    如:之前的header数组中出现过3www6google3com0,且处的位置为12,这里就可以用192 12两个字节来省略(192是因为11000000,前两位为11)
  • QTYPE:与之前的TYPE相同
  • CLASS:与之前的QCLASS相同
  • TTL: 就是TTL 可以使用搜索引擎查询一下
  • RDLENGTH: RDATA的长度

这个Answer section与之前的header不同,并不是只出现一次,与header中ANCOUNT有关,如果ANCOUNT不为1,后面就会出现多个,要使用循环来获取所有应答数据

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
// resolve answer
anCount, c, err := resolveHeader(req, b[:n])
if err != nil {
return nil, err
}

// answer section
log.Println()
log.Println("Answer section:")

var x string
for anCount != 0 {
truex, c = getName(c, b[:n])
truelog.Println(x)

truetYPE := reqType{c[0], c[1]}
truelog.Println("type:", c[0], c[1])
truec = c[2:] // type
truelog.Println("class:", c[0], c[1])
truec = c[2:] // class
truelog.Println("ttl:", c[0], c[1], c[2], c[3])
truec = c[4:] // ttl 4byte
truesum := int(c[0])<<8 + int(c[1])
truelog.Println("rdlength", sum)
truec = c[2:] // RDLENGTH 跳过总和,因为总和不包括计算域名的长度 2+int(c[0])<<8+int(c[1])

trueswitch tYPE {
truecase A:
truetrueDNS = append(DNS, c[0:4])
truetruec = c[4:] // 4 byte ip addr
truecase AAAA:
truetrueDNS = append(DNS, c[0:16])
truetruec = c[16:] // 16 byte ip addr
truecase NS:
truetruefallthrough
truecase MD:
truetruefallthrough
truecase MF:
truetruefallthrough
truecase CNAME:
truetruefallthrough
truecase SOA:
truetruefallthrough
truecase MG:
truetruefallthrough
truecase MB:
truetruefallthrough
truecase MR:
truetruefallthrough
truecase NULL:
truetruefallthrough
truecase WKS:
truetruefallthrough
truecase PTR:
truetruefallthrough
truecase HINFO:
truetruefallthrough
truecase MINFO:
truetruefallthrough
truecase MX:
truetruefallthrough
truecase TXT:
truetruefallthrough
truedefault:
truetruelog.Println("rdata", c[:sum])
truetruec = c[sum:] // RDATA
true}
trueanCount -= 1
}

虽然这里我只处理了A,和AAAA的请求类型,但是每个类型的数据格式在rfc1035都有详细记录,想要自己实现并不难,毕竟我们已经完成的大部分的数据解析,剩下的一点也应该问题不大.


rfc1035
rfc3596