2 * Copyright 2016 Andrei Pangin
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 #include <sys/types.h>
22 #include <sys/socket.h>
24 #include <sys/syscall.h>
33 #define TMP_PATH (MAX_PATH - 64)
35 static char temp_path_storage[TMP_PATH] = {0};
40 const char* get_temp_path() {
41 return temp_path_storage;
44 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
45 // A process may have its own root path (when running in chroot environment)
47 snprintf(path, sizeof(path), "/proc/%d/root", pid);
49 // Append /tmp to the resolved root symlink
50 ssize_t path_size = readlink(path, temp_path_storage, sizeof(temp_path_storage) - 10);
51 strcpy(temp_path_storage + (path_size > 1 ? path_size : 0), "/tmp");
53 // Parse /proc/pid/status to find process credentials
54 snprintf(path, sizeof(path), "/proc/%d/status", pid);
55 FILE* status_file = fopen(path, "r");
56 if (status_file == NULL) {
63 while (getline(&line, &size, status_file) != -1) {
64 if (strncmp(line, "Uid:", 4) == 0) {
65 // Get the effective UID, which is the second value in the line
66 *uid = (uid_t)atoi(strchr(line + 5, '\t'));
67 } else if (strncmp(line, "Gid:", 4) == 0) {
68 // Get the effective GID, which is the second value in the line
69 *gid = (gid_t)atoi(strchr(line + 5, '\t'));
70 } else if (strncmp(line, "NStgid:", 7) == 0) {
71 // PID namespaces can be nested; the last one is the innermost one
72 *nspid = atoi(strrchr(line, '\t'));
81 int enter_mount_ns(int pid) {
84 snprintf(path, sizeof(path), "/proc/%d/ns/mnt", pid);
86 struct stat oldns_stat, newns_stat;
87 if (stat("/proc/self/ns/mnt", &oldns_stat) == 0 && stat(path, &newns_stat) == 0) {
88 // Don't try to call setns() if we're in the same namespace already
89 if (oldns_stat.st_ino != newns_stat.st_ino) {
90 int newns = open(path, O_RDONLY);
95 // Some ancient Linux distributions do not have setns() function
96 int result = syscall(__NR_setns, newns, 0);
98 return result < 0 ? 0 : 1;
106 // The first line of /proc/pid/sched looks like
107 // java (1234, #threads: 12)
108 // where 1234 is the required host PID
109 int sched_get_host_pid(const char* path) {
110 static char* line = NULL;
114 FILE* sched_file = fopen(path, "r");
115 if (sched_file != NULL) {
116 if (getline(&line, &size, sched_file) != -1) {
117 char* c = strrchr(line, '(');
119 result = atoi(c + 1);
128 // Linux kernels < 4.1 do not export NStgid field in /proc/pid/status.
129 // Fortunately, /proc/pid/sched in a container exposes a host PID,
130 // so the idea is to scan all container PIDs to find which one matches the host PID.
131 int alt_lookup_nspid(int pid) {
132 int namespace_differs = 0;
134 snprintf(path, sizeof(path), "/proc/%d/ns/pid", pid);
136 // Don't bother looking for container PID if we are already in the same PID namespace
137 struct stat oldns_stat, newns_stat;
138 if (stat("/proc/self/ns/pid", &oldns_stat) == 0 && stat(path, &newns_stat) == 0) {
139 if (oldns_stat.st_ino == newns_stat.st_ino) {
142 namespace_differs = 1;
145 // Otherwise browse all PIDs in the namespace of the target process
146 // trying to find which one corresponds to the host PID
147 snprintf(path, sizeof(path), "/proc/%d/root/proc", pid);
148 DIR* dir = opendir(path);
150 struct dirent* entry;
151 while ((entry = readdir(dir)) != NULL) {
152 if (entry->d_name[0] >= '1' && entry->d_name[0] <= '9') {
153 // Check if /proc/<container-pid>/sched points back to <host-pid>
154 snprintf(path, sizeof(path), "/proc/%d/root/proc/%s/sched", pid, entry->d_name);
155 if (sched_get_host_pid(path) == pid) {
157 return atoi(entry->d_name);
164 if (namespace_differs) {
165 printf("WARNING: couldn't find container pid of the target process\n");
171 #elif defined(__APPLE__)
173 #include <sys/sysctl.h>
175 // macOS has a secure per-user temporary directory
176 const char* get_temp_path() {
177 if (temp_path_storage[0] == 0) {
178 int path_size = confstr(_CS_DARWIN_USER_TEMP_DIR, temp_path_storage, sizeof(temp_path_storage));
179 if (path_size == 0 || path_size > sizeof(temp_path_storage)) {
180 strcpy(temp_path_storage, "/tmp");
184 return temp_path_storage;
187 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
188 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
189 struct kinfo_proc info;
190 size_t len = sizeof(info);
192 if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
196 *uid = info.kp_eproc.e_ucred.cr_uid;
197 *gid = info.kp_eproc.e_ucred.cr_gid;
202 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
203 int enter_mount_ns(int pid) {
207 // Not used on macOS and FreeBSD
208 int alt_lookup_nspid(int pid) {
214 #include <sys/sysctl.h>
215 #include <sys/user.h>
217 const char* get_temp_path() {
221 int get_process_info(int pid, uid_t* uid, gid_t* gid, int* nspid) {
222 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
223 struct kinfo_proc info;
224 size_t len = sizeof(info);
226 if (sysctl(mib, 4, &info, &len, NULL, 0) < 0 || len <= 0) {
231 *gid = info.ki_groups[0];
236 // This is a Linux-specific API; nothing to do on macOS and FreeBSD
237 int enter_mount_ns(int pid) {
241 // Not used on macOS and FreeBSD
242 int alt_lookup_nspid(int pid) {
249 // Check if remote JVM has already opened socket for Dynamic Attach
250 static int check_socket(int pid) {
252 snprintf(path, sizeof(path), "%s/.java_pid%d", get_temp_path(), pid);
255 return stat(path, &stats) == 0 && S_ISSOCK(stats.st_mode);
258 // Check if a file is owned by current user
259 static int check_file_owner(const char* path) {
261 if (stat(path, &stats) == 0 && stats.st_uid == geteuid()) {
265 // Some mounted filesystems may change the ownership of the file.
266 // JVM will not trust such file, so it's better to remove it and try a different path
271 // Force remote JVM to start Attach listener.
272 // HotSpot will start Attach listener in response to SIGQUIT if it sees .attach_pid file
273 static int start_attach_mechanism(int pid, int nspid) {
275 snprintf(path, sizeof(path), "/proc/%d/cwd/.attach_pid%d", nspid, nspid);
277 int fd = creat(path, 0660);
278 if (fd == -1 || (close(fd) == 0 && !check_file_owner(path))) {
279 // Failed to create attach trigger in current directory. Retry in /tmp
280 snprintf(path, sizeof(path), "%s/.attach_pid%d", get_temp_path(), nspid);
281 fd = creat(path, 0660);
288 // We have to still use the host namespace pid here for the kill() call
291 // Start with 20 ms sleep and increment delay each iteration
292 struct timespec ts = {0, 20000000};
295 nanosleep(&ts, NULL);
296 result = check_socket(nspid);
297 } while (!result && (ts.tv_nsec += 20000000) < 300000000);
303 // Connect to UNIX domain socket created by JVM for Dynamic Attach
304 static int connect_socket(int pid) {
305 int fd = socket(PF_UNIX, SOCK_STREAM, 0);
310 struct sockaddr_un addr;
311 addr.sun_family = AF_UNIX;
312 int bytes = snprintf(addr.sun_path, sizeof(addr.sun_path), "%s/.java_pid%d", get_temp_path(), pid);
313 if (bytes >= sizeof(addr.sun_path)) {
314 addr.sun_path[sizeof(addr.sun_path) - 1] = 0;
317 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
324 // Send command with arguments to socket
325 static int write_command(int fd, int argc, char** argv) {
327 if (write(fd, "1", 2) <= 0) {
332 for (i = 0; i < 4; i++) {
333 const char* arg = i < argc ? argv[i] : "";
334 if (write(fd, arg, strlen(arg) + 1) <= 0) {
341 // Mirror response from remote JVM to stdout
342 static int read_response(int fd) {
344 ssize_t bytes = read(fd, buf, sizeof(buf) - 1);
346 perror("Error reading response");
350 // First line of response is the command result code
352 int result = atoi(buf);
355 fwrite(buf, 1, bytes, stdout);
356 bytes = read(fd, buf, sizeof(buf));
362 int main(int argc, char** argv) {
364 printf("jattach " JATTACH_VERSION " built on " __DATE__ "\n"
365 "Copyright 2018 Andrei Pangin\n"
367 "Usage: jattach <pid> <cmd> [args ...]\n");
371 int pid = atoi(argv[1]);
373 perror("Invalid pid provided");
377 uid_t my_uid = geteuid();
378 gid_t my_gid = getegid();
379 uid_t target_uid = my_uid;
380 gid_t target_gid = my_gid;
382 if (!get_process_info(pid, &target_uid, &target_gid, &nspid)) {
383 fprintf(stderr, "Process %d not found\n", pid);
388 nspid = alt_lookup_nspid(pid);
391 // Make sure our /tmp and target /tmp is the same
392 if (!enter_mount_ns(pid)) {
393 printf("WARNING: couldn't enter target process mnt namespace\n");
396 // Dynamic attach is allowed only for the clients with the same euid/egid.
397 // If we are running under root, switch to the required euid/egid automatically.
398 if ((my_gid != target_gid && setegid(target_gid) != 0) ||
399 (my_uid != target_uid && seteuid(target_uid) != 0)) {
400 perror("Failed to change credentials to match the target process");
404 // Make write() return EPIPE instead of silent process termination
405 signal(SIGPIPE, SIG_IGN);
407 if (!check_socket(nspid) && !start_attach_mechanism(pid, nspid)) {
408 perror("Could not start attach mechanism");
412 int fd = connect_socket(nspid);
414 perror("Could not connect to socket");
418 printf("Connected to remote JVM\n");
419 if (!write_command(fd, argc - 2, argv + 2)) {
420 perror("Error writing to socket");
425 printf("Response code = ");
428 int result = read_response(fd);