Skip to content

eBPF-based security platform

harden: point closed standard descriptors at /dev/null at startup

Daniel Borkmann1f839d8a0efa
diff --git a/Makefile.shirudo b/Makefile.shirudo
index cc77d6c4..470c7154 100644
--- a/Makefile.shirudo
+++ b/Makefile.shirudo
@@ -399,7 +399,7 @@ tools/shirudo-build/shirudo-build: $(BUILD_OBJS) util/sign.o \
util/io.o util/malloc.o util/paths.o \
util/upatch.o util/timefmt.o \
util/elf_target.o util/hex.o util/keys.o \
- util/seal.o \
+ util/seal.o util/harden.o \
util/crypto_openssl.o util/tls_openssl.o \
util/bpm_oci.o util/bpm_package.o \
util/bpm_tree.o $(VERSION_OBJ) \
diff --git a/shirudo.c b/shirudo.c
index cdb55aa0..80a4be4f 100644
--- a/shirudo.c
+++ b/shirudo.c
@@ -106,6 +106,7 @@ int main(int argc, const char **argv)
size_t matches[ARRAY_SIZE(commands)];
size_t i, n_match;
+ shirudo_harden_stdio();
shirudo_log_init();
shirudo_harden_self();
diff --git a/tools/shirudo-build/shirudo-build.c b/tools/shirudo-build/shirudo-build.c
index 62e13010..ec8bf615 100644
--- a/tools/shirudo-build/shirudo-build.c
+++ b/tools/shirudo-build/shirudo-build.c
@@ -19,6 +19,7 @@
#include "bpm.h"
#include "compile.h"
+#include "harden.h"
#include "log.h"
#include "hex.h"
#include "malloc.h"
@@ -234,6 +235,7 @@ int main(int argc, char **argv)
int rc;
int i;
+ shirudo_harden_stdio();
shirudo_log_init();
if (argc >= 2 && strcmp(argv[1], "bpm") == 0)
diff --git a/util/harden.c b/util/harden.c
index 192879d8..e2c7a76b 100644
--- a/util/harden.c
+++ b/util/harden.c
@@ -6,11 +6,32 @@
* sensitive buffers.
*/
+#include <errno.h>
+#include <fcntl.h>
#include <sys/prctl.h>
#include <sys/resource.h>
+#include <unistd.h>
#include "harden.h"
+/*
+ * Started with standard input, output or error closed, the process gives
+ * that number to the next file it opens, and what it prints lands in
+ * that file: point each closed one at /dev/null before anything opens.
+ */
+void shirudo_harden_stdio(void)
+{
+ int fd;
+
+ for (fd = STDIN_FILENO; fd <= STDERR_FILENO; fd++) {
+ if (fcntl(fd, F_GETFD) != -1 || errno != EBADF)
+ continue;
+ /* The ones below fd are open, so fd is the lowest free. */
+ if (open("/dev/null", O_RDWR) != fd)
+ _exit(1);
+ }
+}
+
void shirudo_harden_self(void)
{
struct rlimit no_core = { 0, 0 };
diff --git a/util/harden.h b/util/harden.h
index 354967e2..860949f5 100644
--- a/util/harden.h
+++ b/util/harden.h
@@ -10,6 +10,7 @@
#include <stddef.h>
+void shirudo_harden_stdio(void);
void shirudo_harden_self(void);
#endif /* SHIRUDO_HARDEN_H */