| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use format::elf; |
| 5 |
|
| 6 |
export fn start_linux(iv: *[*]uintptr) never = { |
| 7 |
argc = iv[0]: size; |
| 8 |
argv = &iv[1]: *[*]*u8; |
| 9 |
envp = &argv[argc + 1]: *[*]nullable *u8; |
| 10 |
|
| 11 |
// Read auxv to determine if we need to sanitize file descriptors |
| 12 |
let i = 0z; |
| 13 |
for (envp[i] != null) i += 1; |
| 14 |
const auxv = &envp[i + 1]: *[*][2]uintptr; |
| 15 |
|
| 16 |
let secure = false; |
| 17 |
let uid: uintptr = 0, euid: uintptr = 0; |
| 18 |
let gid: uintptr = 0, egid: uintptr = 0; |
| 19 |
for (let j = 0z; auxv[j][0]: u64 != elf::at::NULL; j += 1) { |
| 20 |
switch (auxv[j][0]: u64) { |
| 21 |
case elf::at::SECURE => secure = auxv[j][1] != 0; |
| 22 |
case elf::at::UID => uid = auxv[j][1]; |
| 23 |
case elf::at::EUID => euid = auxv[j][1]; |
| 24 |
case elf::at::GID => gid = auxv[j][1]; |
| 25 |
case elf::at::EGID => egid = auxv[j][1]; |
| 26 |
case => void; |
| 27 |
}; |
| 28 |
}; |
| 29 |
|
| 30 |
if (secure || uid != euid || gid != egid) { |
| 31 |
sanitize_stdio(); |
| 32 |
}; |
| 33 |
|
| 34 |
start_ha(); |
| 35 |
}; |
| 36 |
|
| 37 |
// The standard library's stdin/stdout/stderr always refer to file descriptors |
| 38 |
// 0, 1, and 2. If these have not been opened, subsequent file descriptors may |
| 39 |
// take these FD numbers, causing I/O intended for stdin/stdout/stderr to use |
| 40 |
// these files instead. |
| 41 |
// |
| 42 |
// If the process is setuid, this can cause the program to write garbage, leak |
| 43 |
// information, or otherwise misbehave within the context of its elevated |
| 44 |
// privileges. In case we have elevated permissions, ensure file descriptors 0-2 |
| 45 |
// are valid and replace them with /dev/null if not. |
| 46 |
fn sanitize_stdio() void = { |
| 47 |
let pfds: [3]pollfd = [ |
| 48 |
pollfd { fd = 0, ... }, |
| 49 |
pollfd { fd = 1, ... }, |
| 50 |
pollfd { fd = 2, ... }, |
| 51 |
]; |
| 52 |
|
| 53 |
const r = poll(&pfds: *[*]pollfd, 3, 0)!; |
| 54 |
for (let i = 0z; i < 3; i += 1) { |
| 55 |
if (pfds[i].revents & POLLNVAL != 0) { |
| 56 |
_ = open("/dev/null", O_RDWR, 0); |
| 57 |
}; |
| 58 |
}; |
| 59 |
}; |