1 // Copyright 2013 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/loader/nacl_listener.h"
6
7 #include <errno.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include <memory>
13 #include <utility>
14
15 #include "base/functional/bind.h"
16 #include "base/memory/raw_ptr.h"
17 #include "base/task/single_thread_task_runner.h"
18 #include "build/build_config.h"
19
20 #if BUILDFLAG(IS_POSIX)
21 #include <unistd.h>
22 #endif
23
24 #include "base/command_line.h"
25 #include "base/logging.h"
26 #include "base/memory/read_only_shared_memory_region.h"
27 #include "base/message_loop/message_pump_type.h"
28 #include "base/rand_util.h"
29 #include "base/run_loop.h"
30 #include "base/synchronization/waitable_event.h"
31 #include "base/task/single_thread_task_runner.h"
32 #include "components/nacl/common/nacl.mojom.h"
33 #include "components/nacl/common/nacl_messages.h"
34 #include "components/nacl/common/nacl_service.h"
35 #include "components/nacl/common/nacl_switches.h"
36 #include "components/nacl/loader/nacl_ipc_adapter.h"
37 #include "components/nacl/loader/nacl_validation_db.h"
38 #include "components/nacl/loader/nacl_validation_query.h"
39 #include "ipc/ipc_channel_handle.h"
40 #include "ipc/ipc_sync_channel.h"
41 #include "ipc/ipc_sync_message_filter.h"
42 #include "mojo/public/cpp/bindings/pending_remote.h"
43 #include "native_client/src/public/chrome_main.h"
44 #include "native_client/src/public/nacl_app.h"
45 #include "native_client/src/public/nacl_desc.h"
46
47 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
48 #include "content/public/common/zygote/sandbox_support_linux.h"
49 #endif
50
51 #if BUILDFLAG(IS_POSIX)
52 #include "base/posix/eintr_wrapper.h"
53 #endif
54
55 namespace {
56
57 NaClListener* g_listener;
58
FatalLogHandler(const char * data,size_t bytes)59 void FatalLogHandler(const char* data, size_t bytes) {
60 // We use uint32_t rather than size_t for the case when the browser and NaCl
61 // processes are a mix of 32-bit and 64-bit processes.
62 uint32_t copy_bytes = std::min<uint32_t>(static_cast<uint32_t>(bytes),
63 nacl::kNaClCrashInfoMaxLogSize);
64
65 // We copy the length of the crash data to the start of the shared memory
66 // segment so we know how much to copy.
67 memcpy(g_listener->crash_info_shmem_memory(), ©_bytes, sizeof(uint32_t));
68
69 memcpy((char*)g_listener->crash_info_shmem_memory() + sizeof(uint32_t),
70 data,
71 copy_bytes);
72 }
73
LoadStatusCallback(int load_status)74 void LoadStatusCallback(int load_status) {
75 g_listener->trusted_listener()->renderer_host()->ReportLoadStatus(
76 static_cast<NaClErrorCode>(load_status));
77 }
78
79 // Creates the PPAPI IPC channel between the NaCl IRT and the host
80 // (browser/renderer) process, and starts to listen it on the thread where
81 // the given task runner runs.
82 // Also, creates and sets the corresponding NaClDesc to the given nap with
83 // the FD #.
SetUpIPCAdapter(IPC::ChannelHandle * handle,scoped_refptr<base::SingleThreadTaskRunner> task_runner,struct NaClApp * nap,int nacl_fd,NaClIPCAdapter::ResolveFileTokenCallback resolve_file_token_cb,NaClIPCAdapter::OpenResourceCallback open_resource_cb)84 void SetUpIPCAdapter(
85 IPC::ChannelHandle* handle,
86 scoped_refptr<base::SingleThreadTaskRunner> task_runner,
87 struct NaClApp* nap,
88 int nacl_fd,
89 NaClIPCAdapter::ResolveFileTokenCallback resolve_file_token_cb,
90 NaClIPCAdapter::OpenResourceCallback open_resource_cb) {
91 mojo::MessagePipe pipe;
92 scoped_refptr<NaClIPCAdapter> ipc_adapter(new NaClIPCAdapter(
93 pipe.handle0.release(), task_runner, std::move(resolve_file_token_cb),
94 std::move(open_resource_cb)));
95 ipc_adapter->ConnectChannel();
96 *handle = pipe.handle1.release();
97
98 // Pass a NaClDesc to the untrusted side. This will hold a ref to the
99 // NaClIPCAdapter.
100 NaClAppSetDesc(nap, nacl_fd, ipc_adapter->MakeNaClDesc());
101 }
102
103 } // namespace
104
105 class BrowserValidationDBProxy : public NaClValidationDB {
106 public:
BrowserValidationDBProxy(NaClListener * listener)107 explicit BrowserValidationDBProxy(NaClListener* listener)
108 : listener_(listener) {
109 }
110
QueryKnownToValidate(const std::string & signature)111 bool QueryKnownToValidate(const std::string& signature) override {
112 // Initialize to false so that if the Send fails to write to the return
113 // value we're safe. For example if the message is (for some reason)
114 // dispatched as an async message the return parameter will not be written.
115 bool result = false;
116 if (!listener_->Send(new NaClProcessMsg_QueryKnownToValidate(signature,
117 &result))) {
118 LOG(ERROR) << "Failed to query NaCl validation cache.";
119 result = false;
120 }
121 return result;
122 }
123
SetKnownToValidate(const std::string & signature)124 void SetKnownToValidate(const std::string& signature) override {
125 // Caching is optional: NaCl will still work correctly if the IPC fails.
126 if (!listener_->Send(new NaClProcessMsg_SetKnownToValidate(signature))) {
127 LOG(ERROR) << "Failed to update NaCl validation cache.";
128 }
129 }
130
131 private:
132 // The listener never dies, otherwise this might be a dangling reference.
133 raw_ptr<NaClListener> listener_;
134 };
135
NaClListener()136 NaClListener::NaClListener()
137 : shutdown_event_(base::WaitableEvent::ResetPolicy::MANUAL,
138 base::WaitableEvent::InitialState::NOT_SIGNALED),
139 io_thread_("NaCl_IOThread"),
140 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
141 prereserved_sandbox_size_(0),
142 #endif
143 #if BUILDFLAG(IS_POSIX)
144 number_of_cores_(-1), // unknown/error
145 #endif
146 is_started_(false) {
147 io_thread_.StartWithOptions(
148 base::Thread::Options(base::MessagePumpType::IO, 0));
149 DCHECK(g_listener == NULL);
150 g_listener = this;
151 }
152
~NaClListener()153 NaClListener::~NaClListener() {
154 NOTREACHED();
155 shutdown_event_.Signal();
156 g_listener = NULL;
157 }
158
Send(IPC::Message * msg)159 bool NaClListener::Send(IPC::Message* msg) {
160 DCHECK(!!main_task_runner_);
161 if (main_task_runner_->BelongsToCurrentThread()) {
162 // This thread owns the channel.
163 return channel_->Send(msg);
164 }
165 // This thread does not own the channel.
166 return filter_->Send(msg);
167 }
168
169 // The NaClProcessMsg_ResolveFileTokenAsyncReply message must be
170 // processed in a MessageFilter so it can be handled on the IO thread.
171 // The main thread used by NaClListener is busy in
172 // NaClChromeMainAppStart(), so it can't be used for servicing messages.
173 class FileTokenMessageFilter : public IPC::MessageFilter {
174 public:
OnMessageReceived(const IPC::Message & msg)175 bool OnMessageReceived(const IPC::Message& msg) override {
176 bool handled = true;
177 IPC_BEGIN_MESSAGE_MAP(FileTokenMessageFilter, msg)
178 IPC_MESSAGE_HANDLER(NaClProcessMsg_ResolveFileTokenReply,
179 OnResolveFileTokenReply)
180 IPC_MESSAGE_UNHANDLED(handled = false)
181 IPC_END_MESSAGE_MAP()
182 return handled;
183 }
184
OnResolveFileTokenReply(uint64_t token_lo,uint64_t token_hi,IPC::PlatformFileForTransit ipc_fd,base::FilePath file_path)185 void OnResolveFileTokenReply(
186 uint64_t token_lo,
187 uint64_t token_hi,
188 IPC::PlatformFileForTransit ipc_fd,
189 base::FilePath file_path) {
190 CHECK(g_listener);
191 g_listener->OnFileTokenResolved(token_lo, token_hi, ipc_fd, file_path);
192 }
193 private:
~FileTokenMessageFilter()194 ~FileTokenMessageFilter() override {}
195 };
196
Listen()197 void NaClListener::Listen() {
198 NaClService service(io_thread_.task_runner());
199 channel_ = IPC::SyncChannel::Create(
200 this, io_thread_.task_runner().get(),
201 base::SingleThreadTaskRunner::GetCurrentDefault(), &shutdown_event_);
202 filter_ = channel_->CreateSyncMessageFilter();
203 channel_->AddFilter(new FileTokenMessageFilter());
204 channel_->Init(service.TakeChannelPipe().release(), IPC::Channel::MODE_CLIENT,
205 true);
206 main_task_runner_ = base::SingleThreadTaskRunner::GetCurrentDefault();
207 base::RunLoop().Run();
208 }
209
210 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
211 // static
MakeSharedMemorySegment(size_t length,int executable)212 int NaClListener::MakeSharedMemorySegment(size_t length, int executable) {
213 return content::SharedMemoryIPCSupport::MakeSharedMemorySegment(length,
214 executable);
215 }
216 #endif
217
OnMessageReceived(const IPC::Message & msg)218 bool NaClListener::OnMessageReceived(const IPC::Message& msg) {
219 bool handled = true;
220 IPC_BEGIN_MESSAGE_MAP(NaClListener, msg)
221 IPC_MESSAGE_HANDLER(NaClProcessMsg_AddPrefetchedResource,
222 OnAddPrefetchedResource)
223 IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStart)
224 IPC_MESSAGE_UNHANDLED(handled = false)
225 IPC_END_MESSAGE_MAP()
226 return handled;
227 }
228
OnOpenResource(const IPC::Message & msg,const std::string & key,NaClIPCAdapter::OpenResourceReplyCallback cb)229 bool NaClListener::OnOpenResource(
230 const IPC::Message& msg,
231 const std::string& key,
232 NaClIPCAdapter::OpenResourceReplyCallback cb) {
233 // This callback is executed only on |io_thread_| with NaClIPCAdapter's
234 // |lock_| not being held.
235 DCHECK(!cb.is_null());
236 auto it = prefetched_resource_files_.find(key);
237
238 if (it != prefetched_resource_files_.end()) {
239 // Fast path for prefetched FDs.
240 IPC::PlatformFileForTransit file = it->second.first;
241 base::FilePath path = it->second.second;
242 prefetched_resource_files_.erase(it);
243 // A pre-opened resource descriptor is available. Run the reply callback
244 // and return true.
245 std::move(cb).Run(msg, file, path);
246 return true;
247 }
248
249 // Return false to fall back to the slow path. Let NaClIPCAdapter issue an
250 // IPC to the renderer.
251 return false;
252 }
253
OnAddPrefetchedResource(const nacl::NaClResourcePrefetchResult & prefetched_resource_file)254 void NaClListener::OnAddPrefetchedResource(
255 const nacl::NaClResourcePrefetchResult& prefetched_resource_file) {
256 DCHECK(!is_started_);
257 if (is_started_)
258 return;
259 bool result = prefetched_resource_files_.insert(std::make_pair(
260 prefetched_resource_file.file_key,
261 std::make_pair(
262 prefetched_resource_file.file,
263 prefetched_resource_file.file_path_metadata))).second;
264 if (!result) {
265 LOG(FATAL) << "Duplicated open_resource key: "
266 << prefetched_resource_file.file_key;
267 }
268 }
269
OnStart(nacl::NaClStartParams params)270 void NaClListener::OnStart(nacl::NaClStartParams params) {
271 is_started_ = true;
272 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
273 int urandom_fd = HANDLE_EINTR(dup(base::GetUrandomFD()));
274 if (urandom_fd < 0) {
275 LOG(FATAL) << "Failed to dup() the urandom FD";
276 }
277 NaClChromeMainSetUrandomFd(urandom_fd);
278 #endif
279 struct NaClApp* nap = NULL;
280 NaClChromeMainInit();
281
282 CHECK(params.crash_info_shmem_region.IsValid());
283 crash_info_shmem_mapping_ = params.crash_info_shmem_region.Map();
284 base::ReadOnlySharedMemoryRegion ro_shmem_region =
285 base::WritableSharedMemoryRegion::ConvertToReadOnly(
286 std::move(params.crash_info_shmem_region));
287 CHECK(crash_info_shmem_mapping_.IsValid());
288 CHECK(ro_shmem_region.IsValid());
289 NaClSetFatalErrorCallback(&FatalLogHandler);
290
291 nap = NaClAppCreate();
292 if (nap == NULL) {
293 LOG(FATAL) << "NaClAppCreate() failed";
294 }
295
296 IPC::ChannelHandle browser_handle;
297 IPC::ChannelHandle ppapi_renderer_handle;
298 IPC::ChannelHandle manifest_service_handle;
299
300 // Create the PPAPI IPC channels between the NaCl IRT and the host
301 // (browser/renderer) processes. The IRT uses these channels to
302 // communicate with the host and to initialize the IPC dispatchers.
303 SetUpIPCAdapter(&browser_handle, io_thread_.task_runner(), nap,
304 NACL_CHROME_DESC_BASE,
305 NaClIPCAdapter::ResolveFileTokenCallback(),
306 NaClIPCAdapter::OpenResourceCallback());
307 SetUpIPCAdapter(&ppapi_renderer_handle, io_thread_.task_runner(), nap,
308 NACL_CHROME_DESC_BASE + 1,
309 NaClIPCAdapter::ResolveFileTokenCallback(),
310 NaClIPCAdapter::OpenResourceCallback());
311 SetUpIPCAdapter(&manifest_service_handle, io_thread_.task_runner(), nap,
312 NACL_CHROME_DESC_BASE + 2,
313 base::BindRepeating(&NaClListener::ResolveFileToken,
314 base::Unretained(this)),
315 base::BindRepeating(&NaClListener::OnOpenResource,
316 base::Unretained(this)));
317
318 mojo::PendingRemote<nacl::mojom::NaClRendererHost> renderer_host;
319 if (!Send(new NaClProcessHostMsg_PpapiChannelsCreated(
320 browser_handle, ppapi_renderer_handle,
321 renderer_host.InitWithNewPipeAndPassReceiver().PassPipe().release(),
322 manifest_service_handle, ro_shmem_region)))
323 LOG(FATAL) << "Failed to send IPC channel handle to NaClProcessHost.";
324
325 trusted_listener_ = std::make_unique<NaClTrustedListener>(
326 std::move(renderer_host), io_thread_.task_runner().get());
327 struct NaClChromeMainArgs* args = NaClChromeMainArgsCreate();
328 if (args == NULL) {
329 LOG(FATAL) << "NaClChromeMainArgsCreate() failed";
330 }
331
332 #if BUILDFLAG(IS_POSIX)
333 args->number_of_cores = number_of_cores_;
334 #endif
335
336 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
337 args->create_memory_object_func = &MakeSharedMemorySegment;
338 #endif
339
340 DCHECK(params.process_type != nacl::kUnknownNaClProcessType);
341 CHECK(params.irt_handle != IPC::InvalidPlatformFileForTransit());
342 args->irt_fd = IPC::PlatformFileForTransitToPlatformFile(params.irt_handle);
343
344 if (params.validation_cache_enabled) {
345 // SHA256 block size.
346 CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
347 // The cache structure is not freed and exists until the NaCl process exits.
348 args->validation_cache = CreateValidationCache(
349 new BrowserValidationDBProxy(this), params.validation_cache_key,
350 params.version);
351 }
352
353 args->enable_debug_stub = params.enable_debug_stub;
354
355 // Now configure parts that depend on process type.
356 // Start with stricter settings.
357 args->enable_exception_handling = 0;
358 args->enable_dyncode_syscalls = 0;
359 // pnacl_mode=1 mostly disables things (IRT interfaces and syscalls).
360 args->pnacl_mode = 1;
361 // Bound the initial nexe's code segment size under PNaCl to reduce the
362 // chance of a code spraying attack succeeding (see
363 // https://code.google.com/p/nativeclient/issues/detail?id=3572).
364 // We can't apply this arbitrary limit outside of PNaCl because it might
365 // break existing NaCl apps, and this limit is only useful if the dyncode
366 // syscalls are disabled.
367 args->initial_nexe_max_code_bytes = 64 << 20; // 64 MB.
368
369 if (params.process_type == nacl::kNativeNaClProcessType) {
370 args->enable_exception_handling = 1;
371 args->enable_dyncode_syscalls = 1;
372 args->pnacl_mode = 0;
373 args->initial_nexe_max_code_bytes = 0;
374 } else if (params.process_type == nacl::kPNaClTranslatorProcessType) {
375 args->pnacl_mode = 0;
376 }
377
378 #if BUILDFLAG(IS_POSIX)
379 args->debug_stub_server_bound_socket_fd =
380 IPC::PlatformFileForTransitToPlatformFile(
381 params.debug_stub_server_bound_socket);
382 #endif
383 args->load_status_handler_func = LoadStatusCallback;
384 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
385 args->prereserved_sandbox_size = prereserved_sandbox_size_;
386 #endif
387
388 base::PlatformFile nexe_file = IPC::PlatformFileForTransitToPlatformFile(
389 params.nexe_file);
390 std::string file_path_str = params.nexe_file_path_metadata.AsUTF8Unsafe();
391 args->nexe_desc = NaClDescCreateWithFilePathMetadata(nexe_file,
392 file_path_str.c_str());
393
394 int exit_status;
395 if (!NaClChromeMainStart(nap, args, &exit_status))
396 NaClExit(1);
397
398 // Report the plugin's exit status if the application started successfully.
399 trusted_listener_->renderer_host()->ReportExitStatus(exit_status);
400 NaClExit(exit_status);
401 }
402
ResolveFileToken(uint64_t token_lo,uint64_t token_hi,NaClIPCAdapter::ResolveFileTokenReplyCallback cb)403 void NaClListener::ResolveFileToken(
404 uint64_t token_lo,
405 uint64_t token_hi,
406 NaClIPCAdapter::ResolveFileTokenReplyCallback cb) {
407 if (!Send(new NaClProcessMsg_ResolveFileToken(token_lo, token_hi))) {
408 std::move(cb).Run(IPC::PlatformFileForTransit(), base::FilePath());
409 return;
410 }
411 resolved_cb_ = std::move(cb);
412 }
413
OnFileTokenResolved(uint64_t token_lo,uint64_t token_hi,IPC::PlatformFileForTransit ipc_fd,base::FilePath file_path)414 void NaClListener::OnFileTokenResolved(
415 uint64_t token_lo,
416 uint64_t token_hi,
417 IPC::PlatformFileForTransit ipc_fd,
418 base::FilePath file_path) {
419 if (resolved_cb_)
420 std::move(resolved_cb_).Run(ipc_fd, file_path);
421 }
422