File: dns_client.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (342 lines) | stat: -rw-r--r-- 10,771 bytes parent folder | download | duplicates (5)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/dns/dns_client.h"

#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <utility>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/histogram_macros.h"
#include "base/notimplemented.h"
#include "base/rand_util.h"
#include "base/values.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/dns/address_sorter.h"
#include "net/dns/dns_session.h"
#include "net/dns/dns_transaction.h"
#include "net/dns/dns_util.h"
#include "net/dns/public/dns_over_https_config.h"
#include "net/dns/public/secure_dns_mode.h"
#include "net/dns/resolve_context.h"
#include "net/log/net_log.h"
#include "net/log/net_log_event_type.h"
#include "net/socket/client_socket_factory.h"
#include "net/third_party/uri_template/uri_template.h"
#include "url/gurl.h"
#include "url/scheme_host_port.h"

namespace net {

namespace {

bool IsEqual(const std::optional<DnsConfig>& c1, const DnsConfig* c2) {
  if (!c1.has_value() && c2 == nullptr)
    return true;

  if (!c1.has_value() || c2 == nullptr)
    return false;

  return c1.value() == *c2;
}

void UpdateConfigForDohUpgrade(DnsConfig* config) {
  bool has_doh_servers = !config->doh_config.servers().empty();
  // Do not attempt upgrade when there are already DoH servers specified or
  // when there are aspects of the system DNS config that are unhandled.
  if (!config->unhandled_options && config->allow_dns_over_https_upgrade &&
      !has_doh_servers &&
      config->secure_dns_mode == SecureDnsMode::kAutomatic) {
    // If we're in strict mode on Android, only attempt to upgrade the
    // specified DoT hostname.
    if (!config->dns_over_tls_hostname.empty()) {
      config->doh_config = DnsOverHttpsConfig(
          GetDohUpgradeServersFromDotHostname(config->dns_over_tls_hostname));
      has_doh_servers = !config->doh_config.servers().empty();
      UMA_HISTOGRAM_BOOLEAN("Net.DNS.UpgradeConfig.DotUpgradeSucceeded",
                            has_doh_servers);
    } else {
      bool all_local = true;
      for (const auto& server : config->nameservers) {
        if (server.address().IsPubliclyRoutable()) {
          all_local = false;
          break;
        }
      }
      UMA_HISTOGRAM_BOOLEAN("Net.DNS.UpgradeConfig.HasPublicInsecureNameserver",
                            !all_local);

      config->doh_config = DnsOverHttpsConfig(
          GetDohUpgradeServersFromNameservers(config->nameservers));
      has_doh_servers = !config->doh_config.servers().empty();
      UMA_HISTOGRAM_BOOLEAN("Net.DNS.UpgradeConfig.InsecureUpgradeSucceeded",
                            has_doh_servers);
    }
  } else {
    UMA_HISTOGRAM_BOOLEAN("Net.DNS.UpgradeConfig.Ineligible.DohSpecified",
                          has_doh_servers);
    UMA_HISTOGRAM_BOOLEAN("Net.DNS.UpgradeConfig.Ineligible.UnhandledOptions",
                          config->unhandled_options);
  }
}

class DnsClientImpl : public DnsClient {
 public:
  DnsClientImpl(NetLog* net_log, const RandIntCallback& rand_int_callback)
      : net_log_(net_log), rand_int_callback_(rand_int_callback) {}

  DnsClientImpl(const DnsClientImpl&) = delete;
  DnsClientImpl& operator=(const DnsClientImpl&) = delete;

  ~DnsClientImpl() override = default;

  bool CanUseSecureDnsTransactions() const override {
    const DnsConfig* config = GetEffectiveConfig();
    return config && !config->doh_config.servers().empty();
  }

  bool CanUseInsecureDnsTransactions() const override {
    const DnsConfig* config = GetEffectiveConfig();
    return config && config->nameservers.size() > 0 && insecure_enabled_ &&
           !config->unhandled_options && !config->dns_over_tls_active;
  }

  bool CanQueryAdditionalTypesViaInsecureDns() const override {
    // Only useful information if insecure DNS is usable, so expect this to
    // never be called if that is not the case.
    DCHECK(CanUseInsecureDnsTransactions());

    return can_query_additional_types_via_insecure_;
  }

  void SetInsecureEnabled(bool enabled,
                          bool additional_types_enabled) override {
    insecure_enabled_ = enabled;
    can_query_additional_types_via_insecure_ = additional_types_enabled;
  }

  bool FallbackFromSecureTransactionPreferred(
      ResolveContext* context) const override {
    if (!CanUseSecureDnsTransactions())
      return true;

    DCHECK(session_);  // Should be true if CanUseSecureDnsTransactions() true.
    return context->NumAvailableDohServers(session_.get()) == 0;
  }

  bool FallbackFromInsecureTransactionPreferred() const override {
    return !CanUseInsecureDnsTransactions() ||
           insecure_fallback_failures_ >= kMaxInsecureFallbackFailures;
  }

  bool SetSystemConfig(std::optional<DnsConfig> system_config) override {
    if (system_config == system_config_)
      return false;

    system_config_ = std::move(system_config);

    return UpdateDnsConfig();
  }

  bool SetConfigOverrides(DnsConfigOverrides config_overrides) override {
    if (config_overrides == config_overrides_)
      return false;

    config_overrides_ = std::move(config_overrides);

    return UpdateDnsConfig();
  }

  void ReplaceCurrentSession() override {
    if (!session_)
      return;

    UpdateSession(session_->config());
  }

