1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/nacl/loader/nacl_listener.h"
14 #include "base/command_line.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/rand_util.h"
19 #include "components/nacl/common/nacl_messages.h"
20 #include "components/nacl/loader/nacl_ipc_adapter.h"
21 #include "components/nacl/loader/nacl_validation_db.h"
22 #include "components/nacl/loader/nacl_validation_query.h"
23 #include "ipc/ipc_channel_handle.h"
24 #include "ipc/ipc_switches.h"
25 #include "ipc/ipc_sync_channel.h"
26 #include "ipc/ipc_sync_message_filter.h"
27 #include "native_client/src/public/chrome_main.h"
28 #include "native_client/src/public/nacl_app.h"
29 #include "native_client/src/trusted/validator/nacl_file_info.h"
32 #include "base/file_descriptor_posix.h"
36 #include "components/nacl/loader/nonsfi/nonsfi_main.h"
37 #include "content/public/common/child_process_sandbox_support_linux.h"
44 #include "content/public/common/sandbox_init.h"
48 #if defined(OS_MACOSX)
50 // On Mac OS X, shm_open() works in the sandbox but does not give us
51 // an FD that we can map as PROT_EXEC. Rather than doing an IPC to
52 // get an executable SHM region when CreateMemoryObject() is called,
53 // we preallocate one on startup, since NaCl's sel_ldr only needs one
54 // of them. This saves a round trip.
56 base::subtle::Atomic32 g_shm_fd = -1;
58 int CreateMemoryObject(size_t size, int executable) {
59 if (executable && size > 0) {
60 int result_fd = base::subtle::NoBarrier_AtomicExchange(&g_shm_fd, -1);
61 if (result_fd != -1) {
62 // ftruncate() is disallowed by the Mac OS X sandbox and
63 // returns EPERM. Luckily, we can get the same effect with
65 if (lseek(result_fd, size - 1, SEEK_SET) == -1) {
66 LOG(ERROR) << "lseek() failed: " << errno;
69 if (write(result_fd, "", 1) != 1) {
70 LOG(ERROR) << "write() failed: " << errno;
76 // Fall back to NaCl's default implementation.
80 #elif defined(OS_LINUX)
82 int CreateMemoryObject(size_t size, int executable) {
83 return content::MakeSharedMemorySegmentViaIPC(size, executable);
88 NaClListener* g_listener;
90 // We wrap the function to convert the bool return value to an int.
91 int BrokerDuplicateHandle(NaClHandle source_handle,
93 NaClHandle* target_handle,
94 uint32_t desired_access,
96 return content::BrokerDuplicateHandle(source_handle, process_id,
97 target_handle, desired_access,
101 int AttachDebugExceptionHandler(const void* info, size_t info_size) {
102 std::string info_string(reinterpret_cast<const char*>(info), info_size);
104 if (!g_listener->Send(new NaClProcessMsg_AttachDebugExceptionHandler(
105 info_string, &result)))
112 // Creates the PPAPI IPC channel between the NaCl IRT and the host
113 // (browser/renderer) process, and starts to listen it on the thread where
114 // the given message_loop_proxy runs.
115 // Also, creates and sets the corresponding NaClDesc to the given nap with
117 void SetUpIPCAdapter(IPC::ChannelHandle* handle,
118 scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
121 scoped_refptr<NaClIPCAdapter> ipc_adapter(
122 new NaClIPCAdapter(*handle, message_loop_proxy.get()));
123 ipc_adapter->ConnectChannel();
124 #if defined(OS_POSIX)
126 base::FileDescriptor(ipc_adapter->TakeClientFileDescriptor(), true);
129 // Pass a NaClDesc to the untrusted side. This will hold a ref to the
131 NaClAppSetDesc(nap, nacl_fd, ipc_adapter->MakeNaClDesc());
136 class BrowserValidationDBProxy : public NaClValidationDB {
138 explicit BrowserValidationDBProxy(NaClListener* listener)
139 : listener_(listener) {
142 virtual bool QueryKnownToValidate(const std::string& signature) OVERRIDE {
143 // Initialize to false so that if the Send fails to write to the return
144 // value we're safe. For example if the message is (for some reason)
145 // dispatched as an async message the return parameter will not be written.
147 if (!listener_->Send(new NaClProcessMsg_QueryKnownToValidate(signature,
149 LOG(ERROR) << "Failed to query NaCl validation cache.";
155 virtual void SetKnownToValidate(const std::string& signature) OVERRIDE {
156 // Caching is optional: NaCl will still work correctly if the IPC fails.
157 if (!listener_->Send(new NaClProcessMsg_SetKnownToValidate(signature))) {
158 LOG(ERROR) << "Failed to update NaCl validation cache.";
162 virtual bool ResolveFileToken(struct NaClFileToken* file_token,
163 int32* fd, std::string* path) OVERRIDE {
166 if (file_token->lo == 0 && file_token->hi == 0) {
169 IPC::PlatformFileForTransit ipc_fd = IPC::InvalidPlatformFileForTransit();
170 base::FilePath ipc_path;
171 if (!listener_->Send(new NaClProcessMsg_ResolveFileToken(file_token->lo,
177 if (ipc_fd == IPC::InvalidPlatformFileForTransit()) {
180 base::PlatformFile handle =
181 IPC::PlatformFileForTransitToPlatformFile(ipc_fd);
183 // On Windows, valid handles are 32 bit unsigned integers so this is safe.
184 *fd = reinterpret_cast<uintptr_t>(handle);
188 // It doesn't matter if the path is invalid UTF8 as long as it's consistent
190 *path = ipc_path.AsUTF8Unsafe();
195 // The listener never dies, otherwise this might be a dangling reference.
196 NaClListener* listener_;
200 NaClListener::NaClListener() : shutdown_event_(true, false),
201 io_thread_("NaCl_IOThread"),
202 #if defined(OS_LINUX)
203 prereserved_sandbox_size_(0),
205 #if defined(OS_POSIX)
206 number_of_cores_(-1), // unknown/error
209 io_thread_.StartWithOptions(
210 base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
212 DCHECK(g_listener == NULL);
217 NaClListener::~NaClListener() {
219 shutdown_event_.Signal();
225 bool NaClListener::Send(IPC::Message* msg) {
226 DCHECK(main_loop_ != NULL);
227 if (base::MessageLoop::current() == main_loop_) {
228 // This thread owns the channel.
229 return channel_->Send(msg);
231 // This thread does not own the channel.
232 return filter_->Send(msg);
236 void NaClListener::Listen() {
237 std::string channel_name =
238 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
239 switches::kProcessChannelID);
240 channel_.reset(new IPC::SyncChannel(
241 this, io_thread_.message_loop_proxy().get(), &shutdown_event_));
242 filter_ = new IPC::SyncMessageFilter(&shutdown_event_);
243 channel_->AddFilter(filter_.get());
244 channel_->Init(channel_name, IPC::Channel::MODE_CLIENT, true);
245 main_loop_ = base::MessageLoop::current();
249 bool NaClListener::OnMessageReceived(const IPC::Message& msg) {
251 IPC_BEGIN_MESSAGE_MAP(NaClListener, msg)
252 IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStart)
253 IPC_MESSAGE_UNHANDLED(handled = false)
254 IPC_END_MESSAGE_MAP()
258 void NaClListener::OnStart(const nacl::NaClStartParams& params) {
259 #if defined(OS_LINUX) || defined(OS_MACOSX)
260 int urandom_fd = dup(base::GetUrandomFD());
261 if (urandom_fd < 0) {
262 LOG(ERROR) << "Failed to dup() the urandom FD";
265 NaClChromeMainSetUrandomFd(urandom_fd);
268 NaClChromeMainInit();
269 struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
271 LOG(ERROR) << "NaClChromeMainArgsCreate() failed";
275 struct NaClApp *nap = NaClAppCreate();
277 LOG(ERROR) << "NaClAppCreate() failed";
281 if (params.enable_ipc_proxy) {
282 // Create the PPAPI IPC channels between the NaCl IRT and the hosts
283 // (browser/renderer) processes. The IRT uses these channels to communicate
284 // with the host and to initialize the IPC dispatchers.
285 IPC::ChannelHandle browser_handle =
286 IPC::Channel::GenerateVerifiedChannelID("nacl");
287 SetUpIPCAdapter(&browser_handle, io_thread_.message_loop_proxy(),
288 nap, NACL_CHROME_DESC_BASE);
290 IPC::ChannelHandle renderer_handle =
291 IPC::Channel::GenerateVerifiedChannelID("nacl");
292 SetUpIPCAdapter(&renderer_handle, io_thread_.message_loop_proxy(),
293 nap, NACL_CHROME_DESC_BASE + 1);
295 if (!Send(new NaClProcessHostMsg_PpapiChannelsCreated(
296 browser_handle, renderer_handle)))
297 LOG(ERROR) << "Failed to send IPC channel handle to NaClProcessHost.";
300 std::vector<nacl::FileDescriptor> handles = params.handles;
302 #if defined(OS_LINUX) || defined(OS_MACOSX)
303 args->number_of_cores = number_of_cores_;
304 args->create_memory_object_func = CreateMemoryObject;
305 # if defined(OS_MACOSX)
306 CHECK(handles.size() >= 1);
307 g_shm_fd = nacl::ToNativeHandle(handles[handles.size() - 1]);
312 if (params.uses_irt) {
313 CHECK(handles.size() >= 1);
314 NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]);
318 args->irt_fd = _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle),
319 _O_RDONLY | _O_BINARY);
320 if (args->irt_fd < 0) {
321 LOG(ERROR) << "_open_osfhandle() failed";
325 args->irt_fd = irt_handle;
328 // Otherwise, the IRT handle is not even sent.
332 if (params.validation_cache_enabled) {
333 // SHA256 block size.
334 CHECK_EQ(params.validation_cache_key.length(), (size_t) 64);
335 // The cache structure is not freed and exists until the NaCl process exits.
336 args->validation_cache = CreateValidationCache(
337 new BrowserValidationDBProxy(this), params.validation_cache_key,
341 CHECK(handles.size() == 1);
342 args->imc_bootstrap_handle = nacl::ToNativeHandle(handles[0]);
343 args->enable_exception_handling = params.enable_exception_handling;
344 args->enable_debug_stub = params.enable_debug_stub;
345 args->enable_dyncode_syscalls = params.enable_dyncode_syscalls;
346 if (!params.enable_dyncode_syscalls) {
347 // Bound the initial nexe's code segment size under PNaCl to
348 // reduce the chance of a code spraying attack succeeding (see
349 // https://code.google.com/p/nativeclient/issues/detail?id=3572).
350 // We assume that !params.enable_dyncode_syscalls is synonymous
351 // with PNaCl. We can't apply this arbitrary limit outside of
352 // PNaCl because it might break existing NaCl apps, and this limit
353 // is only useful if the dyncode syscalls are disabled.
354 args->initial_nexe_max_code_bytes = 32 << 20; // 32 MB
356 #if defined(OS_LINUX) || defined(OS_MACOSX)
357 args->debug_stub_server_bound_socket_fd = nacl::ToNativeHandle(
358 params.debug_stub_server_bound_socket);
361 args->broker_duplicate_handle_func = BrokerDuplicateHandle;
362 args->attach_debug_exception_handler_func = AttachDebugExceptionHandler;
364 #if defined(OS_LINUX)
365 args->prereserved_sandbox_size = prereserved_sandbox_size_;
368 #if defined(OS_LINUX)
369 if (params.enable_nonsfi_mode) {
370 nacl::nonsfi::MainStart(args->imc_bootstrap_handle);
375 NaClChromeMainStartApp(nap, args);