path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
pledge/LICENSE | ISC License
Copyright 2020 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
| 759 | 17 | jart/plegde | false |
pledge/.gitignore | # -*- conf -*-
/o
# TODO: Find some way to have Python write to o/
__pycache__
*.tmp
/.bochs.log
/HTAGS
/TAGS
/bx_enh_dbg.ini
/tool/emacs/*.elc
/perf.data
/perf.data.old
| 173 | 16 | jart/plegde | false |
pledge/Makefile | # Makefiles are prettier like this
ifeq ($(origin .RECIPEPREFIX), undefined)
$(error This Make does not support .RECIPEPREFIX. \
Please use GNU Make 3.82 or later)
endif
.RECIPEPREFIX = >
# Use bash as the shell
SHELL := bash
# ...And use strict flags with it to make sure things fail if a step in there
# fails
.SHELLFLAGS := -eu -o pipefail -c
# Delete the target file of a Make rule if it fails - this guards against
# broken files
.DELETE_ON_ERROR:
# --no-builtin-rules: I'd rather make my own rules myself, make, thanks :)
MAKEFLAGS += --no-builtin-rules
# We use `override` to enable setting part of CFLAGS on the command line
# This makes the compiler generate dependency files, which will solve any
# header-related dependency problems we could have had
override CFLAGS += -MMD -MP -MF [email protected]
# Make it simpler to include library include files
override CFLAGS += -I.
# We need functions provided by defining _GNU_SOURCE
override CFLAGS += -D_GNU_SOURCE
# We need to compile as PIC code since we're making shared libraries here
override CFLAGS += -fPIC
# LDFLAGS should contain CFLAGS (seperate so command-line can add to it, and
# to correspond to usual practice)
override LDFLAGS += $(CFLAGS)
OUTPUT_FOLDER = o/$(MODE)
.PHONY: all clean
all: $(OUTPUT_FOLDER)/pledge $(OUTPUT_FOLDER)/sandbox.so
# Note: we cannot merge the source file list for pledge and the sandbox as this may otherwise result in constructors calling forbidden syscalls in the sandbox
PLEDGE_SOURCE_FILES := cmd/pledge
PLEDGE_SOURCE_FILES += libc/calls/commandv libc/calls/getcpucount libc/calls/islinux
PLEDGE_SOURCE_FILES += libc/calls/landlock_add_rule libc/calls/landlock_create_ruleset
PLEDGE_SOURCE_FILES += libc/calls/landlock_restrict_self libc/calls/parsepromises
PLEDGE_SOURCE_FILES += libc/calls/pledge libc/calls/pledge-linux libc/calls/unveil
PLEDGE_SOURCE_FILES += libc/x/xdie libc/x/xjoinpaths libc/x/xmalloc libc/x/xrealloc
PLEDGE_SOURCE_FILES += libc/x/xstrcat libc/x/xstrdup
PLEDGE_SOURCE_FILES += libc/elf/checkelfaddress libc/elf/getelfsegmentheaderaddress
PLEDGE_SOURCE_FILES += libc/str/classifypath libc/str/endswith libc/str/isabspath
PLEDGE_SOURCE_FILES += libc/intrin/promises libc/intrin/pthread_setcancelstate
PLEDGE_SOURCE_FILES += libc/fmt/joinpaths libc/fmt/sizetol
PLEDGE_SOURCE_FILES += libc/runtime/isdynamicexecutable
PLEDGE_SOURCE_FILES += libc/sysv/calls/ioprio_set
SANDBOX_SOURCE_FILES := cmd/sandbox
SANDBOX_SOURCE_FILES += libc/calls/pledge-linux
SANDBOX_OBJECT_FILES := $(addprefix $(OUTPUT_FOLDER)/, $(addsuffix .o, $(SANDBOX_SOURCE_FILES)))
PLEDGE_OBJECT_FILES := $(addprefix $(OUTPUT_FOLDER)/, $(addsuffix .o, $(PLEDGE_SOURCE_FILES)))
# First we need to have a shared object for the sandbox
$(OUTPUT_FOLDER)/sandbox.so: $(SANDBOX_OBJECT_FILES)
> $(CC) $(LDFLAGS) -shared -o $@ $^
# Next we need to make an object file out of that shared object containing the shared object as a symbol
$(OUTPUT_FOLDER)/embedded-sandbox.o: $(OUTPUT_FOLDER)/sandbox.so
> ld -r -b binary -o $@ $^
# Finally we need to embed the sandbox into our executable so it can copy it out when needed
$(OUTPUT_FOLDER)/pledge: $(PLEDGE_OBJECT_FILES) $(OUTPUT_FOLDER)/embedded-sandbox.o
> $(CC) $(LDFLAGS) -o $@ $^
$(OUTPUT_FOLDER)/%.o: %.c
> @mkdir --parents $(OUTPUT_FOLDER)/cmd
> @mkdir --parents $(OUTPUT_FOLDER)/libc/calls
> @mkdir --parents $(OUTPUT_FOLDER)/libc/sysv/calls
> @mkdir --parents $(OUTPUT_FOLDER)/libc/str
> @mkdir --parents $(OUTPUT_FOLDER)/libc/mem
> @mkdir --parents $(OUTPUT_FOLDER)/libc/fmt
> @mkdir --parents $(OUTPUT_FOLDER)/libc/intrin
> @mkdir --parents $(OUTPUT_FOLDER)/libc/x
> @mkdir --parents $(OUTPUT_FOLDER)/libc/runtime
> @mkdir --parents $(OUTPUT_FOLDER)/libc/elf
> $(CC) -c $< -o $@ $(CFLAGS)
# Include dependencies for the object files
include $(shell [ -d $(OUTPUT_FOLDER)/obj ] && find $(OUTPUT_FOLDER)/ -type f -name '*.d')
# Remove all object, binary and other produced files
clean:
> rm -rf ./o/
| 3,966 | 108 | jart/plegde | false |
pledge/.clang-format | ---
BasedOnStyle: Google
StatementMacros:
- INITIALIZER
AlignConsecutiveMacros: true
AlignConsecutiveDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
AllowShortFunctionsOnASingleLine: false
KeepEmptyLinesAtTheStartOfBlocks: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
IncludeBlocks: Merge
---
Language: Cpp
AllowShortFunctionsOnASingleLine: false
---
Language: Proto
...
| 399 | 18 | jart/plegde | false |
pledge/README.md | # pledge for linux
OpenBSD is an operating system that's famous for its focus on security.
Unfortunately, OpenBSD leader Theo states that there are only 7000 users
of OpenBSD. So it's a very small but elite group, that wields a
disproportionate influence; since we hear all the time about the awesome
security features these guys get to use, even though we usually can't
use them ourselves, *until now*.
Pledge was like the forbidden fruit we'd all covet when the boss says we
must use things like Linux. Why does it matter? It's because pledge()
actually makes security comprehensible. Linux has never really had a
security layer that mere mortals can understand. For example, let's say
you want to do something on Linux like control whether or not some
program you downloaded from the web is allowed to have telemetry. You'd
need to write stuff like this:
```c
static const struct sock_filter kFilter[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, syscall, 0, 14 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 4 - 3, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 10, 0, 13 - 4),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~0x80800),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 1, 8 - 7, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 13 - 8),
/* L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 12 - 10, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 6, 12 - 11, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 17, 0, 13 - 11),
/*L12*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L13*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L14*/ /* next filter */
};
```
Oh my gosh. It's like we traded one form of security privilege for
another. OpenBSD limits security to a small pond, but makes it easy.
Linux is a big tent, but makes it impossibly hard. SECCOMP BPF might as
well be the Traditional Chinese of programming languages, since only a
small number of people who've devoted the oodles of time it takes to
understand code like what you see above have actually been able to
benefit from it. But if you've got OpenBSD privilege, then doing the
same thing becomes easy:
```c
pledge("stdio rpath", 0);
```
That's really all OpenBSD users have to do to prevent things like leaks
of confidential information. So how do we get it that simple on Linux?
The answer is to find someone with enough free time to figure out how to
use SECCOMP BPF to implement pledge. The latest volunteers are us, so
look upon our code ye mighty and despair.
| 2,697 | 56 | jart/plegde | false |
pledge/libc/macros.internal.h | #ifndef PLEDGE_LIBC_MACROS_INTERNAL_H_
#define PLEDGE_LIBC_MACROS_INTERNAL_H_
#define ROUNDUP(X, K) (((X) + (K)-1) & -(K))
#define ARRAYLEN(A) \
((sizeof(A) / sizeof(*(A))) / ((unsigned)!(sizeof(A) % sizeof(*(A)))))
#endif
| 227 | 9 | jart/plegde | false |
pledge/libc/dce.h | #ifndef PLEDGE_LIBC_DCE_H_
#define PLEDGE_LIBC_DCE_H_
#ifndef __linux__
#error "This program is extremely likely to only work properly on Linux !"
#endif
#define IsLinux() 1
#define IsWindows() 0
#define IsOpenbsd() 0
#endif
| 228 | 13 | jart/plegde | false |
pledge/libc/x/xdie.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <stdlib.h>
#include "libc/x/x.h"
void xdie(void) {
abort();
}
| 1,910 | 25 | jart/plegde | false |
pledge/libc/x/xstrcat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Concatenates strings / chars to newly allocated memory, e.g.
*
* xstrcat("hi", ' ', "there")
*
* Or without the C99 helper macro:
*
* (xstrcat)("hi", ' ', "there", NULL)
*
* This goes twice as fast as the more powerful xasprintf(). It's not
* quadratic like strcat(). It's much slower than high-effort stpcpy(),
* particularly with string literals.
*
* @see gc()
*/
char *(xstrcat)(const char *s, ...) {
va_list va;
intptr_t q;
char *p, b[2];
size_t n, m, c;
n = 0;
c = 32;
p = xmalloc(c);
va_start(va, s);
do {
q = (intptr_t)s;
if (q > 0 && q <= 255) {
b[0] = q;
b[1] = '\0';
s = b;
m = 1;
} else {
m = strlen(s);
}
if (n + m + 1 > c) {
do {
c += c >> 1;
} while (n + m + 1 > c);
p = xrealloc(p, c);
}
memcpy(p + n, s, m + 1);
n += m;
} while ((s = va_arg(va, const char *)));
va_end(va);
return p;
}
| 2,827 | 68 | jart/plegde | false |
pledge/libc/x/xmalloc.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/x/x.h"
/**
* Allocates uninitialized memory, or dies.
*/
void *xmalloc(size_t bytes) {
void *res = malloc(bytes);
if (!res) xdie();
return res;
}
| 2,006 | 29 | jart/plegde | false |
pledge/libc/x/xstrdup.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/likely.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Allocates new copy of string, or dies.
*/
char *xstrdup(const char *s) {
size_t len = strlen(s);
char *s2 = malloc(len + 1);
if (UNLIKELY(!s2)) xdie();
return memcpy(s2, s, len + 1);
}
| 2,118 | 32 | jart/plegde | false |
pledge/libc/x/xjoinpaths.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/safemacros.internal.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
#include "libc/x/x.h"
/**
* Joins paths, e.g.
*
* "a" + "b" â "a/b"
* "a/" + "b" â "a/b"
* "a" + "b/" â "a/b/"
* "a" + "/b" â "/b"
* "." + "b" â "b"
* "" + "b" â "b"
*
* @return newly allocated string of resulting path
*/
char *xjoinpaths(const char *path, const char *other) {
if (!*other) {
return xstrdup(path);
} else if (!*path) {
return xstrdup(other);
} else if (isabspath(other) || !strcmp(path, ".")) {
return xstrdup(other);
} else if (endswith(path, "/")) {
return xstrcat(path, other);
} else {
return xstrcat(path, (uintptr_t)'/', other);
}
}
| 2,580 | 49 | jart/plegde | false |
pledge/libc/x/xrealloc.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/x/x.h"
/**
* Allocates/expands/shrinks/frees memory, or die.
*
* This API enables you to do the following:
*
* p = xrealloc(p, n)
*
* The standard behaviors for realloc() still apply:
*
* - `!p` means xmalloc (returns non-NULL)
* - `p && n` means resize (returns non-NULL)
* - `p && !n` means free (returns NULL)
*
* The complexity of resizing is guaranteed to be amortized.
*/
void *xrealloc(void *p, size_t n) {
void *q;
q = realloc(p, n);
if (!q && !(p && !n)) xdie();
return q;
}
| 2,362 | 42 | jart/plegde | false |
pledge/libc/x/x.h | #ifndef PLEDGE_LIBC_X_X_H_
#define PLEDGE_LIBC_X_X_H_
#include "libc/integral/c.h"
_Noreturn void xdie(void);
void *xmalloc(size_t);
void *xrealloc(void *, size_t);
char *xstrdup(const char *);
char *xstrcat(const char *, ...);
#define xstrcat(...) (xstrcat)(__VA_ARGS__, NULL)
char *xjoinpaths(const char *, const char *);
#endif
| 334 | 15 | jart/plegde | false |
pledge/libc/fmt/conv.h | #ifndef PLEDGE_LIBC_SIZETOL_H_
#define PLEDGE_LIBC_SIZETOL_H_
#include "libc/integral/c.h"
long sizetol(const char *, long) paramsnonnull() libcesque;
#endif
| 161 | 9 | jart/plegde | false |
pledge/libc/fmt/sizetol.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/conv.h"
// #include "libc/fmt/fmt.h"
#include "libc/str/str.h"
// #include "libc/sysv/errfuns.h"
#include <errno.h>
static int GetExponent(int c) {
switch (c) {
case '\0':
case ' ':
case '\t':
return 0;
case 'k':
case 'K':
return 1;
case 'm':
case 'M':
return 2;
case 'g':
case 'G':
return 3;
case 't':
case 'T':
return 4;
case 'p':
case 'P':
return 5;
case 'e':
case 'E':
return 6;
default:
return -1;
}
}
/**
* Converts size string to long.
*
* The following unit suffixes may be used
*
* - `k` or `K` for kilo (multiply by ð¹)
* - `m` or `M` for mega (multiply by ð²)
* - `g` or `G` for giga (multiply by ð³)
* - `t` or `T` for tera (multiply by ðâ´)
* - `p` or `P` for peta (multiply by ðâµ)
* - `e` or `E` for exa (multiply by ðâ¶)
*
* If a permitted alpha character is supplied, then any additional
* characters after it (e.g. kbit, Mibit, TiB) are ignored. Spaces
* before the integer are ignored, and overflows will be detected.
*
* Negative numbers are permissible, as well as a leading `+` sign. To
* tell the difference between an error return and `-1` you must clear
* `errno` before calling and test whether it changed.
*
* @param s is non-null nul-terminated input string
* @param b is multiplier which should be 1000 or 1024
* @return size greater than or equal 0 or -1 on error
* @error EINVAL if error is due to bad syntax
* @error EOVERFLOW if error is due to overflow
*/
long sizetol(const char *s, long b) {
long x;
int c, e, d;
do {
c = *s++;
} while (c == ' ' || c == '\t');
d = c == '-' ? -1 : 1;
if (c == '-' || c == '+') c = *s++;
if (!isdigit(c)) {
errno = EINVAL;
return -1;
}
x = 0;
do {
if (__builtin_mul_overflow(x, 10, &x) ||
__builtin_add_overflow(x, (c - '0') * d, &x)) {
errno = EOVERFLOW;
return -1;
}
} while (isdigit((c = *s++)));
if ((e = GetExponent(c)) == -1) {
errno = EINVAL;
return -1;
}
while (e--) {
if (__builtin_mul_overflow(x, b, &x)) {
errno = EOVERFLOW;
return -1;
}
}
return x;
}
| 4,055 | 113 | jart/plegde | false |
pledge/libc/fmt/joinpaths.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bits.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
// #include "libc/sysv/errfuns.h"
/**
* Joins paths, e.g.
*
* 0 + 0 â 0
* "" + "" â ""
* "a" + 0 â "a"
* "a" + "" â "a/"
* 0 + "b" â "b"
* "" + "b" â "b"
* "." + "b" â "./b"
* "b" + "." â "b/."
* "a" + "b" â "a/b"
* "a/" + "b" â "a/b"
* "a" + "b/" â "a/b/"
* "a" + "/b" â "/b"
*
* @return joined path, which may be `buf`, `path`, or `other`, or null
* if (1) `buf` didn't have enough space, or (2) both `path` and
* `other` were null
*/
char *joinpaths(char *buf, size_t size, const char *path, const char *other) {
size_t pathlen, otherlen;
if (!other) return (char *)path;
if (!path) return (char *)other;
pathlen = strlen(path);
if (!pathlen || *other == '/') {
return (/*unconst*/ char *)other;
}
otherlen = strlen(other);
if (path[pathlen - 1] == '/') {
if (pathlen + otherlen + 1 <= size) {
memmove(buf, path, pathlen);
memmove(buf + pathlen, other, otherlen + 1);
return buf;
} else {
return 0;
}
} else {
if (pathlen + 1 + otherlen + 1 <= size) {
memmove(buf, path, pathlen);
buf[pathlen] = '/';
memmove(buf + pathlen + 1, other, otherlen + 1);
return buf;
} else {
return 0;
}
}
}
| 3,244 | 72 | jart/plegde | false |
pledge/libc/elf/getelfsegmentheaderaddress.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/elf/elf.h"
Elf64_Phdr *GetElfSegmentHeaderAddress(const Elf64_Ehdr *elf, size_t mapsize,
unsigned i) {
intptr_t addr =
((intptr_t)elf + (intptr_t)elf->e_phoff + (intptr_t)elf->e_phentsize * i);
CheckElfAddress(elf, mapsize, addr, elf->e_phentsize);
return (Elf64_Phdr *)addr;
}
| 2,181 | 28 | jart/plegde | false |
pledge/libc/elf/checkelfaddress.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/elf/elf.h"
#include "libc/runtime/runtime.h"
void CheckElfAddress(const Elf64_Ehdr *elf, size_t mapsize, intptr_t addr,
size_t addrsize) {
#if 1//!(TRUSTWORTHY + ELF_TRUSTWORTHY + 0) || ELF_UNTRUSTWORTHY + 0
if (addr < (intptr_t)elf || addr + addrsize > (intptr_t)elf + mapsize) {
/* kprintf("%p-%p falls outside interval %p-%p", // */
/* addr, addr + addrsize, // */
/* elf, (char *)elf + mapsize); // */
abort();
}
#endif
}
| 2,362 | 33 | jart/plegde | false |
pledge/libc/elf/elf.h | #ifndef PLEDGE_LIBC_ELF_ELF_H_
#define PLEDGE_LIBC_ELF_ELF_H_
#include <elf.h>
#include <stddef.h>
void CheckElfAddress(const Elf64_Ehdr *, size_t, intptr_t, size_t);
Elf64_Phdr *GetElfSegmentHeaderAddress(const Elf64_Ehdr *, size_t, unsigned);
#endif
| 255 | 11 | jart/plegde | false |
pledge/libc/calls/blockcancel.internal.h | #ifndef PLEDGE_LIBC_CALLS_BLOCKCANCEL_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_BLOCKCANCEL_INTERNAL_H_
#define ALLOW_CANCELLATIONS \
pthread_allow_cancellations(_cancelState); \
} \
while (0)
void pthread_allow_cancellations(int);
#define BLOCK_CANCELLATIONS \
do { \
int _cancelState; \
_cancelState = pthread_block_cancellations()
int pthread_block_cancellations(void);
#endif
| 483 | 19 | jart/plegde | false |
pledge/libc/calls/getcpucount.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <sched.h>
#include "libc/calls/calls.h"
#include "libc/runtime/runtime.h"
static unsigned _getcpucount_linux(void) {
cpu_set_t s = {0};
if (sched_getaffinity(0, sizeof(s), &s) != -1) {
return CPU_COUNT(&s);
} else {
return 0;
}
}
static unsigned _getcpucount_impl(void) {
return _getcpucount_linux();
}
static int g_cpucount;
// precompute because process affinity on linux may change later
__attribute__((__constructor__)) static void _getcpucount_init(void) {
g_cpucount = _getcpucount_impl();
}
/**
* Returns number of CPUs in system.
*
* This is the same as the standard interface:
*
* sysconf(_SC_NPROCESSORS_ONLN);
*
* Except this function isn't a bloated diamond dependency.
*
* On Intel systems with HyperThreading this will return the number of
* cores multiplied by two.
*
* @return cpu count or 0 if it couldn't be determined
*/
unsigned getcpucount(void) {
return g_cpucount;
}
| 2,779 | 60 | jart/plegde | false |
pledge/libc/calls/islinux.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <errno.h>
#include <stdbool.h>
#include <sys/prctl.h>
#include "libc/dce.h"
#include "libc/runtime/runtime.h"
privileged bool is_linux_2_6_23(void) {
return prctl(PR_GET_SECCOMP) >= 0 || errno != EINVAL;
}
| 2,054 | 28 | jart/plegde | false |
pledge/libc/calls/parsepromises.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/pledge.internal.h"
#include "libc/macros.internal.h"
#include "libc/str/str.h"
static int FindPromise(const char *name) {
int i;
for (i = 0; i < ARRAYLEN(kPledge); ++i) {
if (!strcasecmp(name, kPledge[i].name)) {
return i;
}
}
return -1;
}
/**
* Parses the arguments to pledge() into a bitmask.
*
* @return 0 on success, or -1 if invalid
*/
int ParsePromises(const char *promises, unsigned long *out) {
int rc = 0;
int promise;
unsigned long ipromises;
char *tok, *state, *start, buf[256];
if (promises) {
ipromises = -1;
if (memccpy(buf, promises, 0, sizeof(buf))) {
start = buf;
while ((tok = strtok_r(start, " \t\r\n", &state))) {
if ((promise = FindPromise(tok)) != -1) {
ipromises &= ~(1ULL << promise);
} else {
rc = -1;
break;
}
start = 0;
}
} else {
rc = -1;
}
} else {
ipromises = 0;
}
if (!rc) {
*out = ipromises;
}
return rc;
}
| 2,854 | 67 | jart/plegde | false |
pledge/libc/calls/commandv.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
// #include "libc/calls/struct/stat.h"
#include "libc/dce.h"
// #include "libc/errno.h"
#include "libc/intrin/bits.h"
#include "libc/intrin/safemacros.internal.h"
// #include "libc/intrin/strace.internal.h"
// #include "libc/log/libfatal.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
/*
#include "libc/sysv/consts/ok.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/errfuns.h"
*/
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
static bool IsExePath(const char *s, size_t n) {
return n >= 4 && (READ32LE(s + n - 4) == READ32LE(".exe") ||
READ32LE(s + n - 4) == READ32LE(".EXE"));
}
static bool IsComPath(const char *s, size_t n) {
return n >= 4 && (READ32LE(s + n - 4) == READ32LE(".com") ||
READ32LE(s + n - 4) == READ32LE(".COM"));
}
static bool IsComDbgPath(const char *s, size_t n) {
return n >= 8 && (READ64LE(s + n - 8) == READ64LE(".com.dbg") ||
READ64LE(s + n - 8) == READ64LE(".COM.DBG"));
}
static bool AccessCommand(const char *name, char *path, size_t pathsz,
size_t namelen, int *err, const char *suffix,
size_t pathlen) {
size_t suffixlen;
suffixlen = strlen(suffix);
if (IsWindows() && suffixlen == 0 && !IsExePath(name, namelen) &&
!IsComPath(name, namelen))
return false;
if (pathlen + 1 + namelen + suffixlen + 1 > pathsz) return false;
if (pathlen && (path[pathlen - 1] != '/' && path[pathlen - 1] != '\\')) {
path[pathlen] = !IsWindows() ? '/'
: memchr(path, '\\', pathlen) ? '\\'
: '/';
pathlen++;
}
memcpy(path + pathlen, name, namelen);
memcpy(path + pathlen + namelen, suffix, suffixlen + 1);
if (!access(path, X_OK)) {
struct stat st;
if (!stat(path, &st)) {
if (S_ISREG(st.st_mode)) {
return true;
} else {
errno = EACCES;
}
}
}
if (errno == EACCES || *err != EACCES) *err = errno;
return false;
}
static bool SearchPath(const char *name, char *path, size_t pathsz,
size_t namelen, int *err, const char *suffix) {
char sep;
size_t i;
const char *p;
if (!(p = getenv("PATH"))) p = "/bin:/usr/local/bin:/usr/bin";
sep = IsWindows() && strchr(p, ';') ? ';' : ':';
for (;;) {
for (i = 0; p[i] && p[i] != sep; ++i) {
if (i < pathsz) {
path[i] = p[i];
}
}
if (AccessCommand(name, path, pathsz, namelen, err, suffix, i)) {
return true;
}
if (p[i] == sep) {
p += i + 1;
} else {
break;
}
}
return false;
}
static bool FindCommand(const char *name, char *pb, size_t pbsz, size_t namelen,
bool pri, const char *suffix, int *err) {
if (pri && (memchr(name, '/', namelen) || memchr(name, '\\', namelen))) {
pb[0] = 0;
return AccessCommand(name, pb, pbsz, namelen, err, suffix, 0);
}
return SearchPath(name, pb, pbsz, namelen, err, suffix);
}
static bool FindVerbatim(const char *name, char *pb, size_t pbsz,
size_t namelen, bool pri, int *err) {
return FindCommand(name, pb, pbsz, namelen, pri, "", err);
}
static bool FindSuffixed(const char *name, char *pb, size_t pbsz,
size_t namelen, bool pri, int *err) {
return !IsExePath(name, namelen) && !IsComPath(name, namelen) &&
!IsComDbgPath(name, namelen) &&
(FindCommand(name, pb, pbsz, namelen, pri, ".com", err) ||
FindCommand(name, pb, pbsz, namelen, pri, ".exe", err));
}
/**
* Resolves full pathname of executable.
*
* @return execve()'able path, or NULL w/ errno
* @errno ENOENT, EACCES, ENOMEM
* @see free(), execvpe()
* @asyncsignalsafe
* @vforksafe
*/
char *commandv(const char *name, char *pathbuf, size_t pathbufsz) {
int e, f;
char *res;
size_t namelen;
res = 0;
if (!name) {
errno = EFAULT;
} else if (!(namelen = strlen(name))) {
errno = ENOENT;
} else if (namelen + 1 > pathbufsz) {
errno = ENAMETOOLONG;
} else {
e = errno;
f = ENOENT;
if ((IsWindows() &&
(FindSuffixed(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, false, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, false, &f))) ||
(!IsWindows() &&
(FindVerbatim(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, true, &f) ||
FindVerbatim(name, pathbuf, pathbufsz, namelen, false, &f) ||
FindSuffixed(name, pathbuf, pathbufsz, namelen, false, &f)))) {
errno = e;
res = pathbuf;
} else {
errno = f;
}
}
return res;
}
| 6,718 | 173 | jart/plegde | false |
pledge/libc/calls/unveil.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2020 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
/*
#include "libc/assert.h"
*/
#include "libc/calls/blockcancel.internal.h"
#include "libc/calls/calls.h"
#include "libc/calls/landlock.h"
/*
#include "libc/calls/struct/bpf.h"
#include "libc/calls/struct/filter.h"
#include "libc/calls/struct/seccomp.h"
#include "libc/calls/struct/stat.h"
#include "libc/calls/struct/stat.internal.h"
#include "libc/calls/syscall-sysv.internal.h"
*/
#include "libc/calls/syscall_support-sysv.internal.h"
/*
#include "libc/errno.h"
*/
#include "libc/fmt/conv.h"
/*
#include "libc/intrin/strace.internal.h"
*/
#include "libc/macros.internal.h"
/*
#include "libc/nexgen32e/vendor.internal.h"
#include "libc/runtime/internal.h"
*/
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
#include "libc/str/path.h"
#include "libc/str/str.h"
/*
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/audit.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/fd.h"
#include "libc/sysv/consts/nrlinux.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/pr.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/errfuns.h"
#include "libc/thread/tls.h"
*/
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
#include <limits.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#define OFF(f) offsetof(struct seccomp_data, f)
#define UNVEIL_READ \
(LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR | \
LANDLOCK_ACCESS_FS_REFER)
#define UNVEIL_WRITE \
(LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_TRUNCATE)
#define UNVEIL_EXEC (LANDLOCK_ACCESS_FS_EXECUTE)
#define UNVEIL_CREATE \
(LANDLOCK_ACCESS_FS_MAKE_CHAR | LANDLOCK_ACCESS_FS_MAKE_DIR | \
LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_SOCK | \
LANDLOCK_ACCESS_FS_MAKE_FIFO | LANDLOCK_ACCESS_FS_MAKE_BLOCK | \
LANDLOCK_ACCESS_FS_MAKE_SYM)
#define FILE_BITS \
(LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE | \
LANDLOCK_ACCESS_FS_EXECUTE)
static struct sock_filter kUnveilBlacklistAbiVersionBelow3[] = {
#if 0 // Should we have this ? It certainly means things don't work on other
// architectures than x86-64 as-is... (TODO check this up later when
// relevant)
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
#endif
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_truncate, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setxattr, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (1 & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
static struct sock_filter kUnveilBlacklistLatestAbi[] = {
#if 0
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AUDIT_ARCH_X86_64, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
#endif
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setxattr, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (1 & SECCOMP_RET_DATA)),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
static int landlock_abi_version;
__attribute__((__constructor__)) void init_landlock_version() {
landlock_abi_version =
landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
}
/**
* Long living state for landlock calls.
* fs_mask is set to use all the access rights from the latest landlock ABI.
* On init, the current supported abi is checked and unavailable rights are
* masked off.
*
* As of 6.2, the latest abi is v3.
*
* TODO:
* - Integrate with pledge and remove the file access?
* - Stuff state into the .protected section?
*/
_Thread_local static struct {
uint64_t fs_mask;
int fd;
} State;
static int unveil_final(void) {
int e, rc;
struct sock_fprog sandbox = {
.filter = kUnveilBlacklistLatestAbi,
.len = ARRAYLEN(kUnveilBlacklistLatestAbi),
};
if (landlock_abi_version < 3) {
sandbox = (struct sock_fprog){
.filter = kUnveilBlacklistAbiVersionBelow3,
.len = ARRAYLEN(kUnveilBlacklistAbiVersionBelow3),
};
}
e = errno;
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
errno = e;
if ((rc = landlock_restrict_self(State.fd, 0)) != -1 &&
(rc = close(State.fd)) != -1 &&
(rc = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &sandbox)) != -1) {
State.fd = 0;
}
return rc;
}
static int err_close(int rc, int fd) {
int serrno = errno;
close(fd);
errno = serrno;
return rc;
}
static int unveil_init(void) {
int rc, fd;
State.fs_mask = UNVEIL_READ | UNVEIL_WRITE | UNVEIL_EXEC | UNVEIL_CREATE;
if (landlock_abi_version == -1) {
if (errno == EOPNOTSUPP) {
errno = ENOSYS;
}
return -1;
}
if (landlock_abi_version < 2) {
State.fs_mask &= ~LANDLOCK_ACCESS_FS_REFER;
}
if (landlock_abi_version < 3) {
State.fs_mask &= ~LANDLOCK_ACCESS_FS_TRUNCATE;
}
const struct landlock_ruleset_attr attr = {
.handled_access_fs = State.fs_mask,
};
// [undocumented] landlock_create_ruleset() always returns o_cloexec
// assert(__sys_fcntl(rc, F_GETFD, 0) == FD_CLOEXEC);
if ((rc = landlock_create_ruleset(&attr, sizeof(attr), 0)) < 0) return -1;
// grant file descriptor a higher number that's less likely to interfere
if ((fd = fcntl(rc, F_DUPFD_CLOEXEC, 100)) == -1) {
return err_close(-1, rc);
}
if (close(rc) == -1) {
return err_close(-1, fd);
}
State.fd = fd;
return 0;
}
int sys_unveil_linux(const char *path, const char *permissions) {
int rc;
const char *dir;
const char *last;
const char *next;
struct {
char lbuf[PATH_MAX];
char buf1[PATH_MAX];
char buf2[PATH_MAX];
char buf3[PATH_MAX];
char buf4[PATH_MAX];
} b;
CheckLargeStackAllocation(&b, sizeof(b));
if (!State.fd && (rc = unveil_init()) == -1) return rc;
if ((path && !permissions) || (!path && permissions)) {
errno = EINVAL;
return -1;
}
if (!path && !permissions) return unveil_final();
struct landlock_path_beneath_attr pb = {0};
for (const char *c = permissions; *c != '\0'; c++) {
switch (*c) {
case 'r':
pb.allowed_access |= UNVEIL_READ;
break;
case 'w':
pb.allowed_access |= UNVEIL_WRITE;
break;
case 'x':
pb.allowed_access |= UNVEIL_EXEC;
break;
case 'c':
pb.allowed_access |= UNVEIL_CREATE;
break;
default:
errno = EINVAL;
return -1;
}
}
pb.allowed_access &= State.fs_mask;
// landlock exposes all metadata, so we only technically need to add
// realpath(path) to the ruleset. however a corner case exists where
// it isn't valid, e.g. /dev/stdin -> /proc/2834/fd/pipe:[51032], so
// we'll need to work around this, by adding the path which is valid
if (strlen(path) + 1 > PATH_MAX) {
errno = ENAMETOOLONG;
return -1;
}
last = path;
next = path;
for (int i = 0;; ++i) {
if (i == 64) {
// give up
errno = ELOOP;
return -1;
}
int err = errno;
if ((rc = readlinkat(AT_FDCWD, next, b.lbuf, PATH_MAX)) != -1) {
if (rc < PATH_MAX) {
// we need to nul-terminate
b.lbuf[rc] = 0;
// last = next
strcpy(b.buf1, next);
last = b.buf1;
// next = join(dirname(next), link)
strcpy(b.buf2, next);
dir = dirname(b.buf2);
if ((next = joinpaths(b.buf3, PATH_MAX, dir, b.lbuf))) {
// next now points to either: buf3, buf2, lbuf, rodata
strcpy(b.buf4, next);
next = b.buf4;
} else {
errno = ENAMETOOLONG;
return -1;
}
} else {
// symbolic link data was too long
errno = ENAMETOOLONG;
return -1;
}
} else if (errno == EINVAL) {
// next wasn't a symbolic link
errno = err;
path = next;
break;
} else if (i && (errno == ENOENT || errno == ENOTDIR)) {
// next is a broken symlink, use last
errno = err;
path = last;
break;
} else {
// readlink failed for some other reason
return -1;
}
}
// now we can open the path
BLOCK_CANCELLATIONS;
rc = open(path, O_PATH | O_NOFOLLOW | O_CLOEXEC, 0);
ALLOW_CANCELLATIONS;
if (rc == -1) return rc;
pb.parent_fd = rc;
struct stat st;
if ((rc = fstat(pb.parent_fd, &st)) == -1) {
return err_close(rc, pb.parent_fd);
}
if (!S_ISDIR(st.st_mode)) {
pb.allowed_access &= FILE_BITS;
}
if ((rc = landlock_add_rule(State.fd, LANDLOCK_RULE_PATH_BENEATH, &pb, 0))) {
return err_close(rc, pb.parent_fd);
}
close(pb.parent_fd);
return rc;
}
/**
* Makes files accessible, e.g.
*
* unveil(".", "r"); // current directory + children are visible
* unveil("/etc", "r"); // make /etc readable too
* unveil(0, 0); // commit and lock policy
*
* Unveiling restricts a view of the filesystem to a set of allowed
* paths with specific privileges.
*
* Once you start using unveil(), the entire file system is considered
* hidden. You then specify, by repeatedly calling unveil(), which paths
* should become unhidden. When you're finished, you call `unveil(0,0)`
* which commits your policy.
*
* This function requires OpenBSD or Linux 5.13+. We don't consider lack
* of system support to be an ENOSYS error, because the files will still
* become unveiled. Therefore we return 0 in such cases.
*
* There are some differences between unveil() on Linux versus OpenBSD.
*
* 1. Build your policy and lock it in one go. On OpenBSD, policies take
* effect immediately and may evolve as you continue to call unveil()
* but only in a more restrictive direction. On Linux, nothing will
* happen until you call `unveil(0,0)` which commits and locks.
*
* 2. Try not to overlap directory trees. On OpenBSD, if directory trees
* overlap, then the most restrictive policy will be used for a given
* file. On Linux overlapping may result in a less restrictive policy
* and possibly even undefined behavior.
*
* 3. OpenBSD and Linux disagree on error codes. On OpenBSD, accessing
* paths outside of the allowed set raises ENOENT, and accessing ones
* with incorrect permissions raises EACCES. On Linux, both these
* cases raise EACCES.
*
* 4. Unlike OpenBSD, Linux does nothing to conceal the existence of
* paths. Even with an unveil() policy in place, it's still possible
* to access the metadata of all files using functions like stat()
* and open(O_PATH), provided you know the path. A sandboxed process
* can always, for example, determine how many bytes of data are in
* /etc/passwd, even if the file isn't readable. But it's still not
* possible to use opendir() and go fishing for paths which weren't
* previously known.
*
* 5. Use ftruncate() rather than truncate() if you wish for portability to
* Linux kernels versions released before February 2022. One issue
* Landlock hadn't addressed as of ABI version 2 was restrictions over
* truncate() and setxattr() which could permit certain kinds of
* modifications to files outside the sandbox. When your policy is
* committed, we install a SECCOMP BPF filter to disable those calls,
* however similar trickery may be possible through other unaddressed
* calls like ioctl(). Using the pledge() function in addition to
* unveil() will solve this, since it installs a strong system call
* access policy. Linux 6.2 has improved this situation with Landlock
* ABI v3, which added the ability to control truncation operations -
* this means the SECCOMP BPF filter will only disable
* truncate() on Linux 6.1 or older
*
* 6. Set your process-wide policy at startup from the main thread. On
* OpenBSD unveil() will apply process-wide even when called from a
* child thread; whereas with Linux, calling unveil() from a thread
* will cause your ruleset to only apply to that thread in addition
* to any descendent threads it creates.
*
* 7. Always specify at least one path. OpenBSD has unclear semantics
* when `unveil(0,0)` is used without any previous calls.
*
* 8. On OpenBSD calling `unveil(0,0)` will prevent unveil() from being
* used again. On Linux this is allowed, because Landlock is able to
* do that securely, i.e. the second ruleset can only be a subset of
* the previous ones.
*
* This system call is supported natively on OpenBSD and polyfilled on
* Linux using the Landlock LSM[1].
*
* @param path is the file or directory to unveil
* @param permissions is a string consisting of zero or more of the
* following characters:
*
* - 'r' makes `path` available for read-only path operations,
* corresponding to the pledge promise "rpath".
*
* - `w` makes `path` available for write operations, corresponding
* to the pledge promise "wpath".
*
* - `x` makes `path` available for execute operations,
* corresponding to the pledge promises "exec" and "execnative".
*
* - `c` allows `path` to be created and removed, corresponding to
* the pledge promise "cpath".
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if one argument is set and the other is not
* @raise EINVAL if an invalid character in `permissions` was found
* @raise EPERM if unveil() is called after locking
* @note on Linux this function requires Linux Kernel 5.13+ and version 6.2+
* to properly support truncation operations
* @see [1] https://docs.kernel.org/userspace-api/landlock.html
* @threadsafe
*/
int unveil(const char *path, const char *permissions) {
int e, rc;
e = errno;
/*if (IsGenuineBlink()) {
rc = 0; // blink doesn't support landlock
} else if (IsLinux()) {*/
rc = sys_unveil_linux(path, permissions);
/*} else {
abort();
rc = sys_unveil(path, permissions);
}*/
if (rc == -1 && errno == ENOSYS) {
errno = e;
rc = 0;
}
// STRACE("unveil(%#s, %#s) â %d% m", path, permissions, rc);
return rc;
}
| 16,207 | 446 | jart/plegde | false |
pledge/libc/calls/calls.h | #ifndef PLEDGE_LIBC_CALLS_H_
#define PLEDGE_LIBC_CALLS_H_
#include <stddef.h>
char *commandv(const char *, char *, size_t);
int ioprio_set(int, int, int);
int pledge(const char *, const char *);
int unveil(const char *, const char *);
#endif
| 245 | 12 | jart/plegde | false |
pledge/libc/calls/pledge.h | #ifndef PLEDGE_LIBC_CALLS_PLEDGE_H_
#define PLEDGE_LIBC_CALLS_PLEDGE_H_
#define PLEDGE_PENALTY_KILL_THREAD 0x0000
#define PLEDGE_PENALTY_KILL_PROCESS 0x0001
#define PLEDGE_PENALTY_RETURN_EPERM 0x0002
#define PLEDGE_PENALTY_MASK 0x000f
#define PLEDGE_STDERR_LOGGING 0x0010
extern int __pledge_mode;
#endif
| 324 | 14 | jart/plegde | false |
pledge/libc/calls/pledge-linux.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <errno.h>
#include <fcntl.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <sched.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <unistd.h>
#include "libc/calls/pledge.internal.h"
#include "libc/intrin/likely.h"
#include "libc/intrin/promises.internal.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/runtime/stack.h"
/**
* @fileoverview OpenBSD pledge() Polyfill Payload for GNU/Systemd
*
* This file contains only the minimum amount of Linux-specific code
* that's necessary to get a pledge() policy installed. This file is
* designed to not use static or tls memory or libc depnedencies, so
* it can be transplanted into codebases and injected into programs.
*/
#define SPECIAL 0xf000
#define SELF 0x8000
#define ADDRLESS 0x2000
#define INET 0x2000
#define LOCK 0x4000
#define NOEXEC 0x8000
#define EXEC 0x4000
#define READONLY 0x8000
#define WRITEONLY 0x4000
#define CREATONLY 0x2000
#define STDIO 0x8000
#define THREAD 0x8000
#define TTY 0x8000
#define UNIX 0x4000
#define NOBITS 0x8000
#define RESTRICT 0x1000
#define PLEDGE(pledge) pledge, ARRAYLEN(pledge)
#define OFF(f) offsetof(struct seccomp_data, f)
#define bsr(x) (__builtin_clzll(x) ^ 63)
#ifdef __x86_64__
#define MCONTEXT_SYSCALL_RESULT_REGISTER gregs[REG_RAX]
#define MCONTEXT_INSTRUCTION_POINTER gregs[REG_RIP]
#define ARCHITECTURE AUDIT_ARCH_X86_64
#elif defined(__aarch64__)
#define MCONTEXT_SYSCALL_RESULT_REGISTER regs[0]
#define MCONTEXT_INSTRUCTION_POINTER pc
#define ARCHITECTURE AUDIT_ARCH_AARCH64
#else
#error "unsupported architecture"
#endif
struct Filter {
size_t n;
struct sock_filter p[800];
};
static const struct thatispacked SyscallName {
uint16_t n;
const char *const s;
} kSyscallName[] = {
{__NR_exit, "exit"},
{__NR_exit_group, "exit_group"},
{__NR_read, "read"},
{__NR_write, "write"},
#ifdef __NR_open
{__NR_open, "open"},
#endif
{__NR_close, "close"},
#ifdef __NR_stat
{__NR_stat, "stat"},
#endif
{__NR_fstat, "fstat"},
#ifdef __NR_lstat
{__NR_lstat, "lstat"},
#endif
#ifdef __NR_poll
{__NR_poll, "poll"},
#endif
{__NR_ppoll, "ppoll"},
{__NR_brk, "brk"},
{__NR_rt_sigreturn, "sigreturn"},
{__NR_lseek, "lseek"},
{__NR_mmap, "mmap"},
{__NR_msync, "msync"},
{__NR_mprotect, "mprotect"},
{__NR_munmap, "munmap"},
{__NR_rt_sigaction, "sigaction"},
{__NR_rt_sigprocmask, "sigprocmask"},
{__NR_ioctl, "ioctl"},
{__NR_pread64, "pread"},
{__NR_pwrite64, "pwrite"},
{__NR_readv, "readv"},
{__NR_writev, "writev"},
#ifdef __NR_access
{__NR_access, "access"},
#endif
#ifdef __NR_pipe
{__NR_pipe, "pipe"},
#endif
#ifdef __NR_select
{__NR_select, "select"},
#endif
{__NR_pselect6, "pselect6"},
{__NR_sched_yield, "sched_yield"},
{__NR_mremap, "mremap"},
{__NR_mincore, "mincore"},
{__NR_madvise, "madvise"},
{__NR_shmget, "shmget"},
{__NR_shmat, "shmat"},
{__NR_shmctl, "shmctl"},
{__NR_dup, "dup"},
#ifdef __NR_dup2
{__NR_dup2, "dup2"},
#endif
#ifdef __NR_pause
{__NR_pause, "pause"},
#endif
{__NR_nanosleep, "nanosleep"},
{__NR_getitimer, "getitimer"},
{__NR_setitimer, "setitimer"},
#ifdef __NR_alarm
{__NR_alarm, "alarm"},
#endif
{__NR_getpid, "getpid"},
{__NR_sendfile, "sendfile"},
{__NR_socket, "socket"},
{__NR_connect, "connect"},
{__NR_accept, "accept"},
{__NR_sendto, "sendto"},
{__NR_recvfrom, "recvfrom"},
{__NR_sendmsg, "sendmsg"},
{__NR_recvmsg, "recvmsg"},
{__NR_shutdown, "shutdown"},
{__NR_bind, "bind"},
{__NR_listen, "listen"},
{__NR_getsockname, "getsockname"},
{__NR_getpeername, "getpeername"},
{__NR_socketpair, "socketpair"},
{__NR_setsockopt, "setsockopt"},
{__NR_getsockopt, "getsockopt"},
#ifdef __NR_fork
{__NR_fork, "fork"},
#endif
#ifdef __NR_vfork
{__NR_vfork, "vfork"},
#endif
{__NR_execve, "execve"},
{__NR_wait4, "wait4"},
{__NR_kill, "kill"},
{__NR_clone, "clone"},
{__NR_tkill, "tkill"},
{__NR_futex, "futex"},
{__NR_set_robust_list, "set_robust_list"},
{__NR_get_robust_list, "get_robust_list"},
{__NR_uname, "uname"},
{__NR_semget, "semget"},
{__NR_semop, "semop"},
{__NR_semctl, "semctl"},
{__NR_shmdt, "shmdt"},
{__NR_msgget, "msgget"},
{__NR_msgsnd, "msgsnd"},
{__NR_msgrcv, "msgrcv"},
{__NR_msgctl, "msgctl"},
{__NR_fcntl, "fcntl"},
{__NR_flock, "flock"},
{__NR_fsync, "fsync"},
{__NR_fdatasync, "fdatasync"},
{__NR_truncate, "truncate"},
{__NR_ftruncate, "ftruncate"},
{__NR_getcwd, "getcwd"},
{__NR_chdir, "chdir"},
{__NR_fchdir, "fchdir"},
#ifdef __NR_rename
{__NR_rename, "rename"},
#endif
#ifdef __NR_mkdir
{__NR_mkdir, "mkdir"},
#endif
#ifdef __NR_rmdir
{__NR_rmdir, "rmdir"},
#endif
#ifdef __NR_creat
{__NR_creat, "creat"},
#endif
#ifdef __NR_link
{__NR_link, "link"},
#endif
#ifdef __NR_unlink
{__NR_unlink, "unlink"},
#endif
#ifdef __NR_symlink
{__NR_symlink, "symlink"},
#endif
#ifdef __NR_readlink
{__NR_readlink, "readlink"},
#endif
#ifdef __NR_chmod
{__NR_chmod, "chmod"},
#endif
{__NR_fchmod, "fchmod"},
#ifdef __NR_chown
{__NR_chown, "chown"},
#endif
{__NR_fchown, "fchown"},
#ifdef __NR_lchown
{__NR_lchown, "lchown"},
#endif
{__NR_umask, "umask"},
{__NR_gettimeofday, "gettimeofday"},
{__NR_getrlimit, "getrlimit"},
{__NR_getrusage, "getrusage"},
{__NR_sysinfo, "sysinfo"},
{__NR_times, "times"},
{__NR_ptrace, "ptrace"},
{__NR_syslog, "syslog"},
{__NR_getuid, "getuid"},
{__NR_getgid, "getgid"},
{__NR_getppid, "getppid"},
#ifdef __NR_getpgrp
{__NR_getpgrp, "getpgrp"},
#endif
{__NR_setsid, "setsid"},
{__NR_getsid, "getsid"},
{__NR_getpgid, "getpgid"},
{__NR_setpgid, "setpgid"},
{__NR_geteuid, "geteuid"},
{__NR_getegid, "getegid"},
{__NR_getgroups, "getgroups"},
{__NR_setgroups, "setgroups"},
{__NR_setreuid, "setreuid"},
{__NR_setregid, "setregid"},
{__NR_setuid, "setuid"},
{__NR_setgid, "setgid"},
{__NR_setresuid, "setresuid"},
{__NR_setresgid, "setresgid"},
{__NR_getresuid, "getresuid"},
{__NR_getresgid, "getresgid"},
{__NR_rt_sigpending, "sigpending"},
{__NR_rt_sigsuspend, "sigsuspend"},
{__NR_sigaltstack, "sigaltstack"},
#ifdef __NR_mknod
{__NR_mknod, "mknod"},
#endif
{__NR_mknodat, "mknodat"},
{__NR_statfs, "statfs"},
{__NR_fstatfs, "fstatfs"},
{__NR_getpriority, "getpriority"},
{__NR_setpriority, "setpriority"},
{__NR_mlock, "mlock"},
{__NR_munlock, "munlock"},
{__NR_mlockall, "mlockall"},
{__NR_munlockall, "munlockall"},
{__NR_setrlimit, "setrlimit"},
{__NR_chroot, "chroot"},
{__NR_sync, "sync"},
{__NR_acct, "acct"},
{__NR_settimeofday, "settimeofday"},
{__NR_mount, "mount"},
{__NR_reboot, "reboot"},
{__NR_quotactl, "quotactl"},
{__NR_setfsuid, "setfsuid"},
{__NR_setfsgid, "setfsgid"},
{__NR_capget, "capget"},
{__NR_capset, "capset"},
{__NR_rt_sigtimedwait, "sigtimedwait"},
{__NR_rt_sigqueueinfo, "rt_sigqueueinfo"},
{__NR_personality, "personality"},
#ifdef __NR_ustat
{__NR_ustat, "ustat"},
#endif
#ifdef __NR_sysfs
{__NR_sysfs, "sysfs"},
#endif
{__NR_sched_setparam, "sched_setparam"},
{__NR_sched_getparam, "sched_getparam"},
{__NR_sched_setscheduler, "sched_setscheduler"},
{__NR_sched_getscheduler, "sched_getscheduler"},
{__NR_sched_get_priority_max, "sched_get_priority_max"},
{__NR_sched_get_priority_min, "sched_get_priority_min"},
{__NR_sched_rr_get_interval, "sched_rr_get_interval"},
{__NR_vhangup, "vhangup"},
#ifdef __NR_modify_ldt
{__NR_modify_ldt, "modify_ldt"},
#endif
{__NR_pivot_root, "pivot_root"},
#ifdef __NR__sysctl
{__NR__sysctl, "_sysctl"},
#endif
{__NR_prctl, "prctl"},
#ifdef __NR_arch_prctl
{__NR_arch_prctl, "arch_prctl"},
#endif
{__NR_adjtimex, "adjtimex"},
{__NR_umount2, "umount2"},
{__NR_swapon, "swapon"},
{__NR_swapoff, "swapoff"},
{__NR_sethostname, "sethostname"},
{__NR_setdomainname, "setdomainname"},
#ifdef __NR_iopl
{__NR_iopl, "iopl"},
#endif
#ifdef __NR_ioperm
{__NR_ioperm, "ioperm"},
#endif
{__NR_init_module, "init_module"},
{__NR_delete_module, "delete_module"},
{__NR_gettid, "gettid"},
{__NR_readahead, "readahead"},
{__NR_setxattr, "setxattr"},
{__NR_fsetxattr, "fsetxattr"},
{__NR_getxattr, "getxattr"},
{__NR_fgetxattr, "fgetxattr"},
{__NR_listxattr, "listxattr"},
{__NR_flistxattr, "flistxattr"},
{__NR_removexattr, "removexattr"},
{__NR_fremovexattr, "fremovexattr"},
{__NR_lsetxattr, "lsetxattr"},
{__NR_lgetxattr, "lgetxattr"},
{__NR_llistxattr, "llistxattr"},
{__NR_lremovexattr, "lremovexattr"},
{__NR_sched_setaffinity, "sched_setaffinity"},
{__NR_sched_getaffinity, "sched_getaffinity"},
{__NR_io_setup, "io_setup"},
{__NR_io_destroy, "io_destroy"},
{__NR_io_getevents, "io_getevents"},
{__NR_io_submit, "io_submit"},
{__NR_io_cancel, "io_cancel"},
{__NR_lookup_dcookie, "lookup_dcookie"},
#ifdef __NR_epoll_create
{__NR_epoll_create, "epoll_create"},
#endif
#ifdef __NR_epoll_wait
{__NR_epoll_wait, "epoll_wait"},
#endif
{__NR_epoll_ctl, "epoll_ctl"},
#ifdef __NR_getdents
{__NR_getdents, "getdents"},
#endif
{__NR_getdents64, "getdents64"},
{__NR_set_tid_address, "set_tid_address"},
{__NR_restart_syscall, "restart_syscall"},
{__NR_semtimedop, "semtimedop"},
{__NR_fadvise64, "fadvise"},
{__NR_timer_create, "timer_create"},
{__NR_timer_settime, "timer_settime"},
{__NR_timer_gettime, "timer_gettime"},
{__NR_timer_getoverrun, "timer_getoverrun"},
{__NR_timer_delete, "timer_delete"},
{__NR_clock_settime, "clock_settime"},
{__NR_clock_gettime, "clock_gettime"},
{__NR_clock_getres, "clock_getres"},
{__NR_clock_nanosleep, "clock_nanosleep"},
{__NR_tgkill, "tgkill"},
{__NR_mbind, "mbind"},
{__NR_set_mempolicy, "set_mempolicy"},
{__NR_get_mempolicy, "get_mempolicy"},
{__NR_mq_open, "mq_open"},
{__NR_mq_unlink, "mq_unlink"},
{__NR_mq_timedsend, "mq_timedsend"},
{__NR_mq_timedreceive, "mq_timedreceive"},
{__NR_mq_notify, "mq_notify"},
{__NR_mq_getsetattr, "mq_getsetattr"},
{__NR_kexec_load, "kexec_load"},
{__NR_waitid, "waitid"},
{__NR_add_key, "add_key"},
{__NR_request_key, "request_key"},
{__NR_keyctl, "keyctl"},
{__NR_ioprio_set, "ioprio_set"},
{__NR_ioprio_get, "ioprio_get"},
#ifdef __NR_inotify_init
{__NR_inotify_init, "inotify_init"},
#endif
{__NR_inotify_add_watch, "inotify_add_watch"},
{__NR_inotify_rm_watch, "inotify_rm_watch"},
{__NR_openat, "openat"},
{__NR_mkdirat, "mkdirat"},
{__NR_fchownat, "fchownat"},
#ifdef __NR_utime
{__NR_utime, "utime"},
#endif
#ifdef __NR_utimes
{__NR_utimes, "utimes"},
#endif
#ifdef __NR_futimesat
{__NR_futimesat, "futimesat"},
#endif
{__NR_newfstatat, "fstatat"},
{__NR_unlinkat, "unlinkat"},
{__NR_renameat, "renameat"},
{__NR_linkat, "linkat"},
{__NR_symlinkat, "symlinkat"},
{__NR_readlinkat, "readlinkat"},
{__NR_fchmodat, "fchmodat"},
{__NR_faccessat, "faccessat"},
{__NR_unshare, "unshare"},
{__NR_splice, "splice"},
{__NR_tee, "tee"},
{__NR_sync_file_range, "sync_file_range"},
{__NR_vmsplice, "vmsplice"},
{__NR_migrate_pages, "migrate_pages"},
{__NR_move_pages, "move_pages"},
{__NR_preadv, "preadv"},
{__NR_pwritev, "pwritev"},
{__NR_utimensat, "utimensat"},
{__NR_fallocate, "fallocate"},
{__NR_accept4, "accept4"},
{__NR_dup3, "dup3"},
{__NR_pipe2, "pipe2"},
{__NR_epoll_pwait, "epoll_pwait"},
{__NR_epoll_create1, "epoll_create1"},
{__NR_perf_event_open, "perf_event_open"},
{__NR_inotify_init1, "inotify_init1"},
{__NR_rt_tgsigqueueinfo, "rt_tgsigqueueinfo"},
#ifdef __NR_signalfd
{__NR_signalfd, "signalfd"},
#endif
{__NR_signalfd4, "signalfd4"},
#ifdef __NR_eventfd
{__NR_eventfd, "eventfd"},
#endif
{__NR_eventfd2, "eventfd2"},
{__NR_timerfd_create, "timerfd_create"},
{__NR_timerfd_settime, "timerfd_settime"},
{__NR_timerfd_gettime, "timerfd_gettime"},
{__NR_recvmmsg, "recvmmsg"},
{__NR_fanotify_init, "fanotify_init"},
{__NR_fanotify_mark, "fanotify_mark"},
{__NR_prlimit64, "prlimit"},
{__NR_name_to_handle_at, "name_to_handle_at"},
{__NR_open_by_handle_at, "open_by_handle_at"},
{__NR_clock_adjtime, "clock_adjtime"},
{__NR_syncfs, "syncfs"},
{__NR_sendmmsg, "sendmmsg"},
{__NR_setns, "setns"},
{__NR_getcpu, "getcpu"},
{__NR_process_vm_readv, "process_vm_readv"},
{__NR_process_vm_writev, "process_vm_writev"},
{__NR_kcmp, "kcmp"},
{__NR_finit_module, "finit_module"},
{__NR_sched_setattr, "sched_setattr"},
{__NR_sched_getattr, "sched_getattr"},
{__NR_renameat2, "renameat2"},
{__NR_seccomp, "seccomp"},
{__NR_getrandom, "getrandom"},
{__NR_memfd_create, "memfd_create"},
{__NR_kexec_file_load, "kexec_file_load"},
{__NR_bpf, "bpf"},
{__NR_execveat, "execveat"},
{__NR_userfaultfd, "userfaultfd"},
{__NR_membarrier, "membarrier"},
{__NR_mlock2, "mlock2"},
{__NR_copy_file_range, "copy_file_range"},
{__NR_preadv2, "preadv2"},
{__NR_pwritev2, "pwritev2"},
{__NR_pkey_mprotect, "pkey_mprotect"},
{__NR_pkey_alloc, "pkey_alloc"},
{__NR_pkey_free, "pkey_free"},
{__NR_statx, "statx"},
{__NR_io_pgetevents, "io_pgetevents"},
{__NR_rseq, "rseq"},
{__NR_pidfd_send_signal, "pidfd_send_signal"},
{__NR_io_uring_setup, "io_uring_setup"},
{__NR_io_uring_enter, "io_uring_enter"},
{__NR_io_uring_register, "io_uring_register"},
{__NR_open_tree, "open_tree"},
{__NR_move_mount, "move_mount"},
{__NR_fsopen, "fsopen"},
{__NR_fsconfig, "fsconfig"},
{__NR_fsmount, "fsmount"},
{__NR_fspick, "fspick"},
{__NR_pidfd_open, "pidfd_open"},
{__NR_clone3, "clone3"},
{__NR_close_range, "close_range"},
{__NR_openat2, "openat2"},
{__NR_pidfd_getfd, "pidfd_getfd"},
{__NR_faccessat2, "faccessat2"},
{__NR_process_madvise, "process_madvise"},
{__NR_epoll_pwait2, "epoll_pwait2"},
{__NR_mount_setattr, "mount_setattr"},
#ifdef __NR_quotactl_fd
{__NR_quotactl_fd, "quotactl_fd"},
#endif
{__NR_landlock_create_ruleset, "landlock_create_ruleset"},
{__NR_landlock_add_rule, "landlock_add_rule"},
{__NR_landlock_restrict_self, "landlock_restrict_self"},
#ifdef __NR_memfd_secret
{__NR_memfd_secret, "memfd_secret"},
#endif
#ifdef __NR_process_mrelease
{__NR_process_mrelease, "process_mrelease"},
#endif
#ifdef __NR_futex_waitv
{__NR_futex_waitv, "futex_waitv"},
#endif
#ifdef __NR_set_mempolicy_home_node
{__NR_set_mempolicy_home_node, "set_mempolicy_home_node"},
#endif
};
static const uint16_t kPledgeDefault[] = {
__NR_exit, // thread return / exit()
};
// stdio contains all the benign system calls. openbsd makes the
// assumption that preexisting file descriptors are trustworthy. we
// implement checking for these as a simple linear scan rather than
// binary search, since there doesn't appear to be any measurable
// difference in the latency of sched_yield() if it's at the start of
// the bpf script or the end.
static const uint16_t kPledgeStdio[] = {
__NR_rt_sigreturn,
__NR_restart_syscall,
__NR_exit_group,
__NR_sched_yield,
__NR_sched_getaffinity,
__NR_clock_getres,
__NR_clock_gettime,
__NR_clock_nanosleep,
__NR_close_range,
__NR_close,
__NR_write,
__NR_writev,
__NR_pwrite64,
__NR_pwritev,
__NR_pwritev2,
__NR_read,
__NR_readv,
__NR_pread64,
__NR_preadv,
__NR_preadv2,
__NR_dup,
#ifdef __NR_dup2
__NR_dup2,
#endif
__NR_dup3,
__NR_fchdir,
__NR_fcntl | STDIO,
__NR_fstat,
__NR_fsync,
__NR_sysinfo,
__NR_fdatasync,
__NR_ftruncate,
__NR_getrandom,
__NR_getgroups,
__NR_getpgid,
#ifdef __NR_getpgrp
__NR_getpgrp,
#endif
__NR_getpid,
__NR_gettid,
__NR_getuid,
__NR_getgid,
__NR_getsid,
__NR_getppid,
__NR_geteuid,
__NR_getegid,
__NR_getrlimit,
__NR_getresgid,
__NR_getresuid,
__NR_getitimer,
__NR_setitimer,
__NR_timerfd_create,
__NR_timerfd_settime,
__NR_timerfd_gettime,
__NR_copy_file_range,
__NR_gettimeofday,
__NR_sendfile,
__NR_vmsplice,
__NR_splice,
__NR_lseek,
__NR_tee,
__NR_brk,
__NR_msync,
__NR_mmap | NOEXEC,
__NR_mremap,
__NR_munmap,
__NR_mincore,
__NR_madvise,
__NR_fadvise64,
__NR_mprotect | NOEXEC,
#ifdef __NR_arch_prctl
__NR_arch_prctl,
#endif
__NR_migrate_pages,
__NR_sync_file_range,
__NR_set_tid_address,
__NR_membarrier,
__NR_nanosleep,
#ifdef __NR_pipe
__NR_pipe,
#endif
__NR_pipe2,
#ifdef __NR_poll
__NR_poll,
#endif
__NR_ppoll,
#ifdef __NR_select
__NR_select,
#endif
__NR_pselect6,
#ifdef __NR_epoll_create
__NR_epoll_create,
#endif
__NR_epoll_create1,
__NR_epoll_ctl,
#ifdef __NR_epoll_wait
__NR_epoll_wait,
#endif
__NR_epoll_pwait,
__NR_epoll_pwait2,
__NR_recvfrom,
__NR_sendto | ADDRLESS,
__NR_ioctl | RESTRICT,
#ifdef __NR_alarm
__NR_alarm,
#endif
#ifdef __NR_pause
__NR_pause,
#endif
__NR_shutdown,
#ifdef __NR_eventfd
__NR_eventfd,
#endif
__NR_eventfd2,
#ifdef __NR_signalfd
__NR_signalfd,
#endif
__NR_signalfd4,
__NR_rt_sigaction,
__NR_sigaltstack,
__NR_rt_sigprocmask,
__NR_rt_sigsuspend,
__NR_rt_sigpending,
__NR_kill | SELF,
__NR_tkill,
__NR_tgkill | SELF,
__NR_socketpair,
__NR_getrusage,
__NR_times,
__NR_umask,
__NR_wait4,
__NR_uname,
__NR_prctl | STDIO,
__NR_clone | THREAD,
__NR_futex,
__NR_set_robust_list,
__NR_get_robust_list,
__NR_prlimit64 | STDIO,
__NR_sched_getaffinity,
__NR_sched_setaffinity,
__NR_rt_sigtimedwait,
};
static const uint16_t kPledgeFlock[] = {
__NR_flock,
__NR_fcntl | LOCK,
};
static const uint16_t kPledgeRpath[] = {
__NR_chdir,
__NR_getcwd,
#ifdef __NR_open
__NR_open | READONLY,
#endif
__NR_openat | READONLY,
#ifdef __NR_stat
__NR_stat,
#endif
#ifdef __NR_lstat
__NR_lstat,
#endif
__NR_fstat,
__NR_newfstatat,
#ifdef __NR_access
__NR_access,
#endif
__NR_faccessat,
__NR_faccessat2,
#ifdef __NR_readlink
__NR_readlink,
#endif
__NR_readlinkat,
__NR_statfs,
__NR_fstatfs,
#ifdef __NR_getdents
__NR_getdents,
#endif
__NR_getdents64,
};
static const uint16_t kPledgeWpath[] = {
__NR_getcwd,
#ifdef __NR_open
__NR_open | WRITEONLY,
#endif
__NR_openat | WRITEONLY,
#ifdef __NR_stat
__NR_stat,
#endif
__NR_fstat,
#ifdef __NR_lstat
__NR_lstat,
#endif
__NR_newfstatat,
#ifdef __NR_access
__NR_access,
#endif
__NR_truncate,
__NR_faccessat,
__NR_faccessat2,
__NR_readlinkat,
#ifdef __NR_chmod
__NR_chmod | NOBITS,
#endif
__NR_fchmod | NOBITS,
__NR_fchmodat | NOBITS,
};
static const uint16_t kPledgeCpath[] = {
#ifdef __NR_open
__NR_open | CREATONLY,
#endif
__NR_openat | CREATONLY,
#ifdef __NR_creat
__NR_creat | RESTRICT,
#endif
#ifdef __NR_rename
__NR_rename,
#endif
__NR_renameat,
__NR_renameat2,
#ifdef __NR_link
__NR_link,
#endif
__NR_linkat,
#ifdef __NR_symlink
__NR_symlink,
#endif
__NR_symlinkat,
#ifdef __NR_rmdir
__NR_rmdir,
#endif
#ifdef __NR_unlink
__NR_unlink,
#endif
__NR_unlinkat,
#ifdef __NR_mkdir
__NR_mkdir,
#endif
__NR_mkdirat,
};
static const uint16_t kPledgeDpath[] = {
#ifdef __NR_mknod
__NR_mknod, //
#endif
__NR_mknodat, //
};
static const uint16_t kPledgeFattr[] = {
#ifdef __NR_chmod
__NR_chmod | NOBITS, //
#endif
__NR_fchmod | NOBITS, //
__NR_fchmodat | NOBITS, //
#ifdef __NR_utime
__NR_utime, //
#endif
#ifdef __NR_utimes
__NR_utimes, //
#endif
#ifdef __NR_futimesat
__NR_futimesat, //
#endif
__NR_utimensat, //
};
static const uint16_t kPledgeInet[] = {
__NR_socket | INET, //
__NR_listen, //
__NR_bind, //
__NR_sendto, //
__NR_connect, //
__NR_accept, //
__NR_accept4, //
__NR_ioctl | INET, //
__NR_getsockopt | RESTRICT, //
__NR_setsockopt | RESTRICT, //
__NR_getpeername, //
__NR_getsockname, //
};
static const uint16_t kPledgeUnix[] = {
__NR_socket | UNIX, //
__NR_listen, //
__NR_bind, //
__NR_connect, //
__NR_sendto, //
__NR_accept, //
__NR_accept4, //
__NR_getsockopt | RESTRICT, //
__NR_setsockopt | RESTRICT, //
__NR_getpeername, //
__NR_getsockname, //
};
static const uint16_t kPledgeDns[] = {
__NR_socket | INET, //
__NR_bind, //
__NR_sendto, //
__NR_connect, //
__NR_recvfrom, //
__NR_setsockopt | RESTRICT, //
__NR_newfstatat, //
__NR_openat | READONLY, //
__NR_read, //
__NR_close, //
};
static const uint16_t kPledgeTty[] = {
__NR_ioctl | TTY, //
};
static const uint16_t kPledgeRecvfd[] = {
__NR_recvmsg, //
__NR_recvmmsg, //
};
static const uint16_t kPledgeSendfd[] = {
__NR_sendmsg, //
__NR_sendmmsg, //
};
static const uint16_t kPledgeProc[] = {
#ifdef __NR_fork
__NR_fork, //
#endif
#ifdef __NR_vfork
__NR_vfork, //
#endif
__NR_clone | RESTRICT, //
__NR_kill, //
__NR_tgkill, //
__NR_setsid, //
__NR_setpgid, //
__NR_prlimit64, //
__NR_setrlimit, //
__NR_getpriority, //
__NR_setpriority, //
__NR_ioprio_get, //
__NR_ioprio_set, //
__NR_sched_getscheduler, //
__NR_sched_setscheduler, //
__NR_sched_get_priority_min, //
__NR_sched_get_priority_max, //
__NR_sched_getparam, //
__NR_sched_setparam, //
};
static const uint16_t kPledgeId[] = {
__NR_setuid, //
__NR_setreuid, //
__NR_setresuid, //
__NR_setgid, //
__NR_setregid, //
__NR_setresgid, //
__NR_setgroups, //
__NR_prlimit64, //
__NR_setrlimit, //
__NR_getpriority, //
__NR_setpriority, //
__NR_setfsuid, //
__NR_setfsgid, //
};
static const uint16_t kPledgeChown[] = {
#ifdef __NR_chown
__NR_chown, //
#endif
__NR_fchown, //
#ifdef __NR_lchown
__NR_lchown, //
#endif
__NR_fchownat, //
};
static const uint16_t kPledgeSettime[] = {
__NR_settimeofday, //
__NR_clock_adjtime, //
};
static const uint16_t kPledgeProtExec[] = {
__NR_mmap | EXEC, //
__NR_mprotect, //
};
static const uint16_t kPledgeExec[] = {
__NR_execve, //
__NR_execveat, //
};
static const uint16_t kPledgeUnveil[] = {
__NR_landlock_create_ruleset, //
__NR_landlock_add_rule, //
__NR_landlock_restrict_self, //
};
// placeholder group
//
// pledge.com checks this to do auto-unveiling
static const uint16_t kPledgeVminfo[] = {
__NR_sched_yield, //
};
// placeholder group
//
// pledge.com uses this to auto-unveil /tmp and $TMPPATH with rwc
// permissions. pledge() alone (without unveil() too) offers very
// little security here. consider using them together.
static const uint16_t kPledgeTmppath[] = {
#ifdef __NR_lstat
__NR_lstat, //
#endif
#ifdef __NR_unlink
__NR_unlink, //
#endif
__NR_unlinkat, //
};
const struct Pledges kPledge[PROMISE_LEN_] = {
[PROMISE_STDIO] = {"stdio", PLEDGE(kPledgeStdio)},
[PROMISE_RPATH] = {"rpath", PLEDGE(kPledgeRpath)},
[PROMISE_WPATH] = {"wpath", PLEDGE(kPledgeWpath)},
[PROMISE_CPATH] = {"cpath", PLEDGE(kPledgeCpath)},
[PROMISE_DPATH] = {"dpath", PLEDGE(kPledgeDpath)},
[PROMISE_FLOCK] = {"flock", PLEDGE(kPledgeFlock)},
[PROMISE_FATTR] = {"fattr", PLEDGE(kPledgeFattr)},
[PROMISE_INET] = {"inet", PLEDGE(kPledgeInet)},
[PROMISE_UNIX] = {"unix", PLEDGE(kPledgeUnix)},
[PROMISE_DNS] = {"dns", PLEDGE(kPledgeDns)},
[PROMISE_TTY] = {"tty", PLEDGE(kPledgeTty)},
[PROMISE_RECVFD] = {"recvfd", PLEDGE(kPledgeRecvfd)},
[PROMISE_SENDFD] = {"sendfd", PLEDGE(kPledgeSendfd)},
[PROMISE_PROC] = {"proc", PLEDGE(kPledgeProc)},
[PROMISE_EXEC] = {"exec", PLEDGE(kPledgeExec)},
[PROMISE_ID] = {"id", PLEDGE(kPledgeId)},
[PROMISE_UNVEIL] = {"unveil", PLEDGE(kPledgeUnveil)},
[PROMISE_SETTIME] = {"settime", PLEDGE(kPledgeSettime)},
[PROMISE_PROT_EXEC] = {"prot_exec", PLEDGE(kPledgeProtExec)},
[PROMISE_VMINFO] = {"vminfo", PLEDGE(kPledgeVminfo)},
[PROMISE_TMPPATH] = {"tmppath", PLEDGE(kPledgeTmppath)},
[PROMISE_CHOWN] = {"chown", PLEDGE(kPledgeChown)},
};
static const struct sock_filter kPledgeStart[] = {
// make sure this isn't an i386 binary or something
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(arch)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, ARCHITECTURE, 1, 0),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
// each filter assumes ordinal is already loaded into accumulator
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
#ifdef __NR_memfd_secret
// forbid some system calls with ENOSYS (rather than EPERM)
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_memfd_secret, 5, 0),
#else
BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, __NR_landlock_restrict_self + 1, 5, 0),
#endif
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rseq, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_memfd_create, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat2, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone3, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_statx, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (ENOSYS & SECCOMP_RET_DATA)),
};
static const struct sock_filter kFilterIgnoreExitGroup[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_exit_group, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
};
static char *FixCpy(char p[17], uint64_t x, int k) {
while (k > 0) *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15];
*p = '\0';
return p;
}
static privileged char *HexCpy(char p[17], uint64_t x) {
return FixCpy(p, x, ROUNDUP(x ? bsr(x) + 1 : 1, 4));
}
static void Log(const char *s, ...) {
int ax;
va_list va;
va_start(va, s);
do ax = write(2, s, strlen(s));
while ((s = va_arg(va, const char *)));
va_end(va);
}
static void KillThisProcess(void) {
abort();
}
static void KillThisThread(void) {
int ax;
sigset_t full, empty;
sigfillset(&full);
sigemptyset(&empty);
sigaction(SIGABRT, &(struct sigaction){0}, 0);
sigprocmask(SIG_SETMASK, &full, 0);
ax = syscall(__NR_tkill, syscall(__NR_gettid), SIGABRT);
sigprocmask(SIG_SETMASK, &empty, 0);
syscall(__NR_exit, 128 + SIGABRT);
}
static const char *GetSyscallName(uint16_t n) {
int i;
for (i = 0; i < ARRAYLEN(kSyscallName); ++i) {
if (kSyscallName[i].n == n) {
return kSyscallName[i].s;
}
}
return "unknown";
}
static int HasSyscall(const struct Pledges *p, uint16_t n) {
int i;
for (i = 0; i < p->len; ++i) {
if (p->syscalls[i] == n) {
return 1;
}
if ((p->syscalls[i] & 0xfff) == n) {
return 2;
}
}
return 0;
}
static void OnSigSys(int sig, siginfo_t *si, void *vctx) {
bool found;
char ord[17], ip[17];
int i, ok, mode = si->si_errno;
ucontext_t *ctx = vctx;
ctx->uc_mcontext.MCONTEXT_SYSCALL_RESULT_REGISTER = -EPERM;
FixCpy(ord, si->si_syscall, 12);
HexCpy(ip, ctx->uc_mcontext.MCONTEXT_INSTRUCTION_POINTER);
for (found = i = 0; i < ARRAYLEN(kPledge); ++i) {
if (HasSyscall(kPledge + i, si->si_syscall)) {
Log("error: pledge ", kPledge[i].name, " for ",
GetSyscallName(si->si_syscall), " (ord=0x", ord, " ip=0x", ip, ")\n",
NULL);
found = true;
}
}
if (!found) {
Log("error: bad syscall (", GetSyscallName(si->si_syscall), " ord=0x", ord,
" ip=0x", ip, ")\n", NULL);
}
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_PROCESS:
KillThisProcess();
// fallthrough
case PLEDGE_PENALTY_KILL_THREAD:
KillThisThread();
__builtin_trap();
default:
break;
}
}
static void MonitorSigSys(void) {
int ax;
struct sigaction sa = {
.sa_sigaction = OnSigSys,
.sa_flags = SA_SIGINFO | SA_RESTART,
};
// we block changing sigsys once pledge is installed
// so we aren't terribly concerned if this will fail
if (sigaction(SIGSYS, &sa, 0) == -1) {
__builtin_trap();
}
}
static void AppendFilter(struct Filter *f, const struct sock_filter *p,
size_t n) {
if (UNLIKELY(f->n + n > ARRAYLEN(f->p))) __builtin_trap();
memcpy(f->p + f->n, p, n * sizeof(*f->p));
f->n += n;
}
// The first argument of kill() must be
//
// - getpid()
//
static void AllowKillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_kill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of tgkill() must be
//
// - getpid()
//
static void AllowTgkillSelf(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tgkill, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The following system calls are allowed:
//
// - write(2) to allow logging
// - kill(getpid(), SIGABRT) to abort process
// - tkill(gettid(), SIGABRT) to abort thread
// - sigaction(SIGABRT) to force default signal handler
// - sigreturn() to return from signal handler
// - sigprocmask() to force signal delivery
//
static void AllowMonitor(struct Filter *f) {
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_write, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 2, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_kill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, getpid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_tkill, 0, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, gettid(), 0, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigaction, 0, 4),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIGABRT, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigreturn, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_rt_sigprocmask, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static void AllowCloneRestrict(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, CLONE_NEWNS | CLONE_PTRACE | CLONE_UNTRACED),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The first argument of sys_clone_linux() must have:
//
// - CLONE_VM (0x00000100)
// - CLONE_FS (0x00000200)
// - CLONE_FILES (0x00000400)
// - CLONE_THREAD (0x00010000)
// - CLONE_SIGHAND (0x00000800)
//
// The first argument of sys_clone_linux() must NOT have:
//
// - CLONE_NEWNS (0x00020000)
// - CLONE_PTRACE (0x00002000)
// - CLONE_UNTRACED (0x00800000)
//
static void AllowCloneThread(struct Filter *f) {
#define NEED (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SIGHAND)
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_clone, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, NEED),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, NEED, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, CLONE_NEWNS | CLONE_PTRACE | CLONE_UNTRACED),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
#undef NEED
}
// The second argument of ioctl() must be one of:
//
// - FIONREAD (0x541b)
// - FIONBIO (0x5421)
// - FIOCLEX (0x5451)
// - FIONCLEX (0x5450)
//
static void AllowIoctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 7),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONREAD, 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONBIO, 2, 0),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIOCLEX, 1, 0),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, FIONCLEX, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - SIOCATMARK (0x8905)
//
static void AllowIoctlInet(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 4),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SIOCATMARK, 0, 1),
/*L6*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L8*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of ioctl() must be one of:
//
// - TCGETS (0x5401)
// - TCSETS (0x5402)
// - TCSETSW (0x5403)
// - TCSETSF (0x5404)
// - TIOCGWINSZ (0x5413)
// - TIOCSPGRP (0x5410)
// - TIOCGPGRP (0x540f)
// - TIOCSWINSZ (0x5414)
// - TCFLSH (0x540b)
// - TCXONC (0x540a)
// - TCSBRK (0x5409)
// - TIOCSBRK (0x5427)
//
static void AllowIoctlTty(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ioctl, 0, 15),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCGETS, 11, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETS, 10, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETSW, 9, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSETSF, 8, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCGWINSZ, 7, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSPGRP, 6, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCGPGRP, 5, 0),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSWINSZ, 4, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCFLSH, 3, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCXONC, 2, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCSBRK, 1, 0),
/*L13*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TIOCSBRK, 0, 1),
/*L14*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L15*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L16*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The level argument of getsockopt/setsockopt must be one of:
//
// - IPPROTO_IP (0)
// - SOL_SOCKET (1)
// - IPPROTO_TCP (6)
// - IPPROTO_IPV6 (41)
//
// The optname argument of getsockopt/setsockopt must be one of:
//
// - TCP_NODELAY (0x01)
// - TCP_CORK (0x03)
// - TCP_KEEPIDLE (0x04)
// - TCP_KEEPINTVL (0x05)
// - SO_TYPE (0x03)
// - SO_ERROR (0x04)
// - SO_DONTROUTE (0x05)
// - SO_BROADCAST (0x06)
// - SO_REUSEPORT (0x0f)
// - SO_REUSEADDR (0x02)
// - SO_KEEPALIVE (0x09)
// - SO_RCVTIMEO (0x14)
// - SO_SNDTIMEO (0x15)
// - IP_RECVTTL (0x0c)
// - IP_RECVERR (0x0b)
// - TCP_FASTOPEN (0x17)
// - TCP_FASTOPEN_CONNECT (0x1e)
// - IPV6_V6ONLY (0x1a)
// - TCP_QUICKACK (0x0c)
//
static void AllowSockoptRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_getsockopt, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_setsockopt, 0, 29),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOL_SOCKET, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_TCP, 11, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_IP, 18, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_IPV6, 20, 23),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_TYPE, 7 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_ERROR, 6 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_BROADCAST, 5 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_REUSEPORT, 4 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_REUSEADDR, 3 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_KEEPALIVE, 2 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_RCVTIMEO, 1 + 13, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SO_SNDTIMEO, 0 + 13, 14),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_QUICKACK, 6 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_CORK, 5 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_NODELAY, 4 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_KEEPIDLE, 3 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_KEEPINTVL, 2 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_FASTOPEN, 1 + 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, TCP_FASTOPEN_CONNECT, 0 + 5, 6),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IP_RECVTTL, 1 + 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IP_RECVERR, 0 + 2, 3),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPV6_V6ONLY, 0 + 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The flags parameter of mmap() must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_NONBLOCK (0x10000)
// - MAP_HUGETLB (0x40000)
//
static void AllowMmapExec(struct Filter *f) {
// long y = (long)__privileged_end;
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mmap, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, MAP_LOCKED | MAP_NONBLOCK | MAP_HUGETLB),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 5 - 4),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mmap() may only have:
//
// - PROT_NONE
// - PROT_READ
// - PROT_WRITE
//
// The flags parameter must not have:
//
// - MAP_LOCKED (0x02000)
// - MAP_HUGETLB (0x40000)
//
static void AllowMmapNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mmap, 0, 8),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])), // flags
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, MAP_LOCKED | MAP_HUGETLB),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The prot parameter of mprotect() may only have:
//
// - PROT_NONE (0)
// - PROT_READ (1)
// - PROT_WRITE (2)
//
static void AllowMprotectNoexec(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_mprotect, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])), // prot
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(PROT_READ | PROT_WRITE)),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static void AllowOpenReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_TRUNC | O_CREAT),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_RDONLY
//
// The flags parameter of open() must not have:
//
// - O_CREAT (000000100)
// - O_TRUNC (000001000)
// - __O_TMPFILE (020000000)
//
static void AllowOpenatReadonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 9 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDONLY, 0, 8 - 4),
/*L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_TRUNC | O_CREAT),
/*L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L7*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L9*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The open() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static void AllowOpenWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_CREAT),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The open() system call is permitted only when
//
// - (flags & O_ACCMODE) == O_WRONLY
// - (flags & O_ACCMODE) == O_RDWR
//
// The openat() flags parameter must not contain
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
static void AllowOpenatWriteonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 10 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_ACCMODE),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_WRONLY, 1, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_RDWR, 0, 9 - 5),
/* L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L6*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, __O_TMPFILE | O_CREAT),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L8*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/* L9*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L10*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_open
// If the flags parameter of open() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowOpenCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_open, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_CREAT),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_CREAT, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// If the flags parameter of openat() has one of:
//
// - O_CREAT (000000100)
// - __O_TMPFILE (020000000)
//
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowOpenatCreatonly(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_openat, 0, 12 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, O_CREAT),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, O_CREAT, 7 - 4, 0),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 020200000),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 020200000, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[3])),
/* L8*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L10*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L11*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L12*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_creat
// Then the mode parameter must not have:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowCreatRestrict(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_creat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The second argument of fcntl() must be one of:
//
// - F_DUPFD (0)
// - F_DUPFD_CLOEXEC (1030)
// - F_GETFD (1)
// - F_SETFD (2)
// - F_GETFL (3)
// - F_SETFL (4)
//
static void AllowFcntlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fcntl, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_DUPFD_CLOEXEC, 4 - 3, 0),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 5, 5 - 4, 0),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
_Static_assert(F_DUPFD == 0 && F_GETFD == 1 && F_SETFD == 2 && F_GETFL == 3 && F_SETFL == 4, "This ensures that the above BPF_JGE statement will work correctly");
AppendFilter(f, PLEDGE(fragment));
}
// The second argument of fcntl() must be one of:
//
// - F_GETLK (0x05)
// - F_SETLK (0x06)
// - F_SETLKW (0x07)
// - F_OFD_GETLK (0x24)
// - F_OFD_SETLK (0x25)
// - F_OFD_SETLKW (0x26)
//
static void AllowFcntlLock(struct Filter *f) {
static const struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fcntl, 0, 9),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_GETLK, 5, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_SETLK, 4, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_SETLKW, 3, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_GETLK, 2, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_SETLK, 1, 0),
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, F_OFD_SETLKW, 0, 1),
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
};
AppendFilter(f, PLEDGE(fragment));
}
// The addr parameter of sendto() must be
//
// - NULL
//
static void AllowSendtoAddrless(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_sendto, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 0),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[4]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 5),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_INET (0x02)
// - AF_INET6 (0x0a)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (0x01)
// - SOCK_DGRAM (0x02)
//
// The protocol parameter of socket() must be one of:
//
// - 0
// - IPPROTO_ICMP (0x01)
// - IPPROTO_TCP (0x06)
// - IPPROTO_UDP (0x11)
//
static void AllowSocketInet(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socket, 0, 15 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_INET, 1, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_INET6, 0, 14 - 4),
/* L4*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(SOCK_CLOEXEC | SOCK_NONBLOCK)),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_STREAM, 1, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_DGRAM, 0, 14 - 8),
/* L8*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L9*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 3, 0),
/*L10*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_ICMP, 2, 0),
/*L11*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_TCP, 1, 0),
/*L12*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, IPPROTO_UDP, 0, 1),
/*L13*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L14*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L15*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The family parameter of socket() must be one of:
//
// - AF_UNIX (1)
// - AF_LOCAL (1)
//
// The type parameter of socket() will ignore:
//
// - SOCK_CLOEXEC (0x80000)
// - SOCK_NONBLOCK (0x00800)
//
// The type parameter of socket() must be one of:
//
// - SOCK_STREAM (1)
// - SOCK_DGRAM (2)
//
// The protocol parameter of socket() must be one of:
//
// - 0
//
static void AllowSocketUnix(struct Filter *f) {
// clang-format off
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socket, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_UNIX, 0, 10 - 3),
/* L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/* L5*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, ~(SOCK_CLOEXEC | SOCK_NONBLOCK)),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_STREAM, 1, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, SOCK_DGRAM, 0, 10 - 7),
/* L7*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
// clang-format on
AppendFilter(f, PLEDGE(fragment));
}
// The first parameter of prctl() can be any of
//
// - PR_SET_NAME (15)
// - PR_GET_NAME (16)
// - PR_GET_SECCOMP (21)
// - PR_SET_SECCOMP (22)
// - PR_SET_NO_NEW_PRIVS (38)
// - PR_CAPBSET_READ (23)
// - PR_CAPBSET_DROP (24)
//
static void AllowPrctlStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/* L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_prctl, 0, 11 - 1),
/* L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[0])),
/* L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_NAME, 6, 0),
/* L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_GET_NAME, 5, 0),
/* L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_GET_SECCOMP, 4, 0),
/* L5*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_SECCOMP, 3, 0),
/* L6*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_CAPBSET_READ, 2, 0),
/* L7*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_CAPBSET_DROP, 1, 0),
/* L8*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, PR_SET_NO_NEW_PRIVS, 0, 1),
/* L9*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L10*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L11*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#ifdef __NR_chmod
// The mode parameter of chmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowChmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_chmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
#endif
// The mode parameter of fchmod() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowFchmodNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fchmod, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[1])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 07000),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The mode parameter of fchmodat() can't have the following:
//
// - S_ISVTX (01000 sticky)
// - S_ISGID (02000 setgid)
// - S_ISUID (04000 setuid)
//
static void AllowFchmodatNobits(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_fchmodat, 0, 6 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_STMT(BPF_ALU | BPF_AND | BPF_K, S_ISVTX | S_ISGID | S_ISUID),
/*L3*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L4*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L5*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L6*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
// The new_limit parameter of prlimit() must be
//
// - NULL (0)
//
static void AllowPrlimitStdio(struct Filter *f) {
static const struct sock_filter fragment[] = {
/*L0*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_prlimit64, 0, 7 - 1),
/*L1*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2])),
/*L2*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 6 - 3),
/*L3*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(args[2]) + 4),
/*L4*/ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 0, 1),
/*L5*/ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
/*L6*/ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, OFF(nr)),
/*L7*/ /* next filter */
};
AppendFilter(f, PLEDGE(fragment));
}
static int CountUnspecial(const uint16_t *p, size_t len) {
int i, count;
for (count = i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) {
++count;
}
}
return count;
}
static void AppendPledge(struct Filter *f, //
const uint16_t *p, //
size_t len) { //
int i, j, count;
// handle ordinals which allow syscalls regardless of args
// we put in extra effort here to reduce num of bpf instrs
if ((count = CountUnspecial(p, len))) {
if (count < 256) {
for (j = i = 0; i < len; ++i) {
if (p[i] & SPECIAL) continue;
// jump to ALLOW rule below if accumulator equals ordinal
struct sock_filter fragment[] = {
BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, // instruction
p[i], // operand
count - j - 1, // jump if true displacement
j == count - 1), // jump if false displacement
};
AppendFilter(f, PLEDGE(fragment));
++j;
}
struct sock_filter fragment[] = {
BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
};
AppendFilter(f, PLEDGE(fragment));
} else {
__builtin_trap();
}
}
// handle "special" ordinals which use hand-crafted bpf
for (i = 0; i < len; ++i) {
if (!(p[i] & SPECIAL)) continue;
switch (p[i]) {
case __NR_mmap | EXEC:
AllowMmapExec(f);
break;
case __NR_mmap | NOEXEC:
AllowMmapNoexec(f);
break;
case __NR_mprotect | NOEXEC:
AllowMprotectNoexec(f);
break;
#ifdef __NR_chmod
case __NR_chmod | NOBITS:
AllowChmodNobits(f);
break;
#endif
case __NR_fchmod | NOBITS:
AllowFchmodNobits(f);
break;
case __NR_fchmodat | NOBITS:
AllowFchmodatNobits(f);
break;
case __NR_prctl | STDIO:
AllowPrctlStdio(f);
break;
#ifdef __NR_open
case __NR_open | CREATONLY:
AllowOpenCreatonly(f);
break;
#endif
case __NR_openat | CREATONLY:
AllowOpenatCreatonly(f);
break;
#ifdef __NR_open
case __NR_open | READONLY:
AllowOpenReadonly(f);
break;
#endif
case __NR_openat | READONLY:
AllowOpenatReadonly(f);
break;
#ifdef __NR_open
case __NR_open | WRITEONLY:
AllowOpenWriteonly(f);
break;
#endif
case __NR_openat | WRITEONLY:
AllowOpenatWriteonly(f);
break;
case __NR_getsockopt | RESTRICT:
case __NR_setsockopt | RESTRICT:
AllowSockoptRestrict(f);
break;
#ifdef __NR_creat
case __NR_creat | RESTRICT:
AllowCreatRestrict(f);
break;
#endif
case __NR_fcntl | STDIO:
AllowFcntlStdio(f);
break;
case __NR_fcntl | LOCK:
AllowFcntlLock(f);
break;
case __NR_ioctl | RESTRICT:
AllowIoctlStdio(f);
break;
case __NR_ioctl | TTY:
AllowIoctlTty(f);
break;
case __NR_ioctl | INET:
AllowIoctlInet(f);
break;
case __NR_socket | INET:
AllowSocketInet(f);
break;
case __NR_socket | UNIX:
AllowSocketUnix(f);
break;
case __NR_sendto | ADDRLESS:
AllowSendtoAddrless(f);
break;
case __NR_clone | RESTRICT:
AllowCloneRestrict(f);
break;
case __NR_clone | THREAD:
AllowCloneThread(f);
break;
case __NR_prlimit64 | STDIO:
AllowPrlimitStdio(f);
break;
case __NR_kill | SELF:
AllowKillSelf(f);
break;
case __NR_tgkill | SELF:
AllowTgkillSelf(f);
break;
default:
__builtin_trap();
}
}
}
/**
* Installs SECCOMP BPF filter on Linux thread.
*
* @param ipromises is inverted integer bitmask of pledge() promises
* @return 0 on success, or negative error number on error
*/
int sys_pledge_linux(unsigned long ipromises, int mode) {
struct Filter f;
int i, e, rc = -1;
struct sock_filter sf[1] = {BPF_STMT(BPF_RET | BPF_K, 0)};
CheckLargeStackAllocation(&f, sizeof(f));
f.n = 0;
// set up the seccomp filter
AppendFilter(&f, PLEDGE(kPledgeStart));
if (ipromises == -1) {
// if we're pledging empty string, then avoid triggering a sigsys
// when _Exit() gets called since we need to fallback to _Exit1()
AppendFilter(&f, PLEDGE(kFilterIgnoreExitGroup));
}
AppendPledge(&f, PLEDGE(kPledgeDefault));
for (i = 0; i < ARRAYLEN(kPledge); ++i) {
if (~ipromises & (1ul << i)) {
if (kPledge[i].len) {
AppendPledge(&f, kPledge[i].syscalls, kPledge[i].len);
} else {
__builtin_trap();
}
}
}
// now determine what we'll do on sandbox violations
if (mode & PLEDGE_STDERR_LOGGING) {
// trapping mode
//
// if we haven't pledged exec, then we can monitor SIGSYS
// and print a helpful error message when things do break
// to avoid tls / static memory, we embed mode within bpf
MonitorSigSys();
AllowMonitor(&f);
sf[0].k = SECCOMP_RET_TRAP | (mode & SECCOMP_RET_DATA);
AppendFilter(&f, PLEDGE(sf));
} else {
// non-trapping mode
//
// our sigsys error message handler can't be inherited across
// execve() boundaries so if you've pledged exec then that'll
// likely cause a SIGSYS in your child after the exec happens
switch (mode & PLEDGE_PENALTY_MASK) {
case PLEDGE_PENALTY_KILL_THREAD:
sf[0].k = SECCOMP_RET_KILL_THREAD;
break;
case PLEDGE_PENALTY_KILL_PROCESS:
sf[0].k = SECCOMP_RET_KILL_PROCESS;
break;
case PLEDGE_PENALTY_RETURN_EPERM:
sf[0].k = SECCOMP_RET_ERRNO | EPERM;
break;
default:
return -EINVAL;
}
AppendFilter(&f, PLEDGE(sf));
}
// drop privileges
//
// PR_SET_SECCOMP (Linux 2.6.23+) will refuse to work if
// PR_SET_NO_NEW_PRIVS (Linux 3.5+) wasn't called so we punt the error
// detection to the seccomp system call below.
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
// register our seccomp filter with the kernel
struct sock_fprog sandbox = {.len = f.n, .filter = f.p};
rc = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &sandbox, 0, 0);
// the EINVAL error could mean a lot of things. it could mean the bpf
// code is broken. it could also mean we're running on RHEL5 which
// doesn't have SECCOMP support. since we don't consider lack of
// system support for security to be an error, we distinguish these
// two cases by running a simpler SECCOMP operation.
if (rc < 0 && //
errno == EINVAL && //
prctl(PR_GET_SECCOMP, 0, 0, 0, 0) < 0 && //
errno == EINVAL) {
rc = 0; // -ENOSYS
}
return rc;
}
| 69,089 | 2,143 | jart/plegde | false |
pledge/libc/calls/landlock_add_rule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_add_rule(int, enum landlock_rule_type, const void *, uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Adds new rule to Landlock ruleset.
*
* @error ENOSYS if Landlock isn't supported
* @error EPERM if Landlock supported but SECCOMP BPF shut it down
* @error EOPNOTSUPP if Landlock supported but disabled at boot time
* @error EINVAL if flags not 0, or inconsistent access in the rule,
* i.e. landlock_path_beneath_attr::allowed_access is not a subset
* of the ruleset handled accesses
* @error ENOMSG empty allowed_access
* @error EBADF `fd` is not a file descriptor for current thread, or
* member of `rule_attr` is not a file descriptor as expected
* @error EBADFD `fd` is not a ruleset file descriptor, or a member
* of `rule_attr` is not the expected file descriptor type
* @error EPERM `fd` has no write access to the underlying ruleset
* @error EFAULT `rule_attr` inconsistency
*/
int landlock_add_rule(int fd, enum landlock_rule_type rule_type,
const void *rule_attr, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_add_rule, fd, rule_type, rule_attr, flags);
/*KERNTRACE("landlock_add_rule(%d, %d, %p, %#x) â %d% m", fd, rule_type,
rule_attr, flags, rc);*/
return rc;
}
| 3,208 | 54 | jart/plegde | false |
pledge/libc/calls/pledge.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include <errno.h>
#include <unistd.h>
#include "libc/calls/calls.h"
#include "libc/calls/pledge.internal.h"
#include "libc/dce.h"
#include "libc/intrin/promises.internal.h"
#include "libc/runtime/runtime.h"
/**
* Permits system operations, e.g.
*
* __pledge_mode = PLEDGE_PENALTY_KILL_PROCESS | PLEDGE_STDERR_LOGGING;
* if (pledge("stdio rfile tty", 0)) {
* perror("pledge");
* exit(1);
* }
*
* Pledging causes most system calls to become unavailable. Your system
* call policy is enforced by the kernel (which means it can propagate
* across execve() if permitted). Root access is not required. Support
* is limited to Linux 2.6.23+ (c. RHEL6) and OpenBSD. If your kernel
* isn't supported, then pledge() will return 0 and do nothing rather
* than raising ENOSYS. We don't consider lack of system support to be
* an error, because the specified operations will be permitted.
*
* The promises you give pledge() define which system calls are allowed.
* Error messages are logged when sandbox violations occur, but how that
* happens depends on the `mode` parameter (see below).
*
* Timing is everything with pledge. It's designed to be a voluntary
* self-imposed security model. That works best when programs perform
* permission-hungry operations (e.g. calling GetSymbolTable) towards
* the beginning of execution, and then relinquish privilege afterwards
* by calling pledge(). Here's an example of where that matters. Your
* Cosmopolitan C Library needs to code morph your executable in memory
* once you start using threads. But that's only possible to do if you
* used the `prot_exec` promise. So the right thing to do here, is to
* call __enable_threads() before calling pledge() to force it early.
*
* __enable_threads();
* ShowCrashReports();
* pledge("...", 0);
*
* By default exit() is allowed. This is useful for processes that
* perform pure computation and interface with the parent via shared
* memory. On Linux we mean sys_exit (_Exit1), not sys_exit_group
* (_Exit). The difference is effectively meaningless, since _Exit()
* will attempt both. All it means is that, if you're using threads,
* then a `pledge("", 0)` thread can't kill all your threads unless you
* `pledge("stdio", 0)`.
*
* Once pledge is in effect, the chmod functions (if allowed) will not
* permit the sticky/setuid/setgid bits to change. Linux will EPERM here
* and OpenBSD should ignore those three bits rather than crashing.
*
* User and group IDs can't be changed once pledge is in effect. OpenBSD
* should ignore chown without crashing; whereas Linux will just EPERM.
*
* Using pledge is irreversible. On Linux it causes PR_SET_NO_NEW_PRIVS
* to be set on your process; however, if "id" or "recvfd" are allowed
* then then they theoretically could permit the gaining of some new
* privileges. You may call pledge() multiple times if "stdio" is
* allowed. In that case, the process can only move towards a more
* restrictive state.
*
* pledge() can't filter filesystem paths. See unveil() which lets you
* do that. pledge() also can't do address firewalling. For example if
* you use the `inet` promise then your process will be able to talk to
* *every* internet address including public ones.
*
* `promises` is a string that may include any of the following groups
* delimited by spaces.
*
* - "stdio" allows exit, close, dup, dup2, dup3, fchdir, fstat, fsync,
* fdatasync, ftruncate, getdents, getegid, getrandom, geteuid,
* getgid, getgroups, times, getrusage, getitimer, getpgid, getpgrp,
* getpid, getppid, getresgid, getresuid, getrlimit, getsid, wait4,
* gettimeofday, getuid, lseek, madvise, brk, arch_prctl, uname,
* set_tid_address, clock_getres, clock_gettime, clock_nanosleep,
* mremap, mmap, (PROT_EXEC and weird flags aren't allowed), mprotect
* (PROT_EXEC isn't allowed), msync, sync_file_range, migrate_pages,
* munmap, nanosleep, pipe, pipe2, read, readv, pread, recv, poll,
* recvfrom, preadv, write, writev, pwrite, pwritev, select, pselect6,
* copy_file_range, sendfile, tee, splice, vmsplice, alarm, pause,
* send, sendto (only if addr is null), setitimer, shutdown, sigaction
* (but SIGSYS is forbidden), sigaltstack, sigprocmask, sigreturn,
* sigsuspend, umask, mincore, socketpair, ioctl(FIONREAD),
* ioctl(FIONBIO), ioctl(FIOCLEX), ioctl(FIONCLEX), fcntl(F_GETFD),
* fcntl(F_SETFD), fcntl(F_GETFL), fcntl(F_SETFL), sched_yield,
* epoll_create, epoll_create1, epoll_ctl, epoll_wait, epoll_pwait,
* epoll_pwait2, clone(CLONE_THREAD), futex, set_robust_list,
* get_robust_list, setaffinity, sigpending.
*
* - "rpath" (read-only path ops) allows chdir, getcwd, open(O_RDONLY),
* openat(O_RDONLY), stat, fstat, lstat, fstatat, access, faccessat,
* faccessat2, readlink, readlinkat, statfs, fstatfs.
*
* - "wpath" (write path ops) allows getcwd, open(O_WRONLY),
* openat(O_WRONLY), stat, fstat, lstat, fstatat, access, faccessat,
* faccessat2, readlink, readlinkat, chmod, fchmod, fchmodat.
*
* - "cpath" (create path ops) allows open(O_CREAT), openat(O_CREAT),
* rename, renameat, renameat2, link, linkat, symlink, symlinkat,
* unlink, rmdir, unlinkat, mkdir, mkdirat.
*
* - "dpath" (create special path ops) allows mknod, mknodat, mkfifo.
*
* - "flock" allows flock, fcntl(F_GETLK), fcntl(F_SETLK),
* fcntl(F_SETLKW).
*
* - "tty" allows ioctl(TIOCGWINSZ), ioctl(TCGETS), ioctl(TCSETS),
* ioctl(TCSETSW), ioctl(TCSETSF).
*
* - "recvfd" allows recvmsg and recvmmsg.
*
* - "recvfd" allows sendmsg and sendmmsg.
*
* - "fattr" allows chmod, fchmod, fchmodat, utime, utimes, futimens,
* utimensat.
*
* - "inet" allows socket(AF_INET), listen, bind, connect, accept,
* accept4, getpeername, getsockname, setsockopt, getsockopt, sendto.
*
* - "unix" allows socket(AF_UNIX), listen, bind, connect, accept,
* accept4, getpeername, getsockname, setsockopt, getsockopt.
*
* - "dns" allows socket(AF_INET), sendto, recvfrom, connect.
*
* - "proc" allows fork, vfork, clone, kill, tgkill, getpriority,
* setpriority, prlimit, setrlimit, setpgid, setsid.
*
* - "id" allows setuid, setreuid, setresuid, setgid, setregid,
* setresgid, setgroups, prlimit, setrlimit, getpriority, setpriority,
* setfsuid, setfsgid.
*
* - "settime" allows settimeofday and clock_adjtime.
*
* - "exec" allows execve, execveat. Note that `exec` alone might not be
* enough by itself to let your executable be executed. For dynamic,
* interpreted, and ape binaries, you'll usually want `rpath` and
* `prot_exec` too. With APE it's possible to work around this
* requirement, by "assimilating" your binaries beforehand. See the
* assimilate.com program and `--assimilate` flag which can be used to
* turn APE binaries into static native binaries.
*
* - "prot_exec" allows mmap(PROT_EXEC) and mprotect(PROT_EXEC). This is
* needed to (1) code morph mutexes in __enable_threads(), and it's
* needed to (2) launch non-static or non-native executables, e.g.
* non-assimilated APE binaries, or dynamic-linked executables.
*
* - "unveil" allows unveil() to be called, as well as the underlying
* landlock_create_ruleset, landlock_add_rule, landlock_restrict_self
* calls on Linux.
*
* - "vminfo" OpenBSD defines this for programs like `top`. On Linux,
* this is a placeholder group that lets tools like pledge.com check
* `__promises` and automatically unveil() a subset of files top would
* need, e.g. /proc/stat, /proc/meminfo.
*
* - "tmppath" allows unlink, unlinkat, and lstat. This is mostly a
* placeholder group for pledge.com, which reads the `__promises`
* global to determine if /tmp and $TMPPATH should be unveiled.
*
* `execpromises` only matters if "exec" is specified in `promises`. In
* that case, this specifies the promises that'll apply once execve()
* happens. If this is NULL then the default is used, which is
* unrestricted. OpenBSD allows child processes to escape the sandbox
* (so a pledged OpenSSH server process can do things like spawn a root
* shell). Linux however requires monotonically decreasing privileges.
* This function will will perform some validation on Linux to make sure
* that `execpromises` is a subset of `promises`. Your libc wrapper for
* execve() will then apply its SECCOMP BPF filter later. Since Linux
* has to do this before calling sys_execve(), the executed process will
* be weakened to have execute permissions too.
*
* `__pledge_mode` is available to improve the experience of pledge() on
* Linux. It should specify one of the following penalties:
*
* - `PLEDGE_PENALTY_KILL_THREAD` causes the violating thread to be
* killed. This is the default on Linux. It's effectively the same as
* killing the process, since redbean has no threads. The termination
* signal can't be caught and will be either `SIGSYS` or `SIGABRT`.
* Consider enabling stderr logging below so you'll know why your
* program failed. Otherwise check the system log.
*
* - `PLEDGE_PENALTY_KILL_PROCESS` causes the process and all its
* threads to be killed. This is always the case on OpenBSD.
*
* - `PLEDGE_PENALTY_RETURN_EPERM` causes system calls to just return an
* `EPERM` error instead of killing. This is a gentler solution that
* allows code to display a friendly warning. Please note this may
* lead to weird behaviors if the software being sandboxed is lazy
* about checking error results.
*
* `mode` may optionally bitwise or the following flags:
*
* - `PLEDGE_STDERR_LOGGING` enables friendly error message logging
* letting you know which promises are needed whenever violations
* occur. Without this, violations will be logged to `dmesg` on Linux
* if the penalty is to kill the process. You would then need to
* manually look up the system call number and then cross reference it
* with the cosmopolitan libc pledge() documentation. You can also use
* `strace -ff` which is easier. This is ignored OpenBSD, which
* already has a good system log. Turning on stderr logging (which
* uses SECCOMP trapping) also means that the `WTERMSIG()` on your
* killed processes will always be `SIGABRT` on both Linux and
* OpenBSD. Otherwise, Linux prefers to raise `SIGSYS`. Enabling this
* option might not be a good idea if you're pledging `exec` because
* subprocesses can't inherit the `SIGSYS` handler this installs.
*
* @return 0 on success, or -1 w/ errno
* @raise EINVAL if `execpromises` on Linux isn't a subset of `promises`
* @raise EINVAL if `promises` allows exec and `execpromises` is null
* @threadsafe
* @vforksafe
*/
int pledge(const char *promises, const char *execpromises) {
int e, rc;
unsigned long ipromises, iexecpromises;
if (!ParsePromises(promises, &ipromises) &&
!ParsePromises(execpromises, &iexecpromises)) {
// copy exec and execnative from promises to execpromises
iexecpromises = ~(~iexecpromises | (~ipromises & (1ul << PROMISE_EXEC)));
// if bits are missing in execpromises that exist in promises
// then execpromises wouldn't be a monotonic access reduction
// this check only matters when exec / execnative are allowed
if ((ipromises & ~iexecpromises) && (~ipromises & (1ul << PROMISE_EXEC))) {
errno = EINVAL;
rc = -1;
} else {
rc = sys_pledge_linux(ipromises, __pledge_mode);
if (rc > -4096u) errno = -rc, rc = -1;
}
if (!rc && (getpid() == gettid())) {
__promises = ipromises;
__execpromises = iexecpromises;
}
} else {
errno = EINVAL;
rc = -1;
}
return rc;
}
| 13,517 | 262 | jart/plegde | false |
pledge/libc/calls/landlock.h | #ifndef PLEDGE_LIBC_CALLS_LANDLOCK_H_
#define PLEDGE_LIBC_CALLS_LANDLOCK_H_
#include <linux/landlock.h>
#include <stdint.h>
#include <stddef.h>
/**
* Allow renaming or linking file to a different directory.
*
* @see https://lore.kernel.org/r/[email protected]
* @see https://docs.kernel.org/userspace-api/landlock.html
* @note ABI 2+
*/
#ifndef LANDLOCK_ACCESS_FS_REFER
#define LANDLOCK_ACCESS_FS_REFER 0x2000ul
#endif
/**
* Control file truncation.
*
* @see https://lore.kernel.org/all/[email protected]/
* @see https://docs.kernel.org/userspace-api/landlock.html
* @note ABI 3+
*/
#ifndef LANDLOCK_ACCESS_FS_TRUNCATE
#define LANDLOCK_ACCESS_FS_TRUNCATE 0x4000ul
#endif
int landlock_restrict_self(int, uint32_t);
int landlock_add_rule(int, enum landlock_rule_type, const void *, uint32_t);
int landlock_create_ruleset(const struct landlock_ruleset_attr *, size_t,
uint32_t);
#endif
| 978 | 36 | jart/plegde | false |
pledge/libc/calls/landlock_create_ruleset.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_create_ruleset(const struct landlock_ruleset_attr *, size_t,
uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Create new Landlock filesystem sandboxing ruleset.
*
* You may also use this function to query the current ABI version:
*
* landlock_create_ruleset(0, 0, LANDLOCK_CREATE_RULESET_VERSION);
*
* @return close exec file descriptor for new ruleset
* @error ENOSYS if not running Linux 5.13+
* @error EPERM if pledge() or seccomp bpf shut it down
* @error EOPNOTSUPP Landlock supported but disabled at boot
* @error EINVAL unknown flags, or unknown access, or too small size
* @error E2BIG attr or size inconsistencies
* @error EFAULT attr or size inconsistencies
* @error ENOMSG empty landlock_ruleset_attr::handled_access_fs
*/
int landlock_create_ruleset(const struct landlock_ruleset_attr *attr,
size_t size, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_create_ruleset, attr, size, flags);
//KERNTRACE("landlock_create_ruleset(%p, %'zu, %#x) â %d% m", attr, size, flags,
// rc);
return rc;
}
| 3,057 | 54 | jart/plegde | false |
pledge/libc/calls/syscall_support-sysv.internal.h | #ifndef PLEDGE_LIBC_CALLS_SYSCALL_SUPPORT_SYSV_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_SYSCALL_SUPPORT_SYSV_INTERNAL_H_
#include <stdbool.h>
bool is_linux_2_6_23(void);
#endif
| 177 | 9 | jart/plegde | false |
pledge/libc/calls/landlock_restrict_self.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/landlock.h"
/*
#include "libc/intrin/strace.internal.h"
int sys_landlock_restrict_self(int, uint32_t);
*/
#include <sys/syscall.h>
#include <unistd.h>
/**
* Enforces Landlock ruleset on calling thread.
*
* @error EOPNOTSUPP if Landlock supported but disabled at boot time
* @error EINVAL if flags isn't zero
* @error EBADF if `fd` isn't file descriptor for the current thread
* @error EBADFD if `fd` is not a ruleset file descriptor
* @error EPERM if `fd` has no read access to underlying ruleset, or
* current thread is not running with no_new_privs, or it doesnât
* have CAP_SYS_ADMIN in its namespace
* @error E2BIG if the maximum number of stacked rulesets is
* reached for current thread
*/
int landlock_restrict_self(int fd, uint32_t flags) {
int rc;
rc = syscall(__NR_landlock_restrict_self, fd, flags);
//KERNTRACE("landlock_create_ruleset(%d, %#x) â %d% m", fd, flags, rc);
return rc;
}
| 2,792 | 48 | jart/plegde | false |
pledge/libc/calls/pledge.internal.h | #ifndef PLEDGE_LIBC_CALLS_PLEDGE_INTERNAL_H_
#define PLEDGE_LIBC_CALLS_PLEDGE_INTERNAL_H_
#include "libc/calls/pledge.h"
#include "libc/intrin/promises.internal.h"
#include <stdint.h>
#include <stddef.h>
struct Pledges {
const char *name;
const uint16_t *syscalls;
const size_t len;
};
extern const struct Pledges kPledge[PROMISE_LEN_];
int sys_pledge_linux(unsigned long, int);
int ParsePromises(const char *, unsigned long *);
#endif
| 447 | 21 | jart/plegde | false |
pledge/libc/intrin/safemacros.internal.h | #ifndef PLEDGE_LIBC_INTRIN_SAFEMACROS_INTERNAL_H_
#define PLEDGE_LIBC_INTRIN_SAFEMACROS_INTERNAL_H_
#include "libc/integral/c.h"
#define max(x, y) \
({ \
autotype(x) MaxX = (x); \
autotype(y) MaxY = (y); \
MaxX > MaxY ? MaxX : MaxY; \
})
#endif
| 309 | 14 | jart/plegde | false |
pledge/libc/intrin/kprintf.h | #ifndef PLEDGE_LIBC_INTRIN_KPRINTF_H_
#define PLEDGE_LIBC_INTRIN_KPRINTF_H_
#include <stdio.h>
#define kprintf printf
#define ksnprintf snprintf
#endif
| 155 | 10 | jart/plegde | false |
pledge/libc/intrin/promises.internal.h | #ifndef PLEDGE_LIBC_INTRIN_PROMISES_INTERNAL_H_
#define PLEDGE_LIBC_INTRIN_PROMISES_INTERNAL_H_
#define PROMISE_STDIO 0
#define PROMISE_RPATH 1
#define PROMISE_WPATH 2
#define PROMISE_CPATH 3
#define PROMISE_DPATH 4
#define PROMISE_FLOCK 5
#define PROMISE_FATTR 6
#define PROMISE_INET 7
#define PROMISE_UNIX 8
#define PROMISE_DNS 9
#define PROMISE_TTY 10
#define PROMISE_RECVFD 11
#define PROMISE_PROC 12
#define PROMISE_EXEC 13
#define PROMISE_ID 14
#define PROMISE_UNVEIL 15
#define PROMISE_SENDFD 16
#define PROMISE_SETTIME 17
#define PROMISE_PROT_EXEC 18
#define PROMISE_VMINFO 19
#define PROMISE_TMPPATH 20
#define PROMISE_CHOWN 21
#define PROMISE_LEN_ 22
extern unsigned long __promises;
extern unsigned long __execpromises;
#endif
| 833 | 32 | jart/plegde | false |
pledge/libc/intrin/pthread_setcancelstate.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/blockcancel.internal.h"
/*
#include "libc/errno.h"
#include "libc/thread/posixthread.internal.h"
#include "libc/thread/thread.h"
#include "libc/thread/tls.h"
*/
#include <pthread.h>
void pthread_allow_cancellations(int oldstate) {
pthread_setcancelstate(oldstate, 0);
}
int pthread_block_cancellations(void) {
int oldstate;
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
return oldstate;
}
| 2,270 | 38 | jart/plegde | false |
pledge/libc/intrin/promises.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2022 Justine Alexandra Roberts Tunney â
â â
â Permission to use, copy, modify, and/or distribute this software for â
â any purpose with or without fee is hereby granted, provided that the â
â above copyright notice and this permission notice appear in all copies. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/pledge.h"
#include "libc/intrin/promises.internal.h"
// XXX: should be inherited thread local
// see also sys_pledge_linux() which is 100% pure
int __pledge_mode;
unsigned long __promises;
unsigned long __execpromises;
| 2,082 | 27 | jart/plegde | false |
pledge/libc/intrin/likely.h | #ifndef PLEDGE_LIBC_INTRIN_LIKELY_H_
#define PLEDGE_LIBC_INTRIN_LIKELY_H_
#ifndef __STRICT_ANSI__
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define LIKELY(x)
#define UNLIKELY(x)
#endif
#endif
| 252 | 13 | jart/plegde | false |
pledge/libc/intrin/bits.h | #ifndef PLEDGE_LIBC_INTRIN_BITS_H_
#define PLEDGE_LIBC_INTRIN_BITS_H_
#include <stdint.h>
#ifdef __STRICT_ANSI__
#define READ32LE(S) \
((uint32_t)(255 & (S)[3]) << 030 | (uint32_t)(255 & (S)[2]) << 020 | \
(uint32_t)(255 & (S)[1]) << 010 | (uint32_t)(255 & (S)[0]) << 000)
#define READ64LE(S) \
((uint64_t)(255 & (S)[7]) << 070 | (uint64_t)(255 & (S)[6]) << 060 | \
(uint64_t)(255 & (S)[5]) << 050 | (uint64_t)(255 & (S)[4]) << 040 | \
(uint64_t)(255 & (S)[3]) << 030 | (uint64_t)(255 & (S)[2]) << 020 | \
(uint64_t)(255 & (S)[1]) << 010 | (uint64_t)(255 & (S)[0]) << 000)
#else /* gcc needs help knowing above are mov if s isn't a variable */
#define READ32LE(S) \
({ \
const uint8_t *Ptr = (const uint8_t *)(S); \
((uint32_t)Ptr[3] << 030 | (uint32_t)Ptr[2] << 020 | \
(uint32_t)Ptr[1] << 010 | (uint32_t)Ptr[0] << 000); \
})
#define READ64LE(S) \
({ \
const uint8_t *Ptr = (const uint8_t *)(S); \
((uint64_t)Ptr[7] << 070 | (uint64_t)Ptr[6] << 060 | \
(uint64_t)Ptr[5] << 050 | (uint64_t)Ptr[4] << 040 | \
(uint64_t)Ptr[3] << 030 | (uint64_t)Ptr[2] << 020 | \
(uint64_t)Ptr[1] << 010 | (uint64_t)Ptr[0] << 000); \
})
#endif
#endif
| 1,497 | 33 | jart/plegde | false |
pledge/libc/integral/c.h | #ifndef PLEDGE_LIBC_INTEGRAL_C_H_
#define PLEDGE_LIBC_INTEGRAL_C_H_
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#ifndef __STRICT_ANSI__
#define pureconst __attribute__((__const__))
#else
#define pureconst
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__nonnull__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 403)
#define paramsnonnull(opt_1idxs) __attribute__((__nonnull__ opt_1idxs))
#else
#define paramsnonnull(opt_1idxs)
#endif
#define libcesque dontthrow nocallback
#if defined(__cplusplus) && !defined(__STRICT_ANSI__) && \
(__has_attribute(dontthrow) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 303)
#define dontthrow __attribute__((__nothrow__))
#elif defined(_MSC_VER)
#define dontthrow __declspec(nothrow)
#else
#define dontthrow
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__leaf__) || \
(!defined(__llvm__) && \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 406))
#define nocallback __attribute__((__leaf__))
#else
#define nocallback
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__sentinel__) || __GNUC__ + 0 >= 4)
#define nullterminated(x) __attribute__((__sentinel__ x))
#else
#define nullterminated(x)
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__malloc__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define returnspointerwithnoaliases __attribute__((__malloc__))
#elif defined(_MSC_VER)
#define returnspointerwithnoaliases __declspec(allocator)
#else
#define returnspointerwithnoaliases
#endif
#if !defined(__STRICT_ANSI__) && \
((__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 304 || \
__has_attribute(__warn_unused_result__))
#define dontdiscard __attribute__((__warn_unused_result__))
#else
#define dontdiscard
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__returns_nonnull__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define returnsnonnull __attribute__((__returns_nonnull__))
#else
#define returnsnonnull
#endif
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__alloc_size__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409)
#define attributeallocsize(x) __attribute__((__alloc_size__ x))
#else
#define attributeallocsize(x)
#endif
#ifdef __cplusplus
#define forceinline inline
#else
#if !defined(__STRICT_ANSI__) && \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 302
#if (__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 403 || \
!defined(__cplusplus) || \
(defined(__clang__) && \
(defined(__GNUC_STDC_INLINE__) || defined(__GNUC_GNU_INLINE__)))
#if defined(__GNUC_STDC_INLINE__) || defined(__cplusplus)
#define forceinline \
static __inline __attribute__((__always_inline__, __gnu_inline__, \
__no_instrument_function__, __unused__))
#else
#define forceinline \
static __inline __attribute__((__always_inline__, \
__no_instrument_function__, __unused__))
#endif /* __GNUC_STDC_INLINE__ */
#endif /* GCC >= 4.3 */
#elif defined(_MSC_VER)
#define forceinline __forceinline
#else
#define forceinline static inline
#endif /* !ANSI && GCC >= 3.2 */
#endif /* __cplusplus */
#define strlenesque libcesque nosideeffect paramsnonnull()
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__pure__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 296)
#define nosideeffect __attribute__((__pure__))
#else
#define nosideeffect
#endif
#if __cplusplus + 0 >= 201103L
#define autotype(x) auto
#elif ((__has_builtin(auto_type) || defined(__llvm__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 409) && \
!defined(__chibicc__))
#define autotype(x) __auto_type
#else
#define autotype(x) typeof(x)
#endif
#define privileged
#ifndef __STRICT_ANSI__
#define thatispacked __attribute__((__packed__))
#else
#define thatispacked
#endif
#define notpossible __builtin_trap()
#if !defined(__STRICT_ANSI__) && \
(__has_attribute(__noreturn__) || \
(__GNUC__ + 0) * 100 + (__GNUC_MINOR__ + 0) >= 208)
#define wontreturn __attribute__((__noreturn__))
#else
#define wontreturn
#endif
#endif
| 4,386 | 149 | jart/plegde | false |
pledge/libc/sysv/calls/ioprio_set.c | #include "libc/calls/calls.h"
#include <sys/syscall.h>
#include <unistd.h>
int ioprio_set(int which, int who, int ioprio) {
return syscall(__NR_ioprio_set, which, who, ioprio);
}
| 183 | 9 | jart/plegde | false |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 45