summaryrefslogtreecommitdiffstats
path: root/modules/cookies
diff options
context:
space:
mode:
Diffstat (limited to 'modules/cookies')
-rw-r--r--modules/cookies/README.rst56
-rw-r--r--modules/cookies/cookiectl.c689
-rw-r--r--modules/cookies/cookiectl.h35
-rw-r--r--modules/cookies/cookiemonster.c464
-rw-r--r--modules/cookies/cookiemonster.h15
-rw-r--r--modules/cookies/cookies.c78
6 files changed, 1337 insertions, 0 deletions
diff --git a/modules/cookies/README.rst b/modules/cookies/README.rst
new file mode 100644
index 0000000..b8aba8a
--- /dev/null
+++ b/modules/cookies/README.rst
@@ -0,0 +1,56 @@
+.. SPDX-License-Identifier: GPL-3.0-or-later
+
+.. _mod-cookies:
+
+DNS Cookies
+===========
+
+The module performs most of the :rfc:`7873` DNS cookies functionality. Its main purpose is to check the cookies of inbound queries and responses. It is also used to alter the behaviour of the cookie functionality.
+
+Example Configuration
+---------------------
+
+.. code-block:: lua
+
+ -- Load the module before the 'iterate' layer.
+ modules = {
+ 'cookies < iterate'
+ }
+
+ -- Configure the client part of the resolver. Set 8 bytes of the client
+ -- secret and choose the hashing algorithm to be used.
+ -- Use a string composed of hexadecimal digits to set the secret.
+ cookies.config { client_secret = '0123456789ABCDEF',
+ client_cookie_alg = 'FNV-64' }
+
+ -- Configure the server part of the resolver.
+ cookies.config { server_secret = 'FEDCBA9876543210',
+ server_cookie_alg = 'FNV-64' }
+
+ -- Enable client cookie functionality. (Add cookies into outbound
+ -- queries.)
+ cookies.config { client_enabled = true }
+
+ -- Enable server cookie functionality. (Handle cookies in inbound
+ -- requests.)
+ cookies.config { server_enabled = true }
+
+.. tip:: If you want to change several parameters regarding the client or server configuration then do it within a single ``cookies.config()`` invocation.
+
+.. warning:: The module must be loaded before any other module that has direct influence on query processing and response generation. The module must be able to intercept an incoming query before the processing of the actual query starts. It must also be able to check the cookies of inbound responses and eventually discard them before they are handled by other functional units.
+
+Properties
+----------
+
+.. function:: cookies.config(configuration)
+
+ :param table configuration: part of cookie configuration to be changed, may be called without parameter
+ :return: JSON dictionary containing current configuration
+
+ The function may be called without any parameter. In such case it only returns current configuration. The returned JSON also contains available algorithm choices.
+
+Dependencies
+------------
+
+* `Nettle <https://www.lysator.liu.se/~nisse/nettle/>`_ required for HMAC-SHA256
+
diff --git a/modules/cookies/cookiectl.c b/modules/cookies/cookiectl.c
new file mode 100644
index 0000000..f1ab80a
--- /dev/null
+++ b/modules/cookies/cookiectl.c
@@ -0,0 +1,689 @@
+/* Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#include <ccan/json/json.h>
+#include <ctype.h>
+#include <libknot/rrtype/opt-cookie.h>
+#include <libknot/db/db_lmdb.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "lib/cookies/alg_containers.h"
+#include "modules/cookies/cookiectl.h"
+
+#define NAME_CLIENT_ENABLED "client_enabled"
+#define NAME_CLIENT_SECRET "client_secret"
+#define NAME_CLIENT_COOKIE_ALG "client_cookie_alg"
+#define NAME_AVAILABLE_CLIENT_COOKIE_ALGS "available_client_cookie_algs"
+
+#define NAME_SERVER_ENABLED "server_enabled"
+#define NAME_SERVER_SECRET "server_secret"
+#define NAME_SERVER_COOKIE_ALG "server_cookie_alg"
+#define NAME_AVAILABLE_SERVER_COOKIE_ALGS "available_server_cookie_algs"
+
+/**
+ * @brief Initialises cookie control context.
+ * @param ctx cookie control context
+ */
+static void kr_cookie_ctx_init(struct kr_cookie_ctx *ctx)
+{
+ if (!ctx) {
+ return;
+ }
+
+ memset(ctx, 0, sizeof(*ctx));
+
+ ctx->clnt.current.alg_id = ctx->clnt.recent.alg_id = -1;
+ ctx->srvr.current.alg_id = ctx->srvr.recent.alg_id = -1;
+}
+
+/**
+ * @brief Check whether node holds proper 'enabled' value.
+ * @param node JSON node holding the value
+ * @return true if value OK
+ */
+static bool enabled_ok(const JsonNode *node)
+{
+ if (kr_fails_assert(node))
+ return false;
+
+ return node->tag == JSON_BOOL;
+}
+
+/**
+ * @brief Check whether node holds proper 'secret' value.
+ * @param node JSON node holding the value
+ * @return true if value OK
+ */
+static bool secret_ok(const JsonNode *node)
+{
+ if (kr_fails_assert(node))
+ return false;
+
+ if (node->tag != JSON_STRING) {
+ return false;
+ }
+
+ const char *hexstr = node->string_;
+
+ size_t len = strlen(hexstr);
+ if ((len % 2) != 0) {
+ return false;
+ }
+ /* A check for minimal required length could also be performed. */
+
+ for (size_t i = 0; i < len; ++i) {
+ if (!isxdigit(tolower(hexstr[i]))) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * @brief Find hash function with given name.
+ * @param node JSON node holding the value
+ * @param table lookup table with algorithm names
+ * @return pointer to table entry or NULL on error if does not exist
+ */
+static const knot_lookup_t *hash_func_lookup(const JsonNode *node,
+ const knot_lookup_t table[])
+{
+ if (!node || node->tag != JSON_STRING) {
+ return NULL;
+ }
+
+ return knot_lookup_by_name(table, node->string_);
+}
+
+/**
+ * @brief Creates a cookie secret structure.
+ * @param size size of the actual secret
+ * @param zero set to true if value should be cleared
+ * @return pointer to new structure, NULL on failure or if @size is zero
+ */
+static struct kr_cookie_secret *new_cookie_secret(size_t size, bool zero)
+{
+ if (size == 0) {
+ return NULL;
+ }
+
+ struct kr_cookie_secret *sq = malloc(sizeof(*sq) + size);
+ if (!sq) {
+ return NULL;
+ }
+
+ sq->size = size;
+ if (zero) {
+ memset(sq->data, 0, size);
+ }
+ return sq;
+}
+
+/**
+ * @brief Clone a cookie secret.
+ * @param sec secret to be cloned
+ * @return pointer to new structure, NULL on failure or if @size is zero
+ */
+static struct kr_cookie_secret *clone_cookie_secret(const struct kr_cookie_secret *sec)
+{
+ if (!sec || sec->size == 0) {
+ return NULL;
+ }
+
+ struct kr_cookie_secret *sq = malloc(sizeof(*sq) + sec->size);
+ if (!sq) {
+ return NULL;
+ }
+
+ sq->size = sec->size;
+ memcpy(sq->data, sec->data, sq->size);
+ return sq;
+}
+
+static int hexchar2val(int d)
+{
+ if (('0' <= d) && (d <= '9')) {
+ return d - '0';
+ } else if (('a' <= d) && (d <= 'f')) {
+ return d - 'a' + 0x0a;
+ } else {
+ return -1;
+ }
+}
+
+static int hexval2char(int i)
+{
+ if ((0 <= i) && (i <= 9)) {
+ return i + '0';
+ } else if ((0x0a <= i) && (i <= 0x0f)) {
+ return i - 0x0a + 'A';
+ } else {
+ return -1;
+ }
+}
+
+/**
+ * @brief Converts string containing two-digit hexadecimal number into int.
+ * @param hexstr hexadecimal string
+ * @return -1 on error, value from 0 to 255 else.
+ */
+static int hexbyte2int(const char *hexstr)
+{
+ if (!hexstr) {
+ return -1;
+ }
+
+ int dhi = tolower(hexstr[0]);
+ if (!isxdigit(dhi)) {
+ /* Exit also on empty string. */
+ return -1;
+ }
+ int dlo = tolower(hexstr[1]);
+ if (!isxdigit(dlo)) {
+ return -1;
+ }
+
+ dhi = hexchar2val(dhi);
+ if (kr_fails_assert(dhi != -1))
+ return -1;
+ dlo = hexchar2val(dlo);
+ if (kr_fails_assert(dlo != -1))
+ return -1;
+
+ return (dhi << 4) | dlo;
+}
+
+/**
+ * @brief Writes two hexadecimal digits (two byes) into given memory location.
+ * @param tgt target location
+ * @param i number from 0 to 255
+ * @return 0 on success, -1 on failure
+ */
+static int int2hexbyte(char *tgt, int i)
+{
+ if (!tgt || i < 0x00 || i > 0xff) {
+ return -1;
+ }
+
+ int ilo = hexval2char(i & 0x0f);
+ if (kr_fails_assert(ilo != -1))
+ return -1;
+ int ihi = hexval2char((i >> 4) & 0x0f);
+ if (kr_fails_assert(ihi != -1))
+ return -1;
+
+ tgt[0] = ihi;
+ tgt[1] = ilo;
+
+ return 0;
+}
+
+/**
+ * @brief Reads a string containing hexadecimal values.
+ * @note String must consist of hexadecimal digits only and must have even
+ * non-zero length.
+ */
+static struct kr_cookie_secret *new_sq_from_hexstr(const char *hexstr)
+{
+ if (!hexstr) {
+ return NULL;
+ }
+
+ size_t len = strlen(hexstr);
+ if ((len % 2) != 0) {
+ return NULL;
+ }
+
+ struct kr_cookie_secret *sq = new_cookie_secret(len / 2, false);
+ if (!sq) {
+ return NULL;
+ }
+
+ uint8_t *data = sq->data;
+ for (size_t i = 0; i < len; i += 2) {
+ int num = hexbyte2int(hexstr + i);
+ if (num == -1) {
+ free(sq);
+ return NULL;
+ }
+ if (kr_fails_assert(0x00 <= num && num <= 0xff)) {
+ free(sq);
+ return NULL;
+ }
+ *data = num;
+ ++data;
+ }
+
+ return sq;
+}
+
+/**
+ * @brief Creates new secret.
+ * @param node JSON node holding the secret value
+ * @return pointer to newly allocated secret, NULL on error
+ */
+static struct kr_cookie_secret *create_secret(const JsonNode *node)
+{
+ if (!node) {
+ return NULL;
+ }
+
+ if (node->tag != JSON_STRING) {
+ return NULL;
+ }
+
+ return new_sq_from_hexstr(node->string_);
+}
+
+/**
+ * @brief Check whether configuration node contains valid values.
+ */
+static bool configuration_node_ok(const JsonNode *node)
+{
+ if (kr_fails_assert(node))
+ return false;
+
+ if (!node->key) {
+ /* All top most nodes must have names. */
+ return false;
+ }
+
+ if (strcmp(node->key, NAME_CLIENT_ENABLED) == 0) {
+ return enabled_ok(node);
+ } else if (strcmp(node->key, NAME_CLIENT_SECRET) == 0) {
+ return secret_ok(node);
+ } else if (strcmp(node->key, NAME_CLIENT_COOKIE_ALG) == 0) {
+ return hash_func_lookup(node, kr_cc_alg_names) != NULL;
+ } else if (strcmp(node->key, NAME_SERVER_ENABLED) == 0) {
+ return enabled_ok(node);
+ } else if (strcmp(node->key, NAME_SERVER_SECRET) == 0) {
+ return secret_ok(node);
+ } else if (strcmp(node->key, NAME_SERVER_COOKIE_ALG) == 0) {
+ return hash_func_lookup(node, kr_sc_alg_names) != NULL;
+ }
+
+ return false;
+}
+
+/**
+ * @brief Creates a new string from secret quantity.
+ * @param sq secret quantity
+ * @return newly allocated string or NULL on error
+ */
+static char *new_hexstr_from_sq(const struct kr_cookie_secret *sq)
+{
+ if (!sq) {
+ return NULL;
+ }
+
+ char *new_str = malloc((sq->size * 2) + 1);
+ if (!new_str) {
+ return NULL;
+ }
+
+ char *tgt = new_str;
+ for (size_t i = 0; i < sq->size; ++i) {
+ if (0 != int2hexbyte(tgt, sq->data[i])) {
+ free(new_str);
+ return NULL;
+ }
+ tgt += 2;
+ }
+
+ *tgt = '\0';
+ return new_str;
+}
+
+static bool read_secret(JsonNode *root, const char *node_name,
+ const struct kr_cookie_secret *secret)
+{
+ if (kr_fails_assert(root && node_name && secret))
+ return false;
+
+ char *secret_str = new_hexstr_from_sq(secret);
+ if (!secret_str) {
+ return false;
+ }
+
+ JsonNode *str_node = json_mkstring(secret_str);
+ if (!str_node) {
+ free(secret_str);
+ return false;
+ }
+
+ json_append_member(root, node_name, str_node);
+
+ free(secret_str);
+ return true;
+}
+
+static bool read_available_hashes(JsonNode *root, const char *root_name,
+ const knot_lookup_t table[])
+{
+ if (kr_fails_assert(root && root_name && table))
+ return false;
+
+ JsonNode *array = json_mkarray();
+ if (!array) {
+ return false;
+ }
+
+ const knot_lookup_t *aux_ptr = table;
+ while (aux_ptr && (aux_ptr->id >= 0) && aux_ptr->name) {
+ JsonNode *element = json_mkstring(aux_ptr->name);
+ if (!element) {
+ goto fail;
+ }
+ json_append_element(array, element);
+ ++aux_ptr;
+ }
+
+ json_append_member(root, root_name, array);
+
+ return true;
+
+fail:
+ if (array) {
+ json_delete(array);
+ }
+ return false;
+}
+
+/**
+ * @brief Check whether new settings are different from the old ones.
+ */
+static bool is_modified(const struct kr_cookie_comp *running,
+ struct kr_cookie_secret *secr,
+ const knot_lookup_t *alg_lookup)
+{
+ if (kr_fails_assert(running))
+ return false;
+
+ if (alg_lookup && alg_lookup->id >= 0) {
+ if (running->alg_id != alg_lookup->id) {
+ return true;
+ }
+ }
+
+ if (secr) {
+ if (kr_fails_assert(secr->size > 0))
+ return false;
+ if (running->secr->size != secr->size ||
+ 0 != memcmp(running->secr->data, secr->data,
+ running->secr->size)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * @brief Returns newly allocated secret via pointer argument.
+ */
+static bool obtain_secret(JsonNode *root_node, struct kr_cookie_secret **secret,
+ const char *name)
+{
+ if (kr_fails_assert(secret && name))
+ return false;
+
+ const JsonNode *node;
+ if ((node = json_find_member(root_node, name)) != NULL) {
+ *secret = create_secret(node);
+ if (!*secret) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * @brief Updates the current configuration and moves current to recent.
+ */
+static void update_running(struct kr_cookie_settings *running,
+ struct kr_cookie_secret **secret,
+ const knot_lookup_t *alg_lookup)
+{
+ if (kr_fails_assert(running && secret) || kr_fails_assert(*secret || alg_lookup))
+ return;
+
+ running->recent.alg_id = -1;
+ free(running->recent.secr);
+ running->recent.secr = NULL;
+
+ running->recent.alg_id = running->current.alg_id;
+ if (alg_lookup) {
+ if (kr_fails_assert(alg_lookup->id >= 0))
+ return;
+ running->current.alg_id = alg_lookup->id;
+ }
+
+ if (*secret) {
+ running->recent.secr = running->current.secr;
+ running->current.secr = *secret;
+ *secret = NULL;
+ } else {
+ running->recent.secr = clone_cookie_secret(running->current.secr);
+ }
+}
+
+/**
+ * @brief Applies modification onto client/server running configuration.
+ * @note The @a secret is going to be consumed.
+ * @param secret pointer to new secret
+ * @param alg_lookup new algorithm
+ * @param enabled JSON node holding boolean value
+ */
+static void apply_changes(struct kr_cookie_settings *running,
+ struct kr_cookie_secret **secret,
+ const knot_lookup_t *alg_lookup,
+ const JsonNode *enabled)
+{
+ if (kr_fails_assert(running && secret))
+ return;
+
+ if (is_modified(&running->current, *secret, alg_lookup)) {
+ update_running(running, secret, alg_lookup);
+ }
+
+ if (enabled) {
+ kr_assert(enabled->tag == JSON_BOOL);
+ running->enabled = enabled->bool_;
+ }
+}
+
+/**
+ * @brief Applies configuration.
+ *
+ * @note The function must be called after the input values have been checked
+ * for validity. Only first found values are applied.
+ *
+ * @param ctx cookie configuration context
+ * @param root_node JSON root node
+ * @return true if changes were applied
+ */
+static bool config_apply_json(struct kr_cookie_ctx *ctx, JsonNode *root_node)
+{
+ if (kr_fails_assert(ctx && root_node))
+ return;
+
+ /*
+ * These must be allocated before actual change. Allocation failure
+ * should not leave configuration in inconsistent state.
+ */
+ struct kr_cookie_secret *new_clnt_secret = NULL;
+ struct kr_cookie_secret *new_srvr_secret = NULL;
+ if (!obtain_secret(root_node, &new_clnt_secret, NAME_CLIENT_SECRET)) {
+ return false;
+ }
+ if (!obtain_secret(root_node, &new_srvr_secret, NAME_SERVER_SECRET)) {
+ free(new_clnt_secret);
+ return false;
+ }
+
+ /* Algorithm pointers. */
+ const knot_lookup_t *clnt_lookup = hash_func_lookup(json_find_member(root_node, NAME_CLIENT_COOKIE_ALG), kr_cc_alg_names);
+ const knot_lookup_t *srvr_lookup = hash_func_lookup(json_find_member(root_node, NAME_SERVER_COOKIE_ALG), kr_sc_alg_names);
+
+ const JsonNode *clnt_enabled_node = json_find_member(root_node, NAME_CLIENT_ENABLED);
+ const JsonNode *srvr_enabled_node = json_find_member(root_node, NAME_SERVER_ENABLED);
+
+ apply_changes(&ctx->clnt, &new_clnt_secret, clnt_lookup, clnt_enabled_node);
+ apply_changes(&ctx->srvr, &new_srvr_secret, srvr_lookup, srvr_enabled_node);
+
+ /*
+ * Allocated secrets should be already consumed. There is no need to
+ * free them.
+ */
+
+ return true;
+}
+
+bool config_apply(struct kr_cookie_ctx *ctx, const char *args)
+{
+ if (!ctx) {
+ return false;
+ }
+
+ if (!args || !strlen(args)) {
+ return true;
+ }
+
+ if (!args || !strlen(args)) {
+ return true;
+ }
+
+ bool success = false;
+
+ /* Check whether all supplied data are valid. */
+ JsonNode *root_node = json_decode(args);
+ if (!root_node) {
+ return false;
+ }
+ JsonNode *node;
+ json_foreach (node, root_node) {
+ success = configuration_node_ok(node);
+ if (!success) {
+ break;
+ }
+ }
+
+ /* Apply configuration if values seem to be OK. */
+ if (success) {
+ success = config_apply_json(ctx, root_node);
+ }
+
+ json_delete(root_node);
+
+ return success;
+}
+
+char *config_read(struct kr_cookie_ctx *ctx)
+{
+ if (!ctx) {
+ return NULL;
+ }
+
+ const knot_lookup_t *lookup;
+ char *result;
+ JsonNode *root_node = json_mkobject();
+ if (!root_node) {
+ return NULL;
+ }
+
+ json_append_member(root_node, NAME_CLIENT_ENABLED,
+ json_mkbool(ctx->clnt.enabled));
+
+ read_secret(root_node, NAME_CLIENT_SECRET, ctx->clnt.current.secr);
+
+ lookup = knot_lookup_by_id(kr_cc_alg_names, ctx->clnt.current.alg_id);
+ if (lookup) {
+ json_append_member(root_node, NAME_CLIENT_COOKIE_ALG,
+ json_mkstring(lookup->name));
+ }
+
+ read_available_hashes(root_node, NAME_AVAILABLE_CLIENT_COOKIE_ALGS,
+ kr_cc_alg_names);
+
+ json_append_member(root_node, NAME_SERVER_ENABLED,
+ json_mkbool(ctx->srvr.enabled));
+
+ read_secret(root_node, NAME_SERVER_SECRET, ctx->srvr.current.secr);
+
+ lookup = knot_lookup_by_id(kr_sc_alg_names, ctx->srvr.current.alg_id);
+ if (lookup) {
+ json_append_member(root_node, NAME_SERVER_COOKIE_ALG,
+ json_mkstring(lookup->name));
+ }
+
+ read_available_hashes(root_node, NAME_AVAILABLE_SERVER_COOKIE_ALGS,
+ kr_sc_alg_names);
+
+ result = json_encode(root_node);
+ json_delete(root_node);
+ return result;
+}
+
+int config_init(struct kr_cookie_ctx *ctx)
+{
+ if (!ctx) {
+ return kr_error(EINVAL);
+ }
+
+ kr_cookie_ctx_init(ctx);
+
+ struct kr_cookie_secret *cs = new_cookie_secret(KNOT_OPT_COOKIE_CLNT,
+ true);
+ struct kr_cookie_secret *ss = new_cookie_secret(KNOT_OPT_COOKIE_CLNT,
+ true);
+ if (!cs || !ss) {
+ free(cs);
+ free(ss);
+ return kr_error(ENOMEM);
+ }
+
+ const knot_lookup_t *clookup = knot_lookup_by_name(kr_cc_alg_names,
+ "FNV-64");
+ const knot_lookup_t *slookup = knot_lookup_by_name(kr_sc_alg_names,
+ "FNV-64");
+ if (!clookup || !slookup) {
+ free(cs);
+ free(ss);
+ return kr_error(ENOENT);
+ }
+
+ ctx->clnt.current.secr = cs;
+ ctx->clnt.current.alg_id = clookup->id;
+
+ ctx->srvr.current.secr = ss;
+ ctx->srvr.current.alg_id = slookup->id;
+
+ return kr_ok();
+}
+
+void config_deinit(struct kr_cookie_ctx *ctx)
+{
+ if (!ctx) {
+ return;
+ }
+
+ ctx->clnt.enabled = false;
+
+ free(ctx->clnt.recent.secr);
+ ctx->clnt.recent.secr = NULL;
+
+ free(ctx->clnt.current.secr);
+ ctx->clnt.current.secr = NULL;
+
+ ctx->srvr.enabled = false;
+
+ free(ctx->srvr.recent.secr);
+ ctx->srvr.recent.secr = NULL;
+
+ free(ctx->srvr.current.secr);
+ ctx->srvr.current.secr = NULL;
+}
diff --git a/modules/cookies/cookiectl.h b/modules/cookies/cookiectl.h
new file mode 100644
index 0000000..6740e16
--- /dev/null
+++ b/modules/cookies/cookiectl.h
@@ -0,0 +1,35 @@
+/* Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#pragma once
+
+#include "lib/cookies/control.h"
+
+/**
+ * @brief Sets cookie control context structure.
+ * @param ctx cookie control context
+ * @param args JSON string describing configuration changes
+ * @return true if changes successfully applied
+ */
+bool config_apply(struct kr_cookie_ctx *ctx, const char *args);
+
+/**
+ * @brief Reads cookie control context structure.
+ * @param ctx cookie control context
+ * @return JSON string or NULL on error
+ */
+char *config_read(struct kr_cookie_ctx *ctx);
+
+/**
+ * @brief Initialises cookie control context to default values.
+ * @param ctx cookie control context
+ * @return kr_ok() or error code
+ */
+int config_init(struct kr_cookie_ctx *ctx);
+
+/**
+ * @brief Clears the cookie control context.
+ * @param ctx cookie control context
+ */
+void config_deinit(struct kr_cookie_ctx *ctx);
diff --git a/modules/cookies/cookiemonster.c b/modules/cookies/cookiemonster.c
new file mode 100644
index 0000000..595317b
--- /dev/null
+++ b/modules/cookies/cookiemonster.c
@@ -0,0 +1,464 @@
+/* Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#include <ccan/json/json.h>
+#include <libknot/db/db_lmdb.h>
+#include <libknot/error.h>
+#include <libknot/mm_ctx.h>
+#include <libknot/rrtype/opt-cookie.h>
+#include <libknot/version.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "lib/cookies/alg_containers.h"
+#include "lib/cookies/control.h"
+#include "lib/cookies/helper.h"
+#include "lib/cookies/lru_cache.h"
+#include "lib/cookies/nonce.h"
+#include "lib/resolve.h"
+#include "lib/rplan.h"
+#include "modules/cookies/cookiemonster.h"
+
+#define VERBOSE_MSG(qry, ...) kr_log_q(qry, COOKIES, __VA_ARGS__)
+
+/**
+ * Obtain address from query/response context if if can be obtained.
+ * @param req resolution context
+ * @return pointer to where the server socket address, NULL if not provided within context
+ */
+static const struct sockaddr *passed_server_sockaddr(const struct kr_request *req)
+{
+ if (!req || !req->upstream.addr) {
+ return NULL;
+ }
+
+ if (req->upstream.addr->sa_family == AF_INET ||
+ req->upstream.addr->sa_family == AF_INET6) {
+ return req->upstream.addr;
+ }
+
+ return NULL;
+}
+
+/**
+ * Obtain pointer to server socket address that matches obtained cookie.
+ * @param srvr_sa server socket address
+ * @param cc client cookie from the response
+ * @param cc_len client cookie size
+ * @param clnt_sett client cookie settings structure
+ * @retval 1 if cookie matches current settings
+ * @retval 0 if cookie matches recent settings
+ * @return -1 if cookie does not match
+ * @return -2 on any error
+ */
+static int srvr_sockaddr_cc_check(const struct sockaddr *srvr_sa,
+ const uint8_t *cc, uint16_t cc_len,
+ const struct kr_cookie_settings *clnt_sett)
+{
+ if (kr_fails_assert(cc && cc_len > 0 && clnt_sett))
+ return -2;
+
+ if (!srvr_sa) {
+ return -2;
+ }
+
+ if (kr_fails_assert(clnt_sett->current.secr))
+ return -2;
+
+ /* The address must correspond with the client cookie. */
+ struct knot_cc_input input = {
+ .clnt_sockaddr = NULL, /* Not supported yet. */
+ .srvr_sockaddr = srvr_sa,
+ .secret_data = clnt_sett->current.secr->data,
+ .secret_len = clnt_sett->current.secr->size
+ };
+
+ const struct knot_cc_alg *cc_alg = kr_cc_alg_get(clnt_sett->current.alg_id);
+ if (!cc_alg) {
+ return -2;
+ }
+ int comp_ret = -1; /* Cookie does not match. */
+ int ret = knot_cc_check(cc, cc_len, &input, cc_alg);
+ if (ret == KNOT_EOK) {
+ comp_ret = 1;
+ } else {
+ cc_alg = kr_cc_alg_get(clnt_sett->recent.alg_id);
+ if (clnt_sett->recent.secr && cc_alg) {
+ input.secret_data = clnt_sett->recent.secr->data;
+ input.secret_len = clnt_sett->recent.secr->size;
+ ret = knot_cc_check(cc, cc_len, &input, cc_alg);
+ if (ret == KNOT_EOK) {
+ comp_ret = 0;
+ }
+ }
+ }
+
+ return comp_ret;
+}
+
+/**
+ * Obtain cookie from cache.
+ * @note Cookies with invalid length are ignored.
+ * @param cache cache context
+ * @param sa key value
+ * @param cookie_opt entire EDNS cookie option (including header)
+ * @return true if a cookie exists in cache
+ */
+static const uint8_t *get_cookie_opt(kr_cookie_lru_t *cache,
+ const struct sockaddr *sa)
+{
+ if (kr_fails_assert(cache && sa))
+ return NULL;
+
+ const uint8_t *cached_cookie_opt = kr_cookie_lru_get(cache, sa);
+ if (!cached_cookie_opt) {
+ return NULL;
+ }
+
+ size_t cookie_opt_size = KNOT_EDNS_OPTION_HDRLEN +
+ knot_edns_opt_get_length(cached_cookie_opt);
+ if (cookie_opt_size > KR_COOKIE_OPT_MAX_LEN) {
+ return NULL;
+ }
+
+ return cached_cookie_opt;
+}
+
+/**
+ * Check whether the supplied cookie is cached under the given key.
+ * @param cache cache context
+ * @param sa key value
+ * @param cookie_opt cookie option to search for
+ */
+static bool is_cookie_cached(kr_cookie_lru_t *cache, const struct sockaddr *sa,
+ const uint8_t *cookie_opt)
+{
+ if (kr_fails_assert(cache && sa && cookie_opt))
+ return false;
+
+ const uint8_t *cached_opt = get_cookie_opt(cache, sa);
+ if (!cached_opt) {
+ return false;
+ }
+
+ uint16_t cookie_opt_size = KNOT_EDNS_OPTION_HDRLEN +
+ knot_edns_opt_get_length(cookie_opt);
+ uint16_t cached_opt_size = KNOT_EDNS_OPTION_HDRLEN +
+ knot_edns_opt_get_length(cached_opt);
+
+ if (cookie_opt_size != cached_opt_size) {
+ return false;
+ }
+
+ return memcmp(cookie_opt, cached_opt, cookie_opt_size) == 0;
+}
+
+/**
+ * Check cookie content and store it to cache.
+ */
+static bool check_cookie_content_and_cache(const struct kr_cookie_settings *clnt_sett,
+ struct kr_request *req,
+ uint8_t *pkt_cookie_opt,
+ kr_cookie_lru_t *cache)
+{
+ if (kr_fails_assert(clnt_sett && req && pkt_cookie_opt && cache))
+ return false;
+
+ const uint8_t *pkt_cookie_data = knot_edns_opt_get_data(pkt_cookie_opt);
+ uint16_t pkt_cookie_len = knot_edns_opt_get_length(pkt_cookie_opt);
+ /* knot_edns_opt_cookie_parse() returns error on invalid data. */
+
+ const uint8_t *pkt_cc = NULL, *pkt_sc = NULL;
+ uint16_t pkt_cc_len = 0, pkt_sc_len = 0;
+
+ int ret = knot_edns_opt_cookie_parse(pkt_cookie_data, pkt_cookie_len,
+ &pkt_cc, &pkt_cc_len,
+ &pkt_sc, &pkt_sc_len);
+ if (ret != KNOT_EOK || !pkt_sc) {
+ VERBOSE_MSG(NULL, "%s\n",
+ "got malformed DNS cookie or server cookie missing");
+ return false;
+ }
+ if (kr_fails_assert(pkt_cc_len == KNOT_OPT_COOKIE_CLNT))
+ return false;
+
+ /* Check server address against received client cookie. */
+ const struct sockaddr *srvr_sockaddr = passed_server_sockaddr(req);
+ ret = srvr_sockaddr_cc_check(srvr_sockaddr, pkt_cc, pkt_cc_len,
+ clnt_sett);
+ if (ret < 0) {
+ VERBOSE_MSG(NULL, "%s\n", "could not match received cookie");
+ return false;
+ }
+ if (kr_fails_assert(srvr_sockaddr))
+ return false;
+
+ /* Don't cache received cookies that don't match the current secret. */
+ if ((ret == 1) &&
+ !is_cookie_cached(cache, srvr_sockaddr, pkt_cookie_opt)) {
+ ret = kr_cookie_lru_set(cache, srvr_sockaddr, pkt_cookie_opt);
+ if (ret != kr_ok()) {
+ VERBOSE_MSG(NULL, "%s\n", "failed caching cookie");
+ } else {
+ VERBOSE_MSG(NULL, "%s\n", "cookie cached");
+ }
+ }
+
+ return true;
+}
+
+/** Process incoming response. */
+int check_response(kr_layer_t *ctx, knot_pkt_t *pkt)
+{
+ struct kr_request *req = ctx->req;
+ struct kr_query *qry = req->current_query;
+ struct kr_cookie_ctx *cookie_ctx = &req->ctx->cookie_ctx;
+
+ if (ctx->state & (KR_STATE_DONE | KR_STATE_FAIL)) {
+ return ctx->state;
+ }
+
+ if (!cookie_ctx->clnt.enabled || (qry->flags.TCP)) {
+ return ctx->state;
+ }
+
+ /* Obtain cookie if present in response. Don't check actual content. */
+ uint8_t *pkt_cookie_opt = NULL;
+ if (knot_pkt_has_edns(pkt)) {
+ pkt_cookie_opt = knot_edns_get_option(pkt->opt_rr,
+ KNOT_EDNS_OPTION_COOKIE);
+ }
+
+ kr_cookie_lru_t *cookie_cache = req->ctx->cache_cookie;
+
+ const struct sockaddr *srvr_sockaddr = passed_server_sockaddr(req);
+
+ if (!pkt_cookie_opt && srvr_sockaddr &&
+ get_cookie_opt(cookie_cache, srvr_sockaddr)) {
+ /* We haven't received any cookies although we should. */
+ VERBOSE_MSG(NULL, "%s\n",
+ "expected to receive a cookie but none received");
+ return KR_STATE_FAIL;
+ }
+
+ if (!pkt_cookie_opt) {
+ /* Don't do anything if no cookies expected and received. */
+ return ctx->state;
+ }
+
+ if (!check_cookie_content_and_cache(&cookie_ctx->clnt, req,
+ pkt_cookie_opt, cookie_cache)) {
+ return KR_STATE_FAIL;
+ }
+
+ uint16_t rcode = knot_pkt_ext_rcode(pkt);
+ if (rcode == KNOT_RCODE_BADCOOKIE) {
+ struct kr_query *next = NULL;
+ if (!(qry->flags.BADCOOKIE_AGAIN)) {
+ /* Received first BADCOOKIE, regenerate query. */
+ next = kr_rplan_push(&req->rplan, qry->parent,
+ qry->sname, qry->sclass,
+ qry->stype);
+ }
+
+ if (next) {
+ VERBOSE_MSG(NULL, "%s\n", "BADCOOKIE querying again");
+ qry->flags.BADCOOKIE_AGAIN = true;
+ } else {
+ /*
+ * Either the planning of the second request failed or
+ * BADCOOKIE received for the second time.
+ *
+ * RFC7873 5.3 says that TCP should be used. Currently
+ * we always expect that the server doesn't support TCP.
+ */
+ qry->flags.BADCOOKIE_AGAIN = false;
+ return KR_STATE_FAIL;
+ }
+
+ return KR_STATE_CONSUME;
+ }
+
+ return ctx->state;
+}
+
+static inline uint8_t *req_cookie_option(struct kr_request *req)
+{
+ if (!req || !req->qsource.opt) {
+ return NULL;
+ }
+
+ return knot_edns_get_option(req->qsource.opt, KNOT_EDNS_OPTION_COOKIE);
+}
+
+/**
+ * @brief Returns resolver state and sets answer RCODE on missing or invalid
+ * server cookie.
+ *
+ * @note Caller should exit when only KR_STATE_FAIL is returned.
+ *
+ * @param state original resolver state
+ * @param sc_present true if server cookie is present
+ * @param ignore_badcookie true if bad cookies should be treated as good ones
+ * @param req request context
+ * @return new resolver state
+ */
+static int invalid_sc_status(int state, bool sc_present, bool ignore_badcookie,
+ const struct kr_request *req, knot_pkt_t *answer)
+{
+ if (kr_fails_assert(req && answer))
+ return KR_STATE_FAIL;
+
+ const knot_pkt_t *pkt = req->qsource.packet;
+
+ if (!pkt) {
+ return KR_STATE_FAIL;
+ }
+
+ if (knot_wire_get_qdcount(pkt->wire) == 0) {
+ /* RFC7873 5.4 */
+ state = KR_STATE_DONE;
+ if (sc_present) {
+ kr_pkt_set_ext_rcode(answer, KNOT_RCODE_BADCOOKIE);
+ state |= KR_STATE_FAIL;
+ }
+ } else if (!ignore_badcookie) {
+ /* Generate BADCOOKIE response. */
+ VERBOSE_MSG(NULL, "%s\n",
+ !sc_present ? "request is missing server cookie" :
+ "request has invalid server cookie");
+ if (!knot_pkt_has_edns(answer)) {
+ VERBOSE_MSG(NULL, "%s\n",
+ "missing EDNS section in prepared answer");
+ /* Caller should exit on this (and only this) state. */
+ return KR_STATE_FAIL;
+ }
+ kr_pkt_set_ext_rcode(answer, KNOT_RCODE_BADCOOKIE);
+ state = KR_STATE_FAIL | KR_STATE_DONE;
+ }
+
+ return state;
+}
+
+int check_request(kr_layer_t *ctx)
+{
+ struct kr_request *req = ctx->req;
+ struct kr_cookie_settings *srvr_sett = &req->ctx->cookie_ctx.srvr;
+
+ if (!srvr_sett->enabled) {
+ return ctx->state;
+ }
+
+ knot_pkt_t *answer = req->answer; // FIXME: see kr_request_ensure_answer()
+
+ if (ctx->state & (KR_STATE_DONE | KR_STATE_FAIL)) {
+ return ctx->state;
+ }
+
+ if (!srvr_sett->enabled) {
+ if (knot_pkt_has_edns(answer)) {
+ /* Delete any cookies. */
+ knot_edns_remove_options(answer->opt_rr,
+ KNOT_EDNS_OPTION_COOKIE);
+ }
+ return ctx->state;
+ }
+
+ uint8_t *req_cookie_opt = req_cookie_option(req);
+ if (!req_cookie_opt) {
+ return ctx->state; /* Don't do anything without cookies. */
+ }
+
+ struct knot_dns_cookies cookies;
+ memset(&cookies, 0, sizeof(cookies));
+ int ret = kr_parse_cookie_opt(req_cookie_opt, &cookies);
+ if (ret != kr_ok()) {
+ /* FORMERR -- malformed cookies. */
+ VERBOSE_MSG(NULL, "%s\n", "request with malformed cookie");
+ knot_wire_set_rcode(answer->wire, KNOT_RCODE_FORMERR);
+ return KR_STATE_FAIL | KR_STATE_DONE;
+ }
+
+ /*
+ * RFC7873 5.2.3 and 5.2.4 suggest that queries with invalid or
+ * missing server cookies can be treated like normal.
+ * Right now bad cookies are always ignored (i.e. treated as valid).
+ */
+ bool ignore_badcookie = true;
+
+ const struct knot_sc_alg *current_sc_alg = kr_sc_alg_get(srvr_sett->current.alg_id);
+
+ if (!req->qsource.addr || !srvr_sett->current.secr || !current_sc_alg) {
+ VERBOSE_MSG(NULL, "%s\n", "missing valid server cookie context");
+ return KR_STATE_FAIL;
+ }
+
+ int return_state = ctx->state;
+
+ struct knot_sc_private srvr_data = {
+ .clnt_sockaddr = req->qsource.addr,
+ .secret_data = srvr_sett->current.secr->data,
+ .secret_len = srvr_sett->current.secr->size
+ };
+
+ struct knot_sc_input sc_input = {
+ .cc = cookies.cc,
+ .cc_len = cookies.cc_len,
+ /* Don't set nonce here. */
+ .srvr_data = &srvr_data
+ };
+
+ struct kr_nonce_input nonce = {
+ .rand = kr_rand_bytes(sizeof(nonce.rand)),
+ .time = req->current_query->timestamp.tv_sec
+ };
+
+ if (!cookies.sc) {
+ /* Request has no server cookie. */
+ return_state = invalid_sc_status(return_state, false,
+ ignore_badcookie, req, answer);
+ if (return_state & KR_STATE_FAIL) {
+ return return_state;
+ }
+ goto answer_add_cookies;
+ }
+
+ /* Check server cookie obtained in request. */
+
+ ret = knot_sc_check(KR_NONCE_LEN, &cookies, &srvr_data, current_sc_alg);
+ if (ret == KNOT_EINVAL && srvr_sett->recent.secr) {
+ const struct knot_sc_alg *recent_sc_alg = kr_sc_alg_get(srvr_sett->recent.alg_id);
+ if (recent_sc_alg) {
+ /* Try recent algorithm. */
+ struct knot_sc_private recent_srvr_data = {
+ .clnt_sockaddr = req->qsource.addr,
+ .secret_data = srvr_sett->recent.secr->data,
+ .secret_len = srvr_sett->recent.secr->size
+ };
+ ret = knot_sc_check(KR_NONCE_LEN, &cookies,
+ &recent_srvr_data, recent_sc_alg);
+ }
+ }
+ if (ret != KNOT_EOK) {
+ /* Invalid server cookie. */
+ return_state = invalid_sc_status(return_state, true,
+ ignore_badcookie, req, answer);
+ if (return_state & KR_STATE_FAIL) {
+ return return_state;
+ }
+ goto answer_add_cookies;
+ }
+
+ /* Server cookie is OK. */
+
+answer_add_cookies:
+ /* Add server cookie into response. */
+ ret = kr_answer_write_cookie(&sc_input, &nonce, current_sc_alg, answer);
+ if (ret != kr_ok()) {
+ return_state = KR_STATE_FAIL;
+ }
+ return return_state;
+}
+
+#undef VERBOSE_MSG
diff --git a/modules/cookies/cookiemonster.h b/modules/cookies/cookiemonster.h
new file mode 100644
index 0000000..ab1fdeb
--- /dev/null
+++ b/modules/cookies/cookiemonster.h
@@ -0,0 +1,15 @@
+/* Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#pragma once
+
+#include <libknot/packet/pkt.h>
+
+#include "lib/layer.h"
+
+/** Checks cookies of inbound requests. It's for kr_layer_api_t::begin. */
+int check_request(kr_layer_t *ctx);
+
+/** Checks cookies of received responses. It's for kr_layer_api_t::consume. */
+int check_response(kr_layer_t *ctx, knot_pkt_t *pkt);
diff --git a/modules/cookies/cookies.c b/modules/cookies/cookies.c
new file mode 100644
index 0000000..5b688d3
--- /dev/null
+++ b/modules/cookies/cookies.c
@@ -0,0 +1,78 @@
+/* Copyright (C) CZ.NIC, z.s.p.o. <knot-resolver@labs.nic.cz>
+ * SPDX-License-Identifier: GPL-3.0-or-later
+ */
+
+#include "daemon/engine.h"
+#include "lib/layer.h"
+#include "modules/cookies/cookiectl.h"
+#include "modules/cookies/cookiemonster.h"
+
+/**
+ * Get/set DNS cookie related stuff.
+ *
+ * Input: { name: value, ... }
+ * Output: current configuration
+ */
+static char *cookies_config(void *env, struct kr_module *module,
+ const char *args)
+{
+ struct kr_cookie_ctx *cookie_ctx = module->data;
+ if (kr_fails_assert(cookie_ctx))
+ return NULL;
+
+ /* Apply configuration, if any. */
+ config_apply(cookie_ctx, args);
+
+ /* Return current configuration. */
+ return config_read(cookie_ctx);
+}
+
+/*
+ * Module implementation.
+ */
+
+KR_EXPORT
+int cookies_init(struct kr_module *module)
+{
+ /* The function answer_finalize() in resolver is called before any
+ * .finish callback. Therefore this layer does not use it. */
+ static kr_layer_api_t layer = {
+ .begin = &check_request,
+ .consume = &check_response
+ };
+ /* Store module reference */
+ layer.data = module;
+ module->layer = &layer;
+
+ static const struct kr_prop props[] = {
+ { &cookies_config, "config", "Empty value to return current configuration.", },
+ { NULL, NULL, NULL }
+ };
+ module->props = props;
+
+ struct engine *engine = module->data;
+
+ struct kr_cookie_ctx *cookie_ctx = &engine->resolver.cookie_ctx;
+
+ int ret = config_init(cookie_ctx);
+ if (ret != kr_ok()) {
+ return ret;
+ }
+
+ /* Replace engine pointer. */
+ module->data = cookie_ctx;
+
+ return kr_ok();
+}
+
+KR_EXPORT
+int cookies_deinit(struct kr_module *module)
+{
+ struct kr_cookie_ctx *cookie_ctx = module->data;
+
+ config_deinit(cookie_ctx);
+
+ return kr_ok();
+}
+
+KR_MODULE_EXPORT(cookies)