blob: e623d282158bfc012b6337bd8f7867dbbfe33e32 [file] [log] [blame]
Garrick Evans066dc2c2020-12-10 10:43:55 +09001// Copyright 2021 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "dns-proxy/proxy.h"
6
7#include <sys/types.h>
8#include <unistd.h>
9
10#include <utility>
11
12#include <base/bind.h>
13#include <base/threading/thread_task_runner_handle.h>
Garrick Evans9c7afb82021-01-29 22:38:03 +090014#include <base/time/time.h>
Garrick Evans48c84ef2021-01-28 11:29:42 +090015#include <chromeos/patchpanel/net_util.h>
16#include <shill/dbus-constants.h>
Garrick Evans066dc2c2020-12-10 10:43:55 +090017
18namespace dns_proxy {
19
Garrick Evans9c7afb82021-01-29 22:38:03 +090020constexpr base::TimeDelta kShillPropertyAttemptDelay =
21 base::TimeDelta::FromMilliseconds(200);
Jason Jeremy Iman1bb71c22021-01-26 21:49:55 +090022constexpr base::TimeDelta kRequestTimeout = base::TimeDelta::FromSeconds(10000);
Jason Jeremy Iman845f2932021-01-31 16:12:13 +090023constexpr base::TimeDelta kRequestRetryDelay =
24 base::TimeDelta::FromMilliseconds(200);
Garrick Evans9c7afb82021-01-29 22:38:03 +090025
Garrick Evans066dc2c2020-12-10 10:43:55 +090026constexpr char kSystemProxyType[] = "sys";
27constexpr char kDefaultProxyType[] = "def";
28constexpr char kARCProxyType[] = "arc";
Jason Jeremy Iman845f2932021-01-31 16:12:13 +090029constexpr int32_t kRequestMaxRetry = 1;
Garrick Evans34650b32021-02-03 09:24:35 +090030constexpr uint16_t kDefaultPort = 13568; // port 53 in network order.
Garrick Evans066dc2c2020-12-10 10:43:55 +090031// static
32const char* Proxy::TypeToString(Type t) {
33 switch (t) {
34 case Type::kSystem:
35 return kSystemProxyType;
36 case Type::kDefault:
37 return kDefaultProxyType;
38 case Type::kARC:
39 return kARCProxyType;
40 }
41}
42
43// static
44std::optional<Proxy::Type> Proxy::StringToType(const std::string& s) {
45 if (s == kSystemProxyType)
46 return Type::kSystem;
47
48 if (s == kDefaultProxyType)
49 return Type::kDefault;
50
51 if (s == kARCProxyType)
52 return Type::kARC;
53
54 return std::nullopt;
55}
56
57std::ostream& operator<<(std::ostream& stream, Proxy::Type type) {
58 stream << Proxy::TypeToString(type);
59 return stream;
60}
61
62std::ostream& operator<<(std::ostream& stream, Proxy::Options opt) {
63 stream << "{" << Proxy::TypeToString(opt.type) << ":" << opt.ifname << "}";
64 return stream;
65}
66
67Proxy::Proxy(const Proxy::Options& opts) : opts_(opts) {}
68
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090069Proxy::Proxy(const Options& opts,
70 std::unique_ptr<patchpanel::Client> patchpanel,
71 std::unique_ptr<shill::Client> shill)
72 : opts_(opts),
73 patchpanel_(std::move(patchpanel)),
74 shill_(std::move(shill)) {}
75
Garrick Evans066dc2c2020-12-10 10:43:55 +090076int Proxy::OnInit() {
77 LOG(INFO) << "Starting DNS proxy " << opts_;
78
79 /// Run after Daemon::OnInit()
80 base::ThreadTaskRunnerHandle::Get()->PostTask(
81 FROM_HERE, base::Bind(&Proxy::Setup, weak_factory_.GetWeakPtr()));
82 return DBusDaemon::OnInit();
83}
84
85void Proxy::OnShutdown(int*) {
86 LOG(INFO) << "Stopping DNS proxy " << opts_;
Garrick Evans34650b32021-02-03 09:24:35 +090087 if (opts_.type == Type::kSystem)
88 SetShillProperty("");
Garrick Evans066dc2c2020-12-10 10:43:55 +090089}
90
91void Proxy::Setup() {
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090092 // This is only to account for the injected client for testing.
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090093 if (!patchpanel_)
94 patchpanel_ = patchpanel::Client::New();
95
Garrick Evans066dc2c2020-12-10 10:43:55 +090096 CHECK(patchpanel_) << "Failed to initialize patchpanel client";
Garrick Evansfe99aaa2021-02-12 14:32:50 +090097
98 // This is only to account for the injected client for testing.
99 if (!shill_)
100 shill_.reset(new shill::Client(bus_));
101
Garrick Evans066dc2c2020-12-10 10:43:55 +0900102 patchpanel_->RegisterOnAvailableCallback(base::BindRepeating(
103 &Proxy::OnPatchpanelReady, weak_factory_.GetWeakPtr()));
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900104
105 shill_->RegisterOnAvailableCallback(
106 base::BindOnce(&Proxy::OnShillReady, weak_factory_.GetWeakPtr()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900107}
108
109void Proxy::OnPatchpanelReady(bool success) {
110 CHECK(success) << "Failed to connect to patchpanel";
111
112 // The default network proxy might actually be carrying Chrome, Crostini or
113 // if a VPN is on, even ARC traffic, but we attribute this as as "user"
114 // sourced.
115 patchpanel::TrafficCounter::Source traffic_source;
116 switch (opts_.type) {
117 case Type::kSystem:
118 traffic_source = patchpanel::TrafficCounter::SYSTEM;
119 break;
120 case Type::kARC:
121 traffic_source = patchpanel::TrafficCounter::ARC;
122 break;
123 default:
124 traffic_source = patchpanel::TrafficCounter::USER;
125 }
126
127 // Note that using getpid() here requires that this minijail is not creating a
128 // new PID namespace.
129 // The default proxy (only) needs to use the VPN, if applicable, the others
130 // expressly need to avoid it.
131 auto res = patchpanel_->ConnectNamespace(
132 getpid(), opts_.ifname, true /* forward_user_traffic */,
133 opts_.type == Type::kDefault /* route_on_vpn */, traffic_source);
134 CHECK(res.first.is_valid())
135 << "Failed to establish private network namespace";
136 ns_fd_ = std::move(res.first);
Garrick Evans9c7afb82021-01-29 22:38:03 +0900137 ns_ = res.second;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900138 LOG(INFO) << "Sucessfully connected private network namespace:"
Garrick Evans9c7afb82021-01-29 22:38:03 +0900139 << ns_.host_ifname() << " <--> " << ns_.peer_ifname();
Garrick Evans48c84ef2021-01-28 11:29:42 +0900140
Garrick Evans34650b32021-02-03 09:24:35 +0900141 // Now it's safe to register these handlers and respond to them.
142 shill_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
143 &Proxy::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
144 shill_->RegisterDeviceChangedHandler(
145 base::BindRepeating(&Proxy::OnDeviceChanged, weak_factory_.GetWeakPtr()));
146
Garrick Evans48c84ef2021-01-28 11:29:42 +0900147 if (opts_.type == Type::kSystem)
Garrick Evans34650b32021-02-03 09:24:35 +0900148 shill_->RegisterProcessChangedHandler(
149 base::BindRepeating(&Proxy::OnShillReset, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900150}
151
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900152void Proxy::OnShillReady(bool success) {
153 CHECK(success) << "Failed to connect to shill";
154 shill_->Init();
155}
156
Garrick Evans9c7afb82021-01-29 22:38:03 +0900157void Proxy::OnShillReset(bool reset) {
158 if (!reset) {
159 LOG(WARNING) << "Shill has been shutdown";
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900160 // Watch for it to return.
161 shill_->RegisterOnAvailableCallback(
162 base::BindOnce(&Proxy::OnShillReady, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900163 return;
164 }
165
Garrick Evans34650b32021-02-03 09:24:35 +0900166 // Really this means shill crashed. To be safe, explicitly reset the proxy
167 // address. We don't want to crash on failure here because shill might still
168 // have this address and try to use it. This probably redundant though with us
169 // rediscovering the default device.
170 // TODO(garrick): Remove this if so.
Garrick Evans9c7afb82021-01-29 22:38:03 +0900171 LOG(WARNING) << "Shill has been reset";
Garrick Evansaaf9d412021-02-15 11:25:21 +0900172 SetShillProperty(patchpanel::IPv4AddressToString(ns_.peer_ipv4_address()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900173}
174
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900175std::unique_ptr<Resolver> Proxy::NewResolver(base::TimeDelta timeout,
176 base::TimeDelta retry_delay,
177 int max_num_retries) {
178 return std::make_unique<Resolver>(timeout, retry_delay, max_num_retries);
Garrick Evans2ca050d2021-02-09 18:21:36 +0900179}
180
Garrick Evans34650b32021-02-03 09:24:35 +0900181void Proxy::OnDefaultDeviceChanged(const shill::Client::Device* const device) {
182 // ARC proxies will handle changes to their network in OnDeviceChanged.
183 if (opts_.type == Proxy::Type::kARC)
184 return;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900185
Garrick Evans34650b32021-02-03 09:24:35 +0900186 // Default service is either not ready yet or has just disconnected.
187 if (!device) {
188 // If it disconnected, shutdown the resolver.
189 if (device_) {
190 LOG(WARNING) << opts_
191 << " is stopping because there is no default service";
192 resolver_.reset();
193 device_.reset();
194 }
195 return;
196 }
197
198 // The system proxy should ignore when a VPN is turned on as it must continue
199 // to work with the underlying physical interface.
200 // TODO(garrick): We need to handle the case when the system proxy is first
201 // started when a VPN is connected. In this case, we need to dig out the
202 // physical network device and use that from here forward.
203 if (opts_.type == Proxy::Type::kSystem &&
204 device->type == shill::Client::Device::Type::kVPN)
205 return;
206
207 // While this is enforced in shill as well, only enable resolution if the
208 // service online.
209 if (device->state != shill::Client::Device::ConnectionState::kOnline) {
210 if (device_) {
211 LOG(WARNING) << opts_ << " is stopping because the default device ["
212 << device->ifname << "] is offline";
213 resolver_.reset();
214 device_.reset();
215 }
216 return;
217 }
218
219 if (!device_)
220 device_ = std::make_unique<shill::Client::Device>();
221
222 // The default network has changed.
223 if (device->ifname != device_->ifname)
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900224 LOG(INFO) << opts_ << " is now tracking [" << device->ifname << "]";
Garrick Evans34650b32021-02-03 09:24:35 +0900225
226 *device_.get() = *device;
227
228 if (!resolver_) {
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900229 resolver_ =
230 NewResolver(kRequestTimeout, kRequestRetryDelay, kRequestMaxRetry);
Garrick Evans34650b32021-02-03 09:24:35 +0900231
232 struct sockaddr_in addr = {0};
233 addr.sin_family = AF_INET;
234 addr.sin_port = kDefaultPort;
235 addr.sin_addr.s_addr =
236 INADDR_ANY; // Since we're running in the private namespace.
Garrick Evans2ca050d2021-02-09 18:21:36 +0900237
Jason Jeremy Iman6fd98552021-01-27 04:19:07 +0900238 CHECK(resolver_->ListenUDP(reinterpret_cast<struct sockaddr*>(&addr)))
239 << opts_ << " failed to start UDP relay loop";
240 CHECK(resolver_->ListenTCP(reinterpret_cast<struct sockaddr*>(&addr)))
241 << opts_ << " failed to start TCP relay loop";
Garrick Evans34650b32021-02-03 09:24:35 +0900242 }
243
244 // Update the resolver with the latest DNS config.
245 auto name_servers = device_->ipconfig.ipv4_dns_addresses;
246 name_servers.insert(name_servers.end(),
247 device_->ipconfig.ipv6_dns_addresses.begin(),
248 device_->ipconfig.ipv6_dns_addresses.end());
249 resolver_->SetNameServers(name_servers);
250 LOG(INFO) << opts_ << " applied device DNS configuration";
251
252 // For the system proxy, we have to tell shill about it. We should start
253 // receiving DNS traffic on success. But if this fails, we don't have much
254 // choice but to just crash out and try again.
255 if (opts_.type == Type::kSystem)
Garrick Evansaaf9d412021-02-15 11:25:21 +0900256 SetShillProperty(patchpanel::IPv4AddressToString(ns_.peer_ipv4_address()),
Garrick Evans34650b32021-02-03 09:24:35 +0900257 true /* die_on_failure */);
258}
259
260void Proxy::OnDeviceChanged(const shill::Client::Device* const device) {
261 // TODO(garrick): ARC and default for VPN cases.
262}
Garrick Evans066dc2c2020-12-10 10:43:55 +0900263
Garrick Evans9c7afb82021-01-29 22:38:03 +0900264void Proxy::SetShillProperty(const std::string& addr,
265 bool die_on_failure,
266 uint8_t num_retries) {
267 if (opts_.type != Type::kSystem) {
268 LOG(DFATAL) << "Must be called from system proxy only";
269 return;
270 }
Garrick Evans48c84ef2021-01-28 11:29:42 +0900271
Garrick Evans9c7afb82021-01-29 22:38:03 +0900272 if (num_retries == 0) {
273 LOG(ERROR) << "Maximum number of retries exceeding attempt to"
274 << " set dns-proxy address property on shill";
275 CHECK(!die_on_failure);
276 return;
277 }
278
279 // This can only happen if called from OnShutdown and Setup had somehow failed
280 // to create the client... it's unlikely but regardless, that shill client
281 // isn't coming back so there's no point in retrying anything.
Garrick Evans48c84ef2021-01-28 11:29:42 +0900282 if (!shill_) {
Garrick Evans9c7afb82021-01-29 22:38:03 +0900283 LOG(ERROR)
284 << "No connection to shill - cannot set dns-proxy address property ["
285 << addr << "].";
286 return;
Garrick Evans48c84ef2021-01-28 11:29:42 +0900287 }
288
289 brillo::ErrorPtr error;
Garrick Evans9c7afb82021-01-29 22:38:03 +0900290 if (shill_->ManagerProperties()->Set(shill::kDNSProxyIPv4AddressProperty,
291 addr, &error))
292 return;
293
294 LOG(ERROR) << "Failed to set dns-proxy address property [" << addr
295 << "] on shill: " << error->GetMessage() << ". Retrying...";
296
297 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
298 FROM_HERE,
299 base::Bind(&Proxy::SetShillProperty, weak_factory_.GetWeakPtr(), addr,
300 die_on_failure, num_retries - 1),
301 kShillPropertyAttemptDelay);
Garrick Evans48c84ef2021-01-28 11:29:42 +0900302}
303
Garrick Evans066dc2c2020-12-10 10:43:55 +0900304} // namespace dns_proxy