summaryrefslogtreecommitdiff
path: root/lbexec.c
blob: 42e3b6adb608d4f9ce14b0a5d77734ea293cb528 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*
 * lbexec.c - per-command Landlock exec wrapper
 * https://rawnix.org
 *
 * Copyright (c) 2025 zorz@gmx.com
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Usage: lbexec [-p standard|cargo] <command> [args...]
 *
 * Called from build.sh when lockbox=(make meson ninja cargo ...) is set.
 * mkpkg rewrites matching build commands as:
 *   lbexec <command>           (standard profile)
 *   lbexec -p cargo <command>  (cargo profile)
 *
 * Profiles:
 *   standard  full base toolchain + declared deps (default)
 *   cargo     base + declared deps, /etc/ssl only, restricted
 *             $CARGO_HOME, CLONE_NEWNET
 *
 * Environment (exported by mkpkg into build.sh):
 *   MKPKG_DEPENDS       space-separated runtime deps
 *   MKPKG_MAKEDEPENDS   space-separated build-time deps
 *   MKPKG_WORK_DIR      build work directory       (RW)
 *   SRC                 work/src                   (RW)
 *   PKG                 work/pkg                   (RW)
 *   PKGMK_SOURCE_DIR    port directory             (RW)
 *   CARGO_HOME          cargo home (cargo profile) (RO, selective)
 *
 * The parent shell is not restricted -- only the child process and its
 * children run under Landlock.
 */

/* _GNU_SOURCE for unshare() and CLONE_NEWNET */
#define _GNU_SOURCE

#include "lockbox_common.h"
#include "mkpkg.h"

#include <errno.h>
#include <net/if.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <unistd.h>

/* ── Network namespace isolation ─────────────────────────────────────── */

/*
 * Move into a new network namespace so the child process has no external
 * network connectivity. Loopback is brought up so localhost still works.
 *
 * Requires root (or CONFIG_USER_NS for unprivileged unshare).
 * Degrades silently — the caller always continues.
 */
static void try_unshare_net(void)
{
    struct ifreq ifr;
    int          sock;

    if (unshare(CLONE_NEWNET) != 0)
        return;   /* no capability or no kernel support — degrade silently */

    /* bring loopback up so localhost resolution still works */
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
        return;

    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, "lo", IFNAMSIZ - 1);
    if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
        ifr.ifr_flags |= IFF_UP | IFF_LOOPBACK;
        ioctl(sock, SIOCSIFFLAGS, &ifr);
    }
    close(sock);

    fprintf(stderr, "mkpkg: lbexec: network namespace isolated\n");
}

/* ── Parse space-separated env var into names array ──────────────────── */

static int parse_env_list(const char *varname, char **out, int out_max)
{
    const char *val = getenv(varname);
    char       *buf, *tok, *saveptr;
    int         count = 0;

    if (!val || !*val) return 0;

    buf = strdup(val);
    if (!buf) return 0;

    tok = strtok_r(buf, " \t", &saveptr);
    while (tok && count < out_max) {
        out[count] = strdup(tok);
        if (out[count]) count++;
        tok = strtok_r(NULL, " \t", &saveptr);
    }
    free(buf);
    return count;
}

/* ── main ────────────────────────────────────────────────────────────── */

