blob: 7cee20b64bd9d127f1550cf4bee60e94e11e0b99 [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
Hugo Benichi321f23b2020-09-25 15:42:05 +090039// Constants used for dropping locally originated traffic bound to an incorrect
40// source IPv4 address.
41constexpr char kGuestIPv4Subnet[] = "100.115.92.0/23";
42constexpr std::array<const char*, 6> kPhysicalIfnamePrefixes{
43 {"eth+", "wlan+", "mlan+", "usb+", "wwan+", "rmnet+"}};
44
Hugo Benichi7352ad92020-04-07 16:11:59 +090045// Time interval between epoll checks on file descriptors committed by callers
46// of ConnectNamespace DBus API.
47constexpr const base::TimeDelta kConnectNamespaceCheckInterval =
Hugo Benichifa9462e2020-06-26 09:50:48 +090048 base::TimeDelta::FromSeconds(5);
Hugo Benichi7352ad92020-04-07 16:11:59 +090049
Garrick Evans08843932019-09-17 14:41:08 +090050// Passes |method_call| to |handler| and passes the response to
51// |response_sender|. If |handler| returns nullptr, an empty response is
52// created and sent.
53void HandleSynchronousDBusMethodCall(
54 base::Callback<std::unique_ptr<dbus::Response>(dbus::MethodCall*)> handler,
55 dbus::MethodCall* method_call,
56 dbus::ExportedObject::ResponseSender response_sender) {
57 std::unique_ptr<dbus::Response> response = handler.Run(method_call);
58 if (!response)
59 response = dbus::Response::FromMethodCall(method_call);
Qijiang Fan0c657d42020-08-24 19:07:50 +090060 std::move(response_sender).Run(std::move(response));
Garrick Evans08843932019-09-17 14:41:08 +090061}
62
63} // namespace
Kevin Cernekee95d4ae92016-06-19 10:26:29 -070064
Taoyu Lice7caa62019-10-01 15:43:33 +090065Manager::Manager(std::unique_ptr<HelperProcess> adb_proxy,
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090066 std::unique_ptr<HelperProcess> mcast_proxy,
Garrick Evans1f5a3612019-11-08 12:59:03 +090067 std::unique_ptr<HelperProcess> nd_proxy)
Garrick Evans3915af32019-07-25 15:44:34 +090068 : adb_proxy_(std::move(adb_proxy)),
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +090069 mcast_proxy_(std::move(mcast_proxy)),
Garrick Evans4ee5ce22020-03-18 07:05:17 +090070 nd_proxy_(std::move(nd_proxy)) {
Taoyu Li179dcc62019-10-17 11:21:08 +090071 runner_ = std::make_unique<MinijailedProcessRunner>();
Jason Jeremy Imana7273a32020-08-04 11:25:31 +090072 datapath_ = std::make_unique<Datapath>(runner_.get(), &firewall_);
Hugo Benichi7352ad92020-04-07 16:11:59 +090073 connected_namespaces_epollfd_ = epoll_create(1 /* size */);
Taoyu Li179dcc62019-10-17 11:21:08 +090074}
Long Chengd4415582019-09-24 19:16:09 +000075
Garrick Evans207e7482019-12-16 11:54:36 +090076Manager::~Manager() {
77 OnShutdown(nullptr);
78}
79
Jason Jeremy Imanf4156cb2019-11-14 15:36:22 +090080std::map<const std::string, bool> Manager::cached_feature_enabled_ = {};
81
82bool Manager::ShouldEnableFeature(
83 int min_android_sdk_version,
84 int min_chrome_milestone,
85 const std::vector<std::string>& supported_boards,
86 const std::string& feature_name) {
87 static const char kLsbReleasePath[] = "/etc/lsb-release";
88
89 const auto& cached_result = cached_feature_enabled_.find(feature_name);
90 if (cached_result != cached_feature_enabled_.end())
91 return cached_result->second;
92
93 auto check = [min_android_sdk_version, min_chrome_milestone,
94 &supported_boards, &feature_name]() {
95 brillo::KeyValueStore store;
96 if (!store.Load(base::FilePath(kLsbReleasePath))) {
97 LOG(ERROR) << "Could not read lsb-release";
98 return false;
99 }
100
101 std::string value;
102 if (!store.GetString("CHROMEOS_ARC_ANDROID_SDK_VERSION", &value)) {
103 LOG(ERROR) << feature_name
104 << " disabled - cannot determine Android SDK version";
105 return false;
106 }
107 int ver = 0;
108 if (!base::StringToInt(value.c_str(), &ver)) {
109 LOG(ERROR) << feature_name << " disabled - invalid Android SDK version";
110 return false;
111 }
112 if (ver < min_android_sdk_version) {
113 LOG(INFO) << feature_name << " disabled for Android SDK " << value;
114 return false;
115 }
116
117 if (!store.GetString("CHROMEOS_RELEASE_CHROME_MILESTONE", &value)) {
118 LOG(ERROR) << feature_name
119 << " disabled - cannot determine ChromeOS milestone";
120 return false;
121 }
122 if (!base::StringToInt(value.c_str(), &ver)) {
123 LOG(ERROR) << feature_name << " disabled - invalid ChromeOS milestone";
124 return false;
125 }
126 if (ver < min_chrome_milestone) {
127 LOG(INFO) << feature_name << " disabled for ChromeOS milestone " << value;
128 return false;
129 }
130
131 if (!store.GetString("CHROMEOS_RELEASE_BOARD", &value)) {
132 LOG(ERROR) << feature_name << " disabled - cannot determine board";
133 return false;
134 }
135 if (!supported_boards.empty() &&
136 std::find(supported_boards.begin(), supported_boards.end(), value) ==
137 supported_boards.end()) {
138 LOG(INFO) << feature_name << " disabled for board " << value;
139 return false;
140 }
141 return true;
142 };
143
144 bool result = check();
145 cached_feature_enabled_.emplace(feature_name, result);
146 return result;
147}
148
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700149int Manager::OnInit() {
Garrick Evans54861622019-07-19 09:05:09 +0900150 prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800151
152 // Handle subprocess lifecycle.
153 process_reaper_.Register(this);
Hugo Benichi935eca92018-07-03 13:47:24 +0900154
155 CHECK(process_reaper_.WatchForChild(
Garrick Evans96e03042019-05-28 14:30:52 +0900156 FROM_HERE, adb_proxy_->pid(),
157 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
158 adb_proxy_->pid())))
159 << "Failed to watch adb-proxy child process";
Taoyu Liaf944c92019-10-01 12:22:31 +0900160 CHECK(process_reaper_.WatchForChild(
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900161 FROM_HERE, mcast_proxy_->pid(),
162 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
163 nd_proxy_->pid())))
164 << "Failed to watch multicast-proxy child process";
165 CHECK(process_reaper_.WatchForChild(
Taoyu Liaf944c92019-10-01 12:22:31 +0900166 FROM_HERE, nd_proxy_->pid(),
167 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
168 nd_proxy_->pid())))
Jason Jeremy Imand89b5f52019-10-24 10:39:17 +0900169 << "Failed to watch nd-proxy child process";
Garrick Evans96e03042019-05-28 14:30:52 +0900170
Garrick Evans49879532018-12-03 13:15:36 +0900171 // Run after Daemon::OnInit().
hschamf9546312020-04-14 15:12:40 +0900172 base::ThreadTaskRunnerHandle::Get()->PostTask(
Kevin Cernekee95d4ae92016-06-19 10:26:29 -0700173 FROM_HERE,
174 base::Bind(&Manager::InitialSetup, weak_factory_.GetWeakPtr()));
175
176 return DBusDaemon::OnInit();
177}
178
179void Manager::InitialSetup() {
Garrick Evans08843932019-09-17 14:41:08 +0900180 LOG(INFO) << "Setting up DBus service interface";
181 dbus_svc_path_ = bus_->GetExportedObject(
182 dbus::ObjectPath(patchpanel::kPatchPanelServicePath));
183 if (!dbus_svc_path_) {
184 LOG(FATAL) << "Failed to export " << patchpanel::kPatchPanelServicePath
185 << " object";
186 }
187
188 using ServiceMethod =
189 std::unique_ptr<dbus::Response> (Manager::*)(dbus::MethodCall*);
190 const std::map<const char*, ServiceMethod> kServiceMethods = {
191 {patchpanel::kArcStartupMethod, &Manager::OnArcStartup},
192 {patchpanel::kArcShutdownMethod, &Manager::OnArcShutdown},
193 {patchpanel::kArcVmStartupMethod, &Manager::OnArcVmStartup},
194 {patchpanel::kArcVmShutdownMethod, &Manager::OnArcVmShutdown},
Garrick Evans47c19272019-11-21 10:58:21 +0900195 {patchpanel::kTerminaVmStartupMethod, &Manager::OnTerminaVmStartup},
196 {patchpanel::kTerminaVmShutdownMethod, &Manager::OnTerminaVmShutdown},
Garrick Evans51d5b552020-01-30 10:42:06 +0900197 {patchpanel::kPluginVmStartupMethod, &Manager::OnPluginVmStartup},
198 {patchpanel::kPluginVmShutdownMethod, &Manager::OnPluginVmShutdown},
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900199 {patchpanel::kSetVpnIntentMethod, &Manager::OnSetVpnIntent},
Hugo Benichib56b77c2020-01-15 16:00:56 +0900200 {patchpanel::kConnectNamespaceMethod, &Manager::OnConnectNamespace},
Jie Jiang493cde42020-07-17 21:43:39 +0900201 {patchpanel::kGetTrafficCountersMethod, &Manager::OnGetTrafficCounters},
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900202 {patchpanel::kModifyPortRuleMethod, &Manager::OnModifyPortRule},
Garrick Evans08843932019-09-17 14:41:08 +0900203 };
204
205 for (const auto& kv : kServiceMethods) {
206 if (!dbus_svc_path_->ExportMethodAndBlock(
207 patchpanel::kPatchPanelInterface, kv.first,
208 base::Bind(&HandleSynchronousDBusMethodCall,
209 base::Bind(kv.second, base::Unretained(this))))) {
210 LOG(FATAL) << "Failed to export method " << kv.first;
211 }
212 }
213
214 if (!bus_->RequestOwnershipAndBlock(patchpanel::kPatchPanelServiceName,
215 dbus::Bus::REQUIRE_PRIMARY)) {
216 LOG(FATAL) << "Failed to take ownership of "
217 << patchpanel::kPatchPanelServiceName;
218 }
219 LOG(INFO) << "DBus service interface ready";
220
Hugo Benichifda77232020-08-21 18:28:15 +0900221 routing_svc_ = std::make_unique<RoutingService>();
222
223 StartDatapath();
224
225 nd_proxy_->RegisterDeviceMessageHandler(base::Bind(
226 &Manager::OnDeviceMessageFromNDProxy, weak_factory_.GetWeakPtr()));
227
228 shill_client_ = std::make_unique<ShillClient>(bus_);
229 auto* const forwarder = static_cast<TrafficForwarder*>(this);
230
231 GuestMessage::GuestType arc_guest =
232 USE_ARCVM ? GuestMessage::ARC_VM : GuestMessage::ARC;
233 arc_svc_ = std::make_unique<ArcService>(shill_client_.get(), datapath_.get(),
234 &addr_mgr_, forwarder, arc_guest);
235 cros_svc_ = std::make_unique<CrostiniService>(shill_client_.get(), &addr_mgr_,
236 datapath_.get(), forwarder);
237 network_monitor_svc_ =
238 std::make_unique<NetworkMonitorService>(shill_client_.get());
239 network_monitor_svc_->Start();
240
241 counters_svc_ =
242 std::make_unique<CountersService>(shill_client_.get(), runner_.get());
243
244 nd_proxy_->Listen();
245}
246
247void Manager::OnShutdown(int* exit_code) {
248 LOG(INFO) << "Shutting down and cleaning up";
249 cros_svc_.reset();
250 arc_svc_.reset();
251 close(connected_namespaces_epollfd_);
252 // Tear down any remaining connected namespace.
253 std::vector<int> connected_namespaces_fdkeys;
254 for (const auto& kv : connected_namespaces_)
255 connected_namespaces_fdkeys.push_back(kv.first);
256 for (const int fdkey : connected_namespaces_fdkeys)
257 DisconnectNamespace(fdkey);
258 StopDatapath();
259}
260
261void Manager::OnSubprocessExited(pid_t pid, const siginfo_t&) {
262 LOG(ERROR) << "Subprocess " << pid << " exited unexpectedly -"
263 << " attempting to restart";
264
265 HelperProcess* proc;
266 if (pid == adb_proxy_->pid()) {
267 proc = adb_proxy_.get();
268 } else if (pid == mcast_proxy_->pid()) {
269 proc = mcast_proxy_.get();
270 } else if (pid == nd_proxy_->pid()) {
271 proc = nd_proxy_.get();
272 } else {
273 LOG(DFATAL) << "Unknown child process";
274 return;
275 }
276
277 process_reaper_.ForgetChild(pid);
278
279 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
280 FROM_HERE,
281 base::Bind(&Manager::RestartSubprocess, weak_factory_.GetWeakPtr(), proc),
282 base::TimeDelta::FromMilliseconds((2 << proc->restarts()) *
283 kSubprocessRestartDelayMs));
284}
285
286void Manager::RestartSubprocess(HelperProcess* subproc) {
287 if (subproc->Restart()) {
288 DCHECK(process_reaper_.WatchForChild(
289 FROM_HERE, subproc->pid(),
290 base::Bind(&Manager::OnSubprocessExited, weak_factory_.GetWeakPtr(),
291 subproc->pid())))
292 << "Failed to watch child process " << subproc->pid();
293 }
294}
295
296void Manager::StartDatapath() {
297 // b/162966185: Allow Jetstream to disable:
298 // - the IP forwarding setup used for hosting VMs and containers,
299 // - the iptables rules for fwmark based routing.
300 if (USE_JETSTREAM_ROUTING) {
301 LOG(INFO) << "Skipping Datapath routing setup";
302 return;
303 }
304
Taoyu Li6d479442019-12-09 13:02:29 +0900305 auto& runner = datapath_->runner();
Hugo Benichifda77232020-08-21 18:28:15 +0900306
Garrick Evans7cf8c542020-05-25 09:50:17 +0900307 // Enable IPv4 packet forwarding
308 if (runner.sysctl_w("net.ipv4.ip_forward", "1") != 0) {
309 LOG(ERROR) << "Failed to update net.ipv4.ip_forward."
310 << " Guest connectivity will not work correctly.";
311 }
Garrick Evans28d194e2019-12-17 10:22:28 +0900312 // Limit local port range: Android owns 47104-61000.
313 // TODO(garrick): The original history behind this tweak is gone. Some
314 // investigation is needed to see if it is still applicable.
Garrick Evans8e8e3472020-01-23 14:03:50 +0900315 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 47103") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900316 LOG(ERROR) << "Failed to limit local port range. Some Android features or"
317 << " apps may not work correctly.";
318 }
Taoyu Li6d479442019-12-09 13:02:29 +0900319 // Enable IPv6 packet forarding
Garrick Evans8e8e3472020-01-23 14:03:50 +0900320 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "1") != 0) {
Taoyu Li6d479442019-12-09 13:02:29 +0900321 LOG(ERROR) << "Failed to update net.ipv6.conf.all.forwarding."
322 << " IPv6 functionality may be broken.";
323 }
Taoyu Li6d479442019-12-09 13:02:29 +0900324
Garrick Evansd291af62020-05-25 10:39:06 +0900325 if (!datapath_->AddSNATMarkRules()) {
326 LOG(ERROR) << "Failed to install SNAT mark rules."
327 << " Guest connectivity may be broken.";
328 }
329 if (!datapath_->AddForwardEstablishedRule()) {
330 LOG(ERROR) << "Failed to install forwarding rule for established"
331 << " connections.";
332 }
333
Hugo Benichi321f23b2020-09-25 15:42:05 +0900334 // chromium:898210: Drop any locally originated traffic that would exit a
335 // physical interface with a source IPv4 address from the subnet of IPs used
336 // for VMs, containers, and connected namespaces This is needed to prevent
337 // packets leaking with an incorrect src IP when a local process binds to the
338 // wrong interface.
339 for (const auto& oif : kPhysicalIfnamePrefixes) {
340 if (!datapath_->AddSourceIPv4DropRule(oif, kGuestIPv4Subnet))
341 LOG(WARNING) << "Failed to set up IPv4 drop rule for src ip "
342 << kGuestIPv4Subnet << " exiting " << oif;
Garrick Evansff6e37f2020-05-25 10:54:47 +0900343 }
344
Garrick Evansc50426b2020-05-25 11:00:55 +0900345 if (!datapath_->AddOutboundIPv4SNATMark("vmtap+")) {
346 LOG(ERROR) << "Failed to set up NAT for TAP devices."
347 << " Guest connectivity may be broken.";
348 }
Long Chengd4415582019-09-24 19:16:09 +0000349}
Garrick Evans49879532018-12-03 13:15:36 +0900350
Hugo Benichifda77232020-08-21 18:28:15 +0900351void Manager::StopDatapath() {
352 if (USE_JETSTREAM_ROUTING)
353 return;
Garrick Evans28d194e2019-12-17 10:22:28 +0900354
Garrick Evansc50426b2020-05-25 11:00:55 +0900355 datapath_->RemoveOutboundIPv4SNATMark("vmtap+");
Garrick Evansd291af62020-05-25 10:39:06 +0900356 datapath_->RemoveForwardEstablishedRule();
357 datapath_->RemoveSNATMarkRules();
Hugo Benichi321f23b2020-09-25 15:42:05 +0900358 for (const auto& oif : kPhysicalIfnamePrefixes)
359 datapath_->RemoveSourceIPv4DropRule(oif, kGuestIPv4Subnet);
Garrick Evansd291af62020-05-25 10:39:06 +0900360
Garrick Evans7cf8c542020-05-25 09:50:17 +0900361 auto& runner = datapath_->runner();
Garrick Evans28d194e2019-12-17 10:22:28 +0900362 // Restore original local port range.
363 // TODO(garrick): The original history behind this tweak is gone. Some
364 // investigation is needed to see if it is still applicable.
Garrick Evans7cf8c542020-05-25 09:50:17 +0900365 if (runner.sysctl_w("net.ipv4.ip_local_port_range", "32768 61000") != 0) {
Garrick Evans28d194e2019-12-17 10:22:28 +0900366 LOG(ERROR) << "Failed to restore local port range";
367 }
Garrick Evans7cf8c542020-05-25 09:50:17 +0900368 // Disable packet forwarding
369 if (runner.sysctl_w("net.ipv6.conf.all.forwarding", "0") != 0) {
370 LOG(ERROR) << "Failed to restore net.ipv6.conf.all.forwarding.";
371 }
372 if (runner.sysctl_w("net.ipv4.ip_forward", "0") != 0) {
373 LOG(ERROR) << "Failed to restore net.ipv4.ip_forward.";
374 }
Kevin Cernekee27bcaa62016-12-03 11:16:26 -0800375}
376
Garrick Evanse94a14e2019-11-11 10:32:13 +0900377bool Manager::StartArc(pid_t pid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900378 if (!arc_svc_->Start(pid))
379 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900380
381 GuestMessage msg;
382 msg.set_event(GuestMessage::START);
383 msg.set_type(GuestMessage::ARC);
384 msg.set_arc_pid(pid);
385 SendGuestMessage(msg);
386
387 return true;
388}
389
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900390void Manager::StopArc() {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900391 GuestMessage msg;
392 msg.set_event(GuestMessage::STOP);
393 msg.set_type(GuestMessage::ARC);
394 SendGuestMessage(msg);
395
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900396 // After the ARC container has stopped, the pid is not known anymore.
397 // The pid argument is ignored by ArcService.
398 arc_svc_->Stop(0);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900399}
400
Garrick Evans015b0d62020-02-07 09:06:38 +0900401bool Manager::StartArcVm(uint32_t cid) {
Garrick Evans508a4bc2019-11-14 08:45:52 +0900402 if (!arc_svc_->Start(cid))
403 return false;
Garrick Evanse94a14e2019-11-11 10:32:13 +0900404
405 GuestMessage msg;
406 msg.set_event(GuestMessage::START);
407 msg.set_type(GuestMessage::ARC_VM);
408 msg.set_arcvm_vsock_cid(cid);
409 SendGuestMessage(msg);
410
411 return true;
412}
413
Garrick Evans015b0d62020-02-07 09:06:38 +0900414void Manager::StopArcVm(uint32_t cid) {
Garrick Evanse94a14e2019-11-11 10:32:13 +0900415 GuestMessage msg;
416 msg.set_event(GuestMessage::STOP);
417 msg.set_type(GuestMessage::ARC_VM);
418 SendGuestMessage(msg);
419
Garrick Evans21173b12019-11-20 15:23:16 +0900420 arc_svc_->Stop(cid);
Garrick Evanse94a14e2019-11-11 10:32:13 +0900421}
422
Garrick Evans51d5b552020-01-30 10:42:06 +0900423bool Manager::StartCrosVm(uint64_t vm_id,
424 GuestMessage::GuestType vm_type,
Garrick Evans53a2a982020-02-05 10:53:35 +0900425 uint32_t subnet_index) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900426 DCHECK(vm_type == GuestMessage::TERMINA_VM ||
427 vm_type == GuestMessage::PLUGIN_VM);
428
429 if (!cros_svc_->Start(vm_id, vm_type == GuestMessage::TERMINA_VM,
430 subnet_index))
Garrick Evans47c19272019-11-21 10:58:21 +0900431 return false;
432
433 GuestMessage msg;
434 msg.set_event(GuestMessage::START);
Garrick Evans51d5b552020-01-30 10:42:06 +0900435 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900436 SendGuestMessage(msg);
437
438 return true;
439}
440
Garrick Evans51d5b552020-01-30 10:42:06 +0900441void Manager::StopCrosVm(uint64_t vm_id, GuestMessage::GuestType vm_type) {
Garrick Evans47c19272019-11-21 10:58:21 +0900442 GuestMessage msg;
443 msg.set_event(GuestMessage::STOP);
Garrick Evans51d5b552020-01-30 10:42:06 +0900444 msg.set_type(vm_type);
Garrick Evans47c19272019-11-21 10:58:21 +0900445 SendGuestMessage(msg);
446
Garrick Evans51d5b552020-01-30 10:42:06 +0900447 cros_svc_->Stop(vm_id, vm_type == GuestMessage::TERMINA_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900448}
449
Garrick Evans08843932019-09-17 14:41:08 +0900450std::unique_ptr<dbus::Response> Manager::OnArcStartup(
451 dbus::MethodCall* method_call) {
452 LOG(INFO) << "ARC++ starting up";
453
454 std::unique_ptr<dbus::Response> dbus_response(
455 dbus::Response::FromMethodCall(method_call));
456
457 dbus::MessageReader reader(method_call);
458 dbus::MessageWriter writer(dbus_response.get());
459
460 patchpanel::ArcStartupRequest request;
461 patchpanel::ArcStartupResponse response;
462
463 if (!reader.PopArrayOfBytesAsProto(&request)) {
464 LOG(ERROR) << "Unable to parse request";
465 writer.AppendProtoAsArrayOfBytes(response);
466 return dbus_response;
467 }
468
Garrick Evanse01bf072019-11-15 09:08:19 +0900469 if (!StartArc(request.pid()))
470 LOG(ERROR) << "Failed to start ARC++ network service";
Garrick Evanse94a14e2019-11-11 10:32:13 +0900471
Garrick Evans08843932019-09-17 14:41:08 +0900472 writer.AppendProtoAsArrayOfBytes(response);
473 return dbus_response;
474}
475
476std::unique_ptr<dbus::Response> Manager::OnArcShutdown(
477 dbus::MethodCall* method_call) {
478 LOG(INFO) << "ARC++ shutting down";
479
480 std::unique_ptr<dbus::Response> dbus_response(
481 dbus::Response::FromMethodCall(method_call));
482
483 dbus::MessageReader reader(method_call);
484 dbus::MessageWriter writer(dbus_response.get());
485
486 patchpanel::ArcShutdownRequest request;
487 patchpanel::ArcShutdownResponse response;
488
489 if (!reader.PopArrayOfBytesAsProto(&request)) {
490 LOG(ERROR) << "Unable to parse request";
491 writer.AppendProtoAsArrayOfBytes(response);
492 return dbus_response;
493 }
494
Hugo Benichi4d4bb8f2020-07-07 12:16:07 +0900495 StopArc();
Garrick Evanse94a14e2019-11-11 10:32:13 +0900496
Garrick Evans08843932019-09-17 14:41:08 +0900497 writer.AppendProtoAsArrayOfBytes(response);
498 return dbus_response;
499}
500
501std::unique_ptr<dbus::Response> Manager::OnArcVmStartup(
502 dbus::MethodCall* method_call) {
503 LOG(INFO) << "ARCVM starting up";
504
505 std::unique_ptr<dbus::Response> dbus_response(
506 dbus::Response::FromMethodCall(method_call));
507
508 dbus::MessageReader reader(method_call);
509 dbus::MessageWriter writer(dbus_response.get());
510
511 patchpanel::ArcVmStartupRequest request;
512 patchpanel::ArcVmStartupResponse response;
513
514 if (!reader.PopArrayOfBytesAsProto(&request)) {
515 LOG(ERROR) << "Unable to parse request";
516 writer.AppendProtoAsArrayOfBytes(response);
517 return dbus_response;
518 }
519
Garrick Evans47c19272019-11-21 10:58:21 +0900520 if (!StartArcVm(request.cid())) {
Garrick Evanse01bf072019-11-15 09:08:19 +0900521 LOG(ERROR) << "Failed to start ARCVM network service";
Garrick Evans47c19272019-11-21 10:58:21 +0900522 writer.AppendProtoAsArrayOfBytes(response);
523 return dbus_response;
Garrick Evanse01bf072019-11-15 09:08:19 +0900524 }
Garrick Evanse94a14e2019-11-11 10:32:13 +0900525
Garrick Evans47c19272019-11-21 10:58:21 +0900526 // Populate the response with the known devices.
Garrick Evans38b25a42020-04-06 15:17:42 +0900527 for (const auto* config : arc_svc_->GetDeviceConfigs()) {
528 if (config->tap_ifname().empty())
529 continue;
Garrick Evans47c19272019-11-21 10:58:21 +0900530
Garrick Evans38b25a42020-04-06 15:17:42 +0900531 auto* dev = response.add_devices();
532 dev->set_ifname(config->tap_ifname());
533 dev->set_ipv4_addr(config->guest_ipv4_addr());
534 }
Garrick Evanse94b6de2020-02-20 09:19:13 +0900535
Garrick Evans08843932019-09-17 14:41:08 +0900536 writer.AppendProtoAsArrayOfBytes(response);
537 return dbus_response;
538}
539
540std::unique_ptr<dbus::Response> Manager::OnArcVmShutdown(
541 dbus::MethodCall* method_call) {
542 LOG(INFO) << "ARCVM shutting down";
543
544 std::unique_ptr<dbus::Response> dbus_response(
545 dbus::Response::FromMethodCall(method_call));
546
547 dbus::MessageReader reader(method_call);
548 dbus::MessageWriter writer(dbus_response.get());
549
550 patchpanel::ArcVmShutdownRequest request;
551 patchpanel::ArcVmShutdownResponse response;
552
553 if (!reader.PopArrayOfBytesAsProto(&request)) {
554 LOG(ERROR) << "Unable to parse request";
555 writer.AppendProtoAsArrayOfBytes(response);
556 return dbus_response;
557 }
558
Garrick Evans21173b12019-11-20 15:23:16 +0900559 StopArcVm(request.cid());
Garrick Evanse94a14e2019-11-11 10:32:13 +0900560
Garrick Evans08843932019-09-17 14:41:08 +0900561 writer.AppendProtoAsArrayOfBytes(response);
562 return dbus_response;
563}
564
Garrick Evans47c19272019-11-21 10:58:21 +0900565std::unique_ptr<dbus::Response> Manager::OnTerminaVmStartup(
566 dbus::MethodCall* method_call) {
567 LOG(INFO) << "Termina VM starting up";
568
569 std::unique_ptr<dbus::Response> dbus_response(
570 dbus::Response::FromMethodCall(method_call));
571
572 dbus::MessageReader reader(method_call);
573 dbus::MessageWriter writer(dbus_response.get());
574
575 patchpanel::TerminaVmStartupRequest request;
576 patchpanel::TerminaVmStartupResponse response;
577
578 if (!reader.PopArrayOfBytesAsProto(&request)) {
579 LOG(ERROR) << "Unable to parse request";
580 writer.AppendProtoAsArrayOfBytes(response);
581 return dbus_response;
582 }
583
584 const int32_t cid = request.cid();
Garrick Evans53a2a982020-02-05 10:53:35 +0900585 if (!StartCrosVm(cid, GuestMessage::TERMINA_VM)) {
Garrick Evans47c19272019-11-21 10:58:21 +0900586 LOG(ERROR) << "Failed to start Termina VM network service";
587 writer.AppendProtoAsArrayOfBytes(response);
588 return dbus_response;
589 }
590
Garrick Evans51d5b552020-01-30 10:42:06 +0900591 const auto* const tap = cros_svc_->TAP(cid, true /*is_termina*/);
Garrick Evansb1c93712020-01-22 09:28:25 +0900592 if (!tap) {
593 LOG(DFATAL) << "TAP device missing";
594 writer.AppendProtoAsArrayOfBytes(response);
595 return dbus_response;
596 }
Garrick Evans47c19272019-11-21 10:58:21 +0900597
Garrick Evansb1c93712020-01-22 09:28:25 +0900598 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900599 dev->set_ifname(tap->host_ifname());
600 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900601 if (!subnet) {
602 LOG(DFATAL) << "Missing required subnet for {cid: " << cid << "}";
603 writer.AppendProtoAsArrayOfBytes(response);
604 return dbus_response;
605 }
606 auto* resp_subnet = dev->mutable_ipv4_subnet();
607 resp_subnet->set_base_addr(subnet->BaseAddress());
608 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900609 subnet = tap->config().lxd_ipv4_subnet();
Garrick Evansb1c93712020-01-22 09:28:25 +0900610 if (!subnet) {
611 LOG(DFATAL) << "Missing required lxd subnet for {cid: " << cid << "}";
612 writer.AppendProtoAsArrayOfBytes(response);
613 return dbus_response;
614 }
615 resp_subnet = response.mutable_container_subnet();
616 resp_subnet->set_base_addr(subnet->BaseAddress());
617 resp_subnet->set_prefix_len(subnet->PrefixLength());
Garrick Evans47c19272019-11-21 10:58:21 +0900618
619 writer.AppendProtoAsArrayOfBytes(response);
620 return dbus_response;
621}
622
623std::unique_ptr<dbus::Response> Manager::OnTerminaVmShutdown(
624 dbus::MethodCall* method_call) {
625 LOG(INFO) << "Termina VM shutting down";
626
627 std::unique_ptr<dbus::Response> dbus_response(
628 dbus::Response::FromMethodCall(method_call));
629
630 dbus::MessageReader reader(method_call);
631 dbus::MessageWriter writer(dbus_response.get());
632
633 patchpanel::TerminaVmShutdownRequest request;
634 patchpanel::TerminaVmShutdownResponse response;
635
636 if (!reader.PopArrayOfBytesAsProto(&request)) {
637 LOG(ERROR) << "Unable to parse request";
638 writer.AppendProtoAsArrayOfBytes(response);
639 return dbus_response;
640 }
641
Garrick Evans51d5b552020-01-30 10:42:06 +0900642 StopCrosVm(request.cid(), GuestMessage::TERMINA_VM);
643
644 writer.AppendProtoAsArrayOfBytes(response);
645 return dbus_response;
646}
647
648std::unique_ptr<dbus::Response> Manager::OnPluginVmStartup(
649 dbus::MethodCall* method_call) {
650 LOG(INFO) << "Plugin VM starting up";
651
652 std::unique_ptr<dbus::Response> dbus_response(
653 dbus::Response::FromMethodCall(method_call));
654
655 dbus::MessageReader reader(method_call);
656 dbus::MessageWriter writer(dbus_response.get());
657
658 patchpanel::PluginVmStartupRequest request;
659 patchpanel::PluginVmStartupResponse response;
660
661 if (!reader.PopArrayOfBytesAsProto(&request)) {
662 LOG(ERROR) << "Unable to parse request";
663 writer.AppendProtoAsArrayOfBytes(response);
664 return dbus_response;
665 }
666
Garrick Evans08fb34b2020-02-20 10:50:17 +0900667 const uint64_t vm_id = request.id();
Garrick Evans53a2a982020-02-05 10:53:35 +0900668 if (!StartCrosVm(vm_id, GuestMessage::PLUGIN_VM, request.subnet_index())) {
Garrick Evans51d5b552020-01-30 10:42:06 +0900669 LOG(ERROR) << "Failed to start Plugin VM network service";
670 writer.AppendProtoAsArrayOfBytes(response);
671 return dbus_response;
672 }
673
674 const auto* const tap = cros_svc_->TAP(vm_id, false /*is_termina*/);
675 if (!tap) {
676 LOG(DFATAL) << "TAP device missing";
677 writer.AppendProtoAsArrayOfBytes(response);
678 return dbus_response;
679 }
680
Garrick Evans51d5b552020-01-30 10:42:06 +0900681 auto* dev = response.mutable_device();
Garrick Evans6c7dcb82020-03-16 15:21:05 +0900682 dev->set_ifname(tap->host_ifname());
683 const auto* subnet = tap->config().ipv4_subnet();
Garrick Evans51d5b552020-01-30 10:42:06 +0900684 if (!subnet) {
685 LOG(DFATAL) << "Missing required subnet for {cid: " << vm_id << "}";
686 writer.AppendProtoAsArrayOfBytes(response);
687 return dbus_response;
688 }
689 auto* resp_subnet = dev->mutable_ipv4_subnet();
690 resp_subnet->set_base_addr(subnet->BaseAddress());
691 resp_subnet->set_prefix_len(subnet->PrefixLength());
692
693 writer.AppendProtoAsArrayOfBytes(response);
694 return dbus_response;
695}
696
697std::unique_ptr<dbus::Response> Manager::OnPluginVmShutdown(
698 dbus::MethodCall* method_call) {
699 LOG(INFO) << "Plugin VM shutting down";
700
701 std::unique_ptr<dbus::Response> dbus_response(
702 dbus::Response::FromMethodCall(method_call));
703
704 dbus::MessageReader reader(method_call);
705 dbus::MessageWriter writer(dbus_response.get());
706
707 patchpanel::PluginVmShutdownRequest request;
708 patchpanel::PluginVmShutdownResponse response;
709
710 if (!reader.PopArrayOfBytesAsProto(&request)) {
711 LOG(ERROR) << "Unable to parse request";
712 writer.AppendProtoAsArrayOfBytes(response);
713 return dbus_response;
714 }
715
716 StopCrosVm(request.id(), GuestMessage::PLUGIN_VM);
Garrick Evans47c19272019-11-21 10:58:21 +0900717
718 writer.AppendProtoAsArrayOfBytes(response);
719 return dbus_response;
720}
721
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900722std::unique_ptr<dbus::Response> Manager::OnSetVpnIntent(
723 dbus::MethodCall* method_call) {
724 std::unique_ptr<dbus::Response> dbus_response(
725 dbus::Response::FromMethodCall(method_call));
726
727 dbus::MessageReader reader(method_call);
728 dbus::MessageWriter writer(dbus_response.get());
729
730 patchpanel::SetVpnIntentRequest request;
731 patchpanel::SetVpnIntentResponse response;
732
733 bool success = reader.PopArrayOfBytesAsProto(&request);
734 if (!success) {
735 LOG(ERROR) << "Unable to parse SetVpnIntentRequest";
736 // Do not return yet to make sure we close the received fd.
737 }
738
739 base::ScopedFD client_socket;
740 reader.PopFileDescriptor(&client_socket);
741
742 if (success)
743 success = routing_svc_->SetVpnFwmark(client_socket.get(), request.policy());
744
745 response.set_success(success);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900746
747 writer.AppendProtoAsArrayOfBytes(response);
748 return dbus_response;
749}
750
751std::unique_ptr<dbus::Response> Manager::OnConnectNamespace(
752 dbus::MethodCall* method_call) {
753 std::unique_ptr<dbus::Response> dbus_response(
754 dbus::Response::FromMethodCall(method_call));
755
756 dbus::MessageReader reader(method_call);
757 dbus::MessageWriter writer(dbus_response.get());
758
759 patchpanel::ConnectNamespaceRequest request;
760 patchpanel::ConnectNamespaceResponse response;
761
Hugo Benichicc6850f2020-01-17 13:26:06 +0900762 bool success = true;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900763 if (!reader.PopArrayOfBytesAsProto(&request)) {
Hugo Benichicc6850f2020-01-17 13:26:06 +0900764 LOG(ERROR) << "Unable to parse ConnectNamespaceRequest";
765 // Do not return yet to make sure we close the received fd and
766 // validate other arguments.
767 success = false;
Hugo Benichib56b77c2020-01-15 16:00:56 +0900768 }
769
Hugo Benichicc6850f2020-01-17 13:26:06 +0900770 base::ScopedFD client_fd;
771 reader.PopFileDescriptor(&client_fd);
772 if (!client_fd.is_valid()) {
773 LOG(ERROR) << "ConnectNamespaceRequest: invalid file descriptor";
774 success = false;
775 }
776
777 pid_t pid = request.pid();
778 {
779 ScopedNS ns(pid);
780 if (!ns.IsValid()) {
781 LOG(ERROR) << "ConnectNamespaceRequest: invalid namespace pid " << pid;
782 success = false;
783 }
784 }
785
786 const std::string& outbound_ifname = request.outbound_physical_device();
787 if (!outbound_ifname.empty() && !shill_client_->has_device(outbound_ifname)) {
788 LOG(ERROR) << "ConnectNamespaceRequest: invalid outbound ifname "
789 << outbound_ifname;
790 success = false;
791 }
792
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900793 if (success)
794 ConnectNamespace(std::move(client_fd), request, response);
Hugo Benichib56b77c2020-01-15 16:00:56 +0900795
Hugo Benichi7d9d8db2020-03-30 15:56:56 +0900796 writer.AppendProtoAsArrayOfBytes(response);
797 return dbus_response;
798}
799
Jie Jiang493cde42020-07-17 21:43:39 +0900800std::unique_ptr<dbus::Response> Manager::OnGetTrafficCounters(
801 dbus::MethodCall* method_call) {
802 std::unique_ptr<dbus::Response> dbus_response(
803 dbus::Response::FromMethodCall(method_call));
804
805 dbus::MessageReader reader(method_call);
806 dbus::MessageWriter writer(dbus_response.get());
807
808 patchpanel::TrafficCountersRequest request;
809 patchpanel::TrafficCountersResponse response;
810
811 if (!reader.PopArrayOfBytesAsProto(&request)) {
812 LOG(ERROR) << "Unable to parse TrafficCountersRequest";
813 writer.AppendProtoAsArrayOfBytes(response);
814 return dbus_response;
815 }
816
817 const std::set<std::string> devices{request.devices().begin(),
818 request.devices().end()};
819 const auto counters = counters_svc_->GetCounters(devices);
820 for (const auto& kv : counters) {
821 auto* traffic_counter = response.add_counters();
822 const auto& source_and_device = kv.first;
823 const auto& counter = kv.second;
824 traffic_counter->set_source(source_and_device.first);
825 traffic_counter->set_device(source_and_device.second);
826 traffic_counter->set_rx_bytes(counter.rx_bytes);
827 traffic_counter->set_rx_packets(counter.rx_packets);
828 traffic_counter->set_tx_bytes(counter.tx_bytes);
829 traffic_counter->set_tx_packets(counter.tx_packets);
830 }
831
832 writer.AppendProtoAsArrayOfBytes(response);
833 return dbus_response;
834}
835
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900836std::unique_ptr<dbus::Response> Manager::OnModifyPortRule(
837 dbus::MethodCall* method_call) {
838 std::unique_ptr<dbus::Response> dbus_response(
839 dbus::Response::FromMethodCall(method_call));
840
841 dbus::MessageReader reader(method_call);
842 dbus::MessageWriter writer(dbus_response.get());
843
844 patchpanel::ModifyPortRuleRequest request;
845 patchpanel::ModifyPortRuleResponse response;
846
847 if (!reader.PopArrayOfBytesAsProto(&request)) {
848 LOG(ERROR) << "Unable to parse ModifyPortRequest";
849 writer.AppendProtoAsArrayOfBytes(response);
850 return dbus_response;
851 }
852
Jason Jeremy Imanc28df852020-07-11 17:38:26 +0900853 response.set_success(ModifyPortRule(request));
Jason Jeremy Imanb2a421e2020-07-04 20:48:32 +0900854 writer.AppendProtoAsArrayOfBytes(response);
855 return dbus_response;
856}
857
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900858void Manager::ConnectNamespace(
859 base::ScopedFD client_fd,
860 const patchpanel::ConnectNamespaceRequest& request,
861 patchpanel::ConnectNamespaceResponse& response) {
862 std::unique_ptr<Subnet> subnet =
863 addr_mgr_.AllocateIPv4Subnet(AddressManager::Guest::MINIJAIL_NETNS);
864 if (!subnet) {
865 LOG(ERROR) << "ConnectNamespaceRequest: exhausted IPv4 subnet space";
866 return;
867 }
868
869 const std::string ifname_id = std::to_string(connected_namespaces_next_id_);
Hugo Benichi33860d72020-07-09 16:34:01 +0900870 const std::string netns_name = "connected_netns_" + ifname_id;
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900871 const std::string host_ifname = "arc_ns" + ifname_id;
872 const std::string client_ifname = "veth" + ifname_id;
Hugo Benichie8758b52020-04-03 14:49:01 +0900873 const uint32_t host_ipv4_addr = subnet->AddressAtOffset(0);
874 const uint32_t client_ipv4_addr = subnet->AddressAtOffset(1);
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900875
Hugo Benichie8758b52020-04-03 14:49:01 +0900876 // Veth interface configuration and client routing configuration:
Hugo Benichi33860d72020-07-09 16:34:01 +0900877 // - attach a name to the client namespace.
878 // - create veth pair across the current namespace and the client namespace.
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900879 // - configure IPv4 address on remote veth inside client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +0900880 // - configure IPv4 address on local veth inside host namespace.
881 // - add a default IPv4 /0 route sending traffic to that remote veth.
Hugo Benichie8758b52020-04-03 14:49:01 +0900882 pid_t pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +0900883 if (!datapath_->NetnsAttachName(netns_name, pid)) {
884 LOG(ERROR) << "ConnectNamespaceRequest: failed to attach name "
885 << netns_name << " to namespace pid " << pid;
886 return;
887 }
888 if (!datapath_->ConnectVethPair(pid, netns_name, host_ifname, client_ifname,
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900889 addr_mgr_.GenerateMacAddress(),
890 client_ipv4_addr, subnet->PrefixLength(),
891 false /* enable_multicast */)) {
Hugo Benichie8758b52020-04-03 14:49:01 +0900892 LOG(ERROR) << "ConnectNamespaceRequest: failed to create veth pair for "
893 "namespace pid "
894 << pid;
Hugo Benichi33860d72020-07-09 16:34:01 +0900895 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900896 return;
897 }
898 if (!datapath_->ConfigureInterface(
899 host_ifname, addr_mgr_.GenerateMacAddress(), host_ipv4_addr,
900 subnet->PrefixLength(), true /* link up */,
901 false /* enable_multicast */)) {
902 LOG(ERROR) << "ConnectNamespaceRequest: cannot configure host interface "
903 << host_ifname;
904 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900905 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900906 return;
907 }
Hugo Benichi33860d72020-07-09 16:34:01 +0900908 bool peer_route_setup_success;
Hugo Benichie8758b52020-04-03 14:49:01 +0900909 {
910 ScopedNS ns(pid);
Hugo Benichi33860d72020-07-09 16:34:01 +0900911 peer_route_setup_success =
912 ns.IsValid() &&
913 datapath_->AddIPv4Route(host_ipv4_addr, INADDR_ANY, INADDR_ANY);
914 }
915 if (!peer_route_setup_success) {
916 LOG(ERROR) << "ConnectNamespaceRequest: failed to add default /0 route to "
917 << host_ifname << " inside namespace pid " << pid;
918 datapath_->RemoveInterface(host_ifname);
919 datapath_->NetnsDeleteName(netns_name);
920 return;
Hugo Benichie8758b52020-04-03 14:49:01 +0900921 }
922
923 // Host namespace routing configuration
924 // - ingress: add route to client subnet via |host_ifname|.
925 // - egress: - allow forwarding for traffic outgoing |host_ifname|.
926 // - add SNAT mark 0x1/0x1 for traffic outgoing |host_ifname|.
927 // Note that by default unsolicited ingress traffic is not forwarded to the
928 // client namespace unless the client specifically set port forwarding
929 // through permission_broker DBus APIs.
930 // TODO(hugobenichi) If allow_user_traffic is false, then prevent forwarding
931 // both ways between client namespace and other guest containers and VMs.
932 // TODO(hugobenichi) If outbound_physical_device is defined, then set strong
933 // routing to that interface routing table.
934 if (!datapath_->AddIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
935 subnet->Netmask())) {
936 LOG(ERROR)
937 << "ConnectNamespaceRequest: failed to set route to client namespace";
938 datapath_->RemoveInterface(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900939 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900940 return;
941 }
942 if (!datapath_->AddOutboundIPv4(host_ifname)) {
943 LOG(ERROR) << "ConnectNamespaceRequest: failed to allow FORWARD for "
944 "traffic outgoing from "
945 << host_ifname;
946 datapath_->RemoveInterface(host_ifname);
947 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
948 subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +0900949 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900950 return;
951 }
952 if (!datapath_->AddOutboundIPv4SNATMark(host_ifname)) {
953 LOG(ERROR) << "ConnectNamespaceRequest: failed to set SNAT for traffic "
954 "outgoing from "
955 << host_ifname;
956 datapath_->RemoveInterface(host_ifname);
957 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
958 subnet->Netmask());
959 datapath_->RemoveOutboundIPv4(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900960 datapath_->NetnsDeleteName(netns_name);
Hugo Benichie8758b52020-04-03 14:49:01 +0900961 return;
962 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900963
Hugo Benichi7352ad92020-04-07 16:11:59 +0900964 // Dup the client fd into our own: this guarantees that the fd number will
965 // be stable and tied to the actual kernel resources used by the client.
966 base::ScopedFD local_client_fd(dup(client_fd.get()));
967 if (!local_client_fd.is_valid()) {
968 PLOG(ERROR) << "ConnectNamespaceRequest: failed to dup() client fd";
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
978 // Add the dupe fd to the epoll watcher.
979 // TODO(hugobenichi) Find a way to reuse base::FileDescriptorWatcher for
980 // listening to EPOLLHUP.
981 struct epoll_event epevent;
982 epevent.events = EPOLLIN; // EPOLLERR | EPOLLHUP are always waited for.
983 epevent.data.fd = local_client_fd.get();
984 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_ADD,
985 local_client_fd.get(), &epevent) != 0) {
986 PLOG(ERROR) << "ConnectNamespaceResponse: epoll_ctl(EPOLL_CTL_ADD) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +0900987 datapath_->RemoveInterface(host_ifname);
988 datapath_->DeleteIPv4Route(host_ipv4_addr, subnet->BaseAddress(),
989 subnet->Netmask());
990 datapath_->RemoveOutboundIPv4(host_ifname);
991 datapath_->RemoveOutboundIPv4SNATMark(host_ifname);
Hugo Benichi33860d72020-07-09 16:34:01 +0900992 datapath_->NetnsDeleteName(netns_name);
Hugo Benichi7352ad92020-04-07 16:11:59 +0900993 return;
994 }
995
Hugo Benichiadf1ec52020-01-17 16:23:58 +0900996 // Prepare the response before storing ConnectNamespaceInfo.
Hugo Benichi2fd0c6e2020-04-17 16:12:05 +0900997 response.set_peer_ifname(client_ifname);
998 response.set_peer_ipv4_address(host_ipv4_addr);
999 response.set_host_ifname(host_ifname);
1000 response.set_host_ipv4_address(client_ipv4_addr);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001001 auto* response_subnet = response.mutable_ipv4_subnet();
1002 response_subnet->set_base_addr(subnet->BaseAddress());
1003 response_subnet->set_prefix_len(subnet->PrefixLength());
1004
1005 // Store ConnectNamespaceInfo
1006 connected_namespaces_next_id_++;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001007 int fdkey = local_client_fd.release();
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001008 connected_namespaces_[fdkey] = {};
1009 ConnectNamespaceInfo& ns_info = connected_namespaces_[fdkey];
1010 ns_info.pid = request.pid();
Hugo Benichi33860d72020-07-09 16:34:01 +09001011 ns_info.netns_name = std::move(netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001012 ns_info.outbound_ifname = request.outbound_physical_device();
1013 ns_info.host_ifname = std::move(host_ifname);
1014 ns_info.client_ifname = std::move(client_ifname);
1015 ns_info.client_subnet = std::move(subnet);
1016
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001017 LOG(INFO) << "Connected network namespace " << ns_info;
Hugo Benichi7352ad92020-04-07 16:11:59 +09001018
1019 if (connected_namespaces_.size() == 1) {
1020 LOG(INFO) << "Starting ConnectNamespace client fds monitoring";
1021 CheckConnectedNamespaces();
1022 }
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001023}
1024
1025void Manager::DisconnectNamespace(int client_fd) {
1026 auto it = connected_namespaces_.find(client_fd);
1027 if (it == connected_namespaces_.end()) {
1028 LOG(ERROR) << "No ConnectNamespaceInfo found for client_fd " << client_fd;
1029 return;
1030 }
1031
Hugo Benichi7352ad92020-04-07 16:11:59 +09001032 // Remove the client fd dupe from the epoll watcher and close it.
1033 if (epoll_ctl(connected_namespaces_epollfd_, EPOLL_CTL_DEL, client_fd,
Hugo Benichie8758b52020-04-03 14:49:01 +09001034 nullptr) != 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001035 PLOG(ERROR) << "DisconnectNamespace: epoll_ctl(EPOLL_CTL_DEL) failed";
Hugo Benichie8758b52020-04-03 14:49:01 +09001036 if (close(client_fd) < 0)
Hugo Benichi7352ad92020-04-07 16:11:59 +09001037 PLOG(ERROR) << "DisconnectNamespace: close(client_fd) failed";
Hugo Benichi7352ad92020-04-07 16:11:59 +09001038
Hugo Benichie8758b52020-04-03 14:49:01 +09001039 // Destroy the interface configuration and routing configuration:
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001040 // - destroy veth pair.
Hugo Benichie8758b52020-04-03 14:49:01 +09001041 // - remove forwarding rules on host namespace.
1042 // - remove SNAT marking rule on host namespace.
Hugo Benichi33860d72020-07-09 16:34:01 +09001043 // Delete the network namespace attached to the client namespace.
Hugo Benichie8758b52020-04-03 14:49:01 +09001044 // Note that the default route set inside the client namespace by patchpanel
1045 // is not destroyed: it is assumed the client will also teardown its
1046 // namespace if it triggered DisconnectNamespace.
1047 datapath_->RemoveInterface(it->second.host_ifname);
1048 datapath_->RemoveOutboundIPv4(it->second.host_ifname);
1049 datapath_->RemoveOutboundIPv4SNATMark(it->second.host_ifname);
1050 datapath_->DeleteIPv4Route(it->second.client_subnet->AddressAtOffset(0),
1051 it->second.client_subnet->BaseAddress(),
1052 it->second.client_subnet->Netmask());
Hugo Benichi33860d72020-07-09 16:34:01 +09001053 datapath_->NetnsDeleteName(it->second.netns_name);
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001054
1055 LOG(INFO) << "Disconnected network namespace " << it->second;
1056
1057 // This release the allocated IPv4 subnet.
1058 connected_namespaces_.erase(it);
1059}
1060
Hugo Benichi7352ad92020-04-07 16:11:59 +09001061// TODO(hugobenichi) Generalize this check to all resources created by
1062// patchpanel on behalf of a remote client.
1063void Manager::CheckConnectedNamespaces() {
1064 int max_event = 10;
1065 struct epoll_event epevents[max_event];
1066 int nready = epoll_wait(connected_namespaces_epollfd_, epevents, max_event,
1067 0 /* do not block */);
1068 if (nready < 0)
1069 PLOG(ERROR) << "CheckConnectedNamespaces: epoll_wait(0) failed";
1070
1071 for (int i = 0; i < nready; i++)
1072 if (epevents[i].events & (EPOLLHUP | EPOLLERR))
1073 DisconnectNamespace(epevents[i].data.fd);
1074
1075 if (connected_namespaces_.empty()) {
1076 LOG(INFO) << "Stopping ConnectNamespace client fds monitoring";
1077 return;
1078 }
1079
Qijiang Fan2d7aeb42020-05-19 02:06:39 +09001080 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
Hugo Benichi7352ad92020-04-07 16:11:59 +09001081 FROM_HERE,
1082 base::Bind(&Manager::CheckConnectedNamespaces,
Hugo Benichie8758b52020-04-03 14:49:01 +09001083 weak_factory_.GetWeakPtr()),
Hugo Benichi7352ad92020-04-07 16:11:59 +09001084 kConnectNamespaceCheckInterval);
1085}
1086
Jason Jeremy Imanc28df852020-07-11 17:38:26 +09001087bool Manager::ModifyPortRule(const patchpanel::ModifyPortRuleRequest& request) {
1088 switch (request.proto()) {
1089 case patchpanel::ModifyPortRuleRequest::TCP:
1090 case patchpanel::ModifyPortRuleRequest::UDP:
1091 break;
1092 default:
1093 LOG(ERROR) << "Unknown protocol " << request.proto();
1094 return false;
1095 }
1096
1097 switch (request.op()) {
1098 case patchpanel::ModifyPortRuleRequest::CREATE:
1099 switch (request.type()) {
1100 case patchpanel::ModifyPortRuleRequest::ACCESS:
1101 return firewall_.AddAcceptRules(request.proto(),
1102 request.input_dst_port(),
1103 request.input_ifname());
1104 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1105 return firewall_.AddLoopbackLockdownRules(request.proto(),
1106 request.input_dst_port());
1107 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1108 return firewall_.AddIpv4ForwardRule(
1109 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1110 request.input_ifname(), request.dst_ip(), request.dst_port());
1111 default:
1112 LOG(ERROR) << "Unknown port rule type " << request.type();
1113 return false;
1114 }
1115 case patchpanel::ModifyPortRuleRequest::DELETE:
1116 switch (request.type()) {
1117 case patchpanel::ModifyPortRuleRequest::ACCESS:
1118 return firewall_.DeleteAcceptRules(request.proto(),
1119 request.input_dst_port(),
1120 request.input_ifname());
1121 case patchpanel::ModifyPortRuleRequest::LOCKDOWN:
1122 return firewall_.DeleteLoopbackLockdownRules(
1123 request.proto(), request.input_dst_port());
1124 case patchpanel::ModifyPortRuleRequest::FORWARDING:
1125 return firewall_.DeleteIpv4ForwardRule(
1126 request.proto(), request.input_dst_ip(), request.input_dst_port(),
1127 request.input_ifname(), request.dst_ip(), request.dst_port());
1128 default:
1129 LOG(ERROR) << "Unknown port rule type " << request.type();
1130 return false;
1131 }
1132 default:
1133 LOG(ERROR) << "Unknown operation " << request.op();
1134 return false;
1135 }
1136}
1137
Garrick Evanse94a14e2019-11-11 10:32:13 +09001138void Manager::SendGuestMessage(const GuestMessage& msg) {
Garrick Evans96e03042019-05-28 14:30:52 +09001139 IpHelperMessage ipm;
1140 *ipm.mutable_guest_message() = msg;
Garrick Evans96e03042019-05-28 14:30:52 +09001141 adb_proxy_->SendMessage(ipm);
Garrick Evanse94a14e2019-11-11 10:32:13 +09001142 mcast_proxy_->SendMessage(ipm);
1143 nd_proxy_->SendMessage(ipm);
Garrick Evans96e03042019-05-28 14:30:52 +09001144}
1145
Garrick Evans4ac09852020-01-16 14:09:22 +09001146void Manager::StartForwarding(const std::string& ifname_physical,
1147 const std::string& ifname_virtual,
Garrick Evans4ac09852020-01-16 14:09:22 +09001148 bool ipv6,
1149 bool multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001150 if (ifname_physical.empty() || ifname_virtual.empty())
Garrick Evans4ac09852020-01-16 14:09:22 +09001151 return;
1152
1153 IpHelperMessage ipm;
1154 DeviceMessage* msg = ipm.mutable_device_message();
1155 msg->set_dev_ifname(ifname_physical);
Garrick Evans4ac09852020-01-16 14:09:22 +09001156 msg->set_br_ifname(ifname_virtual);
1157
1158 if (ipv6) {
1159 LOG(INFO) << "Starting IPv6 forwarding from " << ifname_physical << " to "
1160 << ifname_virtual;
1161
1162 if (!datapath_->AddIPv6Forwarding(ifname_physical, ifname_virtual)) {
1163 LOG(ERROR) << "Failed to setup iptables forwarding rule for IPv6 from "
1164 << ifname_physical << " to " << ifname_virtual;
1165 }
1166 if (!datapath_->MaskInterfaceFlags(ifname_physical, IFF_ALLMULTI)) {
1167 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1168 << ifname_physical;
1169 }
1170 if (!datapath_->MaskInterfaceFlags(ifname_virtual, IFF_ALLMULTI)) {
1171 LOG(WARNING) << "Failed to setup all multicast mode for interface "
1172 << ifname_virtual;
1173 }
1174 nd_proxy_->SendMessage(ipm);
1175 }
1176
1177 if (multicast) {
1178 LOG(INFO) << "Starting multicast forwarding from " << ifname_physical
1179 << " to " << ifname_virtual;
1180 mcast_proxy_->SendMessage(ipm);
1181 }
1182}
1183
1184void Manager::StopForwarding(const std::string& ifname_physical,
1185 const std::string& ifname_virtual,
1186 bool ipv6,
1187 bool multicast) {
1188 if (ifname_physical.empty())
1189 return;
1190
1191 IpHelperMessage ipm;
1192 DeviceMessage* msg = ipm.mutable_device_message();
1193 msg->set_dev_ifname(ifname_physical);
1194 msg->set_teardown(true);
Taoyu Li7dca19a2020-03-16 16:27:07 +09001195 if (!ifname_virtual.empty()) {
1196 msg->set_br_ifname(ifname_virtual);
1197 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001198
1199 if (ipv6) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001200 if (ifname_virtual.empty()) {
1201 LOG(INFO) << "Stopping IPv6 forwarding on " << ifname_physical;
1202 } else {
1203 LOG(INFO) << "Stopping IPv6 forwarding from " << ifname_physical << " to "
1204 << ifname_virtual;
1205 datapath_->RemoveIPv6Forwarding(ifname_physical, ifname_virtual);
1206 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001207 nd_proxy_->SendMessage(ipm);
1208 }
1209
1210 if (multicast) {
Taoyu Li7dca19a2020-03-16 16:27:07 +09001211 if (ifname_virtual.empty()) {
1212 LOG(INFO) << "Stopping multicast forwarding on " << ifname_physical;
1213 } else {
1214 LOG(INFO) << "Stopping multicast forwarding from " << ifname_physical
1215 << " to " << ifname_virtual;
1216 }
Garrick Evans4ac09852020-01-16 14:09:22 +09001217 mcast_proxy_->SendMessage(ipm);
1218 }
1219}
1220
Garrick Evans4ac09852020-01-16 14:09:22 +09001221void Manager::OnDeviceMessageFromNDProxy(const DeviceMessage& msg) {
1222 LOG_IF(DFATAL, msg.dev_ifname().empty())
1223 << "Received DeviceMessage w/ empty dev_ifname";
1224
1225 if (!datapath_->AddIPv6HostRoute(msg.dev_ifname(), msg.guest_ip6addr(),
1226 128)) {
1227 LOG(WARNING) << "Failed to setup the IPv6 route for interface "
1228 << msg.dev_ifname();
1229 }
1230}
1231
Hugo Benichiadf1ec52020-01-17 16:23:58 +09001232std::ostream& operator<<(std::ostream& stream,
1233 const Manager::ConnectNamespaceInfo& ns_info) {
1234 stream << "{ pid: " << ns_info.pid;
1235 if (!ns_info.outbound_ifname.empty()) {
1236 stream << ", outbound_ifname: " << ns_info.outbound_ifname;
1237 }
1238 stream << ", host_ifname: " << ns_info.host_ifname
1239 << ", client_ifname: " << ns_info.client_ifname
1240 << ", subnet: " << ns_info.client_subnet->ToCidrString() << '}';
1241 return stream;
1242}
1243
Garrick Evans3388a032020-03-24 11:25:55 +09001244} // namespace patchpanel