blob: 49bb60f0094c85962bbecfcbf3194f6d642b5ef1 [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);
Garrick Evans9c7afb82021-01-29 22:38:03 +090023
Garrick Evans066dc2c2020-12-10 10:43:55 +090024constexpr char kSystemProxyType[] = "sys";
25constexpr char kDefaultProxyType[] = "def";
26constexpr char kARCProxyType[] = "arc";
Garrick Evans34650b32021-02-03 09:24:35 +090027constexpr uint16_t kDefaultPort = 13568; // port 53 in network order.
Garrick Evans066dc2c2020-12-10 10:43:55 +090028// static
29const char* Proxy::TypeToString(Type t) {
30 switch (t) {
31 case Type::kSystem:
32 return kSystemProxyType;
33 case Type::kDefault:
34 return kDefaultProxyType;
35 case Type::kARC:
36 return kARCProxyType;
37 }
38}
39
40// static
41std::optional<Proxy::Type> Proxy::StringToType(const std::string& s) {
42 if (s == kSystemProxyType)
43 return Type::kSystem;
44
45 if (s == kDefaultProxyType)
46 return Type::kDefault;
47
48 if (s == kARCProxyType)
49 return Type::kARC;
50
51 return std::nullopt;
52}
53
54std::ostream& operator<<(std::ostream& stream, Proxy::Type type) {
55 stream << Proxy::TypeToString(type);
56 return stream;
57}
58
59std::ostream& operator<<(std::ostream& stream, Proxy::Options opt) {
60 stream << "{" << Proxy::TypeToString(opt.type) << ":" << opt.ifname << "}";
61 return stream;
62}
63
64Proxy::Proxy(const Proxy::Options& opts) : opts_(opts) {}
65
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090066Proxy::Proxy(const Options& opts,
67 std::unique_ptr<patchpanel::Client> patchpanel,
68 std::unique_ptr<shill::Client> shill)
69 : opts_(opts),
70 patchpanel_(std::move(patchpanel)),
71 shill_(std::move(shill)) {}
72
Garrick Evans066dc2c2020-12-10 10:43:55 +090073int Proxy::OnInit() {
74 LOG(INFO) << "Starting DNS proxy " << opts_;
75
76 /// Run after Daemon::OnInit()
77 base::ThreadTaskRunnerHandle::Get()->PostTask(
78 FROM_HERE, base::Bind(&Proxy::Setup, weak_factory_.GetWeakPtr()));
79 return DBusDaemon::OnInit();
80}
81
82void Proxy::OnShutdown(int*) {
83 LOG(INFO) << "Stopping DNS proxy " << opts_;
Garrick Evans34650b32021-02-03 09:24:35 +090084 if (opts_.type == Type::kSystem)
85 SetShillProperty("");
Garrick Evans066dc2c2020-12-10 10:43:55 +090086}
87
88void Proxy::Setup() {
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090089 // This is only to account for the injected client for testing.
90 if (!shill_)
91 shill_.reset(new shill::Client(bus_));
92
Garrick Evans066dc2c2020-12-10 10:43:55 +090093 shill_->Init();
Garrick Evans066dc2c2020-12-10 10:43:55 +090094
Garrick Evans5fe2a4f2021-02-03 17:04:48 +090095 // This is only to account for the injected client for testing.
96 if (!patchpanel_)
97 patchpanel_ = patchpanel::Client::New();
98
Garrick Evans066dc2c2020-12-10 10:43:55 +090099 CHECK(patchpanel_) << "Failed to initialize patchpanel client";
100 patchpanel_->RegisterOnAvailableCallback(base::BindRepeating(
101 &Proxy::OnPatchpanelReady, weak_factory_.GetWeakPtr()));
102}
103
104void Proxy::OnPatchpanelReady(bool success) {
105 CHECK(success) << "Failed to connect to patchpanel";
106
107 // The default network proxy might actually be carrying Chrome, Crostini or
108 // if a VPN is on, even ARC traffic, but we attribute this as as "user"
109 // sourced.
110 patchpanel::TrafficCounter::Source traffic_source;
111 switch (opts_.type) {
112 case Type::kSystem:
113 traffic_source = patchpanel::TrafficCounter::SYSTEM;
114 break;
115 case Type::kARC:
116 traffic_source = patchpanel::TrafficCounter::ARC;
117 break;
118 default:
119 traffic_source = patchpanel::TrafficCounter::USER;
120 }
121
122 // Note that using getpid() here requires that this minijail is not creating a
123 // new PID namespace.
124 // The default proxy (only) needs to use the VPN, if applicable, the others
125 // expressly need to avoid it.
126 auto res = patchpanel_->ConnectNamespace(
127 getpid(), opts_.ifname, true /* forward_user_traffic */,
128 opts_.type == Type::kDefault /* route_on_vpn */, traffic_source);
129 CHECK(res.first.is_valid())
130 << "Failed to establish private network namespace";
131 ns_fd_ = std::move(res.first);
Garrick Evans9c7afb82021-01-29 22:38:03 +0900132 ns_ = res.second;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900133 LOG(INFO) << "Sucessfully connected private network namespace:"
Garrick Evans9c7afb82021-01-29 22:38:03 +0900134 << ns_.host_ifname() << " <--> " << ns_.peer_ifname();
Garrick Evans48c84ef2021-01-28 11:29:42 +0900135
Garrick Evans34650b32021-02-03 09:24:35 +0900136 // Now it's safe to register these handlers and respond to them.
137 shill_->RegisterDefaultDeviceChangedHandler(base::BindRepeating(
138 &Proxy::OnDefaultDeviceChanged, weak_factory_.GetWeakPtr()));
139 shill_->RegisterDeviceChangedHandler(
140 base::BindRepeating(&Proxy::OnDeviceChanged, weak_factory_.GetWeakPtr()));
141
Garrick Evans48c84ef2021-01-28 11:29:42 +0900142 if (opts_.type == Type::kSystem)
Garrick Evans34650b32021-02-03 09:24:35 +0900143 shill_->RegisterProcessChangedHandler(
144 base::BindRepeating(&Proxy::OnShillReset, weak_factory_.GetWeakPtr()));
Garrick Evans9c7afb82021-01-29 22:38:03 +0900145}
146
147void Proxy::OnShillReset(bool reset) {
148 if (!reset) {
149 LOG(WARNING) << "Shill has been shutdown";
150 return;
151 }
152
Garrick Evans34650b32021-02-03 09:24:35 +0900153 // Really this means shill crashed. To be safe, explicitly reset the proxy
154 // address. We don't want to crash on failure here because shill might still
155 // have this address and try to use it. This probably redundant though with us
156 // rediscovering the default device.
157 // TODO(garrick): Remove this if so.
Garrick Evans9c7afb82021-01-29 22:38:03 +0900158 LOG(WARNING) << "Shill has been reset";
Garrick Evans34650b32021-02-03 09:24:35 +0900159 SetShillProperty(patchpanel::IPv4AddressToString(ns_.host_ipv4_address()));
Garrick Evans066dc2c2020-12-10 10:43:55 +0900160}
161
Jason Jeremy Iman1bb71c22021-01-26 21:49:55 +0900162std::unique_ptr<Resolver> Proxy::NewResolver(base::TimeDelta timeout) {
163 return std::make_unique<Resolver>(timeout);
Garrick Evans2ca050d2021-02-09 18:21:36 +0900164}
165
Garrick Evans34650b32021-02-03 09:24:35 +0900166void Proxy::OnDefaultDeviceChanged(const shill::Client::Device* const device) {
167 // ARC proxies will handle changes to their network in OnDeviceChanged.
168 if (opts_.type == Proxy::Type::kARC)
169 return;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900170
Garrick Evans34650b32021-02-03 09:24:35 +0900171 // Default service is either not ready yet or has just disconnected.
172 if (!device) {
173 // If it disconnected, shutdown the resolver.
174 if (device_) {
175 LOG(WARNING) << opts_
176 << " is stopping because there is no default service";
177 resolver_.reset();
178 device_.reset();
179 }
180 return;
181 }
182
183 // The system proxy should ignore when a VPN is turned on as it must continue
184 // to work with the underlying physical interface.
185 // TODO(garrick): We need to handle the case when the system proxy is first
186 // started when a VPN is connected. In this case, we need to dig out the
187 // physical network device and use that from here forward.
188 if (opts_.type == Proxy::Type::kSystem &&
189 device->type == shill::Client::Device::Type::kVPN)
190 return;
191
192 // While this is enforced in shill as well, only enable resolution if the
193 // service online.
194 if (device->state != shill::Client::Device::ConnectionState::kOnline) {
195 if (device_) {
196 LOG(WARNING) << opts_ << " is stopping because the default device ["
197 << device->ifname << "] is offline";
198 resolver_.reset();
199 device_.reset();
200 }
201 return;
202 }
203
204 if (!device_)
205 device_ = std::make_unique<shill::Client::Device>();
206
207 // The default network has changed.
208 if (device->ifname != device_->ifname)
209 LOG(INFO) << opts_ << " is now tracking [" << device_->ifname << "]";
210
211 *device_.get() = *device;
212
213 if (!resolver_) {
Jason Jeremy Iman1bb71c22021-01-26 21:49:55 +0900214 resolver_ = NewResolver(kRequestTimeout);
Garrick Evans34650b32021-02-03 09:24:35 +0900215
216 struct sockaddr_in addr = {0};
217 addr.sin_family = AF_INET;
218 addr.sin_port = kDefaultPort;
219 addr.sin_addr.s_addr =
220 INADDR_ANY; // Since we're running in the private namespace.
Garrick Evans2ca050d2021-02-09 18:21:36 +0900221
Jason Jeremy Iman6fd98552021-01-27 04:19:07 +0900222 CHECK(resolver_->ListenUDP(reinterpret_cast<struct sockaddr*>(&addr)))
223 << opts_ << " failed to start UDP relay loop";
224 CHECK(resolver_->ListenTCP(reinterpret_cast<struct sockaddr*>(&addr)))
225 << opts_ << " failed to start TCP relay loop";
Garrick Evans34650b32021-02-03 09:24:35 +0900226 }
227
228 // Update the resolver with the latest DNS config.
229 auto name_servers = device_->ipconfig.ipv4_dns_addresses;
230 name_servers.insert(name_servers.end(),
231 device_->ipconfig.ipv6_dns_addresses.begin(),
232 device_->ipconfig.ipv6_dns_addresses.end());
233 resolver_->SetNameServers(name_servers);
234 LOG(INFO) << opts_ << " applied device DNS configuration";
235
236 // For the system proxy, we have to tell shill about it. We should start
237 // receiving DNS traffic on success. But if this fails, we don't have much
238 // choice but to just crash out and try again.
239 if (opts_.type == Type::kSystem)
240 SetShillProperty(patchpanel::IPv4AddressToString(ns_.host_ipv4_address()),
241 true /* die_on_failure */);
242}
243
244void Proxy::OnDeviceChanged(const shill::Client::Device* const device) {
245 // TODO(garrick): ARC and default for VPN cases.
246}
Garrick Evans066dc2c2020-12-10 10:43:55 +0900247
Garrick Evans9c7afb82021-01-29 22:38:03 +0900248void Proxy::SetShillProperty(const std::string& addr,
249 bool die_on_failure,
250 uint8_t num_retries) {
251 if (opts_.type != Type::kSystem) {
252 LOG(DFATAL) << "Must be called from system proxy only";
253 return;
254 }
Garrick Evans48c84ef2021-01-28 11:29:42 +0900255
Garrick Evans9c7afb82021-01-29 22:38:03 +0900256 if (num_retries == 0) {
257 LOG(ERROR) << "Maximum number of retries exceeding attempt to"
258 << " set dns-proxy address property on shill";
259 CHECK(!die_on_failure);
260 return;
261 }
262
263 // This can only happen if called from OnShutdown and Setup had somehow failed
264 // to create the client... it's unlikely but regardless, that shill client
265 // isn't coming back so there's no point in retrying anything.
Garrick Evans48c84ef2021-01-28 11:29:42 +0900266 if (!shill_) {
Garrick Evans9c7afb82021-01-29 22:38:03 +0900267 LOG(ERROR)
268 << "No connection to shill - cannot set dns-proxy address property ["
269 << addr << "].";
270 return;
Garrick Evans48c84ef2021-01-28 11:29:42 +0900271 }
272
273 brillo::ErrorPtr error;
Garrick Evans9c7afb82021-01-29 22:38:03 +0900274 if (shill_->ManagerProperties()->Set(shill::kDNSProxyIPv4AddressProperty,
275 addr, &error))
276 return;
277
278 LOG(ERROR) << "Failed to set dns-proxy address property [" << addr
279 << "] on shill: " << error->GetMessage() << ". Retrying...";
280
281 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
282 FROM_HERE,
283 base::Bind(&Proxy::SetShillProperty, weak_factory_.GetWeakPtr(), addr,
284 die_on_failure, num_retries - 1),
285 kShillPropertyAttemptDelay);
Garrick Evans48c84ef2021-01-28 11:29:42 +0900286}
287
Garrick Evans066dc2c2020-12-10 10:43:55 +0900288} // namespace dns_proxy