Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

12.5 KB
Raw Blame
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <bpf/bpf.h>
#include <bpf/libbpf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/un.h>
#include <unistd.h>
#include "ebpf_jev_common.h"
#include "jev.skel.h"

static const char *cg="/sys/fs/cgroup/jev", *protected, *config_file, *weights, *report, *trees, *tree_heads;
static struct sockaddr_un control={.sun_family=AF_UNIX,.sun_path="/run/jev/warden.sock"};
static volatile sig_atomic_t stopping;
static int mode=4, approved_port=19998;
static struct dst_key extra_dsts[64];
static size_t extra_dst_count;
static bool csv, json_stream, instrument_noop, cgroup_taint;
static int parse_allow_dst(const char *spec, struct dst_key *out) {
    char host[128];
    const char *port_str = NULL;
    int fam = AF_INET;
    if (spec[0] == '[') {
        const char *rb = strchr(spec, ']');
        if (!rb || rb[1] != ':') return -1;
        size_t hlen = (size_t)(rb - (spec + 1));
        if (hlen == 0 || hlen >= sizeof(host)) return -1;
        memcpy(host, spec + 1, hlen);
        host[hlen] = '\0';
        port_str = rb + 2;
        fam = AF_INET6;
    } else {
        const char *colon = strrchr(spec, ':');
        if (!colon) return -1;
        size_t hlen = (size_t)(colon - spec);
        if (hlen == 0 || hlen >= sizeof(host)) return -1;
        memcpy(host, spec, hlen);
        host[hlen] = '\0';
        port_str = colon + 1;
        fam = AF_INET;
    }
    char *end = NULL;
    long p = strtol(port_str, &end, 10);
    if (!port_str[0] || !end || *end || p < 1 || p > 65535) return -1;
    memset(out, 0, sizeof(*out));
    out->family = (__u16)fam;
    out->port = (__u16)p;
    if (inet_pton(fam, host, out->addr) != 1) return -1;
    return 0;
}
static void stop(int sig) {(void)sig; stopping=1;}
static int pack(const char *path, void *dst, size_t size) {
    FILE *f=fopen(path,"rb");
    if (!f) return -1;
    int ok=fread(dst,1,size,f)==size && fgetc(f)==EOF && !ferror(f);
    fclose(f);
    if (!ok) errno=EINVAL;
    return ok ? 0 : -1;
}
static int install_model(struct jev *sk,const char *path,bool initial) {
    struct jev_model_weights w={.magic=0x4a455631,.model_gen=1,.thresh_deny=220,.max_uncertainty=96};
    if (path && pack(path,&w,sizeof(w))) return -1;
    if (w.magic!=0x4a455631 || w.shift1>30 || w.shift2>30 || w.emb_shift>30) {errno=EINVAL; return -1;}
    int slot=initial ? 0 : 1-sk->bss->active_slot;
    static unsigned generation;
    if (!initial && w.model_gen==generation) {errno=EALREADY;return -1;}
    while (__atomic_load_n(&sk->bss->readers,__ATOMIC_SEQ_CST) && !stopping) usleep(100);
    if (stopping || bpf_map_update_elem(bpf_map__fd(sk->maps.models_map),&slot,&w,BPF_ANY)) return -1;
    __atomic_store_n(&sk->bss->active_slot,slot,__ATOMIC_SEQ_CST);
    generation=w.model_gen;
    if (json_stream) printf("{\"type\":\"model\",\"gen\":%u}\n",generation);
    fprintf(stderr,"weights generation=%u slot=%d\n",generation,slot);
    return 0;
}
static int obj(int fd,const char *path,unsigned char cls) {
    struct stat st;
    if (stat(path,&st)) return -1;
    struct object_key key={((__u64)major(st.st_dev)<<20)|minor(st.st_dev),st.st_ino};
    return bpf_map_update_elem(fd,&key,&cls,BPF_ANY);
}
static int register_policy(struct jev *s) {
    if (mkdir(cg,0755) && errno!=EEXIST) return -1;
    struct stat st;
    if (stat(cg,&st)) return -1;
    __u64 id=st.st_ino;
    unsigned char yes=1;
    struct dst_key dst={.family=AF_INET,.port=approved_port,.addr={127,0,0,1}};
    struct jev_cgroup_state empty_cgs={};
    if (bpf_map_update_elem(bpf_map__fd(s->maps.monitored_cgroups_map),&id,&yes,BPF_ANY) ||
        bpf_map_update_elem(bpf_map__fd(s->maps.cgroup_state_map),&id,&empty_cgs,BPF_ANY) ||
        (approved_port>0 && bpf_map_update_elem(bpf_map__fd(s->maps.allowlist_dst_map),&dst,&yes,BPF_ANY)) ||
        (protected && obj(bpf_map__fd(s->maps.protected_objects_map),protected,85)) ||
        (config_file && obj(bpf_map__fd(s->maps.protected_objects_map),config_file,40))) return -1;
    for (size_t i=0;i<extra_dst_count;i++)
        if (bpf_map_update_elem(bpf_map__fd(s->maps.allowlist_dst_map),&extra_dsts[i],&yes,BPF_ANY)) return -1;
    struct {const char *name; unsigned char cls;} bins[]={
        {"/usr/bin/git",30},{"/usr/bin/cat",30},{"/usr/bin/make",65},{"/usr/bin/npm",65},
        {"/usr/bin/bash",95},{"/bin/sh",95},{"/usr/bin/python3",127},{"/usr/bin/curl",127}};
    for (size_t i=0;i<sizeof(bins)/sizeof(*bins);i++)
        if (obj(bpf_map__fd(s->maps.binary_classes),bins[i].name,bins[i].cls) && errno!=ENOENT) return -1;
    if (mode==2) {
        struct jev_oblivious_gbdt t={.ntrees=16};
        if (trees) {if (pack(trees,&t,sizeof(t)) || t.ntrees<16 || t.ntrees>32) return -1;}
        else for (int i=0;i<16;i++) {
            t.feature[i][0]=8; t.feature[i][1]=5; t.feature[i][2]=10; t.feature[i][3]=7;
            t.threshold[i][1]=100;
            for (int l=0;l<16;l++) t.leaves[i][l]=(l&3)==3 ? 7 : -7;
        }
        int k=0;
        struct jev_tree_heads aux={};
        if (tree_heads && pack(tree_heads,&aux,sizeof(aux))) return -1;
        if (bpf_map_update_elem(bpf_map__fd(s->maps.tree_heads),&k,&aux,BPF_ANY)) return -1;
        if (bpf_map_update_elem(bpf_map__fd(s->maps.tree_map),&k,&t,BPF_ANY)) return -1;
    }
    return 0;
}
static void json_string(const char *s, size_t n) {
    putchar('"');
    for (size_t i=0;i<n && s[i];i++) {
        unsigned char c=s[i];
        if (c=='"' || c=='\\') printf("\\%c",c);
        else if (c<32 || c>=127) printf("\\u%04x",c);
        else putchar(c);
    }
    putchar('"');
}
static int event(void *ctx,void *data,size_t size) {
    (void)ctx;
    if (size!=sizeof(struct jev_ring_event)) return -EINVAL;
    struct jev_ring_event *e=data;
    const char *actions[]={"ALLOW","DENY -EPERM","ABSTAIN_DENY -EPERM"};
    if (json_stream) {
        const char *type=e->event_type==129 ? "sendmsg" : e->event_type==128 ? "task_alloc" : e->event_type==127 ? "connect" :
                         e->event_type==64 ? "file_open" : "bprm_exec";
        printf("{\"type\":\"%s\",\"pid\":%u,\"ppid\":%u,\"comm\":",type,e->pid,e->ppid);
        json_string(e->comm,sizeof(e->comm));
        fputs(",\"name\":",stdout);
        json_string(e->name,sizeof(e->name));
        printf(",\"verdict\":\"%s\",\"scores\":[%u,%u,%u,%u],\"port\":%u,\"gen\":%u,"
               "\"hook_ns\":%llu,\"opens\":%u,\"execs\":%u,\"depth\":%u,\"inherited\":%u,\"h\":\"",
               actions[e->action%3],e->scores[0],e->scores[1],e->scores[2],e->scores[3],
               e->port,e->model_gen,e->hook_ns,e->opens,e->execs,e->depth,e->inherited_taint);
        for (size_t i=0;i<sizeof(e->h);i++) printf("%02x",(unsigned char)e->h[i]);
        putchar('"');
        if (e->event_type!=128) {
            fputs(",\"x\":[",stdout);
            for (size_t i=0;i<sizeof(e->x);i++) printf("%s%d",i?",":"",e->x[i]);
            putchar(']');
        }
        puts("}");
    } else if (csv) printf("%u,%u,%.16s,%u,%u,%u,%u,%u,%u,%llu,%u,%u\n",
        e->pid,e->ppid,e->comm,e->event_type,e->scores[0],e->scores[1],e->scores[2],
        e->scores[3],e->action,e->hook_ns,e->model_gen,e->inherited_taint);
    else printf("%6u  %-16.16s  %3u   %3u %3u %3u %3u   %8.3f us   %s\n",e->pid,
        e->comm,e->event_type,e->scores[0],e->scores[1],e->scores[2],e->scores[3],
        e->hook_ns/1000.0,actions[e->action%3]);
    return 0;
}
static int reload(const char *path) {
    char absolute[PATH_MAX];
    if (!realpath(path,absolute)) return -1;
    int fd=socket(AF_UNIX,SOCK_SEQPACKET,0), result;
    if (connect(fd,(void *)&control,sizeof(control)) ||
        send(fd,absolute,strlen(absolute)+1,MSG_NOSIGNAL)<0 ||
        recv(fd,&result,sizeof(result),0)!=sizeof(result)) return -1;
    close(fd);
    errno=result;
    return result ? -1 : 0;
}
static void accept_reload(int server,struct jev *s) {
    int fd=accept(server,NULL,NULL);
    if (fd<0) return;
    char path[PATH_MAX];
    struct timeval timeout={.tv_sec=1};
    setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
    ssize_t n=recv(fd,path,sizeof(path),0);
    int result=n<=1 || n>=PATH_MAX || path[n-1] ? EINVAL :
            install_model(s,path,false) ? errno : 0;
    send(fd,&result,sizeof(result),MSG_NOSIGNAL);
    close(fd);
}
int main(int argc,char **argv) {
    if (argc==3 && !strcmp(argv[1],"--reload-weights")) {
        if (!reload(argv[2])) return 0;
        perror("reload");return 1;
    }
    for (int i=1;i<argc;i++) {
        if (!strcmp(argv[i],"--instrument-noop")) {instrument_noop=true;continue;}
        if (!strcmp(argv[i],"--cgroup-taint")) {cgroup_taint=true;continue;}
        if (!strcmp(argv[i],"--json")) {json_stream=true;setvbuf(stdout,NULL,_IOLBF,0);continue;}
        if (!strcmp(argv[i],"--csv")) {csv=true;continue;}
        if (i+1>=argc) return 2;
        const char *arg=argv[i++], *val=argv[i];
        if (!strcmp(arg,"--mode")) mode=atoi(val);
        else if (!strcmp(arg,"--cgroup")) cg=val;
        else if (!strcmp(arg,"--protected")) protected=val;
        else if (!strcmp(arg,"--config")) config_file=val;
        else if (!strcmp(arg,"--weights")) weights=val;
        else if (!strcmp(arg,"--tree-heads")) tree_heads=val;
        else if (!strcmp(arg,"--trees")) trees=val;
        else if (!strcmp(arg,"--allow-port")) approved_port=atoi(val);
        else if (!strcmp(arg,"--allow-dst")) {
            if (extra_dst_count>=sizeof(extra_dsts)/sizeof(*extra_dsts) ||
                parse_allow_dst(val,&extra_dsts[extra_dst_count])) return 2;
            extra_dst_count++;
        }
        else if (!strcmp(arg,"--verifier-report")) report=val;
        else return 2;
    }
    if (mode<0 || mode>4) return 2;
    signal(SIGINT,stop);signal(SIGTERM,stop);
    struct jev *s=jev__open();
    if (!s) return 1;
    if (!json_stream) bpf_program__set_autoload(s->progs.jev_fork_record,false);
    struct bpf_program *p;
    const int cap=8<<20;
    if (report) bpf_object__for_each_program(p,s->obj) {
        char *buf=calloc(1,cap);
        if (!buf) return 1;
        bpf_program__set_log_buf(p,buf,cap); bpf_program__set_log_level(p,1|4);
    }
    int err=jev__load(s);
    if (report) {
        FILE *f=fopen(report,"w");
        if (!f) return 1;
        bpf_object__for_each_program(p,s->obj) {
            size_t len;
            const char *log=bpf_program__log_buf(p,&len);
            struct bpf_prog_info info={}; __u32 n=sizeof(info);
            bpf_prog_get_info_by_fd(bpf_program__fd(p),&info,&n);
            fprintf(f,"%s xlated=%u jited=%u verified_insns=%u\n",bpf_program__name(p),
                    info.xlated_prog_len,info.jited_prog_len,info.verified_insns);
            if (log) {
                // Verifier level 1 includes the instruction trace. Keep statistics and any failure.
                if (err) fputs(log,f);
                else {
                    char *copy=strdup(log), *save, *line=strtok_r(copy,"\n",&save);
                    while (line) {
                        if (strstr(line,"stack depth") || strstr(line,"processed ") ||
                            strstr(line,"verification time")) fprintf(f,"%s\n",line);
                        line=strtok_r(NULL,"\n",&save);
                    }
                    free(copy);
                }
            }
        }
        fclose(f);
    }
    if (err || install_model(s,weights,true) || register_policy(s)) {perror("setup");return 1;}
    s->bss->stream_details=json_stream;
    s->bss->mode=mode;
    s->bss->instrument_noop=instrument_noop;
    s->bss->cgroup_taint_mode=cgroup_taint;
    if (mkdir("/run/jev",0700) && errno!=EEXIST) return 1;
    int server=socket(AF_UNIX,SOCK_SEQPACKET|SOCK_NONBLOCK,0);
    if (bind(server,(void *)&control,sizeof(control)) || listen(server,4)) {perror("control");return 1;}
    struct ring_buffer *rb=ring_buffer__new(bpf_map__fd(s->maps.events_rb),event,NULL,NULL);
    if (!rb || jev__attach(s)) {unlink(control.sun_path);return 1;}
    if (!csv && !json_stream) puts("   PID  COMMAND           TYPE   EXF EVA BEN UNC      HOOK TIME   VERDICT");
    fprintf(stderr,"READY mode=%d cgroup_taint=%d\n",mode,cgroup_taint);
    while (!stopping) {
        int rc=ring_buffer__poll(rb,25);
        if (rc<0 && rc!=-EINTR) {err=1;break;}
        accept_reload(server,s);
    }
    jev__detach(s);ring_buffer__consume(rb);
    fprintf(stderr,"dropped=%llu\n",(unsigned long long)s->bss->dropped);
    ring_buffer__free(rb);jev__destroy(s);close(server);unlink(control.sun_path);
    return err!=0;
}