blob: d263b42aa34458c9b4742f280b7af8ace1502ae8 [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);
22
Garrick Evans066dc2c2020-12-10 10:43:55 +090023constexpr char kSystemProxyType[] = "sys";
24constexpr char kDefaultProxyType[] = "def";
25constexpr char kARCProxyType[] = "arc";
Garrick Evans34650b32021-02-03 09:24:35 +090026constexpr uint16_t kDefaultPort = 13568; // port 53 in network order.
Garrick Evans066dc2c2020-12-10 10:43:55 +090027
28// 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
Garrick Evans34650b32021-02-03 09:24:35 +0900162void Proxy::OnDefaultDeviceChanged(const shill::Client::Device* const device) {
163 // ARC proxies will handle changes to their network in OnDeviceChanged.
164 if (opts_.type == Proxy::Type::kARC)
165 return;
Garrick Evans066dc2c2020-12-10 10:43:55 +0900166
Garrick Evans34650b32021-02-03 09:24:35 +0900167 // Default service is either not ready yet or has just disconnected.
168 if (!device) {
169 // If it disconnected, shutdown the resolver.
170 if (device_) {
171 LOG(WARNING) << opts_
172 << " is stopping because there is no default service";
173 resolver_.reset();
174 device_.reset();
175 }
176 return;
177 }
178
179 // The system proxy should ignore when a VPN is turned on as it must continue
180 // to work with the underlying physical interface.
181 // TODO(garrick): We need to handle the case when the system proxy is first
182 // started when a VPN is connected. In this case, we need to dig out the
183 // physical network device and use that from here forward.
184 if (opts_.type == Proxy::Type::kSystem &&
185 device->type == shill::Client::Device::Type::kVPN)
186 return;
187
188 // While this is enforced in shill as well, only enable resolution if the
189 // service online.
190 if (device->state != shill::Client::Device::ConnectionState::kOnline) {
191 if (device_) {
192 LOG(WARNING) << opts_ << " is stopping because the default device ["
193 << device->ifname << "] is offline";
194 resolver_.reset();
195 device_.reset();
196 }
197 return;
198 }
199
200 if (!device_)
201 device_ = std::make_unique<shill::Client::Device>();
202
203 // The default network has changed.
204 if (device->ifname != device_->ifname)
205 LOG(INFO) << opts_ << " is now tracking [" << device_->ifname << "]";
206
207 *device_.get() = *device;
208
209 if (!resolver_) {
210 resolver_ = std::make_unique<Resolver>();
211
212 struct sockaddr_in addr = {0};
213 addr.sin_family = AF_INET;
214 addr.sin_port = kDefaultPort;
215 addr.sin_addr.s_addr =
216 INADDR_ANY; // Since we're running in the private namespace.
217 CHECK(resolver_->Listen(reinterpret_cast<struct sockaddr*>(&addr)))
218 << opts_ << " failed to start relay loop";
219 }
220
221 // Update the resolver with the latest DNS config.
222 auto name_servers = device_->ipconfig.ipv4_dns_addresses;
223 name_servers.insert(name_servers.end(),
224 device_->ipconfig.ipv6_dns_addresses.begin(),
225 device_->ipconfig.ipv6_dns_addresses.end());
226 resolver_->SetNameServers(name_servers);
227 LOG(INFO) << opts_ << " applied device DNS configuration";
228
229 // For the system proxy, we have to tell shill about it. We should start
230 // receiving DNS traffic on success. But if this fails, we don't have much
231 // choice but to just crash out and try again.
232 if (opts_.type == Type::kSystem)
233 SetShillProperty(patchpanel::IPv4AddressToString(ns_.host_ipv4_address()),
234 true /* die_on_failure */);
235}
236
237void Proxy::OnDeviceChanged(const shill::Client::Device* const device) {
238 // TODO(garrick): ARC and default for VPN cases.
239}
Garrick Evans066dc2c2020-12-10 10:43:55 +0900240
Garrick Evans9c7afb82021-01-29 22:38:03 +0900241void Proxy::SetShillProperty(const std::string& addr,
242 bool die_on_failure,
243 uint8_t num_retries) {
244 if (opts_.type != Type::kSystem) {
245 LOG(DFATAL) << "Must be called from system proxy only";
246 return;
247 }
Garrick Evans48c84ef2021-01-28 11:29:42 +0900248
Garrick Evans9c7afb82021-01-29 22:38:03 +0900249 if (num_retries == 0) {
250 LOG(ERROR) << "Maximum number of retries exceeding attempt to"
251 << " set dns-proxy address property on shill";
252 CHECK(!die_on_failure);
253 return;
254 }
255
256 // This can only happen if called from OnShutdown and Setup had somehow failed
257 // to create the client... it's unlikely but regardless, that shill client
258 // isn't coming back so there's no point in retrying anything.
Garrick Evans48c84ef2021-01-28 11:29:42 +0900259 if (!shill_) {
Garrick Evans9c7afb82021-01-29 22:38:03 +0900260 LOG(ERROR)
261 << "No connection to shill - cannot set dns-proxy address property ["
262 << addr << "].";
263 return;
Garrick Evans48c84ef2021-01-28 11:29:42 +0900264 }
265
266 brillo::ErrorPtr error;
Garrick Evans9c7afb82021-01-29 22:38:03 +0900267 if (shill_->ManagerProperties()->Set(shill::kDNSProxyIPv4AddressProperty,
268 addr, &error))
269 return;
270
271 LOG(ERROR) << "Failed to set dns-proxy address property [" << addr
272 << "] on shill: " << error->GetMessage() << ". Retrying...";
273
274 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
275 FROM_HERE,
276 base::Bind(&Proxy::SetShillProperty, weak_factory_.GetWeakPtr(), addr,
277 die_on_failure, num_retries - 1),
278 kShillPropertyAttemptDelay);
Garrick Evans48c84ef2021-01-28 11:29:42 +0900279}
280
Garrick Evans066dc2c2020-12-10 10:43:55 +0900281} // namespace dns_proxy