-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathptr.go
More file actions
52 lines (44 loc) · 1.2 KB
/
Copy pathptr.go
File metadata and controls
52 lines (44 loc) · 1.2 KB
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
package dns
import (
"fmt"
"net"
"strings"
)
// VerifyPTR checks that the connecting IP has a valid reverse DNS record
// that resolves back to the same IP (forward-confirmed reverse DNS).
func VerifyPTR(ip string) (string, bool, error) {
// Check cache
cacheKey := "ptr:" + ip
if cached, ok := globalCache.Get(cacheKey); ok {
result := cached.(*ptrResult)
return result.hostname, result.valid, nil
}
names, err := net.LookupAddr(ip)
if err != nil || len(names) == 0 {
result := &ptrResult{"", false}
globalCache.Set(cacheKey, result)
return "", false, fmt.Errorf("PTR lookup for %s: %w", ip, err)
}
hostname := strings.TrimSuffix(names[0], ".")
// Forward-confirm: hostname should resolve back to the same IP
addrs, err := net.LookupHost(hostname)
if err != nil {
result := &ptrResult{hostname, false}
globalCache.Set(cacheKey, result)
return hostname, false, nil
}
for _, addr := range addrs {
if addr == ip {
result := &ptrResult{hostname, true}
globalCache.Set(cacheKey, result)
return hostname, true, nil
}
}
result := &ptrResult{hostname, false}
globalCache.Set(cacheKey, result)
return hostname, false, nil
}
type ptrResult struct {
hostname string
valid bool
}