blob: 3013ebe80cfbbde0e02d8c3a84c8f7cab77acb31 [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 Benichi7d9d8db2020-03-30 15:56:56 +090018#include "base/files/scoped_file.h"
Hugo Benichicc6850f2020-01-17 13:26:06 +090019#include <base/bind.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
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090039constexpr char kNDProxyFeatureName[] = "ARC NDProxy";
40constexpr int kNDProxyMinAndroidSdkVersion = 28; // P
41constexpr int kNDProxyMinChromeMilestone = 80;
Taoyu Lic85c44b2019-12-04 17:32:57 +090042
Hugo Benichi7352ad92020-04-07 16:11:59 +090043// Time interval between epoll checks on file descriptors committed by callers
44// of ConnectNamespace DBus API.
45constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090046 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090047
Garrick Evans08843932019-09-17 14:41:08 +090048// Passes |method_call| to |handler| and passes the response to
49// |response_sender|. If |handler| returns nullptr, an empty response is
50// created and sent.
51void HandleSynchronousDBusMethodCall(
52 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
53 dbus::MethodCall* method_call,
54 dbus::ExportedObject::ResponseSender response_sender) {
55 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
56 if (!response)
57 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090058 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090059}
60
61} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070062
Taoyu Lice7caa62019-10-01 15:43:33 +090063Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090064 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090065 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090066 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090067 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090068 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090069 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090070 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090071 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090072}
Long Chengd4415582019-09-24 19:16:09 +000073
Garrick Evans207e7482019-12-16 11:54:36 +090074Manager::~Manager() {
75 OnShutdown(nullptr);
76}
77
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090078std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
79
80bool Manager::ShouldEnableFeature(
81 int min_android_sdk_version,
82 int min_chrome_milestone,
83 const std::vector<std::string>& supported_boards,
84 const std::string& feature_name) {
85 static const char kLsbReleasePath[] = "/etc/lsb-release";
86
87 const auto& cached_result = cached_feature_enabled_.find(feature_name);
88 if (cached_result != cached_feature_enabled_.end())
89 return cached_result->second;
90
91 auto check = [min_android_sdk_version, min_chrome_milestone,
92 &supported_boards, &feature_name]() {
93 brillo::KeyValueStore store;
94 if (!store.Load(base::FilePath(kLsbReleasePath))) {
95 LOG(ERROR) << "Could not read lsb-release";
96 return false;
97 }
98
99 std::string value;
100 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
101 LOG(ERROR) << feature_name
102 << " disabled - cannot determine Android SDK version";
103 return false;
104 }
105 int ver = 0;
106 if (!base::StringToInt(value.c_str(), &ver)) {
107 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
108 return false;
109 }
110 if (ver < min_android_sdk_version) {
111 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
112 return false;
113 }
114
115 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
116 LOG(ERROR) << feature_name
117 << " disabled - cannot determine ChromeOS milestone";
118 return false;
119 }
120 if (!base::StringToInt(value.c_str(), &ver)) {
121 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
122 return false;
123 }
124 if (ver < min_chrome_milestone) {
125 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
126 return false;
127 }
128
129 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
130 LOG(ERROR) << feature_name << " disabled - cannot determine board";
131 return false;
132 }
133 if (!supported_boards.empty() &&
134 std::find(supported_boards.begin(), supported_boards.end(), value) ==
135 supported_boards.end()) {
136 LOG(INFO) << feature_name << " disabled for board " << value;
137 return false;
138 }
139 return true;
140 };
141
142 bool result = check();
143 cached_feature_enabled_.emplace(feature_name, result);
144 return result;
145}
146
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700147int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900148 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800149
150 // Handle subprocess lifecycle.
151 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900152
153 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900154 FROM_HERE, adb_proxy_->pid(),
155 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
156 adb_proxy_->pid())))
157 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900158 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900159 FROM_HERE, mcast_proxy_->pid(),
160 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
161 nd_proxy_->pid())))
162 << "Failed to watch multicast-proxy child process";
163 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900164 FROM_HERE, nd_proxy_->pid(),
165 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
166 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900167 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900168
Garrick Evans49879532018-12-03 13:15:36 +0900169 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900170 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700171 FROM_HERE,
172 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
173
174 return DBusDaemon::OnInit();
175}
176
177void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900178 LOG(INFO) << "Setting up DBus service interface";
179 dbus_svc_path_ = bus_->GetExportedObject(
180 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
181 if (!dbus_svc_path_) {
182 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
183 << " object";
184 }
185
186 using ServiceMethod =
187 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
188 const std::map<const char*, ServiceMethod> kServiceMethods = {
189 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
190 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
191 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
192 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900193 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
194 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900195 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
196 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900197 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900198 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900199 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900200 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900201 };
202
203 for (const auto& kv : kServiceMethods) {
204 if (!dbus_svc_path_->ExportMethodAndBlock(
205 patchpanel::kPatchPanelInterface, kv.first,
206 base::Bind(&HandleSynchronousDBusMethodCall,
207 base::Bind(kv.second, base::Unretained(this))))) {
208 LOG(FATAL) << "Failed to export method " << kv.first;
209 }
210 }
211
212 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
213 dbus::Bus::REQUIRE_PRIMARY)) {
214 LOG(FATAL) << "Failed to take ownership of "
215 << patchpanel::kPatchPanelServiceName;
216 }
217 LOG(INFO) << "DBus service interface ready";
218
Hugo Benichifda77232020-08-21 18:28:15 +0900219 routing_svc_ = std::make_unique<RoutingService>();
220
221 StartDatapath();
222
223 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
224 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
225
226 shill_client_ = std::make_unique<ShillClient>(bus_);
227 auto* const forwarder = static_cast<TrafficForwarder*>(this);
228
229 GuestMessage::GuestType arc_guest =
230 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
231 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
232 &addr_mgr_, forwarder, arc_guest);
233 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
234 datapath_.get(), forwarder);
235 network_monitor_svc_ =
236 std::make_unique<NetworkMonitorService>(shill_client_.get());
237 network_monitor_svc_->Start();
238
239 counters_svc_ =
240 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
241
242 nd_proxy_->Listen();
243}
244
245void Manager::OnShutdown(int* exit_code) {
246 LOG(INFO) << "Shutting down and cleaning up";
247 cros_svc_.reset();
248 arc_svc_.reset();
249 close(connected_namespaces_epollfd_);
250 // Tear down any remaining connected namespace.
251 std::vector<int> connected_namespaces_fdkeys;
252 for (const auto& kv : connected_namespaces_)
253 connected_namespaces_fdkeys.push_back(kv.first);
254 for (const int fdkey : connected_namespaces_fdkeys)
255 DisconnectNamespace(fdkey);
256 StopDatapath();
257}
258
259void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
260 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
261 << " attempting to restart";
262
263 HelperProcess* proc;
264 if (pid == adb_proxy_->pid()) {
265 proc = adb_proxy_.get();
266 } else if (pid == mcast_proxy_->pid()) {
267 proc = mcast_proxy_.get();
268 } else if (pid == nd_proxy_->pid()) {
269 proc = nd_proxy_.get();
270 } else {
271 LOG(DFATAL) << "Unknown child process";
272 return;
273 }
274
275 process_reaper_.ForgetChild(pid);
276
277 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
278 FROM_HERE,
279 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
280 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
281 kSubprocessRestartDelayMs));
282}
283
284void Manager::RestartSubprocess(HelperProcess* subproc) {
285 if (subproc->Restart()) {
286 DCHECK(process_reaper_.WatchForChild(
287 FROM_HERE, subproc->pid(),
288 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
289 subproc->pid())))
290 << "Failed to watch child process " << subproc->pid();
291 }
292}
293
294void Manager::StartDatapath() {
295 // b/162966185: Allow Jetstream to disable:
296 // - the IP forwarding setup used for hosting VMs and containers,
297 // - the iptables rules for fwmark based routing.
298 if (USE_JETSTREAM_ROUTING) {
299 LOG(INFO) << "Skipping Datapath routing setup";
300 return;
301 }
302
Taoyu Li6d479442019-12-09 13:02:29 +0900303 auto& runner = datapath_->runner();
Hugo Benichifda77232020-08-21 18:28:15 +0900304
Garrick Evans7cf8c542020-05-25 09:50:17 +0900305 // Enable IPv4 packet forwarding
306 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
307 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
308 << " Guest connectivity will not work correctly.";
309 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900310 // Limit local port range: Android owns 47104-61000.
311 // TODO(garrick): The original history behind this tweak is gone. Some
312 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900313 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900314 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
315 << " apps may not work correctly.";
316 }
Taoyu Li6d479442019-12-09 13:02:29 +0900317 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900318 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900319 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
320 << " IPv6 functionality may be broken.";
321 }
322 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900323 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900324 kNDProxyMinChromeMilestone, {},
325 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900326 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900327 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
328 << " IPv6 functionality may be broken.";
329 }
330
Garrick Evansd291af62020-05-25 10:39:06 +0900331 if (!datapath_->AddSNATMarkRules()) {
332 LOG(ERROR) << "Failed to install SNAT mark rules."
333 << " Guest connectivity may be broken.";
334 }
335 if (!datapath_->AddForwardEstablishedRule()) {
336 LOG(ERROR) << "Failed to install forwarding rule for established"
337 << " connections.";
338 }
339
Garrick Evansff6e37f2020-05-25 10:54:47 +0900340 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
341 // such that we can better set up the masquerade rules based on connection
342 // type rather than interface names.
343 if (!datapath_->AddInterfaceSNAT("wwan+")) {
344 LOG(ERROR) << "Failed to set up wifi masquerade";
345 }
346
Garrick Evansc50426b2020-05-25 11:00:55 +0900347 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
348 LOG(ERROR) << "Failed to set up NAT for TAP devices."
349 << " Guest connectivity may be broken.";
350 }
Long Chengd4415582019-09-24 19:16:09 +0000351}
Garrick Evans49879532018-12-03 13:15:36 +0900352
Hugo Benichifda77232020-08-21 18:28:15 +0900353void Manager::StopDatapath() {
354 if (USE_JETSTREAM_ROUTING)
355 return;
Garrick Evans28d194e2019-12-17 10:22:28 +0900356
Garrick Evansc50426b2020-05-25 11:00:55 +0900357 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900358 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900359 datapath_->RemoveForwardEstablishedRule();
360 datapath_->RemoveSNATMarkRules();
361
Garrick Evans7cf8c542020-05-25 09:50:17 +0900362 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900363 // Restore original local port range.
364 // TODO(garrick): The original history behind this tweak is gone. Some
365 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900366 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900367 LOG(ERROR) << "Failed to restore local port range";
368 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900369 // Disable packet forwarding
370 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
371 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
372 }
373 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
374 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
375 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800376}
377
Garrick Evanse94a14e2019-11-11 10:32:13 +0900378bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900379 if (!arc_svc_->Start(pid))
380 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900381
382 GuestMessage msg;
383 msg.set_event(GuestMessage::START);
384 msg.set_type(GuestMessage::ARC);
385 msg.set_arc_pid(pid);
386 SendGuestMessage(msg);
387
388 return true;
389}
390
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900391void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900392 GuestMessage msg;
393 msg.set_event(GuestMessage::STOP);
394 msg.set_type(GuestMessage::ARC);
395 SendGuestMessage(msg);
396
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900397 // After the ARC container has stopped, the pid is not known anymore.
398 // The pid argument is ignored by ArcService.
399 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900400}
401
Garrick Evans015b0d62020-02-07 09:06:38 +0900402bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900403 if (!arc_svc_->Start(cid))
404 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900405
406 GuestMessage msg;
407 msg.set_event(GuestMessage::START);
408 msg.set_type(GuestMessage::ARC_VM);
409 msg.set_arcvm_vsock_cid(cid);
410 SendGuestMessage(msg);
411
412 return true;
413}
414
Garrick Evans015b0d62020-02-07 09:06:38 +0900415void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900416 GuestMessage msg;
417 msg.set_event(GuestMessage::STOP);
418 msg.set_type(GuestMessage::ARC_VM);
419 SendGuestMessage(msg);
420
Garrick Evans21173b12019-11-20 15:23:16 +0900421 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900422}
423
Garrick Evans51d5b552020-01-30 10:42:06 +0900424bool Manager::StartCrosVm(uint64_t vm_id,
425 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900426 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900427 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
428 vm_type == GuestMessage::PLUGIN_VM);
429
430 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
431 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900432 return false;
433
434 GuestMessage msg;
435 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900436 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900437 SendGuestMessage(msg);
438
439 return true;
440}
441
Garrick Evans51d5b552020-01-30 10:42:06 +0900442void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900443 GuestMessage msg;
444 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900445 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900446 SendGuestMessage(msg);
447
Garrick Evans51d5b552020-01-30 10:42:06 +0900448 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900449}
450
Garrick Evans08843932019-09-17 14:41:08 +0900451std::unique_ptr<dbus::Response> Manager::OnArcStartup(
452 dbus::MethodCall* method_call) {
453 LOG(INFO) << "ARC++ starting up";
454
455 std::unique_ptr<dbus::Response> dbus_response(
456 dbus::Response::FromMethodCall(method_call));
457
458 dbus::MessageReader reader(method_call);
459 dbus::MessageWriter writer(dbus_response.get());
460
461 patchpanel::ArcStartupRequest request;
462 patchpanel::ArcStartupResponse response;
463
464 if (!reader.PopArrayOfBytesAsProto(&request)) {
465 LOG(ERROR) << "Unable to parse request";
466 writer.AppendProtoAsArrayOfBytes(response);
467 return dbus_response;
468 }
469
Garrick Evanse01bf072019-11-15 09:08:19 +0900470 if (!StartArc(request.pid()))
471 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900472
Garrick Evans08843932019-09-17 14:41:08 +0900473 writer.AppendProtoAsArrayOfBytes(response);
474 return dbus_response;
475}
476
477std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
478 dbus::MethodCall* method_call) {
479 LOG(INFO) << "ARC++ shutting down";
480
481 std::unique_ptr<dbus::Response> dbus_response(
482 dbus::Response::FromMethodCall(method_call));
483
484 dbus::MessageReader reader(method_call);
485 dbus::MessageWriter writer(dbus_response.get());
486
487 patchpanel::ArcShutdownRequest request;
488 patchpanel::ArcShutdownResponse response;
489
490 if (!reader.PopArrayOfBytesAsProto(&request)) {
491 LOG(ERROR) << "Unable to parse request";
492 writer.AppendProtoAsArrayOfBytes(response);
493 return dbus_response;
494 }
495
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900496 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900497
Garrick Evans08843932019-09-17 14:41:08 +0900498 writer.AppendProtoAsArrayOfBytes(response);
499 return dbus_response;
500}
501
502std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
503 dbus::MethodCall* method_call) {
504 LOG(INFO) << "ARCVM starting up";
505
506 std::unique_ptr<dbus::Response> dbus_response(
507 dbus::Response::FromMethodCall(method_call));
508
509 dbus::MessageReader reader(method_call);
510 dbus::MessageWriter writer(dbus_response.get());
511
512 patchpanel::ArcVmStartupRequest request;
513 patchpanel::ArcVmStartupResponse response;
514
515 if (!reader.PopArrayOfBytesAsProto(&request)) {
516 LOG(ERROR) << "Unable to parse request";
517 writer.AppendProtoAsArrayOfBytes(response);
518 return dbus_response;
519 }
520
Garrick Evans47c19272019-11-21 10:58:21 +0900521 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900522 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900523 writer.AppendProtoAsArrayOfBytes(response);
524 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900525 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900526
Garrick Evans47c19272019-11-21 10:58:21 +0900527 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900528 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
529 if (config->tap_ifname().empty())
530 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900531
Garrick Evans38b25a42020-04-06 15:17:42 +0900532 auto* dev = response.add_devices();
533 dev->set_ifname(config->tap_ifname());
534 dev->set_ipv4_addr(config->guest_ipv4_addr());
535 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900536
Garrick Evans08843932019-09-17 14:41:08 +0900537 writer.AppendProtoAsArrayOfBytes(response);
538 return dbus_response;
539}
540
541std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
542 dbus::MethodCall* method_call) {
543 LOG(INFO) << "ARCVM shutting down";
544
545 std::unique_ptr<dbus::Response> dbus_response(
546 dbus::Response::FromMethodCall(method_call));
547
548 dbus::MessageReader reader(method_call);
549 dbus::MessageWriter writer(dbus_response.get());
550
551 patchpanel::ArcVmShutdownRequest request;
552 patchpanel::ArcVmShutdownResponse response;
553
554 if (!reader.PopArrayOfBytesAsProto(&request)) {
555 LOG(ERROR) << "Unable to parse request";
556 writer.AppendProtoAsArrayOfBytes(response);
557 return dbus_response;
558 }
559
Garrick Evans21173b12019-11-20 15:23:16 +0900560 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900561
Garrick Evans08843932019-09-17 14:41:08 +0900562 writer.AppendProtoAsArrayOfBytes(response);
563 return dbus_response;
564}
565
Garrick Evans47c19272019-11-21 10:58:21 +0900566std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
567 dbus::MethodCall* method_call) {
568 LOG(INFO) << "Termina VM starting up";
569
570 std::unique_ptr<dbus::Response> dbus_response(
571 dbus::Response::FromMethodCall(method_call));
572
573 dbus::MessageReader reader(method_call);
574 dbus::MessageWriter writer(dbus_response.get());
575
576 patchpanel::TerminaVmStartupRequest request;
577 patchpanel::TerminaVmStartupResponse response;
578
579 if (!reader.PopArrayOfBytesAsProto(&request)) {
580 LOG(ERROR) << "Unable to parse request";
581 writer.AppendProtoAsArrayOfBytes(response);
582 return dbus_response;
583 }
584
585 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900586 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900587 LOG(ERROR) << "Failed to start Termina VM network service";
588 writer.AppendProtoAsArrayOfBytes(response);
589 return dbus_response;
590 }
591
Garrick Evans51d5b552020-01-30 10:42:06 +0900592 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900593 if (!tap) {
594 LOG(DFATAL) << "TAP device missing";
595 writer.AppendProtoAsArrayOfBytes(response);
596 return dbus_response;
597 }
Garrick Evans47c19272019-11-21 10:58:21 +0900598
Garrick Evansb1c93712020-01-22 09:28:25 +0900599 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900600 dev->set_ifname(tap->host_ifname());
601 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900602 if (!subnet) {
603 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
604 writer.AppendProtoAsArrayOfBytes(response);
605 return dbus_response;
606 }
607 auto* resp_subnet = dev->mutable_ipv4_subnet();
608 resp_subnet->set_base_addr(subnet->BaseAddress());
609 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900610 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900611 if (!subnet) {
612 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
613 writer.AppendProtoAsArrayOfBytes(response);
614 return dbus_response;
615 }
616 resp_subnet = response.mutable_container_subnet();
617 resp_subnet->set_base_addr(subnet->BaseAddress());
618 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900619
620 writer.AppendProtoAsArrayOfBytes(response);
621 return dbus_response;
622}
623
624std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
625 dbus::MethodCall* method_call) {
626 LOG(INFO) << "Termina VM shutting down";
627
628 std::unique_ptr<dbus::Response> dbus_response(
629 dbus::Response::FromMethodCall(method_call));
630
631 dbus::MessageReader reader(method_call);
632 dbus::MessageWriter writer(dbus_response.get());
633
634 patchpanel::TerminaVmShutdownRequest request;
635 patchpanel::TerminaVmShutdownResponse response;
636
637 if (!reader.PopArrayOfBytesAsProto(&request)) {
638 LOG(ERROR) << "Unable to parse request";
639 writer.AppendProtoAsArrayOfBytes(response);
640 return dbus_response;
641 }
642
Garrick Evans51d5b552020-01-30 10:42:06 +0900643 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
644
645 writer.AppendProtoAsArrayOfBytes(response);
646 return dbus_response;
647}
648
649std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
650 dbus::MethodCall* method_call) {
651 LOG(INFO) << "Plugin VM starting up";
652
653 std::unique_ptr<dbus::Response> dbus_response(
654 dbus::Response::FromMethodCall(method_call));
655
656 dbus::MessageReader reader(method_call);
657 dbus::MessageWriter writer(dbus_response.get());
658
659 patchpanel::PluginVmStartupRequest request;
660 patchpanel::PluginVmStartupResponse response;
661
662 if (!reader.PopArrayOfBytesAsProto(&request)) {
663 LOG(ERROR) << "Unable to parse request";
664 writer.AppendProtoAsArrayOfBytes(response);
665 return dbus_response;
666 }
667
Garrick Evans08fb34b2020-02-20 10:50:17 +0900668 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900669 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900670 LOG(ERROR) << "Failed to start Plugin VM network service";
671 writer.AppendProtoAsArrayOfBytes(response);
672 return dbus_response;
673 }
674
675 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
676 if (!tap) {
677 LOG(DFATAL) << "TAP device missing";
678 writer.AppendProtoAsArrayOfBytes(response);
679 return dbus_response;
680 }
681
Garrick Evans51d5b552020-01-30 10:42:06 +0900682 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900683 dev->set_ifname(tap->host_ifname());
684 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900685 if (!subnet) {
686 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
687 writer.AppendProtoAsArrayOfBytes(response);
688 return dbus_response;
689 }
690 auto* resp_subnet = dev->mutable_ipv4_subnet();
691 resp_subnet->set_base_addr(subnet->BaseAddress());
692 resp_subnet->set_prefix_len(subnet->PrefixLength());
693
694 writer.AppendProtoAsArrayOfBytes(response);
695 return dbus_response;
696}
697
698std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
699 dbus::MethodCall* method_call) {
700 LOG(INFO) << "Plugin VM shutting down";
701
702 std::unique_ptr<dbus::Response> dbus_response(
703 dbus::Response::FromMethodCall(method_call));
704
705 dbus::MessageReader reader(method_call);
706 dbus::MessageWriter writer(dbus_response.get());
707
708 patchpanel::PluginVmShutdownRequest request;
709 patchpanel::PluginVmShutdownResponse response;
710
711 if (!reader.PopArrayOfBytesAsProto(&request)) {
712 LOG(ERROR) << "Unable to parse request";
713 writer.AppendProtoAsArrayOfBytes(response);
714 return dbus_response;
715 }
716
717 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900718
719 writer.AppendProtoAsArrayOfBytes(response);
720 return dbus_response;
721}
722
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900723std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
724 dbus::MethodCall* method_call) {
725 std::unique_ptr<dbus::Response> dbus_response(
726 dbus::Response::FromMethodCall(method_call));
727
728 dbus::MessageReader reader(method_call);
729 dbus::MessageWriter writer(dbus_response.get());
730
731 patchpanel::SetVpnIntentRequest request;
732 patchpanel::SetVpnIntentResponse response;
733
734 bool success = reader.PopArrayOfBytesAsProto(&request);
735 if (!success) {
736 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
737 // Do not return yet to make sure we close the received fd.
738 }
739
740 base::ScopedFD client_socket;
741 reader.PopFileDescriptor(&client_socket);
742
743 if (success)
744 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
745
746 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900747
748 writer.AppendProtoAsArrayOfBytes(response);
749 return dbus_response;
750}
751
752std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
753 dbus::MethodCall* method_call) {
754 std::unique_ptr<dbus::Response> dbus_response(
755 dbus::Response::FromMethodCall(method_call));
756
757 dbus::MessageReader reader(method_call);
758 dbus::MessageWriter writer(dbus_response.get());
759
760 patchpanel::ConnectNamespaceRequest request;
761 patchpanel::ConnectNamespaceResponse response;
762
Hugo Benichicc6850f2020-01-17 13:26:06 +0900763 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900764 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900765 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
766 // Do not return yet to make sure we close the received fd and
767 // validate other arguments.
768 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900769 }
770
Hugo Benichicc6850f2020-01-17 13:26:06 +0900771 base::ScopedFD client_fd;
772 reader.PopFileDescriptor(&client_fd);
773 if (!client_fd.is_valid()) {
774 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
775 success = false;
776 }
777
778 pid_t pid = request.pid();
779 {
780 ScopedNS ns(pid);
781 if (!ns.IsValid()) {
782 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
783 success = false;
784 }
785 }
786
787 const std::string& outbound_ifname = request.outbound_physical_device();
788 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
789 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
790 << outbound_ifname;
791 success = false;
792 }
793
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900794 if (success)
795 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900796
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900797 writer.AppendProtoAsArrayOfBytes(response);
798 return dbus_response;
799}
800
Jie Jiang493cde42020-07-17 21:43:39 +0900801std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
802 dbus::MethodCall* method_call) {
803 std::unique_ptr<dbus::Response> dbus_response(
804 dbus::Response::FromMethodCall(method_call));
805
806 dbus::MessageReader reader(method_call);
807 dbus::MessageWriter writer(dbus_response.get());
808
809 patchpanel::TrafficCountersRequest request;
810 patchpanel::TrafficCountersResponse response;
811
812 if (!reader.PopArrayOfBytesAsProto(&request)) {
813 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
814 writer.AppendProtoAsArrayOfBytes(response);
815 return dbus_response;
816 }
817
818 const std::set<std::string> devices{request.devices().begin(),
819 request.devices().end()};
820 const auto counters = counters_svc_->GetCounters(devices);
821 for (const auto& kv : counters) {
822 auto* traffic_counter = response.add_counters();
823 const auto& source_and_device = kv.first;
824 const auto& counter = kv.second;
825 traffic_counter->set_source(source_and_device.first);
826 traffic_counter->set_device(source_and_device.second);
827 traffic_counter->set_rx_bytes(counter.rx_bytes);
828 traffic_counter->set_rx_packets(counter.rx_packets);
829 traffic_counter->set_tx_bytes(counter.tx_bytes);
830 traffic_counter->set_tx_packets(counter.tx_packets);
831 }
832
833 writer.AppendProtoAsArrayOfBytes(response);
834 return dbus_response;
835}
836
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900837std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
838 dbus::MethodCall* method_call) {
839 std::unique_ptr<dbus::Response> dbus_response(
840 dbus::Response::FromMethodCall(method_call));
841
842 dbus::MessageReader reader(method_call);
843 dbus::MessageWriter writer(dbus_response.get());
844
845 patchpanel::ModifyPortRuleRequest request;
846 patchpanel::ModifyPortRuleResponse response;
847
848 if (!reader.PopArrayOfBytesAsProto(&request)) {
849 LOG(ERROR) << "Unable to parse ModifyPortRequest";
850 writer.AppendProtoAsArrayOfBytes(response);
851 return dbus_response;
852 }
853
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900854 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900855 writer.AppendProtoAsArrayOfBytes(response);
856 return dbus_response;
857}
858
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900859void Manager::ConnectNamespace(
860 base::ScopedFD client_fd,
861 const patchpanel::ConnectNamespaceRequest& request,
862 patchpanel::ConnectNamespaceResponse& response) {
863 std::unique_ptr<Subnet> subnet =
864 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
865 if (!subnet) {
866 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
867 return;
868 }
869
870 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900871 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900872 const std::string host_ifname = "arc_ns" + ifname_id;
873 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900874 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
875 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900876
Hugo Benichie8758b52020-04-03 14:49:01 +0900877 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900878 // - attach a name to the client namespace.
879 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900880 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900881 // - configure IPv4 address on local veth inside host namespace.
882 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900883 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900884 if (!datapath_->NetnsAttachName(netns_name, pid)) {
885 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
886 << netns_name << " to namespace pid " << pid;
887 return;
888 }
889 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900890 addr_mgr_.GenerateMacAddress(),
891 client_ipv4_addr, subnet->PrefixLength(),
892 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900893 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
894 "namespace pid "
895 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900896 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900897 return;
898 }
899 if (!datapath_->ConfigureInterface(
900 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
901 subnet->PrefixLength(), true /* link up */,
902 false /* enable_multicast */)) {
903 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
904 << host_ifname;
905 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900906 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900907 return;
908 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900909 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900910 {
911 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900912 peer_route_setup_success =
913 ns.IsValid() &&
914 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
915 }
916 if (!peer_route_setup_success) {
917 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
918 << host_ifname << " inside namespace pid " << pid;
919 datapath_->RemoveInterface(host_ifname);
920 datapath_->NetnsDeleteName(netns_name);
921 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900922 }
923
924 // Host namespace routing configuration
925 // - ingress: add route to client subnet via |host_ifname|.
926 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
927 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
928 // Note that by default unsolicited ingress traffic is not forwarded to the
929 // client namespace unless the client specifically set port forwarding
930 // through permission_broker DBus APIs.
931 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
932 // both ways between client namespace and other guest containers and VMs.
933 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
934 // routing to that interface routing table.
935 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
936 subnet->Netmask())) {
937 LOG(ERROR)
938 << "ConnectNamespaceRequest: failed to set route to client namespace";
939 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900940 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900941 return;
942 }
943 if (!datapath_->AddOutboundIPv4(host_ifname)) {
944 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
945 "traffic outgoing from "
946 << host_ifname;
947 datapath_->RemoveInterface(host_ifname);
948 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
949 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900950 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900951 return;
952 }
953 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
954 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
955 "outgoing from "
956 << host_ifname;
957 datapath_->RemoveInterface(host_ifname);
958 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
959 subnet->Netmask());
960 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900961 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900962 return;
963 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900964
Hugo Benichi7352ad92020-04-07 16:11:59 +0900965 // Dup the client fd into our own: this guarantees that the fd number will
966 // be stable and tied to the actual kernel resources used by the client.
967 base::ScopedFD local_client_fd(dup(client_fd.get()));
968 if (!local_client_fd.is_valid()) {
969 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900970 datapath_->RemoveInterface(host_ifname);
971 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
972 subnet->Netmask());
973 datapath_->RemoveOutboundIPv4(host_ifname);
974 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900975 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900976 return;
977 }
978
979 // Add the dupe fd to the epoll watcher.
980 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
981 // listening to EPOLLHUP.
982 struct epoll_event epevent;
983 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
984 epevent.data.fd = local_client_fd.get();
985 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
986 local_client_fd.get(), &epevent) != 0) {
987 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900988 datapath_->RemoveInterface(host_ifname);
989 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
990 subnet->Netmask());
991 datapath_->RemoveOutboundIPv4(host_ifname);
992 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900993 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900994 return;
995 }
996
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900997 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900998 response.set_peer_ifname(client_ifname);
999 response.set_peer_ipv4_address(host_ipv4_addr);
1000 response.set_host_ifname(host_ifname);
1001 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001002 auto* response_subnet = response.mutable_ipv4_subnet();
1003 response_subnet->set_base_addr(subnet->BaseAddress());
1004 response_subnet->set_prefix_len(subnet->PrefixLength());
1005
1006 // Store ConnectNamespaceInfo
1007 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001008 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001009 connected_namespaces_[fdkey] = {};
1010 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
1011 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +09001012 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001013 ns_info.outbound_ifname = request.outbound_physical_device();
1014 ns_info.host_ifname = std::move(host_ifname);
1015 ns_info.client_ifname = std::move(client_ifname);
1016 ns_info.client_subnet = std::move(subnet);
1017
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001018 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001019
1020 if (connected_namespaces_.size() == 1) {
1021 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1022 CheckConnectedNamespaces();
1023 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001024}
1025
1026void Manager::DisconnectNamespace(int client_fd) {
1027 auto it = connected_namespaces_.find(client_fd);
1028 if (it == connected_namespaces_.end()) {
1029 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
1030 return;
1031 }
1032
Hugo Benichi7352ad92020-04-07 16:11:59 +09001033 // Remove the client fd dupe from the epoll watcher and close it.
1034 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001035 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001036 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001037 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001038 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001039
Hugo Benichie8758b52020-04-03 14:49:01 +09001040 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001041 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +09001042 // - remove forwarding rules on host namespace.
1043 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +09001044 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +09001045 // Note that the default route set inside the client namespace by patchpanel
1046 // is not destroyed: it is assumed the client will also teardown its
1047 // namespace if it triggered DisconnectNamespace.
1048 datapath_->RemoveInterface(it->second.host_ifname);
1049 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
1050 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
1051 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
1052 it->second.client_subnet->BaseAddress(),
1053 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +09001054 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001055
1056 LOG(INFO) << "Disconnected network namespace " << it->second;
1057
1058 // This release the allocated IPv4 subnet.
1059 connected_namespaces_.erase(it);
1060}
1061
Hugo Benichi7352ad92020-04-07 16:11:59 +09001062// TODO(hugobenichi) Generalize this check to all resources created by
1063// patchpanel on behalf of a remote client.
1064void Manager::CheckConnectedNamespaces() {
1065 int max_event = 10;
1066 struct epoll_event epevents[max_event];
1067 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1068 0 /* do not block */);
1069 if (nready < 0)
1070 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1071
1072 for (int i = 0; i < nready; i++)
1073 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1074 DisconnectNamespace(epevents[i].data.fd);
1075
1076 if (connected_namespaces_.empty()) {
1077 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1078 return;
1079 }
1080
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001081 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001082 FROM_HERE,
1083 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001084 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001085 kConnectNamespaceCheckInterval);
1086}
1087
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001088bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1089 switch (request.proto()) {
1090 case patchpanel::ModifyPortRuleRequest::TCP:
1091 case patchpanel::ModifyPortRuleRequest::UDP:
1092 break;
1093 default:
1094 LOG(ERROR) << "Unknown protocol " << request.proto();
1095 return false;
1096 }
1097
1098 switch (request.op()) {
1099 case patchpanel::ModifyPortRuleRequest::CREATE:
1100 switch (request.type()) {
1101 case patchpanel::ModifyPortRuleRequest::ACCESS:
1102 return firewall_.AddAcceptRules(request.proto(),
1103 request.input_dst_port(),
1104 request.input_ifname());
1105 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1106 return firewall_.AddLoopbackLockdownRules(request.proto(),
1107 request.input_dst_port());
1108 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1109 return firewall_.AddIpv4ForwardRule(
1110 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1111 request.input_ifname(), request.dst_ip(), request.dst_port());
1112 default:
1113 LOG(ERROR) << "Unknown port rule type " << request.type();
1114 return false;
1115 }
1116 case patchpanel::ModifyPortRuleRequest::DELETE:
1117 switch (request.type()) {
1118 case patchpanel::ModifyPortRuleRequest::ACCESS:
1119 return firewall_.DeleteAcceptRules(request.proto(),
1120 request.input_dst_port(),
1121 request.input_ifname());
1122 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1123 return firewall_.DeleteLoopbackLockdownRules(
1124 request.proto(), request.input_dst_port());
1125 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1126 return firewall_.DeleteIpv4ForwardRule(
1127 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1128 request.input_ifname(), request.dst_ip(), request.dst_port());
1129 default:
1130 LOG(ERROR) << "Unknown port rule type " << request.type();
1131 return false;
1132 }
1133 default:
1134 LOG(ERROR) << "Unknown operation " << request.op();
1135 return false;
1136 }
1137}
1138
Garrick Evanse94a14e2019-11-11 10:32:13 +09001139void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001140 IpHelperMessage ipm;
1141 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001142 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001143 mcast_proxy_->SendMessage(ipm);
1144 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001145}
1146
Garrick Evans4ac09852020-01-16 14:09:22 +09001147void Manager::StartForwarding(const std::string& ifname_physical,
1148 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001149 bool ipv6,
1150 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001151 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001152 return;
1153
1154 IpHelperMessage ipm;
1155 DeviceMessage* msg = ipm.mutable_device_message();
1156 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001157 msg->set_br_ifname(ifname_virtual);
1158
1159 if (ipv6) {
1160 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1161 << ifname_virtual;
1162
1163 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1164 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1165 << ifname_physical << " to " << ifname_virtual;
1166 }
1167 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1168 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1169 << ifname_physical;
1170 }
1171 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1172 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1173 << ifname_virtual;
1174 }
1175 nd_proxy_->SendMessage(ipm);
1176 }
1177
1178 if (multicast) {
1179 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1180 << " to " << ifname_virtual;
1181 mcast_proxy_->SendMessage(ipm);
1182 }
1183}
1184
1185void Manager::StopForwarding(const std::string& ifname_physical,
1186 const std::string& ifname_virtual,
1187 bool ipv6,
1188 bool multicast) {
1189 if (ifname_physical.empty())
1190 return;
1191
1192 IpHelperMessage ipm;
1193 DeviceMessage* msg = ipm.mutable_device_message();
1194 msg->set_dev_ifname(ifname_physical);
1195 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001196 if (!ifname_virtual.empty()) {
1197 msg->set_br_ifname(ifname_virtual);
1198 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001199
1200 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001201 if (ifname_virtual.empty()) {
1202 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1203 } else {
1204 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1205 << ifname_virtual;
1206 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1207 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001208 nd_proxy_->SendMessage(ipm);
1209 }
1210
1211 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001212 if (ifname_virtual.empty()) {
1213 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1214 } else {
1215 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1216 << " to " << ifname_virtual;
1217 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001218 mcast_proxy_->SendMessage(ipm);
1219 }
1220}
1221
Garrick Evans4ac09852020-01-16 14:09:22 +09001222void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1223 LOG_IF(DFATAL, msg.dev_ifname().empty())
1224 << "Received DeviceMessage w/ empty dev_ifname";
1225
1226 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1227 128)) {
1228 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1229 << msg.dev_ifname();
1230 }
1231}
1232
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001233std::ostream& operator<<(std::ostream& stream,
1234 const Manager::ConnectNamespaceInfo& ns_info) {
1235 stream << "{ pid: " << ns_info.pid;
1236 if (!ns_info.outbound_ifname.empty()) {
1237 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1238 }
1239 stream << ", host_ifname: " << ns_info.host_ifname
1240 << ", client_ifname: " << ns_info.client_ifname
1241 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1242 return stream;
1243}
1244
Garrick Evans3388a032020-03-24 11:25:55 +09001245} // namespace patchpanel