Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / components / nacl / loader / nacl_helper_linux.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 // A mini-zygote specifically for Native Client.
6
7 #include "components/nacl/loader/nacl_helper_linux.h"
8
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <link.h>
12 #include <signal.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/socket.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18
19 #include <string>
20 #include <vector>
21
22 #include "base/at_exit.h"
23 #include "base/command_line.h"
24 #include "base/files/scoped_file.h"
25 #include "base/logging.h"
26 #include "base/memory/scoped_ptr.h"
27 #include "base/memory/scoped_vector.h"
28 #include "base/message_loop/message_loop.h"
29 #include "base/posix/eintr_wrapper.h"
30 #include "base/posix/global_descriptors.h"
31 #include "base/posix/unix_domain_socket_linux.h"
32 #include "base/process/kill.h"
33 #include "base/process/process_handle.h"
34 #include "base/rand_util.h"
35 #include "components/nacl/common/nacl_switches.h"
36 #include "components/nacl/loader/nacl_listener.h"
37 #include "components/nacl/loader/nonsfi/irt_exception_handling.h"
38 #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h"
39 #include "content/public/common/child_process_sandbox_support_linux.h"
40 #include "content/public/common/content_descriptors.h"
41 #include "content/public/common/zygote_fork_delegate_linux.h"
42 #include "crypto/nss_util.h"
43 #include "ipc/ipc_descriptors.h"
44 #include "ipc/ipc_switches.h"
45 #include "sandbox/linux/services/libc_urandom_override.h"
46
47 namespace {
48
49 struct NaClLoaderSystemInfo {
50   size_t prereserved_sandbox_size;
51   long number_of_cores;
52 };
53
54 // Replace |file_descriptor| with the reading end of a closed pipe.
55 void ReplaceFDWithDummy(int file_descriptor) {
56   // Make sure that file_descriptor is an open descriptor.
57   PCHECK(-1 != fcntl(file_descriptor, F_GETFD, 0));
58   int pipefd[2];
59   PCHECK(0 == pipe(pipefd));
60   PCHECK(-1 != dup2(pipefd[0], file_descriptor));
61   PCHECK(0 == IGNORE_EINTR(close(pipefd[0])));
62   PCHECK(0 == IGNORE_EINTR(close(pipefd[1])));
63 }
64
65 // The child must mimic the behavior of zygote_main_linux.cc on the child
66 // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
67 //   if (!child) {
68 void BecomeNaClLoader(base::ScopedFD browser_fd,
69                       const NaClLoaderSystemInfo& system_info,
70                       bool uses_nonsfi_mode,
71                       nacl::NaClSandbox* nacl_sandbox) {
72   DCHECK(nacl_sandbox);
73   VLOG(1) << "NaCl loader: setting up IPC descriptor";
74   // Close or shutdown IPC channels that we don't need anymore.
75   PCHECK(0 == IGNORE_EINTR(close(kNaClZygoteDescriptor)));
76   // In Non-SFI mode, it's important to close any non-expected IPC channels.
77   if (uses_nonsfi_mode) {
78     // The low-level kSandboxIPCChannel is used by renderers and NaCl for
79     // various operations. See the LinuxSandbox::METHOD_* methods. NaCl uses
80     // LinuxSandbox::METHOD_MAKE_SHARED_MEMORY_SEGMENT in SFI mode, so this
81     // should only be closed in Non-SFI mode.
82     // This file descriptor is insidiously used by a number of APIs. Closing it
83     // could lead to difficult to debug issues. Instead of closing it, replace
84     // it with a dummy.
85     const int sandbox_ipc_channel =
86         base::GlobalDescriptors::kBaseDescriptor + kSandboxIPCChannel;
87
88     ReplaceFDWithDummy(sandbox_ipc_channel);
89
90     // Install crash signal handlers before disallowing system calls.
91     nacl::nonsfi::InitializeSignalHandler();
92   }
93
94   // Finish layer-1 sandbox initialization and initialize the layer-2 sandbox.
95   CHECK(!nacl_sandbox->HasOpenDirectory());
96   nacl_sandbox->InitializeLayerTwoSandbox(uses_nonsfi_mode);
97   nacl_sandbox->SealLayerOneSandbox();
98   nacl_sandbox->CheckSandboxingStateWithPolicy();
99
100   base::GlobalDescriptors::GetInstance()->Set(kPrimaryIPCChannel,
101                                               browser_fd.release());
102
103   base::MessageLoopForIO main_message_loop;
104   NaClListener listener;
105   listener.set_uses_nonsfi_mode(uses_nonsfi_mode);
106   listener.set_prereserved_sandbox_size(system_info.prereserved_sandbox_size);
107   listener.set_number_of_cores(system_info.number_of_cores);
108   listener.Listen();
109   _exit(0);
110 }
111
112 // Start the NaCl loader in a child created by the NaCl loader Zygote.
113 void ChildNaClLoaderInit(ScopedVector<base::ScopedFD> child_fds,
114                          const NaClLoaderSystemInfo& system_info,
115                          bool uses_nonsfi_mode,
116                          nacl::NaClSandbox* nacl_sandbox,
117                          const std::string& channel_id) {
118   DCHECK(child_fds.size() >
119          std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex,
120                   content::ZygoteForkDelegate::kBrowserFDIndex));
121
122   // Ping the PID oracle socket.
123   CHECK(content::SendZygoteChildPing(
124       child_fds[content::ZygoteForkDelegate::kPIDOracleFDIndex]->get()));
125
126   CommandLine::ForCurrentProcess()->AppendSwitchASCII(
127       switches::kProcessChannelID, channel_id);
128
129   // Save the browser socket and close the rest.
130   base::ScopedFD browser_fd(
131       child_fds[content::ZygoteForkDelegate::kBrowserFDIndex]->Pass());
132   child_fds.clear();
133
134   BecomeNaClLoader(
135       browser_fd.Pass(), system_info, uses_nonsfi_mode, nacl_sandbox);
136   _exit(1);
137 }
138
139 // Handle a fork request from the Zygote.
140 // Some of this code was lifted from
141 // content/browser/zygote_main_linux.cc:ForkWithRealPid()
142 bool HandleForkRequest(ScopedVector<base::ScopedFD> child_fds,
143                        const NaClLoaderSystemInfo& system_info,
144                        nacl::NaClSandbox* nacl_sandbox,
145                        PickleIterator* input_iter,
146                        Pickle* output_pickle) {
147   bool uses_nonsfi_mode;
148   if (!input_iter->ReadBool(&uses_nonsfi_mode)) {
149     LOG(ERROR) << "Could not read uses_nonsfi_mode status";
150     return false;
151   }
152
153   std::string channel_id;
154   if (!input_iter->ReadString(&channel_id)) {
155     LOG(ERROR) << "Could not read channel_id string";
156     return false;
157   }
158
159   if (content::ZygoteForkDelegate::kNumPassedFDs != child_fds.size()) {
160     LOG(ERROR) << "nacl_helper: unexpected number of fds, got "
161         << child_fds.size();
162     return false;
163   }
164
165   VLOG(1) << "nacl_helper: forking";
166   pid_t child_pid = fork();
167   if (child_pid < 0) {
168     PLOG(ERROR) << "*** fork() failed.";
169   }
170
171   if (child_pid == 0) {
172     ChildNaClLoaderInit(child_fds.Pass(),
173                         system_info,
174                         uses_nonsfi_mode,
175                         nacl_sandbox,
176                         channel_id);
177     NOTREACHED();
178   }
179
180   // I am the parent.
181   // First, close the dummy_fd so the sandbox won't find me when
182   // looking for the child's pid in /proc. Also close other fds.
183   child_fds.clear();
184   VLOG(1) << "nacl_helper: child_pid is " << child_pid;
185
186   // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
187   output_pickle->WriteInt(child_pid);
188   return true;
189 }
190
191 bool HandleGetTerminationStatusRequest(PickleIterator* input_iter,
192                                        Pickle* output_pickle) {
193   pid_t child_to_wait;
194   if (!input_iter->ReadInt(&child_to_wait)) {
195     LOG(ERROR) << "Could not read pid to wait for";
196     return false;
197   }
198
199   bool known_dead;
200   if (!input_iter->ReadBool(&known_dead)) {
201     LOG(ERROR) << "Could not read known_dead status";
202     return false;
203   }
204   // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
205   // called from the Zygote's kZygoteCommandReap command). This means that we
206   // will sometimes detect the process as still running when it's not. Fix
207   // this!
208
209   int exit_code;
210   base::TerminationStatus status;
211   if (known_dead)
212     status = base::GetKnownDeadTerminationStatus(child_to_wait, &exit_code);
213   else
214     status = base::GetTerminationStatus(child_to_wait, &exit_code);
215   output_pickle->WriteInt(static_cast<int>(status));
216   output_pickle->WriteInt(exit_code);
217   return true;
218 }
219
220 // Honor a command |command_type|. Eventual command parameters are
221 // available in |input_iter| and eventual file descriptors attached to
222 // the command are in |attached_fds|.
223 // Reply to the command on |reply_fds|.
224 bool HonorRequestAndReply(int reply_fd,
225                           int command_type,
226                           ScopedVector<base::ScopedFD> attached_fds,
227                           const NaClLoaderSystemInfo& system_info,
228                           nacl::NaClSandbox* nacl_sandbox,
229                           PickleIterator* input_iter) {
230   Pickle write_pickle;
231   bool have_to_reply = false;
232   // Commands must write anything to send back to |write_pickle|.
233   switch (command_type) {
234     case nacl::kNaClForkRequest:
235       have_to_reply = HandleForkRequest(attached_fds.Pass(),
236                                         system_info,
237                                         nacl_sandbox,
238                                         input_iter,
239                                         &write_pickle);
240       break;
241     case nacl::kNaClGetTerminationStatusRequest:
242       have_to_reply =
243           HandleGetTerminationStatusRequest(input_iter, &write_pickle);
244       break;
245     default:
246       LOG(ERROR) << "Unsupported command from Zygote";
247       return false;
248   }
249   if (!have_to_reply)
250     return false;
251   const std::vector<int> empty;  // We never send file descriptors back.
252   if (!UnixDomainSocket::SendMsg(reply_fd, write_pickle.data(),
253                                  write_pickle.size(), empty)) {
254     LOG(ERROR) << "*** send() to zygote failed";
255     return false;
256   }
257   return true;
258 }
259
260 // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
261 // Die on EOF from |zygote_ipc_fd|.
262 bool HandleZygoteRequest(int zygote_ipc_fd,
263                          const NaClLoaderSystemInfo& system_info,
264                          nacl::NaClSandbox* nacl_sandbox) {
265   ScopedVector<base::ScopedFD> fds;
266   char buf[kNaClMaxIPCMessageLength];
267   const ssize_t msglen = UnixDomainSocket::RecvMsg(zygote_ipc_fd,
268       &buf, sizeof(buf), &fds);
269   // If the Zygote has started handling requests, we should be sandboxed via
270   // the setuid sandbox.
271   if (!nacl_sandbox->layer_one_enabled()) {
272     LOG(ERROR) << "NaCl helper process running without a sandbox!\n"
273       << "Most likely you need to configure your SUID sandbox "
274       << "correctly";
275   }
276   if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) {
277     // EOF from the browser. Goodbye!
278     _exit(0);
279   }
280   if (msglen < 0) {
281     PLOG(ERROR) << "nacl_helper: receive from zygote failed";
282     return false;
283   }
284
285   Pickle read_pickle(buf, msglen);
286   PickleIterator read_iter(read_pickle);
287   int command_type;
288   if (!read_iter.ReadInt(&command_type)) {
289     LOG(ERROR) << "Unable to read command from Zygote";
290     return false;
291   }
292   return HonorRequestAndReply(zygote_ipc_fd,
293                               command_type,
294                               fds.Pass(),
295                               system_info,
296                               nacl_sandbox,
297                               &read_iter);
298 }
299
300 static const char kNaClHelperReservedAtZero[] = "reserved_at_zero";
301 static const char kNaClHelperRDebug[] = "r_debug";
302
303 // Since we were started by nacl_helper_bootstrap rather than in the
304 // usual way, the debugger cannot figure out where our executable
305 // or the dynamic linker or the shared libraries are in memory,
306 // so it won't find any symbols.  But we can fake it out to find us.
307 //
308 // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
309 // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
310 // structure.  The debugger will look for that symbol by name to
311 // discover the addresses of key dynamic linker data structures.
312 // Since all it knows about is the original main executable, which
313 // is the bootstrap program, it finds the symbol defined there.  The
314 // dynamic linker's structure is somewhere else, but it is filled in
315 // after initialization.  The parts that really matter to the
316 // debugger never change.  So we just copy the contents of the
317 // dynamic linker's structure into the address provided by the option.
318 // Hereafter, if someone attaches a debugger (or examines a core dump),
319 // the debugger will find all the symbols in the normal way.
320 static void CheckRDebug(char* argv0) {
321   std::string r_debug_switch_value =
322       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(kNaClHelperRDebug);
323   if (!r_debug_switch_value.empty()) {
324     char* endp;
325     uintptr_t r_debug_addr = strtoul(r_debug_switch_value.c_str(), &endp, 0);
326     if (r_debug_addr != 0 && *endp == '\0') {
327       r_debug* bootstrap_r_debug = reinterpret_cast<r_debug*>(r_debug_addr);
328       *bootstrap_r_debug = _r_debug;
329
330       // Since the main executable (the bootstrap program) does not
331       // have a dynamic section, the debugger will not skip the
332       // first element of the link_map list as it usually would for
333       // an executable or PIE that was loaded normally.  But the
334       // dynamic linker has set l_name for the PIE to "" as is
335       // normal for the main executable.  So the debugger doesn't
336       // know which file it is.  Fill in the actual file name, which
337       // came in as our argv[0].
338       link_map* l = _r_debug.r_map;
339       if (l->l_name[0] == '\0')
340         l->l_name = argv0;
341     }
342   }
343 }
344
345 // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
346 // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
347 // sandbox memory.
348 //
349 // CheckReservedAtZero parses the value of the argument reserved_at_zero
350 // and returns the amount of prereserved sandbox memory.
351 static size_t CheckReservedAtZero() {
352   size_t prereserved_sandbox_size = 0;
353   std::string reserved_at_zero_switch_value =
354       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
355           kNaClHelperReservedAtZero);
356   if (!reserved_at_zero_switch_value.empty()) {
357     char* endp;
358     prereserved_sandbox_size =
359         strtoul(reserved_at_zero_switch_value.c_str(), &endp, 0);
360     if (*endp != '\0')
361       LOG(ERROR) << "Could not parse reserved_at_zero argument value of "
362                  << reserved_at_zero_switch_value;
363   }
364   return prereserved_sandbox_size;
365 }
366
367 }  // namespace
368
369 #if defined(ADDRESS_SANITIZER)
370 // Do not install the SIGSEGV handler in ASan. This should make the NaCl
371 // platform qualification test pass.
372 static const char kAsanDefaultOptionsNaCl[] = "handle_segv=0";
373
374 // Override the default ASan options for the NaCl helper.
375 // __asan_default_options should not be instrumented, because it is called
376 // before ASan is initialized.
377 extern "C"
378 __attribute__((no_sanitize_address))
379 // The function isn't referenced from the executable itself. Make sure it isn't
380 // stripped by the linker.
381 __attribute__((used))
382 __attribute__((visibility("default")))
383 const char* __asan_default_options() {
384   return kAsanDefaultOptionsNaCl;
385 }
386 #endif
387
388 int main(int argc, char* argv[]) {
389   CommandLine::Init(argc, argv);
390   base::AtExitManager exit_manager;
391   base::RandUint64();  // acquire /dev/urandom fd before sandbox is raised
392   // Allows NSS to fopen() /dev/urandom.
393   sandbox::InitLibcUrandomOverrides();
394 #if defined(USE_NSS)
395   // Configure NSS for use inside the NaCl process.
396   // The fork check has not caused problems for NaCl, but this appears to be
397   // best practice (see other places LoadNSSLibraries is called.)
398   crypto::DisableNSSForkCheck();
399   // Without this line on Linux, HMAC::Init will instantiate a singleton that
400   // in turn attempts to open a file.  Disabling this behavior avoids a ~70 ms
401   // stall the first time HMAC is used.
402   crypto::ForceNSSNoDBInit();
403   // Load shared libraries before sandbox is raised.
404   // NSS is needed to perform hashing for validation caching.
405   crypto::LoadNSSLibraries();
406 #endif
407   const NaClLoaderSystemInfo system_info = {
408     CheckReservedAtZero(),
409     sysconf(_SC_NPROCESSORS_ONLN)
410   };
411
412   CheckRDebug(argv[0]);
413
414   scoped_ptr<nacl::NaClSandbox> nacl_sandbox(new nacl::NaClSandbox);
415   // Make sure that the early initialization did not start any spurious
416   // threads.
417 #if !defined(THREAD_SANITIZER)
418   CHECK(nacl_sandbox->IsSingleThreaded());
419 #endif
420
421   const bool is_init_process = 1 == getpid();
422   nacl_sandbox->InitializeLayerOneSandbox();
423   CHECK_EQ(is_init_process, nacl_sandbox->layer_one_enabled());
424
425   const std::vector<int> empty;
426   // Send the zygote a message to let it know we are ready to help
427   if (!UnixDomainSocket::SendMsg(kNaClZygoteDescriptor,
428                                  kNaClHelperStartupAck,
429                                  sizeof(kNaClHelperStartupAck), empty)) {
430     LOG(ERROR) << "*** send() to zygote failed";
431   }
432
433   // Now handle requests from the Zygote.
434   while (true) {
435     bool request_handled = HandleZygoteRequest(
436         kNaClZygoteDescriptor, system_info, nacl_sandbox.get());
437     // Do not turn this into a CHECK() without thinking about robustness
438     // against malicious IPC requests.
439     DCHECK(request_handled);
440   }
441   NOTREACHED();
442 }