eBPF-based security platform
json: walk any document through the parser's grammar
Daniel Borkmannee734baaaa51
diff --git a/testing/fuzz/fuzz-json.c b/testing/fuzz/fuzz-json.cindex 6a54e69a..0ea37cd2 100644--- a/testing/fuzz/fuzz-json.c+++ b/testing/fuzz/fuzz-json.c@@ -2,10 +2,16 @@/** Copyright (c) 2026 Authors of shirudo*- * json_parse() over a schema with every field type.+ * json_parse() over a schema with every field type, and json_walk()+ * over the same input.*/+#include <stdlib.h>+#include "fuzz.h"++#include <shirudo/string.h>+#include "json.h"static int on_elem(void *ctx)@@ -14,6 +20,23 @@ static int on_elem(void *ctx)return 0;}+/* Whatever the walk hands over is whole UTF-8 text without a NUL. */+static int check_text(void *ctx, const char *s)+{+ size_t n = strlen(s), w;++ for (size_t i = 0; i < n; i += w) {+ w = utf8_width(s + i, n - i);+ if (!w)+ abort();+ }+ return 0;+}++static const struct json_visitor checker = {+ .key = check_text, .string = check_text,+};+int LLVMFuzzerTestOneInput(const __u8 *data, size_t size){char s[64], k[32], v[16];@@ -37,5 +60,6 @@ int LLVMFuzzerTestOneInput(const __u8 *data, size_t size)};json_parse((const char *)data, size, root, ARRAY_SIZE(root));+ json_walk((const char *)data, size, &checker, NULL);return 0;}diff --git a/testing/unit/json.c b/testing/unit/json.cindex 32be5aa0..fc8fcf2b 100644--- a/testing/unit/json.c+++ b/testing/unit/json.c@@ -499,6 +499,148 @@ static void lossy_writes_replace_bad_bytes(void)"\"a\\ufffdb\\ufffdc\\ufffd\\ufffd\xc3\xa9\"}");}+struct trace {+ char buf[512];+ size_t len;+};++static int trace_put(struct trace *t, const char *s)+{+ size_t n = strlen(s);++ if (t->len + n >= sizeof(t->buf))+ return -E2BIG;+ memcpy(t->buf + t->len, s, n + 1);+ t->len += n;+ return 0;+}++static int trace_open(void *ctx, bool array)+{+ return trace_put(ctx, array ? "[" : "{");+}++static int trace_close(void *ctx, bool array)+{+ return trace_put(ctx, array ? "]" : "}");+}++static int trace_key(void *ctx, const char *key)+{+ return trace_put(ctx, "k:") ?: trace_put(ctx, key) ?: trace_put(ctx, " ");+}++static int trace_string(void *ctx, const char *s)+{+ return trace_put(ctx, "s:") ?: trace_put(ctx, s) ?: trace_put(ctx, " ");+}++static int trace_number(void *ctx, const char *text, size_t len,+ bool integer)+{+ char num[64];++ if (strsprintf(num, sizeof(num), "%s:%.*s ", integer ? "i" : "d",+ (int)len, text) < 0)+ return -E2BIG;+ return trace_put(ctx, num);+}++static int trace_literal(void *ctx, int value)+{+ return trace_put(ctx, value > 0 ? "true " : value ? "null " : "false ");+}++static const struct json_visitor tracer = {+ .open = trace_open, .close = trace_close, .key = trace_key,+ .string = trace_string, .number = trace_number,+ .literal = trace_literal,+};++static int walk(const char *text, struct trace *t)+{+ t->len = 0;+ t->buf[0] = '\0';+ return json_walk(text, strlen(text), &tracer, t);+}++/* The walk reports a document in order, held to the parser's rules. */+static void walk_reports_every_token(void)+{+ char deep[128];+ struct trace t;+ int i;++ ASSERT_EQ(walk(" {\"a\":[1,\"x\\u00e9\",true,null,{\"b\":-2.5e3}],"+ "\"c\":{},\"d\":false} ", &t), 0);+ EXPECT_STREQ(t.buf, "{k:a [i:1 s:x\xc3\xa9 true null {k:b d:-2.5e3 }]"+ "k:c {}k:d false }");+ ASSERT_EQ(walk("\"top\"", &t), 0);+ EXPECT_STREQ(t.buf, "s:top ");+ ASSERT_EQ(walk("-0", &t), 0);+ EXPECT_STREQ(t.buf, "i:-0 ");++ EXPECT_EQ(walk("{\"a\":1,}", &t), -EINVAL);+ EXPECT_EQ(walk("{\"a\":\"\\u0000\"}", &t), -EINVAL);+ EXPECT_EQ(walk("[\"\xff\"]", &t), -EINVAL);+ EXPECT_EQ(walk("[1] 2", &t), -EINVAL);+ EXPECT_EQ(walk("", &t), -EINVAL);+ for (i = 0; i < 40; i++)+ deep[i] = '[';+ deep[i] = '\0';+ EXPECT_EQ(walk(deep, &t), -E2BIG);+ EXPECT_EQ(json_walk("[1]", 3, NULL, NULL), -EINVAL);+}++/*+ * ECMA-404, 2nd edition: what the grammar holds is taken, what it does+ * not is refused, and the restrictions json.h lists are refused too.+ */+static void walk_follows_ecma_404(void)+{+ static const char *const conforming[] = {+ "[]", "{}", "0", "-0", "1.5e+10", "1E-2", "-0.0e0", "true",+ "null", "\"\"", "{\"\":0}", " \t\n\r[1] ",+ "[\"\\u002F\\u002f\\/\"]", "\"\\uD834\\uDD1E\"",+ "[\"\\b\\f\\n\\r\\t\\\"\\\\\"]", "[\"\x7f\"]",+ "{\"a\":[{\"b\":null}],\"c\":\"\xf0\x9d\x84\x9e\"}",+ };+ static const char *const nonconforming[] = {+ "[01]", "[1.]", "[.5]", "[+1]", "[-]", "[1e]", "[1e+]", "[NaN]",+ "[Infinity]", "[\"\x01\"]", "[\"\\x41\"]", "[\"\\u12\"]",+ "[True]", "[1,]", "{\"a\":1,}", "{a:1}", "['a']", "[\"a\" \"b\"]",+ "\v[1]", "\f[1]", "\xef\xbb\xbf[1]", "[1]x", "[\"a]", "{\"a\"}",+ "{\"a\" 1}", "[1 2]", "",+ };+ static const char *const restricted[] = {+ "\"\\u0000\"", "\"\\uD800\"", "\"\\uDC00\"",+ "\"\\uD800\\u0041\"", "[\"\xff\"]", "[\"\xed\xa0\x80\"]",+ };+ struct trace t;+ size_t i;++ for (i = 0; i < ARRAY_SIZE(conforming); i++)+ EXPECT_EQ(walk(conforming[i], &t), 0);+ for (i = 0; i < ARRAY_SIZE(nonconforming); i++)+ EXPECT_EQ(walk(nonconforming[i], &t), -EINVAL);+ for (i = 0; i < ARRAY_SIZE(restricted); i++)+ EXPECT_EQ(walk(restricted[i], &t), -EINVAL);+}++static int stop_at_number(void *ctx, const char *text, size_t len,+ bool integer)+{+ return -ECANCELED;+}++static void walk_stops_where_a_callback_says(void)+{+ static const struct json_visitor stop = { .number = stop_at_number };++ EXPECT_EQ(json_walk("[\"a\",2,3]", 9, &stop, NULL), -ECANCELED);+ EXPECT_EQ(json_walk("[\"a\"]", 5, &stop, NULL), 0);+}+static const struct unit_case cases[] = {UNIT_CASE(extracts_scalars_and_skips_nested_sets),UNIT_CASE(skips_unknown_keys_and_objects),@@ -523,6 +665,9 @@ static const struct unit_case cases[] = {UNIT_CASE(emitter_takes_well_formed_utf8_only),UNIT_CASE(emitter_grows_up_to_its_max),UNIT_CASE(lossy_writes_replace_bad_bytes),+ UNIT_CASE(walk_reports_every_token),+ UNIT_CASE(walk_follows_ecma_404),+ UNIT_CASE(walk_stops_where_a_callback_says),{}};diff --git a/util/json.c b/util/json.cindex 9b21e4a2..4bc57134 100644--- a/util/json.c+++ b/util/json.c@@ -320,8 +320,31 @@ struct pctx {__u32 depth;struct json_field *fields;size_t n_fields;+ const struct json_visitor *v;+ void *v_ctx;+ char *scratch; /* walk: decoded text */+ size_t scratch_cap;};+/*+ * A walk reports what the parse discards, through the same grammar, so+ * that one parser checks every document shirudo reads.+ */+static int visit_open(struct pctx *c, bool array)+{+ return c->v && c->v->open ? c->v->open(c->v_ctx, array) : 0;+}++static int visit_close(struct pctx *c, bool array)+{+ return c->v && c->v->close ? c->v->close(c->v_ctx, array) : 0;+}++static int visit_literal(struct pctx *c, int value)+{+ return c->v && c->v->literal ? c->v->literal(c->v_ctx, value) : 0;+}+static void reset_seen(struct json_field *fields, size_t n){size_t i;@@ -513,24 +536,30 @@ static int parse_value(struct pctx *c, struct json_field *f);static int parse_object(struct pctx *c){- char key[256];+ char buf[256], *key = c->v ? c->scratch : buf;+ size_t key_cap = c->v ? c->scratch_cap : sizeof(buf);int ret;if (++c->depth > JSON_MAX_DEPTH)return -E2BIG;c->p++; /* consume '{' */+ ret = visit_open(c, false);+ if (ret)+ return ret;skip_ws(c);if (c->p < c->end && *c->p == '}') {c->p++;c->depth--;- return 0;+ return visit_close(c, false);}for (;;) {struct json_field *f = NULL;size_t i;skip_ws(c);- ret = parse_string(c, key, sizeof(key));+ ret = parse_string(c, key, key_cap);+ if (!ret && c->v && c->v->key)+ ret = c->v->key(c->v_ctx, key);if (ret)return ret;skip_ws(c);@@ -563,7 +592,7 @@ static int parse_object(struct pctx *c)return -EINVAL;}c->depth--;- return 0;+ return visit_close(c, false);}static int parse_array(struct pctx *c)@@ -573,11 +602,14 @@ static int parse_array(struct pctx *c)if (++c->depth > JSON_MAX_DEPTH)return -E2BIG;c->p++; /* consume '[' */+ ret = visit_open(c, true);+ if (ret)+ return ret;skip_ws(c);if (c->p < c->end && *c->p == ']') {c->p++;c->depth--;- return 0;+ return visit_close(c, true);}for (;;) {ret = parse_value(c, NULL); /* elements never dispatched */@@ -597,7 +629,7 @@ static int parse_array(struct pctx *c)return -EINVAL;}c->depth--;- return 0;+ return visit_close(c, true);}static int parse_array_into(struct pctx *c, struct json_field *f)@@ -708,7 +740,9 @@ static int parse_number(struct pctx *c, struct json_field *f)return -EINVAL;}if (!f)- return 0;+ return c->v && c->v->number ?+ c->v->number(c->v_ctx, start, (size_t)(c->p - start),+ c->p == int_end) : 0;if (f->type != JSON_T_INT || c->p != int_end)return -EINVAL;if (parse_s64(start, (size_t)(int_end - start), INT64_MIN, INT64_MAX,@@ -771,6 +805,13 @@ static int parse_value(struct pctx *c, struct json_field *f)f->seen = 1;return 0;}+ if (c->v) {+ int ret = parse_string(c, c->scratch, c->scratch_cap);++ if (!ret && c->v->string)+ ret = c->v->string(c->v_ctx, c->scratch);+ return ret;+ }return parse_string(c, NULL, 0);case 't':if (lit(c, "true"))@@ -781,7 +822,7 @@ static int parse_value(struct pctx *c, struct json_field *f)*(int *)f->dst = 1;f->seen = 1;}- return 0;+ return f ? 0 : visit_literal(c, 1);case 'f':if (lit(c, "false"))return -EINVAL;@@ -791,11 +832,11 @@ static int parse_value(struct pctx *c, struct json_field *f)*(int *)f->dst = 0;f->seen = 1;}- return 0;+ return f ? 0 : visit_literal(c, 0);case 'n':if (lit(c, "null"))return -EINVAL;- return 0; /* null never dispatched */+ return f ? 0 : visit_literal(c, -1); /* null never dispatched */default:return parse_number(c, f);}@@ -825,3 +866,28 @@ int json_parse(const char *data, size_t len,return -EINVAL; /* trailing garbage */return 0;}++int json_walk(const char *data, size_t len,+ const struct json_visitor *v, void *ctx)+{+ struct pctx c = {+ .p = data, .end = data + len, .v = v, .v_ctx = ctx,+ };+ int ret;++ if (len > JSON_MAX_BYTES || !v)+ return len > JSON_MAX_BYTES ? -E2BIG : -EINVAL;+ /* A decoded string is never longer than its encoding. */+ c.scratch_cap = len + 1;+ c.scratch = xmalloc(c.scratch_cap);+ if (!c.scratch)+ return -ENOMEM;+ ret = parse_value(&c, NULL);+ if (!ret) {+ skip_ws(&c);+ if (c.p != c.end)+ ret = -EINVAL;+ }+ xfree(c.scratch, c.scratch_cap);+ return ret;+}diff --git a/util/json.h b/util/json.hindex f0ed6740..2b78b49f 100644--- a/util/json.h+++ b/util/json.h@@ -126,4 +126,32 @@ struct json_field {int json_parse(const char *data, size_t len,struct json_field *fields, size_t n_fields);+/*+ * Both readers take JSON text as ECMA-404, 2nd edition, defines it,+ * under the restrictions its section 2 lets a processor impose:+ * json_parse() takes an object alone and a declared key once, and both+ * refuse \u0000 and a lone surrogate escape, which no C string or UTF-8+ * holds, bytes that are no well-formed UTF-8, more than JSON_MAX_DEPTH+ * levels and more than JSON_MAX_BYTES.+ *+ * json_walk() reports every token of a document of any one value, in+ * order and checked as json_parse() checks one: strings and keys+ * decoded and terminated, numbers as their text, with integer set when+ * it has no fraction or exponent, literals as 1 for true, 0 for false+ * and -1 for null. A callback may be NULL; one that returns a negative+ * errno stops the walk with it.+ */+struct json_visitor {+ int (*open)(void *ctx, bool array);+ int (*close)(void *ctx, bool array);+ int (*key)(void *ctx, const char *key);+ int (*string)(void *ctx, const char *s);+ int (*number)(void *ctx, const char *text, size_t len,+ bool integer);+ int (*literal)(void *ctx, int value);+};++int json_walk(const char *data, size_t len,+ const struct json_visitor *v, void *ctx);+#endif /* SHIRUDO_JSON_H */