sigsys_handlers.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Copyright (c) 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. // Note: any code in this file MUST be async-signal safe.
  5. #include "sandbox/linux/seccomp-bpf-helpers/sigsys_handlers.h"
  6. #include <fcntl.h>
  7. #include <stddef.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <sys/syscall.h>
  11. #include <unistd.h>
  12. #include "base/check.h"
  13. #include "base/debug/crash_logging.h"
  14. #include "base/posix/eintr_wrapper.h"
  15. #include "build/build_config.h"
  16. #include "sandbox/linux/bpf_dsl/bpf_dsl.h"
  17. #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
  18. #include "sandbox/linux/seccomp-bpf/syscall.h"
  19. #include "sandbox/linux/services/syscall_wrappers.h"
  20. #include "sandbox/linux/system_headers/linux_seccomp.h"
  21. #include "sandbox/linux/system_headers/linux_stat.h"
  22. #include "sandbox/linux/system_headers/linux_syscalls.h"
  23. #if defined(__mips__)
  24. // __NR_Linux, is defined in <asm/unistd.h>.
  25. #include <asm/unistd.h>
  26. #endif
  27. #define SECCOMP_MESSAGE_COMMON_CONTENT "seccomp-bpf failure"
  28. #define SECCOMP_MESSAGE_CLONE_CONTENT "clone() failure"
  29. #define SECCOMP_MESSAGE_PRCTL_CONTENT "prctl() failure"
  30. #define SECCOMP_MESSAGE_IOCTL_CONTENT "ioctl() failure"
  31. #define SECCOMP_MESSAGE_KILL_CONTENT "(tg)kill() failure"
  32. #define SECCOMP_MESSAGE_FUTEX_CONTENT "futex() failure"
  33. #define SECCOMP_MESSAGE_PTRACE_CONTENT "ptrace() failure"
  34. namespace {
  35. base::debug::CrashKeyString* seccomp_crash_key = nullptr;
  36. inline bool IsArchitectureX86_64() {
  37. #if defined(__x86_64__)
  38. return true;
  39. #else
  40. return false;
  41. #endif
  42. }
  43. // Write |error_message| to stderr. Similar to RawLog(), but a bit more careful
  44. // about async-signal safety. |size| is the size to write and should typically
  45. // not include a terminating \0.
  46. void WriteToStdErr(const char* error_message, size_t size) {
  47. while (size > 0) {
  48. // TODO(jln): query the current policy to check if send() is available and
  49. // use it to perform a non-blocking write.
  50. const int ret = HANDLE_EINTR(
  51. sandbox::sys_write(STDERR_FILENO, error_message, size));
  52. // We can't handle any type of error here.
  53. if (ret <= 0 || static_cast<size_t>(ret) > size) break;
  54. size -= ret;
  55. error_message += ret;
  56. }
  57. }
  58. // Invalid syscall values are truncated to zero.
  59. // On architectures where base value is zero (Intel and Arm),
  60. // syscall number is the same as offset from base.
  61. // This function returns values between 0 and 1023 on all architectures.
  62. // On architectures where base value is different than zero (currently only
  63. // Mips), we are truncating valid syscall values to offset from base.
  64. uint32_t SyscallNumberToOffsetFromBase(uint32_t sysno) {
  65. #if defined(__mips__)
  66. // On MIPS syscall numbers are in different range than on x86 and ARM.
  67. // Valid MIPS O32 ABI syscall __NR_syscall will be truncated to zero for
  68. // simplicity.
  69. sysno = sysno - __NR_Linux;
  70. #endif
  71. if (sysno >= 1024)
  72. sysno = 0;
  73. return sysno;
  74. }
  75. // Print a seccomp-bpf failure to handle |sysno| to stderr in an
  76. // async-signal safe way.
  77. void PrintSyscallError(uint32_t sysno) {
  78. if (sysno >= 1024)
  79. sysno = 0;
  80. // TODO(markus): replace with async-signal safe snprintf when available.
  81. const size_t kNumDigits = 4;
  82. char sysno_base10[kNumDigits];
  83. uint32_t rem = sysno;
  84. uint32_t mod = 0;
  85. for (int i = kNumDigits - 1; i >= 0; i--) {
  86. mod = rem % 10;
  87. rem /= 10;
  88. sysno_base10[i] = '0' + mod;
  89. }
  90. #if defined(ARCH_CPU_MIPS_FAMILY) && defined(ARCH_CPU_32_BITS)
  91. static const char kSeccompErrorPrefix[] = __FILE__
  92. ":**CRASHING**:" SECCOMP_MESSAGE_COMMON_CONTENT " in syscall 4000 + ";
  93. #else
  94. static const char kSeccompErrorPrefix[] =
  95. __FILE__":**CRASHING**:" SECCOMP_MESSAGE_COMMON_CONTENT " in syscall ";
  96. #endif
  97. static const char kSeccompErrorPostfix[] = "\n";
  98. WriteToStdErr(kSeccompErrorPrefix, sizeof(kSeccompErrorPrefix) - 1);
  99. WriteToStdErr(sysno_base10, sizeof(sysno_base10));
  100. WriteToStdErr(kSeccompErrorPostfix, sizeof(kSeccompErrorPostfix) - 1);
  101. }
  102. // Helper to convert a number of type T to a hexadecimal string using
  103. // stack-allocated storage.
  104. template <typename T>
  105. class NumberToHex {
  106. public:
  107. explicit NumberToHex(T value) {
  108. static const char kHexChars[] = "0123456789abcdef";
  109. memset(str_, '0', sizeof(str_));
  110. str_[1] = 'x';
  111. str_[sizeof(str_) - 1] = '\0';
  112. T rem = value;
  113. T mod = 0;
  114. for (size_t i = sizeof(str_) - 2; i >= 2; --i) {
  115. mod = rem % 16;
  116. rem /= 16;
  117. str_[i] = kHexChars[mod];
  118. }
  119. }
  120. const char* str() const { return str_; }
  121. static size_t length() { return sizeof(str_) - 1; }
  122. private:
  123. // HEX uses two characters per byte, with a leading '0x', and a trailing NUL.
  124. char str_[sizeof(T) * 2 + 3];
  125. };
  126. // Records the syscall number and first four arguments in a crash key, to help
  127. // debug the failure.
  128. void SetSeccompCrashKey(const struct arch_seccomp_data& args) {
  129. NumberToHex<int> nr(args.nr);
  130. NumberToHex<uint64_t> arg1(args.args[0]);
  131. NumberToHex<uint64_t> arg2(args.args[1]);
  132. NumberToHex<uint64_t> arg3(args.args[2]);
  133. NumberToHex<uint64_t> arg4(args.args[3]);
  134. // In order to avoid calling into libc sprintf functions from an unsafe signal
  135. // context, manually construct the crash key string.
  136. const char* const prefixes[] = {
  137. "nr=",
  138. " arg1=",
  139. " arg2=",
  140. " arg3=",
  141. " arg4=",
  142. };
  143. const char* const values[] = {
  144. nr.str(),
  145. arg1.str(),
  146. arg2.str(),
  147. arg3.str(),
  148. arg4.str(),
  149. };
  150. size_t crash_key_length = nr.length() + arg1.length() + arg2.length() +
  151. arg3.length() + arg4.length();
  152. for (auto* prefix : prefixes) {
  153. crash_key_length += strlen(prefix);
  154. }
  155. ++crash_key_length; // For the trailing NUL byte.
  156. char crash_key[crash_key_length];
  157. memset(crash_key, '\0', crash_key_length);
  158. size_t offset = 0;
  159. for (size_t i = 0; i < std::size(values); ++i) {
  160. const char* strings[2] = { prefixes[i], values[i] };
  161. for (auto* string : strings) {
  162. size_t string_len = strlen(string);
  163. memmove(&crash_key[offset], string, string_len);
  164. offset += string_len;
  165. }
  166. }
  167. base::debug::SetCrashKeyString(seccomp_crash_key, crash_key);
  168. }
  169. } // namespace
  170. namespace sandbox {
  171. intptr_t CrashSIGSYS_Handler(const struct arch_seccomp_data& args, void* aux) {
  172. uint32_t syscall = SyscallNumberToOffsetFromBase(args.nr);
  173. PrintSyscallError(syscall);
  174. SetSeccompCrashKey(args);
  175. // Encode 8-bits of the 1st two arguments too, so we can discern which socket
  176. // type, which fcntl, ... etc., without being likely to hit a mapped
  177. // address.
  178. // Do not encode more bits here without thinking about increasing the
  179. // likelihood of collision with mapped pages.
  180. syscall |= ((args.args[0] & 0xffUL) << 12);
  181. syscall |= ((args.args[1] & 0xffUL) << 20);
  182. // Purposefully dereference the syscall as an address so it'll show up very
  183. // clearly and easily in crash dumps.
  184. volatile char* addr = reinterpret_cast<volatile char*>(syscall);
  185. *addr = '\0';
  186. // In case we hit a mapped address, hit the null page with just the syscall,
  187. // for paranoia.
  188. syscall &= 0xfffUL;
  189. addr = reinterpret_cast<volatile char*>(syscall);
  190. *addr = '\0';
  191. for (;;)
  192. _exit(1);
  193. }
  194. // TODO(jln): refactor the reporting functions.
  195. intptr_t SIGSYSCloneFailure(const struct arch_seccomp_data& args, void* aux) {
  196. static const char kSeccompCloneError[] =
  197. __FILE__":**CRASHING**:" SECCOMP_MESSAGE_CLONE_CONTENT "\n";
  198. WriteToStdErr(kSeccompCloneError, sizeof(kSeccompCloneError) - 1);
  199. SetSeccompCrashKey(args);
  200. // "flags" is the first argument in the kernel's clone().
  201. // Mark as volatile to be able to find the value on the stack in a minidump.
  202. volatile uint64_t clone_flags = args.args[0];
  203. volatile char* addr;
  204. if (IsArchitectureX86_64()) {
  205. addr = reinterpret_cast<volatile char*>(clone_flags & 0xFFFFFF);
  206. *addr = '\0';
  207. }
  208. // Hit the NULL page if this fails to fault.
  209. addr = reinterpret_cast<volatile char*>(clone_flags & 0xFFF);
  210. *addr = '\0';
  211. for (;;)
  212. _exit(1);
  213. }
  214. intptr_t SIGSYSPrctlFailure(const struct arch_seccomp_data& args,
  215. void* /* aux */) {
  216. static const char kSeccompPrctlError[] =
  217. __FILE__":**CRASHING**:" SECCOMP_MESSAGE_PRCTL_CONTENT "\n";
  218. WriteToStdErr(kSeccompPrctlError, sizeof(kSeccompPrctlError) - 1);
  219. SetSeccompCrashKey(args);
  220. // Mark as volatile to be able to find the value on the stack in a minidump.
  221. volatile uint64_t option = args.args[0];
  222. volatile char* addr =
  223. reinterpret_cast<volatile char*>(option & 0xFFF);
  224. *addr = '\0';
  225. for (;;)
  226. _exit(1);
  227. }
  228. intptr_t SIGSYSIoctlFailure(const struct arch_seccomp_data& args,
  229. void* /* aux */) {
  230. static const char kSeccompIoctlError[] =
  231. __FILE__":**CRASHING**:" SECCOMP_MESSAGE_IOCTL_CONTENT "\n";
  232. WriteToStdErr(kSeccompIoctlError, sizeof(kSeccompIoctlError) - 1);
  233. SetSeccompCrashKey(args);
  234. // Make "request" volatile so that we can see it on the stack in a minidump.
  235. volatile uint64_t request = args.args[1];
  236. volatile char* addr = reinterpret_cast<volatile char*>(request & 0xFFFF);
  237. *addr = '\0';
  238. // Hit the NULL page if this fails.
  239. addr = reinterpret_cast<volatile char*>(request & 0xFFF);
  240. *addr = '\0';
  241. for (;;)
  242. _exit(1);
  243. }
  244. intptr_t SIGSYSKillFailure(const struct arch_seccomp_data& args,
  245. void* /* aux */) {
  246. static const char kSeccompKillError[] =
  247. __FILE__":**CRASHING**:" SECCOMP_MESSAGE_KILL_CONTENT "\n";
  248. WriteToStdErr(kSeccompKillError, sizeof(kSeccompKillError) - 1);
  249. SetSeccompCrashKey(args);
  250. // Make "pid" volatile so that we can see it on the stack in a minidump.
  251. volatile uint64_t my_pid = sys_getpid();
  252. volatile char* addr = reinterpret_cast<volatile char*>(my_pid & 0xFFF);
  253. *addr = '\0';
  254. for (;;)
  255. _exit(1);
  256. }
  257. intptr_t SIGSYSFutexFailure(const struct arch_seccomp_data& args,
  258. void* /* aux */) {
  259. static const char kSeccompFutexError[] =
  260. __FILE__ ":**CRASHING**:" SECCOMP_MESSAGE_FUTEX_CONTENT "\n";
  261. WriteToStdErr(kSeccompFutexError, sizeof(kSeccompFutexError) - 1);
  262. SetSeccompCrashKey(args);
  263. volatile int futex_op = args.args[1];
  264. volatile char* addr = reinterpret_cast<volatile char*>(futex_op & 0xFFF);
  265. *addr = '\0';
  266. for (;;)
  267. _exit(1);
  268. }
  269. intptr_t SIGSYSPtraceFailure(const struct arch_seccomp_data& args,
  270. void* /* aux */) {
  271. static const char kSeccompPtraceError[] =
  272. __FILE__ ":**CRASHING**:" SECCOMP_MESSAGE_PTRACE_CONTENT "\n";
  273. WriteToStdErr(kSeccompPtraceError, sizeof(kSeccompPtraceError) - 1);
  274. SetSeccompCrashKey(args);
  275. volatile int ptrace_op = args.args[0];
  276. volatile char* addr = reinterpret_cast<volatile char*>(ptrace_op & 0xFFF);
  277. *addr = '\0';
  278. for (;;)
  279. _exit(1);
  280. }
  281. intptr_t SIGSYSSchedHandler(const struct arch_seccomp_data& args,
  282. void* aux) {
  283. switch (args.nr) {
  284. case __NR_sched_getaffinity:
  285. case __NR_sched_getattr:
  286. case __NR_sched_getparam:
  287. case __NR_sched_getscheduler:
  288. case __NR_sched_rr_get_interval:
  289. case __NR_sched_setaffinity:
  290. case __NR_sched_setattr:
  291. case __NR_sched_setparam:
  292. case __NR_sched_setscheduler:
  293. const pid_t tid = sys_gettid();
  294. // The first argument is the pid. If is our thread id, then replace it
  295. // with 0, which is equivalent and allowed by the policy.
  296. if (args.args[0] == static_cast<uint64_t>(tid)) {
  297. return Syscall::Call(args.nr,
  298. 0,
  299. static_cast<intptr_t>(args.args[1]),
  300. static_cast<intptr_t>(args.args[2]),
  301. static_cast<intptr_t>(args.args[3]),
  302. static_cast<intptr_t>(args.args[4]),
  303. static_cast<intptr_t>(args.args[5]));
  304. }
  305. break;
  306. }
  307. CrashSIGSYS_Handler(args, aux);
  308. // Should never be reached.
  309. RAW_CHECK(false);
  310. return -ENOSYS;
  311. }
  312. intptr_t SIGSYSFstatatHandler(const struct arch_seccomp_data& args,
  313. void* fs_denied_errno) {
  314. if (args.nr == __NR_fstatat_default) {
  315. if (*reinterpret_cast<const char*>(args.args[1]) == '\0' &&
  316. args.args[3] == static_cast<uint64_t>(AT_EMPTY_PATH)) {
  317. return syscall(__NR_fstat_default, static_cast<int>(args.args[0]),
  318. reinterpret_cast<default_stat_struct*>(args.args[2]));
  319. }
  320. return -reinterpret_cast<intptr_t>(fs_denied_errno);
  321. }
  322. CrashSIGSYS_Handler(args, fs_denied_errno);
  323. // Should never be reached.
  324. RAW_CHECK(false);
  325. return -ENOSYS;
  326. }
  327. bpf_dsl::ResultExpr CrashSIGSYS() {
  328. return bpf_dsl::Trap(CrashSIGSYS_Handler, NULL);
  329. }
  330. bpf_dsl::ResultExpr CrashSIGSYSClone() {
  331. return bpf_dsl::Trap(SIGSYSCloneFailure, NULL);
  332. }
  333. bpf_dsl::ResultExpr CrashSIGSYSPrctl() {
  334. return bpf_dsl::Trap(SIGSYSPrctlFailure, NULL);
  335. }
  336. bpf_dsl::ResultExpr CrashSIGSYSIoctl() {
  337. return bpf_dsl::Trap(SIGSYSIoctlFailure, NULL);
  338. }
  339. bpf_dsl::ResultExpr CrashSIGSYSKill() {
  340. return bpf_dsl::Trap(SIGSYSKillFailure, NULL);
  341. }
  342. bpf_dsl::ResultExpr CrashSIGSYSFutex() {
  343. return bpf_dsl::Trap(SIGSYSFutexFailure, NULL);
  344. }
  345. bpf_dsl::ResultExpr CrashSIGSYSPtrace() {
  346. return bpf_dsl::Trap(SIGSYSPtraceFailure, NULL);
  347. }
  348. bpf_dsl::ResultExpr RewriteSchedSIGSYS() {
  349. return bpf_dsl::Trap(SIGSYSSchedHandler, NULL);
  350. }
  351. bpf_dsl::ResultExpr RewriteFstatatSIGSYS(int fs_denied_errno) {
  352. return bpf_dsl::Trap(SIGSYSFstatatHandler,
  353. reinterpret_cast<void*>(fs_denied_errno));
  354. }
  355. void AllocateCrashKeys() {
  356. if (seccomp_crash_key)
  357. return;
  358. seccomp_crash_key = base::debug::AllocateCrashKeyString(
  359. "seccomp-sigsys", base::debug::CrashKeySize::Size256);
  360. }
  361. const char* GetErrorMessageContentForTests() {
  362. return SECCOMP_MESSAGE_COMMON_CONTENT;
  363. }
  364. const char* GetCloneErrorMessageContentForTests() {
  365. return SECCOMP_MESSAGE_CLONE_CONTENT;
  366. }
  367. const char* GetPrctlErrorMessageContentForTests() {
  368. return SECCOMP_MESSAGE_PRCTL_CONTENT;
  369. }
  370. const char* GetIoctlErrorMessageContentForTests() {
  371. return SECCOMP_MESSAGE_IOCTL_CONTENT;
  372. }
  373. const char* GetKillErrorMessageContentForTests() {
  374. return SECCOMP_MESSAGE_KILL_CONTENT;
  375. }
  376. const char* GetFutexErrorMessageContentForTests() {
  377. return SECCOMP_MESSAGE_FUTEX_CONTENT;
  378. }
  379. const char* GetPtraceErrorMessageContentForTests() {
  380. return SECCOMP_MESSAGE_PTRACE_CONTENT;
  381. }
  382. } // namespace sandbox.