blob: 0404d2c0fc91f7a06ba23348e1e92ff53560cb1b [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>
Garrick Evans4f5428c2021-02-15 11:23:54 +09008#include <sysexits.h>
Garrick Evans066dc2c2020-12-10 10:43:55 +09009#include <unistd.h>
10
11#include <utility>
12
13#include <base/bind.h>
14#include <base/threading/thread_task_runner_handle.h>
Garrick Evans9c7afb82021-01-29 22:38:03 +090015#include <base/time/time.h>
Garrick Evans48c84ef2021-01-28 11:29:42 +090016#include <chromeos/patchpanel/net_util.h>
17#include <shill/dbus-constants.h>
Garrick Evans066dc2c2020-12-10 10:43:55 +090018
19namespace dns_proxy {
20
Garrick Evans9c7afb82021-01-29 22:38:03 +090021constexpr base::TimeDelta kShillPropertyAttemptDelay =
22 base::TimeDelta::FromMilliseconds(200);
Jason Jeremy Iman1bb71c22021-01-26 21:49:55 +090023constexpr base::TimeDelta kRequestTimeout = base::TimeDelta::FromSeconds(10000);
Jason Jeremy Iman845f2932021-01-31 16:12:13 +090024constexpr base::TimeDelta kRequestRetryDelay =
25 base::TimeDelta::FromMilliseconds(200);
Garrick Evans9c7afb82021-01-29 22:38:03 +090026
Garrick Evans066dc2c2020-12-10 10:43:55 +090027constexpr char kSystemProxyType[] = "sys";
28constexpr char kDefaultProxyType[] = "def";
29constexpr char kARCProxyType[] = "arc";
Jason Jeremy Iman845f2932021-01-31 16:12:13 +090030constexpr int32_t kRequestMaxRetry = 1;
Garrick Evans34650b32021-02-03 09:24:35 +090031constexpr uint16_t kDefaultPort = 13568; // port 53 in network order.
Garrick Evans066dc2c2020-12-10 10:43:55 +090032// static
33const char* Proxy::TypeToString(Type t) {
34 switch (t) {
35 case Type::kSystem:
36 return kSystemProxyType;
37 case Type::kDefault:
38 return kDefaultProxyType;
39 case Type::kARC:
40 return kARCProxyType;
41 }
42}
43
44// static
45std::optional<Proxy::Type> Proxy::StringToType(const std::string& s) {
46 if (s == kSystemProxyType)
47 return Type::kSystem;
48
49 if (s == kDefaultProxyType)
50 return Type::kDefault;
51
52 if (s == kARCProxyType)
53 return Type::kARC;
54
55 return std::nullopt;
56}
57
58std::ostream& operator<<(std::ostream& stream, Proxy::Type type) {
59 stream << Proxy::TypeToString(type);
60 return stream;
61}
62
63std::ostream& operator<<(std::ostream& stream, Proxy::Options opt) {
64 stream << "{" << Proxy::TypeToString(opt.type) << ":" << opt.ifname << "}";
65 return stream;
66}
67
68Proxy::Proxy(const Proxy::Options& opts) : opts_(opts) {}
69
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090070Proxy::Proxy(const Options& opts,
71 std::unique_ptr<patchpanel::Client> patchpanel,
72 std::unique_ptr<shill::Client> shill)
73 : opts_(opts),
74 patchpanel_(std::move(patchpanel)),
75 shill_(std::move(shill)) {}
76
Garrick Evans066dc2c2020-12-10 10:43:55 +090077int Proxy::OnInit() {
78 LOG(INFO) << "Starting DNS proxy " << opts_;
79
80 /// Run after Daemon::OnInit()
81 base::ThreadTaskRunnerHandle::Get()->PostTask(
82 FROM_HERE, base::Bind(&Proxy::Setup, weak_factory_.GetWeakPtr()));
83 return DBusDaemon::OnInit();
84}
85
86void Proxy::OnShutdown(int*) {
87 LOG(INFO) << "Stopping DNS proxy " << opts_;
Garrick Evans34650b32021-02-03 09:24:35 +090088 if (opts_.type == Type::kSystem)
89 SetShillProperty("");
Garrick Evans066dc2c2020-12-10 10:43:55 +090090}
91
92void Proxy::Setup() {
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090093 // This is only to account for the injected client for testing.
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090094 if (!patchpanel_)
95 patchpanel_ = patchpanel::Client::New();
96
Garrick Evans066dc2c2020-12-10 10:43:55 +090097 CHECK(patchpanel_) << "Failed to initialize patchpanel client";
Garrick Evansfe99aaa2021-02-12 14:32:50 +090098
99 // This is only to account for the injected client for testing.
100 if (!shill_)
101 shill_.reset(new shill::Client(bus_));
102
Garrick Evans066dc2c2020-12-10 10:43:55 +0900103 patchpanel_->RegisterOnAvailableCallback(base::BindRepeating(
104 &Proxy::OnPatchpanelReady, weak_factory_.GetWeakPtr()));
Garrick Evans4f5428c2021-02-15 11:23:54 +0900105 patchpanel_->RegisterProcessChangedCallback(base::BindRepeating(
106 &Proxy::OnPatchpanelReset, weak_factory_.GetWeakPtr()));
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900107
108 shill_->RegisterOnAvailableCallback(
109 base::BindOnce(&Proxy::OnShillReady, weak_factory_.GetWeakPtr()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900110}
111
112void Proxy::OnPatchpanelReady(bool success) {
113 CHECK(success) << "Failed to connect to patchpanel";
114
115 // The default network proxy might actually be carrying Chrome, Crostini or
116 // if a VPN is on, even ARC traffic, but we attribute this as as "user"
117 // sourced.
118 patchpanel::TrafficCounter::Source traffic_source;
119 switch (opts_.type) {
120 case Type::kSystem:
121 traffic_source = patchpanel::TrafficCounter::SYSTEM;
122 break;
123 case Type::kARC:
124 traffic_source = patchpanel::TrafficCounter::ARC;
125 break;
126 default:
127 traffic_source = patchpanel::TrafficCounter::USER;
128 }
129
130 // Note that using getpid() here requires that this minijail is not creating a
131 // new PID namespace.
132 // The default proxy (only) needs to use the VPN, if applicable, the others
133 // expressly need to avoid it.
134 auto res = patchpanel_->ConnectNamespace(
135 getpid(), opts_.ifname, true /* forward_user_traffic */,
136 opts_.type == Type::kDefault /* route_on_vpn */, traffic_source);
137 CHECK(res.first.is_valid())
138 << "Failed to establish private network namespace";
139 ns_fd_ = std::move(res.first);
Garrick Evans9c7afb82021-01-29 22:38:03 +0900140 ns_ = res.second;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900141 LOG(INFO) << "Sucessfully connected private network namespace:"
Garrick Evans9c7afb82021-01-29 22:38:03 +0900142 << ns_.host_ifname() << " <--> " << ns_.peer_ifname();
Garrick Evans48c84ef2021-01-28 11:29:42 +0900143
Garrick Evans34650b32021-02-03 09:24:35 +0900144 // Now it's safe to register these handlers and respond to them.
145 shill_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
146 &Proxy::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
147 shill_->RegisterDeviceChangedHandler(
148 base::BindRepeating(&Proxy::OnDeviceChanged, weak_factory_.GetWeakPtr()));
149
Garrick Evans48c84ef2021-01-28 11:29:42 +0900150 if (opts_.type == Type::kSystem)
Garrick Evans34650b32021-02-03 09:24:35 +0900151 shill_->RegisterProcessChangedHandler(
152 base::BindRepeating(&Proxy::OnShillReset, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900153}
154
Garrick Evans4f5428c2021-02-15 11:23:54 +0900155void Proxy::OnPatchpanelReset(bool reset) {
156 // If patchpanel crashes, the proxy is useless since the connected virtual
157 // network is gone. So the best bet is to exit and have the controller restart
158 // us. Note if this is the system proxy, it will inform shill on shutdown.
159 LOG(ERROR) << "Patchpanel has been shutdown - restarting DNS proxy " << opts_;
160 QuitWithExitCode(EX_UNAVAILABLE);
161
162 LOG(WARNING) << "Patchpanel has been reset";
163}
164
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900165void Proxy::OnShillReady(bool success) {
166 CHECK(success) << "Failed to connect to shill";
167 shill_->Init();
168}
169
Garrick Evans9c7afb82021-01-29 22:38:03 +0900170void Proxy::OnShillReset(bool reset) {
171 if (!reset) {
172 LOG(WARNING) << "Shill has been shutdown";
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900173 // Watch for it to return.
174 shill_->RegisterOnAvailableCallback(
175 base::BindOnce(&Proxy::OnShillReady, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900176 return;
177 }
178
Garrick Evans34650b32021-02-03 09:24:35 +0900179 // Really this means shill crashed. To be safe, explicitly reset the proxy
180 // address. We don't want to crash on failure here because shill might still
181 // have this address and try to use it. This probably redundant though with us
182 // rediscovering the default device.
183 // TODO(garrick): Remove this if so.
Garrick Evans9c7afb82021-01-29 22:38:03 +0900184 LOG(WARNING) << "Shill has been reset";
Garrick Evansaaf9d412021-02-15 11:25:21 +0900185 SetShillProperty(patchpanel::IPv4AddressToString(ns_.peer_ipv4_address()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900186}
187
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900188std::unique_ptr<Resolver> Proxy::NewResolver(base::TimeDelta timeout,
189 base::TimeDelta retry_delay,
190 int max_num_retries) {
191 return std::make_unique<Resolver>(timeout, retry_delay, max_num_retries);
Garrick Evans2ca050d2021-02-09 18:21:36 +0900192}
193
Garrick Evans34650b32021-02-03 09:24:35 +0900194void Proxy::OnDefaultDeviceChanged(const shill::Client::Device* const device) {
195 // ARC proxies will handle changes to their network in OnDeviceChanged.
196 if (opts_.type == Proxy::Type::kARC)
197 return;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900198
Garrick Evans34650b32021-02-03 09:24:35 +0900199 // Default service is either not ready yet or has just disconnected.
200 if (!device) {
201 // If it disconnected, shutdown the resolver.
202 if (device_) {
203 LOG(WARNING) << opts_
204 << " is stopping because there is no default service";
205 resolver_.reset();
206 device_.reset();
207 }
208 return;
209 }
210
211 // The system proxy should ignore when a VPN is turned on as it must continue
212 // to work with the underlying physical interface.
213 // TODO(garrick): We need to handle the case when the system proxy is first
214 // started when a VPN is connected. In this case, we need to dig out the
215 // physical network device and use that from here forward.
216 if (opts_.type == Proxy::Type::kSystem &&
217 device->type == shill::Client::Device::Type::kVPN)
218 return;
219
220 // While this is enforced in shill as well, only enable resolution if the
221 // service online.
222 if (device->state != shill::Client::Device::ConnectionState::kOnline) {
223 if (device_) {
224 LOG(WARNING) << opts_ << " is stopping because the default device ["
225 << device->ifname << "] is offline";
226 resolver_.reset();
227 device_.reset();
228 }
229 return;
230 }
231
232 if (!device_)
233 device_ = std::make_unique<shill::Client::Device>();
234
235 // The default network has changed.
236 if (device->ifname != device_->ifname)
Garrick Evansfe99aaa2021-02-12 14:32:50 +0900237 LOG(INFO) << opts_ << " is now tracking [" << device->ifname << "]";
Garrick Evans34650b32021-02-03 09:24:35 +0900238
239 *device_.get() = *device;
240
241 if (!resolver_) {
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900242 resolver_ =
243 NewResolver(kRequestTimeout, kRequestRetryDelay, kRequestMaxRetry);
Garrick Evans34650b32021-02-03 09:24:35 +0900244
245 struct sockaddr_in addr = {0};
246 addr.sin_family = AF_INET;
247 addr.sin_port = kDefaultPort;
248 addr.sin_addr.s_addr =
249 INADDR_ANY; // Since we're running in the private namespace.
Garrick Evans2ca050d2021-02-09 18:21:36 +0900250
Jason Jeremy Iman6fd98552021-01-27 04:19:07 +0900251 CHECK(resolver_->ListenUDP(reinterpret_cast<struct sockaddr*>(&addr)))
252 << opts_ << " failed to start UDP relay loop";
253 CHECK(resolver_->ListenTCP(reinterpret_cast<struct sockaddr*>(&addr)))
254 << opts_ << " failed to start TCP relay loop";
Garrick Evans34650b32021-02-03 09:24:35 +0900255 }
256
257 // Update the resolver with the latest DNS config.
258 auto name_servers = device_->ipconfig.ipv4_dns_addresses;
259 name_servers.insert(name_servers.end(),
260 device_->ipconfig.ipv6_dns_addresses.begin(),
261 device_->ipconfig.ipv6_dns_addresses.end());
262 resolver_->SetNameServers(name_servers);
263 LOG(INFO) << opts_ << " applied device DNS configuration";
264
265 // For the system proxy, we have to tell shill about it. We should start
266 // receiving DNS traffic on success. But if this fails, we don't have much
267 // choice but to just crash out and try again.
268 if (opts_.type == Type::kSystem)
Garrick Evansaaf9d412021-02-15 11:25:21 +0900269 SetShillProperty(patchpanel::IPv4AddressToString(ns_.peer_ipv4_address()),
Garrick Evans34650b32021-02-03 09:24:35 +0900270 true /* die_on_failure */);
271}
272
273void Proxy::OnDeviceChanged(const shill::Client::Device* const device) {
274 // TODO(garrick): ARC and default for VPN cases.
275}
Garrick Evans066dc2c2020-12-10 10:43:55 +0900276
Garrick Evans9c7afb82021-01-29 22:38:03 +0900277void Proxy::SetShillProperty(const std::string& addr,
278 bool die_on_failure,
279 uint8_t num_retries) {
280 if (opts_.type != Type::kSystem) {
281 LOG(DFATAL) << "Must be called from system proxy only";
282 return;
283 }
Garrick Evans48c84ef2021-01-28 11:29:42 +0900284
Garrick Evans9c7afb82021-01-29 22:38:03 +0900285 if (num_retries == 0) {
286 LOG(ERROR) << "Maximum number of retries exceeding attempt to"
287 << " set dns-proxy address property on shill";
288 CHECK(!die_on_failure);
289 return;
290 }
291
292 // This can only happen if called from OnShutdown and Setup had somehow failed
293 // to create the client... it's unlikely but regardless, that shill client
294 // isn't coming back so there's no point in retrying anything.
Garrick Evans48c84ef2021-01-28 11:29:42 +0900295 if (!shill_) {
Garrick Evans9c7afb82021-01-29 22:38:03 +0900296 LOG(ERROR)
297 << "No connection to shill - cannot set dns-proxy address property ["
298 << addr << "].";
299 return;
Garrick Evans48c84ef2021-01-28 11:29:42 +0900300 }
301
302 brillo::ErrorPtr error;
Garrick Evans9c7afb82021-01-29 22:38:03 +0900303 if (shill_->ManagerProperties()->Set(shill::kDNSProxyIPv4AddressProperty,
304 addr, &error))
305 return;
306
307 LOG(ERROR) << "Failed to set dns-proxy address property [" << addr
308 << "] on shill: " << error->GetMessage() << ". Retrying...";
309
310 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
311 FROM_HERE,
312 base::Bind(&Proxy::SetShillProperty, weak_factory_.GetWeakPtr(), addr,
313 die_on_failure, num_retries - 1),
314 kShillPropertyAttemptDelay);
Garrick Evans48c84ef2021-01-28 11:29:42 +0900315}
316
Garrick Evans066dc2c2020-12-10 10:43:55 +0900317} // namespace dns_proxy