Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / components / nacl / loader / nacl_listener.cc
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.
4
5 #include "components/nacl/loader/nacl_listener.h"
6
7 #include <errno.h>
8 #include <stdlib.h>
9
10 #if defined(OS_POSIX)
11 #include <unistd.h>
12 #endif
13
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"
30
31 #if defined(OS_POSIX)
32 #include "base/file_descriptor_posix.h"
33 #endif
34
35 #if defined(OS_LINUX)
36 #include "components/nacl/loader/nonsfi/nonsfi_main.h"
37 #include "content/public/common/child_process_sandbox_support_linux.h"
38 #endif
39
40 #if defined(OS_WIN)
41 #include <fcntl.h>
42 #include <io.h>
43
44 #include "content/public/common/sandbox_init.h"
45 #endif
46
47 namespace {
48 #if defined(OS_MACOSX)
49
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.
55
56 base::subtle::Atomic32 g_shm_fd = -1;
57
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
64       // lseek() + write().
65       if (lseek(result_fd, size - 1, SEEK_SET) == -1) {
66         LOG(ERROR) << "lseek() failed: " << errno;
67         return -1;
68       }
69       if (write(result_fd, "", 1) != 1) {
70         LOG(ERROR) << "write() failed: " << errno;
71         return -1;
72       }
73       return result_fd;
74     }
75   }
76   // Fall back to NaCl's default implementation.
77   return -1;
78 }
79
80 #elif defined(OS_LINUX)
81
82 int CreateMemoryObject(size_t size, int executable) {
83   return content::MakeSharedMemorySegmentViaIPC(size, executable);
84 }
85
86 #elif defined(OS_WIN)
87
88 NaClListener* g_listener;
89
90 // We wrap the function to convert the bool return value to an int.
91 int BrokerDuplicateHandle(NaClHandle source_handle,
92                           uint32_t process_id,
93                           NaClHandle* target_handle,
94                           uint32_t desired_access,
95                           uint32_t options) {
96   return content::BrokerDuplicateHandle(source_handle, process_id,
97                                         target_handle, desired_access,
98                                         options);
99 }
100
101 int AttachDebugExceptionHandler(const void* info, size_t info_size) {
102   std::string info_string(reinterpret_cast<const char*>(info), info_size);
103   bool result = false;
104   if (!g_listener->Send(new NaClProcessMsg_AttachDebugExceptionHandler(
105            info_string, &result)))
106     return false;
107   return result;
108 }
109
110 #endif
111
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
116 // the FD #.
117 void SetUpIPCAdapter(IPC::ChannelHandle* handle,
118                      scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
119                      struct NaClApp* nap,
120                      int nacl_fd) {
121   scoped_refptr<NaClIPCAdapter> ipc_adapter(
122       new NaClIPCAdapter(*handle, message_loop_proxy.get()));
123   ipc_adapter->ConnectChannel();
124 #if defined(OS_POSIX)
125   handle->socket =
126       base::FileDescriptor(ipc_adapter->TakeClientFileDescriptor(), true);
127 #endif
128
129   // Pass a NaClDesc to the untrusted side. This will hold a ref to the
130   // NaClIPCAdapter.
131   NaClAppSetDesc(nap, nacl_fd, ipc_adapter->MakeNaClDesc());
132 }
133
134 }  // namespace
135
136 class BrowserValidationDBProxy : public NaClValidationDB {
137  public:
138   explicit BrowserValidationDBProxy(NaClListener* listener)
139       : listener_(listener) {
140   }
141
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.
146     bool result = false;
147     if (!listener_->Send(new NaClProcessMsg_QueryKnownToValidate(signature,
148                                                                  &result))) {
149       LOG(ERROR) << "Failed to query NaCl validation cache.";
150       result = false;
151     }
152     return result;
153   }
154
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.";
159     }
160   }
161
162   virtual bool ResolveFileToken(struct NaClFileToken* file_token,
163                                 int32* fd, std::string* path) OVERRIDE {
164     *fd = -1;
165     *path = "";
166     if (file_token->lo == 0 && file_token->hi == 0) {
167       return false;
168     }
169     IPC::PlatformFileForTransit ipc_fd = IPC::InvalidPlatformFileForTransit();
170     base::FilePath ipc_path;
171     if (!listener_->Send(new NaClProcessMsg_ResolveFileToken(file_token->lo,
172                                                              file_token->hi,
173                                                              &ipc_fd,
174                                                              &ipc_path))) {
175       return false;
176     }
177     if (ipc_fd == IPC::InvalidPlatformFileForTransit()) {
178       return false;
179     }
180     base::PlatformFile handle =
181         IPC::PlatformFileForTransitToPlatformFile(ipc_fd);
182 #if defined(OS_WIN)
183     // On Windows, valid handles are 32 bit unsigned integers so this is safe.
184     *fd = reinterpret_cast<uintptr_t>(handle);
185 #else
186     *fd = handle;
187 #endif
188     // It doesn't matter if the path is invalid UTF8 as long as it's consistent
189     // and unforgeable.
190     *path = ipc_path.AsUTF8Unsafe();
191     return true;
192   }
193
194  private:
195   // The listener never dies, otherwise this might be a dangling reference.
196   NaClListener* listener_;
197 };
198
199
200 NaClListener::NaClListener() : shutdown_event_(true, false),
201                                io_thread_("NaCl_IOThread"),
202 #if defined(OS_LINUX)
203                                prereserved_sandbox_size_(0),
204 #endif
205 #if defined(OS_POSIX)
206                                number_of_cores_(-1),  // unknown/error
207 #endif
208                                main_loop_(NULL) {
209   io_thread_.StartWithOptions(
210       base::Thread::Options(base::MessageLoop::TYPE_IO, 0));
211 #if defined(OS_WIN)
212   DCHECK(g_listener == NULL);
213   g_listener = this;
214 #endif
215 }
216
217 NaClListener::~NaClListener() {
218   NOTREACHED();
219   shutdown_event_.Signal();
220 #if defined(OS_WIN)
221   g_listener = NULL;
222 #endif
223 }
224
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);
230   } else {
231     // This thread does not own the channel.
232     return filter_->Send(msg);
233   }
234 }
235
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();
246   main_loop_->Run();
247 }
248
249 bool NaClListener::OnMessageReceived(const IPC::Message& msg) {
250   bool handled = true;
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()
255   return handled;
256 }
257
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";
263     return;
264   }
265   NaClChromeMainSetUrandomFd(urandom_fd);
266 #endif
267
268   NaClChromeMainInit();
269   struct NaClChromeMainArgs *args = NaClChromeMainArgsCreate();
270   if (args == NULL) {
271     LOG(ERROR) << "NaClChromeMainArgsCreate() failed";
272     return;
273   }
274
275   struct NaClApp *nap = NaClAppCreate();
276   if (nap == NULL) {
277     LOG(ERROR) << "NaClAppCreate() failed";
278     return;
279   }
280
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);
289
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);
294
295     if (!Send(new NaClProcessHostMsg_PpapiChannelsCreated(
296             browser_handle, renderer_handle)))
297       LOG(ERROR) << "Failed to send IPC channel handle to NaClProcessHost.";
298   }
299
300   std::vector<nacl::FileDescriptor> handles = params.handles;
301
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]);
308   handles.pop_back();
309 # endif
310 #endif
311
312   if (params.uses_irt) {
313     CHECK(handles.size() >= 1);
314     NaClHandle irt_handle = nacl::ToNativeHandle(handles[handles.size() - 1]);
315     handles.pop_back();
316
317 #if defined(OS_WIN)
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";
322       return;
323     }
324 #else
325     args->irt_fd = irt_handle;
326 #endif
327   } else {
328     // Otherwise, the IRT handle is not even sent.
329     args->irt_fd = -1;
330   }
331
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,
338         params.version);
339   }
340
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
355   }
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);
359 #endif
360 #if defined(OS_WIN)
361   args->broker_duplicate_handle_func = BrokerDuplicateHandle;
362   args->attach_debug_exception_handler_func = AttachDebugExceptionHandler;
363 #endif
364 #if defined(OS_LINUX)
365   args->prereserved_sandbox_size = prereserved_sandbox_size_;
366 #endif
367
368 #if defined(OS_LINUX)
369   if (params.enable_nonsfi_mode) {
370     nacl::nonsfi::MainStart(args->imc_bootstrap_handle);
371     NOTREACHED();
372     return;
373   }
374 #endif
375   NaClChromeMainStartApp(nap, args);
376   NOTREACHED();
377 }