| 1 | package dns_spoof |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "net" |
| 6 | "os" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/gobwas/glob" |
| 11 | |
| 12 | "github.com/evilsocket/islazy/str" |
| 13 | ) |
| 14 | |
| 15 | var hostsSplitter = regexp.MustCompile(`\s+`) |
| 16 | |
| 17 | type HostEntry struct { |
| 18 | Host string |
| 19 | Suffix string |
| 20 | Expr glob.Glob |
| 21 | Address net.IP |
| 22 | } |
| 23 | |
| 24 | func (e HostEntry) Matches(host string) bool { |
| 25 | lowerHost := strings.ToLower(host) |
| 26 | return e.Host == lowerHost || strings.HasSuffix(lowerHost, e.Suffix) || (e.Expr != nil && e.Expr.Match(lowerHost)) |
| 27 | } |
| 28 | |
| 29 | type Hosts []HostEntry |
| 30 | |
| 31 | func NewHostEntry(host string, address net.IP) HostEntry { |
| 32 | entry := HostEntry{ |
| 33 | Host: host, |
| 34 | Address: address, |
| 35 | } |
| 36 | |
| 37 | if host[0] == '.' { |
| 38 | entry.Suffix = host |
| 39 | } else { |
| 40 | entry.Suffix = "." + host |
| 41 | } |
| 42 | |
| 43 | if expr, err := glob.Compile(host); err == nil { |
| 44 | entry.Expr = expr |
| 45 | } |
| 46 | |
| 47 | return entry |
| 48 | } |
| 49 | |
| 50 | func HostsFromFile(filename string, defaultAddress net.IP) (err error, entries []HostEntry) { |
| 51 | input, err := os.Open(filename) |
| 52 | if err != nil { |
| 53 | return |
| 54 | } |
| 55 | defer input.Close() |
| 56 | |
| 57 | scanner := bufio.NewScanner(input) |
| 58 | scanner.Split(bufio.ScanLines) |
| 59 | for scanner.Scan() { |
| 60 | line := str.Trim(scanner.Text()) |
| 61 | if line == "" || line[0] == '#' { |
| 62 | continue |
| 63 | } |
| 64 | if parts := hostsSplitter.Split(line, 2); len(parts) == 2 { |
| 65 | address := net.ParseIP(parts[0]) |
| 66 | domain := parts[1] |
| 67 | entries = append(entries, NewHostEntry(domain, address)) |
| 68 | } else { |
| 69 | entries = append(entries, NewHostEntry(line, defaultAddress)) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | return |
| 74 | } |
| 75 | |
| 76 | func (h Hosts) Resolve(host string) net.IP { |
| 77 | for _, entry := range h { |
| 78 | if entry.Matches(host) { |
| 79 | return entry.Address |
| 80 | } |
| 81 | } |
| 82 | return nil |
| 83 | } |