qwenguard / code /firmware /guard.c
jgalego's picture
Publish the verifier and the firmware sources
3b06f1d verified
Raw History Blame Contribute Delete
15.1 kB
// Qwenguard: checks every tool call Qwen writes against policy.h before the host may run it.
//
// guard_check() reads a call from its rows (the i-th token's first 16 bytes, NUL-padded, rows
// 1 .. 80, as Qwenputer's bridge captures them), parses all of it and returns 0 to allow it, with
// guard_hash the SHA-256 of POLICY, the function and each parameter as key=value in the order
// written, every field ending in a NUL; or the reason it is denied, with guard_param the parameter
// that reason names, if any. It depends on the rows and the ledger alone.
//
// On Qwenputer (without ZKVM), each run (GO, after </tool_call>) checks the call at 0x8000 and
// prints the verdict as the start of the tool response, then parks (+ the HALT echo \n):
// \n<tool_response>\nguard: allow <hex of guard_hash> (left open for the host's result)
// \n<tool_response>\nguard: deny <reason>[ <param>]\n</tool_response>\n<think>\n\n</think>\n
// The park is reached by the same instructions every time, and no byte store ever merges with an
// earlier call's data (a byte store's record carries its whole word), so every run's trace depends
// on its call and the ledger alone.
#include "policy.h"
#define ROWS 80
#define COUNT(a) ((int)(sizeof a / sizeof *a))
// --- the call text: rows 1 .. 79, each up to its first NUL, packed into words -------------------
static unsigned words[ROWS * 4], acc;
#define call ((const char *)words)
static int len, nwords, pos;
static void append(unsigned w, int k) { // w's first k bytes (the rest are 0) after the text
int at = len & 3;
acc |= w << 8 * at;
if (at + k >= 4) {
words[nwords++] = acc;
acc = at ? w >> (32 - 8 * at) : 0;
}
len += k;
}
static int prefix(unsigned w) { // how many bytes come before w's first NUL; -1 if any follow it
int k = 0;
while (k < 4 && (w >> 8 * k & 255)) k++;
return k < 4 && w >> 8 * k ? -1 : k;
}
static const char *gather(const volatile unsigned *text) {
int ended = 0;
len = nwords = 0;
acc = 0;
for (int i = 1; i <= ROWS; i++) {
const volatile unsigned *r = text + 4 * i;
unsigned w[4] = {r[0], r[1], r[2], r[3]};
if (!(w[0] | w[1] | w[2] | w[3])) {
ended = 1;
continue;
}
if (ended) return "row"; // a token after an empty row
if (i == ROWS) return "long"; // row 80 holds the last of 80 or more tokens
int j = 0, k = 4, n = 0;
for (; j < 4 && k == 4; j++) {
if ((k = prefix(w[j])) < 0) return "row"; // a NUL inside the token
append(w[j], k);
n += k;
}
while (j < 4)
if (w[j++]) return "row";
if (n == 16) return "cut"; // the token may have more than 16 bytes
}
words[nwords] = acc; // the word at len, whose unused bytes are 0
// The compiler may read past len (a literal match loads all its bytes before comparing),
// and a load's record carries its value: no byte of an earlier call may be left to read.
int i = nwords + 1;
for (; i & 7; i++) words[i] = 0;
for (; i < COUNT(words); i += 8)
words[i] = words[i + 1] = words[i + 2] = words[i + 3] = words[i + 4] = words[i + 5] =
words[i + 6] = words[i + 7] = 0;
return 0;
}
// --- parsing: \n<function=NAME>\n (<parameter=KEY>\nVALUE\n</parameter>\n)* </function>\n -------
typedef struct {
int at, n;
} Span;
static Span fn, keys[8], values[8];
static int nparams;
static int lit(const char *s) {
int p = pos;
while (*s)
if (p >= len || call[p++] != *s++) return 0;
pos = p;
return 1;
}
static int ident(Span *s) { // [a-z_]{1,32}
s->at = pos;
while (pos < len && pos - s->at <= 32 &&
((call[pos] >= 'a' && call[pos] <= 'z') || call[pos] == '_'))
pos++;
s->n = pos - s->at;
return s->n >= 1 && s->n <= 32;
}
static int parse(void) {
pos = nparams = 0;
if (!lit("\n<function=") || !ident(&fn) || !lit(">\n")) return 0;
while (lit("<parameter=")) {
if (nparams == COUNT(keys) || !ident(&keys[nparams]) || !lit(">\n")) return 0;
int at = pos;
while (pos < len && call[pos] != '<') pos++; // no value holds '<'
if (pos == at || call[pos - 1] != '\n') return 0;
values[nparams++] = (Span){at, pos - 1 - at};
if (!lit("</parameter>\n")) return 0;
}
return lit("</function>\n") && pos == len;
}
static int is(Span s, const char *name) {
for (int i = 0; i < s.n; i++)
if (call[s.at + i] != name[i]) return 0;
return !name[s.n];
}
// --- values: ASCII only, each kind its own character set ----------------------------------------
#define ALNUM ['a' ... 'z'] = 1, ['A' ... 'Z'] = 1, ['0' ... '9'] = 1
static const unsigned char PAYEE_SET[128] = {ALNUM, ['-'] = 1};
static const unsigned char NAME_SET[128] = {ALNUM, ['.'] = 1, ['-'] = 1};
static const unsigned char LOCAL_SET[128] = {ALNUM, ['.'] = 1, ['_'] = 1, ['+'] = 1, ['-'] = 1};
static const unsigned char URL_SET[128] = {ALNUM, ['-'] = 1, ['.'] = 1, ['_'] = 1, ['~'] = 1,
['/'] = 1, ['?'] = 1, ['='] = 1, ['&'] = 1, ['%'] = 1,
['+'] = 1, [','] = 1, [':'] = 1};
static const unsigned char EXPR_SET[128] = {['a' ... 'z'] = 1, ['0' ... '9'] = 1, ['+'] = 1,
['-'] = 1, ['*'] = 1, ['/'] = 1, ['('] = 1,
[')'] = 1, ['.'] = 1, [','] = 1, ['%'] = 1, [' '] = 1};
static const unsigned char AMOUNT_SET[128] = {['0' ... '9'] = 1, ['.'] = 1};
static int all(int at, int n, const unsigned char *set) {
for (int i = 0; i < n; i++) {
unsigned c = (unsigned char)call[at + i];
if (c > 127 || !set[c]) return 0;
}
return 1;
}
static int text(Span v, int newlines) { // printable ASCII but '>' (and '<', which ends a value)
for (int i = 0; i < v.n; i++) {
int c = call[v.at + i];
if (!(c >= ' ' && c <= '~' && c != '>') && !(newlines && c == '\n')) return 0;
}
return 1;
}
static int lower(int c) { return c >= 'A' && c <= 'Z' ? c + 32 : c; }
static int listed(int at, int n, const char *const *list, int count) {
for (int j = 0; j < count; j++) {
int i = 0;
while (i < n && list[j][i] == lower(call[at + i])) i++;
if (i == n && !list[j][n]) return 1;
}
return 0;
}
static unsigned spent; // the ledger guard_check was given
static const char *amount(Span v) {
const char *s = call + v.at;
int i = 0, units = 0, frac = 0, f;
while (i < v.n && s[i] >= '0' && s[i] <= '9') units = 10 * units + s[i++] - '0';
if (i == 0 || i > 7 || (s[0] == '0' && i > 1)) return "amount";
if (i < v.n) { // '.' and one or two digits
if (s[i++] != '.') return "amount";
for (f = i; i < v.n && s[i] >= '0' && s[i] <= '9'; i++) frac = 10 * frac + s[i] - '0';
if (i != v.n || i - f < 1 || i - f > 2) return "amount";
if (i - f == 1) frac *= 10;
}
unsigned cents = 100 * units + frac;
if (cents < 1 || cents > MAX_CENTS) return "amount";
return spent > MAX_TOTAL_CENTS - cents ? "budget" : 0;
}
static const char *url(Span v) {
if (v.n > 256 || !all(v.at, v.n, URL_SET)) return "charset";
if (v.n < 8 || !is((Span){v.at, 8}, "https://")) return "scheme";
int host = v.at + 8, n = 0;
while (8 + n < v.n && call[host + n] != '/') n++;
if (!n || !all(host, n, NAME_SET)) return "charset"; // a port, userinfo or query at the host
return listed(host, n, FETCH_HOSTS, COUNT(FETCH_HOSTS)) ? 0 : "domain";
}
static const char *email(Span v) {
int at = -1;
for (int i = 0; i < v.n; i++)
if (call[v.at + i] == '@') {
if (at >= 0) return "charset";
at = i;
}
if (v.n > 96 || at < 1 || at == v.n - 1 || !all(v.at, at, LOCAL_SET) ||
!all(v.at + at + 1, v.n - at - 1, NAME_SET))
return "charset";
return listed(v.at + at + 1, v.n - at - 1, MAIL_DOMAINS, COUNT(MAIL_DOMAINS)) ? 0 : "recipient";
}
static const char *value(int kind, Span v) {
switch (kind) {
case PAYEE:
if (v.n < 1 || v.n > 32 || !all(v.at, v.n, PAYEE_SET)) return "charset";
return listed(v.at, v.n, PAYEES, COUNT(PAYEES)) ? 0 : "payee";
case AMOUNT:
return all(v.at, v.n, AMOUNT_SET) ? amount(v) : "charset";
case URL:
return url(v);
case EMAIL:
return email(v);
case SUBJECT:
return v.n >= 1 && v.n <= 120 && text(v, 0) ? 0 : "charset";
case BODY:
return text(v, 1) ? 0 : "charset";
default: // EXPR
return v.n >= 1 && v.n <= 200 && all(v.at, v.n, EXPR_SET) ? 0 : "charset";
}
}
// --- SHA-256 of the call ------------------------------------------------------------------------
static const unsigned K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
static const unsigned H0[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
unsigned guard_hash[8];
static unsigned W[64], word, fed; // fed: bytes hashed so far
#define ROR(x, n) ((x) >> (n) | (x) << (32 - (n)))
// one round; the caller rotates the names instead of the values (8 rounds per loop pass)
#define ROUND(a, b, c, d, e, f, g, h, i) \
do { \
unsigned t = h + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + (g ^ (e & (f ^ g))) + K[i] + \
W[i]; \
d += t; \
h = t + (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) | (c & (a | b))); \
} while (0)
static void block(void) {
for (int i = 16; i < 64; i++) {
unsigned a = W[i - 15], b = W[i - 2];
W[i] = W[i - 16] + (ROR(a, 7) ^ ROR(a, 18) ^ a >> 3) + W[i - 7] +
(ROR(b, 17) ^ ROR(b, 19) ^ b >> 10);
}
unsigned *H = guard_hash, a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5],
g = H[6], h = H[7];
for (int i = 0; i < 64; i += 8) {
ROUND(a, b, c, d, e, f, g, h, i);
ROUND(h, a, b, c, d, e, f, g, i + 1);
ROUND(g, h, a, b, c, d, e, f, i + 2);
ROUND(f, g, h, a, b, c, d, e, i + 3);
ROUND(e, f, g, h, a, b, c, d, i + 4);
ROUND(d, e, f, g, h, a, b, c, i + 5);
ROUND(c, d, e, f, g, h, a, b, i + 6);
ROUND(b, c, d, e, f, g, h, a, i + 7);
}
H[0] += a, H[1] += b, H[2] += c, H[3] += d, H[4] += e, H[5] += f, H[6] += g, H[7] += h;
}
static void feed(unsigned c) { // big-endian words straight into W, compressing every 64 bytes
word = word << 8 | (c & 255);
if ((++fed & 3) == 0) W[(fed - 1) >> 2 & 15] = word;
if ((fed & 63) == 0) block();
}
static void add(const char *s, int n, int end) {
for (int i = 0; i < n; i++) feed((unsigned char)s[i]);
feed(end);
}
static void hash(void) {
word = fed = 0;
for (int i = 0; i < 8; i++) guard_hash[i] = H0[i];
add(POLICY, sizeof POLICY - 1, 0);
add(call + fn.at, fn.n, 0);
for (int i = 0; i < nparams; i++) {
add(call + keys[i].at, keys[i].n, '=');
add(call + values[i].at, values[i].n, 0);
}
unsigned bits = 8 * fed;
feed(0x80);
while ((fed & 63) != 56) feed(0);
for (int i = 7; i >= 0; i--) feed(i < 4 ? bits >> 8 * i : 0);
}
// --- the verdict --------------------------------------------------------------------------------
const char *guard_param;
const char *guard_check(const volatile unsigned *text, unsigned ledger) {
const char *why = gather(text);
guard_param = 0;
spent = ledger;
if (why) return why;
if (!parse()) return "parse";
int f = 0;
while (f < COUNT(FUNCTIONS) && !is(fn, FUNCTIONS[f].name)) f++;
if (f == COUNT(FUNCTIONS)) return "function";
int found[3] = {-1, -1, -1};
for (int i = 0; i < nparams; i++) {
int j = 0;
while (j < 3 && !(FUNCTIONS[f].params[j] && is(keys[i], FUNCTIONS[f].params[j]))) j++;
if (j == 3) return "unexpected";
if (found[j] >= 0) {
guard_param = FUNCTIONS[f].params[j];
return "duplicate";
}
found[j] = i;
}
for (int j = 0; j < 3 && FUNCTIONS[f].params[j]; j++) {
if (found[j] < 0) {
guard_param = FUNCTIONS[f].params[j];
return "missing";
}
if ((why = value(FUNCTIONS[f].kinds[j], values[found[j]]))) {
if (why[0] == 'c') guard_param = FUNCTIONS[f].params[j]; // only charset names it
return why;
}
}
hash();
return 0;
}
// --- on Qwenputer: the bridge's park loop -------------------------------------------------------
#ifndef ZKVM
#include "rt.h"
enum { TOOL_RESPONSE = 256, TOOL_RESPONSE_END, THINK, THINK_END };
// The host's ledger: cents already transferred in this conversation. The host writes it into the
// snapshot before each segment; it lives in .data so that the ELF holds its value.
__attribute__((section(".data.ledger"))) volatile unsigned ledger = 0;
void exit(int code) {
for (;;) rv_ecall2(93, code, 0, 0);
}
static void put(int c) { rv_ecall2(1, c, 0, 0); }
static void say(const char *s) {
while (*s) put(*s++);
}
static __attribute__((noinline)) void park(void) { rv_ecall2(93, 0, 0, 0); }
int main(void) {
for (;;) {
park();
const char *why = guard_check((const volatile unsigned *)0x8000, ledger);
put('\n');
put(TOOL_RESPONSE);
put('\n');
say("guard: ");
if (why) {
say("deny ");
say(why);
if (guard_param) {
put(' ');
say(guard_param);
}
put('\n');
put(TOOL_RESPONSE_END);
put('\n');
put(THINK);
put('\n');
put('\n');
put(THINK_END);
put('\n');
} else {
say("allow ");
for (int i = 0; i < 64; i++)
put("0123456789abcdef"[guard_hash[i / 8] >> (28 - 4 * (i % 8)) & 15]);
}
}
}
#endif