  DnsSession* GetCurrentSession() override { return session_.get(); }

  const DnsConfig* GetEffectiveConfig() const override {
    if (!session_)
      return nullptr;

    DCHECK(session_->config().IsValid());
    return &session_->config();
  }

  const DnsHosts* GetHosts() const override {
    const DnsConfig* config = GetEffectiveConfig();
    if (!config)
      return nullptr;

    return &config->hosts;
  }

  std::optional<std::vector<IPEndPoint>> GetPresetAddrs(
      const url::SchemeHostPort& endpoint) const override {
    DCHECK(endpoint.IsValid());
    if (!session_)
      return std::nullopt;
    const auto& servers = session_->config().doh_config.servers();
    auto it = std::ranges::find_if(servers, [&](const auto& server) {
      std::string uri;
      bool valid = uri_template::Expand(server.server_template(), {}, &uri);
      // Server templates are validated before being allowed into the config.
      DCHECK(valid);
      GURL gurl(uri);
      return url::SchemeHostPort(gurl) == endpoint;
    });
    if (it == servers.end())
      return std::nullopt;
    std::vector<IPEndPoint> combined;
    for (const IPAddressList& ips : it->endpoints()) {
      for (const IPAddress& ip : ips) {
        combined.emplace_back(ip, endpoint.port());
      }
    }
    return combined;
  }

  DnsTransactionFactory* GetTransactionFactory() override {
    return session_.get() ? factory_.get() : nullptr;
  }

  AddressSorter* GetAddressSorter() override { return address_sorter_.get(); }

  void IncrementInsecureFallbackFailures() override {
    ++insecure_fallback_failures_;
  }

  void ClearInsecureFallbackFailures() override {
    insecure_fallback_failures_ = 0;
  }

  base::Value::Dict GetDnsConfigAsValueForNetLog() const override {
    const DnsConfig* config = GetEffectiveConfig();
    if (config == nullptr)
      return base::Value::Dict();
    base::Value::Dict dict = config->ToDict();
    dict.Set("can_use_secure_dns_transactions", CanUseSecureDnsTransactions());
    dict.Set("can_use_insecure_dns_transactions",
             CanUseInsecureDnsTransactions());
    return dict;
  }

  std::optional<DnsConfig> GetSystemConfigForTesting() const override {
    return system_config_;
  }

  DnsConfigOverrides GetConfigOverridesForTesting() const override {
    return config_overrides_;
  }

  void SetTransactionFactoryForTesting(
      std::unique_ptr<DnsTransactionFactory> factory) override {
    factory_ = std::move(factory);
  }

  void SetAddressSorterForTesting(
      std::unique_ptr<AddressSorter> address_sorter) override {
    NOTIMPLEMENTED();
  }

 private:
  std::optional<DnsConfig> BuildEffectiveConfig() const {
    DnsConfig config;
    if (config_overrides_.OverridesEverything()) {
      config = config_overrides_.ApplyOverrides(DnsConfig());
    } else {
      if (!system_config_)
        return std::nullopt;

      config = config_overrides_.ApplyOverrides(system_config_.value());
    }

    UpdateConfigForDohUpgrade(&config);

    // TODO(ericorth): Consider keeping a separate DnsConfig for pure Chrome-
    // produced configs to allow respecting all fields like |unhandled_options|
    // while still being able to fallback to system config for DoH.
    // For now, clear the nameservers for extra security if parts of the system
    // config are unhandled.
    if (config.unhandled_options)
      config.nameservers.clear();

    if (!config.IsValid())
      return std::nullopt;

    return config;
  }

  bool UpdateDnsConfig() {
    std::optional<DnsConfig> new_effective_config = BuildEffectiveConfig();

    if (IsEqual(new_effective_config, GetEffectiveConfig()))
      return false;

    insecure_fallback_failures_ = 0;
    UpdateSession(std::move(new_effective_config));

    if (net_log_) {
      net_log_->AddGlobalEntry(NetLogEventType::DNS_CONFIG_CHANGED, [this] {
        return GetDnsConfigAsValueForNetLog();
      });
    }

    return true;
  }

  void UpdateSession(std::optional<DnsConfig> new_effective_config) {
    factory_.reset();
    session_ = nullptr;

    if (new_effective_config) {
      DCHECK(new_effective_config.value().IsValid());

      session_ = base::MakeRefCounted<DnsSession>(
          std::move(new_effective_config).value(), rand_int_callback_,
          net_log_);
      factory_ = DnsTransactionFactory::CreateFactory(session_.get());
    }
  }

  bool insecure_enabled_ = false;
  bool can_query_additional_types_via_insecure_ = false;
  int insecure_fallback_failures_ = 0;

  std::optional<DnsConfig> system_config_;
  DnsConfigOverrides config_overrides_;

  scoped_refptr<DnsSession> session_;
  std::unique_ptr<DnsTransactionFactory> factory_;
  std::unique_ptr<AddressSorter> address_sorter_ =
      AddressSorter::CreateAddressSorter();

  raw_ptr<NetLog> net_log_;

  const RandIntCallback rand_int_callback_;
};

}  // namespace

// static
std::unique_ptr<DnsClient> DnsClient::CreateClient(NetLog* net_log) {
  return std::make_unique<DnsClientImpl>(net_log,
                                         base::BindRepeating(&base::RandInt));
}

// static
std::unique_ptr<DnsClient> DnsClient::CreateClientForTesting(
    NetLog* net_log,
    const RandIntCallback& rand_int_callback) {
  return std::make_unique<DnsClientImpl>(net_log, rand_int_callback);
}

}  // namespace net