blob: 4de083f2dec529adb2abad959b057eea6dc23351 [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.
93 if (!shill_)
94 shill_.reset(new shill::Client(bus_));
95
Garrick Evans066dc2c2020-12-10 10:43:55 +090096 shill_->Init();
Garrick Evans066dc2c2020-12-10 10:43:55 +090097
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090098 // This is only to account for the injected client for testing.
99 if (!patchpanel_)
100 patchpanel_ = patchpanel::Client::New();
101
Garrick Evans066dc2c2020-12-10 10:43:55 +0900102 CHECK(patchpanel_) << "Failed to initialize patchpanel client";
103 patchpanel_->RegisterOnAvailableCallback(base::BindRepeating(
104 &Proxy::OnPatchpanelReady, weak_factory_.GetWeakPtr()));
105}
106
107void Proxy::OnPatchpanelReady(bool success) {
108 CHECK(success) << "Failed to connect to patchpanel";
109
110 // The default network proxy might actually be carrying Chrome, Crostini or
111 // if a VPN is on, even ARC traffic, but we attribute this as as "user"
112 // sourced.
113 patchpanel::TrafficCounter::Source traffic_source;
114 switch (opts_.type) {
115 case Type::kSystem:
116 traffic_source = patchpanel::TrafficCounter::SYSTEM;
117 break;
118 case Type::kARC:
119 traffic_source = patchpanel::TrafficCounter::ARC;
120 break;
121 default:
122 traffic_source = patchpanel::TrafficCounter::USER;
123 }
124
125 // Note that using getpid() here requires that this minijail is not creating a
126 // new PID namespace.
127 // The default proxy (only) needs to use the VPN, if applicable, the others
128 // expressly need to avoid it.
129 auto res = patchpanel_->ConnectNamespace(
130 getpid(), opts_.ifname, true /* forward_user_traffic */,
131 opts_.type == Type::kDefault /* route_on_vpn */, traffic_source);
132 CHECK(res.first.is_valid())
133 << "Failed to establish private network namespace";
134 ns_fd_ = std::move(res.first);
Garrick Evans9c7afb82021-01-29 22:38:03 +0900135 ns_ = res.second;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900136 LOG(INFO) << "Sucessfully connected private network namespace:"
Garrick Evans9c7afb82021-01-29 22:38:03 +0900137 << ns_.host_ifname() << " <--> " << ns_.peer_ifname();
Garrick Evans48c84ef2021-01-28 11:29:42 +0900138
Garrick Evans34650b32021-02-03 09:24:35 +0900139 // Now it's safe to register these handlers and respond to them.
140 shill_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
141 &Proxy::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
142 shill_->RegisterDeviceChangedHandler(
143 base::BindRepeating(&Proxy::OnDeviceChanged, weak_factory_.GetWeakPtr()));
144
Garrick Evans48c84ef2021-01-28 11:29:42 +0900145 if (opts_.type == Type::kSystem)
Garrick Evans34650b32021-02-03 09:24:35 +0900146 shill_->RegisterProcessChangedHandler(
147 base::BindRepeating(&Proxy::OnShillReset, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900148}
149
150void Proxy::OnShillReset(bool reset) {
151 if (!reset) {
152 LOG(WARNING) << "Shill has been shutdown";
153 return;
154 }
155
Garrick Evans34650b32021-02-03 09:24:35 +0900156 // Really this means shill crashed. To be safe, explicitly reset the proxy
157 // address. We don't want to crash on failure here because shill might still
158 // have this address and try to use it. This probably redundant though with us
159 // rediscovering the default device.
160 // TODO(garrick): Remove this if so.
Garrick Evans9c7afb82021-01-29 22:38:03 +0900161 LOG(WARNING) << "Shill has been reset";
Garrick Evans34650b32021-02-03 09:24:35 +0900162 SetShillProperty(patchpanel::IPv4AddressToString(ns_.host_ipv4_address()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900163}
164
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900165std::unique_ptr<Resolver> Proxy::NewResolver(base::TimeDelta timeout,
166 base::TimeDelta retry_delay,
167 int max_num_retries) {
168 return std::make_unique<Resolver>(timeout, retry_delay, max_num_retries);
Garrick Evans2ca050d2021-02-09 18:21:36 +0900169}
170
Garrick Evans34650b32021-02-03 09:24:35 +0900171void Proxy::OnDefaultDeviceChanged(const shill::Client::Device* const device) {
172 // ARC proxies will handle changes to their network in OnDeviceChanged.
173 if (opts_.type == Proxy::Type::kARC)
174 return;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900175
Garrick Evans34650b32021-02-03 09:24:35 +0900176 // Default service is either not ready yet or has just disconnected.
177 if (!device) {
178 // If it disconnected, shutdown the resolver.
179 if (device_) {
180 LOG(WARNING) << opts_
181 << " is stopping because there is no default service";
182 resolver_.reset();
183 device_.reset();
184 }
185 return;
186 }
187
188 // The system proxy should ignore when a VPN is turned on as it must continue
189 // to work with the underlying physical interface.
190 // TODO(garrick): We need to handle the case when the system proxy is first
191 // started when a VPN is connected. In this case, we need to dig out the
192 // physical network device and use that from here forward.
193 if (opts_.type == Proxy::Type::kSystem &&
194 device->type == shill::Client::Device::Type::kVPN)
195 return;
196
197 // While this is enforced in shill as well, only enable resolution if the
198 // service online.
199 if (device->state != shill::Client::Device::ConnectionState::kOnline) {
200 if (device_) {
201 LOG(WARNING) << opts_ << " is stopping because the default device ["
202 << device->ifname << "] is offline";
203 resolver_.reset();
204 device_.reset();
205 }
206 return;
207 }
208
209 if (!device_)
210 device_ = std::make_unique<shill::Client::Device>();
211
212 // The default network has changed.
213 if (device->ifname != device_->ifname)
214 LOG(INFO) << opts_ << " is now tracking [" << device_->ifname << "]";
215
216 *device_.get() = *device;
217
218 if (!resolver_) {
Jason Jeremy Iman845f2932021-01-31 16:12:13 +0900219 resolver_ =
220 NewResolver(kRequestTimeout, kRequestRetryDelay, kRequestMaxRetry);
Garrick Evans34650b32021-02-03 09:24:35 +0900221
222 struct sockaddr_in addr = {0};
223 addr.sin_family = AF_INET;
224 addr.sin_port = kDefaultPort;
225 addr.sin_addr.s_addr =
226 INADDR_ANY; // Since we're running in the private namespace.
Garrick Evans2ca050d2021-02-09 18:21:36 +0900227
Jason Jeremy Iman6fd98552021-01-27 04:19:07 +0900228 CHECK(resolver_->ListenUDP(reinterpret_cast<struct sockaddr*>(&addr)))
229 << opts_ << " failed to start UDP relay loop";
230 CHECK(resolver_->ListenTCP(reinterpret_cast<struct sockaddr*>(&addr)))
231 << opts_ << " failed to start TCP relay loop";
Garrick Evans34650b32021-02-03 09:24:35 +0900232 }
233
234 // Update the resolver with the latest DNS config.
235 auto name_servers = device_->ipconfig.ipv4_dns_addresses;
236 name_servers.insert(name_servers.end(),
237 device_->ipconfig.ipv6_dns_addresses.begin(),
238 device_->ipconfig.ipv6_dns_addresses.end());
239 resolver_->SetNameServers(name_servers);
240 LOG(INFO) << opts_ << " applied device DNS configuration";
241
242 // For the system proxy, we have to tell shill about it. We should start
243 // receiving DNS traffic on success. But if this fails, we don't have much
244 // choice but to just crash out and try again.
245 if (opts_.type == Type::kSystem)
246 SetShillProperty(patchpanel::IPv4AddressToString(ns_.host_ipv4_address()),
247 true /* die_on_failure */);
248}
249
250void Proxy::OnDeviceChanged(const shill::Client::Device* const device) {
251 // TODO(garrick): ARC and default for VPN cases.
252}
Garrick Evans066dc2c2020-12-10 10:43:55 +0900253
Garrick Evans9c7afb82021-01-29 22:38:03 +0900254void Proxy::SetShillProperty(const std::string& addr,
255 bool die_on_failure,
256 uint8_t num_retries) {
257 if (opts_.type != Type::kSystem) {
258 LOG(DFATAL) << "Must be called from system proxy only";
259 return;
260 }
Garrick Evans48c84ef2021-01-28 11:29:42 +0900261
Garrick Evans9c7afb82021-01-29 22:38:03 +0900262 if (num_retries == 0) {
263 LOG(ERROR) << "Maximum number of retries exceeding attempt to"
264 << " set dns-proxy address property on shill";
265 CHECK(!die_on_failure);
266 return;
267 }
268
269 // This can only happen if called from OnShutdown and Setup had somehow failed
270 // to create the client... it's unlikely but regardless, that shill client
271 // isn't coming back so there's no point in retrying anything.
Garrick Evans48c84ef2021-01-28 11:29:42 +0900272 if (!shill_) {
Garrick Evans9c7afb82021-01-29 22:38:03 +0900273 LOG(ERROR)
274 << "No connection to shill - cannot set dns-proxy address property ["
275 << addr << "].";
276 return;
Garrick Evans48c84ef2021-01-28 11:29:42 +0900277 }
278
279 brillo::ErrorPtr error;
Garrick Evans9c7afb82021-01-29 22:38:03 +0900280 if (shill_->ManagerProperties()->Set(shill::kDNSProxyIPv4AddressProperty,
281 addr, &error))
282 return;
283
284 LOG(ERROR) << "Failed to set dns-proxy address property [" << addr
285 << "] on shill: " << error->GetMessage() << ". Retrying...";
286
287 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
288 FROM_HERE,
289 base::Bind(&Proxy::SetShillProperty, weak_factory_.GetWeakPtr(), addr,
290 die_on_failure, num_retries - 1),
291 kShillPropertyAttemptDelay);
Garrick Evans48c84ef2021-01-28 11:29:42 +0900292}
293
Garrick Evans066dc2c2020-12-10 10:43:55 +0900294} // namespace dns_proxy