Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 80 additions & 3 deletions modules-contrib/cachedb_nats/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,16 @@ module is loaded, JSON documents stored under keys that begin with
[fts_json_prefix](#fts_json_prefix-string) are indexed in shared memory:
every top-level *string* field becomes a *field:value* entry pointing at
the document key. Numbers, booleans and nested values are not indexed.
Values are indexed decoded, and a malformed document, or one over the
*cachedb_nats_fts*
[json_max_depth](../cachedb_nats_fts/README.md#json_max_depth-integer) or
[json_max_bytes](../cachedb_nats_fts/README.md#json_max_bytes-integer)
limits, is not indexed (see the
[cachedb_nats_fts overview](../cachedb_nats_fts/README.md#overview)).
These are separate from this module's own
[json_max_depth](#json_max_depth-integer) and
[json_max_bytes](#json_max_bytes-integer), which apply to the documents
it reads.


The index answers the CacheDB `query()` and `update()` calls that
Expand Down Expand Up @@ -795,8 +805,11 @@ ignored.** Only usrloc rows expire.
and `.` `_` `-` `/` `\` `=` (see [KV Key Validation](#kv-key-validation)).
- **Values:** usrloc rows are limited by
[max_value_size](#max_value_size-integer) (1 MiB by
default); JSON documents over 1 MiB or nested deeper than 64 levels are
rejected.
default) when written. A JSON document read back that is larger than
[json_max_bytes](#json_max_bytes-integer) (1 MiB by default), nested
deeper than [json_max_depth](#json_max_depth-integer) (64 levels by
default) or holding a NUL byte is refused: a query skips it and logs
an error.
- **Revisions are 32-bit in the script.**
[nats_kv_update()](#nats_kv_updatebucket-key-value-expected_rev) compares
against a revision truncated to 32 bits, so a compare-and-swap fails
Expand Down Expand Up @@ -1668,7 +1681,10 @@ oversize row is detected before the CAS write and the offending
contact's save fails cleanly — never a silent truncation or
corruption. Set this to the deployment's real per-message cap
(and no larger than the stream's `max_msg_size`).
A value **<= 0** disables the guard.
A value **<= 0** disables the guard. Keep
[json_max_bytes](#json_max_bytes-integer) at or above this value: a
larger row is written, then refused on every read (a warning is logged
at startup).


*Default value is "1048576" (1 MiB, the
Expand All @@ -1682,6 +1698,67 @@ modparam("cachedb_nats", "max_value_size", 65536)
```


#### json_max_depth (integer)


Maximum nesting depth, counting the top-level object as 1, of a JSON
document read from the bucket (usrloc rows and documents returned by
CacheDB queries, and the
[nats_reg_show](#cachedb_natsnats_reg_show) MI command). A deeper
document is refused before it is parsed: a query skips it and logs an
error. The JSON parser recurses once per level, so this bounds the
stack a document written to the bucket can use. The value must be
between 1 and 1024; any other value is an error in the configuration,
reported when it is read (`opensips -C` included), and OpenSIPS does
not start.


This limit applies to what *cachedb_nats* reads. The
[cachedb_nats_fts](../cachedb_nats_fts/README.md) module has its own
[json_max_depth](../cachedb_nats_fts/README.md#json_max_depth-integer)
for the documents it indexes.


*Default value is "64".*


```opensips title="Set json_max_depth parameter"
...
modparam("cachedb_nats", "json_max_depth", 16)
...
```


#### json_max_bytes (integer)


Maximum size, in bytes, of a JSON document read from the bucket (as
for [json_max_depth](#json_max_depth-integer)). A larger document is
refused before it is parsed: a query skips it and logs an error. The
value must be at least 2 (the size of `{}`); a smaller value is an
error in the configuration, reported when it is read (`opensips -C`
included), and OpenSIPS does not start. Keep it at or above
[max_value_size](#max_value_size-integer); otherwise a warning is
logged at startup.


This limit applies to what *cachedb_nats* reads. The
[cachedb_nats_fts](../cachedb_nats_fts/README.md) module has its own
[json_max_bytes](../cachedb_nats_fts/README.md#json_max_bytes-integer)
for the documents it indexes.


*Default value is "1048576" (1 MiB, the NATS `max_payload`
default).*


```opensips title="Set json_max_bytes parameter"
...
modparam("cachedb_nats", "json_max_bytes", 2097152)
...
```


#### kv_op_timeout_ms (integer)


Expand Down
17 changes: 13 additions & 4 deletions modules-contrib/cachedb_nats/cachedb_nats.c
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
#include "cachedb_nats.h"
#include "cachedb_nats_dbase.h"
#include "cachedb_nats_json.h"
#include "cachedb_nats_json_internal.h" /* json_max_* modparams */
#include "../cachedb_nats_fts/cachedb_nats_fts_api.h"
#include "cachedb_nats_watch.h"
#include "cachedb_nats_native.h"
Expand Down Expand Up @@ -352,6 +353,10 @@ static const param_export_t params[] = {
{"reap_interval", INT_PARAM, &nats_reap_interval},
{"expired_linger", INT_PARAM, &nats_expired_linger},
{"max_value_size", INT_PARAM, &nats_max_value_size},
{"json_max_depth", INT_PARAM|USE_FUNC_PARAM,
(void *)cdbn_json_set_max_depth},
{"json_max_bytes", INT_PARAM|USE_FUNC_PARAM,
(void *)cdbn_json_set_max_bytes},
{"kv_watch", STR_PARAM|USE_FUNC_PARAM, (void *)&set_watch_pattern},
{"reconnect_wait_ms", INT_PARAM, &nats_cdb_reconnect_wait_ms},
{"max_reconnect", INT_PARAM, &nats_cdb_max_reconnect},
Expand Down Expand Up @@ -502,10 +507,10 @@ struct module_exports exports = {
"cachedb_nats", /* module name */
MOD_TYPE_CACHEDB, /* class of this module */
MODULE_VERSION,
RTLD_NOW | RTLD_GLOBAL, /* dlopen flags: GLOBAL so the optional
* cachedb_nats_fts module (loaded after
* us) resolves the shared JSON walkers
* this module defines */
DEFAULT_DLFLAGS, /* dlopen flags: never RTLD_GLOBAL, which
* would let this module's symbols, its
* exports included, stand in for those
* of modules loaded after it */
0, /* load function */
&deps, /* OpenSIPS module dependencies */
cmds, /* exported functions */
Expand Down Expand Up @@ -562,6 +567,10 @@ static int init_check_params(void)
* every usrloc read/write, watch event and reap pass). */
fts_json_prefix_len = fts_json_prefix ? (int)strlen(fts_json_prefix) : 0;

if (cdbn_json_check_limits() < 0)
return -1;
cdbn_json_check_row_size(nats_max_value_size);

/* Kv_ttl becomes the KV bucket's
* MaxAge (nats_pool.c: kvCfg.TTL). Stream MaxAge takes precedence over
* per-message TTL and would SILENTLY EXPIRE PERMANENT CONTACTS
Expand Down
41 changes: 41 additions & 0 deletions modules-contrib/cachedb_nats/cachedb_nats_json_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
#include <time.h>

#include "../../cachedb/cachedb.h"
#include "../../sr_module.h" /* modparam_t */
#include "cachedb_nats_json.h"
#include "../../locking.h"

Expand Down Expand Up @@ -140,6 +141,46 @@ const char *cdbn_parse_json_string(const char *p, const char *end,
*/
int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out);

/*
* Limits json_parse_guard() applies before cJSON parses a broker-supplied
* document (modparams json_max_depth and json_max_bytes): a document
* nested deeper, or larger, is refused. cJSON recurses once per nesting
* level, hence the depth ceiling.
*/
#define CDBN_JSON_DEFAULT_MAX_DEPTH 64
#define CDBN_JSON_DEFAULT_MAX_BYTES (1 * 1024 * 1024)
#define CDBN_JSON_DEPTH_CEILING 1024
extern int cdbn_json_max_depth;
extern int cdbn_json_max_bytes;

/*
* The json_max_depth / json_max_bytes modparam setters (INT_PARAM): check
* the value as the config is read, so that "opensips -C" reports a bad
* one, and store it.
*
* @return 0 when stored; -1, with an error logged and the value
* unchanged, when out of range (depth 1..CDBN_JSON_DEPTH_CEILING,
* bytes at least 2, the size of "{}").
*/
int cdbn_json_set_max_depth(modparam_t type, void *val);
int cdbn_json_set_max_bytes(modparam_t type, void *val);

/*
* Check both limits again (mod_init).
*
* @return 0 when valid; -1, with an error logged, otherwise.
*/
int cdbn_json_check_limits(void);

/*
* Warn when json_max_bytes is below @max_value_size (the usrloc row write
* cap; <= 0 means none): such a row is written, then refused on every
* read.
*
* @return 1 when it warned, 0 otherwise.
*/
int cdbn_json_check_row_size(int max_value_size);

/* --- JSON sink / serializer (cachedb_nats_json_ser.c) -------------- */

typedef struct {
Expand Down
79 changes: 67 additions & 12 deletions modules-contrib/cachedb_nats/cachedb_nats_json_walk.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@
*/

/*
* cachedb_nats_json_walk.c — the shared, dependency-free JSON walkers
* cachedb_nats_json_walk.c — the dependency-free JSON walkers
* (cdbn_skip_ws, cdbn_parse_json_string, cdbn_skip_json_value, cdbn_safe_json_to_dict)
* used by this module's JSON layer AND by the optional cachedb_nats_fts
* module (declared in cachedb_nats_json_internal.h). Split into their
* own TU so unit tests can link them without dragging either module's
* full dependency graph.
* used by this module's JSON layer (declared in
* cachedb_nats_json_internal.h). Split into their own TU so unit tests
* can link them without dragging the module's full dependency graph.
*/

#include <stdint.h>
Expand All @@ -43,12 +42,68 @@
* the recursive cJSON_Parse() (see json_parse_guard). cJSON recurses
* one C stack frame per nesting level with no internal cap, so an
* attacker who can publish to the KV bucket could otherwise crash a SIP
* worker with a deeply nested value. Depth 64 is far beyond any real
* usrloc/cachedb document; the byte cap matches NATS's default
* max_payload (1 MiB).
* worker with a deeply nested value. The json_max_depth / json_max_bytes
* modparams; the defaults (depth 64, NATS's default max_payload of 1 MiB)
* are far beyond any real usrloc/cachedb document.
*/
#define NATS_JSON_MAX_DEPTH 64
#define NATS_JSON_MAX_BYTES (1 * 1024 * 1024)
int cdbn_json_max_depth = CDBN_JSON_DEFAULT_MAX_DEPTH;
int cdbn_json_max_bytes = CDBN_JSON_DEFAULT_MAX_BYTES;

static int valid_max_depth(int v)
{
if (v < 1 || v > CDBN_JSON_DEPTH_CEILING) {
LM_ERR("json_max_depth %d out of range: 1 (the top-level object) "
"to %d (deeper risks the stack in the recursive parser)\n",
v, CDBN_JSON_DEPTH_CEILING);
return 0;
}
return 1;
}

static int valid_max_bytes(int v)
{
if (v < 2) {
LM_ERR("json_max_bytes %d out of range: at least 2 (\"{}\")\n", v);
return 0;
}
return 1;
}

int cdbn_json_set_max_depth(modparam_t type, void *val)
{
int v = (int)(long)val;

if (!valid_max_depth(v))
return -1;
cdbn_json_max_depth = v;
return 0;
}

int cdbn_json_set_max_bytes(modparam_t type, void *val)
{
int v = (int)(long)val;

if (!valid_max_bytes(v))
return -1;
cdbn_json_max_bytes = v;
return 0;
}

int cdbn_json_check_limits(void)
{
return valid_max_depth(cdbn_json_max_depth)
&& valid_max_bytes(cdbn_json_max_bytes) ? 0 : -1;
}

int cdbn_json_check_row_size(int max_value_size)
{
if (max_value_size <= 0 || cdbn_json_max_bytes >= max_value_size)
return 0;
LM_WARN("json_max_bytes (%d) is below max_value_size (%d): a usrloc "
"row larger than json_max_bytes is written, then refused on "
"every read\n", cdbn_json_max_bytes, max_value_size);
return 1;
}

/**
* cdbn_skip_ws() — Advance past JSON whitespace characters.
Expand Down Expand Up @@ -236,7 +291,7 @@ int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out)
int rc;

if (json_parse_guard(data, data_len,
NATS_JSON_MAX_DEPTH, NATS_JSON_MAX_BYTES) != 0) {
cdbn_json_max_depth, cdbn_json_max_bytes) != 0) {
LM_WARN("rejecting broker JSON document (%d bytes): failed "
"depth/size/NUL guard before parse\n", data_len);
return -1;
Expand All @@ -245,7 +300,7 @@ int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out)
if (data_len < (int)sizeof(stackbuf)) {
buf = stackbuf;
} else {
buf = pkg_malloc(data_len + 1);
buf = pkg_malloc((size_t)data_len + 1);
if (!buf) {
LM_ERR("no pkg memory for %d-byte JSON parse copy\n",
data_len);
Expand Down
2 changes: 2 additions & 0 deletions modules-contrib/cachedb_nats/test/cn_ut.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ void cn_ut_doc_filter(void);
void cn_ut_emit_rows(void);
void cn_ut_fmt_table(void);
void cn_ut_fts_optional(void);
void cn_ut_global_scope(void);
void cn_ut_index_stale_recovery(void);
void cn_ut_insecure_url_warn(void);
void cn_ut_json_escape(void);
void cn_ut_json_foreach(void);
void cn_ut_json_limits(void);
void cn_ut_json_name_passthrough(void);
void cn_ut_json_parse_guard(void);
void cn_ut_kv_epoch_refresh(void);
Expand Down
2 changes: 2 additions & 0 deletions modules-contrib/cachedb_nats/test/test_all.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ void cn_ut_all(void)
cn_ut_emit_rows();
cn_ut_fmt_table();
cn_ut_fts_optional();
cn_ut_global_scope();
cn_ut_index_stale_recovery();
cn_ut_insecure_url_warn();
cn_ut_json_escape();
cn_ut_json_foreach();
cn_ut_json_limits();
cn_ut_json_name_passthrough();
cn_ut_json_parse_guard();
cn_ut_kv_epoch_refresh();
Expand Down
Loading
Loading