dns_spoof_hosts.go 1.5 KB

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