aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/Makefile.in20
-rw-r--r--src/lib/common.c192
-rw-r--r--src/lib/libnetlink.c803
-rw-r--r--src/lib/pid.c392
4 files changed, 1407 insertions, 0 deletions
diff --git a/src/lib/Makefile.in b/src/lib/Makefile.in
new file mode 100644
index 000000000..6e6be1910
--- /dev/null
+++ b/src/lib/Makefile.in
@@ -0,0 +1,20 @@
1PREFIX=@prefix@
2VERSION=@PACKAGE_VERSION@
3NAME=@PACKAGE_NAME@
4
5H_FILE_LIST = $(wildcard *.[h])
6C_FILE_LIST = $(wildcard *.c)
7OBJS = $(C_FILE_LIST:.c=.o)
8BINOBJS = $(foreach file, $(OBJS), $file)
9CFLAGS += -ggdb -O2 -DVERSION='"$(VERSION)"' -fstack-protector-all -D_FORTIFY_SOURCE=2 -fPIC -Wformat -Wformat-security
10LDFLAGS:=-pic -Wl,-z,relro -Wl,-z,now
11
12all: $(OBJS)
13
14%.o : %.c $(H_FILE_LIST)
15 $(CC) $(CFLAGS) $(INCLUDE) -c $< -o $@
16
17clean:; rm -f $(OBJS)
18
19distclean: clean
20 rm -fr Makefile
diff --git a/src/lib/common.c b/src/lib/common.c
new file mode 100644
index 000000000..6d928abbb
--- /dev/null
+++ b/src/lib/common.c
@@ -0,0 +1,192 @@
1/*
2 * Copyright (C) 2014, 2015 netblue30 (netblue30@yahoo.com)
3 *
4 * This file is part of firejail project
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19*/
20#define _GNU_SOURCE
21#include <stdio.h>
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <sys/wait.h>
25#include <fcntl.h>
26#include <sys/syscall.h>
27#include <errno.h>
28#include <unistd.h>
29#include <sys/prctl.h>
30#include <signal.h>
31#include <dirent.h>
32#include <string.h>
33#include "../include/common.h"
34
35int join_namespace(pid_t pid, char *type) {
36 char *path;
37 if (asprintf(&path, "/proc/%u/ns/%s", pid, type) == -1)
38 errExit("asprintf");
39
40 int fd = open(path, O_RDONLY);
41 if (fd < 0) {
42 free(path);
43 fprintf(stderr, "Error: cannot open /proc/%u/ns/%s.\n", pid, type);
44 return -1;
45 }
46
47 if (syscall(__NR_setns, fd, 0) < 0) {
48 free(path);
49 fprintf(stderr, "Error: cannot join namespace %s.\n", type);
50 close(fd);
51 return -1;
52 }
53
54 close(fd);
55 free(path);
56 return 0;
57}
58
59// return 1 if error
60int name2pid(const char *name, pid_t *pid) {
61 pid_t parent = getpid();
62
63 DIR *dir;
64 if (!(dir = opendir("/proc"))) {
65 // sleep 2 seconds and try again
66 sleep(2);
67 if (!(dir = opendir("/proc"))) {
68 fprintf(stderr, "Error: cannot open /proc directory\n");
69 exit(1);
70 }
71 }
72
73 struct dirent *entry;
74 char *end;
75 while ((entry = readdir(dir))) {
76 pid_t newpid = strtol(entry->d_name, &end, 10);
77 if (end == entry->d_name || *end)
78 continue;
79 if (newpid == parent)
80 continue;
81
82 // check if this is a firejail executable
83 char *comm = pid_proc_comm(newpid);
84 if (comm) {
85 // remove \n
86 char *ptr = strchr(comm, '\n');
87 if (ptr)
88 *ptr = '\0';
89 if (strcmp(comm, "firejail")) {
90 free(comm);
91 continue;
92 }
93 free(comm);
94 }
95
96 char *cmd = pid_proc_cmdline(newpid);
97 if (cmd) {
98 // mark the end of the name
99 char *ptr = strstr(cmd, "--name=");
100 char *start = ptr;
101 if (!ptr) {
102 free(cmd);
103 continue;
104 }
105 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
106 ptr++;
107 *ptr = '\0';
108 int rv = strcmp(start + 7, name);
109 if (rv == 0) {
110 free(cmd);
111 *pid = newpid;
112 closedir(dir);
113 return 0;
114 }
115 free(cmd);
116 }
117 }
118 closedir(dir);
119 return 1;
120}
121
122#define BUFLEN 4096
123char *pid_proc_comm(const pid_t pid) {
124 // open /proc/pid/cmdline file
125 char *fname;
126 int fd;
127 if (asprintf(&fname, "/proc/%d//comm", pid) == -1)
128 return NULL;
129 if ((fd = open(fname, O_RDONLY)) < 0) {
130 free(fname);
131 return NULL;
132 }
133 free(fname);
134
135 // read file
136 unsigned char buffer[BUFLEN];
137 ssize_t len;
138 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0) {
139 close(fd);
140 return NULL;
141 }
142 buffer[len] = '\0';
143 close(fd);
144
145 // return a malloc copy of the command line
146 char *rv = strdup((char *) buffer);
147 if (strlen(rv) == 0) {
148 free(rv);
149 return NULL;
150 }
151 return rv;
152}
153
154char *pid_proc_cmdline(const pid_t pid) {
155 // open /proc/pid/cmdline file
156 char *fname;
157 int fd;
158 if (asprintf(&fname, "/proc/%d/cmdline", pid) == -1)
159 return NULL;
160 if ((fd = open(fname, O_RDONLY)) < 0) {
161 free(fname);
162 return NULL;
163 }
164 free(fname);
165
166 // read file
167 unsigned char buffer[BUFLEN];
168 ssize_t len;
169 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0) {
170 close(fd);
171 return NULL;
172 }
173 buffer[len] = '\0';
174 close(fd);
175
176 // clean data
177 int i;
178 for (i = 0; i < len; i++) {
179 if (buffer[i] == '\0')
180 buffer[i] = ' ';
181 if (buffer[i] >= 0x80) // execv in progress!!!
182 return NULL;
183 }
184
185 // return a malloc copy of the command line
186 char *rv = strdup((char *) buffer);
187 if (strlen(rv) == 0) {
188 free(rv);
189 return NULL;
190 }
191 return rv;
192}
diff --git a/src/lib/libnetlink.c b/src/lib/libnetlink.c
new file mode 100644
index 000000000..264632a01
--- /dev/null
+++ b/src/lib/libnetlink.c
@@ -0,0 +1,803 @@
1/* file extracted from iproute2 software package
2 *
3 * Original source code:
4 *
5 * Information:
6 * http://www.linuxfoundation.org/collaborate/workgroups/networking/iproute2
7 *
8 * Download:
9 * http://www.kernel.org/pub/linux/utils/net/iproute2/
10 *
11 * Repository:
12 * git://git.kernel.org/pub/scm/linux/kernel/git/shemminger/iproute2.git
13 *
14 * License: GPL v2
15 *
16 * Original copyright header
17 *
18 * libnetlink.c RTnetlink service routines.
19 *
20 * This program is free software; you can redistribute it and/or
21 * modify it under the terms of the GNU General Public License
22 * as published by the Free Software Foundation; either version
23 * 2 of the License, or (at your option) any later version.
24 *
25 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
26 *
27 */
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <unistd.h>
32#include <syslog.h>
33#include <fcntl.h>
34#include <net/if_arp.h>
35#include <sys/socket.h>
36#include <netinet/in.h>
37#include <string.h>
38#include <errno.h>
39#include <time.h>
40#include <sys/uio.h>
41
42#include "../include/libnetlink.h"
43
44int rcvbuf = 1024 * 1024;
45
46void rtnl_close(struct rtnl_handle *rth)
47{
48 if (rth->fd >= 0) {
49 close(rth->fd);
50 rth->fd = -1;
51 }
52}
53
54int rtnl_open_byproto(struct rtnl_handle *rth, unsigned subscriptions,
55 int protocol)
56{
57 socklen_t addr_len;
58 int sndbuf = 32768;
59
60 memset(rth, 0, sizeof(*rth));
61
62 rth->fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, protocol);
63 if (rth->fd < 0) {
64 perror("Cannot open netlink socket");
65 return -1;
66 }
67
68 if (setsockopt(rth->fd,SOL_SOCKET,SO_SNDBUF,&sndbuf,sizeof(sndbuf)) < 0) {
69 perror("SO_SNDBUF");
70 return -1;
71 }
72
73 if (setsockopt(rth->fd,SOL_SOCKET,SO_RCVBUF,&rcvbuf,sizeof(rcvbuf)) < 0) {
74 perror("SO_RCVBUF");
75 return -1;
76 }
77
78 memset(&rth->local, 0, sizeof(rth->local));
79 rth->local.nl_family = AF_NETLINK;
80 rth->local.nl_groups = subscriptions;
81
82 if (bind(rth->fd, (struct sockaddr*)&rth->local, sizeof(rth->local)) < 0) {
83 perror("Cannot bind netlink socket");
84 return -1;
85 }
86 addr_len = sizeof(rth->local);
87 if (getsockname(rth->fd, (struct sockaddr*)&rth->local, &addr_len) < 0) {
88 perror("Cannot getsockname");
89 return -1;
90 }
91 if (addr_len != sizeof(rth->local)) {
92 fprintf(stderr, "Wrong address length %d\n", addr_len);
93 return -1;
94 }
95 if (rth->local.nl_family != AF_NETLINK) {
96 fprintf(stderr, "Wrong address family %d\n", rth->local.nl_family);
97 return -1;
98 }
99 rth->seq = time(NULL);
100 return 0;
101}
102
103int rtnl_open(struct rtnl_handle *rth, unsigned subscriptions)
104{
105 return rtnl_open_byproto(rth, subscriptions, NETLINK_ROUTE);
106}
107
108int rtnl_wilddump_request(struct rtnl_handle *rth, int family, int type)
109{
110 return rtnl_wilddump_req_filter(rth, family, type, RTEXT_FILTER_VF);
111}
112
113int rtnl_wilddump_req_filter(struct rtnl_handle *rth, int family, int type,
114 __u32 filt_mask)
115{
116 struct {
117 struct nlmsghdr nlh;
118 struct ifinfomsg ifm;
119 /* attribute has to be NLMSG aligned */
120 struct rtattr ext_req __attribute__ ((aligned(NLMSG_ALIGNTO)));
121 __u32 ext_filter_mask;
122 } req;
123
124 memset(&req, 0, sizeof(req));
125 req.nlh.nlmsg_len = sizeof(req);
126 req.nlh.nlmsg_type = type;
127 req.nlh.nlmsg_flags = NLM_F_DUMP|NLM_F_REQUEST;
128 req.nlh.nlmsg_pid = 0;
129 req.nlh.nlmsg_seq = rth->dump = ++rth->seq;
130 req.ifm.ifi_family = family;
131
132 req.ext_req.rta_type = IFLA_EXT_MASK;
133 req.ext_req.rta_len = RTA_LENGTH(sizeof(__u32));
134 req.ext_filter_mask = filt_mask;
135
136 return send(rth->fd, (void*)&req, sizeof(req), 0);
137}
138
139int rtnl_send(struct rtnl_handle *rth, const void *buf, int len)
140{
141 return send(rth->fd, buf, len, 0);
142}
143
144int rtnl_send_check(struct rtnl_handle *rth, const void *buf, int len)
145{
146 struct nlmsghdr *h;
147 int status;
148 char resp[1024];
149
150 status = send(rth->fd, buf, len, 0);
151 if (status < 0)
152 return status;
153
154 /* Check for immediate errors */
155 status = recv(rth->fd, resp, sizeof(resp), MSG_DONTWAIT|MSG_PEEK);
156 if (status < 0) {
157 if (errno == EAGAIN)
158 return 0;
159 return -1;
160 }
161
162 for (h = (struct nlmsghdr *)resp; NLMSG_OK(h, status);
163 h = NLMSG_NEXT(h, status)) {
164 if (h->nlmsg_type == NLMSG_ERROR) {
165 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
166 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr)))
167 fprintf(stderr, "ERROR truncated\n");
168 else
169 errno = -err->error;
170 return -1;
171 }
172 }
173
174 return 0;
175}
176
177int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len)
178{
179 struct nlmsghdr nlh;
180 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
181 struct iovec iov[2] = {
182 { .iov_base = &nlh, .iov_len = sizeof(nlh) },
183 { .iov_base = req, .iov_len = len }
184 };
185 struct msghdr msg = {
186 .msg_name = &nladdr,
187 .msg_namelen = sizeof(nladdr),
188 .msg_iov = iov,
189 .msg_iovlen = 2,
190 };
191
192 nlh.nlmsg_len = NLMSG_LENGTH(len);
193 nlh.nlmsg_type = type;
194 nlh.nlmsg_flags = NLM_F_DUMP|NLM_F_REQUEST;
195 nlh.nlmsg_pid = 0;
196 nlh.nlmsg_seq = rth->dump = ++rth->seq;
197
198 return sendmsg(rth->fd, &msg, 0);
199}
200
201int rtnl_dump_filter_l(struct rtnl_handle *rth,
202 const struct rtnl_dump_filter_arg *arg)
203{
204 struct sockaddr_nl nladdr;
205 struct iovec iov;
206 struct msghdr msg = {
207 .msg_name = &nladdr,
208 .msg_namelen = sizeof(nladdr),
209 .msg_iov = &iov,
210 .msg_iovlen = 1,
211 };
212 char buf[16384];
213 int dump_intr = 0;
214
215 iov.iov_base = buf;
216 while (1) {
217 int status;
218 const struct rtnl_dump_filter_arg *a;
219 int found_done = 0;
220 int msglen = 0;
221
222 iov.iov_len = sizeof(buf);
223 status = recvmsg(rth->fd, &msg, 0);
224
225 if (status < 0) {
226 if (errno == EINTR || errno == EAGAIN)
227 continue;
228 fprintf(stderr, "netlink receive error %s (%d)\n",
229 strerror(errno), errno);
230 return -1;
231 }
232
233 if (status == 0) {
234 fprintf(stderr, "EOF on netlink\n");
235 return -1;
236 }
237
238 for (a = arg; a->filter; a++) {
239 struct nlmsghdr *h = (struct nlmsghdr*)buf;
240 msglen = status;
241
242 while (NLMSG_OK(h, msglen)) {
243 int err;
244
245 if (nladdr.nl_pid != 0 ||
246 h->nlmsg_pid != rth->local.nl_pid ||
247 h->nlmsg_seq != rth->dump)
248 goto skip_it;
249
250 if (h->nlmsg_flags & NLM_F_DUMP_INTR)
251 dump_intr = 1;
252
253 if (h->nlmsg_type == NLMSG_DONE) {
254 found_done = 1;
255 break; /* process next filter */
256 }
257 if (h->nlmsg_type == NLMSG_ERROR) {
258 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
259 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
260 fprintf(stderr,
261 "ERROR truncated\n");
262 } else {
263 errno = -err->error;
264 perror("RTNETLINK answers");
265 }
266 return -1;
267 }
268 err = a->filter(&nladdr, h, a->arg1);
269 if (err < 0)
270 return err;
271
272skip_it:
273 h = NLMSG_NEXT(h, msglen);
274 }
275 }
276
277 if (found_done) {
278 if (dump_intr)
279 fprintf(stderr,
280 "Dump was interrupted and may be inconsistent.\n");
281 return 0;
282 }
283
284 if (msg.msg_flags & MSG_TRUNC) {
285 fprintf(stderr, "Message truncated\n");
286 continue;
287 }
288 if (msglen) {
289 fprintf(stderr, "!!!Remnant of size %d\n", msglen);
290 exit(1);
291 }
292 }
293}
294
295int rtnl_dump_filter(struct rtnl_handle *rth,
296 rtnl_filter_t filter,
297 void *arg1)
298{
299 const struct rtnl_dump_filter_arg a[2] = {
300 { .filter = filter, .arg1 = arg1, },
301 { .filter = NULL, .arg1 = NULL, },
302 };
303
304 return rtnl_dump_filter_l(rth, a);
305}
306
307int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n, pid_t peer,
308 unsigned groups, struct nlmsghdr *answer)
309{
310 int status;
311 unsigned seq;
312 struct nlmsghdr *h;
313 struct sockaddr_nl nladdr;
314 struct iovec iov = {
315 .iov_base = (void*) n,
316 .iov_len = n->nlmsg_len
317 };
318 struct msghdr msg = {
319 .msg_name = &nladdr,
320 .msg_namelen = sizeof(nladdr),
321 .msg_iov = &iov,
322 .msg_iovlen = 1,
323 };
324 char buf[16384];
325
326 memset(&nladdr, 0, sizeof(nladdr));
327 nladdr.nl_family = AF_NETLINK;
328 nladdr.nl_pid = peer;
329 nladdr.nl_groups = groups;
330
331 n->nlmsg_seq = seq = ++rtnl->seq;
332
333 if (answer == NULL)
334 n->nlmsg_flags |= NLM_F_ACK;
335
336 status = sendmsg(rtnl->fd, &msg, 0);
337
338 if (status < 0) {
339 perror("Cannot talk to rtnetlink");
340 return -1;
341 }
342
343 memset(buf,0,sizeof(buf));
344
345 iov.iov_base = buf;
346
347 while (1) {
348 iov.iov_len = sizeof(buf);
349 status = recvmsg(rtnl->fd, &msg, 0);
350
351 if (status < 0) {
352 if (errno == EINTR || errno == EAGAIN)
353 continue;
354 fprintf(stderr, "netlink receive error %s (%d)\n",
355 strerror(errno), errno);
356 return -1;
357 }
358 if (status == 0) {
359 fprintf(stderr, "EOF on netlink\n");
360 return -1;
361 }
362 if (msg.msg_namelen != sizeof(nladdr)) {
363 fprintf(stderr, "sender address length == %d\n", msg.msg_namelen);
364 exit(1);
365 }
366 for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) {
367 int len = h->nlmsg_len;
368 int l = len - sizeof(*h);
369
370 if (l < 0 || len>status) {
371 if (msg.msg_flags & MSG_TRUNC) {
372 fprintf(stderr, "Truncated message\n");
373 return -1;
374 }
375 fprintf(stderr, "!!!malformed message: len=%d\n", len);
376 exit(1);
377 }
378
379 if (nladdr.nl_pid != peer ||
380 h->nlmsg_pid != rtnl->local.nl_pid ||
381 h->nlmsg_seq != seq) {
382 /* Don't forget to skip that message. */
383 status -= NLMSG_ALIGN(len);
384 h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
385 continue;
386 }
387
388 if (h->nlmsg_type == NLMSG_ERROR) {
389 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
390 if (l < sizeof(struct nlmsgerr)) {
391 fprintf(stderr, "ERROR truncated\n");
392 } else {
393 if (!err->error) {
394 if (answer)
395 memcpy(answer, h, h->nlmsg_len);
396 return 0;
397 }
398
399 fprintf(stderr, "RTNETLINK answers: %s\n", strerror(-err->error));
400 errno = -err->error;
401 }
402 return -1;
403 }
404 if (answer) {
405 memcpy(answer, h, h->nlmsg_len);
406 return 0;
407 }
408
409 fprintf(stderr, "Unexpected reply!!!\n");
410
411 status -= NLMSG_ALIGN(len);
412 h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
413 }
414 if (msg.msg_flags & MSG_TRUNC) {
415 fprintf(stderr, "Message truncated\n");
416 continue;
417 }
418 if (status) {
419 fprintf(stderr, "!!!Remnant of size %d\n", status);
420 exit(1);
421 }
422 }
423}
424
425int rtnl_listen(struct rtnl_handle *rtnl,
426 rtnl_filter_t handler,
427 void *jarg)
428{
429 int status;
430 struct nlmsghdr *h;
431 struct sockaddr_nl nladdr;
432 struct iovec iov;
433 struct msghdr msg = {
434 .msg_name = &nladdr,
435 .msg_namelen = sizeof(nladdr),
436 .msg_iov = &iov,
437 .msg_iovlen = 1,
438 };
439 char buf[8192];
440
441 memset(&nladdr, 0, sizeof(nladdr));
442 nladdr.nl_family = AF_NETLINK;
443 nladdr.nl_pid = 0;
444 nladdr.nl_groups = 0;
445
446 iov.iov_base = buf;
447 while (1) {
448 iov.iov_len = sizeof(buf);
449 status = recvmsg(rtnl->fd, &msg, 0);
450
451 if (status < 0) {
452 if (errno == EINTR || errno == EAGAIN)
453 continue;
454 fprintf(stderr, "netlink receive error %s (%d)\n",
455 strerror(errno), errno);
456 if (errno == ENOBUFS)
457 continue;
458 return -1;
459 }
460 if (status == 0) {
461 fprintf(stderr, "EOF on netlink\n");
462 return -1;
463 }
464 if (msg.msg_namelen != sizeof(nladdr)) {
465 fprintf(stderr, "Sender address length == %d\n", msg.msg_namelen);
466 exit(1);
467 }
468 for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) {
469 int err;
470 int len = h->nlmsg_len;
471 int l = len - sizeof(*h);
472
473 if (l<0 || len>status) {
474 if (msg.msg_flags & MSG_TRUNC) {
475 fprintf(stderr, "Truncated message\n");
476 return -1;
477 }
478 fprintf(stderr, "!!!malformed message: len=%d\n", len);
479 exit(1);
480 }
481
482 err = handler(&nladdr, h, jarg);
483 if (err < 0)
484 return err;
485
486 status -= NLMSG_ALIGN(len);
487 h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len));
488 }
489 if (msg.msg_flags & MSG_TRUNC) {
490 fprintf(stderr, "Message truncated\n");
491 continue;
492 }
493 if (status) {
494 fprintf(stderr, "!!!Remnant of size %d\n", status);
495 exit(1);
496 }
497 }
498}
499
500int rtnl_from_file(FILE *rtnl, rtnl_filter_t handler,
501 void *jarg)
502{
503 int status;
504 struct sockaddr_nl nladdr;
505 char buf[8192];
506 struct nlmsghdr *h = (void*)buf;
507
508 memset(&nladdr, 0, sizeof(nladdr));
509 nladdr.nl_family = AF_NETLINK;
510 nladdr.nl_pid = 0;
511 nladdr.nl_groups = 0;
512
513 while (1) {
514 int err, len;
515 int l;
516
517 status = fread(&buf, 1, sizeof(*h), rtnl);
518
519 if (status < 0) {
520 if (errno == EINTR)
521 continue;
522 perror("rtnl_from_file: fread");
523 return -1;
524 }
525 if (status == 0)
526 return 0;
527
528 len = h->nlmsg_len;
529 l = len - sizeof(*h);
530
531 if (l<0 || len>sizeof(buf)) {
532 fprintf(stderr, "!!!malformed message: len=%d @%lu\n",
533 len, ftell(rtnl));
534 return -1;
535 }
536
537 status = fread(NLMSG_DATA(h), 1, NLMSG_ALIGN(l), rtnl);
538
539 if (status < 0) {
540 perror("rtnl_from_file: fread");
541 return -1;
542 }
543 if (status < l) {
544 fprintf(stderr, "rtnl-from_file: truncated message\n");
545 return -1;
546 }
547
548 err = handler(&nladdr, h, jarg);
549 if (err < 0)
550 return err;
551 }
552}
553
554int addattr(struct nlmsghdr *n, int maxlen, int type)
555{
556 return addattr_l(n, maxlen, type, NULL, 0);
557}
558
559int addattr8(struct nlmsghdr *n, int maxlen, int type, __u8 data)
560{
561 return addattr_l(n, maxlen, type, &data, sizeof(__u8));
562}
563
564int addattr16(struct nlmsghdr *n, int maxlen, int type, __u16 data)
565{
566 return addattr_l(n, maxlen, type, &data, sizeof(__u16));
567}
568
569int addattr32(struct nlmsghdr *n, int maxlen, int type, __u32 data)
570{
571 return addattr_l(n, maxlen, type, &data, sizeof(__u32));
572}
573
574int addattr64(struct nlmsghdr *n, int maxlen, int type, __u64 data)
575{
576 return addattr_l(n, maxlen, type, &data, sizeof(__u64));
577}
578
579int addattrstrz(struct nlmsghdr *n, int maxlen, int type, const char *str)
580{
581 return addattr_l(n, maxlen, type, str, strlen(str)+1);
582}
583
584
585
586int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
587 int alen)
588{
589
590#if 0
591printf("%d: %s\n", __LINE__, __FUNCTION__);
592printf("\ttype %d - ", type);
593if (type == IFLA_LINK) {
594 printf("IFLA_LINK\n");
595 int i;
596 printf("\tdata - ");
597 for (i = 0; i < alen; i++)
598 printf("%02x, ", *((unsigned char *)data + i));
599 printf("\n");
600}
601else if (type == IFLA_IFNAME) {
602 printf("IFLA_IFNAME\n");
603 printf("\tdata - #%s#\n", data);
604}
605else if (type == IFLA_LINKINFO) printf("IFLA_LINKINFO\n");
606else if (type == IFLA_ADDRESS) {
607 printf("IFLA_ADDRESS or IFLA_INFO_KIND\n");
608 int i;
609 printf("\tdata - ");
610 for (i = 0; i < alen; i++)
611 printf("%02x, ", *((unsigned char *)data + i));
612 printf("\n");
613}
614else if (type == IFLA_BROADCAST) printf("IFLA_BROADCAST or IFLA_INFO_DATA\n");
615
616printf("\tdata length: %d\n", alen);
617#endif
618
619 int len = RTA_LENGTH(alen);
620 struct rtattr *rta;
621
622 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
623 fprintf(stderr, "addattr_l ERROR: message exceeded bound of %d\n",maxlen);
624 return -1;
625 }
626 rta = NLMSG_TAIL(n);
627 rta->rta_type = type;
628 rta->rta_len = len;
629 memcpy(RTA_DATA(rta), data, alen);
630 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
631 return 0;
632}
633
634#if 0
635int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data,
636 int alen)
637{
638printf("%s: adding type %d, length %d ", __FUNCTION__, type, alen);
639if (type == IFLA_INFO_KIND) {
640if (alen)
641 printf("(IFLA_INFO_KIND %s)\n", (char *)data);
642else
643printf("(VETH_INFO_PEER)\n");
644}
645else if (type == IFLA_IFNAME) {
646printf("(IFLA_IFNAME %s)\n", (char *) data);
647}
648else if (type == IFLA_NET_NS_PID) {
649printf("(IFLA_NET_NS_PID %u)\n", *((unsigned *) data));
650}
651else if (type == IFLA_LINKINFO)
652printf("(IFLA_LINKINFO)\n");
653else if (type == IFLA_INFO_DATA)
654printf("(IFLA_INFO_DATA)\n");
655else
656 printf("\n");
657
658 int len = RTA_LENGTH(alen);
659 struct rtattr *rta;
660
661 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) {
662 fprintf(stderr, "addattr_l ERROR: message exceeded bound of %d\n",maxlen);
663 return -1;
664 }
665 rta = NLMSG_TAIL(n);
666 rta->rta_type = type;
667 rta->rta_len = len;
668 memcpy(RTA_DATA(rta), data, alen);
669 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
670 return 0;
671}
672#endif
673
674int addraw_l(struct nlmsghdr *n, int maxlen, const void *data, int len)
675{
676 if (NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len) > maxlen) {
677 fprintf(stderr, "addraw_l ERROR: message exceeded bound of %d\n",maxlen);
678 return -1;
679 }
680
681 memcpy(NLMSG_TAIL(n), data, len);
682 memset((void *) NLMSG_TAIL(n) + len, 0, NLMSG_ALIGN(len) - len);
683 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len);
684 return 0;
685}
686
687struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
688{
689 struct rtattr *nest = NLMSG_TAIL(n);
690
691 addattr_l(n, maxlen, type, NULL, 0);
692 return nest;
693}
694
695int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
696{
697 nest->rta_len = (void *)NLMSG_TAIL(n) - (void *)nest;
698 return n->nlmsg_len;
699}
700
701struct rtattr *addattr_nest_compat(struct nlmsghdr *n, int maxlen, int type,
702 const void *data, int len)
703{
704 struct rtattr *start = NLMSG_TAIL(n);
705
706 addattr_l(n, maxlen, type, data, len);
707 addattr_nest(n, maxlen, type);
708 return start;
709}
710
711int addattr_nest_compat_end(struct nlmsghdr *n, struct rtattr *start)
712{
713 struct rtattr *nest = (void *)start + NLMSG_ALIGN(start->rta_len);
714
715 start->rta_len = (void *)NLMSG_TAIL(n) - (void *)start;
716 addattr_nest_end(n, nest);
717 return n->nlmsg_len;
718}
719
720int rta_addattr32(struct rtattr *rta, int maxlen, int type, __u32 data)
721{
722 int len = RTA_LENGTH(4);
723 struct rtattr *subrta;
724
725 if (RTA_ALIGN(rta->rta_len) + len > maxlen) {
726 fprintf(stderr,"rta_addattr32: Error! max allowed bound %d exceeded\n",maxlen);
727 return -1;
728 }
729 subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len));
730 subrta->rta_type = type;
731 subrta->rta_len = len;
732 memcpy(RTA_DATA(subrta), &data, 4);
733 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + len;
734 return 0;
735}
736
737int rta_addattr_l(struct rtattr *rta, int maxlen, int type,
738 const void *data, int alen)
739{
740 struct rtattr *subrta;
741 int len = RTA_LENGTH(alen);
742
743 if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) {
744 fprintf(stderr,"rta_addattr_l: Error! max allowed bound %d exceeded\n",maxlen);
745 return -1;
746 }
747 subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len));
748 subrta->rta_type = type;
749 subrta->rta_len = len;
750 memcpy(RTA_DATA(subrta), data, alen);
751 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
752 return 0;
753}
754
755int parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len)
756{
757 return parse_rtattr_flags(tb, max, rta, len, 0);
758}
759
760int parse_rtattr_flags(struct rtattr *tb[], int max, struct rtattr *rta,
761 int len, unsigned short flags)
762{
763 unsigned short type;
764
765 memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
766 while (RTA_OK(rta, len)) {
767 type = rta->rta_type & ~flags;
768 if ((type <= max) && (!tb[type]))
769 tb[type] = rta;
770 rta = RTA_NEXT(rta,len);
771 }
772 if (len)
773 fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len);
774 return 0;
775}
776
777int parse_rtattr_byindex(struct rtattr *tb[], int max, struct rtattr *rta, int len)
778{
779 int i = 0;
780
781 memset(tb, 0, sizeof(struct rtattr *) * max);
782 while (RTA_OK(rta, len)) {
783 if (rta->rta_type <= max && i < max)
784 tb[i++] = rta;
785 rta = RTA_NEXT(rta,len);
786 }
787 if (len)
788 fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len);
789 return i;
790}
791
792int __parse_rtattr_nested_compat(struct rtattr *tb[], int max, struct rtattr *rta,
793 int len)
794{
795 if (RTA_PAYLOAD(rta) < len)
796 return -1;
797 if (RTA_PAYLOAD(rta) >= RTA_ALIGN(len) + sizeof(struct rtattr)) {
798 rta = RTA_DATA(rta) + RTA_ALIGN(len);
799 return parse_rtattr_nested(tb, max, rta);
800 }
801 memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
802 return 0;
803}
diff --git a/src/lib/pid.c b/src/lib/pid.c
new file mode 100644
index 000000000..a0261ead2
--- /dev/null
+++ b/src/lib/pid.c
@@ -0,0 +1,392 @@
1/*
2 * Copyright (C) 2014, 2015 netblue30 (netblue30@yahoo.com)
3 *
4 * This file is part of firejail project
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19*/
20#include "../include/common.h"
21#include "../include/pid.h"
22#include <string.h>
23#include <sys/types.h>
24#include <pwd.h>
25#include <sys/ioctl.h>
26#include <dirent.h>
27
28#define PIDS_BUFLEN 4096
29//Process pids[max_pids];
30Process *pids = NULL;
31int max_pids=32769;
32#define PIDS_BUFLEN 4096
33
34// get the memory associated with this pid
35void pid_getmem(unsigned pid, unsigned *rss, unsigned *shared) {
36 // open stat file
37 char *file;
38 if (asprintf(&file, "/proc/%u/statm", pid) == -1) {
39 perror("asprintf");
40 exit(1);
41 }
42 FILE *fp = fopen(file, "r");
43 if (!fp) {
44 free(file);
45 return;
46 }
47 free(file);
48
49 unsigned a, b, c;
50 if (3 != fscanf(fp, "%u %u %u", &a, &b, &c)) {
51 fclose(fp);
52 return;
53 }
54 *rss += b;
55 *shared += c;
56 fclose(fp);
57}
58
59
60void pid_get_cpu_time(unsigned pid, unsigned *utime, unsigned *stime) {
61 // open stat file
62 char *file;
63 if (asprintf(&file, "/proc/%u/stat", pid) == -1) {
64 perror("asprintf");
65 exit(1);
66 }
67 FILE *fp = fopen(file, "r");
68 if (!fp) {
69 free(file);
70 return;
71 }
72 free(file);
73
74 char line[PIDS_BUFLEN];
75 if (fgets(line, PIDS_BUFLEN - 1, fp)) {
76 char *ptr = line;
77 // jump 13 fields
78 int i;
79 for (i = 0; i < 13; i++) {
80 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
81 ptr++;
82 if (*ptr == '\0')
83 goto myexit;
84 ptr++;
85 }
86 if (2 != sscanf(ptr, "%u %u", utime, stime))
87 goto myexit;
88 }
89
90myexit:
91 fclose(fp);
92}
93
94unsigned long long pid_get_start_time(unsigned pid) {
95 // open stat file
96 char *file;
97 if (asprintf(&file, "/proc/%u/stat", pid) == -1) {
98 perror("asprintf");
99 exit(1);
100 }
101 FILE *fp = fopen(file, "r");
102 if (!fp) {
103 free(file);
104 return 0;
105 }
106 free(file);
107
108 char line[PIDS_BUFLEN];
109 unsigned long long retval = 0;
110 if (fgets(line, PIDS_BUFLEN - 1, fp)) {
111 char *ptr = line;
112 // jump 21 fields
113 int i;
114 for (i = 0; i < 21; i++) {
115 while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0')
116 ptr++;
117 if (*ptr == '\0')
118 goto myexit;
119 ptr++;
120 }
121 if (1 != sscanf(ptr, "%llu", &retval))
122 goto myexit;
123 }
124
125myexit:
126 fclose(fp);
127 return retval;
128}
129
130char *pid_get_user_name(uid_t uid) {
131 struct passwd *pw = getpwuid(uid);
132 if (pw)
133 return strdup(pw->pw_name);
134 return NULL;
135}
136
137uid_t pid_get_uid(pid_t pid) {
138 uid_t rv = 0;
139
140 // open stat file
141 char *file;
142 if (asprintf(&file, "/proc/%u/status", pid) == -1) {
143 perror("asprintf");
144 exit(1);
145 }
146 FILE *fp = fopen(file, "r");
147 if (!fp) {
148 free(file);
149 return 0;
150 }
151
152 // look for firejail executable name
153 char buf[PIDS_BUFLEN];
154 while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
155 if (strncmp(buf, "Uid:", 4) == 0) {
156 char *ptr = buf + 5;
157 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
158 ptr++;
159 }
160 if (*ptr == '\0')
161 goto doexit;
162
163 rv = atoi(ptr);
164 break; // break regardless!
165 }
166 }
167doexit:
168 fclose(fp);
169 free(file);
170 return rv;
171}
172
173static void print_elem(unsigned index, int nowrap) {
174 // get terminal size
175 struct winsize sz;
176 int col = 0;
177 if (isatty(STDIN_FILENO)) {
178 if (!ioctl(0, TIOCGWINSZ, &sz))
179 col = sz.ws_col;
180 }
181
182 // indent
183 char indent[(pids[index].level - 1) * 2 + 1];
184 memset(indent, ' ', sizeof(indent));
185 indent[(pids[index].level - 1) * 2] = '\0';
186
187 // get data
188 uid_t uid = pids[index].uid;
189 char *cmd = pid_proc_cmdline(index);
190 char *user = pid_get_user_name(uid);
191 char *allocated = user;
192 if (user ==NULL)
193 user = "";
194 if (cmd) {
195 if (col < 4 || nowrap)
196 printf("%s%u:%s:%s\n", indent, index, user, cmd);
197 else {
198 char *out;
199 if (asprintf(&out, "%s%u:%s:%s\n", indent, index, user, cmd) == -1)
200 errExit("asprintf");
201 int len = strlen(out);
202 if (len > col) {
203 out[col] = '\0';
204 out[col - 1] = '\n';
205 }
206 printf("%s", out);
207 free(out);
208 }
209
210 free(cmd);
211 }
212 else {
213 if (pids[index].zombie)
214 printf("%s%u: (zombie)\n", indent, index);
215 else
216 printf("%s%u:\n", indent, index);
217 }
218 if (allocated)
219 free(allocated);
220}
221
222// recursivity!!!
223void pid_print_tree(unsigned index, unsigned parent, int nowrap) {
224 print_elem(index, nowrap);
225
226 int i;
227 for (i = index + 1; i < max_pids; i++) {
228 if (pids[i].parent == index)
229 pid_print_tree(i, index, nowrap);
230 }
231
232 for (i = 0; i < index; i++) {
233 if (pids[i].parent == index)
234 pid_print_tree(i, index, nowrap);
235 }
236}
237
238void pid_print_list(unsigned index, int nowrap) {
239 print_elem(index, nowrap);
240}
241
242// recursivity!!!
243void pid_store_cpu(unsigned index, unsigned parent, unsigned *utime, unsigned *stime) {
244 if (pids[index].level == 1) {
245 *utime = 0;
246 *stime = 0;
247 }
248
249 unsigned utmp = 0;
250 unsigned stmp = 0;
251 pid_get_cpu_time(index, &utmp, &stmp);
252 *utime += utmp;
253 *stime += stmp;
254
255 int i;
256 for (i = index + 1; i < max_pids; i++) {
257 if (pids[i].parent == index)
258 pid_store_cpu(i, index, utime, stime);
259 }
260
261 if (pids[index].level == 1) {
262 pids[index].utime = *utime;
263 pids[index].stime = *stime;
264 }
265}
266
267// mon_pid: pid of sandbox to be monitored, 0 if all sandboxes are included
268void pid_read(pid_t mon_pid) {
269 if (pids == NULL) {
270 FILE *fp = fopen("/proc/sys/kernel/pid_max", "r");
271 if (fp) {
272 int val;
273 if (fscanf(fp, "%d", &val) == 1) {
274 if (val >= max_pids)
275 max_pids = val + 1;
276 }
277 fclose(fp);
278 }
279 pids = malloc(sizeof(Process) * max_pids);
280 if (pids == NULL)
281 errExit("malloc");
282 }
283 memset(pids, 0, sizeof(Process) * max_pids);
284 pid_t mypid = getpid();
285
286 DIR *dir;
287 if (!(dir = opendir("/proc"))) {
288 // sleep 2 seconds and try again
289 sleep(2);
290 if (!(dir = opendir("/proc"))) {
291 fprintf(stderr, "Error: cannot open /proc directory\n");
292 exit(1);
293 }
294 }
295
296 pid_t child = -1;
297 struct dirent *entry;
298 char *end;
299 while (child < 0 && (entry = readdir(dir))) {
300 pid_t pid = strtol(entry->d_name, &end, 10);
301 pid %= max_pids;
302 if (end == entry->d_name || *end)
303 continue;
304 if (pid == mypid)
305 continue;
306
307 // open stat file
308 char *file;
309 if (asprintf(&file, "/proc/%u/status", pid) == -1) {
310 perror("asprintf");
311 exit(1);
312 }
313 FILE *fp = fopen(file, "r");
314 if (!fp) {
315 free(file);
316 continue;
317 }
318
319 // look for firejail executable name
320 char buf[PIDS_BUFLEN];
321 while (fgets(buf, PIDS_BUFLEN - 1, fp)) {
322 if (strncmp(buf, "Name:", 5) == 0) {
323 char *ptr = buf + 5;
324 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
325 ptr++;
326 }
327 if (*ptr == '\0') {
328 fprintf(stderr, "Error: cannot read /proc file\n");
329 exit(1);
330 }
331
332 if (mon_pid == 0 && strncmp(ptr, "firejail", 8) == 0) {
333 pids[pid].level = 1;
334 }
335 else if (mon_pid == pid && strncmp(ptr, "firejail", 8) == 0) {
336 pids[pid].level = 1;
337 }
338// else if (mon_pid == 0 && strncmp(ptr, "lxc-execute", 11) == 0) {
339// pids[pid].level = 1;
340// }
341// else if (mon_pid == pid && strncmp(ptr, "lxc-execute", 11) == 0) {
342// pids[pid].level = 1;
343// }
344 else
345 pids[pid].level = -1;
346 }
347 if (strncmp(buf, "State:", 6) == 0) {
348 if (strstr(buf, "(zombie)"))
349 pids[pid].zombie = 1;
350 }
351 else if (strncmp(buf, "PPid:", 5) == 0) {
352 char *ptr = buf + 5;
353 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
354 ptr++;
355 }
356 if (*ptr == '\0') {
357 fprintf(stderr, "Error: cannot read /proc file\n");
358 exit(1);
359 }
360 unsigned parent = atoi(ptr);
361 parent %= max_pids;
362 if (pids[parent].level > 0) {
363 pids[pid].level = pids[parent].level + 1;
364 }
365 pids[pid].parent = parent;
366 }
367 else if (strncmp(buf, "Uid:", 4) == 0) {
368 char *ptr = buf + 5;
369 while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t')) {
370 ptr++;
371 }
372 if (*ptr == '\0') {
373 fprintf(stderr, "Error: cannot read /proc file\n");
374 exit(1);
375 }
376 pids[pid].uid = atoi(ptr);
377 break;
378 }
379 }
380 fclose(fp);
381 free(file);
382 }
383 closedir(dir);
384
385 pid_t pid;
386 for (pid = 0; pid < max_pids; pid++) {
387 int parent = pids[pid].parent;
388 if (pids[parent].level > 0) {
389 pids[pid].level = pids[parent].level + 1;
390 }
391 }
392}