Skip to content

Commit 122d423

Browse files
committed
look(1): Capsicumise
Signed-off-by: Faraz Vahedi <kfv@kfv.io>
1 parent ce5b536 commit 122d423

File tree

1 file changed

+28
-7
lines changed

1 file changed

+28
-7
lines changed

usr.bin/look/look.c

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@
4141
*/
4242

4343
#include <sys/types.h>
44+
#include <sys/capsicum.h>
4445
#include <sys/mman.h>
4546
#include <sys/stat.h>
4647

48+
#include <capsicum_helpers.h>
4749
#include <err.h>
4850
#include <errno.h>
4951
#include <fcntl.h>
@@ -89,8 +91,11 @@ int
8991
main(int argc, char *argv[])
9092
{
9193
struct stat sb;
92-
int ch, fd, match;
94+
int ch, match;
95+
size_t nfiles;
9396
wchar_t termchar;
97+
cap_rights_t rights;
98+
int *fds;
9499
unsigned char *back, *front;
95100
unsigned const char *file;
96101
wchar_t *key;
@@ -132,22 +137,38 @@ main(int argc, char *argv[])
132137

133138
match = 1;
134139

135-
do {
136-
if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
140+
cap_rights_init(&rights, CAP_MMAP_R, CAP_READ, CAP_FSTAT);
141+
nfiles = argc > 1 ? argc - 1 : argc;
142+
if ((fds = malloc(nfiles * sizeof(int))) == NULL)
143+
err(2, NULL);
144+
for (size_t idx = 0; idx < nfiles; file = argv[idx++]) {
145+
if ((fds[idx] = open(file, O_RDONLY, 0)) < 0)
146+
continue;
147+
if (caph_rights_limit(fds[idx], &rights) != 0)
148+
err(2, "unable to limit rights for %s", file);
149+
}
150+
151+
caph_cache_catpages();
152+
if (caph_enter() != 0)
153+
err(EXIT_FAILURE, "failed to enter capability mode");
154+
155+
for (size_t idx = 0; idx < nfiles; file = argv[idx++]) {
156+
if (fstat(fds[idx], &sb))
137157
err(2, "%s", file);
138158
if ((uintmax_t)sb.st_size > (uintmax_t)SIZE_T_MAX)
139159
errx(2, "%s: %s", file, strerror(EFBIG));
140160
if (sb.st_size == 0) {
141-
close(fd);
161+
close(fds[idx]);
142162
continue;
143163
}
144-
if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
164+
if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fds[idx], (off_t)0)) == MAP_FAILED)
145165
err(2, "%s", file);
146166
back = front + sb.st_size;
147167
match *= (look(key, front, back));
148-
close(fd);
149-
} while (argc-- > 2 && (file = *argv++));
168+
close(fds[idx]);
169+
}
150170

171+
free(fds);
151172
exit(match);
152173
}
153174

0 commit comments

Comments
 (0)