eBPF-based security platform
json: refuse a declared key named twice even when it was null
Daniel Borkmannb40c19df2b3c
diff --git a/testing/unit/json.c b/testing/unit/json.cindex 9236f248..718e88c2 100644--- a/testing/unit/json.c+++ b/testing/unit/json.c@@ -314,8 +314,8 @@ static void declared_key_takes_one_value(void)EXPECT_EQ(json_parse(nested, strlen(nested), top, ARRAY_SIZE(top)),-EINVAL);- ASSERT_EQ(parse("{\"type\":null,\"type\":\"b\"}", &d), 0);- EXPECT_STREQ(d.type, "b");+ EXPECT_EQ(parse("{\"type\":null,\"type\":\"b\"}", &d), -EINVAL);+ EXPECT_EQ(parse("{\"type\":null,\"type\":null}", &d), -EINVAL);ASSERT_EQ(parse("{\"x\":1,\"x\":{},\"type\":\"t\"}", &d), 0);EXPECT_STREQ(d.type, "t");ASSERT_EQ(parse("{\"events\":[{\"type\":\"a\"},{\"type\":\"b\"}]}",diff --git a/util/json.c b/util/json.cindex f5fd337a..6eb83efc 100644--- a/util/json.c+++ b/util/json.c@@ -539,9 +539,10 @@ static int parse_object(struct pctx *c){char buf[256], *key = c->v ? c->scratch : buf;size_t key_cap = c->v ? c->scratch_cap : sizeof(buf);+ __u64 named = 0;int ret;- if (++c->depth > JSON_MAX_DEPTH)+ if (++c->depth > JSON_MAX_DEPTH || c->n_fields > JSON_MAX_FIELDS)return -E2BIG;c->p++; /* consume '{' */ret = visit_open(c, false);@@ -574,8 +575,13 @@ static int parse_object(struct pctx *c)}}/* Readers that take the first or the last would differ. */- if (f && f->seen)- return -EINVAL;+ if (f) {+ __u64 bit = 1ULL << (f - c->fields);++ if (named & bit)+ return -EINVAL;+ named |= bit;+ }ret = parse_value(c, f);if (ret)return ret;diff --git a/util/json.h b/util/json.hindex 21e87b24..904a4b69 100644--- a/util/json.h+++ b/util/json.h@@ -19,6 +19,8 @@#ifndef JSON_MAX_DEPTH#define JSON_MAX_DEPTH 32u#endif+/* The declared keys of one object, which json_parse() tells apart. */+#define JSON_MAX_FIELDS 64u#ifndef JSON_MAX_STRING_BYTES#define JSON_MAX_STRING_BYTES (16u * 1024u * 1024u)#endif@@ -132,9 +134,10 @@ struct json_field {};/*- * -EINVAL on malformed input, a type mismatch or a declared key given a- * value twice in one object (null gives none), -E2BIG on a bounds- * violation, -ENOSPC when a string exceeds its dst_cap.+ * -EINVAL on malformed input, a type mismatch or a declared key named+ * twice in one object, null or not, -E2BIG on a bounds violation or more+ * than JSON_MAX_FIELDS declared keys, -ENOSPC when a string exceeds its+ * dst_cap.*/int json_parse(const char *data, size_t len,struct json_field *fields, size_t n_fields);