nacl_helper_linux.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. // A mini-zygote specifically for Native Client.
  5. #include "components/nacl/loader/nacl_helper_linux.h"
  6. #include <errno.h>
  7. #include <fcntl.h>
  8. #include <link.h>
  9. #include <signal.h>
  10. #include <stddef.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <sys/socket.h>
  14. #include <sys/stat.h>
  15. #include <sys/types.h>
  16. #include <memory>
  17. #include <string>
  18. #include <utility>
  19. #include <vector>
  20. #include "base/at_exit.h"
  21. #include "base/command_line.h"
  22. #include "base/environment.h"
  23. #include "base/files/scoped_file.h"
  24. #include "base/json/json_reader.h"
  25. #include "base/logging.h"
  26. #include "base/message_loop/message_pump_type.h"
  27. #include "base/posix/eintr_wrapper.h"
  28. #include "base/posix/global_descriptors.h"
  29. #include "base/posix/unix_domain_socket.h"
  30. #include "base/process/kill.h"
  31. #include "base/process/process_handle.h"
  32. #include "base/rand_util.h"
  33. #include "base/task/single_thread_task_executor.h"
  34. #include "build/build_config.h"
  35. #include "components/nacl/common/nacl_switches.h"
  36. #include "components/nacl/loader/nacl_listener.h"
  37. #include "components/nacl/loader/sandbox_linux/nacl_sandbox_linux.h"
  38. #include "content/public/common/content_descriptors.h"
  39. #include "content/public/common/zygote/send_zygote_child_ping_linux.h"
  40. #include "content/public/common/zygote/zygote_fork_delegate_linux.h"
  41. #include "mojo/core/embedder/embedder.h"
  42. #include "sandbox/linux/services/credentials.h"
  43. #include "sandbox/linux/services/namespace_sandbox.h"
  44. #include "third_party/cros_system_api/switches/chrome_switches.h"
  45. namespace {
  46. struct NaClLoaderSystemInfo {
  47. size_t prereserved_sandbox_size;
  48. long number_of_cores;
  49. };
  50. #if BUILDFLAG(IS_CHROMEOS)
  51. std::string GetCommandLineFeatureFlagChoice(
  52. const base::CommandLine* command_line,
  53. std::string feature_flag) {
  54. std::string encoded =
  55. command_line->GetSwitchValueNative(chromeos::switches::kFeatureFlags);
  56. if (encoded.empty()) {
  57. return "";
  58. }
  59. auto flags_list = base::JSONReader::Read(encoded);
  60. if (!flags_list) {
  61. LOG(WARNING) << "Failed to parse feature flags configuration";
  62. return "";
  63. }
  64. for (const auto& flag : flags_list.value().GetListDeprecated()) {
  65. if (!flag.is_string())
  66. continue;
  67. std::string flag_string = flag.GetString();
  68. if (flag_string.rfind(feature_flag) != std::string::npos)
  69. // For option x, this has the form "feature-flag-name@x". Return "x".
  70. return flag_string.substr(feature_flag.size() + 1);
  71. }
  72. return "";
  73. }
  74. void AddVerboseLoggingInNaclSwitch(base::CommandLine* command_line) {
  75. if (command_line->HasSwitch(switches::kVerboseLoggingInNacl))
  76. // Flag is already present, nothing to do here.
  77. return;
  78. std::string option = GetCommandLineFeatureFlagChoice(
  79. command_line, switches::kVerboseLoggingInNacl);
  80. // This needs to be kept in sync with the order of choices for
  81. // kVerboseLoggingInNacl in chrome/browser/about_flags.cc
  82. if (option == "")
  83. return;
  84. if (option == "1")
  85. return command_line->AppendSwitchASCII(
  86. switches::kVerboseLoggingInNacl,
  87. switches::kVerboseLoggingInNaclChoiceLow);
  88. if (option == "2")
  89. return command_line->AppendSwitchASCII(
  90. switches::kVerboseLoggingInNacl,
  91. switches::kVerboseLoggingInNaclChoiceMedium);
  92. if (option == "3")
  93. return command_line->AppendSwitchASCII(
  94. switches::kVerboseLoggingInNacl,
  95. switches::kVerboseLoggingInNaclChoiceHigh);
  96. if (option == "4")
  97. return command_line->AppendSwitchASCII(
  98. switches::kVerboseLoggingInNacl,
  99. switches::kVerboseLoggingInNaclChoiceHighest);
  100. if (option == "5")
  101. return command_line->AppendSwitchASCII(
  102. switches::kVerboseLoggingInNacl,
  103. switches::kVerboseLoggingInNaclChoiceDisabled);
  104. }
  105. #endif // BUILDFLAG(IS_CHROMEOS)
  106. // The child must mimic the behavior of zygote_main_linux.cc on the child
  107. // side of the fork. See zygote_main_linux.cc:HandleForkRequest from
  108. // if (!child) {
  109. void BecomeNaClLoader(base::ScopedFD browser_fd,
  110. const NaClLoaderSystemInfo& system_info,
  111. nacl::NaClSandbox* nacl_sandbox) {
  112. DCHECK(nacl_sandbox);
  113. VLOG(1) << "NaCl loader: setting up IPC descriptor";
  114. // Close or shutdown IPC channels that we don't need anymore.
  115. PCHECK(0 == IGNORE_EINTR(close(kNaClZygoteDescriptor)));
  116. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  117. if (command_line->HasSwitch(switches::kVerboseLoggingInNacl)) {
  118. base::Environment::Create()->SetVar(
  119. "NACLVERBOSITY",
  120. command_line->GetSwitchValueASCII(switches::kVerboseLoggingInNacl));
  121. }
  122. // Always ignore SIGPIPE, for consistency with other Chrome processes and
  123. // because some IPC code, such as sync_socket_posix.cc, requires this.
  124. // We do this before seccomp-bpf is initialized.
  125. PCHECK(signal(SIGPIPE, SIG_IGN) != SIG_ERR);
  126. // Finish layer-1 sandbox initialization and initialize the layer-2 sandbox.
  127. CHECK(!nacl_sandbox->HasOpenDirectory());
  128. nacl_sandbox->InitializeLayerTwoSandbox();
  129. nacl_sandbox->SealLayerOneSandbox();
  130. nacl_sandbox->CheckSandboxingStateWithPolicy();
  131. base::GlobalDescriptors::GetInstance()->Set(kMojoIPCChannel,
  132. browser_fd.release());
  133. // The Mojo EDK must be initialized before using IPC.
  134. mojo::core::Init();
  135. base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO);
  136. NaClListener listener;
  137. listener.set_prereserved_sandbox_size(system_info.prereserved_sandbox_size);
  138. listener.set_number_of_cores(system_info.number_of_cores);
  139. listener.Listen();
  140. _exit(0);
  141. }
  142. // Start the NaCl loader in a child created by the NaCl loader Zygote.
  143. void ChildNaClLoaderInit(std::vector<base::ScopedFD> child_fds,
  144. const NaClLoaderSystemInfo& system_info,
  145. nacl::NaClSandbox* nacl_sandbox,
  146. const std::string& channel_id) {
  147. DCHECK(child_fds.size() >
  148. std::max(content::ZygoteForkDelegate::kPIDOracleFDIndex,
  149. content::ZygoteForkDelegate::kBrowserFDIndex));
  150. // Ping the PID oracle socket.
  151. CHECK(content::SendZygoteChildPing(
  152. child_fds[content::ZygoteForkDelegate::kPIDOracleFDIndex].get()));
  153. // Save the browser socket and close the rest.
  154. base::ScopedFD browser_fd(
  155. std::move(child_fds[content::ZygoteForkDelegate::kBrowserFDIndex]));
  156. child_fds.clear();
  157. BecomeNaClLoader(std::move(browser_fd), system_info, nacl_sandbox);
  158. _exit(1);
  159. }
  160. // Handle a fork request from the Zygote.
  161. // Some of this code was lifted from
  162. // content/browser/zygote_main_linux.cc:ForkWithRealPid()
  163. bool HandleForkRequest(std::vector<base::ScopedFD> child_fds,
  164. const NaClLoaderSystemInfo& system_info,
  165. nacl::NaClSandbox* nacl_sandbox,
  166. base::PickleIterator* input_iter,
  167. base::Pickle* output_pickle) {
  168. std::string channel_id;
  169. if (!input_iter->ReadString(&channel_id)) {
  170. LOG(ERROR) << "Could not read channel_id string";
  171. return false;
  172. }
  173. if (content::ZygoteForkDelegate::kNumPassedFDs != child_fds.size()) {
  174. LOG(ERROR) << "nacl_helper: unexpected number of fds, got "
  175. << child_fds.size();
  176. return false;
  177. }
  178. VLOG(1) << "nacl_helper: forking";
  179. pid_t child_pid;
  180. if (sandbox::NamespaceSandbox::InNewUserNamespace()) {
  181. child_pid = sandbox::NamespaceSandbox::ForkInNewPidNamespace(
  182. /*drop_capabilities_in_child=*/true);
  183. } else {
  184. child_pid = sandbox::Credentials::ForkAndDropCapabilitiesInChild();
  185. }
  186. if (child_pid < 0) {
  187. PLOG(ERROR) << "*** fork() failed.";
  188. }
  189. if (child_pid == 0) {
  190. ChildNaClLoaderInit(std::move(child_fds), system_info, nacl_sandbox,
  191. channel_id);
  192. NOTREACHED();
  193. }
  194. // I am the parent.
  195. // First, close the dummy_fd so the sandbox won't find me when
  196. // looking for the child's pid in /proc. Also close other fds.
  197. child_fds.clear();
  198. VLOG(1) << "nacl_helper: child_pid is " << child_pid;
  199. // Now send child_pid (eventually -1 if fork failed) to the Chrome Zygote.
  200. output_pickle->WriteInt(child_pid);
  201. return true;
  202. }
  203. bool HandleGetTerminationStatusRequest(base::PickleIterator* input_iter,
  204. base::Pickle* output_pickle) {
  205. pid_t child_to_wait;
  206. if (!input_iter->ReadInt(&child_to_wait)) {
  207. LOG(ERROR) << "Could not read pid to wait for";
  208. return false;
  209. }
  210. bool known_dead;
  211. if (!input_iter->ReadBool(&known_dead)) {
  212. LOG(ERROR) << "Could not read known_dead status";
  213. return false;
  214. }
  215. // TODO(jln): With NaCl, known_dead seems to never be set to true (unless
  216. // called from the Zygote's kZygoteCommandReap command). This means that we
  217. // will sometimes detect the process as still running when it's not. Fix
  218. // this!
  219. int exit_code;
  220. base::TerminationStatus status;
  221. if (known_dead)
  222. status = base::GetKnownDeadTerminationStatus(child_to_wait, &exit_code);
  223. else
  224. status = base::GetTerminationStatus(child_to_wait, &exit_code);
  225. output_pickle->WriteInt(static_cast<int>(status));
  226. output_pickle->WriteInt(exit_code);
  227. return true;
  228. }
  229. // Honor a command |command_type|. Eventual command parameters are
  230. // available in |input_iter| and eventual file descriptors attached to
  231. // the command are in |attached_fds|.
  232. // Reply to the command on |reply_fds|.
  233. bool HonorRequestAndReply(int reply_fd,
  234. int command_type,
  235. std::vector<base::ScopedFD> attached_fds,
  236. const NaClLoaderSystemInfo& system_info,
  237. nacl::NaClSandbox* nacl_sandbox,
  238. base::PickleIterator* input_iter) {
  239. base::Pickle write_pickle;
  240. bool have_to_reply = false;
  241. // Commands must write anything to send back to |write_pickle|.
  242. switch (command_type) {
  243. case nacl::kNaClForkRequest:
  244. have_to_reply =
  245. HandleForkRequest(std::move(attached_fds), system_info, nacl_sandbox,
  246. input_iter, &write_pickle);
  247. break;
  248. case nacl::kNaClGetTerminationStatusRequest:
  249. have_to_reply =
  250. HandleGetTerminationStatusRequest(input_iter, &write_pickle);
  251. break;
  252. default:
  253. LOG(ERROR) << "Unsupported command from Zygote";
  254. return false;
  255. }
  256. if (!have_to_reply)
  257. return false;
  258. const std::vector<int> empty; // We never send file descriptors back.
  259. if (!base::UnixDomainSocket::SendMsg(reply_fd, write_pickle.data(),
  260. write_pickle.size(), empty)) {
  261. LOG(ERROR) << "*** send() to zygote failed";
  262. return false;
  263. }
  264. return true;
  265. }
  266. // Read a request from the Zygote from |zygote_ipc_fd| and handle it.
  267. // Die on EOF from |zygote_ipc_fd|.
  268. bool HandleZygoteRequest(int zygote_ipc_fd,
  269. const NaClLoaderSystemInfo& system_info,
  270. nacl::NaClSandbox* nacl_sandbox) {
  271. std::vector<base::ScopedFD> fds;
  272. char buf[kNaClMaxIPCMessageLength];
  273. const ssize_t msglen = base::UnixDomainSocket::RecvMsg(zygote_ipc_fd,
  274. &buf, sizeof(buf), &fds);
  275. // If the Zygote has started handling requests, we should be sandboxed via
  276. // the setuid sandbox.
  277. if (!nacl_sandbox->layer_one_enabled()) {
  278. LOG(ERROR) << "NaCl helper process running without a sandbox!\n"
  279. << "Most likely you need to configure your SUID sandbox "
  280. << "correctly";
  281. }
  282. if (msglen == 0 || (msglen == -1 && errno == ECONNRESET)) {
  283. // EOF from the browser. Goodbye!
  284. _exit(0);
  285. }
  286. if (msglen < 0) {
  287. PLOG(ERROR) << "nacl_helper: receive from zygote failed";
  288. return false;
  289. }
  290. base::Pickle read_pickle(buf, msglen);
  291. base::PickleIterator read_iter(read_pickle);
  292. int command_type;
  293. if (!read_iter.ReadInt(&command_type)) {
  294. LOG(ERROR) << "Unable to read command from Zygote";
  295. return false;
  296. }
  297. return HonorRequestAndReply(zygote_ipc_fd, command_type, std::move(fds),
  298. system_info, nacl_sandbox, &read_iter);
  299. }
  300. static const char kNaClHelperReservedAtZero[] = "reserved_at_zero";
  301. static const char kNaClHelperRDebug[] = "r_debug";
  302. // Since we were started by nacl_helper_bootstrap rather than in the
  303. // usual way, the debugger cannot figure out where our executable
  304. // or the dynamic linker or the shared libraries are in memory,
  305. // so it won't find any symbols. But we can fake it out to find us.
  306. //
  307. // The zygote passes --r_debug=0xXXXXXXXXXXXXXXXX.
  308. // nacl_helper_bootstrap replaces the Xs with the address of its _r_debug
  309. // structure. The debugger will look for that symbol by name to
  310. // discover the addresses of key dynamic linker data structures.
  311. // Since all it knows about is the original main executable, which
  312. // is the bootstrap program, it finds the symbol defined there. The
  313. // dynamic linker's structure is somewhere else, but it is filled in
  314. // after initialization. The parts that really matter to the
  315. // debugger never change. So we just copy the contents of the
  316. // dynamic linker's structure into the address provided by the option.
  317. // Hereafter, if someone attaches a debugger (or examines a core dump),
  318. // the debugger will find all the symbols in the normal way.
  319. static void CheckRDebug(char* argv0) {
  320. std::string r_debug_switch_value =
  321. base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
  322. 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. // Since the main executable (the bootstrap program) does not
  330. // have a dynamic section, the debugger will not skip the
  331. // first element of the link_map list as it usually would for
  332. // an executable or PIE that was loaded normally. But the
  333. // dynamic linker has set l_name for the PIE to "" as is
  334. // normal for the main executable. So the debugger doesn't
  335. // know which file it is. Fill in the actual file name, which
  336. // came in as our argv[0].
  337. link_map* l = _r_debug.r_map;
  338. if (l->l_name[0] == '\0')
  339. l->l_name = argv0;
  340. }
  341. }
  342. }
  343. // The zygote passes --reserved_at_zero=0xXXXXXXXXXXXXXXXX.
  344. // nacl_helper_bootstrap replaces the Xs with the amount of prereserved
  345. // sandbox memory.
  346. //
  347. // CheckReservedAtZero parses the value of the argument reserved_at_zero
  348. // and returns the amount of prereserved sandbox memory.
  349. static size_t CheckReservedAtZero() {
  350. size_t prereserved_sandbox_size = 0;
  351. std::string reserved_at_zero_switch_value =
  352. base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
  353. kNaClHelperReservedAtZero);
  354. if (!reserved_at_zero_switch_value.empty()) {
  355. char* endp;
  356. prereserved_sandbox_size =
  357. strtoul(reserved_at_zero_switch_value.c_str(), &endp, 0);
  358. if (*endp != '\0')
  359. LOG(ERROR) << "Could not parse reserved_at_zero argument value of "
  360. << reserved_at_zero_switch_value;
  361. }
  362. return prereserved_sandbox_size;
  363. }
  364. } // namespace
  365. #if defined(ADDRESS_SANITIZER)
  366. // Do not install the SIGSEGV handler in ASan. This should make the NaCl
  367. // platform qualification test pass.
  368. // detect_odr_violation=0: http://crbug.com/376306
  369. extern const char* kAsanDefaultOptionsNaCl;
  370. const char* kAsanDefaultOptionsNaCl = "handle_segv=0:detect_odr_violation=0";
  371. #endif
  372. int main(int argc, char* argv[]) {
  373. base::CommandLine::Init(argc, argv);
  374. base::AtExitManager exit_manager;
  375. base::RandUint64(); // acquire /dev/urandom fd before sandbox is raised
  376. const NaClLoaderSystemInfo system_info = {CheckReservedAtZero(),
  377. sysconf(_SC_NPROCESSORS_ONLN)};
  378. CheckRDebug(argv[0]);
  379. #if BUILDFLAG(IS_CHROMEOS)
  380. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  381. AddVerboseLoggingInNaclSwitch(command_line);
  382. if (command_line->HasSwitch(switches::kVerboseLoggingInNacl)) {
  383. if (!freopen("/tmp/nacl.log", "a", stderr))
  384. LOG(WARNING) << "Could not open /tmp/nacl.log";
  385. }
  386. #endif
  387. std::unique_ptr<nacl::NaClSandbox> nacl_sandbox(new nacl::NaClSandbox);
  388. // Make sure that the early initialization did not start any spurious
  389. // threads.
  390. #if !defined(THREAD_SANITIZER)
  391. CHECK(nacl_sandbox->IsSingleThreaded());
  392. #endif
  393. const bool is_init_process = 1 == getpid();
  394. nacl_sandbox->InitializeLayerOneSandbox();
  395. CHECK_EQ(is_init_process, nacl_sandbox->layer_one_enabled());
  396. const std::vector<int> empty;
  397. // Send the zygote a message to let it know we are ready to help
  398. if (!base::UnixDomainSocket::SendMsg(kNaClZygoteDescriptor,
  399. kNaClHelperStartupAck,
  400. sizeof(kNaClHelperStartupAck), empty)) {
  401. LOG(ERROR) << "*** send() to zygote failed";
  402. }
  403. // Now handle requests from the Zygote.
  404. while (true) {
  405. bool request_handled = HandleZygoteRequest(
  406. kNaClZygoteDescriptor, system_info, nacl_sandbox.get());
  407. // Do not turn this into a CHECK() without thinking about robustness
  408. // against malicious IPC requests.
  409. DCHECK(request_handled);
  410. }
  411. NOTREACHED();
  412. }