v2fly/app/dns/nameserver.go

221 lines
7.7 KiB
Go
Raw Normal View History

2017-12-19 22:55:09 +00:00
package dns
2016-05-16 06:09:28 +00:00
import (
"context"
"net/url"
"strings"
"time"
2016-05-16 06:09:28 +00:00
2021-02-16 20:31:50 +00:00
core "github.com/v2fly/v2ray-core/v4"
"github.com/v2fly/v2ray-core/v4/app/router"
"github.com/v2fly/v2ray-core/v4/common/errors"
"github.com/v2fly/v2ray-core/v4/common/net"
"github.com/v2fly/v2ray-core/v4/common/strmatcher"
"github.com/v2fly/v2ray-core/v4/features/dns"
2021-02-16 20:31:50 +00:00
"github.com/v2fly/v2ray-core/v4/features/routing"
2016-05-16 06:09:28 +00:00
)
// Server is the interface for Name Server.
type Server interface {
2019-02-22 23:01:23 +00:00
// Name of the Client.
2018-11-22 15:29:09 +00:00
Name() string
2019-02-22 23:01:23 +00:00
// QueryIP sends IP queries to its configured server.
QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, disableCache bool) ([]net.IP, error)
2016-05-16 06:09:28 +00:00
}
2016-05-16 16:05:01 +00:00
// Client is the interface for DNS client.
type Client struct {
server Server
clientIP net.IP
skipFallback bool
domains []string
expectIPs []*router.GeoIPMatcher
2016-05-16 16:05:01 +00:00
}
var errExpectedIPNonMatch = errors.New("expectIPs not match")
// NewServer creates a name server object according to the network destination url.
func NewServer(dest net.Destination, dispatcher routing.Dispatcher) (Server, error) {
if address := dest.Address; address.Family().IsDomain() {
u, err := url.Parse(address.Domain())
if err != nil {
return nil, err
}
switch {
case strings.EqualFold(u.String(), "localhost"):
return NewLocalNameServer(), nil
case strings.EqualFold(u.Scheme, "https"): // DOH Remote mode
return NewDoHNameServer(u, dispatcher)
case strings.EqualFold(u.Scheme, "https+local"): // DOH Local mode
return NewDoHLocalNameServer(u), nil
case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
2020-12-25 11:13:50 +00:00
return NewQUICNameServer(u)
case strings.EqualFold(u.Scheme, "tcp"): // DNS-over-TCP Remote mode
return NewTCPNameServer(u, dispatcher)
case strings.EqualFold(u.Scheme, "tcp+local"): // DNS-over-TCP Local mode
return NewTCPLocalNameServer(u)
case strings.EqualFold(u.String(), "fakedns"):
Feature: Fake DNS support (#406) * Add fake dns A new config object "fake" in DnsObject for toggling fake dns function Compare with sniffing, fake dns is not limited to http and tls traffic. It works across all inbounds. For example, when dns request come from one inbound, the local DNS server of v2ray will response with a unique fake IP for every unique domain name. Then later on v2ray received a request to one of the fake IP from any inbounds, it will override the request destination with the previously saved domain. By default, v2ray cache up to 65535 addresses. The old records will be discarded bases on LRU. The fake IP will be 240.x.x.x * fix an edge case when encounter a fake IP in use * Move lru to common.cache package * Added the necessary change to obtain request IP from sniffer * Refactor the code so that it may stop depending on global variables in the future. * Replace string manipulation code with more generic codes, hopefully this will work for both IPv4 and IPv6 networks. * Try to use IPv4 version of address if possible * Added Test Case for Fake Dns * Added More Test Case for Fake Dns * Stop user from creating a instance with LRU size more than subnet size, it will create a infinite loop * Move Fake DNS to a separate package * Generated Code for fakedns * Encapsulate Fake DNS as a Instance wide service * Added Support for metadata sniffer, which will be used for Fake DNS * Dependency injection for fake dns * Fake DNS As a Sniffer * Remove stub object * Remove global variable * Update generated protobuf file for metadata only sniffing * Apply Fake DNS config to session * Loading for fake dns settings * Bug fix * Include fake dns in all * Fix FakeDns Lint Condition * Fix sniffer config * Fix lint message * Fix dependency resolution * Fix fake dns not loaded as sniffer * reduce ttl for fake dns * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Apply Coding Style * Fix crashed when no fake dns * Apply Coding Style * Fix Fake DNS do not apply to UDP socket * Fixed a bug prevent FakeDNS App Setting from become effective * Fixed a caveat prevent FakeDNS App Setting from become effective * Use log comparison to reduce in issue when it comes to really high value typical for ipv6 subnet * Add build tag for fakedns * Removal of FakeDNS specific logic at DNS client: making it a standard dns client * Regenerate auto generated file * Amended version of configure file * Bug fixes for fakeDNS * Bug fixes for fakeDNS * Fix test: remove reference to removed attribute * Test: fix codacy issue * Conf: Remove old field support * Test: fix codacy issue * Change test scale for TestFakeDnsHolderCreateMappingAndRollOver * Test: fix codacy issue Co-authored-by: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Co-authored-by: loyalsoldier <10487845+Loyalsoldier@users.noreply.github.com> Co-authored-by: kslr <kslrwang@gmail.com>
2021-02-08 10:18:52 +00:00
return NewFakeDNSServer(), nil
}
}
if dest.Network == net.Network_Unknown {
dest.Network = net.Network_UDP
}
if dest.Network == net.Network_UDP { // UDP classic DNS mode
return NewClassicNameServer(dest, dispatcher), nil
2018-06-26 13:16:45 +00:00
}
return nil, newError("No available name server could be created from ", dest).AtWarning()
}
// NewClient creates a DNS client managing a name server with client IP, domain rules and expected IPs.
func NewClient(ctx context.Context, ns *NameServer, clientIP net.IP, container router.GeoIPMatcherContainer, matcherInfos *[]DomainMatcherInfo, updateDomainRule func(strmatcher.Matcher, int, []DomainMatcherInfo) error) (*Client, error) {
client := &Client{}
err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
// Create a new server for each client for now
server, err := NewServer(ns.Address.AsDestination(), dispatcher)
if err != nil {
return newError("failed to create nameserver").Base(err).AtWarning()
}
// Priotize local domains with specific TLDs or without any dot to local DNS
if _, isLocalDNS := server.(*LocalNameServer); isLocalDNS {
ns.PrioritizedDomain = append(ns.PrioritizedDomain, localTLDsAndDotlessDomains...)
ns.OriginalRules = append(ns.OriginalRules, localTLDsAndDotlessDomainsRule)
2021-03-03 08:53:42 +00:00
// The following lines is a solution to avoid core panicsrule index out of range when setting `localhost` DNS client in config.
// Because the `localhost` DNS client will apend len(localTLDsAndDotlessDomains) rules into matcherInfos to match `geosite:private` default rule.
// But `matcherInfos` has no enough length to add rules, which leads to core panics (rule index out of range).
// To avoid this, the length of `matcherInfos` must be equal to the expected, so manually append it with Golang default zero value first for later modification.
// Related issues:
// https://github.com/v2fly/v2ray-core/issues/529
// https://github.com/v2fly/v2ray-core/issues/719
for i := 0; i < len(localTLDsAndDotlessDomains); i++ {
*matcherInfos = append(*matcherInfos, DomainMatcherInfo{
2021-03-03 08:53:42 +00:00
clientIdx: uint16(0),
domainRuleIdx: uint16(0),
})
}
}
// Establish domain rules
var rules []string
ruleCurr := 0
ruleIter := 0
for _, domain := range ns.PrioritizedDomain {
domainRule, err := toStrMatcher(domain.Type, domain.Domain)
if err != nil {
return newError("failed to create prioritized domain").Base(err).AtWarning()
}
originalRuleIdx := ruleCurr
if ruleCurr < len(ns.OriginalRules) {
rule := ns.OriginalRules[ruleCurr]
if ruleCurr >= len(rules) {
rules = append(rules, rule.Rule)
}
ruleIter++
if ruleIter >= int(rule.Size) {
ruleIter = 0
ruleCurr++
}
} else { // No original rule, generate one according to current domain matcher (majorly for compatibility with tests)
rules = append(rules, domainRule.String())
ruleCurr++
}
2021-03-03 08:53:42 +00:00
err = updateDomainRule(domainRule, originalRuleIdx, *matcherInfos)
if err != nil {
return newError("failed to create prioritized domain").Base(err).AtWarning()
}
}
// Establish expected IPs
var matchers []*router.GeoIPMatcher
for _, geoip := range ns.Geoip {
matcher, err := container.Add(geoip)
if err != nil {
return newError("failed to create ip matcher").Base(err).AtWarning()
}
matchers = append(matchers, matcher)
}
if len(clientIP) > 0 {
switch ns.Address.Address.GetAddress().(type) {
case *net.IPOrDomain_Domain:
newError("DNS: client ", ns.Address.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
case *net.IPOrDomain_Ip:
newError("DNS: client ", ns.Address.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
}
}
client.server = server
client.clientIP = clientIP
client.skipFallback = ns.SkipFallback
client.domains = rules
client.expectIPs = matchers
return nil
})
return client, err
}
// NewSimpleClient creates a DNS client with a simple destination.
func NewSimpleClient(ctx context.Context, endpoint *net.Endpoint, clientIP net.IP) (*Client, error) {
client := &Client{}
err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
server, err := NewServer(endpoint.AsDestination(), dispatcher)
if err != nil {
return newError("failed to create nameserver").Base(err).AtWarning()
}
client.server = server
client.clientIP = clientIP
return nil
})
if len(clientIP) > 0 {
switch endpoint.Address.GetAddress().(type) {
case *net.IPOrDomain_Domain:
newError("DNS: client ", endpoint.Address.GetDomain(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
case *net.IPOrDomain_Ip:
newError("DNS: client ", endpoint.Address.GetIp(), " uses clientIP ", clientIP.String()).AtInfo().WriteToLog()
}
2018-06-26 13:16:45 +00:00
}
return client, err
}
// Name returns the server name the client manages.
func (c *Client) Name() string {
return c.server.Name()
2018-06-26 13:16:45 +00:00
}
// QueryIP send DNS query to the name server with the client's IP.
func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption, disableCache bool) ([]net.IP, error) {
ctx, cancel := context.WithTimeout(ctx, 4*time.Second)
ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option, disableCache)
cancel()
if err != nil {
return ips, err
}
return c.MatchExpectedIPs(domain, ips)
2018-11-22 15:29:09 +00:00
}
// MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
if len(c.expectIPs) == 0 {
return ips, nil
}
newIps := []net.IP{}
for _, ip := range ips {
for _, matcher := range c.expectIPs {
if matcher.Match(ip) {
newIps = append(newIps, ip)
break
}
}
}
if len(newIps) == 0 {
return nil, errExpectedIPNonMatch
2018-06-26 13:16:45 +00:00
}
newError("domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()).AtDebug().WriteToLog()
return newIps, nil
2016-05-16 16:05:01 +00:00
}