1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 #include "components/nacl/browser/nacl_process_host.h"
11
12 #include <string.h>
13
14 #include <algorithm>
15 #include <memory>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include "base/base_switches.h"
21 #include "base/command_line.h"
22 #include "base/feature_list.h"
23 #include "base/files/file_util.h"
24 #include "base/functional/bind.h"
25 #include "base/location.h"
26 #include "base/metrics/histogram_macros.h"
27 #include "base/path_service.h"
28 #include "base/process/launch.h"
29 #include "base/process/process_iterator.h"
30 #include "base/rand_util.h"
31 #include "base/strings/string_number_conversions.h"
32 #include "base/strings/string_split.h"
33 #include "base/strings/string_util.h"
34 #include "base/strings/stringprintf.h"
35 #include "base/strings/utf_string_conversions.h"
36 #include "base/sys_byteorder.h"
37 #include "base/task/single_thread_task_runner.h"
38 #include "base/task/thread_pool.h"
39 #include "build/build_config.h"
40 #include "build/chromeos_buildflags.h"
41 #include "components/nacl/browser/nacl_browser.h"
42 #include "components/nacl/browser/nacl_browser_delegate.h"
43 #include "components/nacl/browser/nacl_host_message_filter.h"
44 #include "components/nacl/common/nacl_cmd_line.h"
45 #include "components/nacl/common/nacl_constants.h"
46 #include "components/nacl/common/nacl_host_messages.h"
47 #include "components/nacl/common/nacl_messages.h"
48 #include "components/nacl/common/nacl_process_type.h"
49 #include "components/nacl/common/nacl_switches.h"
50 #include "components/url_formatter/url_formatter.h"
51 #include "content/public/browser/browser_child_process_host.h"
52 #include "content/public/browser/browser_ppapi_host.h"
53 #include "content/public/browser/child_process_data.h"
54 #include "content/public/browser/child_process_host.h"
55 #include "content/public/browser/plugin_service.h"
56 #include "content/public/browser/render_process_host.h"
57 #include "content/public/browser/web_contents.h"
58 #include "content/public/common/content_switches.h"
59 #include "content/public/common/process_type.h"
60 #include "content/public/common/sandboxed_process_launcher_delegate.h"
61 #include "content/public/common/zygote/zygote_buildflags.h"
62 #include "ipc/ipc_channel.h"
63 #include "mojo/public/cpp/system/invitation.h"
64 #include "net/socket/socket_descriptor.h"
65 #include "ppapi/host/host_factory.h"
66 #include "ppapi/host/ppapi_host.h"
67 #include "ppapi/proxy/ppapi_messages.h"
68 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
69 #include "sandbox/policy/mojom/sandbox.mojom.h"
70 #include "sandbox/policy/switches.h"
71
72 #if BUILDFLAG(USE_ZYGOTE)
73 #include "content/public/common/zygote/zygote_handle.h" // nogncheck
74 #endif // BUILDFLAG(USE_ZYGOTE)
75
76 #if BUILDFLAG(IS_POSIX)
77
78 #include <arpa/inet.h>
79 #include <fcntl.h>
80 #include <netinet/in.h>
81 #include <sys/socket.h>
82
83 #endif
84
85 using content::BrowserThread;
86 using content::ChildProcessData;
87 using content::ChildProcessHost;
88 using ppapi::proxy::SerializedHandle;
89
90 namespace nacl {
91 namespace {
92
93 // NOTE: changes to this class need to be reviewed by the security team.
94 class NaClSandboxedProcessLauncherDelegate
95 : public content::SandboxedProcessLauncherDelegate {
96 public:
97 NaClSandboxedProcessLauncherDelegate() = default;
98
99 #if BUILDFLAG(USE_ZYGOTE)
GetZygote()100 content::ZygoteCommunication* GetZygote() override {
101 return content::GetGenericZygote();
102 }
103 #endif // BUILDFLAG(USE_ZYGOTE)
104
GetSandboxType()105 sandbox::mojom::Sandbox GetSandboxType() override {
106 return sandbox::mojom::Sandbox::kPpapi;
107 }
108 };
109
CloseFile(base::File file)110 void CloseFile(base::File file) {
111 // The base::File destructor will close the file for us.
112 }
113
114 } // namespace
115
NaClProcessHost(const GURL & manifest_url,base::File nexe_file,const NaClFileToken & nexe_token,const std::vector<NaClResourcePrefetchResult> & prefetched_resource_files,ppapi::PpapiPermissions permissions,uint32_t permission_bits,bool off_the_record,NaClAppProcessType process_type,const base::FilePath & profile_directory)116 NaClProcessHost::NaClProcessHost(
117 const GURL& manifest_url,
118 base::File nexe_file,
119 const NaClFileToken& nexe_token,
120 const std::vector<NaClResourcePrefetchResult>& prefetched_resource_files,
121 ppapi::PpapiPermissions permissions,
122 uint32_t permission_bits,
123 bool off_the_record,
124 NaClAppProcessType process_type,
125 const base::FilePath& profile_directory)
126 : manifest_url_(manifest_url),
127 nexe_file_(std::move(nexe_file)),
128 nexe_token_(nexe_token),
129 prefetched_resource_files_(prefetched_resource_files),
130 permissions_(permissions),
131 reply_msg_(nullptr),
132 enable_debug_stub_(false),
133 enable_crash_throttling_(false),
134 off_the_record_(off_the_record),
135 process_type_(process_type),
136 profile_directory_(profile_directory) {
137 process_ = content::BrowserChildProcessHost::Create(
138 static_cast<content::ProcessType>(PROCESS_TYPE_NACL_LOADER), this,
139 content::ChildProcessHost::IpcMode::kLegacy);
140 process_->SetMetricsName("NaCl Loader");
141
142 // Set the display name so the user knows what plugin the process is running.
143 // We aren't on the UI thread so getting the pref locale for language
144 // formatting isn't possible, so IDN will be lost, but this is probably OK
145 // for this use case.
146 process_->SetName(url_formatter::FormatUrl(manifest_url_));
147
148 enable_debug_stub_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
149 switches::kEnableNaClDebug);
150 DCHECK(process_type_ != kUnknownNaClProcessType);
151 enable_crash_throttling_ = process_type_ != kNativeNaClProcessType;
152 }
153
~NaClProcessHost()154 NaClProcessHost::~NaClProcessHost() {
155 // Report exit status only if the process was successfully started.
156 if (process_->GetData().GetProcess().IsValid()) {
157 content::ChildProcessTerminationInfo info =
158 process_->GetTerminationInfo(false /* known_dead */);
159 std::string message =
160 base::StringPrintf("NaCl process exited with status %i (0x%x)",
161 info.exit_code, info.exit_code);
162 if (info.exit_code == 0) {
163 VLOG(1) << message;
164 } else {
165 LOG(ERROR) << message;
166 }
167 NaClBrowser::GetInstance()->OnProcessEnd(process_->GetData().id);
168 }
169
170 for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
171 // The process failed to launch for some reason. Close resource file
172 // handles.
173 base::File file(IPC::PlatformFileForTransitToFile(
174 prefetched_resource_files_[i].file));
175 base::ThreadPool::PostTask(
176 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
177 base::BindOnce(&CloseFile, std::move(file)));
178 }
179 // Open files need to be closed on the blocking pool.
180 if (nexe_file_.IsValid()) {
181 base::ThreadPool::PostTask(
182 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
183 base::BindOnce(&CloseFile, std::move(nexe_file_)));
184 }
185
186 if (reply_msg_) {
187 // The process failed to launch for some reason.
188 // Don't keep the renderer hanging.
189 reply_msg_->set_reply_error();
190 nacl_host_message_filter_->Send(reply_msg_);
191 }
192 }
193
OnProcessCrashed(int exit_status)194 void NaClProcessHost::OnProcessCrashed(int exit_status) {
195 if (enable_crash_throttling_ &&
196 !base::CommandLine::ForCurrentProcess()->HasSwitch(
197 switches::kDisablePnaclCrashThrottling)) {
198 NaClBrowser::GetInstance()->OnProcessCrashed();
199 }
200 }
201
202 // This is called at browser startup.
203 // static
EarlyStartup()204 void NaClProcessHost::EarlyStartup() {
205 NaClBrowser::GetInstance()->EarlyStartup();
206 // Inform NaClBrowser that we exist and will have a debug port at some point.
207 // TODO(crbug.com/40118868): Revisit the macro expression once build flag switch
208 // of lacros-chrome is complete.
209 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
210 // Open the IRT file early to make sure that it isn't replaced out from
211 // under us by autoupdate.
212 NaClBrowser::GetInstance()->EnsureIrtAvailable();
213 #endif
214 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
215 std::string nacl_debug_mask =
216 cmd->GetSwitchValueASCII(switches::kNaClDebugMask);
217 // By default, exclude debugging SSH and the PNaCl translator.
218 // about::flags only allows empty flags as the default, so replace
219 // the empty setting with the default. To debug all apps, use a wild-card.
220 if (nacl_debug_mask.empty()) {
221 nacl_debug_mask = "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
222 }
223 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask);
224 }
225
Launch(NaClHostMessageFilter * nacl_host_message_filter,IPC::Message * reply_msg,const base::FilePath & manifest_path)226 void NaClProcessHost::Launch(
227 NaClHostMessageFilter* nacl_host_message_filter,
228 IPC::Message* reply_msg,
229 const base::FilePath& manifest_path) {
230 nacl_host_message_filter_ = nacl_host_message_filter;
231 reply_msg_ = reply_msg;
232 manifest_path_ = manifest_path;
233
234 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
235 // to too many crashes within a given time period.
236 if (enable_crash_throttling_ &&
237 !base::CommandLine::ForCurrentProcess()->HasSwitch(
238 switches::kDisablePnaclCrashThrottling) &&
239 NaClBrowser::GetInstance()->IsThrottled()) {
240 SendErrorToRenderer("Process creation was throttled due to excessive"
241 " crashes");
242 delete this;
243 return;
244 }
245
246 const base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
247 if (cmd->HasSwitch(switches::kNaClGdb) &&
248 !cmd->HasSwitch(switches::kEnableNaClDebug)) {
249 LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag";
250 }
251
252 // Start getting the IRT open asynchronously while we launch the NaCl process.
253 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
254 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
255 nacl_browser->EnsureAllResourcesAvailable();
256 if (!nacl_browser->IsOk()) {
257 SendErrorToRenderer("could not find all the resources needed"
258 " to launch the process");
259 delete this;
260 return;
261 }
262
263 // Launch the process
264 if (!LaunchSelLdr()) {
265 delete this;
266 }
267 }
268
OnChannelConnected(int32_t peer_pid)269 void NaClProcessHost::OnChannelConnected(int32_t peer_pid) {
270 if (!base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
271 switches::kNaClGdb).empty()) {
272 LaunchNaClGdb();
273 }
274 }
275
276 // Needed to handle sync messages in OnMessageReceived.
Send(IPC::Message * msg)277 bool NaClProcessHost::Send(IPC::Message* msg) {
278 return process_->Send(msg);
279 }
280
LaunchNaClGdb()281 void NaClProcessHost::LaunchNaClGdb() {
282 const base::CommandLine& command_line =
283 *base::CommandLine::ForCurrentProcess();
284 base::CommandLine::StringType nacl_gdb =
285 command_line.GetSwitchValueNative(switches::kNaClGdb);
286 // We don't support spaces inside arguments in --nacl-gdb switch.
287 base::CommandLine cmd_line(base::SplitString(
288 nacl_gdb, base::CommandLine::StringType(1, ' '),
289 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL));
290 cmd_line.AppendArg("--eval-command");
291 base::FilePath::StringType irt_path(
292 NaClBrowser::GetInstance()->GetIrtFilePath().value());
293 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
294 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
295 std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
296 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
297 FILE_PATH_LITERAL("\""));
298 if (!manifest_path_.empty()) {
299 cmd_line.AppendArg("--eval-command");
300 base::FilePath::StringType manifest_path_value(manifest_path_.value());
301 std::replace(manifest_path_value.begin(), manifest_path_value.end(),
302 '\\', '/');
303 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
304 manifest_path_value + FILE_PATH_LITERAL("\""));
305 }
306 cmd_line.AppendArg("--eval-command");
307 cmd_line.AppendArg("target remote :4014");
308 base::FilePath script =
309 command_line.GetSwitchValuePath(switches::kNaClGdbScript);
310 if (!script.empty()) {
311 cmd_line.AppendArg("--command");
312 cmd_line.AppendArgNative(script.value());
313 }
314 base::LaunchProcess(cmd_line, base::LaunchOptions());
315 }
316
LaunchSelLdr()317 bool NaClProcessHost::LaunchSelLdr() {
318 process_->GetHost()->CreateChannelMojo();
319
320 // Build command line for nacl.
321
322 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
323 int flags = ChildProcessHost::CHILD_ALLOW_SELF;
324 #else
325 int flags = ChildProcessHost::CHILD_NORMAL;
326 #endif
327
328 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
329 if (exe_path.empty())
330 return false;
331
332 std::unique_ptr<base::CommandLine> cmd_line(new base::CommandLine(exe_path));
333 CopyNaClCommandLineArguments(cmd_line.get());
334
335 cmd_line->AppendSwitchASCII(switches::kProcessType,
336 switches::kNaClLoaderProcess);
337 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
338 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
339
340 process_->Launch(std::make_unique<NaClSandboxedProcessLauncherDelegate>(),
341 std::move(cmd_line), true);
342 return true;
343 }
344
OnMessageReceived(const IPC::Message & msg)345 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
346 bool handled = true;
347 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
348 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
349 OnQueryKnownToValidate)
350 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
351 OnSetKnownToValidate)
352 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileToken,
353 OnResolveFileToken)
354 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
355 OnPpapiChannelsCreated)
356 IPC_MESSAGE_UNHANDLED(handled = false)
357 IPC_END_MESSAGE_MAP()
358 return handled;
359 }
360
OnProcessLaunched()361 void NaClProcessHost::OnProcessLaunched() {
362 if (!StartWithLaunchedProcess())
363 delete this;
364 }
365
366 // Called when the NaClBrowser singleton has been fully initialized.
OnResourcesReady()367 void NaClProcessHost::OnResourcesReady() {
368 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
369 if (!nacl_browser->IsReady()) {
370 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
371 delete this;
372 } else if (!StartNaClExecution()) {
373 delete this;
374 }
375 }
376
ReplyToRenderer(mojo::ScopedMessagePipeHandle ppapi_channel_handle,mojo::ScopedMessagePipeHandle trusted_channel_handle,mojo::ScopedMessagePipeHandle manifest_service_channel_handle,base::ReadOnlySharedMemoryRegion crash_info_shmem_region)377 void NaClProcessHost::ReplyToRenderer(
378 mojo::ScopedMessagePipeHandle ppapi_channel_handle,
379 mojo::ScopedMessagePipeHandle trusted_channel_handle,
380 mojo::ScopedMessagePipeHandle manifest_service_channel_handle,
381 base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
382 // Hereafter, we always send an IPC message with handles created above
383 // which, on Windows, are not closable in this process.
384 std::string error_message;
385 if (!crash_info_shmem_region.IsValid()) {
386 // On error, we do not send "IPC::ChannelHandle"s to the renderer process.
387 // Note that some other FDs/handles still get sent to the renderer, but
388 // will be closed there.
389 ppapi_channel_handle.reset();
390 trusted_channel_handle.reset();
391 manifest_service_channel_handle.reset();
392 error_message = "shared memory region not valid";
393 }
394
395 const ChildProcessData& data = process_->GetData();
396 SendMessageToRenderer(
397 NaClLaunchResult(
398 ppapi_channel_handle.release(), trusted_channel_handle.release(),
399 manifest_service_channel_handle.release(), data.GetProcess().Pid(),
400 data.id, std::move(crash_info_shmem_region)),
401 error_message);
402 }
403
SendErrorToRenderer(const std::string & error_message)404 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
405 LOG(ERROR) << "NaCl process launch failed: " << error_message;
406 SendMessageToRenderer(NaClLaunchResult(), error_message);
407 }
408
SendMessageToRenderer(const NaClLaunchResult & result,const std::string & error_message)409 void NaClProcessHost::SendMessageToRenderer(
410 const NaClLaunchResult& result,
411 const std::string& error_message) {
412 DCHECK(nacl_host_message_filter_.get());
413 DCHECK(reply_msg_);
414 if (!nacl_host_message_filter_.get() || !reply_msg_) {
415 // As DCHECKed above, this case should not happen in general.
416 // Though, in this case, unfortunately there is no proper way to release
417 // resources which are already created in |result|. We just give up on
418 // releasing them, and leak them.
419 return;
420 }
421
422 NaClHostMsg_LaunchNaCl::WriteReplyParams(reply_msg_, result, error_message);
423 nacl_host_message_filter_->Send(reply_msg_);
424 nacl_host_message_filter_.reset();
425 reply_msg_ = nullptr;
426 }
427
SetDebugStubPort(int port)428 void NaClProcessHost::SetDebugStubPort(int port) {
429 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
430 nacl_browser->SetProcessGdbDebugStubPort(process_->GetData().id, port);
431 }
432
433 #if BUILDFLAG(IS_POSIX)
434 // TCP port we chose for NaCl debug stub. It can be any other number.
435 static const uint16_t kInitialDebugStubPort = 4014;
436
GetDebugStubSocketHandle()437 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
438 // We always try to allocate the default port first. If this fails, we then
439 // allocate any available port.
440 // On success, if the test system has register a handler
441 // (GdbDebugStubPortListener), we fire a notification.
442 uint16_t port = kInitialDebugStubPort;
443 net::SocketDescriptor s =
444 net::CreatePlatformSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
445 if (s != net::kInvalidSocket) {
446 // Allow rapid reuse.
447 static const int kOn = 1;
448 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
449
450 sockaddr_in addr;
451 memset(&addr, 0, sizeof(addr));
452 addr.sin_family = AF_INET;
453 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
454 addr.sin_port = base::HostToNet16(port);
455 if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
456 // Try allocate any available port.
457 addr.sin_port = base::HostToNet16(0);
458 if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
459 close(s);
460 LOG(ERROR) << "Could not bind socket to port" << port;
461 s = net::kInvalidSocket;
462 } else {
463 sockaddr_in sock_addr;
464 socklen_t sock_addr_size = sizeof(sock_addr);
465 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sock_addr),
466 &sock_addr_size) != 0 ||
467 sock_addr_size != sizeof(sock_addr)) {
468 LOG(ERROR) << "Could not determine bound port, getsockname() failed";
469 close(s);
470 s = net::kInvalidSocket;
471 } else {
472 port = base::NetToHost16(sock_addr.sin_port);
473 }
474 }
475 }
476 }
477
478 if (s != net::kInvalidSocket) {
479 SetDebugStubPort(port);
480 }
481 if (s == net::kInvalidSocket) {
482 LOG(ERROR) << "failed to open socket for debug stub";
483 return net::kInvalidSocket;
484 }
485 LOG(WARNING) << "debug stub on port " << port;
486 if (listen(s, 1)) {
487 LOG(ERROR) << "listen() failed on debug stub socket";
488 if (IGNORE_EINTR(close(s)) < 0)
489 PLOG(ERROR) << "failed to close debug stub socket";
490 return net::kInvalidSocket;
491 }
492 return s;
493 }
494 #endif
495
StartNaClExecution()496 bool NaClProcessHost::StartNaClExecution() {
497 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
498
499 NaClStartParams params;
500
501 params.process_type = process_type_;
502 bool enable_nacl_debug = enable_debug_stub_ &&
503 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
504 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
505 params.validation_cache_key = nacl_browser->GetValidationCacheKey();
506 params.version = NaClBrowser::GetDelegate()->GetVersionString();
507 params.enable_debug_stub = enable_nacl_debug;
508
509 const base::File& irt_file = nacl_browser->IrtFile();
510 CHECK(irt_file.IsValid());
511 // Send over the IRT file handle. We don't close our own copy!
512 params.irt_handle =
513 IPC::GetPlatformFileForTransit(irt_file.GetPlatformFile(), false);
514 if (params.irt_handle == IPC::InvalidPlatformFileForTransit()) {
515 return false;
516 }
517
518 #if BUILDFLAG(IS_POSIX)
519 if (params.enable_debug_stub) {
520 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
521 if (server_bound_socket != net::kInvalidSocket) {
522 params.debug_stub_server_bound_socket =
523 IPC::GetPlatformFileForTransit(server_bound_socket, true);
524 }
525 }
526 #endif
527
528 // Create a shared memory region that the renderer and the plugin share to
529 // report crash information.
530 params.crash_info_shmem_region =
531 base::WritableSharedMemoryRegion::Create(kNaClCrashInfoShmemSize);
532 if (!params.crash_info_shmem_region.IsValid()) {
533 DLOG(ERROR) << "Failed to create a shared memory buffer";
534 return false;
535 }
536
537 // Pass the pre-opened resource files to the loader. We do not have to reopen
538 // resource files here because the descriptors are not from a renderer.
539 for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
540 process_->Send(
541 new NaClProcessMsg_AddPrefetchedResource(NaClResourcePrefetchResult(
542 prefetched_resource_files_[i].file,
543 prefetched_resource_files_[i].file_path_metadata,
544 prefetched_resource_files_[i].file_key)));
545 }
546 prefetched_resource_files_.clear();
547
548 base::FilePath file_path;
549 if (NaClBrowser::GetInstance()->GetFilePath(nexe_token_.lo, nexe_token_.hi,
550 &file_path)) {
551 // We have to reopen the file in the browser process; we don't want a
552 // compromised renderer to pass an arbitrary fd that could get loaded
553 // into the plugin process.
554 base::ThreadPool::PostTaskAndReplyWithResult(
555 FROM_HERE,
556 // USER_BLOCKING because it is on the critical path of displaying the
557 // official virtual keyboard on Chrome OS. https://crbug.com/976542
558 {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
559 base::BindOnce(OpenNaClReadExecImpl, file_path,
560 true /* is_executable */),
561 base::BindOnce(&NaClProcessHost::StartNaClFileResolved,
562 weak_factory_.GetWeakPtr(), std::move(params),
563 file_path));
564 return true;
565 }
566
567 StartNaClFileResolved(std::move(params), base::FilePath(), base::File());
568 return true;
569 }
570
StartNaClFileResolved(NaClStartParams params,const base::FilePath & file_path,base::File checked_nexe_file)571 void NaClProcessHost::StartNaClFileResolved(
572 NaClStartParams params,
573 const base::FilePath& file_path,
574 base::File checked_nexe_file) {
575 if (checked_nexe_file.IsValid()) {
576 // Release the file received from the renderer. This has to be done on a
577 // thread where IO is permitted, though.
578 base::ThreadPool::PostTask(
579 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
580 base::BindOnce(&CloseFile, std::move(nexe_file_)));
581 params.nexe_file_path_metadata = file_path;
582 params.nexe_file =
583 IPC::TakePlatformFileForTransit(std::move(checked_nexe_file));
584 } else {
585 params.nexe_file = IPC::TakePlatformFileForTransit(std::move(nexe_file_));
586 }
587
588 process_->Send(new NaClProcessMsg_Start(std::move(params)));
589 }
590
StartPPAPIProxy(mojo::ScopedMessagePipeHandle channel_handle)591 bool NaClProcessHost::StartPPAPIProxy(
592 mojo::ScopedMessagePipeHandle channel_handle) {
593 if (ipc_proxy_channel_.get()) {
594 // Attempt to open more than 1 browser channel is not supported.
595 // Shut down the NaCl process.
596 process_->GetHost()->ForceShutdown();
597 return false;
598 }
599
600 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
601
602 ipc_proxy_channel_ = IPC::ChannelProxy::Create(
603 channel_handle.release(), IPC::Channel::MODE_CLIENT, nullptr,
604 base::SingleThreadTaskRunner::GetCurrentDefault().get(),
605 base::SingleThreadTaskRunner::GetCurrentDefault().get());
606 // Create the browser ppapi host and enable PPAPI message dispatching to the
607 // browser process.
608 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
609 ipc_proxy_channel_.get(), // sender
610 permissions_, process_->GetData().GetProcess().Duplicate(),
611 ipc_proxy_channel_.get(), profile_directory_));
612
613 ppapi::PpapiNaClPluginArgs args;
614 args.off_the_record = nacl_host_message_filter_->off_the_record();
615 args.permissions = permissions_;
616 base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
617 DCHECK(cmdline);
618 std::string flag_allowlist[] = {
619 switches::kV,
620 switches::kVModule,
621 };
622 for (size_t i = 0; i < std::size(flag_allowlist); ++i) {
623 std::string value = cmdline->GetSwitchValueASCII(flag_allowlist[i]);
624 if (!value.empty()) {
625 args.switch_names.push_back(flag_allowlist[i]);
626 args.switch_values.push_back(value);
627 }
628 }
629
630 std::string enabled_features;
631 std::string disabled_features;
632 base::FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features,
633 &disabled_features);
634 if (!enabled_features.empty()) {
635 args.switch_names.push_back(switches::kEnableFeatures);
636 args.switch_values.push_back(enabled_features);
637 }
638 if (!disabled_features.empty()) {
639 args.switch_names.push_back(switches::kDisableFeatures);
640 args.switch_values.push_back(disabled_features);
641 }
642
643 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
644 std::unique_ptr<ppapi::host::HostFactory>(
645 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
646 ppapi_host_.get())));
647
648 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
649 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
650 return true;
651 }
652
653 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
654 // received.
OnPpapiChannelsCreated(const IPC::ChannelHandle & raw_ppapi_browser_channel_handle,const IPC::ChannelHandle & raw_ppapi_renderer_channel_handle,const IPC::ChannelHandle & raw_trusted_renderer_channel_handle,const IPC::ChannelHandle & raw_manifest_service_channel_handle,base::ReadOnlySharedMemoryRegion crash_info_shmem_region)655 void NaClProcessHost::OnPpapiChannelsCreated(
656 const IPC::ChannelHandle& raw_ppapi_browser_channel_handle,
657 const IPC::ChannelHandle& raw_ppapi_renderer_channel_handle,
658 const IPC::ChannelHandle& raw_trusted_renderer_channel_handle,
659 const IPC::ChannelHandle& raw_manifest_service_channel_handle,
660 base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
661 DCHECK(raw_ppapi_browser_channel_handle.is_mojo_channel_handle());
662 DCHECK(raw_ppapi_renderer_channel_handle.is_mojo_channel_handle());
663 DCHECK(raw_trusted_renderer_channel_handle.is_mojo_channel_handle());
664 DCHECK(raw_manifest_service_channel_handle.is_mojo_channel_handle());
665
666 mojo::ScopedMessagePipeHandle ppapi_browser_channel_handle(
667 raw_ppapi_browser_channel_handle.mojo_handle);
668 mojo::ScopedMessagePipeHandle ppapi_renderer_channel_handle(
669 raw_ppapi_renderer_channel_handle.mojo_handle);
670 mojo::ScopedMessagePipeHandle trusted_renderer_channel_handle(
671 raw_trusted_renderer_channel_handle.mojo_handle);
672 mojo::ScopedMessagePipeHandle manifest_service_channel_handle(
673 raw_manifest_service_channel_handle.mojo_handle);
674
675 if (!StartPPAPIProxy(std::move(ppapi_browser_channel_handle))) {
676 SendErrorToRenderer("Browser PPAPI proxy could not start.");
677 return;
678 }
679
680 // Let the renderer know that the IPC channels are established.
681 ReplyToRenderer(std::move(ppapi_renderer_channel_handle),
682 std::move(trusted_renderer_channel_handle),
683 std::move(manifest_service_channel_handle),
684 std::move(crash_info_shmem_region));
685 }
686
StartWithLaunchedProcess()687 bool NaClProcessHost::StartWithLaunchedProcess() {
688 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
689
690 if (nacl_browser->IsReady())
691 return StartNaClExecution();
692 if (nacl_browser->IsOk()) {
693 nacl_browser->WaitForResources(base::BindOnce(
694 &NaClProcessHost::OnResourcesReady, weak_factory_.GetWeakPtr()));
695 return true;
696 }
697 SendErrorToRenderer("previously failed to acquire shared resources");
698 return false;
699 }
700
OnQueryKnownToValidate(const std::string & signature,bool * result)701 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
702 bool* result) {
703 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
704 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
705 }
706
OnSetKnownToValidate(const std::string & signature)707 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
708 NaClBrowser::GetInstance()->SetKnownToValidate(
709 signature, off_the_record_);
710 }
711
OnResolveFileToken(uint64_t file_token_lo,uint64_t file_token_hi)712 void NaClProcessHost::OnResolveFileToken(uint64_t file_token_lo,
713 uint64_t file_token_hi) {
714 // Was the file registered?
715 //
716 // Note that the file path cache is of bounded size, and old entries can get
717 // evicted. If a large number of NaCl modules are being launched at once,
718 // resolving the file_token may fail because the path cache was thrashed
719 // while the file_token was in flight. In this case the query fails, and we
720 // need to fall back to the slower path.
721 //
722 // However: each NaCl process will consume 2-3 entries as it starts up, this
723 // means that eviction will not happen unless you start up 33+ NaCl processes
724 // at the same time, and this still requires worst-case timing. As a
725 // practical matter, no entries should be evicted prematurely.
726 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
727 // data structure overhead) * 100 = 35k when full, so making it bigger should
728 // not be a problem, if needed.
729 //
730 // Each NaCl process will consume 2-3 entries because the manifest and main
731 // nexe are currently not resolved. Shared libraries will be resolved. They
732 // will be loaded sequentially, so they will only consume a single entry
733 // while the load is in flight.
734 //
735 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
736 // bogus keys are getting queried, this would be good to know.
737 base::FilePath file_path;
738 if (!NaClBrowser::GetInstance()->GetFilePath(
739 file_token_lo, file_token_hi, &file_path)) {
740 Send(new NaClProcessMsg_ResolveFileTokenReply(
741 file_token_lo,
742 file_token_hi,
743 IPC::PlatformFileForTransit(),
744 base::FilePath()));
745 return;
746 }
747
748 // Open the file.
749 base::ThreadPool::PostTaskAndReplyWithResult(
750 FROM_HERE,
751 // USER_BLOCKING because it is on the critical path of displaying the
752 // official virtual keyboard on Chrome OS. https://crbug.com/976542
753 {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
754 base::BindOnce(OpenNaClReadExecImpl, file_path, true /* is_executable */),
755 base::BindOnce(&NaClProcessHost::FileResolved, weak_factory_.GetWeakPtr(),
756 file_token_lo, file_token_hi, file_path));
757 }
758
FileResolved(uint64_t file_token_lo,uint64_t file_token_hi,const base::FilePath & file_path,base::File file)759 void NaClProcessHost::FileResolved(
760 uint64_t file_token_lo,
761 uint64_t file_token_hi,
762 const base::FilePath& file_path,
763 base::File file) {
764 base::FilePath out_file_path;
765 IPC::PlatformFileForTransit out_handle;
766 if (file.IsValid()) {
767 out_file_path = file_path;
768 out_handle = IPC::TakePlatformFileForTransit(std::move(file));
769 } else {
770 out_handle = IPC::InvalidPlatformFileForTransit();
771 }
772 Send(new NaClProcessMsg_ResolveFileTokenReply(
773 file_token_lo,
774 file_token_hi,
775 out_handle,
776 out_file_path));
777 }
778
779 } // namespace nacl
780