int main(int argc, char *argv[])
{
    int                abi, ruleset_fd;
    uint64_t           all_rw;
    lockbox_profile_t  profile = LOCKBOX_PROFILE_STANDARD;
    int                cmd_start;
    int                dep_count;
    char              *dep_names[256];
    struct landlock_ruleset_attr rs_attr = {0};

    /* parse optional -p <profile> */
    cmd_start = 1;
    if (argc >= 3 && strcmp(argv[1], "-p") == 0) {
        if (strcmp(argv[2], "cargo") == 0)
            profile = LOCKBOX_PROFILE_CARGO;
        else if (strcmp(argv[2], "standard") == 0)
            profile = LOCKBOX_PROFILE_STANDARD;
        else {
            fprintf(stderr, "lbexec: unknown profile '%s'\n", argv[2]);
            return 1;
        }
        cmd_start = 3;
    }

    if (argc <= cmd_start) {
        fprintf(stderr, "usage: lbexec [-p standard|cargo] <command> [args...]\n");
        return 1;
    }

    /* probe Landlock ABI */
    abi = (int)syscall(SYS_landlock_create_ruleset,
                       (void *)NULL, 0, LANDLOCK_CREATE_RULESET_VERSION);
    if (abi < 1) {
        fprintf(stderr,
                "mkpkg: error: lbexec: Landlock not available (abi=%d): %s\n",
                abi, strerror(errno));
        return 1;
    }
    fprintf(stderr, "mkpkg: lbexec: Landlock ABI v%d, profile: %s\n",
            abi, profile == LOCKBOX_PROFILE_CARGO ? "cargo" : "standard");

    all_rw = ACCESS_RW;
    if (abi < 3)
        all_rw &= ~(uint64_t)LANDLOCK_ACCESS_FS_TRUNCATE;

    /* create ruleset */
    rs_attr.handled_access_fs = ACCESS_RO | all_rw;
    ruleset_fd = ll_create_ruleset(&rs_attr, sizeof(rs_attr), 0);
    if (ruleset_fd < 0) {
        fprintf(stderr, "mkpkg: error: lbexec: create_ruleset: %s\n",
                strerror(errno));
        return 1;
    }

    /* collect declared deps from environment */
    dep_count  = 0;
    dep_count += parse_env_list("MKPKG_MAKEDEPENDS",
                                dep_names + dep_count, 256 - dep_count);
    dep_count += parse_env_list("MKPKG_DEPENDS",
                                dep_names + dep_count, 256 - dep_count);

    if (profile == LOCKBOX_PROFILE_CARGO) {
        /* network isolation first — before filesystem restriction */
        try_unshare_net();

        if (lb_setup_cargo_ruleset(ruleset_fd, all_rw,
                                   (const char **)dep_names,
                                   dep_count) != 0) {
            close(ruleset_fd);
            return 1;
        }
    } else {
        /* standard profile: full base toolchain + declared deps */
        int   i;
        int   base_count = 0;
        int   total;
        const char **names;
        const char *build_paths[] = {
            getenv("MKPKG_WORK_DIR"),
            getenv("SRC"),
            getenv("PKG"),
            getenv("PKGMK_SOURCE_DIR"),
            "/tmp",
            NULL
        };

        while (lockbox_base[base_count]) base_count++;
        total = base_count + dep_count;
        names = malloc((size_t)total * sizeof(char *));
        if (!names) {
            fprintf(stderr, "mkpkg: error: lbexec: malloc: %s\n",
                    strerror(errno));
            close(ruleset_fd);
            return 1;
        }
        for (i = 0; i < base_count; i++)
            names[i] = lockbox_base[i];
        for (i = 0; i < dep_count; i++)
            names[base_count + i] = dep_names[i];

        if (lb_add_rules_for_packages(ruleset_fd, names, total,
                                       base_count) != 0) {
            free(names);
            close(ruleset_fd);
            return 1;
        }
        free(names);

        for (i = 0; build_paths[i]; i++) {
            if (!build_paths[i][0]) continue;
            if (ll_add_path(ruleset_fd, build_paths[i], all_rw) != 0) {
                fprintf(stderr,
                        "mkpkg: error: lbexec: ll_add_path '%s': %s\n",
                        build_paths[i], strerror(errno));
                close(ruleset_fd);
                return 1;
            }
        }

        if (ll_add_path(ruleset_fd, "/dev",  all_rw)    != 0 ||
            ll_add_path(ruleset_fd, "/proc", ACCESS_RO) != 0 ||
            ll_add_path(ruleset_fd, "/etc",  ACCESS_RO) != 0) {
            fprintf(stderr,
                    "mkpkg: error: lbexec: ll_add_path pseudo-fs: %s\n",
                    strerror(errno));
            close(ruleset_fd);
            return 1;
        }
    }

    /* engage Landlock */
    if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
        fprintf(stderr,
                "mkpkg: error: lbexec: PR_SET_NO_NEW_PRIVS: %s\n",
                strerror(errno));
        close(ruleset_fd);
        return 1;
    }

    if (ll_restrict_self(ruleset_fd) != 0) {
        fprintf(stderr,
                "mkpkg: error: lbexec: restrict_self: %s\n",
                strerror(errno));
        close(ruleset_fd);
        return 1;
    }

    close(ruleset_fd);
    fprintf(stderr, "mkpkg: lbexec: sandbox engaged, executing: %s\n",
            argv[cmd_start]);

    execvp(argv[cmd_start], argv + cmd_start);
    fprintf(stderr, "mkpkg: error: lbexec: execvp '%s': %s\n",
            argv[cmd_start], strerror(errno));
    return 127;
}