blob: dc6f6bab6860e139912bcc73043b17c877fa0573 [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);
58 response_sender.Run(std::move(response));
59}
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>();
70 datapath_ = std::make_unique<Datapath>(runner_.get());
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
Taoyu Li6d479442019-12-09 13:02:29 +0900219 auto& runner = datapath_->runner();
Garrick Evans7cf8c542020-05-25 09:50:17 +0900220 // Enable IPv4 packet forwarding
221 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
222 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
223 << " Guest connectivity will not work correctly.";
224 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900225 // Limit local port range: Android owns 47104-61000.
226 // TODO(garrick): The original history behind this tweak is gone. Some
227 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900228 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900229 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
230 << " apps may not work correctly.";
231 }
Taoyu Li6d479442019-12-09 13:02:29 +0900232 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900233 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900234 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
235 << " IPv6 functionality may be broken.";
236 }
237 // Kernel proxy_ndp is only needed for legacy IPv6 configuration
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +0900238 if (!ShouldEnableFeature(kNDProxyMinAndroidSdkVersion,
Garrick Evansf5862122020-03-16 09:13:45 +0900239 kNDProxyMinChromeMilestone, {},
240 kNDProxyFeatureName) &&
Garrick Evans8e8e3472020-01-23 14:03:50 +0900241 runner.sysctl_w("net.ipv6.conf.all.proxy_ndp", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900242 LOG(ERROR) << "Failed to update net.ipv6.conf.all.proxy_ndp."
243 << " IPv6 functionality may be broken.";
244 }
245
Garrick Evansd291af62020-05-25 10:39:06 +0900246 if (!datapath_->AddSNATMarkRules()) {
247 LOG(ERROR) << "Failed to install SNAT mark rules."
248 << " Guest connectivity may be broken.";
249 }
250 if (!datapath_->AddForwardEstablishedRule()) {
251 LOG(ERROR) << "Failed to install forwarding rule for established"
252 << " connections.";
253 }
254
Garrick Evansff6e37f2020-05-25 10:54:47 +0900255 // TODO(chromium:898210): Move interface-specific masquerading setup to shill;
256 // such that we can better set up the masquerade rules based on connection
257 // type rather than interface names.
258 if (!datapath_->AddInterfaceSNAT("wwan+")) {
259 LOG(ERROR) << "Failed to set up wifi masquerade";
260 }
261
Garrick Evansc50426b2020-05-25 11:00:55 +0900262 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
263 LOG(ERROR) << "Failed to set up NAT for TAP devices."
264 << " Guest connectivity may be broken.";
265 }
266
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900267 routing_svc_ = std::make_unique<RoutingService>();
268
Garrick Evans4ac09852020-01-16 14:09:22 +0900269 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
270 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
271
Garrick Evans69b85872020-02-04 11:40:26 +0900272 shill_client_ = std::make_unique<ShillClient>(bus_);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900273 auto* const forwarder = static_cast<TrafficForwarder*>(this);
Garrick Evans5d55f5e2019-07-17 15:28:10 +0900274
Hugo Benichiad1bdd92020-06-12 13:48:37 +0900275 GuestMessage::GuestType arc_guest =
276 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
277 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
278 &addr_mgr_, forwarder, arc_guest);
Garrick Evans1b1f67c2020-02-04 16:21:25 +0900279 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
280 datapath_.get(), forwarder);
Jie Jiang01c1a2e2020-04-08 20:58:30 +0900281 network_monitor_svc_ =
282 std::make_unique<NetworkMonitorService>(shill_client_.get());
283 network_monitor_svc_->Start();
Taoyu Liaf944c92019-10-01 12:22:31 +0900284
Jie Jiang493cde42020-07-17 21:43:39 +0900285 counters_svc_ =
286 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
287
Taoyu Liaf944c92019-10-01 12:22:31 +0900288 nd_proxy_->Listen();
Long Chengd4415582019-09-24 19:16:09 +0000289}
Garrick Evans49879532018-12-03 13:15:36 +0900290
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800291void Manager::OnShutdown(int* exit_code) {
Garrick Evans664a82f2019-12-17 12:18:05 +0900292 LOG(INFO) << "Shutting down and cleaning up";
Garrick Evans207e7482019-12-16 11:54:36 +0900293 cros_svc_.reset();
294 arc_svc_.reset();
Hugo Benichi7352ad92020-04-07 16:11:59 +0900295 close(connected_namespaces_epollfd_);
Hugo Benichie8758b52020-04-03 14:49:01 +0900296 // Tear down any remaining connected namespace.
297 std::vector<int> connected_namespaces_fdkeys;
298 for (const auto& kv : connected_namespaces_)
299 connected_namespaces_fdkeys.push_back(kv.first);
300 for (const int fdkey : connected_namespaces_fdkeys)
301 DisconnectNamespace(fdkey);
Garrick Evans28d194e2019-12-17 10:22:28 +0900302
Garrick Evansc50426b2020-05-25 11:00:55 +0900303 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansff6e37f2020-05-25 10:54:47 +0900304 datapath_->RemoveInterfaceSNAT("wwan+");
Garrick Evansd291af62020-05-25 10:39:06 +0900305 datapath_->RemoveForwardEstablishedRule();
306 datapath_->RemoveSNATMarkRules();
307
Garrick Evans7cf8c542020-05-25 09:50:17 +0900308 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900309 // Restore original local port range.
310 // TODO(garrick): The original history behind this tweak is gone. Some
311 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900312 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900313 LOG(ERROR) << "Failed to restore local port range";
314 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900315 // Disable packet forwarding
316 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
317 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
318 }
319 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
320 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
321 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800322}
323
Garrick Evans4c042572019-12-17 13:42:25 +0900324void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
325 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
326 << " attempting to restart";
327
328 HelperProcess* proc;
329 if (pid == adb_proxy_->pid()) {
330 proc = adb_proxy_.get();
331 } else if (pid == mcast_proxy_->pid()) {
332 proc = mcast_proxy_.get();
333 } else if (pid == nd_proxy_->pid()) {
334 proc = nd_proxy_.get();
335 } else {
336 LOG(DFATAL) << "Unknown child process";
337 return;
338 }
339
340 process_reaper_.ForgetChild(pid);
341
hschamf9546312020-04-14 15:12:40 +0900342 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Garrick Evans4c042572019-12-17 13:42:25 +0900343 FROM_HERE,
344 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
345 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
346 kSubprocessRestartDelayMs));
347}
348
349void Manager::RestartSubprocess(HelperProcess* subproc) {
350 if (subproc->Restart()) {
351 DCHECK(process_reaper_.WatchForChild(
352 FROM_HERE, subproc->pid(),
353 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
354 subproc->pid())))
355 << "Failed to watch child process " << subproc->pid();
356 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800357}
358
Garrick Evanse94a14e2019-11-11 10:32:13 +0900359bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900360 if (!arc_svc_->Start(pid))
361 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900362
363 GuestMessage msg;
364 msg.set_event(GuestMessage::START);
365 msg.set_type(GuestMessage::ARC);
366 msg.set_arc_pid(pid);
367 SendGuestMessage(msg);
368
369 return true;
370}
371
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900372void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900373 GuestMessage msg;
374 msg.set_event(GuestMessage::STOP);
375 msg.set_type(GuestMessage::ARC);
376 SendGuestMessage(msg);
377
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900378 // After the ARC container has stopped, the pid is not known anymore.
379 // The pid argument is ignored by ArcService.
380 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900381}
382
Garrick Evans015b0d62020-02-07 09:06:38 +0900383bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900384 if (!arc_svc_->Start(cid))
385 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900386
387 GuestMessage msg;
388 msg.set_event(GuestMessage::START);
389 msg.set_type(GuestMessage::ARC_VM);
390 msg.set_arcvm_vsock_cid(cid);
391 SendGuestMessage(msg);
392
393 return true;
394}
395
Garrick Evans015b0d62020-02-07 09:06:38 +0900396void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900397 GuestMessage msg;
398 msg.set_event(GuestMessage::STOP);
399 msg.set_type(GuestMessage::ARC_VM);
400 SendGuestMessage(msg);
401
Garrick Evans21173b12019-11-20 15:23:16 +0900402 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900403}
404
Garrick Evans51d5b552020-01-30 10:42:06 +0900405bool Manager::StartCrosVm(uint64_t vm_id,
406 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900407 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900408 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
409 vm_type == GuestMessage::PLUGIN_VM);
410
411 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
412 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900413 return false;
414
415 GuestMessage msg;
416 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900417 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900418 SendGuestMessage(msg);
419
420 return true;
421}
422
Garrick Evans51d5b552020-01-30 10:42:06 +0900423void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900424 GuestMessage msg;
425 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900426 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900427 SendGuestMessage(msg);
428
Garrick Evans51d5b552020-01-30 10:42:06 +0900429 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900430}
431
Garrick Evans08843932019-09-17 14:41:08 +0900432std::unique_ptr<dbus::Response> Manager::OnArcStartup(
433 dbus::MethodCall* method_call) {
434 LOG(INFO) << "ARC++ starting up";
435
436 std::unique_ptr<dbus::Response> dbus_response(
437 dbus::Response::FromMethodCall(method_call));
438
439 dbus::MessageReader reader(method_call);
440 dbus::MessageWriter writer(dbus_response.get());
441
442 patchpanel::ArcStartupRequest request;
443 patchpanel::ArcStartupResponse response;
444
445 if (!reader.PopArrayOfBytesAsProto(&request)) {
446 LOG(ERROR) << "Unable to parse request";
447 writer.AppendProtoAsArrayOfBytes(response);
448 return dbus_response;
449 }
450
Garrick Evanse01bf072019-11-15 09:08:19 +0900451 if (!StartArc(request.pid()))
452 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900453
Garrick Evans08843932019-09-17 14:41:08 +0900454 writer.AppendProtoAsArrayOfBytes(response);
455 return dbus_response;
456}
457
458std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
459 dbus::MethodCall* method_call) {
460 LOG(INFO) << "ARC++ shutting down";
461
462 std::unique_ptr<dbus::Response> dbus_response(
463 dbus::Response::FromMethodCall(method_call));
464
465 dbus::MessageReader reader(method_call);
466 dbus::MessageWriter writer(dbus_response.get());
467
468 patchpanel::ArcShutdownRequest request;
469 patchpanel::ArcShutdownResponse response;
470
471 if (!reader.PopArrayOfBytesAsProto(&request)) {
472 LOG(ERROR) << "Unable to parse request";
473 writer.AppendProtoAsArrayOfBytes(response);
474 return dbus_response;
475 }
476
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900477 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900478
Garrick Evans08843932019-09-17 14:41:08 +0900479 writer.AppendProtoAsArrayOfBytes(response);
480 return dbus_response;
481}
482
483std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
484 dbus::MethodCall* method_call) {
485 LOG(INFO) << "ARCVM starting up";
486
487 std::unique_ptr<dbus::Response> dbus_response(
488 dbus::Response::FromMethodCall(method_call));
489
490 dbus::MessageReader reader(method_call);
491 dbus::MessageWriter writer(dbus_response.get());
492
493 patchpanel::ArcVmStartupRequest request;
494 patchpanel::ArcVmStartupResponse response;
495
496 if (!reader.PopArrayOfBytesAsProto(&request)) {
497 LOG(ERROR) << "Unable to parse request";
498 writer.AppendProtoAsArrayOfBytes(response);
499 return dbus_response;
500 }
501
Garrick Evans47c19272019-11-21 10:58:21 +0900502 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900503 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900504 writer.AppendProtoAsArrayOfBytes(response);
505 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900506 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900507
Garrick Evans47c19272019-11-21 10:58:21 +0900508 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900509 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
510 if (config->tap_ifname().empty())
511 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900512
Garrick Evans38b25a42020-04-06 15:17:42 +0900513 auto* dev = response.add_devices();
514 dev->set_ifname(config->tap_ifname());
515 dev->set_ipv4_addr(config->guest_ipv4_addr());
516 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900517
Garrick Evans08843932019-09-17 14:41:08 +0900518 writer.AppendProtoAsArrayOfBytes(response);
519 return dbus_response;
520}
521
522std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
523 dbus::MethodCall* method_call) {
524 LOG(INFO) << "ARCVM shutting down";
525
526 std::unique_ptr<dbus::Response> dbus_response(
527 dbus::Response::FromMethodCall(method_call));
528
529 dbus::MessageReader reader(method_call);
530 dbus::MessageWriter writer(dbus_response.get());
531
532 patchpanel::ArcVmShutdownRequest request;
533 patchpanel::ArcVmShutdownResponse response;
534
535 if (!reader.PopArrayOfBytesAsProto(&request)) {
536 LOG(ERROR) << "Unable to parse request";
537 writer.AppendProtoAsArrayOfBytes(response);
538 return dbus_response;
539 }
540
Garrick Evans21173b12019-11-20 15:23:16 +0900541 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900542
Garrick Evans08843932019-09-17 14:41:08 +0900543 writer.AppendProtoAsArrayOfBytes(response);
544 return dbus_response;
545}
546
Garrick Evans47c19272019-11-21 10:58:21 +0900547std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
548 dbus::MethodCall* method_call) {
549 LOG(INFO) << "Termina VM starting up";
550
551 std::unique_ptr<dbus::Response> dbus_response(
552 dbus::Response::FromMethodCall(method_call));
553
554 dbus::MessageReader reader(method_call);
555 dbus::MessageWriter writer(dbus_response.get());
556
557 patchpanel::TerminaVmStartupRequest request;
558 patchpanel::TerminaVmStartupResponse response;
559
560 if (!reader.PopArrayOfBytesAsProto(&request)) {
561 LOG(ERROR) << "Unable to parse request";
562 writer.AppendProtoAsArrayOfBytes(response);
563 return dbus_response;
564 }
565
566 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900567 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900568 LOG(ERROR) << "Failed to start Termina VM network service";
569 writer.AppendProtoAsArrayOfBytes(response);
570 return dbus_response;
571 }
572
Garrick Evans51d5b552020-01-30 10:42:06 +0900573 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900574 if (!tap) {
575 LOG(DFATAL) << "TAP device missing";
576 writer.AppendProtoAsArrayOfBytes(response);
577 return dbus_response;
578 }
Garrick Evans47c19272019-11-21 10:58:21 +0900579
Garrick Evansb1c93712020-01-22 09:28:25 +0900580 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900581 dev->set_ifname(tap->host_ifname());
582 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900583 if (!subnet) {
584 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
585 writer.AppendProtoAsArrayOfBytes(response);
586 return dbus_response;
587 }
588 auto* resp_subnet = dev->mutable_ipv4_subnet();
589 resp_subnet->set_base_addr(subnet->BaseAddress());
590 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900591 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900592 if (!subnet) {
593 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
594 writer.AppendProtoAsArrayOfBytes(response);
595 return dbus_response;
596 }
597 resp_subnet = response.mutable_container_subnet();
598 resp_subnet->set_base_addr(subnet->BaseAddress());
599 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900600
601 writer.AppendProtoAsArrayOfBytes(response);
602 return dbus_response;
603}
604
605std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
606 dbus::MethodCall* method_call) {
607 LOG(INFO) << "Termina VM shutting down";
608
609 std::unique_ptr<dbus::Response> dbus_response(
610 dbus::Response::FromMethodCall(method_call));
611
612 dbus::MessageReader reader(method_call);
613 dbus::MessageWriter writer(dbus_response.get());
614
615 patchpanel::TerminaVmShutdownRequest request;
616 patchpanel::TerminaVmShutdownResponse response;
617
618 if (!reader.PopArrayOfBytesAsProto(&request)) {
619 LOG(ERROR) << "Unable to parse request";
620 writer.AppendProtoAsArrayOfBytes(response);
621 return dbus_response;
622 }
623
Garrick Evans51d5b552020-01-30 10:42:06 +0900624 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
625
626 writer.AppendProtoAsArrayOfBytes(response);
627 return dbus_response;
628}
629
630std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
631 dbus::MethodCall* method_call) {
632 LOG(INFO) << "Plugin VM starting up";
633
634 std::unique_ptr<dbus::Response> dbus_response(
635 dbus::Response::FromMethodCall(method_call));
636
637 dbus::MessageReader reader(method_call);
638 dbus::MessageWriter writer(dbus_response.get());
639
640 patchpanel::PluginVmStartupRequest request;
641 patchpanel::PluginVmStartupResponse response;
642
643 if (!reader.PopArrayOfBytesAsProto(&request)) {
644 LOG(ERROR) << "Unable to parse request";
645 writer.AppendProtoAsArrayOfBytes(response);
646 return dbus_response;
647 }
648
Garrick Evans08fb34b2020-02-20 10:50:17 +0900649 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900650 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900651 LOG(ERROR) << "Failed to start Plugin VM network service";
652 writer.AppendProtoAsArrayOfBytes(response);
653 return dbus_response;
654 }
655
656 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
657 if (!tap) {
658 LOG(DFATAL) << "TAP device missing";
659 writer.AppendProtoAsArrayOfBytes(response);
660 return dbus_response;
661 }
662
Garrick Evans51d5b552020-01-30 10:42:06 +0900663 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900664 dev->set_ifname(tap->host_ifname());
665 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900666 if (!subnet) {
667 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
668 writer.AppendProtoAsArrayOfBytes(response);
669 return dbus_response;
670 }
671 auto* resp_subnet = dev->mutable_ipv4_subnet();
672 resp_subnet->set_base_addr(subnet->BaseAddress());
673 resp_subnet->set_prefix_len(subnet->PrefixLength());
674
675 writer.AppendProtoAsArrayOfBytes(response);
676 return dbus_response;
677}
678
679std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
680 dbus::MethodCall* method_call) {
681 LOG(INFO) << "Plugin VM shutting down";
682
683 std::unique_ptr<dbus::Response> dbus_response(
684 dbus::Response::FromMethodCall(method_call));
685
686 dbus::MessageReader reader(method_call);
687 dbus::MessageWriter writer(dbus_response.get());
688
689 patchpanel::PluginVmShutdownRequest request;
690 patchpanel::PluginVmShutdownResponse response;
691
692 if (!reader.PopArrayOfBytesAsProto(&request)) {
693 LOG(ERROR) << "Unable to parse request";
694 writer.AppendProtoAsArrayOfBytes(response);
695 return dbus_response;
696 }
697
698 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900699
700 writer.AppendProtoAsArrayOfBytes(response);
701 return dbus_response;
702}
703
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900704std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
705 dbus::MethodCall* method_call) {
706 std::unique_ptr<dbus::Response> dbus_response(
707 dbus::Response::FromMethodCall(method_call));
708
709 dbus::MessageReader reader(method_call);
710 dbus::MessageWriter writer(dbus_response.get());
711
712 patchpanel::SetVpnIntentRequest request;
713 patchpanel::SetVpnIntentResponse response;
714
715 bool success = reader.PopArrayOfBytesAsProto(&request);
716 if (!success) {
717 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
718 // Do not return yet to make sure we close the received fd.
719 }
720
721 base::ScopedFD client_socket;
722 reader.PopFileDescriptor(&client_socket);
723
724 if (success)
725 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
726
727 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900728
729 writer.AppendProtoAsArrayOfBytes(response);
730 return dbus_response;
731}
732
733std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
734 dbus::MethodCall* method_call) {
735 std::unique_ptr<dbus::Response> dbus_response(
736 dbus::Response::FromMethodCall(method_call));
737
738 dbus::MessageReader reader(method_call);
739 dbus::MessageWriter writer(dbus_response.get());
740
741 patchpanel::ConnectNamespaceRequest request;
742 patchpanel::ConnectNamespaceResponse response;
743
Hugo Benichicc6850f2020-01-17 13:26:06 +0900744 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900745 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900746 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
747 // Do not return yet to make sure we close the received fd and
748 // validate other arguments.
749 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900750 }
751
Hugo Benichicc6850f2020-01-17 13:26:06 +0900752 base::ScopedFD client_fd;
753 reader.PopFileDescriptor(&client_fd);
754 if (!client_fd.is_valid()) {
755 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
756 success = false;
757 }
758
759 pid_t pid = request.pid();
760 {
761 ScopedNS ns(pid);
762 if (!ns.IsValid()) {
763 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
764 success = false;
765 }
766 }
767
768 const std::string& outbound_ifname = request.outbound_physical_device();
769 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
770 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
771 << outbound_ifname;
772 success = false;
773 }
774
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900775 if (success)
776 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900777
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900778 writer.AppendProtoAsArrayOfBytes(response);
779 return dbus_response;
780}
781
Jie Jiang493cde42020-07-17 21:43:39 +0900782std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
783 dbus::MethodCall* method_call) {
784 std::unique_ptr<dbus::Response> dbus_response(
785 dbus::Response::FromMethodCall(method_call));
786
787 dbus::MessageReader reader(method_call);
788 dbus::MessageWriter writer(dbus_response.get());
789
790 patchpanel::TrafficCountersRequest request;
791 patchpanel::TrafficCountersResponse response;
792
793 if (!reader.PopArrayOfBytesAsProto(&request)) {
794 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
795 writer.AppendProtoAsArrayOfBytes(response);
796 return dbus_response;
797 }
798
799 const std::set<std::string> devices{request.devices().begin(),
800 request.devices().end()};
801 const auto counters = counters_svc_->GetCounters(devices);
802 for (const auto& kv : counters) {
803 auto* traffic_counter = response.add_counters();
804 const auto& source_and_device = kv.first;
805 const auto& counter = kv.second;
806 traffic_counter->set_source(source_and_device.first);
807 traffic_counter->set_device(source_and_device.second);
808 traffic_counter->set_rx_bytes(counter.rx_bytes);
809 traffic_counter->set_rx_packets(counter.rx_packets);
810 traffic_counter->set_tx_bytes(counter.tx_bytes);
811 traffic_counter->set_tx_packets(counter.tx_packets);
812 }
813
814 writer.AppendProtoAsArrayOfBytes(response);
815 return dbus_response;
816}
817
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900818std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
819 dbus::MethodCall* method_call) {
820 std::unique_ptr<dbus::Response> dbus_response(
821 dbus::Response::FromMethodCall(method_call));
822
823 dbus::MessageReader reader(method_call);
824 dbus::MessageWriter writer(dbus_response.get());
825
826 patchpanel::ModifyPortRuleRequest request;
827 patchpanel::ModifyPortRuleResponse response;
828
829 if (!reader.PopArrayOfBytesAsProto(&request)) {
830 LOG(ERROR) << "Unable to parse ModifyPortRequest";
831 writer.AppendProtoAsArrayOfBytes(response);
832 return dbus_response;
833 }
834
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900835 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900836 writer.AppendProtoAsArrayOfBytes(response);
837 return dbus_response;
838}
839
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900840void Manager::ConnectNamespace(
841 base::ScopedFD client_fd,
842 const patchpanel::ConnectNamespaceRequest& request,
843 patchpanel::ConnectNamespaceResponse& response) {
844 std::unique_ptr<Subnet> subnet =
845 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
846 if (!subnet) {
847 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
848 return;
849 }
850
851 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900852 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900853 const std::string host_ifname = "arc_ns" + ifname_id;
854 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900855 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
856 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900857
Hugo Benichie8758b52020-04-03 14:49:01 +0900858 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900859 // - attach a name to the client namespace.
860 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900861 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900862 // - configure IPv4 address on local veth inside host namespace.
863 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900864 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900865 if (!datapath_->NetnsAttachName(netns_name, pid)) {
866 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
867 << netns_name << " to namespace pid " << pid;
868 return;
869 }
870 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900871 addr_mgr_.GenerateMacAddress(),
872 client_ipv4_addr, subnet->PrefixLength(),
873 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900874 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
875 "namespace pid "
876 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900877 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900878 return;
879 }
880 if (!datapath_->ConfigureInterface(
881 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
882 subnet->PrefixLength(), true /* link up */,
883 false /* enable_multicast */)) {
884 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
885 << host_ifname;
886 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900887 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900888 return;
889 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900890 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900891 {
892 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900893 peer_route_setup_success =
894 ns.IsValid() &&
895 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
896 }
897 if (!peer_route_setup_success) {
898 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
899 << host_ifname << " inside namespace pid " << pid;
900 datapath_->RemoveInterface(host_ifname);
901 datapath_->NetnsDeleteName(netns_name);
902 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900903 }
904
905 // Host namespace routing configuration
906 // - ingress: add route to client subnet via |host_ifname|.
907 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
908 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
909 // Note that by default unsolicited ingress traffic is not forwarded to the
910 // client namespace unless the client specifically set port forwarding
911 // through permission_broker DBus APIs.
912 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
913 // both ways between client namespace and other guest containers and VMs.
914 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
915 // routing to that interface routing table.
916 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
917 subnet->Netmask())) {
918 LOG(ERROR)
919 << "ConnectNamespaceRequest: failed to set route to client namespace";
920 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900921 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900922 return;
923 }
924 if (!datapath_->AddOutboundIPv4(host_ifname)) {
925 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
926 "traffic outgoing from "
927 << host_ifname;
928 datapath_->RemoveInterface(host_ifname);
929 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
930 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900931 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900932 return;
933 }
934 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
935 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
936 "outgoing from "
937 << host_ifname;
938 datapath_->RemoveInterface(host_ifname);
939 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
940 subnet->Netmask());
941 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900942 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900943 return;
944 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900945
Hugo Benichi7352ad92020-04-07 16:11:59 +0900946 // Dup the client fd into our own: this guarantees that the fd number will
947 // be stable and tied to the actual kernel resources used by the client.
948 base::ScopedFD local_client_fd(dup(client_fd.get()));
949 if (!local_client_fd.is_valid()) {
950 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
Hugo Benichie8758b52020-04-03 14:49:01 +0900951 datapath_->RemoveInterface(host_ifname);
952 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
953 subnet->Netmask());
954 datapath_->RemoveOutboundIPv4(host_ifname);
955 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900956 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900957 return;
958 }
959
960 // Add the dupe fd to the epoll watcher.
961 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
962 // listening to EPOLLHUP.
963 struct epoll_event epevent;
964 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
965 epevent.data.fd = local_client_fd.get();
966 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
967 local_client_fd.get(), &epevent) != 0) {
968 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900969 datapath_->RemoveInterface(host_ifname);
970 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
971 subnet->Netmask());
972 datapath_->RemoveOutboundIPv4(host_ifname);
973 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900974 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900975 return;
976 }
977
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900978 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900979 response.set_peer_ifname(client_ifname);
980 response.set_peer_ipv4_address(host_ipv4_addr);
981 response.set_host_ifname(host_ifname);
982 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900983 auto* response_subnet = response.mutable_ipv4_subnet();
984 response_subnet->set_base_addr(subnet->BaseAddress());
985 response_subnet->set_prefix_len(subnet->PrefixLength());
986
987 // Store ConnectNamespaceInfo
988 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +0900989 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900990 connected_namespaces_[fdkey] = {};
991 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
992 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900993 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900994 ns_info.outbound_ifname = request.outbound_physical_device();
995 ns_info.host_ifname = std::move(host_ifname);
996 ns_info.client_ifname = std::move(client_ifname);
997 ns_info.client_subnet = std::move(subnet);
998
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900999 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001000
1001 if (connected_namespaces_.size() == 1) {
1002 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1003 CheckConnectedNamespaces();
1004 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001005}
1006
1007void Manager::DisconnectNamespace(int client_fd) {
1008 auto it = connected_namespaces_.find(client_fd);
1009 if (it == connected_namespaces_.end()) {
1010 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
1011 return;
1012 }
1013
Hugo Benichi7352ad92020-04-07 16:11:59 +09001014 // Remove the client fd dupe from the epoll watcher and close it.
1015 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001016 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001017 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001018 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001019 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001020
Hugo Benichie8758b52020-04-03 14:49:01 +09001021 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001022 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +09001023 // - remove forwarding rules on host namespace.
1024 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +09001025 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +09001026 // Note that the default route set inside the client namespace by patchpanel
1027 // is not destroyed: it is assumed the client will also teardown its
1028 // namespace if it triggered DisconnectNamespace.
1029 datapath_->RemoveInterface(it->second.host_ifname);
1030 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
1031 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
1032 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
1033 it->second.client_subnet->BaseAddress(),
1034 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +09001035 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001036
1037 LOG(INFO) << "Disconnected network namespace " << it->second;
1038
1039 // This release the allocated IPv4 subnet.
1040 connected_namespaces_.erase(it);
1041}
1042
Hugo Benichi7352ad92020-04-07 16:11:59 +09001043// TODO(hugobenichi) Generalize this check to all resources created by
1044// patchpanel on behalf of a remote client.
1045void Manager::CheckConnectedNamespaces() {
1046 int max_event = 10;
1047 struct epoll_event epevents[max_event];
1048 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1049 0 /* do not block */);
1050 if (nready < 0)
1051 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1052
1053 for (int i = 0; i < nready; i++)
1054 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1055 DisconnectNamespace(epevents[i].data.fd);
1056
1057 if (connected_namespaces_.empty()) {
1058 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1059 return;
1060 }
1061
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001062 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001063 FROM_HERE,
1064 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001065 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001066 kConnectNamespaceCheckInterval);
1067}
1068
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001069bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1070 switch (request.proto()) {
1071 case patchpanel::ModifyPortRuleRequest::TCP:
1072 case patchpanel::ModifyPortRuleRequest::UDP:
1073 break;
1074 default:
1075 LOG(ERROR) << "Unknown protocol " << request.proto();
1076 return false;
1077 }
1078
1079 switch (request.op()) {
1080 case patchpanel::ModifyPortRuleRequest::CREATE:
1081 switch (request.type()) {
1082 case patchpanel::ModifyPortRuleRequest::ACCESS:
1083 return firewall_.AddAcceptRules(request.proto(),
1084 request.input_dst_port(),
1085 request.input_ifname());
1086 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1087 return firewall_.AddLoopbackLockdownRules(request.proto(),
1088 request.input_dst_port());
1089 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1090 return firewall_.AddIpv4ForwardRule(
1091 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1092 request.input_ifname(), request.dst_ip(), request.dst_port());
1093 default:
1094 LOG(ERROR) << "Unknown port rule type " << request.type();
1095 return false;
1096 }
1097 case patchpanel::ModifyPortRuleRequest::DELETE:
1098 switch (request.type()) {
1099 case patchpanel::ModifyPortRuleRequest::ACCESS:
1100 return firewall_.DeleteAcceptRules(request.proto(),
1101 request.input_dst_port(),
1102 request.input_ifname());
1103 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1104 return firewall_.DeleteLoopbackLockdownRules(
1105 request.proto(), request.input_dst_port());
1106 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1107 return firewall_.DeleteIpv4ForwardRule(
1108 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1109 request.input_ifname(), request.dst_ip(), request.dst_port());
1110 default:
1111 LOG(ERROR) << "Unknown port rule type " << request.type();
1112 return false;
1113 }
1114 default:
1115 LOG(ERROR) << "Unknown operation " << request.op();
1116 return false;
1117 }
1118}
1119
Garrick Evanse94a14e2019-11-11 10:32:13 +09001120void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001121 IpHelperMessage ipm;
1122 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001123 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001124 mcast_proxy_->SendMessage(ipm);
1125 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001126}
1127
Garrick Evans4ac09852020-01-16 14:09:22 +09001128void Manager::StartForwarding(const std::string& ifname_physical,
1129 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001130 bool ipv6,
1131 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001132 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001133 return;
1134
1135 IpHelperMessage ipm;
1136 DeviceMessage* msg = ipm.mutable_device_message();
1137 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001138 msg->set_br_ifname(ifname_virtual);
1139
1140 if (ipv6) {
1141 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1142 << ifname_virtual;
1143
1144 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1145 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1146 << ifname_physical << " to " << ifname_virtual;
1147 }
1148 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1149 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1150 << ifname_physical;
1151 }
1152 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1153 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1154 << ifname_virtual;
1155 }
1156 nd_proxy_->SendMessage(ipm);
1157 }
1158
1159 if (multicast) {
1160 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1161 << " to " << ifname_virtual;
1162 mcast_proxy_->SendMessage(ipm);
1163 }
1164}
1165
1166void Manager::StopForwarding(const std::string& ifname_physical,
1167 const std::string& ifname_virtual,
1168 bool ipv6,
1169 bool multicast) {
1170 if (ifname_physical.empty())
1171 return;
1172
1173 IpHelperMessage ipm;
1174 DeviceMessage* msg = ipm.mutable_device_message();
1175 msg->set_dev_ifname(ifname_physical);
1176 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001177 if (!ifname_virtual.empty()) {
1178 msg->set_br_ifname(ifname_virtual);
1179 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001180
1181 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001182 if (ifname_virtual.empty()) {
1183 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1184 } else {
1185 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1186 << ifname_virtual;
1187 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1188 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001189 nd_proxy_->SendMessage(ipm);
1190 }
1191
1192 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001193 if (ifname_virtual.empty()) {
1194 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1195 } else {
1196 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1197 << " to " << ifname_virtual;
1198 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001199 mcast_proxy_->SendMessage(ipm);
1200 }
1201}
1202
Garrick Evans4ac09852020-01-16 14:09:22 +09001203void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1204 LOG_IF(DFATAL, msg.dev_ifname().empty())
1205 << "Received DeviceMessage w/ empty dev_ifname";
1206
1207 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1208 128)) {
1209 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1210 << msg.dev_ifname();
1211 }
1212}
1213
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001214std::ostream& operator<<(std::ostream& stream,
1215 const Manager::ConnectNamespaceInfo& ns_info) {
1216 stream << "{ pid: " << ns_info.pid;
1217 if (!ns_info.outbound_ifname.empty()) {
1218 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1219 }
1220 stream << ", host_ifname: " << ns_info.host_ifname
1221 << ", client_ifname: " << ns_info.client_ifname
1222 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1223 return stream;
1224}
1225
Garrick Evans3388a032020-03-24 11:25:55 +09001226} // namespace patchpanel