1 // Copyright (c) 2009 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.
5 // The following is duplicated from base/linux_utils.cc.
6 // We shouldn't link against C++ code in a setuid binary.
8 // Needed for O_DIRECTORY, must be defined before fcntl.h is included
9 // (and it can be included earlier than the explicit #include below
10 // in some versions of glibc).
13 #include "sandbox/linux/suid/linux_util.h"
23 #include <sys/types.h>
26 // expected prefix of the target of the /proc/self/fd/%d link for a socket
27 static const char kSocketLinkPrefix[] = "socket:[";
29 // Parse a symlink in /proc/pid/fd/$x and return the inode number of the
31 // inode_out: (output) set to the inode number on success
32 // path: e.g. /proc/1234/fd/5 (must be a UNIX domain socket descriptor)
33 static bool ProcPathGetInodeAt(ino_t* inode_out,
36 // We also check that the path is relative.
37 if (!inode_out || !path || *path == '/')
40 const ssize_t n = readlinkat(base_dir_fd, path, buf, sizeof(buf) - 1);
45 if (memcmp(kSocketLinkPrefix, buf, sizeof(kSocketLinkPrefix) - 1))
50 const unsigned long long int inode_ull =
51 strtoull(buf + sizeof(kSocketLinkPrefix) - 1, &endptr, 10);
52 if (inode_ull == ULLONG_MAX || !endptr || *endptr != ']' || errno != 0)
55 *inode_out = inode_ull;
59 static DIR* opendirat(int base_dir_fd, const char* name) {
60 // Also check that |name| is relative.
61 if (base_dir_fd < 0 || !name || *name == '/')
63 int new_dir_fd = openat(base_dir_fd, name, O_RDONLY | O_DIRECTORY);
67 return fdopendir(new_dir_fd);
70 bool FindProcessHoldingSocket(pid_t* pid_out, ino_t socket_inode) {
71 bool already_found = false;
73 DIR* proc = opendir("/proc");
77 const uid_t uid = getuid();
79 while ((dent = readdir(proc))) {
82 const unsigned long int pid_ul = strtoul(dent->d_name, &endptr, 10);
83 if (pid_ul == ULONG_MAX || !endptr || *endptr || errno != 0)
86 // We have this setuid code here because the zygote and its children have
87 // /proc/$pid/fd owned by root. While scanning through /proc, we add this
88 // extra check so users cannot accidentally gain information about other
89 // users' processes. To determine process ownership, we use the property
90 // that if user foo owns process N, then /proc/N is owned by foo.
95 snprintf(buf, sizeof(buf), "/proc/%lu", pid_ul);
96 proc_pid_fd = open(buf, O_RDONLY | O_DIRECTORY);
99 if (fstat(proc_pid_fd, &statbuf) < 0 || uid != statbuf.st_uid) {
105 DIR* fd = opendirat(proc_pid_fd, "fd");
111 while ((dent = readdir(fd))) {
113 int printed = snprintf(buf, sizeof(buf), "fd/%s", dent->d_name);
114 if (printed < 0 || printed >= (int)(sizeof(buf) - 1)) {
119 if (ProcPathGetInodeAt(&fd_inode, proc_pid_fd, buf)) {
120 if (fd_inode == socket_inode) {
128 already_found = true;
139 return already_found;