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 #include "components/nacl/browser/nacl_process_host.h"
6
7 #include <string.h>
8
9 #include <algorithm>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 #include <vector>
14
15 #include "base/base_switches.h"
16 #include "base/command_line.h"
17 #include "base/feature_list.h"
18 #include "base/files/file_util.h"
19 #include "base/functional/bind.h"
20 #include "base/location.h"
21 #include "base/metrics/histogram_macros.h"
22 #include "base/path_service.h"
23 #include "base/process/launch.h"
24 #include "base/process/process_iterator.h"
25 #include "base/rand_util.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_split.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/sys_byteorder.h"
32 #include "base/task/single_thread_task_runner.h"
33 #include "base/task/thread_pool.h"
34 #include "build/build_config.h"
35 #include "build/chromeos_buildflags.h"
36 #include "components/nacl/browser/nacl_browser.h"
37 #include "components/nacl/browser/nacl_browser_delegate.h"
38 #include "components/nacl/browser/nacl_host_message_filter.h"
39 #include "components/nacl/common/nacl_cmd_line.h"
40 #include "components/nacl/common/nacl_constants.h"
41 #include "components/nacl/common/nacl_host_messages.h"
42 #include "components/nacl/common/nacl_messages.h"
43 #include "components/nacl/common/nacl_process_type.h"
44 #include "components/nacl/common/nacl_switches.h"
45 #include "components/url_formatter/url_formatter.h"
46 #include "content/public/browser/browser_child_process_host.h"
47 #include "content/public/browser/browser_ppapi_host.h"
48 #include "content/public/browser/child_process_data.h"
49 #include "content/public/browser/child_process_host.h"
50 #include "content/public/browser/plugin_service.h"
51 #include "content/public/browser/render_process_host.h"
52 #include "content/public/browser/web_contents.h"
53 #include "content/public/common/content_switches.h"
54 #include "content/public/common/process_type.h"
55 #include "content/public/common/sandboxed_process_launcher_delegate.h"
56 #include "content/public/common/zygote/zygote_buildflags.h"
57 #include "ipc/ipc_channel.h"
58 #include "mojo/public/cpp/system/invitation.h"
59 #include "net/socket/socket_descriptor.h"
60 #include "ppapi/host/host_factory.h"
61 #include "ppapi/host/ppapi_host.h"
62 #include "ppapi/proxy/ppapi_messages.h"
63 #include "ppapi/shared_impl/ppapi_nacl_plugin_args.h"
64 #include "sandbox/policy/mojom/sandbox.mojom.h"
65 #include "sandbox/policy/switches.h"
66
67 #if BUILDFLAG(USE_ZYGOTE)
68 #include "content/public/common/zygote/zygote_handle.h" // nogncheck
69 #endif // BUILDFLAG(USE_ZYGOTE)
70
71 #if BUILDFLAG(IS_POSIX)
72
73 #include <arpa/inet.h>
74 #include <fcntl.h>
75 #include <netinet/in.h>
76 #include <sys/socket.h>
77
78 #elif BUILDFLAG(IS_WIN)
79 #include <windows.h>
80 #include <winsock2.h>
81
82 #include "base/threading/thread.h"
83 #include "base/win/scoped_handle.h"
84 #include "base/win/windows_version.h"
85 #include "components/nacl/browser/nacl_broker_service_win.h"
86 #include "components/nacl/common/nacl_debug_exception_handler_win.h"
87 #include "sandbox/policy/win/sandbox_win.h"
88 #endif
89
90 using content::BrowserThread;
91 using content::ChildProcessData;
92 using content::ChildProcessHost;
93 using ppapi::proxy::SerializedHandle;
94
95 namespace nacl {
96
97 #if BUILDFLAG(IS_WIN)
98 namespace {
99
100 // Looks for the largest contiguous unallocated region of address
101 // space and returns it via |*out_addr| and |*out_size|.
FindAddressSpace(base::ProcessHandle process,char ** out_addr,size_t * out_size)102 void FindAddressSpace(base::ProcessHandle process,
103 char** out_addr, size_t* out_size) {
104 *out_addr = nullptr;
105 *out_size = 0;
106 char* addr = 0;
107 while (true) {
108 MEMORY_BASIC_INFORMATION info;
109 size_t result = VirtualQueryEx(process, static_cast<void*>(addr),
110 &info, sizeof(info));
111 if (result < sizeof(info))
112 break;
113 if (info.State == MEM_FREE && info.RegionSize > *out_size) {
114 *out_addr = addr;
115 *out_size = info.RegionSize;
116 }
117 addr += info.RegionSize;
118 }
119 }
120
121 #ifdef _DLL
122
IsInPath(const std::string & path_env_var,const std::string & dir)123 bool IsInPath(const std::string& path_env_var, const std::string& dir) {
124 for (const base::StringPiece& cur : base::SplitStringPiece(
125 path_env_var, ";", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
126 if (cur == dir)
127 return true;
128 }
129 return false;
130 }
131
132 #endif // _DLL
133
134 } // namespace
135
136 // Allocates |size| bytes of address space in the given process at a
137 // randomised address.
AllocateAddressSpaceASLR(base::ProcessHandle process,size_t size)138 void* AllocateAddressSpaceASLR(base::ProcessHandle process, size_t size) {
139 char* addr;
140 size_t avail_size;
141 FindAddressSpace(process, &addr, &avail_size);
142 if (avail_size < size)
143 return nullptr;
144 size_t offset = base::RandGenerator(avail_size - size);
145 const int kPageSize = 0x10000;
146 void* request_addr = reinterpret_cast<void*>(
147 reinterpret_cast<uint64_t>(addr + offset) & ~(kPageSize - 1));
148 return VirtualAllocEx(process, request_addr, size,
149 MEM_RESERVE, PAGE_NOACCESS);
150 }
151
152 namespace {
153
RunningOnWOW64()154 bool RunningOnWOW64() {
155 return base::win::OSInfo::GetInstance()->IsWowX86OnAMD64();
156 }
157
158 } // namespace
159
160 #endif // BUILDFLAG(IS_WIN)
161
162 namespace {
163
164 // NOTE: changes to this class need to be reviewed by the security team.
165 class NaClSandboxedProcessLauncherDelegate
166 : public content::SandboxedProcessLauncherDelegate {
167 public:
NaClSandboxedProcessLauncherDelegate()168 NaClSandboxedProcessLauncherDelegate() {}
169
170 #if BUILDFLAG(IS_WIN)
PostSpawnTarget(base::ProcessHandle process)171 void PostSpawnTarget(base::ProcessHandle process) override {
172 // For Native Client sel_ldr processes on 32-bit Windows, reserve 1 GB of
173 // address space to prevent later failure due to address space fragmentation
174 // from .dll loading. The NaCl process will attempt to locate this space by
175 // scanning the address space using VirtualQuery.
176 // TODO(bbudge) Handle the --no-sandbox case.
177 // http://code.google.com/p/nativeclient/issues/detail?id=2131
178 const SIZE_T kNaClSandboxSize = 1 << 30;
179 if (!nacl::AllocateAddressSpaceASLR(process, kNaClSandboxSize)) {
180 DLOG(WARNING) << "Failed to reserve address space for Native Client";
181 }
182 }
183
GetSandboxTag()184 std::string GetSandboxTag() override {
185 return sandbox::policy::SandboxWin::GetSandboxTagForDelegate(
186 "nacl-process-host", GetSandboxType());
187 }
188
CetCompatible()189 bool CetCompatible() override {
190 // Disable CET for NaCl loader processes as x86 NaCl sandboxes are not CET
191 // compatible. NaCl untrusted code is allowed to switch stacks within the
192 // sandbox.
193 return false;
194 }
195 #endif // BUILDFLAG(IS_WIN)
196
197 #if BUILDFLAG(USE_ZYGOTE)
GetZygote()198 content::ZygoteCommunication* GetZygote() override {
199 return content::GetGenericZygote();
200 }
201 #endif // BUILDFLAG(USE_ZYGOTE)
202
GetSandboxType()203 sandbox::mojom::Sandbox GetSandboxType() override {
204 return sandbox::mojom::Sandbox::kPpapi;
205 }
206 };
207
CloseFile(base::File file)208 void CloseFile(base::File file) {
209 // The base::File destructor will close the file for us.
210 }
211
212 } // namespace
213
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)214 NaClProcessHost::NaClProcessHost(
215 const GURL& manifest_url,
216 base::File nexe_file,
217 const NaClFileToken& nexe_token,
218 const std::vector<NaClResourcePrefetchResult>& prefetched_resource_files,
219 ppapi::PpapiPermissions permissions,
220 uint32_t permission_bits,
221 bool off_the_record,
222 NaClAppProcessType process_type,
223 const base::FilePath& profile_directory)
224 : manifest_url_(manifest_url),
225 nexe_file_(std::move(nexe_file)),
226 nexe_token_(nexe_token),
227 prefetched_resource_files_(prefetched_resource_files),
228 permissions_(permissions),
229 #if BUILDFLAG(IS_WIN)
230 process_launched_by_broker_(false),
231 #endif
232 reply_msg_(nullptr),
233 #if BUILDFLAG(IS_WIN)
234 debug_exception_handler_requested_(false),
235 #endif
236 enable_debug_stub_(false),
237 enable_crash_throttling_(false),
238 off_the_record_(off_the_record),
239 process_type_(process_type),
240 profile_directory_(profile_directory) {
241 process_ = content::BrowserChildProcessHost::Create(
242 static_cast<content::ProcessType>(PROCESS_TYPE_NACL_LOADER), this,
243 content::ChildProcessHost::IpcMode::kLegacy);
244 process_->SetMetricsName("NaCl Loader");
245
246 // Set the display name so the user knows what plugin the process is running.
247 // We aren't on the UI thread so getting the pref locale for language
248 // formatting isn't possible, so IDN will be lost, but this is probably OK
249 // for this use case.
250 process_->SetName(url_formatter::FormatUrl(manifest_url_));
251
252 enable_debug_stub_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
253 switches::kEnableNaClDebug);
254 DCHECK(process_type_ != kUnknownNaClProcessType);
255 enable_crash_throttling_ = process_type_ != kNativeNaClProcessType;
256 }
257
~NaClProcessHost()258 NaClProcessHost::~NaClProcessHost() {
259 // Report exit status only if the process was successfully started.
260 if (process_->GetData().GetProcess().IsValid()) {
261 content::ChildProcessTerminationInfo info =
262 process_->GetTerminationInfo(false /* known_dead */);
263 std::string message =
264 base::StringPrintf("NaCl process exited with status %i (0x%x)",
265 info.exit_code, info.exit_code);
266 if (info.exit_code == 0) {
267 VLOG(1) << message;
268 } else {
269 LOG(ERROR) << message;
270 }
271 NaClBrowser::GetInstance()->OnProcessEnd(process_->GetData().id);
272 }
273
274 // Note: this does not work on Windows, though we currently support this
275 // prefetching feature only on POSIX platforms, so it should be ok.
276 #if BUILDFLAG(IS_WIN)
277 DCHECK(prefetched_resource_files_.empty());
278 #else
279 for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
280 // The process failed to launch for some reason. Close resource file
281 // handles.
282 base::File file(IPC::PlatformFileForTransitToFile(
283 prefetched_resource_files_[i].file));
284 base::ThreadPool::PostTask(
285 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
286 base::BindOnce(&CloseFile, std::move(file)));
287 }
288 #endif
289 // Open files need to be closed on the blocking pool.
290 if (nexe_file_.IsValid()) {
291 base::ThreadPool::PostTask(
292 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
293 base::BindOnce(&CloseFile, std::move(nexe_file_)));
294 }
295
296 if (reply_msg_) {
297 // The process failed to launch for some reason.
298 // Don't keep the renderer hanging.
299 reply_msg_->set_reply_error();
300 nacl_host_message_filter_->Send(reply_msg_);
301 }
302 #if BUILDFLAG(IS_WIN)
303 if (process_launched_by_broker_) {
304 NaClBrokerService::GetInstance()->OnLoaderDied();
305 }
306 #endif
307 }
308
OnProcessCrashed(int exit_status)309 void NaClProcessHost::OnProcessCrashed(int exit_status) {
310 if (enable_crash_throttling_ &&
311 !base::CommandLine::ForCurrentProcess()->HasSwitch(
312 switches::kDisablePnaclCrashThrottling)) {
313 NaClBrowser::GetInstance()->OnProcessCrashed();
314 }
315 }
316
317 // This is called at browser startup.
318 // static
EarlyStartup()319 void NaClProcessHost::EarlyStartup() {
320 NaClBrowser::GetInstance()->EarlyStartup();
321 // Inform NaClBrowser that we exist and will have a debug port at some point.
322 // TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
323 // of lacros-chrome is complete.
324 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS)
325 // Open the IRT file early to make sure that it isn't replaced out from
326 // under us by autoupdate.
327 NaClBrowser::GetInstance()->EnsureIrtAvailable();
328 #endif
329 base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
330 std::string nacl_debug_mask =
331 cmd->GetSwitchValueASCII(switches::kNaClDebugMask);
332 // By default, exclude debugging SSH and the PNaCl translator.
333 // about::flags only allows empty flags as the default, so replace
334 // the empty setting with the default. To debug all apps, use a wild-card.
335 if (nacl_debug_mask.empty()) {
336 nacl_debug_mask = "!*://*/*ssh_client.nmf,chrome://pnacl-translator/*";
337 }
338 NaClBrowser::GetDelegate()->SetDebugPatterns(nacl_debug_mask);
339 }
340
Launch(NaClHostMessageFilter * nacl_host_message_filter,IPC::Message * reply_msg,const base::FilePath & manifest_path)341 void NaClProcessHost::Launch(
342 NaClHostMessageFilter* nacl_host_message_filter,
343 IPC::Message* reply_msg,
344 const base::FilePath& manifest_path) {
345 nacl_host_message_filter_ = nacl_host_message_filter;
346 reply_msg_ = reply_msg;
347 manifest_path_ = manifest_path;
348
349 // Do not launch the requested NaCl module if NaCl is marked "unstable" due
350 // to too many crashes within a given time period.
351 if (enable_crash_throttling_ &&
352 !base::CommandLine::ForCurrentProcess()->HasSwitch(
353 switches::kDisablePnaclCrashThrottling) &&
354 NaClBrowser::GetInstance()->IsThrottled()) {
355 SendErrorToRenderer("Process creation was throttled due to excessive"
356 " crashes");
357 delete this;
358 return;
359 }
360
361 const base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
362 #if BUILDFLAG(IS_WIN)
363 if (cmd->HasSwitch(switches::kEnableNaClDebug) &&
364 !cmd->HasSwitch(sandbox::policy::switches::kNoSandbox)) {
365 // We don't switch off sandbox automatically for security reasons.
366 SendErrorToRenderer("NaCl's GDB debug stub requires --no-sandbox flag"
367 " on Windows. See crbug.com/265624.");
368 delete this;
369 return;
370 }
371 #endif
372 if (cmd->HasSwitch(switches::kNaClGdb) &&
373 !cmd->HasSwitch(switches::kEnableNaClDebug)) {
374 LOG(WARNING) << "--nacl-gdb flag requires --enable-nacl-debug flag";
375 }
376
377 // Start getting the IRT open asynchronously while we launch the NaCl process.
378 // We'll make sure this actually finished in StartWithLaunchedProcess, below.
379 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
380 nacl_browser->EnsureAllResourcesAvailable();
381 if (!nacl_browser->IsOk()) {
382 SendErrorToRenderer("could not find all the resources needed"
383 " to launch the process");
384 delete this;
385 return;
386 }
387
388 // Launch the process
389 if (!LaunchSelLdr()) {
390 delete this;
391 }
392 }
393
OnChannelConnected(int32_t peer_pid)394 void NaClProcessHost::OnChannelConnected(int32_t peer_pid) {
395 if (!base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
396 switches::kNaClGdb).empty()) {
397 LaunchNaClGdb();
398 }
399 }
400
401 #if BUILDFLAG(IS_WIN)
OnProcessLaunchedByBroker(base::Process process)402 void NaClProcessHost::OnProcessLaunchedByBroker(base::Process process) {
403 process_launched_by_broker_ = true;
404 process_->SetProcess(std::move(process));
405 SetDebugStubPort(nacl::kGdbDebugStubPortUnknown);
406 if (!StartWithLaunchedProcess())
407 delete this;
408 }
409
OnDebugExceptionHandlerLaunchedByBroker(bool success)410 void NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker(bool success) {
411 IPC::Message* reply = attach_debug_exception_handler_reply_msg_.release();
412 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply, success);
413 Send(reply);
414 }
415 #endif
416
417 // Needed to handle sync messages in OnMessageReceived.
Send(IPC::Message * msg)418 bool NaClProcessHost::Send(IPC::Message* msg) {
419 return process_->Send(msg);
420 }
421
LaunchNaClGdb()422 void NaClProcessHost::LaunchNaClGdb() {
423 const base::CommandLine& command_line =
424 *base::CommandLine::ForCurrentProcess();
425 #if BUILDFLAG(IS_WIN)
426 base::FilePath nacl_gdb =
427 command_line.GetSwitchValuePath(switches::kNaClGdb);
428 base::CommandLine cmd_line(nacl_gdb);
429 #else
430 base::CommandLine::StringType nacl_gdb =
431 command_line.GetSwitchValueNative(switches::kNaClGdb);
432 // We don't support spaces inside arguments in --nacl-gdb switch.
433 base::CommandLine cmd_line(base::SplitString(
434 nacl_gdb, base::CommandLine::StringType(1, ' '),
435 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL));
436 #endif
437 cmd_line.AppendArg("--eval-command");
438 base::FilePath::StringType irt_path(
439 NaClBrowser::GetInstance()->GetIrtFilePath().value());
440 // Avoid back slashes because nacl-gdb uses posix escaping rules on Windows.
441 // See issue https://code.google.com/p/nativeclient/issues/detail?id=3482.
442 std::replace(irt_path.begin(), irt_path.end(), '\\', '/');
443 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-irt \"") + irt_path +
444 FILE_PATH_LITERAL("\""));
445 if (!manifest_path_.empty()) {
446 cmd_line.AppendArg("--eval-command");
447 base::FilePath::StringType manifest_path_value(manifest_path_.value());
448 std::replace(manifest_path_value.begin(), manifest_path_value.end(),
449 '\\', '/');
450 cmd_line.AppendArgNative(FILE_PATH_LITERAL("nacl-manifest \"") +
451 manifest_path_value + FILE_PATH_LITERAL("\""));
452 }
453 cmd_line.AppendArg("--eval-command");
454 cmd_line.AppendArg("target remote :4014");
455 base::FilePath script =
456 command_line.GetSwitchValuePath(switches::kNaClGdbScript);
457 if (!script.empty()) {
458 cmd_line.AppendArg("--command");
459 cmd_line.AppendArgNative(script.value());
460 }
461 base::LaunchProcess(cmd_line, base::LaunchOptions());
462 }
463
LaunchSelLdr()464 bool NaClProcessHost::LaunchSelLdr() {
465 process_->GetHost()->CreateChannelMojo();
466
467 // Build command line for nacl.
468
469 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
470 int flags = ChildProcessHost::CHILD_ALLOW_SELF;
471 #elif BUILDFLAG(IS_APPLE)
472 int flags = ChildProcessHost::CHILD_PLUGIN;
473 #else
474 int flags = ChildProcessHost::CHILD_NORMAL;
475 #endif
476
477 base::FilePath exe_path = ChildProcessHost::GetChildPath(flags);
478 if (exe_path.empty())
479 return false;
480
481 #if BUILDFLAG(IS_WIN)
482 // On Windows 64-bit NaCl loader is called nacl64.exe instead of chrome.exe
483 if (RunningOnWOW64()) {
484 if (!NaClBrowser::GetInstance()->GetNaCl64ExePath(&exe_path)) {
485 SendErrorToRenderer("could not get path to nacl64.exe");
486 return false;
487 }
488
489 #ifdef _DLL
490 // When using the DLL CRT on Windows, we need to amend the PATH to include
491 // the location of the x64 CRT DLLs. This is only the case when using a
492 // component=shared_library build (i.e. generally dev debug builds). The
493 // x86 CRT DLLs are in e.g. out\Debug for chrome.exe etc., so the x64 ones
494 // are put in out\Debug\x64 which we add to the PATH here so that loader
495 // can find them. See http://crbug.com/346034.
496 std::unique_ptr<base::Environment> env(base::Environment::Create());
497 static const char kPath[] = "PATH";
498 std::string old_path;
499 base::FilePath module_path;
500 if (!base::PathService::Get(base::FILE_MODULE, &module_path)) {
501 SendErrorToRenderer("could not get path to current module");
502 return false;
503 }
504 std::string x64_crt_path =
505 base::WideToUTF8(module_path.DirName().Append(L"x64").value());
506 if (!env->GetVar(kPath, &old_path)) {
507 env->SetVar(kPath, x64_crt_path);
508 } else if (!IsInPath(old_path, x64_crt_path)) {
509 std::string new_path(old_path);
510 new_path.append(";");
511 new_path.append(x64_crt_path);
512 env->SetVar(kPath, new_path);
513 }
514 #endif // _DLL
515 }
516 #endif
517
518 std::unique_ptr<base::CommandLine> cmd_line(new base::CommandLine(exe_path));
519 CopyNaClCommandLineArguments(cmd_line.get());
520
521 cmd_line->AppendSwitchASCII(switches::kProcessType,
522 switches::kNaClLoaderProcess);
523 if (NaClBrowser::GetDelegate()->DialogsAreSuppressed())
524 cmd_line->AppendSwitch(switches::kNoErrorDialogs);
525
526 #if BUILDFLAG(IS_WIN)
527 cmd_line->AppendArg(switches::kPrefetchArgumentOther);
528 #endif // BUILDFLAG(IS_WIN)
529
530 // On Windows we might need to start the broker process to launch a new loader
531 #if BUILDFLAG(IS_WIN)
532 if (RunningOnWOW64()) {
533 if (!NaClBrokerService::GetInstance()->LaunchLoader(
534 weak_factory_.GetWeakPtr(),
535 process_->GetHost()->GetMojoInvitation()->ExtractMessagePipe(0))) {
536 SendErrorToRenderer("broker service did not launch process");
537 return false;
538 }
539 return true;
540 }
541 #endif
542 process_->Launch(std::make_unique<NaClSandboxedProcessLauncherDelegate>(),
543 std::move(cmd_line), true);
544 return true;
545 }
546
OnMessageReceived(const IPC::Message & msg)547 bool NaClProcessHost::OnMessageReceived(const IPC::Message& msg) {
548 bool handled = true;
549 IPC_BEGIN_MESSAGE_MAP(NaClProcessHost, msg)
550 IPC_MESSAGE_HANDLER(NaClProcessMsg_QueryKnownToValidate,
551 OnQueryKnownToValidate)
552 IPC_MESSAGE_HANDLER(NaClProcessMsg_SetKnownToValidate,
553 OnSetKnownToValidate)
554 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileToken,
555 OnResolveFileToken)
556
557 #if BUILDFLAG(IS_WIN)
558 IPC_MESSAGE_HANDLER_DELAY_REPLY(
559 NaClProcessMsg_AttachDebugExceptionHandler,
560 OnAttachDebugExceptionHandler)
561 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_DebugStubPortSelected,
562 OnDebugStubPortSelected)
563 #endif
564 IPC_MESSAGE_HANDLER(NaClProcessHostMsg_PpapiChannelsCreated,
565 OnPpapiChannelsCreated)
566 IPC_MESSAGE_UNHANDLED(handled = false)
567 IPC_END_MESSAGE_MAP()
568 return handled;
569 }
570
OnProcessLaunched()571 void NaClProcessHost::OnProcessLaunched() {
572 if (!StartWithLaunchedProcess())
573 delete this;
574 }
575
576 // Called when the NaClBrowser singleton has been fully initialized.
OnResourcesReady()577 void NaClProcessHost::OnResourcesReady() {
578 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
579 if (!nacl_browser->IsReady()) {
580 SendErrorToRenderer("could not acquire shared resources needed by NaCl");
581 delete this;
582 } else if (!StartNaClExecution()) {
583 delete this;
584 }
585 }
586
ReplyToRenderer(mojo::ScopedMessagePipeHandle ppapi_channel_handle,mojo::ScopedMessagePipeHandle trusted_channel_handle,mojo::ScopedMessagePipeHandle manifest_service_channel_handle,base::ReadOnlySharedMemoryRegion crash_info_shmem_region)587 void NaClProcessHost::ReplyToRenderer(
588 mojo::ScopedMessagePipeHandle ppapi_channel_handle,
589 mojo::ScopedMessagePipeHandle trusted_channel_handle,
590 mojo::ScopedMessagePipeHandle manifest_service_channel_handle,
591 base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
592 // Hereafter, we always send an IPC message with handles created above
593 // which, on Windows, are not closable in this process.
594 std::string error_message;
595 if (!crash_info_shmem_region.IsValid()) {
596 // On error, we do not send "IPC::ChannelHandle"s to the renderer process.
597 // Note that some other FDs/handles still get sent to the renderer, but
598 // will be closed there.
599 ppapi_channel_handle.reset();
600 trusted_channel_handle.reset();
601 manifest_service_channel_handle.reset();
602 error_message = "shared memory region not valid";
603 }
604
605 const ChildProcessData& data = process_->GetData();
606 SendMessageToRenderer(
607 NaClLaunchResult(
608 ppapi_channel_handle.release(), trusted_channel_handle.release(),
609 manifest_service_channel_handle.release(), data.GetProcess().Pid(),
610 data.id, std::move(crash_info_shmem_region)),
611 error_message);
612 }
613
SendErrorToRenderer(const std::string & error_message)614 void NaClProcessHost::SendErrorToRenderer(const std::string& error_message) {
615 LOG(ERROR) << "NaCl process launch failed: " << error_message;
616 SendMessageToRenderer(NaClLaunchResult(), error_message);
617 }
618
SendMessageToRenderer(const NaClLaunchResult & result,const std::string & error_message)619 void NaClProcessHost::SendMessageToRenderer(
620 const NaClLaunchResult& result,
621 const std::string& error_message) {
622 DCHECK(nacl_host_message_filter_.get());
623 DCHECK(reply_msg_);
624 if (!nacl_host_message_filter_.get() || !reply_msg_) {
625 // As DCHECKed above, this case should not happen in general.
626 // Though, in this case, unfortunately there is no proper way to release
627 // resources which are already created in |result|. We just give up on
628 // releasing them, and leak them.
629 return;
630 }
631
632 NaClHostMsg_LaunchNaCl::WriteReplyParams(reply_msg_, result, error_message);
633 nacl_host_message_filter_->Send(reply_msg_);
634 nacl_host_message_filter_.reset();
635 reply_msg_ = nullptr;
636 }
637
SetDebugStubPort(int port)638 void NaClProcessHost::SetDebugStubPort(int port) {
639 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
640 nacl_browser->SetProcessGdbDebugStubPort(process_->GetData().id, port);
641 }
642
643 #if BUILDFLAG(IS_POSIX)
644 // TCP port we chose for NaCl debug stub. It can be any other number.
645 static const uint16_t kInitialDebugStubPort = 4014;
646
GetDebugStubSocketHandle()647 net::SocketDescriptor NaClProcessHost::GetDebugStubSocketHandle() {
648 // We always try to allocate the default port first. If this fails, we then
649 // allocate any available port.
650 // On success, if the test system has register a handler
651 // (GdbDebugStubPortListener), we fire a notification.
652 uint16_t port = kInitialDebugStubPort;
653 net::SocketDescriptor s =
654 net::CreatePlatformSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
655 if (s != net::kInvalidSocket) {
656 // Allow rapid reuse.
657 static const int kOn = 1;
658 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
659
660 sockaddr_in addr;
661 memset(&addr, 0, sizeof(addr));
662 addr.sin_family = AF_INET;
663 addr.sin_addr.s_addr = inet_addr("127.0.0.1");
664 addr.sin_port = base::HostToNet16(port);
665 if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
666 // Try allocate any available port.
667 addr.sin_port = base::HostToNet16(0);
668 if (bind(s, reinterpret_cast<sockaddr*>(&addr), sizeof(addr))) {
669 close(s);
670 LOG(ERROR) << "Could not bind socket to port" << port;
671 s = net::kInvalidSocket;
672 } else {
673 sockaddr_in sock_addr;
674 socklen_t sock_addr_size = sizeof(sock_addr);
675 if (getsockname(s, reinterpret_cast<struct sockaddr*>(&sock_addr),
676 &sock_addr_size) != 0 ||
677 sock_addr_size != sizeof(sock_addr)) {
678 LOG(ERROR) << "Could not determine bound port, getsockname() failed";
679 close(s);
680 s = net::kInvalidSocket;
681 } else {
682 port = base::NetToHost16(sock_addr.sin_port);
683 }
684 }
685 }
686 }
687
688 if (s != net::kInvalidSocket) {
689 SetDebugStubPort(port);
690 }
691 if (s == net::kInvalidSocket) {
692 LOG(ERROR) << "failed to open socket for debug stub";
693 return net::kInvalidSocket;
694 }
695 LOG(WARNING) << "debug stub on port " << port;
696 if (listen(s, 1)) {
697 LOG(ERROR) << "listen() failed on debug stub socket";
698 if (IGNORE_EINTR(close(s)) < 0)
699 PLOG(ERROR) << "failed to close debug stub socket";
700 return net::kInvalidSocket;
701 }
702 return s;
703 }
704 #endif
705
706 #if BUILDFLAG(IS_WIN)
OnDebugStubPortSelected(uint16_t debug_stub_port)707 void NaClProcessHost::OnDebugStubPortSelected(uint16_t debug_stub_port) {
708 SetDebugStubPort(debug_stub_port);
709 }
710 #endif
711
StartNaClExecution()712 bool NaClProcessHost::StartNaClExecution() {
713 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
714
715 NaClStartParams params;
716
717 params.process_type = process_type_;
718 bool enable_nacl_debug = enable_debug_stub_ &&
719 NaClBrowser::GetDelegate()->URLMatchesDebugPatterns(manifest_url_);
720 params.validation_cache_enabled = nacl_browser->ValidationCacheIsEnabled();
721 params.validation_cache_key = nacl_browser->GetValidationCacheKey();
722 params.version = NaClBrowser::GetDelegate()->GetVersionString();
723 params.enable_debug_stub = enable_nacl_debug;
724
725 const base::File& irt_file = nacl_browser->IrtFile();
726 CHECK(irt_file.IsValid());
727 // Send over the IRT file handle. We don't close our own copy!
728 params.irt_handle =
729 IPC::GetPlatformFileForTransit(irt_file.GetPlatformFile(), false);
730 if (params.irt_handle == IPC::InvalidPlatformFileForTransit()) {
731 return false;
732 }
733
734 #if BUILDFLAG(IS_POSIX)
735 if (params.enable_debug_stub) {
736 net::SocketDescriptor server_bound_socket = GetDebugStubSocketHandle();
737 if (server_bound_socket != net::kInvalidSocket) {
738 params.debug_stub_server_bound_socket =
739 IPC::GetPlatformFileForTransit(server_bound_socket, true);
740 }
741 }
742 #endif
743
744 // Create a shared memory region that the renderer and the plugin share to
745 // report crash information.
746 params.crash_info_shmem_region =
747 base::WritableSharedMemoryRegion::Create(kNaClCrashInfoShmemSize);
748 if (!params.crash_info_shmem_region.IsValid()) {
749 DLOG(ERROR) << "Failed to create a shared memory buffer";
750 return false;
751 }
752
753 // Pass the pre-opened resource files to the loader. We do not have to reopen
754 // resource files here because the descriptors are not from a renderer.
755 for (size_t i = 0; i < prefetched_resource_files_.size(); ++i) {
756 process_->Send(
757 new NaClProcessMsg_AddPrefetchedResource(NaClResourcePrefetchResult(
758 prefetched_resource_files_[i].file,
759 prefetched_resource_files_[i].file_path_metadata,
760 prefetched_resource_files_[i].file_key)));
761 }
762 prefetched_resource_files_.clear();
763
764 base::FilePath file_path;
765 if (NaClBrowser::GetInstance()->GetFilePath(nexe_token_.lo, nexe_token_.hi,
766 &file_path)) {
767 // We have to reopen the file in the browser process; we don't want a
768 // compromised renderer to pass an arbitrary fd that could get loaded
769 // into the plugin process.
770 base::ThreadPool::PostTaskAndReplyWithResult(
771 FROM_HERE,
772 // USER_BLOCKING because it is on the critical path of displaying the
773 // official virtual keyboard on Chrome OS. https://crbug.com/976542
774 {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
775 base::BindOnce(OpenNaClReadExecImpl, file_path,
776 true /* is_executable */),
777 base::BindOnce(&NaClProcessHost::StartNaClFileResolved,
778 weak_factory_.GetWeakPtr(), std::move(params),
779 file_path));
780 return true;
781 }
782
783 StartNaClFileResolved(std::move(params), base::FilePath(), base::File());
784 return true;
785 }
786
StartNaClFileResolved(NaClStartParams params,const base::FilePath & file_path,base::File checked_nexe_file)787 void NaClProcessHost::StartNaClFileResolved(
788 NaClStartParams params,
789 const base::FilePath& file_path,
790 base::File checked_nexe_file) {
791 if (checked_nexe_file.IsValid()) {
792 // Release the file received from the renderer. This has to be done on a
793 // thread where IO is permitted, though.
794 base::ThreadPool::PostTask(
795 FROM_HERE, {base::TaskPriority::BEST_EFFORT, base::MayBlock()},
796 base::BindOnce(&CloseFile, std::move(nexe_file_)));
797 params.nexe_file_path_metadata = file_path;
798 params.nexe_file =
799 IPC::TakePlatformFileForTransit(std::move(checked_nexe_file));
800 } else {
801 params.nexe_file = IPC::TakePlatformFileForTransit(std::move(nexe_file_));
802 }
803
804 process_->Send(new NaClProcessMsg_Start(std::move(params)));
805 }
806
StartPPAPIProxy(mojo::ScopedMessagePipeHandle channel_handle)807 bool NaClProcessHost::StartPPAPIProxy(
808 mojo::ScopedMessagePipeHandle channel_handle) {
809 if (ipc_proxy_channel_.get()) {
810 // Attempt to open more than 1 browser channel is not supported.
811 // Shut down the NaCl process.
812 process_->GetHost()->ForceShutdown();
813 return false;
814 }
815
816 DCHECK_EQ(PROCESS_TYPE_NACL_LOADER, process_->GetData().process_type);
817
818 ipc_proxy_channel_ = IPC::ChannelProxy::Create(
819 channel_handle.release(), IPC::Channel::MODE_CLIENT, nullptr,
820 base::SingleThreadTaskRunner::GetCurrentDefault().get(),
821 base::SingleThreadTaskRunner::GetCurrentDefault().get());
822 // Create the browser ppapi host and enable PPAPI message dispatching to the
823 // browser process.
824 ppapi_host_.reset(content::BrowserPpapiHost::CreateExternalPluginProcess(
825 ipc_proxy_channel_.get(), // sender
826 permissions_, process_->GetData().GetProcess().Duplicate(),
827 ipc_proxy_channel_.get(), profile_directory_));
828
829 ppapi::PpapiNaClPluginArgs args;
830 args.off_the_record = nacl_host_message_filter_->off_the_record();
831 args.permissions = permissions_;
832 base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess();
833 DCHECK(cmdline);
834 std::string flag_allowlist[] = {
835 switches::kV,
836 switches::kVModule,
837 };
838 for (size_t i = 0; i < std::size(flag_allowlist); ++i) {
839 std::string value = cmdline->GetSwitchValueASCII(flag_allowlist[i]);
840 if (!value.empty()) {
841 args.switch_names.push_back(flag_allowlist[i]);
842 args.switch_values.push_back(value);
843 }
844 }
845
846 std::string enabled_features;
847 std::string disabled_features;
848 base::FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features,
849 &disabled_features);
850 if (!enabled_features.empty()) {
851 args.switch_names.push_back(switches::kEnableFeatures);
852 args.switch_values.push_back(enabled_features);
853 }
854 if (!disabled_features.empty()) {
855 args.switch_names.push_back(switches::kDisableFeatures);
856 args.switch_values.push_back(disabled_features);
857 }
858
859 ppapi_host_->GetPpapiHost()->AddHostFactoryFilter(
860 std::unique_ptr<ppapi::host::HostFactory>(
861 NaClBrowser::GetDelegate()->CreatePpapiHostFactory(
862 ppapi_host_.get())));
863
864 // Send a message to initialize the IPC dispatchers in the NaCl plugin.
865 ipc_proxy_channel_->Send(new PpapiMsg_InitializeNaClDispatcher(args));
866 return true;
867 }
868
869 // This method is called when NaClProcessHostMsg_PpapiChannelCreated is
870 // 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)871 void NaClProcessHost::OnPpapiChannelsCreated(
872 const IPC::ChannelHandle& raw_ppapi_browser_channel_handle,
873 const IPC::ChannelHandle& raw_ppapi_renderer_channel_handle,
874 const IPC::ChannelHandle& raw_trusted_renderer_channel_handle,
875 const IPC::ChannelHandle& raw_manifest_service_channel_handle,
876 base::ReadOnlySharedMemoryRegion crash_info_shmem_region) {
877 DCHECK(raw_ppapi_browser_channel_handle.is_mojo_channel_handle());
878 DCHECK(raw_ppapi_renderer_channel_handle.is_mojo_channel_handle());
879 DCHECK(raw_trusted_renderer_channel_handle.is_mojo_channel_handle());
880 DCHECK(raw_manifest_service_channel_handle.is_mojo_channel_handle());
881
882 mojo::ScopedMessagePipeHandle ppapi_browser_channel_handle(
883 raw_ppapi_browser_channel_handle.mojo_handle);
884 mojo::ScopedMessagePipeHandle ppapi_renderer_channel_handle(
885 raw_ppapi_renderer_channel_handle.mojo_handle);
886 mojo::ScopedMessagePipeHandle trusted_renderer_channel_handle(
887 raw_trusted_renderer_channel_handle.mojo_handle);
888 mojo::ScopedMessagePipeHandle manifest_service_channel_handle(
889 raw_manifest_service_channel_handle.mojo_handle);
890
891 if (!StartPPAPIProxy(std::move(ppapi_browser_channel_handle))) {
892 SendErrorToRenderer("Browser PPAPI proxy could not start.");
893 return;
894 }
895
896 // Let the renderer know that the IPC channels are established.
897 ReplyToRenderer(std::move(ppapi_renderer_channel_handle),
898 std::move(trusted_renderer_channel_handle),
899 std::move(manifest_service_channel_handle),
900 std::move(crash_info_shmem_region));
901 }
902
StartWithLaunchedProcess()903 bool NaClProcessHost::StartWithLaunchedProcess() {
904 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
905
906 if (nacl_browser->IsReady())
907 return StartNaClExecution();
908 if (nacl_browser->IsOk()) {
909 nacl_browser->WaitForResources(base::BindOnce(
910 &NaClProcessHost::OnResourcesReady, weak_factory_.GetWeakPtr()));
911 return true;
912 }
913 SendErrorToRenderer("previously failed to acquire shared resources");
914 return false;
915 }
916
OnQueryKnownToValidate(const std::string & signature,bool * result)917 void NaClProcessHost::OnQueryKnownToValidate(const std::string& signature,
918 bool* result) {
919 NaClBrowser* nacl_browser = NaClBrowser::GetInstance();
920 *result = nacl_browser->QueryKnownToValidate(signature, off_the_record_);
921 }
922
OnSetKnownToValidate(const std::string & signature)923 void NaClProcessHost::OnSetKnownToValidate(const std::string& signature) {
924 NaClBrowser::GetInstance()->SetKnownToValidate(
925 signature, off_the_record_);
926 }
927
OnResolveFileToken(uint64_t file_token_lo,uint64_t file_token_hi)928 void NaClProcessHost::OnResolveFileToken(uint64_t file_token_lo,
929 uint64_t file_token_hi) {
930 // Was the file registered?
931 //
932 // Note that the file path cache is of bounded size, and old entries can get
933 // evicted. If a large number of NaCl modules are being launched at once,
934 // resolving the file_token may fail because the path cache was thrashed
935 // while the file_token was in flight. In this case the query fails, and we
936 // need to fall back to the slower path.
937 //
938 // However: each NaCl process will consume 2-3 entries as it starts up, this
939 // means that eviction will not happen unless you start up 33+ NaCl processes
940 // at the same time, and this still requires worst-case timing. As a
941 // practical matter, no entries should be evicted prematurely.
942 // The cache itself should take ~ (150 characters * 2 bytes/char + ~60 bytes
943 // data structure overhead) * 100 = 35k when full, so making it bigger should
944 // not be a problem, if needed.
945 //
946 // Each NaCl process will consume 2-3 entries because the manifest and main
947 // nexe are currently not resolved. Shared libraries will be resolved. They
948 // will be loaded sequentially, so they will only consume a single entry
949 // while the load is in flight.
950 //
951 // TODO(ncbray): track behavior with UMA. If entries are getting evicted or
952 // bogus keys are getting queried, this would be good to know.
953 base::FilePath file_path;
954 if (!NaClBrowser::GetInstance()->GetFilePath(
955 file_token_lo, file_token_hi, &file_path)) {
956 Send(new NaClProcessMsg_ResolveFileTokenReply(
957 file_token_lo,
958 file_token_hi,
959 IPC::PlatformFileForTransit(),
960 base::FilePath()));
961 return;
962 }
963
964 // Open the file.
965 base::ThreadPool::PostTaskAndReplyWithResult(
966 FROM_HERE,
967 // USER_BLOCKING because it is on the critical path of displaying the
968 // official virtual keyboard on Chrome OS. https://crbug.com/976542
969 {base::MayBlock(), base::TaskPriority::USER_BLOCKING},
970 base::BindOnce(OpenNaClReadExecImpl, file_path, true /* is_executable */),
971 base::BindOnce(&NaClProcessHost::FileResolved, weak_factory_.GetWeakPtr(),
972 file_token_lo, file_token_hi, file_path));
973 }
974
FileResolved(uint64_t file_token_lo,uint64_t file_token_hi,const base::FilePath & file_path,base::File file)975 void NaClProcessHost::FileResolved(
976 uint64_t file_token_lo,
977 uint64_t file_token_hi,
978 const base::FilePath& file_path,
979 base::File file) {
980 base::FilePath out_file_path;
981 IPC::PlatformFileForTransit out_handle;
982 if (file.IsValid()) {
983 out_file_path = file_path;
984 out_handle = IPC::TakePlatformFileForTransit(std::move(file));
985 } else {
986 out_handle = IPC::InvalidPlatformFileForTransit();
987 }
988 Send(new NaClProcessMsg_ResolveFileTokenReply(
989 file_token_lo,
990 file_token_hi,
991 out_handle,
992 out_file_path));
993 }
994
995 #if BUILDFLAG(IS_WIN)
OnAttachDebugExceptionHandler(const std::string & info,IPC::Message * reply_msg)996 void NaClProcessHost::OnAttachDebugExceptionHandler(const std::string& info,
997 IPC::Message* reply_msg) {
998 if (!AttachDebugExceptionHandler(info, reply_msg)) {
999 // Send failure message.
1000 NaClProcessMsg_AttachDebugExceptionHandler::WriteReplyParams(reply_msg,
1001 false);
1002 Send(reply_msg);
1003 }
1004 }
1005
AttachDebugExceptionHandler(const std::string & info,IPC::Message * reply_msg)1006 bool NaClProcessHost::AttachDebugExceptionHandler(const std::string& info,
1007 IPC::Message* reply_msg) {
1008 bool enable_exception_handling = process_type_ == kNativeNaClProcessType;
1009 if (!enable_exception_handling && !enable_debug_stub_) {
1010 DLOG(ERROR) <<
1011 "Debug exception handler requested by NaCl process when not enabled";
1012 return false;
1013 }
1014 if (debug_exception_handler_requested_) {
1015 // The NaCl process should not request this multiple times.
1016 DLOG(ERROR) << "Multiple AttachDebugExceptionHandler requests received";
1017 return false;
1018 }
1019 debug_exception_handler_requested_ = true;
1020
1021 base::ProcessId nacl_pid = process_->GetData().GetProcess().Pid();
1022 // We cannot use process_->GetData().handle because it does not have
1023 // the necessary access rights. We open the new handle here rather
1024 // than in the NaCl broker process in case the NaCl loader process
1025 // dies before the NaCl broker process receives the message we send.
1026 // The debug exception handler uses DebugActiveProcess() to attach,
1027 // but this takes a PID. We need to prevent the NaCl loader's PID
1028 // from being reused before DebugActiveProcess() is called, and
1029 // holding a process handle open achieves this.
1030 base::Process process =
1031 base::Process::OpenWithAccess(nacl_pid,
1032 PROCESS_QUERY_INFORMATION |
1033 PROCESS_SUSPEND_RESUME |
1034 PROCESS_TERMINATE |
1035 PROCESS_VM_OPERATION |
1036 PROCESS_VM_READ |
1037 PROCESS_VM_WRITE |
1038 PROCESS_DUP_HANDLE |
1039 SYNCHRONIZE);
1040 if (!process.IsValid()) {
1041 LOG(ERROR) << "Failed to get process handle";
1042 return false;
1043 }
1044
1045 attach_debug_exception_handler_reply_msg_.reset(reply_msg);
1046 // If the NaCl loader is 64-bit, the process running its debug
1047 // exception handler must be 64-bit too, so we use the 64-bit NaCl
1048 // broker process for this. Otherwise, on a 32-bit system, we use
1049 // the 32-bit browser process to run the debug exception handler.
1050 if (RunningOnWOW64()) {
1051 return NaClBrokerService::GetInstance()->LaunchDebugExceptionHandler(
1052 weak_factory_.GetWeakPtr(), nacl_pid, process.Handle(),
1053 info);
1054 }
1055 NaClStartDebugExceptionHandlerThread(
1056 std::move(process), info,
1057 base::SingleThreadTaskRunner::GetCurrentDefault(),
1058 base::BindRepeating(
1059 &NaClProcessHost::OnDebugExceptionHandlerLaunchedByBroker,
1060 weak_factory_.GetWeakPtr()));
1061 return true;
1062 }
1063 #endif
1064
1065 } // namespace nacl
1066