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/trusted/service_runtime/sel_main_chrome.h"
28 #include "native_client/src/trusted/validator/nacl_file_info.h"
31 #include "base/file_descriptor_posix.h"
35 #include "content/public/common/child_process_sandbox_support_linux.h"
42 #include "content/public/common/sandbox_init.h"
46 #if defined(OS_MACOSX)
48 // On Mac OS X, shm_open() works in the sandbox but does not give us
49 // an FD that we can map as PROT_EXEC. Rather than doing an IPC to
50 // get an executable SHM region when CreateMemoryObject() is called,
51 // we preallocate one on startup, since NaCl's sel_ldr only needs one
52 // of them. This saves a round trip.
54 base::subtle::Atomic32 g_shm_fd
= -1;
56 int CreateMemoryObject(size_t size
, int executable
) {
57 if (executable
&& size
> 0) {
58 int result_fd
= base::subtle::NoBarrier_AtomicExchange(&g_shm_fd
, -1);
59 if (result_fd
!= -1) {
60 // ftruncate() is disallowed by the Mac OS X sandbox and
61 // returns EPERM. Luckily, we can get the same effect with
63 if (lseek(result_fd
, size
- 1, SEEK_SET
) == -1) {
64 LOG(ERROR
) << "lseek() failed: " << errno
;
67 if (write(result_fd
, "", 1) != 1) {
68 LOG(ERROR
) << "write() failed: " << errno
;
74 // Fall back to NaCl's default implementation.
78 #elif defined(OS_LINUX)
80 int CreateMemoryObject(size_t size
, int executable
) {
81 return content::MakeSharedMemorySegmentViaIPC(size
, executable
);
86 NaClListener
* g_listener
;
88 // We wrap the function to convert the bool return value to an int.
89 int BrokerDuplicateHandle(NaClHandle source_handle
,
91 NaClHandle
* target_handle
,
92 uint32_t desired_access
,
94 return content::BrokerDuplicateHandle(source_handle
, process_id
,
95 target_handle
, desired_access
,
99 int AttachDebugExceptionHandler(const void* info
, size_t info_size
) {
100 std::string
info_string(reinterpret_cast<const char*>(info
), info_size
);
102 if (!g_listener
->Send(new NaClProcessMsg_AttachDebugExceptionHandler(
103 info_string
, &result
)))
112 class BrowserValidationDBProxy
: public NaClValidationDB
{
114 explicit BrowserValidationDBProxy(NaClListener
* listener
)
115 : listener_(listener
) {
118 virtual bool QueryKnownToValidate(const std::string
& signature
) OVERRIDE
{
119 // Initialize to false so that if the Send fails to write to the return
120 // value we're safe. For example if the message is (for some reason)
121 // dispatched as an async message the return parameter will not be written.
123 if (!listener_
->Send(new NaClProcessMsg_QueryKnownToValidate(signature
,
125 LOG(ERROR
) << "Failed to query NaCl validation cache.";
131 virtual void SetKnownToValidate(const std::string
& signature
) OVERRIDE
{
132 // Caching is optional: NaCl will still work correctly if the IPC fails.
133 if (!listener_
->Send(new NaClProcessMsg_SetKnownToValidate(signature
))) {
134 LOG(ERROR
) << "Failed to update NaCl validation cache.";
138 virtual bool ResolveFileToken(struct NaClFileToken
* file_token
,
139 int32
* fd
, std::string
* path
) OVERRIDE
{
142 if (file_token
->lo
== 0 && file_token
->hi
== 0) {
145 IPC::PlatformFileForTransit ipc_fd
= IPC::InvalidPlatformFileForTransit();
146 base::FilePath ipc_path
;
147 if (!listener_
->Send(new NaClProcessMsg_ResolveFileToken(file_token
->lo
,
153 if (ipc_fd
== IPC::InvalidPlatformFileForTransit()) {
156 base::PlatformFile handle
=
157 IPC::PlatformFileForTransitToPlatformFile(ipc_fd
);
159 // On Windows, valid handles are 32 bit unsigned integers so this is safe.
160 *fd
= reinterpret_cast<uintptr_t>(handle
);
164 // It doesn't matter if the path is invalid UTF8 as long as it's consistent
166 *path
= ipc_path
.AsUTF8Unsafe();
171 // The listener never dies, otherwise this might be a dangling reference.
172 NaClListener
* listener_
;
176 NaClListener::NaClListener() : shutdown_event_(true, false),
177 io_thread_("NaCl_IOThread"),
178 #if defined(OS_LINUX)
179 prereserved_sandbox_size_(0),
181 #if defined(OS_POSIX)
182 number_of_cores_(-1), // unknown/error
185 io_thread_
.StartWithOptions(
186 base::Thread::Options(base::MessageLoop::TYPE_IO
, 0));
188 DCHECK(g_listener
== NULL
);
193 NaClListener::~NaClListener() {
195 shutdown_event_
.Signal();
201 bool NaClListener::Send(IPC::Message
* msg
) {
202 DCHECK(main_loop_
!= NULL
);
203 if (base::MessageLoop::current() == main_loop_
) {
204 // This thread owns the channel.
205 return channel_
->Send(msg
);
207 // This thread does not own the channel.
208 return filter_
->Send(msg
);
212 void NaClListener::Listen() {
213 std::string channel_name
=
214 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
215 switches::kProcessChannelID
);
216 channel_
.reset(new IPC::SyncChannel(
217 this, io_thread_
.message_loop_proxy().get(), &shutdown_event_
));
218 filter_
= new IPC::SyncMessageFilter(&shutdown_event_
);
219 channel_
->AddFilter(filter_
.get());
220 channel_
->Init(channel_name
, IPC::Channel::MODE_CLIENT
, true);
221 main_loop_
= base::MessageLoop::current();
225 bool NaClListener::OnMessageReceived(const IPC::Message
& msg
) {
227 IPC_BEGIN_MESSAGE_MAP(NaClListener
, msg
)
228 IPC_MESSAGE_HANDLER(NaClProcessMsg_Start
, OnStart
)
229 IPC_MESSAGE_UNHANDLED(handled
= false)
230 IPC_END_MESSAGE_MAP()
234 void NaClListener::OnStart(const nacl::NaClStartParams
& params
) {
235 struct NaClChromeMainArgs
*args
= NaClChromeMainArgsCreate();
237 LOG(ERROR
) << "NaClChromeMainArgsCreate() failed";
241 if (params
.enable_ipc_proxy
) {
242 // Create the initial PPAPI IPC channel between the NaCl IRT and the
243 // browser process. The IRT uses this channel to communicate with the
244 // browser and to create additional IPC channels to renderer processes.
245 IPC::ChannelHandle handle
=
246 IPC::Channel::GenerateVerifiedChannelID("nacl");
247 scoped_refptr
<NaClIPCAdapter
> ipc_adapter(
248 new NaClIPCAdapter(handle
, io_thread_
.message_loop_proxy().get()));
249 ipc_adapter
->ConnectChannel();
251 // Pass a NaClDesc to the untrusted side. This will hold a ref to the
253 args
->initial_ipc_desc
= ipc_adapter
->MakeNaClDesc();
254 #if defined(OS_POSIX)
255 handle
.socket
= base::FileDescriptor(
256 ipc_adapter
->TakeClientFileDescriptor(), true);
258 if (!Send(new NaClProcessHostMsg_PpapiChannelCreated(handle
)))
259 LOG(ERROR
) << "Failed to send IPC channel handle to NaClProcessHost.";
262 std::vector
<nacl::FileDescriptor
> handles
= params
.handles
;
264 #if defined(OS_LINUX) || defined(OS_MACOSX)
265 args
->urandom_fd
= dup(base::GetUrandomFD());
266 if (args
->urandom_fd
< 0) {
267 LOG(ERROR
) << "Failed to dup() the urandom FD";
270 args
->number_of_cores
= number_of_cores_
;
271 args
->create_memory_object_func
= CreateMemoryObject
;
272 # if defined(OS_MACOSX)
273 CHECK(handles
.size() >= 1);
274 g_shm_fd
= nacl::ToNativeHandle(handles
[handles
.size() - 1]);
279 if (params
.uses_irt
) {
280 CHECK(handles
.size() >= 1);
281 NaClHandle irt_handle
= nacl::ToNativeHandle(handles
[handles
.size() - 1]);
285 args
->irt_fd
= _open_osfhandle(reinterpret_cast<intptr_t>(irt_handle
),
286 _O_RDONLY
| _O_BINARY
);
287 if (args
->irt_fd
< 0) {
288 LOG(ERROR
) << "_open_osfhandle() failed";
292 args
->irt_fd
= irt_handle
;
295 // Otherwise, the IRT handle is not even sent.
299 if (params
.validation_cache_enabled
) {
300 // SHA256 block size.
301 CHECK_EQ(params
.validation_cache_key
.length(), (size_t) 64);
302 // The cache structure is not freed and exists until the NaCl process exits.
303 args
->validation_cache
= CreateValidationCache(
304 new BrowserValidationDBProxy(this), params
.validation_cache_key
,
308 CHECK(handles
.size() == 1);
309 args
->imc_bootstrap_handle
= nacl::ToNativeHandle(handles
[0]);
310 args
->enable_exception_handling
= params
.enable_exception_handling
;
311 args
->enable_debug_stub
= params
.enable_debug_stub
;
312 args
->enable_dyncode_syscalls
= params
.enable_dyncode_syscalls
;
313 if (!params
.enable_dyncode_syscalls
) {
314 // Bound the initial nexe's code segment size under PNaCl to
315 // reduce the chance of a code spraying attack succeeding (see
316 // https://code.google.com/p/nativeclient/issues/detail?id=3572).
317 // We assume that !params.enable_dyncode_syscalls is synonymous
318 // with PNaCl. We can't apply this arbitrary limit outside of
319 // PNaCl because it might break existing NaCl apps, and this limit
320 // is only useful if the dyncode syscalls are disabled.
321 args
->initial_nexe_max_code_bytes
= 32 << 20; // 32 MB
323 #if defined(OS_LINUX) || defined(OS_MACOSX)
324 args
->debug_stub_server_bound_socket_fd
= nacl::ToNativeHandle(
325 params
.debug_stub_server_bound_socket
);
328 args
->broker_duplicate_handle_func
= BrokerDuplicateHandle
;
329 args
->attach_debug_exception_handler_func
= AttachDebugExceptionHandler
;
331 #if defined(OS_LINUX)
332 args
->prereserved_sandbox_size
= prereserved_sandbox_size_
;
334 NaClChromeMainStart(args
);