blob: 370df2ec6ed03f19df805255f685089001b1f36e [file] [log] [blame]
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07001// Copyright 2016 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
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/manager.h"
Kevin Cernekee4e62cc12016-12-03 11:50:53 -08006
Kevin Cernekee95d4ae92016-06-19 10:26:29 -07007#include <arpa/inet.h>
Garrick Evans4ac09852020-01-16 14:09:22 +09008#include <net/if.h>
Hugo Benichi935eca92018-07-03 13:47:24 +09009#include <netinet/in.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070010#include <stdint.h>
Hugo Benichi7352ad92020-04-07 16:11:59 +090011#include <sys/epoll.h>
Garrick Evans54861622019-07-19 09:05:09 +090012#include <sys/prctl.h>
Garrick Evans96e03042019-05-28 14:30:52 +090013#include <sys/socket.h>
14#include <sys/un.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070015
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080016#include <utility>
17
Hugo Benichicc6850f2020-01-17 13:26:06 +090018#include <base/bind.h>
Taoyu Lia0727dc2020-09-24 19:54:59 +090019#include <base/files/scoped_file.h>
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070020#include <base/logging.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090021#include <base/strings/string_number_conversions.h>
Garrick Evans96e03042019-05-28 14:30:52 +090022#include <base/strings/string_split.h>
Garrick Evans6f258d02019-06-28 16:32:07 +090023#include <base/strings/string_util.h>
Taoyu Li179dcc62019-10-17 11:21:08 +090024#include <base/strings/stringprintf.h>
hschamf9546312020-04-14 15:12:40 +090025#include <base/threading/thread_task_runner_handle.h>
Taoyu Lic85c44b2019-12-04 17:32:57 +090026#include <brillo/key_value_store.h>
Kevin Cernekee27bcaa62016-12-03 11:16:26 -080027#include <brillo/minijail/minijail.h>
28
Garrick Evans3388a032020-03-24 11:25:55 +090029#include "patchpanel/ipc.pb.h"
30#include "patchpanel/mac_address_generator.h"
31#include "patchpanel/net_util.h"
32#include "patchpanel/routing_service.h"
33#include "patchpanel/scoped_ns.h"
Garrick Evans428e4762018-12-11 15:18:42 +090034
Garrick Evans3388a032020-03-24 11:25:55 +090035namespace patchpanel {
Garrick Evans08843932019-09-17 14:41:08 +090036namespace {
Garrick Evans4c042572019-12-17 13:42:25 +090037constexpr int kSubprocessRestartDelayMs = 900;
Garrick Evans08843932019-09-17 14:41:08 +090038
Hugo Benichi321f23b2020-09-25 15:42:05 +090039// Constants used for dropping locally originated traffic bound to an incorrect
40// source IPv4 address.
41constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
42constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
43 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
44
Hugo Benichi7352ad92020-04-07 16:11:59 +090045// Time interval between epoll checks on file descriptors committed by callers
46// of ConnectNamespace DBus API.
47constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090048 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090049
Garrick Evans08843932019-09-17 14:41:08 +090050// Passes |method_call| to |handler| and passes the response to
51// |response_sender|. If |handler| returns nullptr, an empty response is
52// created and sent.
53void HandleSynchronousDBusMethodCall(
54 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
55 dbus::MethodCall* method_call,
56 dbus::ExportedObject::ResponseSender response_sender) {
57 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
58 if (!response)
59 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090060 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090061}
62
63} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070064
Taoyu Lice7caa62019-10-01 15:43:33 +090065Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090066 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090067 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090068 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090069 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090070 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090071 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090072 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090073 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090074}
Long Chengd4415582019-09-24 19:16:09 +000075
Garrick Evans207e7482019-12-16 11:54:36 +090076Manager::~Manager() {
77 OnShutdown(nullptr);
78}
79
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090080std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
81
82bool Manager::ShouldEnableFeature(
83 int min_android_sdk_version,
84 int min_chrome_milestone,
85 const std::vector<std::string>& supported_boards,
86 const std::string& feature_name) {
87 static const char kLsbReleasePath[] = "/etc/lsb-release";
88
89 const auto& cached_result = cached_feature_enabled_.find(feature_name);
90 if (cached_result != cached_feature_enabled_.end())
91 return cached_result->second;
92
93 auto check = [min_android_sdk_version, min_chrome_milestone,
94 &supported_boards, &feature_name]() {
95 brillo::KeyValueStore store;
96 if (!store.Load(base::FilePath(kLsbReleasePath))) {
97 LOG(ERROR) << "Could not read lsb-release";
98 return false;
99 }
100
101 std::string value;
102 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
103 LOG(ERROR) << feature_name
104 << " disabled - cannot determine Android SDK version";
105 return false;
106 }
107 int ver = 0;
108 if (!base::StringToInt(value.c_str(), &ver)) {
109 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
110 return false;
111 }
112 if (ver < min_android_sdk_version) {
113 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
114 return false;
115 }
116
117 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
118 LOG(ERROR) << feature_name
119 << " disabled - cannot determine ChromeOS milestone";
120 return false;
121 }
122 if (!base::StringToInt(value.c_str(), &ver)) {
123 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
124 return false;
125 }
126 if (ver < min_chrome_milestone) {
127 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
128 return false;
129 }
130
131 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
132 LOG(ERROR) << feature_name << " disabled - cannot determine board";
133 return false;
134 }
135 if (!supported_boards.empty() &&
136 std::find(supported_boards.begin(), supported_boards.end(), value) ==
137 supported_boards.end()) {
138 LOG(INFO) << feature_name << " disabled for board " << value;
139 return false;
140 }
141 return true;
142 };
143
144 bool result = check();
145 cached_feature_enabled_.emplace(feature_name, result);
146 return result;
147}
148
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700149int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900150 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800151
152 // Handle subprocess lifecycle.
153 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900154
155 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900156 FROM_HERE, adb_proxy_->pid(),
157 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
158 adb_proxy_->pid())))
159 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900160 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900161 FROM_HERE, mcast_proxy_->pid(),
162 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
163 nd_proxy_->pid())))
164 << "Failed to watch multicast-proxy child process";
165 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900166 FROM_HERE, nd_proxy_->pid(),
167 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
168 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900169 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900170
Garrick Evans49879532018-12-03 13:15:36 +0900171 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900172 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700173 FROM_HERE,
174 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
175
176 return DBusDaemon::OnInit();
177}
178
179void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900180 LOG(INFO) << "Setting up DBus service interface";
181 dbus_svc_path_ = bus_->GetExportedObject(
182 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
183 if (!dbus_svc_path_) {
184 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
185 << " object";
186 }
187
188 using ServiceMethod =
189 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
190 const std::map<const char*, ServiceMethod> kServiceMethods = {
191 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
192 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
193 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
194 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900195 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
196 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900197 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
198 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900199 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900200 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900201 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900202 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900203 };
204
205 for (const auto& kv : kServiceMethods) {
206 if (!dbus_svc_path_->ExportMethodAndBlock(
207 patchpanel::kPatchPanelInterface, kv.first,
208 base::Bind(&HandleSynchronousDBusMethodCall,
209 base::Bind(kv.second, base::Unretained(this))))) {
210 LOG(FATAL) << "Failed to export method " << kv.first;
211 }
212 }
213
214 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
215 dbus::Bus::REQUIRE_PRIMARY)) {
216 LOG(FATAL) << "Failed to take ownership of "
217 << patchpanel::kPatchPanelServiceName;
218 }
219 LOG(INFO) << "DBus service interface ready";
220
Hugo Benichifda77232020-08-21 18:28:15 +0900221 routing_svc_ = std::make_unique<RoutingService>();
222
223 StartDatapath();
224
Taoyu Lia0727dc2020-09-24 19:54:59 +0900225 nd_proxy_->RegisterNDProxyMessageHandler(
226 base::Bind(&Manager::OnNDProxyMessage, weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900227
228 shill_client_ = std::make_unique<ShillClient>(bus_);
229 auto* const forwarder = static_cast<TrafficForwarder*>(this);
230
231 GuestMessage::GuestType arc_guest =
232 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
233 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
234 &addr_mgr_, forwarder, arc_guest);
235 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
236 datapath_.get(), forwarder);
Jie Jiang84966852020-09-18 18:49:05 +0900237 network_monitor_svc_ = std::make_unique<NetworkMonitorService>(
238 shill_client_.get(),
239 base::BindRepeating(&Manager::OnNeighborConnectedStateChanged,
240 weak_factory_.GetWeakPtr()));
Hugo Benichifda77232020-08-21 18:28:15 +0900241 network_monitor_svc_->Start();
242
243 counters_svc_ =
244 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
245
246 nd_proxy_->Listen();
247}
248
249void Manager::OnShutdown(int* exit_code) {
250 LOG(INFO) << "Shutting down and cleaning up";
Jie Jiang84966852020-09-18 18:49:05 +0900251 network_monitor_svc_.reset();
Hugo Benichifda77232020-08-21 18:28:15 +0900252 cros_svc_.reset();
253 arc_svc_.reset();
254 close(connected_namespaces_epollfd_);
255 // Tear down any remaining connected namespace.
256 std::vector<int> connected_namespaces_fdkeys;
257 for (const auto& kv : connected_namespaces_)
258 connected_namespaces_fdkeys.push_back(kv.first);
259 for (const int fdkey : connected_namespaces_fdkeys)
260 DisconnectNamespace(fdkey);
261 StopDatapath();
262}
263
264void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
265 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
266 << " attempting to restart";
267
268 HelperProcess* proc;
269 if (pid == adb_proxy_->pid()) {
270 proc = adb_proxy_.get();
271 } else if (pid == mcast_proxy_->pid()) {
272 proc = mcast_proxy_.get();
273 } else if (pid == nd_proxy_->pid()) {
274 proc = nd_proxy_.get();
275 } else {
276 LOG(DFATAL) << "Unknown child process";
277 return;
278 }
279
280 process_reaper_.ForgetChild(pid);
281
282 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
283 FROM_HERE,
284 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
285 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
286 kSubprocessRestartDelayMs));
287}
288
289void Manager::RestartSubprocess(HelperProcess* subproc) {
290 if (subproc->Restart()) {
291 DCHECK(process_reaper_.WatchForChild(
292 FROM_HERE, subproc->pid(),
293 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
294 subproc->pid())))
295 << "Failed to watch child process " << subproc->pid();
296 }
297}
298
299void Manager::StartDatapath() {
300 // b/162966185: Allow Jetstream to disable:
301 // - the IP forwarding setup used for hosting VMs and containers,
302 // - the iptables rules for fwmark based routing.
303 if (USE_JETSTREAM_ROUTING) {
304 LOG(INFO) << "Skipping Datapath routing setup";
305 return;
306 }
307
Taoyu Li6d479442019-12-09 13:02:29 +0900308 auto& runner = datapath_->runner();
Hugo Benichifda77232020-08-21 18:28:15 +0900309
Garrick Evans7cf8c542020-05-25 09:50:17 +0900310 // Enable IPv4 packet forwarding
311 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
312 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
313 << " Guest connectivity will not work correctly.";
314 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900315 // Limit local port range: Android owns 47104-61000.
316 // TODO(garrick): The original history behind this tweak is gone. Some
317 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900318 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900319 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
320 << " apps may not work correctly.";
321 }
Taoyu Li6d479442019-12-09 13:02:29 +0900322 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900323 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900324 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
325 << " IPv6 functionality may be broken.";
326 }
Taoyu Li6d479442019-12-09 13:02:29 +0900327
Garrick Evansd291af62020-05-25 10:39:06 +0900328 if (!datapath_->AddSNATMarkRules()) {
329 LOG(ERROR) << "Failed to install SNAT mark rules."
330 << " Guest connectivity may be broken.";
331 }
332 if (!datapath_->AddForwardEstablishedRule()) {
333 LOG(ERROR) << "Failed to install forwarding rule for established"
334 << " connections.";
335 }
336
Hugo Benichi321f23b2020-09-25 15:42:05 +0900337 // chromium:898210: Drop any locally originated traffic that would exit a
338 // physical interface with a source IPv4 address from the subnet of IPs used
339 // for VMs, containers, and connected namespaces This is needed to prevent
340 // packets leaking with an incorrect src IP when a local process binds to the
341 // wrong interface.
342 for (const auto& oif : kPhysicalIfnamePrefixes) {
343 if (!datapath_->AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
344 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
345 << kGuestIPv4Subnet << " exiting " << oif;
Garrick Evansff6e37f2020-05-25 10:54:47 +0900346 }
347
Garrick Evansc50426b2020-05-25 11:00:55 +0900348 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
349 LOG(ERROR) << "Failed to set up NAT for TAP devices."
350 << " Guest connectivity may be broken.";
351 }
Long Chengd4415582019-09-24 19:16:09 +0000352}
Garrick Evans49879532018-12-03 13:15:36 +0900353
Hugo Benichifda77232020-08-21 18:28:15 +0900354void Manager::StopDatapath() {
355 if (USE_JETSTREAM_ROUTING)
356 return;
Garrick Evans28d194e2019-12-17 10:22:28 +0900357
Garrick Evansc50426b2020-05-25 11:00:55 +0900358 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansd291af62020-05-25 10:39:06 +0900359 datapath_->RemoveForwardEstablishedRule();
360 datapath_->RemoveSNATMarkRules();
Hugo Benichi321f23b2020-09-25 15:42:05 +0900361 for (const auto& oif : kPhysicalIfnamePrefixes)
362 datapath_->RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
Garrick Evansd291af62020-05-25 10:39:06 +0900363
Garrick Evans7cf8c542020-05-25 09:50:17 +0900364 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900365 // Restore original local port range.
366 // TODO(garrick): The original history behind this tweak is gone. Some
367 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900368 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900369 LOG(ERROR) << "Failed to restore local port range";
370 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900371 // Disable packet forwarding
372 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
373 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
374 }
375 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
376 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
377 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800378}
379
Garrick Evanse94a14e2019-11-11 10:32:13 +0900380bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900381 if (!arc_svc_->Start(pid))
382 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900383
384 GuestMessage msg;
385 msg.set_event(GuestMessage::START);
386 msg.set_type(GuestMessage::ARC);
387 msg.set_arc_pid(pid);
388 SendGuestMessage(msg);
389
390 return true;
391}
392
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900393void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900394 GuestMessage msg;
395 msg.set_event(GuestMessage::STOP);
396 msg.set_type(GuestMessage::ARC);
397 SendGuestMessage(msg);
398
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900399 // After the ARC container has stopped, the pid is not known anymore.
400 // The pid argument is ignored by ArcService.
401 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900402}
403
Garrick Evans015b0d62020-02-07 09:06:38 +0900404bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900405 if (!arc_svc_->Start(cid))
406 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900407
408 GuestMessage msg;
409 msg.set_event(GuestMessage::START);
410 msg.set_type(GuestMessage::ARC_VM);
411 msg.set_arcvm_vsock_cid(cid);
412 SendGuestMessage(msg);
413
414 return true;
415}
416
Garrick Evans015b0d62020-02-07 09:06:38 +0900417void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900418 GuestMessage msg;
419 msg.set_event(GuestMessage::STOP);
420 msg.set_type(GuestMessage::ARC_VM);
421 SendGuestMessage(msg);
422
Garrick Evans21173b12019-11-20 15:23:16 +0900423 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900424}
425
Garrick Evans51d5b552020-01-30 10:42:06 +0900426bool Manager::StartCrosVm(uint64_t vm_id,
427 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900428 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900429 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
430 vm_type == GuestMessage::PLUGIN_VM);
431
432 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
433 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900434 return false;
435
436 GuestMessage msg;
437 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900438 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900439 SendGuestMessage(msg);
440
441 return true;
442}
443
Garrick Evans51d5b552020-01-30 10:42:06 +0900444void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900445 GuestMessage msg;
446 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900447 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900448 SendGuestMessage(msg);
449
Garrick Evans51d5b552020-01-30 10:42:06 +0900450 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900451}
452
Garrick Evans08843932019-09-17 14:41:08 +0900453std::unique_ptr<dbus::Response> Manager::OnArcStartup(
454 dbus::MethodCall* method_call) {
455 LOG(INFO) << "ARC++ starting up";
456
457 std::unique_ptr<dbus::Response> dbus_response(
458 dbus::Response::FromMethodCall(method_call));
459
460 dbus::MessageReader reader(method_call);
461 dbus::MessageWriter writer(dbus_response.get());
462
463 patchpanel::ArcStartupRequest request;
464 patchpanel::ArcStartupResponse response;
465
466 if (!reader.PopArrayOfBytesAsProto(&request)) {
467 LOG(ERROR) << "Unable to parse request";
468 writer.AppendProtoAsArrayOfBytes(response);
469 return dbus_response;
470 }
471
Garrick Evanse01bf072019-11-15 09:08:19 +0900472 if (!StartArc(request.pid()))
473 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900474
Garrick Evans08843932019-09-17 14:41:08 +0900475 writer.AppendProtoAsArrayOfBytes(response);
476 return dbus_response;
477}
478
479std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
480 dbus::MethodCall* method_call) {
481 LOG(INFO) << "ARC++ shutting down";
482
483 std::unique_ptr<dbus::Response> dbus_response(
484 dbus::Response::FromMethodCall(method_call));
485
486 dbus::MessageReader reader(method_call);
487 dbus::MessageWriter writer(dbus_response.get());
488
489 patchpanel::ArcShutdownRequest request;
490 patchpanel::ArcShutdownResponse response;
491
492 if (!reader.PopArrayOfBytesAsProto(&request)) {
493 LOG(ERROR) << "Unable to parse request";
494 writer.AppendProtoAsArrayOfBytes(response);
495 return dbus_response;
496 }
497
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900498 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900499
Garrick Evans08843932019-09-17 14:41:08 +0900500 writer.AppendProtoAsArrayOfBytes(response);
501 return dbus_response;
502}
503
504std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
505 dbus::MethodCall* method_call) {
506 LOG(INFO) << "ARCVM starting up";
507
508 std::unique_ptr<dbus::Response> dbus_response(
509 dbus::Response::FromMethodCall(method_call));
510
511 dbus::MessageReader reader(method_call);
512 dbus::MessageWriter writer(dbus_response.get());
513
514 patchpanel::ArcVmStartupRequest request;
515 patchpanel::ArcVmStartupResponse response;
516
517 if (!reader.PopArrayOfBytesAsProto(&request)) {
518 LOG(ERROR) << "Unable to parse request";
519 writer.AppendProtoAsArrayOfBytes(response);
520 return dbus_response;
521 }
522
Garrick Evans47c19272019-11-21 10:58:21 +0900523 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900524 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900525 writer.AppendProtoAsArrayOfBytes(response);
526 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900527 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900528
Garrick Evans47c19272019-11-21 10:58:21 +0900529 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900530 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
531 if (config->tap_ifname().empty())
532 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900533
Garrick Evans38b25a42020-04-06 15:17:42 +0900534 auto* dev = response.add_devices();
535 dev->set_ifname(config->tap_ifname());
536 dev->set_ipv4_addr(config->guest_ipv4_addr());
537 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900538
Garrick Evans08843932019-09-17 14:41:08 +0900539 writer.AppendProtoAsArrayOfBytes(response);
540 return dbus_response;
541}
542
543std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
544 dbus::MethodCall* method_call) {
545 LOG(INFO) << "ARCVM shutting down";
546
547 std::unique_ptr<dbus::Response> dbus_response(
548 dbus::Response::FromMethodCall(method_call));
549
550 dbus::MessageReader reader(method_call);
551 dbus::MessageWriter writer(dbus_response.get());
552
553 patchpanel::ArcVmShutdownRequest request;
554 patchpanel::ArcVmShutdownResponse response;
555
556 if (!reader.PopArrayOfBytesAsProto(&request)) {
557 LOG(ERROR) << "Unable to parse request";
558 writer.AppendProtoAsArrayOfBytes(response);
559 return dbus_response;
560 }
561
Garrick Evans21173b12019-11-20 15:23:16 +0900562 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900563
Garrick Evans08843932019-09-17 14:41:08 +0900564 writer.AppendProtoAsArrayOfBytes(response);
565 return dbus_response;
566}
567
Garrick Evans47c19272019-11-21 10:58:21 +0900568std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
569 dbus::MethodCall* method_call) {
570 LOG(INFO) << "Termina VM starting up";
571
572 std::unique_ptr<dbus::Response> dbus_response(
573 dbus::Response::FromMethodCall(method_call));
574
575 dbus::MessageReader reader(method_call);
576 dbus::MessageWriter writer(dbus_response.get());
577
578 patchpanel::TerminaVmStartupRequest request;
579 patchpanel::TerminaVmStartupResponse response;
580
581 if (!reader.PopArrayOfBytesAsProto(&request)) {
582 LOG(ERROR) << "Unable to parse request";
583 writer.AppendProtoAsArrayOfBytes(response);
584 return dbus_response;
585 }
586
587 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900588 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900589 LOG(ERROR) << "Failed to start Termina VM network service";
590 writer.AppendProtoAsArrayOfBytes(response);
591 return dbus_response;
592 }
593
Garrick Evans51d5b552020-01-30 10:42:06 +0900594 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900595 if (!tap) {
596 LOG(DFATAL) << "TAP device missing";
597 writer.AppendProtoAsArrayOfBytes(response);
598 return dbus_response;
599 }
Garrick Evans47c19272019-11-21 10:58:21 +0900600
Garrick Evansb1c93712020-01-22 09:28:25 +0900601 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900602 dev->set_ifname(tap->host_ifname());
603 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900604 if (!subnet) {
605 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
606 writer.AppendProtoAsArrayOfBytes(response);
607 return dbus_response;
608 }
609 auto* resp_subnet = dev->mutable_ipv4_subnet();
610 resp_subnet->set_base_addr(subnet->BaseAddress());
611 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900612 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900613 if (!subnet) {
614 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
615 writer.AppendProtoAsArrayOfBytes(response);
616 return dbus_response;
617 }
618 resp_subnet = response.mutable_container_subnet();
619 resp_subnet->set_base_addr(subnet->BaseAddress());
620 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900621
622 writer.AppendProtoAsArrayOfBytes(response);
623 return dbus_response;
624}
625
626std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
627 dbus::MethodCall* method_call) {
628 LOG(INFO) << "Termina VM shutting down";
629
630 std::unique_ptr<dbus::Response> dbus_response(
631 dbus::Response::FromMethodCall(method_call));
632
633 dbus::MessageReader reader(method_call);
634 dbus::MessageWriter writer(dbus_response.get());
635
636 patchpanel::TerminaVmShutdownRequest request;
637 patchpanel::TerminaVmShutdownResponse response;
638
639 if (!reader.PopArrayOfBytesAsProto(&request)) {
640 LOG(ERROR) << "Unable to parse request";
641 writer.AppendProtoAsArrayOfBytes(response);
642 return dbus_response;
643 }
644
Garrick Evans51d5b552020-01-30 10:42:06 +0900645 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
646
647 writer.AppendProtoAsArrayOfBytes(response);
648 return dbus_response;
649}
650
651std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
652 dbus::MethodCall* method_call) {
653 LOG(INFO) << "Plugin VM starting up";
654
655 std::unique_ptr<dbus::Response> dbus_response(
656 dbus::Response::FromMethodCall(method_call));
657
658 dbus::MessageReader reader(method_call);
659 dbus::MessageWriter writer(dbus_response.get());
660
661 patchpanel::PluginVmStartupRequest request;
662 patchpanel::PluginVmStartupResponse response;
663
664 if (!reader.PopArrayOfBytesAsProto(&request)) {
665 LOG(ERROR) << "Unable to parse request";
666 writer.AppendProtoAsArrayOfBytes(response);
667 return dbus_response;
668 }
669
Garrick Evans08fb34b2020-02-20 10:50:17 +0900670 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900671 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900672 LOG(ERROR) << "Failed to start Plugin VM network service";
673 writer.AppendProtoAsArrayOfBytes(response);
674 return dbus_response;
675 }
676
677 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
678 if (!tap) {
679 LOG(DFATAL) << "TAP device missing";
680 writer.AppendProtoAsArrayOfBytes(response);
681 return dbus_response;
682 }
683
Garrick Evans51d5b552020-01-30 10:42:06 +0900684 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900685 dev->set_ifname(tap->host_ifname());
686 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900687 if (!subnet) {
688 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
689 writer.AppendProtoAsArrayOfBytes(response);
690 return dbus_response;
691 }
692 auto* resp_subnet = dev->mutable_ipv4_subnet();
693 resp_subnet->set_base_addr(subnet->BaseAddress());
694 resp_subnet->set_prefix_len(subnet->PrefixLength());
695
696 writer.AppendProtoAsArrayOfBytes(response);
697 return dbus_response;
698}
699
700std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
701 dbus::MethodCall* method_call) {
702 LOG(INFO) << "Plugin VM shutting down";
703
704 std::unique_ptr<dbus::Response> dbus_response(
705 dbus::Response::FromMethodCall(method_call));
706
707 dbus::MessageReader reader(method_call);
708 dbus::MessageWriter writer(dbus_response.get());
709
710 patchpanel::PluginVmShutdownRequest request;
711 patchpanel::PluginVmShutdownResponse response;
712
713 if (!reader.PopArrayOfBytesAsProto(&request)) {
714 LOG(ERROR) << "Unable to parse request";
715 writer.AppendProtoAsArrayOfBytes(response);
716 return dbus_response;
717 }
718
719 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900720
721 writer.AppendProtoAsArrayOfBytes(response);
722 return dbus_response;
723}
724
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900725std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
726 dbus::MethodCall* method_call) {
727 std::unique_ptr<dbus::Response> dbus_response(
728 dbus::Response::FromMethodCall(method_call));
729
730 dbus::MessageReader reader(method_call);
731 dbus::MessageWriter writer(dbus_response.get());
732
733 patchpanel::SetVpnIntentRequest request;
734 patchpanel::SetVpnIntentResponse response;
735
736 bool success = reader.PopArrayOfBytesAsProto(&request);
737 if (!success) {
738 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
739 // Do not return yet to make sure we close the received fd.
740 }
741
742 base::ScopedFD client_socket;
743 reader.PopFileDescriptor(&client_socket);
744
745 if (success)
746 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
747
748 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900749
750 writer.AppendProtoAsArrayOfBytes(response);
751 return dbus_response;
752}
753
754std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
755 dbus::MethodCall* method_call) {
756 std::unique_ptr<dbus::Response> dbus_response(
757 dbus::Response::FromMethodCall(method_call));
758
759 dbus::MessageReader reader(method_call);
760 dbus::MessageWriter writer(dbus_response.get());
761
762 patchpanel::ConnectNamespaceRequest request;
763 patchpanel::ConnectNamespaceResponse response;
764
Hugo Benichicc6850f2020-01-17 13:26:06 +0900765 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900766 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900767 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
768 // Do not return yet to make sure we close the received fd and
769 // validate other arguments.
770 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900771 }
772
Hugo Benichicc6850f2020-01-17 13:26:06 +0900773 base::ScopedFD client_fd;
774 reader.PopFileDescriptor(&client_fd);
775 if (!client_fd.is_valid()) {
776 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
777 success = false;
778 }
779
780 pid_t pid = request.pid();
781 {
782 ScopedNS ns(pid);
783 if (!ns.IsValid()) {
784 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
785 success = false;
786 }
787 }
788
789 const std::string& outbound_ifname = request.outbound_physical_device();
790 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
791 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
792 << outbound_ifname;
793 success = false;
794 }
795
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900796 if (success)
797 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900798
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900799 writer.AppendProtoAsArrayOfBytes(response);
800 return dbus_response;
801}
802
Jie Jiang493cde42020-07-17 21:43:39 +0900803std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
804 dbus::MethodCall* method_call) {
805 std::unique_ptr<dbus::Response> dbus_response(
806 dbus::Response::FromMethodCall(method_call));
807
808 dbus::MessageReader reader(method_call);
809 dbus::MessageWriter writer(dbus_response.get());
810
811 patchpanel::TrafficCountersRequest request;
812 patchpanel::TrafficCountersResponse response;
813
814 if (!reader.PopArrayOfBytesAsProto(&request)) {
815 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
816 writer.AppendProtoAsArrayOfBytes(response);
817 return dbus_response;
818 }
819
820 const std::set<std::string> devices{request.devices().begin(),
821 request.devices().end()};
822 const auto counters = counters_svc_->GetCounters(devices);
823 for (const auto& kv : counters) {
824 auto* traffic_counter = response.add_counters();
825 const auto& source_and_device = kv.first;
826 const auto& counter = kv.second;
827 traffic_counter->set_source(source_and_device.first);
828 traffic_counter->set_device(source_and_device.second);
829 traffic_counter->set_rx_bytes(counter.rx_bytes);
830 traffic_counter->set_rx_packets(counter.rx_packets);
831 traffic_counter->set_tx_bytes(counter.tx_bytes);
832 traffic_counter->set_tx_packets(counter.tx_packets);
833 }
834
835 writer.AppendProtoAsArrayOfBytes(response);
836 return dbus_response;
837}
838
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900839std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
840 dbus::MethodCall* method_call) {
841 std::unique_ptr<dbus::Response> dbus_response(
842 dbus::Response::FromMethodCall(method_call));
843
844 dbus::MessageReader reader(method_call);
845 dbus::MessageWriter writer(dbus_response.get());
846
847 patchpanel::ModifyPortRuleRequest request;
848 patchpanel::ModifyPortRuleResponse response;
849
850 if (!reader.PopArrayOfBytesAsProto(&request)) {
851 LOG(ERROR) << "Unable to parse ModifyPortRequest";
852 writer.AppendProtoAsArrayOfBytes(response);
853 return dbus_response;
854 }
855
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900856 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900857 writer.AppendProtoAsArrayOfBytes(response);
858 return dbus_response;
859}
860
Jie Jiang84966852020-09-18 18:49:05 +0900861void Manager::OnNeighborConnectedStateChanged(
862 int ifindex,
863 const shill::IPAddress& ip_addr,
864 NeighborLinkMonitor::NeighborRole role,
865 bool connected) {
866 if (!ip_addr.IsValid()) {
867 LOG(DFATAL) << "ip_addr is not valid";
868 return;
869 }
870
871 using SignalProto = NeighborConnectedStateChangedSignal;
872 SignalProto proto;
873 proto.set_ifindex(ifindex);
874 proto.set_ip_addr(ip_addr.ToString());
875 switch (role) {
876 case NeighborLinkMonitor::NeighborRole::kGateway:
877 proto.set_role(SignalProto::GATEWAY);
878 break;
879 case NeighborLinkMonitor::NeighborRole::kDNSServer:
880 proto.set_role(SignalProto::DNS_SERVER);
881 break;
882 case NeighborLinkMonitor::NeighborRole::kGatewayAndDNSServer:
883 proto.set_role(SignalProto::GATEWAY_AND_DNS_SERVER);
884 break;
885 default:
886 NOTREACHED();
887 }
888
889 dbus::Signal signal(kPatchPanelInterface,
890 kNeighborConnectedStateChangedSignal);
891 dbus::MessageWriter writer(&signal);
892 if (!writer.AppendProtoAsArrayOfBytes(proto)) {
893 LOG(ERROR) << "Failed to encode proto NeighborConnectedStateChangedSignal";
894 return;
895 }
896
897 dbus_svc_path_->SendSignal(&signal);
898}
899
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900900void Manager::ConnectNamespace(
901 base::ScopedFD client_fd,
902 const patchpanel::ConnectNamespaceRequest& request,
903 patchpanel::ConnectNamespaceResponse& response) {
904 std::unique_ptr<Subnet> subnet =
905 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
906 if (!subnet) {
907 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
908 return;
909 }
910
911 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900912 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900913 const std::string host_ifname = "arc_ns" + ifname_id;
914 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900915 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
916 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900917
Hugo Benichie8758b52020-04-03 14:49:01 +0900918 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900919 // - attach a name to the client namespace.
920 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900921 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900922 // - configure IPv4 address on local veth inside host namespace.
923 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900924 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900925 if (!datapath_->NetnsAttachName(netns_name, pid)) {
926 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
927 << netns_name << " to namespace pid " << pid;
928 return;
929 }
930 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900931 addr_mgr_.GenerateMacAddress(),
932 client_ipv4_addr, subnet->PrefixLength(),
933 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900934 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
935 "namespace pid "
936 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900937 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900938 return;
939 }
940 if (!datapath_->ConfigureInterface(
941 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
942 subnet->PrefixLength(), true /* link up */,
943 false /* enable_multicast */)) {
944 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
945 << host_ifname;
946 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900947 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900948 return;
949 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900950 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900951 {
952 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900953 peer_route_setup_success =
954 ns.IsValid() &&
955 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
956 }
957 if (!peer_route_setup_success) {
958 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
959 << host_ifname << " inside namespace pid " << pid;
960 datapath_->RemoveInterface(host_ifname);
961 datapath_->NetnsDeleteName(netns_name);
962 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900963 }
964
965 // Host namespace routing configuration
966 // - ingress: add route to client subnet via |host_ifname|.
967 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
968 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
969 // Note that by default unsolicited ingress traffic is not forwarded to the
970 // client namespace unless the client specifically set port forwarding
971 // through permission_broker DBus APIs.
972 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
973 // both ways between client namespace and other guest containers and VMs.
974 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
975 // routing to that interface routing table.
976 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
977 subnet->Netmask())) {
978 LOG(ERROR)
979 << "ConnectNamespaceRequest: failed to set route to client namespace";
980 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900981 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900982 return;
983 }
984 if (!datapath_->AddOutboundIPv4(host_ifname)) {
985 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
986 "traffic outgoing from "
987 << host_ifname;
988 datapath_->RemoveInterface(host_ifname);
989 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
990 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900991 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900992 return;
993 }
994 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
995 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
996 "outgoing from "
997 << host_ifname;
998 datapath_->RemoveInterface(host_ifname);
999 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
1000 subnet->Netmask());
1001 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +09001002 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +09001003 return;
1004 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001005
Hugo Benichi7352ad92020-04-07 16:11:59 +09001006 // Dup the client fd into our own: this guarantees that the fd number will
1007 // be stable and tied to the actual kernel resources used by the client.
1008 base::ScopedFD local_client_fd(dup(client_fd.get()));
1009 if (!local_client_fd.is_valid()) {
1010 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +09001011 datapath_->RemoveInterface(host_ifname);
1012 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
1013 subnet->Netmask());
1014 datapath_->RemoveOutboundIPv4(host_ifname);
1015 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +09001016 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +09001017 return;
1018 }
1019
1020 // Add the dupe fd to the epoll watcher.
1021 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
1022 // listening to EPOLLHUP.
1023 struct epoll_event epevent;
1024 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
1025 epevent.data.fd = local_client_fd.get();
1026 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
1027 local_client_fd.get(), &epevent) != 0) {
1028 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001029 datapath_->RemoveInterface(host_ifname);
1030 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
1031 subnet->Netmask());
1032 datapath_->RemoveOutboundIPv4(host_ifname);
1033 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +09001034 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +09001035 return;
1036 }
1037
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001038 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +09001039 response.set_peer_ifname(client_ifname);
1040 response.set_peer_ipv4_address(host_ipv4_addr);
1041 response.set_host_ifname(host_ifname);
1042 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001043 auto* response_subnet = response.mutable_ipv4_subnet();
1044 response_subnet->set_base_addr(subnet->BaseAddress());
1045 response_subnet->set_prefix_len(subnet->PrefixLength());
1046
1047 // Store ConnectNamespaceInfo
1048 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001049 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001050 connected_namespaces_[fdkey] = {};
1051 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
1052 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +09001053 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001054 ns_info.outbound_ifname = request.outbound_physical_device();
1055 ns_info.host_ifname = std::move(host_ifname);
1056 ns_info.client_ifname = std::move(client_ifname);
1057 ns_info.client_subnet = std::move(subnet);
1058
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001059 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001060
1061 if (connected_namespaces_.size() == 1) {
1062 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1063 CheckConnectedNamespaces();
1064 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001065}
1066
1067void Manager::DisconnectNamespace(int client_fd) {
1068 auto it = connected_namespaces_.find(client_fd);
1069 if (it == connected_namespaces_.end()) {
1070 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
1071 return;
1072 }
1073
Hugo Benichi7352ad92020-04-07 16:11:59 +09001074 // Remove the client fd dupe from the epoll watcher and close it.
1075 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001076 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001077 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001078 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001079 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001080
Hugo Benichie8758b52020-04-03 14:49:01 +09001081 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001082 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +09001083 // - remove forwarding rules on host namespace.
1084 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +09001085 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +09001086 // Note that the default route set inside the client namespace by patchpanel
1087 // is not destroyed: it is assumed the client will also teardown its
1088 // namespace if it triggered DisconnectNamespace.
1089 datapath_->RemoveInterface(it->second.host_ifname);
1090 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
1091 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
1092 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
1093 it->second.client_subnet->BaseAddress(),
1094 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +09001095 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001096
1097 LOG(INFO) << "Disconnected network namespace " << it->second;
1098
1099 // This release the allocated IPv4 subnet.
1100 connected_namespaces_.erase(it);
1101}
1102
Hugo Benichi7352ad92020-04-07 16:11:59 +09001103// TODO(hugobenichi) Generalize this check to all resources created by
1104// patchpanel on behalf of a remote client.
1105void Manager::CheckConnectedNamespaces() {
1106 int max_event = 10;
1107 struct epoll_event epevents[max_event];
1108 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1109 0 /* do not block */);
1110 if (nready < 0)
1111 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1112
1113 for (int i = 0; i < nready; i++)
1114 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1115 DisconnectNamespace(epevents[i].data.fd);
1116
1117 if (connected_namespaces_.empty()) {
1118 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1119 return;
1120 }
1121
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001122 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001123 FROM_HERE,
1124 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001125 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001126 kConnectNamespaceCheckInterval);
1127}
1128
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001129bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1130 switch (request.proto()) {
1131 case patchpanel::ModifyPortRuleRequest::TCP:
1132 case patchpanel::ModifyPortRuleRequest::UDP:
1133 break;
1134 default:
1135 LOG(ERROR) << "Unknown protocol " << request.proto();
1136 return false;
1137 }
1138
1139 switch (request.op()) {
1140 case patchpanel::ModifyPortRuleRequest::CREATE:
1141 switch (request.type()) {
1142 case patchpanel::ModifyPortRuleRequest::ACCESS:
1143 return firewall_.AddAcceptRules(request.proto(),
1144 request.input_dst_port(),
1145 request.input_ifname());
1146 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1147 return firewall_.AddLoopbackLockdownRules(request.proto(),
1148 request.input_dst_port());
1149 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1150 return firewall_.AddIpv4ForwardRule(
1151 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1152 request.input_ifname(), request.dst_ip(), request.dst_port());
1153 default:
1154 LOG(ERROR) << "Unknown port rule type " << request.type();
1155 return false;
1156 }
1157 case patchpanel::ModifyPortRuleRequest::DELETE:
1158 switch (request.type()) {
1159 case patchpanel::ModifyPortRuleRequest::ACCESS:
1160 return firewall_.DeleteAcceptRules(request.proto(),
1161 request.input_dst_port(),
1162 request.input_ifname());
1163 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1164 return firewall_.DeleteLoopbackLockdownRules(
1165 request.proto(), request.input_dst_port());
1166 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1167 return firewall_.DeleteIpv4ForwardRule(
1168 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1169 request.input_ifname(), request.dst_ip(), request.dst_port());
1170 default:
1171 LOG(ERROR) << "Unknown port rule type " << request.type();
1172 return false;
1173 }
1174 default:
1175 LOG(ERROR) << "Unknown operation " << request.op();
1176 return false;
1177 }
1178}
1179
Garrick Evanse94a14e2019-11-11 10:32:13 +09001180void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001181 IpHelperMessage ipm;
1182 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001183 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001184 mcast_proxy_->SendMessage(ipm);
1185 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001186}
1187
Garrick Evans4ac09852020-01-16 14:09:22 +09001188void Manager::StartForwarding(const std::string& ifname_physical,
1189 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001190 bool ipv6,
1191 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001192 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001193 return;
1194
1195 IpHelperMessage ipm;
1196 DeviceMessage* msg = ipm.mutable_device_message();
1197 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001198 msg->set_br_ifname(ifname_virtual);
1199
1200 if (ipv6) {
1201 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1202 << ifname_virtual;
1203
1204 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1205 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1206 << ifname_physical << " to " << ifname_virtual;
1207 }
1208 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1209 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1210 << ifname_physical;
1211 }
1212 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1213 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1214 << ifname_virtual;
1215 }
1216 nd_proxy_->SendMessage(ipm);
1217 }
1218
1219 if (multicast) {
1220 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1221 << " to " << ifname_virtual;
1222 mcast_proxy_->SendMessage(ipm);
1223 }
1224}
1225
1226void Manager::StopForwarding(const std::string& ifname_physical,
1227 const std::string& ifname_virtual,
1228 bool ipv6,
1229 bool multicast) {
1230 if (ifname_physical.empty())
1231 return;
1232
1233 IpHelperMessage ipm;
1234 DeviceMessage* msg = ipm.mutable_device_message();
1235 msg->set_dev_ifname(ifname_physical);
1236 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001237 if (!ifname_virtual.empty()) {
1238 msg->set_br_ifname(ifname_virtual);
1239 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001240
1241 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001242 if (ifname_virtual.empty()) {
1243 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1244 } else {
1245 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1246 << ifname_virtual;
1247 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1248 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001249 nd_proxy_->SendMessage(ipm);
1250 }
1251
1252 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001253 if (ifname_virtual.empty()) {
1254 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1255 } else {
1256 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1257 << " to " << ifname_virtual;
1258 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001259 mcast_proxy_->SendMessage(ipm);
1260 }
1261}
1262
Taoyu Lia0727dc2020-09-24 19:54:59 +09001263void Manager::OnNDProxyMessage(const NDProxyMessage& msg) {
1264 LOG_IF(DFATAL, msg.ifname().empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001265 << "Received DeviceMessage w/ empty dev_ifname";
Taoyu Lia0727dc2020-09-24 19:54:59 +09001266 switch (msg.type()) {
1267 case NDProxyMessage::ADD_ROUTE:
1268 if (!datapath_->AddIPv6HostRoute(msg.ifname(), msg.ip6addr(), 128)) {
1269 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1270 << msg.ifname() << ", addr " << msg.ip6addr();
1271 }
1272 break;
1273 case NDProxyMessage::ADD_ADDR:
1274 if (!datapath_->AddIPv6Address(msg.ifname(), msg.ip6addr())) {
1275 LOG(WARNING) << "Failed to setup the IPv6 address for interface "
1276 << msg.ifname() << ", addr " << msg.ip6addr();
1277 }
1278 break;
1279 case NDProxyMessage::DEL_ADDR:
1280 datapath_->RemoveIPv6Address(msg.ifname(), msg.ip6addr());
1281 break;
1282 default:
1283 LOG(ERROR) << "Unknown NDProxy event " << msg.type();
1284 NOTREACHED();
Garrick Evans4ac09852020-01-16 14:09:22 +09001285 }
1286}
1287
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001288std::ostream& operator<<(std::ostream& stream,
1289 const Manager::ConnectNamespaceInfo& ns_info) {
1290 stream << "{ pid: " << ns_info.pid;
1291 if (!ns_info.outbound_ifname.empty()) {
1292 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1293 }
1294 stream << ", host_ifname: " << ns_info.host_ifname
1295 << ", client_ifname: " << ns_info.client_ifname
1296 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1297 return stream;
1298}
1299
Garrick Evans3388a032020-03-24 11:25:55 +09001300} // namespace patchpanel