diff --git a/mail/dovecot/Makefile b/mail/dovecot/Makefile index 3d670f9788..7916cfe50a 100644 --- a/mail/dovecot/Makefile +++ b/mail/dovecot/Makefile @@ -9,7 +9,7 @@ include $(TOPDIR)/rules.mk PKG_NAME:=dovecot PKG_VERSION:=2.3.21.1 -PKG_RELEASE:=1 +PKG_RELEASE:=2 PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz PKG_SOURCE_URL:=https://dovecot.org/releases/2.3 diff --git a/mail/dovecot/patches/200-CVE-2025-59031.patch b/mail/dovecot/patches/200-CVE-2025-59031.patch new file mode 100644 index 0000000000..177bfa46b9 --- /dev/null +++ b/mail/dovecot/patches/200-CVE-2025-59031.patch @@ -0,0 +1,131 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2025-59031 + +Upstream commits: + fts: Remove decode2text.sh + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/plugins/fts/Makefile.am ++++ b/src/plugins/fts/Makefile.am +@@ -63,9 +63,6 @@ xml2text_CPPFLAGS = $(AM_CPPFLAGS) $(BIN + xml2text_LDADD = $(LIBDOVECOT) $(BINARY_LDFLAGS) + xml2text_DEPENDENCIES = $(module_LTLIBRARIES) $(LIBDOVECOT_DEPS) + +-pkglibexec_SCRIPTS = decode2text.sh +-EXTRA_DIST = $(pkglibexec_SCRIPTS) +- + doveadm_module_LTLIBRARIES = \ + lib20_doveadm_fts_plugin.la + +--- a/src/plugins/fts/decode2text.sh ++++ /dev/null +@@ -1,105 +0,0 @@ +-#!/bin/sh +- +-# Example attachment decoder script. The attachment comes from stdin, and +-# the script is expected to output UTF-8 data to stdout. (If the output isn't +-# UTF-8, everything except valid UTF-8 sequences are dropped from it.) +- +-# The attachment decoding is enabled by setting: +-# +-# plugin { +-# fts_decoder = decode2text +-# } +-# service decode2text { +-# executable = script /usr/local/libexec/dovecot/decode2text.sh +-# user = dovecot +-# unix_listener decode2text { +-# mode = 0666 +-# } +-# } +- +-libexec_dir=`dirname $0` +-content_type=$1 +- +-# The second parameter is the format's filename extension, which is used when +-# found from a filename of application/octet-stream. You can also add more +-# extensions by giving more parameters. +-formats='application/pdf pdf +-application/x-pdf pdf +-application/msword doc +-application/mspowerpoint ppt +-application/vnd.ms-powerpoint ppt +-application/ms-excel xls +-application/x-msexcel xls +-application/vnd.ms-excel xls +-application/vnd.openxmlformats-officedocument.wordprocessingml.document docx +-application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx +-application/vnd.openxmlformats-officedocument.presentationml.presentation pptx +-application/vnd.oasis.opendocument.text odt +-application/vnd.oasis.opendocument.spreadsheet ods +-application/vnd.oasis.opendocument.presentation odp +-' +- +-if [ "$content_type" = "" ]; then +- echo "$formats" +- exit 0 +-fi +- +-fmt=`echo "$formats" | grep -w "^$content_type" | cut -d ' ' -f 2` +-if [ "$fmt" = "" ]; then +- echo "Content-Type: $content_type not supported" >&2 +- exit 1 +-fi +- +-# most decoders can't handle stdin directly, so write the attachment +-# to a temp file +-path=`mktemp` +-trap "rm -f $path" 0 1 2 3 14 15 +-cat > $path +- +-xmlunzip() { +- name=$1 +- +- tempdir=`mktemp -d` +- if [ "$tempdir" = "" ]; then +- exit 1 +- fi +- trap "rm -rf $path $tempdir" 0 1 2 3 14 15 +- cd $tempdir || exit 1 +- unzip -q "$path" 2>/dev/null || exit 0 +- find . -name "$name" -print0 | xargs -0 cat | +- $libexec_dir/xml2text +-} +- +-wait_timeout() { +- childpid=$! +- trap "kill -9 $childpid; rm -f $path" 1 2 3 14 15 +- wait $childpid +-} +- +-LANG=en_US.UTF-8 +-export LANG +-if [ $fmt = "pdf" ]; then +- /usr/bin/pdftotext $path - 2>/dev/null& +- wait_timeout 2>/dev/null +-elif [ $fmt = "doc" ]; then +- (/usr/bin/catdoc $path; true) 2>/dev/null& +- wait_timeout 2>/dev/null +-elif [ $fmt = "ppt" ]; then +- (/usr/bin/catppt $path; true) 2>/dev/null& +- wait_timeout 2>/dev/null +-elif [ $fmt = "xls" ]; then +- (/usr/bin/xls2csv $path; true) 2>/dev/null& +- wait_timeout 2>/dev/null +-elif [ $fmt = "odt" -o $fmt = "ods" -o $fmt = "odp" ]; then +- xmlunzip "content.xml" +-elif [ $fmt = "docx" ]; then +- xmlunzip "document.xml" +-elif [ $fmt = "xlsx" ]; then +- xmlunzip "sharedStrings.xml" +-elif [ $fmt = "pptx" ]; then +- xmlunzip "slide*.xml" +-else +- echo "Buggy decoder script: $fmt not handled" >&2 +- exit 1 +-fi +-exit 0 diff --git a/mail/dovecot/patches/201-CVE-2026-0394.patch b/mail/dovecot/patches/201-CVE-2026-0394.patch new file mode 100644 index 0000000000..b7a38be50f --- /dev/null +++ b/mail/dovecot/patches/201-CVE-2026-0394.patch @@ -0,0 +1,94 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-0394 + +Upstream commits: + auth: db-passwd-file - Add db_passwd_fix_path() + auth: db-passwd-file - Normalize path with db_passwd_fix_path() + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/auth/db-passwd-file.c ++++ b/src/auth/db-passwd-file.c +@@ -14,6 +14,7 @@ + #include "str.h" + #include "eacces-error.h" + #include "ioloop.h" ++#include "path-util.h" + + #include + #include +@@ -420,19 +421,28 @@ void db_passwd_file_unref(struct db_pass + i_free(db); + } + +-static const char * +-path_fix(const char *path, +- const struct auth_request *auth_request ATTR_UNUSED) ++int db_passwd_fix_path(const char *path, const char **path_r, ++ const char *orig_path, const char **error_r) + { ++ /* normalize path */ ++ const char *normalized; ++ if (t_normpath(path, &normalized, error_r) < 0) ++ return -1; ++ ++ /* check base path */ + const char *p; ++ if (*orig_path != '%' && ++ (p = strchr(orig_path, '%')) != NULL) { ++ ptrdiff_t len = p - orig_path; ++ if (strncmp(orig_path, normalized, len) != 0) { ++ *error_r = t_strdup_printf("Path is outside '%s'", ++ t_strdup_until(orig_path, p)); ++ return -1; ++ } ++ } + +- p = strchr(path, '/'); +- if (p == NULL) +- return path; +- +- /* most likely this is an invalid request. just cut off the '/' and +- everything after it. */ +- return t_strdup_until(path, p); ++ *path_r = normalized; ++ return 0; + } + + int db_passwd_file_lookup(struct db_passwd_file *db, +@@ -449,14 +459,19 @@ int db_passwd_file_lookup(struct db_pass + pw = db->default_file; + else { + dest = t_str_new(256); +- if (auth_request_var_expand(dest, db->path, request, path_fix, ++ if (auth_request_var_expand(dest, db->path, request, NULL, + &error) <= 0) { + e_error(authdb_event(request), + "Failed to expand passwd-file path %s: %s", + db->path, error); + return -1; + } +- ++ const char *path; ++ if (db_passwd_fix_path(str_c(dest), &path, db->path, &error) < 0) { ++ e_info(authdb_event(request), "Failed to normalize path: %s", ++ error); ++ return 0; ++ } + pw = hash_table_lookup(db->files, str_c(dest)); + if (pw == NULL) { + /* doesn't exist yet. create lookup for it. */ +--- a/src/auth/db-passwd-file.h ++++ b/src/auth/db-passwd-file.h +@@ -45,6 +45,8 @@ struct db_passwd_file { + bool userdb_warn_missing:1; + }; + ++int db_passwd_fix_path(const char *path, const char **path_r, ++ const char *orig_path, const char **error_r); + int db_passwd_file_lookup(struct db_passwd_file *db, + struct auth_request *request, + const char *username_format, diff --git a/mail/dovecot/patches/202-CVE-2026-27855.patch b/mail/dovecot/patches/202-CVE-2026-27855.patch new file mode 100644 index 0000000000..cc23a36a2f --- /dev/null +++ b/mail/dovecot/patches/202-CVE-2026-27855.patch @@ -0,0 +1,139 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-27855 + +Upstream commits: + auth: cache - Use translated username in auth_cache_remove() + auth: Move passdb event lifecycle handling to auth_request_passdb_event_(begin|end) + auth: Initialize set_credentials event properly + auth: passdb-sql - Require update_query to be set when used + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/auth/auth-cache.c ++++ b/src/auth/auth-cache.c +@@ -472,7 +472,7 @@ void auth_cache_remove(struct auth_cache + { + struct auth_cache_node *node; + +- key = auth_request_expand_cache_key(request, key, request->fields.user); ++ key = auth_request_expand_cache_key(request, key, request->fields.translated_username); + node = hash_table_lookup(cache->hash, key); + if (node == NULL) + return; +--- a/src/auth/auth-request.c ++++ b/src/auth/auth-request.c +@@ -628,7 +628,7 @@ auth_request_cache_result_to_str(enum au + } + } + +-void auth_request_passdb_lookup_begin(struct auth_request *request) ++void auth_request_passdb_event_begin(struct auth_request *request) + { + struct event *event; + const char *name; +@@ -655,11 +655,33 @@ void auth_request_passdb_lookup_begin(st + else if (*request->passdb->set->auth_verbose == 'n') + event_set_min_log_level(event, LOG_TYPE_WARNING); + ++ array_push_back(&request->authdb_event, &event); ++} ++ ++void auth_request_passdb_event_end(struct auth_request *request) ++{ ++ struct event *event = authdb_event(request); ++ event_unref(&event); ++ array_pop_back(&request->authdb_event); ++ ++ /* restore protocol-specific settings */ ++ request->set = global_auth_settings; ++} ++ ++void auth_request_passdb_lookup_begin(struct auth_request *request) ++{ ++ struct event *event; ++ ++ i_assert(request->passdb != NULL); ++ i_assert(!request->userdb_lookup); ++ auth_request_passdb_event_begin(request); ++ ++ event = authdb_event(request); ++ + e_debug(event_create_passthrough(event)-> + set_name("auth_passdb_request_started")-> + event(), + "Performing passdb lookup"); +- array_push_back(&request->authdb_event, &event); + } + + void auth_request_passdb_lookup_end(struct auth_request *request, +@@ -675,8 +697,7 @@ void auth_request_passdb_lookup_end(stru + request->set->cache_ttl != 0 && request->set->cache_size != 0) + e->add_str("cache", auth_request_cache_result_to_str(request->passdb_cache_result)); + e_debug(e->event(), "Finished passdb lookup"); +- event_unref(&event); +- array_pop_back(&request->authdb_event); ++ auth_request_passdb_event_end(request); + } + + void auth_request_userdb_lookup_begin(struct auth_request *request) +@@ -1327,6 +1348,8 @@ void auth_request_set_credentials(struct + struct auth_passdb *passdb = request->passdb; + const char *cache_key, *new_credentials; + ++ auth_request_passdb_event_begin(request); ++ + cache_key = passdb_cache == NULL ? NULL : passdb->cache_key; + if (cache_key != NULL) + auth_cache_remove(passdb_cache, request, cache_key); +@@ -1343,6 +1366,8 @@ void auth_request_set_credentials(struct + /* this passdb doesn't support credentials update */ + callback(FALSE, request); + } ++ ++ auth_request_passdb_event_end(request); + } + + static void auth_request_userdb_save_cache(struct auth_request *request, +--- a/src/auth/auth-request.h ++++ b/src/auth/auth-request.h +@@ -379,6 +379,9 @@ void auth_request_master_user_login_fini + const char *auth_request_get_log_prefix_db(struct auth_request *auth_request); + void auth_request_fields_init(struct auth_request *request); + ++void auth_request_passdb_event_begin(struct auth_request *request); ++void auth_request_passdb_event_end(struct auth_request *request); ++ + void auth_request_passdb_lookup_begin(struct auth_request *request); + void auth_request_passdb_lookup_end(struct auth_request *request, + enum passdb_result result); +--- a/src/auth/auth-worker-client.c ++++ b/src/auth/auth-worker-client.c +@@ -487,8 +487,10 @@ auth_worker_handle_setcred(struct auth_w + } + } + ++ auth_request_passdb_event_begin(auth_request); + auth_request->passdb->passdb->iface. + set_credentials(auth_request, creds, set_credentials_callback); ++ auth_request_passdb_event_end(auth_request); + return TRUE; + } + +--- a/src/auth/passdb-sql.c ++++ b/src/auth/passdb-sql.c +@@ -245,6 +245,12 @@ static void sql_set_credentials(struct a + return; + } + ++ if (*query == '\0') { ++ e_error(authdb_event(request), "update_query is empty"); ++ callback(FALSE, request); ++ return; ++ } ++ + sql_request = i_new(struct passdb_sql_request, 1); + sql_request->auth_request = request; + sql_request->callback.set_credentials = callback; diff --git a/mail/dovecot/patches/203-CVE-2026-27856.patch b/mail/dovecot/patches/203-CVE-2026-27856.patch new file mode 100644 index 0000000000..24f4f7ffbb --- /dev/null +++ b/mail/dovecot/patches/203-CVE-2026-27856.patch @@ -0,0 +1,77 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-27856 + +Upstream commits: + doveadm: client-connection - Use timing safe credential check + doveadm: Use datastack for temporary b64 value + doveadm: client-connection - Get API key from per-connection settings + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/doveadm/client-connection-http.c ++++ b/src/doveadm/client-connection-http.c +@@ -972,7 +972,7 @@ doveadm_http_server_auth_basic(struct cl + struct client_connection_http *conn = req->conn; + const struct doveadm_settings *set = conn->conn.set; + string_t *b64_value; +- char *value; ++ const char *value; + + if (*set->doveadm_password == '\0') { + i_error("Invalid authentication attempt to HTTP API: " +@@ -980,11 +980,11 @@ doveadm_http_server_auth_basic(struct cl + return FALSE; + } + +- b64_value = str_new(conn->conn.pool, 32); +- value = p_strdup_printf(conn->conn.pool, +- "doveadm:%s", set->doveadm_password); +- base64_encode(value, strlen(value), b64_value); +- if (creds->data != NULL && strcmp(creds->data, str_c(b64_value)) == 0) ++ value = t_strdup_printf("doveadm:%s", set->doveadm_password); ++ b64_value = t_base64_encode_str(0, UINT_MAX, value); ++ ++ if (creds->data != NULL && ++ str_equals_timing_almost_safe(str_c(b64_value), creds->data)) + return TRUE; + + i_error("Invalid authentication attempt to HTTP API " +@@ -997,7 +997,7 @@ doveadm_http_server_auth_api_key(struct + const struct http_auth_credentials *creds) + { + struct client_connection_http *conn = req->conn; +- const struct doveadm_settings *set = doveadm_settings; ++ const struct doveadm_settings *set = conn->conn.set; + string_t *b64_value; + + if (*set->doveadm_api_key == '\0') { +@@ -1006,10 +1006,9 @@ doveadm_http_server_auth_api_key(struct + return FALSE; + } + +- b64_value = str_new(conn->conn.pool, 32); +- base64_encode(set->doveadm_api_key, +- strlen(set->doveadm_api_key), b64_value); +- if (creds->data != NULL && strcmp(creds->data, str_c(b64_value)) == 0) ++ b64_value = t_base64_encode_str(0, UINT_MAX, set->doveadm_api_key); ++ if (creds->data != NULL && ++ str_equals_timing_almost_safe(creds->data, str_c(b64_value))) + return TRUE; + + i_error("Invalid authentication attempt to HTTP API " +--- a/src/doveadm/client-connection-tcp.c ++++ b/src/doveadm/client-connection-tcp.c +@@ -342,9 +342,7 @@ client_connection_tcp_authenticate(struc + return -1; + } + pass = t_strndup(data + 9, size - 9); +- if (strlen(pass) != strlen(set->doveadm_password) || +- !mem_equals_timing_safe(pass, set->doveadm_password, +- strlen(pass))) { ++ if (!str_equals_timing_almost_safe(pass, set->doveadm_password)) { + i_error("doveadm client authenticated with wrong password"); + return -1; + } diff --git a/mail/dovecot/patches/204-CVE-2026-27857.patch b/mail/dovecot/patches/204-CVE-2026-27857.patch new file mode 100644 index 0000000000..3cea405c26 --- /dev/null +++ b/mail/dovecot/patches/204-CVE-2026-27857.patch @@ -0,0 +1,397 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-27857 + +Upstream commits: + lib-imap, global: Add params parameter to imap_parser_create() + lib-imap: Add imap_parser_params.list_count_limit + imap-login: Limit the number of open IMAP parser lists + global: Use const for struct imap_parser_params params + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +The Pigeonhole part of this fix is in mail/pigeonhole/patches. + +--- a/src/director/director-test.c ++++ b/src/director/director-test.c +@@ -250,7 +250,7 @@ static void imap_client_create(int fd) + o_stream_set_no_error_handling(client->output, TRUE); + client->io = io_add(fd, IO_READ, imap_client_input, client); + client->parser = +- imap_parser_create(client->input, client->output, 4096); ++ imap_parser_create(client->input, client->output, 4096, NULL); + o_stream_nsend_str(client->output, + "* OK [CAPABILITY IMAP4rev1] director-test ready.\r\n"); + DLLIST_PREPEND(&imap_clients, client); +--- a/src/imap-login/imap-login-client.c ++++ b/src/imap-login/imap-login-client.c +@@ -375,11 +375,14 @@ static void imap_client_create(struct cl + { + struct imap_client *imap_client = (struct imap_client *)client; + ++ const struct imap_parser_params params = { ++ .list_count_limit = IMAP_LOGIN_LIST_COUNT_LIMIT, ++ }; + imap_client->set = other_sets[0]; + imap_client->parser = + imap_parser_create(imap_client->common.input, + imap_client->common.output, +- IMAP_LOGIN_MAX_LINE_LENGTH); ++ IMAP_LOGIN_MAX_LINE_LENGTH, ¶ms); + if (imap_client->set->imap_literal_minus) + imap_parser_enable_literal_minus(imap_client->parser); + client->io = io_add_istream(client->input, client_input, client); +@@ -412,11 +415,14 @@ static void imap_client_starttls(struct + { + struct imap_client *imap_client = (struct imap_client *)client; + ++ const struct imap_parser_params params = { ++ .list_count_limit = IMAP_LOGIN_LIST_COUNT_LIMIT, ++ }; + imap_parser_unref(&imap_client->parser); + imap_client->parser = + imap_parser_create(imap_client->common.input, + imap_client->common.output, +- IMAP_LOGIN_MAX_LINE_LENGTH); ++ IMAP_LOGIN_MAX_LINE_LENGTH, ¶ms); + + /* CRLF is lost from buffer when streams are reopened. */ + imap_client->skip_line = FALSE; +--- a/src/imap-login/imap-login-client.h ++++ b/src/imap-login/imap-login-client.h +@@ -11,6 +11,10 @@ + /* maximum length for IMAP command line. */ + #define IMAP_LOGIN_MAX_LINE_LENGTH 8192 + ++/* Maximum number of '(' allowed in an IMAP command. Pre-login only uses ++ lists in the ID command. */ ++#define IMAP_LOGIN_LIST_COUNT_LIMIT 1 ++ + enum imap_client_id_state { + IMAP_CLIENT_ID_STATE_LIST = 0, + IMAP_CLIENT_ID_STATE_KEY, +--- a/src/imap-login/imap-login-cmd-id.c ++++ b/src/imap-login/imap-login-cmd-id.c +@@ -235,9 +235,14 @@ int cmd_id(struct imap_client *client) + + if (client->cmd_id == NULL) { + client->cmd_id = id = i_new(struct imap_client_cmd_id, 1); ++ ++ const struct imap_parser_params params = { ++ .list_count_limit = IMAP_LOGIN_LIST_COUNT_LIMIT, ++ }; + id->parser = imap_parser_create(client->common.input, + client->common.output, +- IMAP_LOGIN_MAX_LINE_LENGTH); ++ IMAP_LOGIN_MAX_LINE_LENGTH, ++ ¶ms); + if (client->set->imap_literal_minus) + imap_parser_enable_literal_minus(id->parser); + parser_flags = IMAP_PARSE_FLAG_STOP_AT_LIST; +--- a/src/imap/cmd-append.c ++++ b/src/imap/cmd-append.c +@@ -947,7 +947,8 @@ bool cmd_append(struct client_command_co + o_stream_unset_flush_callback(client->output); + + ctx->save_parser = imap_parser_create(client->input, client->output, +- client->set->imap_max_line_length); ++ client->set->imap_max_line_length, ++ NULL); + if (client->set->imap_literal_minus) + imap_parser_enable_literal_minus(ctx->save_parser); + +--- a/src/imap/cmd-setmetadata.c ++++ b/src/imap/cmd-setmetadata.c +@@ -289,7 +289,8 @@ cmd_setmetadata_start(struct imap_setmet + asynchronously the same way as APPEND does. */ + client->input_lock = cmd; + ctx->parser = imap_parser_create(client->input, client->output, +- client->set->imap_max_line_length); ++ client->set->imap_max_line_length, ++ NULL); + if (client->set->imap_literal_minus) + imap_parser_enable_literal_minus(ctx->parser); + o_stream_unset_flush_callback(client->output); +--- a/src/imap/imap-client.c ++++ b/src/imap/imap-client.c +@@ -958,7 +958,8 @@ client_command_new(struct client *client + } else { + cmd->parser = + imap_parser_create(client->input, client->output, +- client->set->imap_max_line_length); ++ client->set->imap_max_line_length, ++ NULL); + if (client->set->imap_literal_minus) + imap_parser_enable_literal_minus(cmd->parser); + } +--- a/src/lib-imap-client/imapc-connection.c ++++ b/src/lib-imap-client/imapc-connection.c +@@ -1845,7 +1845,8 @@ static void imapc_connection_connect_nex + o_stream_set_flush_callback(conn->output, imapc_connection_connected, + conn); + conn->parser = imap_parser_create(conn->input, NULL, +- conn->client->set.max_line_length); ++ conn->client->set.max_line_length, ++ NULL); + conn->to = timeout_add(conn->client->set.connect_timeout_msecs, + imapc_connection_timeout, conn); + conn->to_output = timeout_add(conn->client->set.max_idle_time*1000, +--- a/src/lib-imap-storage/imap-msgpart.c ++++ b/src/lib-imap-storage/imap-msgpart.c +@@ -148,7 +148,7 @@ imap_msgpart_get_header_fields(pool_t po + int result = 0; + + input = i_stream_create_from_data(header_list, strlen(header_list)); +- parser = imap_parser_create(input, NULL, SIZE_MAX); ++ parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + + if (imap_parser_finish_line(parser, 0, 0, &args) > 0 && + imap_arg_get_list_full(args, &hdr_list, &list_count) && +--- a/src/lib-imap/imap-bodystructure.c ++++ b/src/lib-imap/imap-bodystructure.c +@@ -703,7 +703,7 @@ int imap_bodystructure_parse_full(const + input = i_stream_create_from_data(bodystructure, strlen(bodystructure)); + (void)i_stream_read(input); + +- parser = imap_parser_create(input, NULL, SIZE_MAX); ++ parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + ret = imap_parser_finish_line(parser, 0, + IMAP_PARSE_FLAG_LITERAL_TYPE, &args); + if (ret < 0) { +@@ -953,7 +953,7 @@ int imap_body_parse_from_bodystructure(c + input = i_stream_create_from_data(bodystructure, strlen(bodystructure)); + (void)i_stream_read(input); + +- parser = imap_parser_create(input, NULL, SIZE_MAX); ++ parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + ret = imap_parser_finish_line(parser, 0, IMAP_PARSE_FLAG_NO_UNESCAPE | + IMAP_PARSE_FLAG_LITERAL_TYPE, &args); + if (ret < 0) { +--- a/src/lib-imap/imap-envelope.c ++++ b/src/lib-imap/imap-envelope.c +@@ -222,7 +222,7 @@ bool imap_envelope_parse(const char *env + input = i_stream_create_from_data(envelope, strlen(envelope)); + (void)i_stream_read(input); + +- parser = imap_parser_create(input, NULL, SIZE_MAX); ++ parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + ret = imap_parser_finish_line(parser, 0, + IMAP_PARSE_FLAG_LITERAL_TYPE, &args); + if (ret < 0) { +--- a/src/lib-imap/imap-id.c ++++ b/src/lib-imap/imap-id.c +@@ -111,7 +111,7 @@ const char *imap_id_reply_generate(const + input = i_stream_create_from_data(settings, strlen(settings)); + (void)i_stream_read(input); + +- parser = imap_parser_create(input, NULL, SIZE_MAX); ++ parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + if (imap_parser_finish_line(parser, 0, 0, &args) <= 0) + ret = "NIL"; + else +--- a/src/lib-imap/imap-parser.c ++++ b/src/lib-imap/imap-parser.c +@@ -39,6 +39,7 @@ struct imap_parser { + struct istream *input; + struct ostream *output; + size_t max_line_size; ++ unsigned int list_count_limit; + enum imap_parser_flags flags; + + /* reset by imap_parser_reset(): */ +@@ -46,6 +47,7 @@ struct imap_parser { + ARRAY_TYPE(imap_arg_list) root_list; + ARRAY_TYPE(imap_arg_list) *cur_list; + struct imap_arg *list_arg; ++ unsigned int list_count; + + enum arg_parse_type cur_type; + size_t cur_pos; /* parser position in input buffer */ +@@ -69,7 +71,8 @@ struct imap_parser { + + struct imap_parser * + imap_parser_create(struct istream *input, struct ostream *output, +- size_t max_line_size) ++ size_t max_line_size, ++ const struct imap_parser_params *params) + { + struct imap_parser *parser; + +@@ -80,6 +83,10 @@ imap_parser_create(struct istream *input + parser->input = input; + parser->output = output; + parser->max_line_size = max_line_size; ++ if (params != NULL && params->list_count_limit > 0) ++ parser->list_count_limit = params->list_count_limit; ++ else ++ parser->list_count_limit = UINT_MAX; + + p_array_init(&parser->root_list, parser->pool, LIST_INIT_COUNT); + parser->cur_list = &parser->root_list; +@@ -121,6 +128,7 @@ void imap_parser_reset(struct imap_parse + p_array_init(&parser->root_list, parser->pool, LIST_INIT_COUNT); + parser->cur_list = &parser->root_list; + parser->list_arg = NULL; ++ parser->list_count = 0; + + parser->cur_type = ARG_PARSE_NONE; + parser->cur_pos = 0; +@@ -209,6 +217,12 @@ static bool imap_parser_close_list(struc + parser->error = IMAP_PARSE_ERROR_BAD_SYNTAX; + return FALSE; + } ++ if (parser->list_count >= parser->list_count_limit) { ++ parser->error_msg = "Too many '('"; ++ parser->error = IMAP_PARSE_ERROR_BAD_SYNTAX; ++ return FALSE; ++ } ++ parser->list_count++; + + arg = imap_arg_create(parser); + arg->type = IMAP_ARG_EOL; +--- a/src/lib-imap/imap-parser.h ++++ b/src/lib-imap/imap-parser.h +@@ -38,6 +38,15 @@ enum imap_parser_error { + IMAP_PARSE_ERROR_LITERAL_TOO_BIG + }; + ++struct imap_parser_params { ++ /* How many open lists ('(' chars) to allow before faililng the parsing. ++ 0 means unlimited. This is mainly used to prevent excessive memory ++ usage in imap-login process. In imap process there are many other ++ ways to increase memory usage, so we let the max_line_size be the ++ only limit. */ ++ unsigned int list_count_limit; ++}; ++ + struct imap_parser; + + /* Create new IMAP argument parser. output is used for sending command +@@ -53,7 +62,8 @@ struct imap_parser; + 2 * max_line_size. */ + struct imap_parser * + imap_parser_create(struct istream *input, struct ostream *output, +- size_t max_line_size) ATTR_NULL(2); ++ size_t max_line_size, ++ const struct imap_parser_params *params); + void imap_parser_ref(struct imap_parser *parser); + void imap_parser_unref(struct imap_parser **parser); + +--- a/src/lib-imap/test-imap-parser.c ++++ b/src/lib-imap/test-imap-parser.c +@@ -2,6 +2,7 @@ + + #include "lib.h" + #include "istream.h" ++#include "istream-chain.h" + #include "imap-parser.h" + #include "test-common.h" + +@@ -16,7 +17,7 @@ static void test_imap_parser_crlf(void) + + test_begin("imap parser crlf handling"); + input = test_istream_create(test_input); +- parser = imap_parser_create(input, NULL, 1024); ++ parser = imap_parser_create(input, NULL, 1024, NULL); + + /* must return -2 until LF is read */ + for (i = 0; test_input[i] != '\n'; i++) { +@@ -60,7 +61,7 @@ static void test_imap_parser_partial_lis + + test_begin("imap parser partial list"); + input = test_istream_create(test_input); +- parser = imap_parser_create(input, NULL, 1024); ++ parser = imap_parser_create(input, NULL, 1024, NULL); + + (void)i_stream_read(input); + test_assert(imap_parser_read_args(parser, 0, +@@ -79,6 +80,50 @@ static void test_imap_parser_partial_lis + test_end(); + } + ++static void test_imap_parser_list_limit(void) ++{ ++ struct { ++ const char *input; ++ int ret; ++ } tests[] = { ++ { "(())\r\n", 1 }, ++ { "((()))\r\n", -1 }, ++ }; ++ struct istream_chain *chain; ++ struct istream *chain_input; ++ struct imap_parser *parser; ++ const struct imap_arg *args; ++ ++ test_begin("imap parser list limit"); ++ const struct imap_parser_params params = { ++ .list_count_limit = 2, ++ }; ++ ++ for (unsigned int i = 0; i < N_ELEMENTS(tests); i++) { ++ chain_input = i_stream_create_chain(&chain, IO_BLOCK_SIZE); ++ parser = imap_parser_create(chain_input, NULL, 1024, ¶ms); ++ ++ for (unsigned int j = 0; j < 2; j++) { ++ struct istream *input = ++ test_istream_create(tests[i].input); ++ i_stream_chain_append(chain, input); ++ i_stream_unref(&input); ++ ++ (void)i_stream_read(chain_input); ++ ++ test_assert_cmp(imap_parser_read_args(parser, 0, 0, &args), ==, tests[i].ret); ++ /* skip over CRLF */ ++ i_stream_skip(chain_input, i_stream_get_data_size(chain_input)); ++ ++ /* make sure parser reset works */ ++ imap_parser_reset(parser); ++ } ++ imap_parser_unref(&parser); ++ i_stream_destroy(&chain_input); ++ } ++ test_end(); ++} ++ + static void test_imap_parser_read_tag_cmd(void) + { + enum read_type { +@@ -123,7 +168,7 @@ static void test_imap_parser_read_tag_cm + if (tests[i].type != COMMAND) { + input = test_istream_create(tests[i].input); + test_assert(i_stream_read(input) > 0); +- parser = imap_parser_create(input, NULL, 1024); ++ parser = imap_parser_create(input, NULL, 1024, NULL); + ret = imap_parser_read_tag(parser, &atom); + test_assert_idx(ret == tests[i].ret, i); + test_assert_idx(ret <= 0 || strcmp(tests[i].tag, atom) == 0, i); +@@ -134,7 +179,7 @@ static void test_imap_parser_read_tag_cm + if (tests[i].type != TAG) { + input = test_istream_create(tests[i].input); + test_assert(i_stream_read(input) > 0); +- parser = imap_parser_create(input, NULL, 1024); ++ parser = imap_parser_create(input, NULL, 1024, NULL); + ret = imap_parser_read_command_name(parser, &atom); + test_assert_idx(ret == tests[i].ret, i); + test_assert_idx(ret <= 0 || strcmp(tests[i].tag, atom) == 0, i); +@@ -150,6 +195,7 @@ int main(void) + static void (*const test_functions[])(void) = { + test_imap_parser_crlf, + test_imap_parser_partial_list, ++ test_imap_parser_list_limit, + test_imap_parser_read_tag_cmd, + NULL + }; +--- a/src/plugins/virtual/virtual-config.c ++++ b/src/plugins/virtual/virtual-config.c +@@ -54,7 +54,7 @@ virtual_search_args_parse(const string_t + input = i_stream_create_from_data(str_data(rule), str_len(rule)); + (void)i_stream_read(input); + +- imap_parser = imap_parser_create(input, NULL, SIZE_MAX); ++ imap_parser = imap_parser_create(input, NULL, SIZE_MAX, NULL); + ret = imap_parser_finish_line(imap_parser, 0, 0, &args); + if (ret < 0) { + sargs = NULL; diff --git a/mail/dovecot/patches/205-CVE-2026-27859.patch b/mail/dovecot/patches/205-CVE-2026-27859.patch new file mode 100644 index 0000000000..2ba78084a9 --- /dev/null +++ b/mail/dovecot/patches/205-CVE-2026-27859.patch @@ -0,0 +1,95 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-27859 + +Upstream commits: + lib-mail: Limit the number of RFC2231 parameters that can be parsed + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-mail/rfc2231-parser.c ++++ b/src/lib-mail/rfc2231-parser.c +@@ -45,7 +45,7 @@ int rfc2231_parse(struct rfc822_parser_c + const struct rfc2231_parameter *rfc2231_params; + const char *key, *p, *p2; + string_t *str; +- unsigned int i, j, count, next, next_idx; ++ unsigned int i, j, count, next, next_idx, params_count = 0; + bool ok, have_extended, broken = FALSE; + const char *prev_replacement_str; + int ret; +@@ -63,6 +63,8 @@ int rfc2231_parse(struct rfc822_parser_c + t_array_init(&rfc2231_params_arr, 8); + str = t_str_new(64); + while ((ret = rfc822_parse_content_param(ctx, &key, str)) != 0) { ++ if (++params_count > RFC2231_MAX_PARAMS) ++ break; + if (ret < 0) { + /* try to continue anyway.. */ + broken = TRUE; +--- a/src/lib-mail/rfc822-parser.h ++++ b/src/lib-mail/rfc822-parser.h +@@ -3,6 +3,11 @@ + + #include "unichar.h" + ++/* Maximum number of parameters to parse. After this the rest of the parameters ++ are skipped. This is to avoid excessive CPU usage that can be caused by ++ merging of these parameters. */ ++#define RFC2231_MAX_PARAMS 128 ++ + /* This can be used as a common NUL replacement character */ + #define RFC822_NUL_REPLACEMENT_STR UNICODE_REPLACEMENT_CHAR_UTF8 + +--- a/src/lib-mail/test-rfc2231-parser.c ++++ b/src/lib-mail/test-rfc2231-parser.c +@@ -1,6 +1,7 @@ + /* Copyright (c) 2007-2018 Dovecot authors, see the included COPYING file */ + + #include "lib.h" ++#include "str.h" + #include "rfc822-parser.h" + #include "rfc2231-parser.h" + #include "test-common.h" +@@ -41,10 +42,39 @@ static void test_rfc2231_parser(void) + test_end(); + } + ++static void test_rfc2231_parser_limits(void) ++{ ++ string_t *input = t_str_new(1024); ++ ++ test_begin("rfc2231 parser limits"); ++ str_append(input, "; "); ++ for (unsigned int i = 0; i < 1100; i++) ++ str_printfa(input, "a%u=b%u; ", i, i); ++ struct rfc822_parser_context parser; ++ const char *const *result; ++ rfc822_parser_init(&parser, str_data(input), str_len(input), NULL); ++ test_assert(rfc2231_parse(&parser, &result) == 0); ++ ++ unsigned int count = str_array_length(result); ++ test_assert(count == RFC2231_MAX_PARAMS * 2); ++ for (unsigned int i = 0; i < count; i += 2) { ++ str_truncate(input, 0); ++ str_printfa(input, "a%u", i / 2); ++ test_assert_strcmp_idx(result[i], str_c(input), i); ++ ++ str_truncate(input, 0); ++ str_printfa(input, "b%u", i / 2); ++ test_assert_strcmp_idx(result[i + 1], str_c(input), i); ++ } ++ rfc822_parser_deinit(&parser); ++ test_end(); ++} ++ + int main(void) + { + static void (*const test_functions[])(void) = { + test_rfc2231_parser, ++ test_rfc2231_parser_limits, + NULL + }; + return test_run(test_functions); diff --git a/mail/dovecot/patches/206-CVE-2026-33603.patch b/mail/dovecot/patches/206-CVE-2026-33603.patch new file mode 100644 index 0000000000..bdc5f58190 --- /dev/null +++ b/mail/dovecot/patches/206-CVE-2026-33603.patch @@ -0,0 +1,36 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-33603 + +Upstream commits: + login-common: Only accept base64 in sasl + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/login-common/client-common-auth.c ++++ b/src/login-common/client-common-auth.c +@@ -3,6 +3,7 @@ + #include "hostpid.h" + #include "login-common.h" + #include "array.h" ++#include "base64.h" + #include "iostream.h" + #include "istream.h" + #include "ostream.h" +@@ -655,6 +656,14 @@ client_auth_handle_reply(struct client * + + void client_auth_respond(struct client *client, const char *response) + { ++ /* Only accept base64 */ ++ for (size_t i = 0; response[i] != '\0'; i++) { ++ if (!base64_is_valid_char(response[i]) && response[i] != '=') { ++ client_auth_fail(client, "Invalid base64 in response"); ++ return; ++ } ++ } ++ + client->auth_waiting = FALSE; + client_set_auth_waiting(client); + auth_client_request_continue(client->auth_request, response); diff --git a/mail/dovecot/patches/207-CVE-2026-40020.patch b/mail/dovecot/patches/207-CVE-2026-40020.patch new file mode 100644 index 0000000000..11a4616522 --- /dev/null +++ b/mail/dovecot/patches/207-CVE-2026-40020.patch @@ -0,0 +1,96 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40020 + +Upstream commits: + acl: Add acl_id_is_valid() + imap-acl: Fail if ACL identifier is invalid + acl: Assert-crash if ACL identifier is invalid before writing it + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/plugins/acl/acl-api.c ++++ b/src/plugins/acl/acl-api.c +@@ -3,6 +3,7 @@ + #include "lib.h" + #include "array.h" + #include "str.h" ++#include "unichar.h" + #include "strescape.h" + #include "hash.h" + #include "mail-user.h" +@@ -11,6 +12,8 @@ + #include "acl-cache.h" + #include "acl-api-private.h" + ++#include ++ + struct acl_letter_map { + char letter; + const char *name; +@@ -269,6 +272,19 @@ int acl_backend_nonowner_lookups_rebuild + return backend->v.nonowner_lookups_rebuild(backend); + } + ++bool acl_id_is_valid(const char *id) ++{ ++ size_t len = strlen(id); ++ ++ if (len > ACL_ID_MAX_LEN) ++ return FALSE; ++ for (size_t i = 0; i < len; i++) { ++ if (i_iscntrl(id[i])) ++ return FALSE; ++ } ++ return uni_utf8_data_is_valid((const unsigned char *)id, len); ++} ++ + void acl_rights_write_id(string_t *dest, const struct acl_rights *right) + { + switch (right->id_type) { +--- a/src/plugins/acl/acl-api.h ++++ b/src/plugins/acl/acl-api.h +@@ -35,6 +35,8 @@ struct acl_object; + #define MAILBOX_ATTRIBUTE_PREFIX_ACL \ + MAILBOX_ATTRIBUTE_PREFIX_DOVECOT_PVT"acl/" + ++#define ACL_ID_MAX_LEN 1024 ++ + /* ACL identifiers in override order */ + enum acl_id_type { + /* Anyone's rights, including anonymous's. +@@ -164,4 +166,8 @@ int acl_object_list_deinit(struct acl_ob + /* Returns the canonical ID for the right. */ + const char *acl_rights_get_id(const struct acl_rights *right); + ++/* Returns TRUE if the ACL identifier string is valid: no longer than ++ ACL_ID_MAX_LEN bytes, no control characters and valid UTF-8. */ ++bool acl_id_is_valid(const char *id); ++ + #endif +--- a/src/plugins/acl/acl-backend-vfile-update.c ++++ b/src/plugins/acl/acl-backend-vfile-update.c +@@ -116,6 +116,7 @@ vfile_write_right(string_t *dest, const + if (neg) str_append_c(dest,'-'); + acl_rights_write_id(dest, right); + ++ i_assert(acl_id_is_valid(str_c(dest))); + if (strchr(str_c(dest), ' ') != NULL) T_BEGIN { + /* need to escape it */ + const char *escaped = t_strdup(str_escape(str_c(dest))); +--- a/src/plugins/imap-acl/imap-acl-plugin.c ++++ b/src/plugins/imap-acl/imap-acl-plugin.c +@@ -802,6 +802,11 @@ imap_acl_identifier_parse(struct client_ + { + struct mail_user *user = cmd->client->user; + ++ if (!acl_id_is_valid(id)) { ++ *client_error_r = "Invalid identifier"; ++ return -1; ++ } ++ + if (str_begins(id, IMAP_ACL_GLOBAL_PREFIX)) { + *client_error_r = t_strdup_printf("Global ACLs can't be modified: %s", + id); diff --git a/mail/dovecot/patches/208-CVE-2026-42006.patch b/mail/dovecot/patches/208-CVE-2026-42006.patch new file mode 100644 index 0000000000..acf931ce48 --- /dev/null +++ b/mail/dovecot/patches/208-CVE-2026-42006.patch @@ -0,0 +1,92 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-42006 + +Upstream commits: + lib-imap: Fix imap_parser_params.list_count_limit to actually work + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-imap/imap-parser.c ++++ b/src/lib-imap/imap-parser.c +@@ -191,8 +191,15 @@ static struct imap_arg *imap_arg_create( + return arg; + } + +-static void imap_parser_open_list(struct imap_parser *parser) ++static bool imap_parser_open_list(struct imap_parser *parser) + { ++ if (parser->list_count >= parser->list_count_limit) { ++ parser->error_msg = "Too many '('"; ++ parser->error = IMAP_PARSE_ERROR_BAD_SYNTAX; ++ return FALSE; ++ } ++ parser->list_count++; ++ + parser->list_arg = imap_arg_create(parser); + parser->list_arg->type = IMAP_ARG_LIST; + p_array_init(&parser->list_arg->_data.list, parser->pool, +@@ -200,6 +207,7 @@ static void imap_parser_open_list(struct + parser->cur_list = &parser->list_arg->_data.list; + + parser->cur_type = ARG_PARSE_NONE; ++ return TRUE; + } + + static bool imap_parser_close_list(struct imap_parser *parser) +@@ -217,12 +225,6 @@ static bool imap_parser_close_list(struc + parser->error = IMAP_PARSE_ERROR_BAD_SYNTAX; + return FALSE; + } +- if (parser->list_count >= parser->list_count_limit) { +- parser->error_msg = "Too many '('"; +- parser->error = IMAP_PARSE_ERROR_BAD_SYNTAX; +- return FALSE; +- } +- parser->list_count++; + + arg = imap_arg_create(parser); + arg->type = IMAP_ARG_EOL; +@@ -673,7 +675,8 @@ static bool imap_parser_read_arg(struct + parser->literal8 = FALSE; + break; + case '(': +- imap_parser_open_list(parser); ++ if (!imap_parser_open_list(parser)) ++ return FALSE; + if ((parser->flags & IMAP_PARSE_FLAG_STOP_AT_LIST) != 0) { + i_stream_skip(parser->input, 1); + return FALSE; +--- a/src/lib-imap/test-imap-parser.c ++++ b/src/lib-imap/test-imap-parser.c +@@ -85,9 +85,15 @@ static void test_imap_parser_list_limit( + struct { + const char *input; + int ret; ++ const char *error; + } tests[] = { +- { "(())\r\n", 1 }, +- { "((()))\r\n", -1 }, ++ { "(())\r\n", 1, NULL }, ++ { "((\r\n", -1, "Missing ')'" }, ++ { "(()\r\n", -1, "Missing ')'" }, ++ { "(()))\r\n", -1, "Unexpected ')'" }, ++ { "((()))\r\n", -1, "Too many '('" }, ++ { "(({10}\r\n", -2, NULL }, ++ { "((({10}\r\n", -1, "Too many '('" }, + }; + struct istream_chain *chain; + struct istream *chain_input; +@@ -112,6 +118,10 @@ static void test_imap_parser_list_limit( + (void)i_stream_read(chain_input); + + test_assert_cmp(imap_parser_read_args(parser, 0, 0, &args), ==, tests[i].ret); ++ if (tests[i].ret == -1) { ++ enum imap_parser_error err; ++ test_assert_strcmp_idx(imap_parser_get_error(parser, &err), tests[i].error, i); ++ } + /* skip over CRLF */ + i_stream_skip(chain_input, i_stream_get_data_size(chain_input)); + diff --git a/mail/dovecot/patches/209-lib-test-Add-test-assert-memcmp.patch b/mail/dovecot/patches/209-lib-test-Add-test-assert-memcmp.patch new file mode 100644 index 0000000000..dfa335fc28 --- /dev/null +++ b/mail/dovecot/patches/209-lib-test-Add-test-assert-memcmp.patch @@ -0,0 +1,103 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Stephan Bosch +Subject: [PATCH] lib-test: Add test_assert_memcmp*() + +Upstream commit: + https://github.com/dovecot/core/commit/4677492d038f5187363790b5a93bd5fccc989a98 + +Needed by the test of the fix for CVE-2026-33604. + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-test/test-common.c ++++ b/src/lib-test/test-common.c +@@ -82,6 +82,39 @@ void test_assert_failed_strcmp_idx(const + #endif + } + ++static void print_memcmp_data(const void *_data, size_t len) ++{ ++ const unsigned char *data = _data; ++ size_t i; ++ ++ for (i = 0; i < len; i++) { ++ if (data[i] >= 0x20 && data[i] < 0x7f) ++ printf("%c", data[i]); ++ else ++ printf("\\x%02X", data[i]); ++ } ++} ++ ++void test_assert_failed_memcmp_idx(const char *code, const char *file, unsigned int line, ++ const void *src, const void *dst, size_t len, long long i) ++{ ++ printf("%s:%u: Assert", file, line); ++ if (i == LLONG_MIN) ++ printf(" failed: %s\n", code); ++ else ++ printf("(#%lld) failed: %s\n", i, code); ++ printf(" \""); ++ print_memcmp_data(src, len); ++ printf("\" != \""); ++ print_memcmp_data(dst, len); ++ printf("\" (len == %zu)", len); ++ fflush(stdout); ++ test_success = FALSE; ++#ifdef STATIC_CHECKER ++ i_unreached(); ++#endif ++} ++ + void test_assert_failed_cmp_intmax_idx(const char *code, const char *file, + unsigned int line, + intmax_t src, intmax_t dst, +--- a/src/lib-test/test-common.h ++++ b/src/lib-test/test-common.h +@@ -32,7 +32,14 @@ void test_begin(const char *name); + test_assert_strcmp_idx(s1, s2, LLONG_MIN); \ + } STMT_END + +-/* Same as test_assert_strcmp expect that it takes an additional i as input. ++/* Additional parameters are m1 (source) and m2 (destination) memory and len ++ * in memcmp(). ++ */ ++#define test_assert_memcmp(m1, m2, len) STMT_START { \ ++ test_assert_memcmp_idx(m1, m2, len, LLONG_MIN); \ ++ } STMT_END ++ ++/* Same as test_assert_strcmp except that it takes an additional i as input. + * When i is greater than or equals 0 it is used to identify the barrage of + * tests failed like in test_assert_idx. + */ +@@ -44,6 +51,19 @@ void test_begin(const char *name); + __FILE__, __LINE__, _temp_s1, _temp_s2, i); \ + } STMT_END + ++/* Same as test_assert_memcmp except that it takes an additional i as input. ++ * When i is greater than or equals 0 it is used to identify the barrage of ++ * tests failed like in test_assert_idx. ++*/ ++#define test_assert_memcmp_idx(_m1, _m2, _len, i) STMT_START { \ ++ const void *_temp_m1 = (_m1); \ ++ const void *_temp_m2 = (_m2); \ ++ const size_t _temp_len = (_len); \ ++ if ((memcmp(_temp_m1,_temp_m2, _temp_len) != 0)) \ ++ test_assert_failed_memcmp_idx("memcmp(" #_m1 "," #_m2 "," #_len ")", \ ++ __FILE__, __LINE__, _temp_m1, _temp_m2, _temp_len, i); \ ++ } STMT_END ++ + #define test_assert_cmp(_value1, _op, _value2) \ + test_assert_cmp_idx(_value1, _op, _value2, LLONG_MIN) + #define test_assert_cmp_idx(_value1, _op, _value2, _idx) STMT_START { \ +@@ -81,6 +101,9 @@ void test_assert_failed_idx(const char * + void test_assert_failed_strcmp_idx(const char *code, const char *file, unsigned int line, + const char * src, const char * dst, long long i) + ATTR_STATIC_CHECKER_NORETURN; ++void test_assert_failed_memcmp_idx(const char *code, const char *file, unsigned int line, ++ const void *src, const void *dst, size_t len, long long i) ++ ATTR_STATIC_CHECKER_NORETURN; + void test_assert_failed_cmp_intmax_idx(const char *code, const char *file, + unsigned int line, + intmax_t src, intmax_t dst, diff --git a/mail/dovecot/patches/210-lib-test-Require-both-lengths-in-test-assert-memcmp.patch b/mail/dovecot/patches/210-lib-test-Require-both-lengths-in-test-assert-memcmp.patch new file mode 100644 index 0000000000..a73c7755c0 --- /dev/null +++ b/mail/dovecot/patches/210-lib-test-Require-both-lengths-in-test-assert-memcmp.patch @@ -0,0 +1,45 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] lib-test: Require both lengths in test_assert_memcmp() + +Upstream commit: + https://github.com/dovecot/core/commit/8f04979a7e72d3b3e04f3a93bd8088f5e2332dd9 + +Needed by the test of the fix for CVE-2026-33604. + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-test/test-common.h ++++ b/src/lib-test/test-common.h +@@ -35,8 +35,8 @@ void test_begin(const char *name); + /* Additional parameters are m1 (source) and m2 (destination) memory and len + * in memcmp(). + */ +-#define test_assert_memcmp(m1, m2, len) STMT_START { \ +- test_assert_memcmp_idx(m1, m2, len, LLONG_MIN); \ ++#define test_assert_memcmp(m1, len1, m2, len2) STMT_START { \ ++ test_assert_memcmp_idx(m1, len1, m2, len2, LLONG_MIN); \ + } STMT_END + + /* Same as test_assert_strcmp except that it takes an additional i as input. +@@ -55,12 +55,14 @@ void test_begin(const char *name); + * When i is greater than or equals 0 it is used to identify the barrage of + * tests failed like in test_assert_idx. + */ +-#define test_assert_memcmp_idx(_m1, _m2, _len, i) STMT_START { \ ++#define test_assert_memcmp_idx(_m1, _len1, _m2, _len2, i) STMT_START { \ + const void *_temp_m1 = (_m1); \ + const void *_temp_m2 = (_m2); \ +- const size_t _temp_len = (_len); \ +- if ((memcmp(_temp_m1,_temp_m2, _temp_len) != 0)) \ +- test_assert_failed_memcmp_idx("memcmp(" #_m1 "," #_m2 "," #_len ")", \ ++ const size_t _temp_len = I_MIN((_len1), (_len2)); \ ++ if ((_len1) != (_len2)) \ ++ test_assert_failed_ucmp_intmax_idx(#_len1 " == " #_len2, __FILE__, __LINE__, _len1, _len2, "=", i); \ ++ if ((memcmp(_temp_m1, _temp_m2, _temp_len) != 0)) \ ++ test_assert_failed_memcmp_idx("memcmp(" #_m1 "," #_m2 "," #_len2 ")", \ + __FILE__, __LINE__, _temp_m1, _temp_m2, _temp_len, i); \ + } STMT_END + diff --git a/mail/dovecot/patches/211-CVE-2026-33604.patch b/mail/dovecot/patches/211-CVE-2026-33604.patch new file mode 100644 index 0000000000..6df9626c61 --- /dev/null +++ b/mail/dovecot/patches/211-CVE-2026-33604.patch @@ -0,0 +1,257 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Marco Bettini +Subject: [PATCH] Fix CVE-2026-33604 + +Upstream commits: + lib-mail: o_stream_dot_sendv() - Use I_MIN() + https://github.com/dovecot/core/commit/8e254544cd8314092b4e3b2e7654df34b73e721b + lib-mail: o_stream_dot_sendv() - Fix boundary off by one + https://github.com/dovecot/core/commit/b5921303c9ba9ae51b68a3a9f0ef2be1fdb35cc0 + lib-mail: o_stream_dot_sendv() - Use enumeration to define the items to inject + https://github.com/dovecot/core/commit/0e9af24dc0d191be3c8ba7747a00a54337c6fd9a + lib-mail: o_stream_dot_sendv() - Do not send unguarded '.' after bare '\r' + https://github.com/dovecot/core/commit/5d8bea193dec2d2a065868f383738ba6625f839e + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-mail/ostream-dot.c ++++ b/src/lib-mail/ostream-dot.c +@@ -71,6 +71,14 @@ o_stream_dot_close(struct iostream_priva + o_stream_close(dstream->ostream.parent); + } + ++#define ADD_MAX 3 ++enum o_stream_dot_sendv_add { ++ ADD_NONE, ++ ADD_CR, ++ ADD_DOT, ++ ADD_LF_DOT, ++}; ++ + static ssize_t + o_stream_dot_sendv(struct ostream_private *stream, + const struct const_iovec *iov, unsigned int iov_count) +@@ -105,8 +113,8 @@ o_stream_dot_sendv(struct ostream_privat + + p = data; + pend = CONST_PTR_OFFSET(data, size); +- for (; p < pend && (size_t)(p-data)+2 < max_bytes; p++) { +- char add = 0; ++ for (; p < pend && ((size_t)(p - data) + ADD_MAX) <= max_bytes; p++) { ++ enum o_stream_dot_sendv_add add = ADD_NONE; + + switch (dstream->state) { + /* none */ +@@ -114,8 +122,7 @@ o_stream_dot_sendv(struct ostream_privat + switch (*p) { + case '\n': + dstream->state = STREAM_STATE_CRLF; +- /* add missing CR */ +- add = '\r'; ++ add = ADD_CR; + break; + case '\r': + dstream->state = STREAM_STATE_CR; +@@ -130,6 +137,9 @@ o_stream_dot_sendv(struct ostream_privat + case '\n': + dstream->state = STREAM_STATE_CRLF; + break; ++ case '.': ++ add = ADD_LF_DOT; ++ /* fall through */ + default: + dstream->state = STREAM_STATE_NONE; + break; +@@ -144,12 +154,10 @@ o_stream_dot_sendv(struct ostream_privat + break; + case '\n': + dstream->state = STREAM_STATE_CRLF; +- /* add missing CR */ +- add = '\r'; ++ add = ADD_CR; + break; + case '.': +- /* add dot */ +- add = '.'; ++ add = ADD_DOT; + /* fall through */ + default: + dstream->state = STREAM_STATE_NONE; +@@ -172,22 +180,60 @@ o_stream_dot_sendv(struct ostream_privat + max_bytes -= chunk; + sent += chunk; + } +- /* insert byte (substitute one with pair) */ + data++; +- iovn.iov_base = (add == '\r' ? "\r\n" : ".."); +- iovn.iov_len = 2; ++ ++ /* Apply the modifications required according to RFC 5321 to the ++ stream : ++ ++ ADD_DOT - Apply standard SMTP dot-stuffing ++ ++ ADD_CR - Convert invalid lone LFs to CRLF to comply with ++ DATA line termination requirements, and avoid ++ potentially emitting bare "\n." sequences (same ++ threat as below for "\r." sequences). ++ ++ ADD_LF_DOT - Guard against invalid "\r." sequences. ++ A downstream MTA that incorrectly handles bare CRs ++ as line terminators could interpret a '.' at the ++ start of the next line as end-of-DATA. This would ++ allow any following bytes to be processed as SMTP ++ commands. ++ ++ ADD_CR and ADD_LF_DOT make the istream-dot round-trip lossy, ++ as these introduce bytes not present in the original input. ++ We accept this tradeoff, since preserving exact byte fidelity ++ for malformed input is less important than eliminating an ++ injection vector. */ ++ ++ switch(add) { ++ case ADD_DOT: ++ iovn.iov_base = ".."; ++ iovn.iov_len = 2; ++ break; ++ case ADD_CR: ++ iovn.iov_base = "\r\n"; ++ iovn.iov_len = 2; ++ break; ++ case ADD_LF_DOT: ++ iovn.iov_base = "\n.."; ++ iovn.iov_len = 3; ++ break; ++ default: ++ i_unreached(); ++ } ++ + array_push_back(&iov_arr, &iovn); +- i_assert(max_bytes >= 2); +- max_bytes -= 2; +- added++; ++ i_assert(iovn.iov_len <= ADD_MAX); ++ i_assert(iovn.iov_len <= max_bytes); ++ max_bytes -= iovn.iov_len; ++ added += iovn.iov_len - 1; + sent++; + } + } + + if (max_bytes == 0) + break; +- chunk = ((size_t)(p-data) >= max_bytes ? +- max_bytes : (size_t)(p - data)); ++ chunk = I_MIN((size_t)(p - data), max_bytes); + if (chunk > 0) { + iovn.iov_base = data; + iovn.iov_len = chunk; +--- a/src/lib-mail/test-ostream-dot.c ++++ b/src/lib-mail/test-ostream-dot.c +@@ -57,6 +57,9 @@ static void test_ostream_dot(void) + { "foo\n.\n", "foo\r\n..\r\n.\r\n" }, + { ".foo\r\n.\r\nfoo\r\n", "..foo\r\n..\r\nfoo\r\n.\r\n" }, + { ".foo\n.\nfoo\n", "..foo\r\n..\r\nfoo\r\n.\r\n" }, ++ { ".", "..\r\n.\r\n" }, ++ { "\r.", "\r\n..\r\n.\r\n" }, ++ { "\r\r.", "\r\r\n..\r\n.\r\n" }, + { "\r\n", "\r\n.\r\n" }, + { "\n", "\r\n.\r\n" }, + { "", "\r\n.\r\n" }, +@@ -92,11 +95,94 @@ static void test_ostream_dot_parent_almo + test_end(); + } + ++static void test_ostream_dot_parent_max_bytes_boundary(void) ++{ ++ buffer_t *output_data; ++ struct ostream *test_output, *output; ++ ssize_t ret; ++ ++ test_begin("dot ostream parent exact fit"); ++ output_data = t_buffer_create(1024); ++ test_output = test_ostream_create_nonblocking(output_data, 3); ++ test_ostream_set_max_output_size(test_output, 3); ++ ++ output = o_stream_create_dot(test_output, FALSE); ++ ret = o_stream_send(output, ".", 1); ++ test_assert(ret == 1); ++ test_assert_ucmp(output_data->used, ==, 2); ++ test_assert_memcmp(output_data->data, output_data->used, "..", 2); ++ ++ o_stream_unref(&output); ++ o_stream_unref(&test_output); ++ test_end(); ++} ++ ++/* STATE_CR must persist across sendv calls so that a bare CR ending one send ++ followed by '.' starting the next still triggers ADD_LF_DOT. ++ A stateless per-call implementation would emit the '.' unguarded and let a ++ downstream MTA that treats bare CR as EOL interpret it as end-of-DATA. */ ++static void test_ostream_dot_cr_across_sendv(void) ++{ ++ buffer_t *output_data; ++ struct ostream *test_output, *output; ++ ssize_t ret; ++ const char *expected = "\r\n..\r\n.\r\n"; ++ ++ test_begin("dot ostream CR across sendv calls"); ++ output_data = t_buffer_create(1024); ++ test_output = o_stream_create_buffer(output_data); ++ ++ output = o_stream_create_dot(test_output, FALSE); ++ ret = o_stream_send(output, "\r", 1); ++ test_assert(ret == 1); ++ ret = o_stream_send(output, ".", 1); ++ test_assert(ret == 1); ++ test_assert(o_stream_finish(output) > 0); ++ ++ o_stream_unref(&output); ++ o_stream_unref(&test_output); ++ ++ test_assert_ucmp(str_len(output_data), ==, strlen(expected)); ++ test_assert_memcmp(str_c(output_data), str_len(output_data), ++ expected, strlen(expected)); ++ test_end(); ++} ++ ++/* Off-by-one regression guard for the bare-CR + '.' injection. ++ Input "\r." places '.' at offset 1; the ADD_LF_DOT pair injects 3 bytes ++ ("\n.."). The loop guard check becomes (1 + 3) <= max_bytes, so max_bytes==4 ++ is the exact-fit case. */ ++static void test_ostream_dot_cr_dot_exact_fit(void) ++{ ++ buffer_t *output_data; ++ struct ostream *test_output, *output; ++ ssize_t ret; ++ ++ test_begin("dot ostream CR+dot exact fit"); ++ output_data = t_buffer_create(1024); ++ test_output = test_ostream_create_nonblocking(output_data, 4); ++ test_ostream_set_max_output_size(test_output, 4); ++ ++ output = o_stream_create_dot(test_output, FALSE); ++ ret = o_stream_send(output, "\r.", 2); ++ test_assert(ret == 2); ++ test_assert_ucmp(output_data->used, ==, 4); ++ test_assert_memcmp(output_data->data, output_data->used, ++ "\r\n..", 4); ++ ++ o_stream_unref(&output); ++ o_stream_unref(&test_output); ++ test_end(); ++} ++ + int main(void) + { + static void (*const test_functions[])(void) = { + test_ostream_dot, + test_ostream_dot_parent_almost_full, ++ test_ostream_dot_parent_max_bytes_boundary, ++ test_ostream_dot_cr_across_sendv, ++ test_ostream_dot_cr_dot_exact_fit, + NULL + }; + return test_run(test_functions); diff --git a/mail/dovecot/patches/212-CVE-2026-33607.patch b/mail/dovecot/patches/212-CVE-2026-33607.patch new file mode 100644 index 0000000000..b0bcfef30b --- /dev/null +++ b/mail/dovecot/patches/212-CVE-2026-33607.patch @@ -0,0 +1,175 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Guilhem Moulin +Subject: [PATCH] Fix CVE-2026-33607 + +Upstream commits: + lib-imap: imap-match - Limit backtracking to 20k to mitigate excessive CPU usage + https://github.com/dovecot/core/commit/e487bab78ac4b8c38621f29e56ffb5ac2e739658#diff-7fa3a9504538f178768669758fc0c71a12c3b629730be94d82f7b17ab815eb22 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-imap/imap-match.c ++++ b/src/lib-imap/imap-match.c +@@ -235,9 +235,11 @@ bool imap_match_globs_equal(const struct + (i_toupper(*(data)) == i_toupper(*(pattern)) && \ + (data) < (ctx)->inboxcase_end)) + ++#define MATCH_SUB_MAX_BACKTRACK_COUNT 20000 ++ + static enum imap_match_result + match_sub(struct imap_match_context *ctx, const char **data_p, +- const char **pattern_p) ++ const char **pattern_p, unsigned int *backtrack_count_p) + { + enum imap_match_result ret, match; + unsigned int i; +@@ -282,7 +284,9 @@ match_sub(struct imap_match_context *ctx + /* skip over this hierarchy */ + while (*data != '\0') { + if (CMP_CUR_CHR(ctx, data, pattern)) { +- ret = match_sub(ctx, &data, &pattern); ++ if ((*backtrack_count_p)++ > MATCH_SUB_MAX_BACKTRACK_COUNT) ++ return IMAP_MATCH_NO; ++ ret = match_sub(ctx, &data, &pattern, backtrack_count_p); + if (ret == IMAP_MATCH_YES) + break; + +@@ -317,7 +321,7 @@ match_sub(struct imap_match_context *ctx + + static enum imap_match_result + imap_match_pattern(struct imap_match_context *ctx, +- const char *data, const char *pattern) ++ const char *data, const char *pattern, unsigned int *backtrack_count_p) + { + enum imap_match_result ret, match; + +@@ -330,8 +334,10 @@ imap_match_pattern(struct imap_match_con + } + + if (*pattern != '*') { ++ if ((*backtrack_count_p)++ > MATCH_SUB_MAX_BACKTRACK_COUNT) ++ return IMAP_MATCH_NO; + /* handle the pattern up to the first '*' */ +- ret = match_sub(ctx, &data, &pattern); ++ ret = match_sub(ctx, &data, &pattern, backtrack_count_p); + if (ret != IMAP_MATCH_YES || *pattern == '\0') + return ret; + } +@@ -345,7 +351,9 @@ imap_match_pattern(struct imap_match_con + + while (*data != '\0') { + if (CMP_CUR_CHR(ctx, data, pattern)) { +- ret = match_sub(ctx, &data, &pattern); ++ if ((*backtrack_count_p)++ > MATCH_SUB_MAX_BACKTRACK_COUNT) ++ return IMAP_MATCH_NO; ++ ret = match_sub(ctx, &data, &pattern, backtrack_count_p); + if (ret == IMAP_MATCH_YES) + break; + match |= ret; +@@ -363,7 +371,7 @@ enum imap_match_result + imap_match(struct imap_match_glob *glob, const char *data) + { + struct imap_match_context ctx; +- unsigned int i; ++ unsigned int i, count; + enum imap_match_result ret, match; + + match = IMAP_MATCH_NO; +@@ -371,7 +379,8 @@ imap_match(struct imap_match_glob *glob, + for (i = 0; glob->patterns[i].pattern != NULL; i++) { + ctx.inboxcase = glob->patterns[i].inboxcase; + +- ret = imap_match_pattern(&ctx, data, glob->patterns[i].pattern); ++ count = 0; ++ ret = imap_match_pattern(&ctx, data, glob->patterns[i].pattern, &count); + if (ret == IMAP_MATCH_YES) + return IMAP_MATCH_YES; + +--- a/src/lib-imap/test-imap-match.c ++++ b/src/lib-imap/test-imap-match.c +@@ -1,6 +1,7 @@ + /* Copyright (c) 2008-2018 Dovecot authors, see the included COPYING file */ + + #include "lib.h" ++#include "str.h" + #include "imap-match.h" + #include "test-common.h" + +@@ -88,6 +89,67 @@ static void test_imap_match(void) + test_end(); + } + ++static void test_imap_match_no_redos(void) ++{ ++ /* Verify that patterns with many % wildcards followed by a literal ++ that repeats in the data do not cause exponential backtracking. ++ The NFA simulation is O(n_data * n_pattern) regardless of wildcard ++ count, so even very large pattern/data combinations must complete ++ quickly. */ ++ struct imap_match_glob *glob; ++ pool_t pool; ++ const unsigned int wildcard_count = 1000; ++ ++ pool = pool_alloconly_create("imap match redos", 1024); ++ test_begin("imap match no redos"); ++ ++ /* 255-character single-hierarchy mailbox name */ ++ string_t *mailbox_name = str_new(pool, 256); ++ for (unsigned int i = 0; i < 255; i++) ++ str_append_c(mailbox_name, 'a'); ++ ++ /* N x "%a" against 255 "a"s: match when N <= 255 */ ++ string_t *pattern = str_new(pool, wildcard_count * 2 + 10); ++ for (unsigned int i = 0; i < 255; i++) ++ str_append(pattern, "%a"); ++ glob = imap_match_init(pool, str_c(pattern), FALSE, '/'); ++ test_assert(imap_match(glob, str_c(mailbox_name)) == IMAP_MATCH_YES); ++ ++ /* More wildcards than data characters -> non-match */ ++ str_truncate(pattern, 0); ++ for (unsigned int i = 0; i < wildcard_count; i++) ++ str_append(pattern, "%a"); ++ glob = imap_match_init(pool, str_c(pattern), FALSE, '/'); ++ test_assert(imap_match(glob, str_c(mailbox_name)) == IMAP_MATCH_NO); ++ ++ /* Large N x "%a" + "b" against 255 "a"s: no match */ ++ str_append_c(pattern, 'b'); ++ glob = imap_match_init(pool, str_c(pattern), FALSE, '/'); ++ test_assert(imap_match(glob, str_c(mailbox_name)) == IMAP_MATCH_NO); ++ ++ /* Same with "*" wildcards: returns CHILDREN because the pattern ++ could match something under the current name */ ++ str_truncate(pattern, 0); ++ for (unsigned int i = 0; i < wildcard_count; i++) ++ str_append(pattern, "*a"); ++ str_append_c(pattern, 'b'); ++ glob = imap_match_init(pool, str_c(pattern), FALSE, '/'); ++ test_assert(imap_match(glob, str_c(mailbox_name)) == IMAP_MATCH_CHILDREN); ++ p_clear(pool); ++ ++ /* Positive case: 5 x "%a" + "b" should match "aaaaab" */ ++ glob = imap_match_init(pool, "%a%a%a%a%ab", FALSE, '/'); ++ test_assert(imap_match(glob, "aaaaab") == IMAP_MATCH_YES); ++ p_clear(pool); ++ ++ /* Negative case: 5 x "%a" + "b" does not match "aaaaa" (no trailing b) */ ++ glob = imap_match_init(pool, "%a%a%a%a%ab", FALSE, '/'); ++ test_assert(imap_match(glob, "aaaaa") == IMAP_MATCH_NO); ++ ++ pool_unref(&pool); ++ test_end(); ++} ++ + static void test_imap_match_globs_equal(void) + { + struct imap_match_glob *glob; +@@ -120,6 +182,7 @@ int main(void) + { + static void (*const test_functions[])(void) = { + test_imap_match, ++ test_imap_match_no_redos, + test_imap_match_globs_equal, + NULL + }; diff --git a/mail/dovecot/patches/213-CVE-2026-27852.patch b/mail/dovecot/patches/213-CVE-2026-27852.patch new file mode 100644 index 0000000000..70d6238cb1 --- /dev/null +++ b/mail/dovecot/patches/213-CVE-2026-27852.patch @@ -0,0 +1,814 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-27852 + +Upstream commits: + imap: Stream BODYSTRUCTURE to client without ostream memory duplication + https://github.com/dovecot/core/commit/a67a9464acad60a337a31ac6fb3f36df95f002eb + imap: Stream ENVELOPE to client without ostream memory duplication + https://github.com/dovecot/core/commit/2837d1e1fe5af07d09c10f6c09fb7fcca85a89c8 + lib-mail: message-parser-from-parts: Enforce 50 MB all-headers-max-size limit + https://github.com/dovecot/core/commit/be07a3c783fd9359ddd5b183becb0da17f3d743c + lib-mail: Add count field to struct message_address_list + https://github.com/dovecot/core/commit/e4b8d305ce0dd48843e69b8b3b235f275e89c93f + lib-storage/mbox: Explicitly disable the header block size limit + https://github.com/dovecot/core/commit/33461dedda0f09793b2b7c8a7990935fa322a897 + lib-mail: istream-header-filter - Use container_of() for struct casts + https://github.com/dovecot/core/commit/17e5f5d27b3b35fd9195da77feb555fbbdc08263 + lib-mail: Make istream-header-filter's per-header size limit configurable + https://github.com/dovecot/core/commit/0a7a98851b0f49759780156e2bfd0e4ec19752fc + lib-storage: Cap per-header size in index_mail_get_header_stream() + https://github.com/dovecot/core/commit/94454090c12b6a4081fb75559e24ab024a66cf27 + lib-mail: Clamp hdr->value cumulatively against header_block_max_size + https://github.com/dovecot/core/commit/fc7a4eef0f7166acb4aafe995930ddc0da9f7cf6 + lib-mail: Introduce struct message_part_data_limits and thread it through parsers + https://github.com/dovecot/core/commit/c5282786988d6be67d74067908f27e5480938a00 + lib-mail: Limit total address count per message to 100 000 + https://github.com/dovecot/core/commit/a973e668bcdbfba8c0ceb1ed74b091b82cab501a + lib-mail: Limit total Content-Language tag count per message to 100 000 + https://github.com/dovecot/core/commit/a1baaddc23493a9061fe5430085b36ce8543bae6 + lib-mail: Limit total MIME parameter count per message to 200 000 + https://github.com/dovecot/core/commit/69868fbdb06aa08ee74b1031d5cb461a73394006 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/imap/imap-fetch.c ++++ b/src/imap/imap-fetch.c +@@ -732,6 +732,34 @@ static bool fetch_body_init(struct imap_ + return imap_fetch_body_section_init(ctx); + } + ++static int fetch_bodystructure_stream_continue(struct imap_fetch_context *ctx) ++{ ++ struct imap_fetch_state *state = &ctx->state; ++ enum ostream_send_istream_result res; ++ ++ o_stream_set_max_buffer_size(ctx->client->output, 0); ++ res = o_stream_send_istream(ctx->client->output, state->cur_input); ++ o_stream_set_max_buffer_size(ctx->client->output, SIZE_MAX); ++ ++ switch (res) { ++ case OSTREAM_SEND_ISTREAM_RESULT_FINISHED: ++ i_stream_unref(&state->cur_input); ++ state->cont_handler = NULL; ++ if (o_stream_send(ctx->client->output, ")", 1) < 0) ++ return -1; ++ return 1; ++ case OSTREAM_SEND_ISTREAM_RESULT_WAIT_INPUT: ++ i_unreached(); ++ case OSTREAM_SEND_ISTREAM_RESULT_WAIT_OUTPUT: ++ return 0; ++ case OSTREAM_SEND_ISTREAM_RESULT_ERROR_INPUT: ++ i_unreached(); ++ case OSTREAM_SEND_ISTREAM_RESULT_ERROR_OUTPUT: ++ return -1; ++ } ++ i_unreached(); ++} ++ + static int fetch_bodystructure(struct imap_fetch_context *ctx, + struct mail *mail, void *context ATTR_UNUSED) + { +@@ -748,12 +776,13 @@ static int fetch_bodystructure(struct im + return -1; + } + +- if (o_stream_send(ctx->client->output, "BODYSTRUCTURE (", 15) < 0 || +- o_stream_send_str(ctx->client->output, bodystructure) < 0 || +- o_stream_send(ctx->client->output, ")", 1) < 0) ++ if (o_stream_send(ctx->client->output, "BODYSTRUCTURE (", 15) < 0) + return -1; + +- return 1; ++ ctx->state.cur_input = ++ i_stream_create_from_data(bodystructure, strlen(bodystructure)); ++ ctx->state.cont_handler = fetch_bodystructure_stream_continue; ++ return fetch_bodystructure_stream_continue(ctx); + } + + static bool fetch_bodystructure_init(struct imap_fetch_init_context *ctx) +@@ -764,6 +793,34 @@ static bool fetch_bodystructure_init(str + return TRUE; + } + ++static int fetch_envelope_stream_continue(struct imap_fetch_context *ctx) ++{ ++ struct imap_fetch_state *state = &ctx->state; ++ enum ostream_send_istream_result res; ++ ++ o_stream_set_max_buffer_size(ctx->client->output, 0); ++ res = o_stream_send_istream(ctx->client->output, state->cur_input); ++ o_stream_set_max_buffer_size(ctx->client->output, SIZE_MAX); ++ ++ switch (res) { ++ case OSTREAM_SEND_ISTREAM_RESULT_FINISHED: ++ i_stream_unref(&state->cur_input); ++ state->cont_handler = NULL; ++ if (o_stream_send(ctx->client->output, ")", 1) < 0) ++ return -1; ++ return 1; ++ case OSTREAM_SEND_ISTREAM_RESULT_WAIT_INPUT: ++ i_unreached(); ++ case OSTREAM_SEND_ISTREAM_RESULT_WAIT_OUTPUT: ++ return 0; ++ case OSTREAM_SEND_ISTREAM_RESULT_ERROR_INPUT: ++ i_unreached(); ++ case OSTREAM_SEND_ISTREAM_RESULT_ERROR_OUTPUT: ++ return -1; ++ } ++ i_unreached(); ++} ++ + static int fetch_envelope(struct imap_fetch_context *ctx, struct mail *mail, + void *context ATTR_UNUSED) + { +@@ -779,11 +836,13 @@ static int fetch_envelope(struct imap_fe + return -1; + } + +- if (o_stream_send(ctx->client->output, "ENVELOPE (", 10) < 0 || +- o_stream_send_str(ctx->client->output, envelope) < 0 || +- o_stream_send(ctx->client->output, ")", 1) < 0) ++ if (o_stream_send(ctx->client->output, "ENVELOPE (", 10) < 0) + return -1; +- return 1; ++ ++ ctx->state.cur_input = ++ i_stream_create_from_data(envelope, strlen(envelope)); ++ ctx->state.cont_handler = fetch_envelope_stream_continue; ++ return fetch_envelope_stream_continue(ctx); + } + + static bool fetch_envelope_init(struct imap_fetch_init_context *ctx) +--- a/src/lib-imap/test-imap-bodystructure.c ++++ b/src/lib-imap/test-imap-bodystructure.c +@@ -398,10 +398,11 @@ msg_parse(pool_t pool, const char *messa + + input = i_stream_create_from_data(message, strlen(message)); + parser = message_parser_init(pool, input, &parser_set); ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + while ((ret = message_parser_parse_next_block(parser, &block)) > 0) { + if (parse_bodystructure) { + message_part_data_parse_from_header(pool, block.part, +- block.hdr); ++ &limits, block.hdr); + } + } + test_assert(ret < 0); +--- a/src/lib-imap/test-imap-envelope.c ++++ b/src/lib-imap/test-imap-envelope.c +@@ -132,9 +132,11 @@ msg_parse(pool_t pool, const char *messa + + input = i_stream_create_from_data(message, strlen(message)); + parser = message_parser_init(pool, input, &parser_set); ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + while ((ret = message_parser_parse_next_block(parser, &block)) > 0) { + i_assert(block.part->parent == NULL); +- message_part_envelope_parse_from_header(pool, &envlp, block.hdr); ++ message_part_envelope_parse_from_header(pool, &envlp, &limits, ++ block.hdr); + } + test_assert(ret < 0); + +--- a/src/lib-mail/istream-header-filter.c ++++ b/src/lib-mail/istream-header-filter.c +@@ -28,6 +28,7 @@ struct header_filter_istream { + + buffer_t *hdr_buf; + struct message_size header_size; ++ size_t max_header_block_size; + uoff_t skip_count; + uoff_t last_lf_offset; + +@@ -60,7 +61,7 @@ static ssize_t i_stream_header_filter_re + static void i_stream_header_filter_destroy(struct iostream_private *stream) + { + struct header_filter_istream *mstream = +- (struct header_filter_istream *)stream; ++ container_of(stream, struct header_filter_istream, istream.iostream); + + if (mstream->hdr_ctx != NULL) + message_parse_header_deinit(&mstream->hdr_ctx); +@@ -194,6 +195,8 @@ static ssize_t read_header(struct header + mstream->hdr_ctx = + message_parse_header_init(mstream->istream.parent, + NULL, 0); ++ message_parse_header_set_limit(mstream->hdr_ctx, ++ mstream->max_header_block_size); + } + + /* remove skipped data from hdr_buf */ +@@ -468,7 +471,7 @@ handle_end_body_with_lf(struct header_fi + static ssize_t i_stream_header_filter_read(struct istream_private *stream) + { + struct header_filter_istream *mstream = +- (struct header_filter_istream *)stream; ++ container_of(stream, struct header_filter_istream, istream); + uoff_t v_offset; + ssize_t ret; + +@@ -552,7 +555,7 @@ static void i_stream_header_filter_seek( + uoff_t v_offset, bool mark ATTR_UNUSED) + { + struct header_filter_istream *mstream = +- (struct header_filter_istream *)stream; ++ container_of(stream, struct header_filter_istream, istream); + + if (stream->istream.v_offset == v_offset) { + /* just reset the input buffer */ +@@ -602,7 +605,7 @@ static int + i_stream_header_filter_stat(struct istream_private *stream, bool exact) + { + struct header_filter_istream *mstream = +- (struct header_filter_istream *)stream; ++ container_of(stream, struct header_filter_istream, istream); + const struct stat *st; + uoff_t old_offset; + +@@ -671,7 +674,7 @@ i_stream_header_filter_snapshot(struct i + struct istream_snapshot *prev_snapshot) + { + struct header_filter_istream *mstream = +- (struct header_filter_istream *)stream; ++ container_of(stream, struct header_filter_istream, istream); + struct header_filter_istream_snapshot *snapshot; + + if (stream->buffer != mstream->hdr_buf->data) { +@@ -707,6 +710,9 @@ i_stream_create_header_filter(struct ist + mstream->pool = pool_alloconly_create(MEMPOOL_GROWING + "header filter stream", 256); + mstream->istream.max_buffer_size = input->real_stream->max_buffer_size; ++ /* Default to no per-header block size limit. Callers that want one ++ call i_stream_header_filter_set_max_header_block_size(). */ ++ mstream->max_header_block_size = SIZE_MAX; + + mstream->headers = headers_count == 0 ? NULL : + p_new(mstream->pool, const char *, headers_count); +@@ -760,3 +766,17 @@ void i_stream_header_filter_add(struct h + buffer_append(input->hdr_buf, data, size); + input->headers_edited = TRUE; + } ++ ++void i_stream_header_filter_set_max_header_block_size( ++ struct istream *input, size_t max_header_block_size) ++{ ++ struct header_filter_istream *mstream = ++ container_of(input->real_stream, struct header_filter_istream, ++ istream); ++ ++ mstream->max_header_block_size = max_header_block_size; ++ if (mstream->hdr_ctx != NULL) { ++ message_parse_header_set_limit(mstream->hdr_ctx, ++ max_header_block_size); ++ } ++} +--- a/src/lib-mail/istream-header-filter.h ++++ b/src/lib-mail/istream-header-filter.h +@@ -49,4 +49,12 @@ i_stream_create_header_filter(struct ist + void i_stream_header_filter_add(struct header_filter_istream *input, + const void *data, size_t size); + ++/* Set a per-header-block maximum size for this filter stream. Data beyond ++ this limit in any single header is dropped from the filter's output and ++ from values delivered to the filter callback. The default is SIZE_MAX ++ (unlimited). Use MESSAGE_HEADER_BLOCK_DEFAULT_MAX_SIZE from ++ message-header-parser.h for the standard cap. */ ++void i_stream_header_filter_set_max_header_block_size( ++ struct istream *input, size_t max_header_block_size); ++ + #endif +--- a/src/lib-mail/message-address.c ++++ b/src/lib-mail/message-address.c +@@ -30,6 +30,7 @@ static void add_address(struct message_a + i_zero(&ctx->addr); + + DLLIST2_APPEND(&ctx->addr_list.head, &ctx->addr_list.tail, addr); ++ ctx->addr_list.count++; + } + + /* quote with "" and escape all '\', '"' and "'" characters if need */ +--- a/src/lib-mail/message-address.h ++++ b/src/lib-mail/message-address.h +@@ -33,6 +33,7 @@ struct message_address { + + struct message_address_list { + struct message_address *head, *tail; ++ unsigned int count; + }; + + /* Parse message addresses from given data. Note that giving an empty string +--- a/src/lib-mail/message-header-parser.c ++++ b/src/lib-mail/message-header-parser.c +@@ -96,7 +96,6 @@ int message_parse_header_next(struct mes + /* new header line */ + line->name_offset = ctx->input->v_offset; + colon_pos = UINT_MAX; +- ctx->header_block_total_size += ctx->value_buf->used; + buffer_set_used_size(ctx->value_buf, 0); + } + +@@ -362,12 +361,17 @@ int message_parse_header_next(struct mes + } + } + +- line->value_len = I_MIN(line->value_len, ctx->header_block_max_size); + size_t line_value_size = line->value_len; +- size_t header_total_used = ctx->header_block_total_size + ctx->value_buf->used; +- size_t line_available = ctx->header_block_max_size <= header_total_used ? 0 : +- ctx->header_block_max_size - header_total_used; ++ /* Clamp line_value_size against the remaining header_block_max_size ++ budget. header_block_total_size is the running sum of ++ line_value_size across all chunks of all headers; value_buf growth ++ is bounded implicitly because every append to value_buf uses ++ line_value_size. */ ++ size_t line_available = ++ ctx->header_block_max_size <= ctx->header_block_total_size ? 0 : ++ ctx->header_block_max_size - ctx->header_block_total_size; + line_value_size = I_MIN(line_value_size, line_available); ++ ctx->header_block_total_size += line_value_size; + + if (!line->continued) { + /* first header line. make a copy of the line since we can't +@@ -397,10 +401,12 @@ int message_parse_header_next(struct mes + + line->full_value = ctx->value_buf->data; + line->full_value_len = ctx->value_buf->used; ++ line->value_len = line_value_size; + } else { + /* we didn't want full_value, and this is a continued line. */ + line->full_value = NULL; + line->full_value_len = 0; ++ line->value_len = line_value_size; + } + + /* always reset it */ +--- a/src/lib-mail/message-parser-from-parts.c ++++ b/src/lib-mail/message-parser-from-parts.c +@@ -303,6 +303,11 @@ static int preparsed_parse_next_header(s + } + + if (hdr != NULL) { ++ if (!hdr->continues) { ++ ctx->all_headers_total_size += hdr->name_len; ++ ctx->all_headers_total_size += hdr->middle_len; ++ } ++ ctx->all_headers_total_size += hdr->value_len; + block_r->hdr = hdr; + block_r->size = 0; + return 1; +@@ -344,6 +349,11 @@ static int preparsed_parse_next_header_i + message_parse_header_init(hdr_input, NULL, ctx->hdr_flags); + i_stream_unref(&hdr_input); + ++ size_t headers_available = ++ ctx->all_headers_max_size > ctx->all_headers_total_size ? ++ ctx->all_headers_max_size - ctx->all_headers_total_size : 0; ++ message_parse_header_lower_limit(ctx->hdr_parser_ctx, headers_available); ++ + ctx->parse_next_block = preparsed_parse_next_header; + return preparsed_parse_next_header(ctx, block_r); + } +--- a/src/lib-mail/message-part-data.c ++++ b/src/lib-mail/message-part-data.c +@@ -173,6 +173,7 @@ envelope_get_field(const char *name) + + void message_part_envelope_parse_from_header(pool_t pool, + struct message_part_envelope **data, ++ struct message_part_data_limits *limits, + struct message_header_line *hdr) + { + struct message_part_envelope *d; +@@ -237,9 +238,12 @@ void message_part_envelope_parse_from_he + if (addr_p != NULL) { + message_address_parse_full(pool, hdr->full_value, + hdr->full_value_len, +- UINT_MAX, ++ limits->remaining_addresses, + MESSAGE_ADDRESS_PARSE_FLAG_FILL_MISSING, + &new_addr); ++ i_assert(new_addr.count <= limits->remaining_addresses); ++ limits->remaining_addresses -= new_addr.count; ++ + /* Merge multiple headers the same as if they were comma + separated in a single line. This is better from security + point of view, because attacker could intentionally write +@@ -247,6 +251,7 @@ void message_part_envelope_parse_from_he + validated while MUA only shows the second From header. */ + DLLIST2_JOIN(&addr_p->head, &addr_p->tail, + &new_addr.head, &new_addr.tail); ++ addr_p->count += new_addr.count; + } else if (str_p != NULL) { + *str_p = message_header_strdup(pool, hdr->full_value, + hdr->full_value_len); +@@ -258,7 +263,8 @@ void message_part_envelope_parse_from_he + static void + parse_mime_parameters(struct rfc822_parser_context *parser, + pool_t pool, const struct message_part_param **params_r, +- unsigned int *params_count_r) ++ unsigned int *params_count_r, ++ struct message_part_data_limits *limits) + { + const char *const *results; + struct message_part_param *params; +@@ -270,6 +276,10 @@ parse_mime_parameters(struct rfc822_pars + i_assert((params_count % 2) == 0); + params_count /= 2; + ++ if (params_count > limits->remaining_mime_params) ++ params_count = limits->remaining_mime_params; ++ limits->remaining_mime_params -= params_count; ++ + if (params_count > 0) { + params = p_new(pool, struct message_part_param, params_count); + for (i = 0; i < params_count; i++) { +@@ -284,7 +294,8 @@ parse_mime_parameters(struct rfc822_pars + + static void + parse_content_type(struct message_part_data *data, +- pool_t pool, struct message_header_line *hdr) ++ pool_t pool, struct message_header_line *hdr, ++ struct message_part_data_limits *limits) + { + struct rfc822_parser_context parser; + string_t *str; +@@ -327,7 +338,7 @@ parse_content_type(struct message_part_d + + parse_mime_parameters(&parser, pool, + &data->content_type_params, +- &data->content_type_params_count); ++ &data->content_type_params_count, limits); + rfc822_parser_deinit(&parser); + } + +@@ -352,7 +363,8 @@ parse_content_transfer_encoding(struct m + + static void + parse_content_disposition(struct message_part_data *data, +- pool_t pool, struct message_header_line *hdr) ++ pool_t pool, struct message_header_line *hdr, ++ struct message_part_data_limits *limits) + { + struct rfc822_parser_context parser; + string_t *str; +@@ -369,13 +381,14 @@ parse_content_disposition(struct message + + parse_mime_parameters(&parser, pool, + &data->content_disposition_params, +- &data->content_disposition_params_count); ++ &data->content_disposition_params_count, limits); + rfc822_parser_deinit(&parser); + } + + static void + parse_content_language(struct message_part_data *data, +- pool_t pool, const unsigned char *value, size_t value_len) ++ pool_t pool, const unsigned char *value, size_t value_len, ++ struct message_part_data_limits *limits) + { + struct rfc822_parser_context parser; + ARRAY_TYPE(const_string) langs; +@@ -393,8 +406,11 @@ parse_content_language(struct message_pa + + rfc822_skip_lwsp(&parser); + while (rfc822_parse_atom(&parser, str) >= 0) { +- const char *lang = p_strdup(pool, str_c(str)); ++ if (limits->remaining_language_tags == 0) ++ break; ++ limits->remaining_language_tags--; + ++ const char *lang = p_strdup(pool, str_c(str)); + array_push_back(&langs, &lang); + str_truncate(str, 0); + +@@ -414,7 +430,8 @@ parse_content_language(struct message_pa + + static void + parse_content_header(struct message_part_data *data, +- pool_t pool, struct message_header_line *hdr) ++ pool_t pool, struct message_header_line *hdr, ++ struct message_part_data_limits *limits) + { + const char *name = hdr->name + strlen("Content-"); + +@@ -443,7 +460,7 @@ parse_content_header(struct message_part + case 't': + case 'T': + if (strcasecmp(name, "Type") == 0 && data->content_type == NULL) +- parse_content_type(data, pool, hdr); ++ parse_content_type(data, pool, hdr, limits); + else if (strcasecmp(name, "Transfer-Encoding") == 0 && + data->content_transfer_encoding == NULL) + parse_content_transfer_encoding(data, pool, hdr); +@@ -454,7 +471,7 @@ parse_content_header(struct message_part + if (strcasecmp(name, "Language") == 0 && + data->content_language == NULL) { + parse_content_language(data, pool, +- hdr->full_value, hdr->full_value_len); ++ hdr->full_value, hdr->full_value_len, limits); + } else if (strcasecmp(name, "Location") == 0 && + data->content_location == NULL) { + data->content_location = +@@ -472,13 +489,14 @@ parse_content_header(struct message_part + hdr->full_value_len); + else if (strcasecmp(name, "Disposition") == 0 && + data->content_disposition_params == NULL) +- parse_content_disposition(data, pool, hdr); ++ parse_content_disposition(data, pool, hdr, limits); + break; + } + } + + void message_part_data_parse_from_header(pool_t pool, + struct message_part *part, ++ struct message_part_data_limits *limits, + struct message_header_line *hdr) + { + struct message_part_data *part_data; +@@ -518,13 +536,14 @@ void message_part_data_parse_from_header + + if (strncasecmp(hdr->name, "Content-", 8) == 0) { + T_BEGIN { +- parse_content_header(part_data, pool, hdr); ++ parse_content_header(part_data, pool, hdr, limits); + } T_END; + } + + if (parent_rfc822) { + /* message/rfc822, we need the envelope */ +- message_part_envelope_parse_from_header(pool, &part_data->envelope, hdr); ++ message_part_envelope_parse_from_header(pool, &part_data->envelope, ++ limits, hdr); + } + } + +--- a/src/lib-mail/message-part-data.h ++++ b/src/lib-mail/message-part-data.h +@@ -8,6 +8,22 @@ + + struct message_header_line; + ++#define MESSAGE_PART_DATA_MAX_TOTAL_ADDRESSES 100000 ++#define MESSAGE_PART_DATA_MAX_TOTAL_LANGUAGE_TAGS 100000 ++/* Combined limit for Content-Type + Content-Disposition parameters */ ++#define MESSAGE_PART_DATA_MAX_TOTAL_MIME_PARAMS 200000 ++ ++struct message_part_data_limits { ++ unsigned int remaining_addresses; ++ unsigned int remaining_language_tags; ++ unsigned int remaining_mime_params; ++}; ++ ++#define MESSAGE_PART_DATA_LIMITS_INIT \ ++ { MESSAGE_PART_DATA_MAX_TOTAL_ADDRESSES, \ ++ MESSAGE_PART_DATA_MAX_TOTAL_LANGUAGE_TAGS, \ ++ MESSAGE_PART_DATA_MAX_TOTAL_MIME_PARAMS } ++ + struct message_part_param { + const char *name; + const char *value; +@@ -93,11 +109,13 @@ bool message_part_is_attachment(struct m + /* Update envelope data based from given header field */ + void message_part_envelope_parse_from_header(pool_t pool, + struct message_part_envelope **_data, ++ struct message_part_data_limits *limits, + struct message_header_line *hdr); + + /* Parse a single header. Note that this modifies part->context. */ + void message_part_data_parse_from_header(pool_t pool, + struct message_part *part, ++ struct message_part_data_limits *limits, + struct message_header_line *hdr); + + #endif +--- a/src/lib-mail/test-message-decoder.c ++++ b/src/lib-mail/test-message-decoder.c +@@ -260,8 +260,10 @@ static void test_message_decoder_content + parser = message_parser_init(pool, istream, &parser_set); + decoder = message_decoder_init(NULL, 0); + ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + while ((ret = message_parser_parse_next_block(parser, &input)) > 0) { +- message_part_data_parse_from_header(pool, input.part, input.hdr); ++ message_part_data_parse_from_header(pool, input.part, &limits, ++ input.hdr); + if (message_decoder_decode_next_block(decoder, &input, &output) && + output.hdr == NULL && output.size > 0) + str_append_data(str_out, output.data, output.size); +@@ -349,8 +351,10 @@ static void test_message_decoder_invalid + parser = message_parser_init(pool, istream, &parser_set); + decoder = message_decoder_init(NULL, 0); + ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + while ((ret = message_parser_parse_next_block(parser, &input)) > 0) { +- message_part_data_parse_from_header(pool, input.part, input.hdr); ++ message_part_data_parse_from_header(pool, input.part, &limits, ++ input.hdr); + if (input.hdr != NULL && + strcasecmp(input.hdr->name, "content-transfer-encoding") == 0) { + enum message_cte cte = message_decoder_parse_cte(input.hdr); +@@ -480,8 +484,10 @@ UNICODE_REPLACEMENT_CHAR_UTF8; + parser = message_parser_init(pool, istream, &parser_set); + decoder = message_decoder_init(NULL, 0); + ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + while ((ret = message_parser_parse_next_block(parser, &input)) > 0) { +- message_part_data_parse_from_header(pool, input.part, input.hdr); ++ message_part_data_parse_from_header(pool, input.part, &limits, ++ input.hdr); + if (message_decoder_decode_next_block(decoder, &input, &output) && + output.hdr == NULL && output.size > 0) + str_append_data(str_out, output.data, output.size); +--- a/src/lib-mail/test-message-header-parser.c ++++ b/src/lib-mail/test-message-header-parser.c +@@ -494,11 +494,14 @@ static void test_message_header_truncati + struct message_header_parser_ctx *parser = message_parse_header_init(input, NULL, MESSAGE_HEADER_PARSER_FLAG_CLEAN_ONELINE); + message_parse_header_set_limit(parser, 96); + ++ /* hdr->value is now also clamped cumulatively against the same ++ header_block_max_size budget as full_value, so later chunks of a ++ multiline header shrink or disappear once the budget is used up. */ + assert_parse_line( 1, "header1", "this is short", "this is short"); + assert_parse_line( 2, "header2", "this is multiline", "this is multiline"); + assert_parse_line( 3, "header2", " and long 343638404244464850525456586062", "this is multiline and long 343638404244464850525456586062"); +- assert_parse_line( 4, "header2", " 64666870727476788082848688909294969800", "this is multiline and long 343638404244464850525456586062 6466687072747678808284868"); +- assert_parse_line( 5, "header2", " 02040608101214161820222426283032343638", "this is multiline and long 343638404244464850525456586062 6466687072747678808284868"); ++ assert_parse_line( 4, "header2", " 6466687072747678808284868", "this is multiline and long 343638404244464850525456586062 6466687072747678808284868"); ++ assert_parse_line( 5, "header2", "", "this is multiline and long 343638404244464850525456586062 6466687072747678808284868"); + assert_parse_line( 6, "header3", "", ""); + test_assert(message_parse_header_next(parser, &hdr) > 0 && hdr->eoh); + +@@ -515,11 +518,16 @@ static void test_message_header_truncati + struct message_header_parser_ctx *parser = message_parse_header_init(input, NULL, 0); + message_parse_header_set_limit(parser, 96); + ++ /* hdr->value is clamped cumulatively against header_block_max_size. ++ The \n that NO flags inserts between continuations goes into ++ value_buf but is not added to header_block_total_size, so line 4's ++ value hits the same 26-byte cap as in CLEAN_ONELINE and ++ full_value_len is one byte larger than the nominal limit. */ + assert_parse_line( 1, "header1", "this is short", "this is short"); + assert_parse_line( 2, "header2", "this is multiline", "this is multiline"); + assert_parse_line( 3, "header2", " and long 343638404244464850525456586062", "this is multiline\n and long 343638404244464850525456586062"); +- assert_parse_line( 4, "header2", " 64666870727476788082848688909294969800", "this is multiline\n and long 343638404244464850525456586062\n 646668707274767880828486"); +- assert_parse_line( 5, "header2", " 02040608101214161820222426283032343638", "this is multiline\n and long 343638404244464850525456586062\n 646668707274767880828486"); ++ assert_parse_line( 4, "header2", " 6466687072747678808284868", "this is multiline\n and long 343638404244464850525456586062\n 6466687072747678808284868"); ++ assert_parse_line( 5, "header2", "", "this is multiline\n and long 343638404244464850525456586062\n 6466687072747678808284868"); + assert_parse_line( 6, "header3", "", ""); + test_assert(message_parse_header_next(parser, &hdr) > 0 && hdr->eoh); + +--- a/src/lib-mail/test-message-parser.c ++++ b/src/lib-mail/test-message-parser.c +@@ -51,12 +51,13 @@ static int message_parse_stream(pool_t p + struct message_parser_ctx *parser; + struct message_block block; + ++ struct message_part_data_limits limits = MESSAGE_PART_DATA_LIMITS_INIT; + i_zero(&block); + parser = message_parser_init(pool, input, set); + while ((ret = message_parser_parse_next_block(parser, &block)) > 0) + if (parse_data) + message_part_data_parse_from_header(pool, block.part, +- block.hdr); ++ &limits, block.hdr); + message_parser_deinit(&parser, parts_r); + test_assert(input->stream_errno == 0); + return ret; +--- a/src/lib-storage/index/index-mail-headers.c ++++ b/src/lib-storage/index/index-mail-headers.c +@@ -304,12 +304,15 @@ void index_mail_parse_header(struct mess + if (data->save_bodystructure_header && + !data->parsed_bodystructure_header) { + i_assert(part != NULL); +- message_part_data_parse_from_header(mail->mail.data_pool, part, hdr); ++ message_part_data_parse_from_header(mail->mail.data_pool, part, ++ &mail->data.part_data_limits, ++ hdr); + } + + if (data->save_envelope) { + message_part_envelope_parse_from_header(mail->mail.data_pool, +- &data->envelope_data, hdr); ++ &data->envelope_data, ++ &mail->data.part_data_limits, hdr); + + if (hdr == NULL) + index_mail_parse_finish_imap_envelope(mail); +@@ -506,7 +509,8 @@ imap_envelope_parse_callback(struct mess + struct index_mail *mail) + { + message_part_envelope_parse_from_header(mail->mail.data_pool, +- &mail->data.envelope_data, hdr); ++ &mail->data.envelope_data, ++ &mail->data.part_data_limits, hdr); + + if (hdr == NULL) + index_mail_parse_finish_imap_envelope(mail); +@@ -985,6 +989,11 @@ int index_mail_get_header_stream(struct + HEADER_FILTER_HIDE_BODY, + headers->name, headers->count, + header_cache_callback, mail); ++ /* Cap per-header data so a single pathological header cannot exhaust ++ memory in mail->header_data / the filter's buffer. */ ++ i_stream_header_filter_set_max_header_block_size( ++ mail->data.filter_stream, ++ MESSAGE_HEADER_BLOCK_DEFAULT_MAX_SIZE); + *stream_r = mail->data.filter_stream; + return 0; + } +--- a/src/lib-storage/index/index-mail.c ++++ b/src/lib-storage/index/index-mail.c +@@ -702,11 +702,16 @@ void index_mail_cache_pop3_data(struct m + &order, sizeof(order)); + } + ++struct parse_bodystructure_ctx { ++ pool_t pool; ++ struct message_part_data_limits *limits; ++}; ++ + static void parse_bodystructure_part_header(struct message_part *part, + struct message_header_line *hdr, +- pool_t pool) ++ struct parse_bodystructure_ctx *ctx) + { +- message_part_data_parse_from_header(pool, part, hdr); ++ message_part_data_parse_from_header(ctx->pool, part, ctx->limits, hdr); + } + + static bool want_plain_bodystructure_cached(struct index_mail *mail) +@@ -1321,9 +1326,13 @@ static int index_mail_parse_body(struct + /* bodystructure header is parsed, we want the body's mime + headers too */ + i_assert(data->parsed_bodystructure_header); ++ struct parse_bodystructure_ctx bsctx = { ++ .pool = mail->mail.data_pool, ++ .limits = &mail->data.part_data_limits, ++ }; + message_parser_parse_body(data->parser_ctx, + parse_bodystructure_part_header, +- mail->mail.data_pool); ++ &bsctx); + } else { + message_parser_parse_body(data->parser_ctx, + *null_message_part_header_callback, NULL); +@@ -1851,6 +1860,8 @@ static void index_mail_init_data(struct + data->received_date = (time_t)-1; + data->sent_date.time = (uint32_t)-1; + data->dont_cache_field_idx = UINT_MAX; ++ data->part_data_limits = (struct message_part_data_limits) ++ MESSAGE_PART_DATA_LIMITS_INIT; + + data->wanted_fields = mail->mail.wanted_fields; + if (mail->mail.wanted_headers != NULL) { +@@ -2311,7 +2322,9 @@ void index_mail_cache_parse_continue(str + mail->data.header_parsed = TRUE; + } else { + message_part_data_parse_from_header(mail->mail.data_pool, +- block.part, block.hdr); ++ block.part, ++ &mail->data.part_data_limits, ++ block.hdr); + } + } + } +--- a/src/lib-storage/index/index-mail.h ++++ b/src/lib-storage/index/index-mail.h +@@ -2,6 +2,7 @@ + #define INDEX_MAIL_H + + #include "message-size.h" ++#include "message-part-data.h" + #include "mail-cache.h" + #include "mail-storage-private.h" + +@@ -86,6 +87,7 @@ struct index_mail_data { + const char *envelope, *body, *bodystructure, *guid, *filename; + const char *from_envelope, *body_snippet; + struct message_part_envelope *envelope_data; ++ struct message_part_data_limits part_data_limits; + + uint32_t cache_flags; + uint64_t modseq, pvt_modseq; +--- a/src/lib-storage/index/mbox/mbox-sync-parse.c ++++ b/src/lib-storage/index/mbox/mbox-sync-parse.c +@@ -479,6 +479,9 @@ int mbox_sync_parse_next_mail(struct ist + + line_start_pos = 0; + hdr_ctx = message_parse_header_init(input, NULL, 0); ++ /* Rewriting the mbox requires the full raw header bytes, so disable ++ the default per-header block size limit. */ ++ message_parse_header_set_limit(hdr_ctx, SIZE_MAX); + while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) { + if (hdr->eoh) { + ctx->have_eoh = TRUE; +@@ -576,6 +579,8 @@ bool mbox_sync_parse_match_mail(struct m + mbox_md5_ctx = mbox->md5_v.init(); + + hdr_ctx = message_parse_header_init(mbox->mbox_stream, NULL, 0); ++ /* MD5 matching must see the full raw header bytes. */ ++ message_parse_header_set_limit(hdr_ctx, SIZE_MAX); + while ((ret = message_parse_header_next(hdr_ctx, &hdr)) > 0) { + if (hdr->eoh) + break; diff --git a/mail/dovecot/patches/214-CVE-2026-33606.patch b/mail/dovecot/patches/214-CVE-2026-33606.patch new file mode 100644 index 0000000000..97becb09a8 --- /dev/null +++ b/mail/dovecot/patches/214-CVE-2026-33606.patch @@ -0,0 +1,53 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-33606 + +Upstream commits: + dsync: Avoid potentially excessive data stack growth for mailbox attribute sending + https://github.com/dovecot/core/commit/116bab8d7e4acedae628cc88772049bc08a36047 + dsync: Fix escaping mail or attribute value that begins with a "." line + https://github.com/dovecot/core/commit/3f73c11d0ebcfebbda0225699f30513efd8c77f4 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/doveadm/dsync/dsync-ibc-stream.c ++++ b/src/doveadm/dsync/dsync-ibc-stream.c +@@ -1502,12 +1502,12 @@ dsync_ibc_stream_send_mailbox_attribute( + { + struct dsync_ibc_stream *ibc = (struct dsync_ibc_stream *)_ibc; + struct dsync_serializer_encoder *encoder; +- string_t *str = t_str_new(128); + char type[2]; + + if (ibc->minor_version < DSYNC_PROTOCOL_MINOR_HAVE_ATTRIBUTES) + return; + ++ string_t *str = str_new(default_pool, 128); + str_append_c(str, items[ITEM_MAILBOX_ATTRIBUTE].chr); + encoder = dsync_ibc_send_encode_begin(ibc, ITEM_MAILBOX_ATTRIBUTE); + +@@ -1543,11 +1543,12 @@ dsync_ibc_stream_send_mailbox_attribute( + dsync_ibc_stream_send_string(ibc, str); + + if (attr->value_stream != NULL) { +- ibc->value_output_last = '\0'; ++ ibc->value_output_last = '\n'; + ibc->value_output = attr->value_stream; + i_stream_ref(ibc->value_output); + (void)dsync_ibc_stream_send_value_stream(ibc); + } ++ str_free(&str); + } + + static enum dsync_ibc_recv_ret +@@ -1920,7 +1921,7 @@ dsync_ibc_stream_send_mail(struct dsync_ + dsync_ibc_stream_send_string(ibc, str); + + if (mail->input != NULL) { +- ibc->value_output_last = '\0'; ++ ibc->value_output_last = '\n'; + ibc->value_output = mail->input; + i_stream_ref(ibc->value_output); + (void)dsync_ibc_stream_send_value_stream(ibc); diff --git a/mail/dovecot/patches/215-CVE-2026-40015.patch b/mail/dovecot/patches/215-CVE-2026-40015.patch new file mode 100644 index 0000000000..5647dfebb8 --- /dev/null +++ b/mail/dovecot/patches/215-CVE-2026-40015.patch @@ -0,0 +1,144 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40015 + +Upstream commits: + imap-hibernate: Fix out-of-bounds read when parsing DONE command tag + https://github.com/dovecot/core/commit/a880d0bc5600d338cc6fb21e30a16a7257687b64 + imap-hibernate: Use imap-parser API for parsing DONE command + https://github.com/dovecot/core/commit/e767537bfa1bc71b69312691152c3d6bc92f8a50 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/imap-hibernate/imap-client.c ++++ b/src/imap-hibernate/imap-client.c +@@ -20,6 +20,7 @@ + #include "master-service-settings.h" + #include "imap-keepalive.h" + #include "imap-master-connection.h" ++#include "imap-parser.h" + #include "imap-client.h" + + #include +@@ -312,62 +313,78 @@ static void imap_client_move_back(struct + } + + static enum imap_client_input_state +-imap_client_input_parse(const unsigned char *data, size_t size, const char **tag_r) ++imap_client_input_parse_input(struct istream *input, struct imap_parser *parser, ++ const char **tag_r) + { +- const unsigned char *tag_start, *tag_end; +- ++ const unsigned char *rest; ++ size_t rest_size; ++ const char *word, *tag; + enum imap_client_input_state state = IMAP_CLIENT_INPUT_STATE_DONE_LF; ++ int ret; + +- /* skip over DONE[\r]\n */ +- if (i_memcasecmp(data, "DONE", I_MIN(size, 4)) != 0) +- return IMAP_CLIENT_INPUT_STATE_BAD; +- if (size <= 4) ++ /* read DONE */ ++ word = imap_parser_read_word(parser); ++ if (word == NULL) + return IMAP_CLIENT_INPUT_STATE_UNKNOWN; +- data += 4; size -= 4; ++ if (strcasecmp(word, "DONE") != 0) ++ return IMAP_CLIENT_INPUT_STATE_BAD; + +- if (data[0] == '\r') { ++ /* read [\r]\n after DONE */ ++ rest = i_stream_get_data(input, &rest_size); ++ if (rest_size == 0) ++ return IMAP_CLIENT_INPUT_STATE_UNKNOWN; ++ if (rest[0] == '\r') { + state = IMAP_CLIENT_INPUT_STATE_DONE_CRLF; +- data++; size--; ++ i_stream_skip(input, 1); ++ rest = i_stream_get_data(input, &rest_size); ++ if (rest_size == 0) ++ return IMAP_CLIENT_INPUT_STATE_UNKNOWN; + } +- if (size == 0) +- return IMAP_CLIENT_INPUT_STATE_UNKNOWN; +- if (data[0] != '\n') ++ if (rest[0] != '\n') + return IMAP_CLIENT_INPUT_STATE_BAD; +- data++; size--; +- if (size == 0) +- return state; +- +- tag_start = data; +- +- /* skip over tag */ +- while(data[0] != ' ' && +- data[0] != '\r' && +- data[0] != '\t' ) { data++; size--; } ++ i_stream_skip(input, 1); + +- tag_end = data; ++ /* optionally followed by " IDLE[\r]\n" - checking this assumes ++ that the DONE and IDLE are sent in the same IP packet, otherwise ++ we'll unnecessarily recreate the imap process and immediately resume ++ IDLE there. if this becomes an issue we could add a small delay to ++ the imap process creation and wait for the IDLE command during it. */ ++ rest = i_stream_get_data(input, &rest_size); ++ if (rest_size == 0) ++ return state; + +- if (size == 0) ++ ret = imap_parser_read_tag(parser, &tag); ++ if (ret <= 0) + return state; +- if (data[0] != ' ') +- return IMAP_CLIENT_INPUT_STATE_BAD; +- data++; size--; + +- /* skip over IDLE[\r]\n - checking this assumes that the DONE and IDLE +- are sent in the same IP packet, otherwise we'll unnecessarily +- recreate the imap process and immediately resume IDLE there. if this +- becomes an issue we could add a small delay to the imap process +- creation and wait for the IDLE command during it. */ +- if (size <= 4 || i_memcasecmp(data, "IDLE", 4) != 0) ++ /* read IDLE */ ++ word = imap_parser_read_word(parser); ++ if (word == NULL || strcasecmp(word, "IDLE") != 0) + return state; +- data += 4; size -= 4; + +- if (data[0] == '\r') { +- data++; size--; +- } +- if (size == 1 && data[0] == '\n') { +- *tag_r = t_strdup_until(tag_start, tag_end); +- return IMAP_CLIENT_INPUT_STATE_DONEIDLE; ++ /* require [\r]\n and nothing else left */ ++ rest = i_stream_get_data(input, &rest_size); ++ if (rest_size > 0 && rest[0] == '\r') { ++ i_stream_skip(input, 1); ++ rest = i_stream_get_data(input, &rest_size); + } ++ if (rest_size != 1 || rest[0] != '\n') ++ return state; ++ ++ *tag_r = t_strdup(tag); ++ return IMAP_CLIENT_INPUT_STATE_DONEIDLE; ++} ++ ++static enum imap_client_input_state ++imap_client_input_parse(const unsigned char *data, size_t size, const char **tag_r) ++{ ++ struct istream *input = i_stream_create_from_data(data, size); ++ struct imap_parser *parser = ++ imap_parser_create(input, NULL, size, NULL); ++ enum imap_client_input_state state = ++ imap_client_input_parse_input(input, parser, tag_r); ++ imap_parser_unref(&parser); ++ i_stream_unref(&input); + return state; + } + diff --git a/mail/dovecot/patches/216-CVE-2026-42008.patch b/mail/dovecot/patches/216-CVE-2026-42008.patch new file mode 100644 index 0000000000..ff7452c247 --- /dev/null +++ b/mail/dovecot/patches/216-CVE-2026-42008.patch @@ -0,0 +1,23 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Markus Valentin +Subject: [PATCH] Fix CVE-2026-42008 + +Upstream commits: + auth: Fix prefixing forward_fields without a value from client + https://github.com/dovecot/core/commit/ca55238f3716da3f1df945616c12690e1919c10a + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/auth/auth-fields.c ++++ b/src/auth/auth-fields.c +@@ -124,7 +124,7 @@ void auth_fields_import_prefixed(struct + for (; *arg != NULL; arg++) { + value = strchr(*arg, '='); + if (value == NULL) { +- key = *arg; ++ key = *prefix != '\0' ? t_strconcat(prefix, *arg, NULL) : *arg; + value = NULL; + } else { + key = t_strdup_until(*arg, value++); diff --git a/mail/dovecot/patches/217-CVE-2026-40203.patch b/mail/dovecot/patches/217-CVE-2026-40203.patch new file mode 100644 index 0000000000..bd14a24f71 --- /dev/null +++ b/mail/dovecot/patches/217-CVE-2026-40203.patch @@ -0,0 +1,149 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40203 + +Upstream commits: + lib-compression: Add o_stream_deflate_reset_dict() + https://github.com/dovecot/core/commit/370f4d49f1a3c62a7b7831ed9218bbb9755740ed + imap: Reset DEFLATE dictionary after every tagged reply + https://github.com/dovecot/core/commit/38350a7c284b8de7e02ca60e173abdb76848a216 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +Adjusted for this version: + - imap-zlib-plugin.c in 2.3.21 includes only compression.h, so + ostream-zlib.h is included explicitly, as upstream commit 38350a7c28 + does in imap-client.c. + +--- a/src/lib-compression/ostream-zlib.c ++++ b/src/lib-compression/ostream-zlib.c +@@ -25,6 +25,7 @@ struct zlib_ostream { + + bool gz:1; + bool flushed:1; ++ bool pending_dict_reset:1; + }; + + int compression_get_min_level_gz(void) +@@ -212,8 +213,14 @@ o_stream_zlib_send_flush(struct zlib_ost + if ((ret = o_stream_zlib_send_outbuf(zstream)) <= 0) + return ret; + +- flush = final ? Z_FINISH : +- (!zstream->gz ? Z_SYNC_FLUSH : Z_NO_FLUSH); ++ if (final) ++ flush = Z_FINISH; ++ else if (zstream->gz) ++ flush = Z_NO_FLUSH; ++ else if (zstream->pending_dict_reset) ++ flush = Z_FULL_FLUSH; ++ else ++ flush = Z_SYNC_FLUSH; + + i_assert(zstream->outbuf_used == 0); + do { +@@ -243,6 +250,10 @@ o_stream_zlib_send_flush(struct zlib_ost + } + } while (zs->avail_out != sizeof(zstream->outbuf)); + ++ /* Z_FULL_FLUSH completes here; clear the request so subsequent flushes ++ use the normal Z_SYNC_FLUSH again. */ ++ zstream->pending_dict_reset = FALSE; ++ + if (final) { + if (o_stream_zlib_send_gz_trailer(zstream) < 0) + return -1; +@@ -389,4 +400,27 @@ struct ostream *o_stream_create_deflate( + { + return o_stream_create_zlib(output, level, FALSE); + } ++ ++void o_stream_deflate_reset_dict(struct ostream *_output) ++{ ++ struct ostream_private *stream = _output->real_stream; ++ ++ /* Traverse the ostream parent chain to find the deflate ostream. ++ The caller may pass a rawlog-wrapped stream or the deflate stream ++ itself; either way we find it by its sendv function pointer. */ ++ while (stream != NULL) { ++ if (stream->sendv == o_stream_zlib_sendv) { ++ struct zlib_ostream *zstream = ++ container_of(stream, struct zlib_ostream, ostream); ++ i_assert(!zstream->gz); ++ zstream->pending_dict_reset = TRUE; ++ o_stream_set_flush_pending( ++ &zstream->ostream.ostream, TRUE); ++ return; ++ } ++ stream = (stream->parent != NULL) ? ++ stream->parent->real_stream : NULL; ++ } ++ /* No deflate ostream found in the chain – nothing to reset. */ ++} + #endif +--- a/src/lib-compression/ostream-zlib.h ++++ b/src/lib-compression/ostream-zlib.h +@@ -23,4 +23,11 @@ int compression_get_min_level_zstd(void) + int compression_get_default_level_zstd(void); + int compression_get_max_level_zstd(void); + ++/* Reset the deflate compression dictionary so that subsequent compressed ++ output cannot reference data from before this call. Pass any ostream in ++ the chain (e.g. a rawlog wrapper); the function locates the deflate stream ++ internally. Safe to call when compression is not active – it is a no-op ++ in that case. */ ++void o_stream_deflate_reset_dict(struct ostream *output); ++ + #endif +--- a/src/plugins/imap-zlib/imap-zlib-plugin.c ++++ b/src/plugins/imap-zlib/imap-zlib-plugin.c +@@ -7,6 +7,7 @@ + #include "module-context.h" + #include "imap-commands.h" + #include "compression.h" ++#include "ostream-zlib.h" + #include "imap-zlib-plugin.h" + + +@@ -20,6 +21,8 @@ struct zlib_client { + + int (*next_state_export)(struct client *client, bool internal, + buffer_t *dest, const char **error_r); ++ void (*next_send_tagline)(struct client_command_context *cmd, ++ const char *data); + const struct compression_handler *handler; + }; + +@@ -144,6 +147,21 @@ imap_zlib_state_export(struct client *cl + return zclient->next_state_export(client, internal, dest, error_r); + } + ++static void ++imap_zlib_send_tagline(struct client_command_context *cmd, const char *data) ++{ ++ struct client *client = cmd->client; ++ struct zlib_client *zclient = IMAP_ZLIB_IMAP_CONTEXT(client); ++ ++ /* Send original tagline. */ ++ zclient->next_send_tagline(cmd, data); ++ ++ /* Reset the DEFLATE compression dictionary after every tagged reply so ++ that cross-command compression correlation attacks (CRIME-style) are ++ not possible. */ ++ o_stream_deflate_reset_dict(client->output); ++} ++ + static void imap_zlib_client_created(struct client **clientp) + { + struct client *client = *clientp; +@@ -157,6 +175,8 @@ static void imap_zlib_client_created(str + + zclient->next_state_export = (*clientp)->v.state_export; + (*clientp)->v.state_export = imap_zlib_state_export; ++ zclient->next_send_tagline = (*clientp)->v.send_tagline; ++ (*clientp)->v.send_tagline = imap_zlib_send_tagline; + + client_add_capability(*clientp, "COMPRESS=DEFLATE"); + } diff --git a/mail/dovecot/patches/218-CVE-2026-40017.patch b/mail/dovecot/patches/218-CVE-2026-40017.patch new file mode 100644 index 0000000000..6841e0e33f --- /dev/null +++ b/mail/dovecot/patches/218-CVE-2026-40017.patch @@ -0,0 +1,1133 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40017 + +Upstream commits: + lib: Add XXH64 hash implementation + https://github.com/dovecot/core/commit/a308c4bb8d7a3ba0a2c6a7bcd1456d6730261f60 + lib: Replace str_hash/strcase_hash with xxh64 + https://github.com/dovecot/core/commit/7de0c5f0f5f386cbc11bfb30f422e575d80ed150 + lib: Add str_stable_hash() + https://github.com/dovecot/core/commit/356468362b39241a5f35f9947fd2679cd09b1b22 + lib: Key str_hash/strcase_hash with a random seed to prevent HashDoS + https://github.com/dovecot/core/commit/9896a67986a405c33c2a7fcda030d451df689503 + lib-index: mail-index-strmap - Fix OOB read from truncated record size + https://github.com/dovecot/core/commit/8d4ff69d4a40d1073946823cd0f7c1d937f51aee + lib-index: Rename crc32 variables/parameters to hash in strmap + https://github.com/dovecot/core/commit/9c50e0f64f35485f27208732cc8c694add5fc133 + lib-index: Add keyed xxh64 strmap format v2, gated by config version + https://github.com/dovecot/core/commit/d34ac20f89bef60f91cd898e431018ee57061125 + lib-storage: thread - Avoid excessive data stack growth with many References msgids + https://github.com/dovecot/core/commit/0ad27eb7e68e9999f7979d38b5d2d87c18bc9219 + doveadm: Fix ubsan unsigned integer overflow error + https://github.com/dovecot/core/commit/ac5ee9f37a6afadf23722a7ed55932a6afcf6ffe + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/doveadm/doveadm-who.c ++++ b/src/doveadm/doveadm-who.c +@@ -39,10 +39,10 @@ static unsigned int who_user_hash(const + unsigned int hash = str_hash(user->service); + + if (user->username[0] != '\0') +- hash += str_hash(user->username); ++ hash ^= str_hash(user->username); + else { + who_user_ip(user, &ip); +- hash += net_ip_hash(&ip); ++ hash ^= net_ip_hash(&ip); + } + return hash; + } +--- a/src/lib-index/mail-index-strmap.c ++++ b/src/lib-index/mail-index-strmap.c +@@ -8,6 +8,8 @@ + #include "file-lock.h" + #include "file-dotlock.h" + #include "crc32.h" ++#include "randgen.h" ++#include "xxh64.h" + #include "safe-mkstemp.h" + #include "str.h" + #include "mail-index-private.h" +@@ -24,6 +26,12 @@ struct mail_index_strmap { + struct file_lock *file_lock; + struct dotlock *dotlock; + struct dotlock_settings dotlock_settings; ++ ++ /* If TRUE, new files are created in v2 format (xxh64-keyed hashes). ++ If FALSE, new files are created in v1 format (crc32). Existing ++ files of either version are always read; on rebuild they are ++ recreated in this preferred format. */ ++ bool enable_xxh64; + }; + + struct mail_index_strmap_view { +@@ -31,9 +39,17 @@ struct mail_index_strmap_view { + struct mail_index_view *view; + + ARRAY_TYPE(mail_index_strmap_rec) recs; +- ARRAY(uint32_t) recs_crc32; ++ ARRAY(uint32_t) recs_hash; + struct hash2_table *hash; + ++ /* On-disk format version that view's hash values are computed ++ against. v1 = crc32_str_nonzero, v2 = keyed xxh64. Set from the ++ file header when opening an existing file; otherwise from ++ strmap->enable_xxh64. */ ++ uint8_t format_version; ++ /* Per-file random IV mixed into the xxh64 hash. Unused for v1. */ ++ uint64_t hash_iv; ++ + mail_index_strmap_key_cmp_t *key_compare; + mail_index_strmap_rec_cmp_t *rec_compare; + mail_index_strmap_remap_t *remap_cb; +@@ -74,7 +90,7 @@ struct mail_index_strmap_view_sync { + + struct mail_index_strmap_hash_key { + const char *str; +- uint32_t crc32; ++ uint32_t hash; + }; + + /* number of bytes required to store one string idx */ +@@ -95,7 +111,8 @@ static const struct dotlock_settings def + }; + + struct mail_index_strmap * +-mail_index_strmap_init(struct mail_index *index, const char *suffix) ++mail_index_strmap_init(struct mail_index *index, const char *suffix, ++ bool enable_xxh64) + { + struct mail_index_strmap *strmap; + +@@ -105,6 +122,7 @@ mail_index_strmap_init(struct mail_index + strmap->index = index; + strmap->path = i_strconcat(index->filepath, suffix, NULL); + strmap->fd = -1; ++ strmap->enable_xxh64 = enable_xxh64; + + strmap->dotlock_settings = default_dotlock_settings; + strmap->dotlock_settings.use_excl_lock = +@@ -116,7 +134,7 @@ mail_index_strmap_init(struct mail_index + + static bool + mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx, +- uint32_t *crc32_r); ++ uint32_t *hash_r); + + static void + mail_index_strmap_set_syscall_error(struct mail_index_strmap *strmap, +@@ -165,7 +183,7 @@ static unsigned int mail_index_strmap_ha + { + const struct mail_index_strmap_hash_key *key = _key; + +- return key->crc32; ++ return key->hash; + } + + static bool +@@ -200,7 +218,10 @@ mail_index_strmap_view_open(struct mail_ + view->next_str_idx = 1; + + i_array_init(&view->recs, 64); +- i_array_init(&view->recs_crc32, 64); ++ i_array_init(&view->recs_hash, 64); ++ view->format_version = strmap->enable_xxh64 ? ++ MAIL_INDEX_STRMAP_VERSION_V2 : MAIL_INDEX_STRMAP_VERSION_V1; ++ random_fill(&view->hash_iv, sizeof(view->hash_iv)); + view->hash = hash2_create(0, sizeof(struct mail_index_strmap_rec), + mail_index_strmap_hash_key, + mail_index_strmap_hash_cmp, view); +@@ -215,7 +236,7 @@ void mail_index_strmap_view_close(struct + + *_view = NULL; + array_free(&view->recs); +- array_free(&view->recs_crc32); ++ array_free(&view->recs_hash); + hash2_destroy(&view->hash); + i_free(view); + } +@@ -229,7 +250,7 @@ static void mail_index_strmap_view_reset + { + view->remap_cb(NULL, 0, 0, view->cb_context); + array_clear(&view->recs); +- array_clear(&view->recs_crc32); ++ array_clear(&view->recs_hash); + hash2_clear(view->hash); + + view->last_added_uid = 0; +@@ -253,7 +274,7 @@ static int mail_index_strmap_open(struct + const struct mail_index_header *idx_hdr; + struct mail_index_strmap_header hdr; + const unsigned char *data; +- size_t size; ++ size_t size, hdr_size; + int ret; + + i_assert(strmap->fd == -1); +@@ -266,7 +287,12 @@ static int mail_index_strmap_open(struct + return -1; + } + strmap->input = i_stream_create_fd(strmap->fd, SIZE_MAX); +- ret = i_stream_read_bytes(strmap->input, &data, &size, sizeof(hdr)); ++ ++ /* Read the smaller v1 header first; bytes 0..7 have identical ++ layout in both formats so we can decide based on the version ++ byte before reading the v2 tail. */ ++ ret = i_stream_read_bytes(strmap->input, &data, &size, ++ MAIL_INDEX_STRMAP_HEADER_V1_SIZE); + if (ret <= 0) { + if (ret < 0) { + mail_index_strmap_set_syscall_error(strmap, "read()"); +@@ -277,23 +303,55 @@ static int mail_index_strmap_open(struct + } + return ret; + } +- memcpy(&hdr, data, sizeof(hdr)); ++ ++ i_zero(&hdr); ++ hdr_size = data[0] == MAIL_INDEX_STRMAP_VERSION_V2 ? ++ MAIL_INDEX_STRMAP_HEADER_V2_SIZE : ++ MAIL_INDEX_STRMAP_HEADER_V1_SIZE; ++ if (hdr_size > MAIL_INDEX_STRMAP_HEADER_V1_SIZE) { ++ ret = i_stream_read_bytes(strmap->input, &data, &size, hdr_size); ++ if (ret <= 0) { ++ if (ret < 0) { ++ mail_index_strmap_set_syscall_error(strmap, "read()"); ++ mail_index_strmap_close(strmap); ++ } else { ++ mail_index_strmap_view_set_corrupted(view); ++ } ++ return ret; ++ } ++ } ++ memcpy(&hdr, data, hdr_size); + + idx_hdr = mail_index_get_header(view->view); +- if (hdr.version != MAIL_INDEX_STRMAP_VERSION || +- hdr.uid_validity != idx_hdr->uid_validity) { ++ uint8_t compat_flags = 0; ++#ifndef WORDS_BIGENDIAN ++ if (hdr.version >= MAIL_INDEX_STRMAP_VERSION_V2) ++ compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN; ++#endif ++ if ((hdr.version != MAIL_INDEX_STRMAP_VERSION_V1 && ++ hdr.version != MAIL_INDEX_STRMAP_VERSION_V2) || ++ hdr.compat_flags != compat_flags || ++ hdr.uid_validity != idx_hdr->uid_validity || ++ (strmap->enable_xxh64 && ++ hdr.version < MAIL_INDEX_STRMAP_VERSION_V2)) { + /* need to rebuild. if we already had something in the strmap, +- we can keep it. */ ++ we can keep it. The enable_xxh64 case forces a v1 file to ++ be discarded so the next write creates a v2 file - we never ++ stay on v1 once the dovecot_storage_version threshold has ++ been reached. */ + i_unlink(strmap->path); + mail_index_strmap_close(strmap); + return 0; + } ++ view->format_version = hdr.version; ++ view->hash_iv = hdr.version >= MAIL_INDEX_STRMAP_VERSION_V2 ? ++ hdr.hash_iv : 0; + + /* we'll read the entire file from the beginning */ + view->last_added_uid = 0; + view->last_read_uid = 0; + view->total_ref_count = 0; +- view->last_read_block_offset = sizeof(struct mail_index_strmap_header); ++ view->last_read_block_offset = hdr_size; + view->next_str_idx = 1; + + mail_index_strmap_view_reset(view); +@@ -413,13 +471,13 @@ mail_index_strmap_uid_exists(struct mail + + static int + mail_index_strmap_read_rec_first(struct mail_index_strmap_read_context *ctx, +- uint32_t *crc32_r) ++ uint32_t *hash_r) + { + size_t size; + uint32_t n, i, count, str_idx; + int ret; + +- /* *count *count ++ /* *count *count + where + n = 0 -> count=1 (only Message-ID:) + n = 1 -> count=2 (Message-ID: + In-Reply-To:) +@@ -428,9 +486,12 @@ mail_index_strmap_read_rec_first(struct + if (mail_index_strmap_read_packed(ctx, &n) <= 0) + return -1; + count = n < 2 ? n + 1 : n; ++ /* check that rec_size fits */ ++ if (UINT_MAX / (sizeof(ctx->rec.str_idx) + sizeof(*hash_r)) < count) ++ return -1; + ctx->view->total_ref_count += count; + +- ctx->rec_size = count * (sizeof(ctx->rec.str_idx) + sizeof(*crc32_r)); ++ ctx->rec_size = count * (sizeof(ctx->rec.str_idx) + sizeof(*hash_r)); + ret = mail_index_strmap_uid_exists(ctx, ctx->rec.uid); + if (ret < 0) + return -1; +@@ -454,10 +515,10 @@ mail_index_strmap_read_rec_first(struct + /* everything exists. save it. FIXME: these ref_index values + are thread index specific, perhaps something more generic + should be used some day */ +- ctx->end = ctx->data + count * sizeof(*crc32_r); ++ ctx->end = ctx->data + count * sizeof(*hash_r); + + ctx->next_ref_index = 0; +- if (!mail_index_strmap_read_rec_next(ctx, crc32_r)) ++ if (!mail_index_strmap_read_rec_next(ctx, hash_r)) + i_unreached(); + ctx->next_ref_index = n == 1 ? 1 : 2; + return 1; +@@ -465,7 +526,7 @@ mail_index_strmap_read_rec_first(struct + + static bool + mail_index_strmap_read_rec_next(struct mail_index_strmap_read_context *ctx, +- uint32_t *crc32_r) ++ uint32_t *hash_r) + { + if (ctx->data == ctx->end) { + i_stream_skip(ctx->view->strmap->input, ctx->rec_size); +@@ -478,7 +539,7 @@ mail_index_strmap_read_rec_next(struct m + + /* read the record contents */ + memcpy(&ctx->rec.str_idx, ctx->str_idx_base, sizeof(ctx->rec.str_idx)); +- memcpy(crc32_r, ctx->data, sizeof(*crc32_r)); ++ memcpy(hash_r, ctx->data, sizeof(*hash_r)); + + ctx->rec.ref_index = ctx->next_ref_index++; + +@@ -486,7 +547,7 @@ mail_index_strmap_read_rec_next(struct m + ctx->highest_str_idx = ctx->rec.str_idx; + + /* get to the next record */ +- ctx->data += sizeof(*crc32_r); ++ ctx->data += sizeof(*hash_r); + ctx->str_idx_base += sizeof(ctx->rec.str_idx); + return TRUE; + } +@@ -547,12 +608,12 @@ strmap_read_block_init(struct mail_index + + static int + strmap_read_block_next(struct mail_index_strmap_read_context *ctx, +- uint32_t *crc32_r) ++ uint32_t *hash_r) + { + uint32_t uid_diff; + int ret; + +- if (mail_index_strmap_read_rec_next(ctx, crc32_r)) ++ if (mail_index_strmap_read_rec_next(ctx, hash_r)) + return 1; + + /* get next UID */ +@@ -565,7 +626,7 @@ strmap_read_block_next(struct mail_index + return -1; + + ctx->rec.uid += uid_diff; +- ret = mail_index_strmap_read_rec_first(ctx, crc32_r); ++ ret = mail_index_strmap_read_rec_first(ctx, hash_r); + } while (ret == 0); + return ret; + } +@@ -635,12 +696,12 @@ strmap_view_sync_handle_conflict(struct + + static int + strmap_view_sync_block_check_conflicts(struct mail_index_strmap_read_context *ctx, +- uint32_t crc32) ++ uint32_t hash) + { + struct mail_index_strmap_rec *hash_rec; + struct hash2_iter iter; + +- if (crc32 == 0) { ++ if (hash == 0) { + /* unique string - there are no conflicts */ + return 0; + } +@@ -657,9 +718,9 @@ strmap_view_sync_block_check_conflicts(s + strmap index until X has been expunged. */ + i_zero(&iter); + while ((hash_rec = hash2_iterate(ctx->view->hash, +- crc32, &iter)) != NULL && ++ hash, &iter)) != NULL && + hash_rec->str_idx != ctx->rec.str_idx) { +- /* CRC32 matches, but string index doesn't */ ++ /* hash matches, but string index doesn't */ + if (!strmap_view_sync_handle_conflict(ctx, hash_rec, &iter)) { + ctx->lost_expunged_uid = hash_rec->uid; + return -1; +@@ -672,10 +733,10 @@ static int + mail_index_strmap_view_sync_block(struct mail_index_strmap_read_context *ctx) + { + struct mail_index_strmap_rec *hash_rec; +- uint32_t crc32, prev_uid = 0; ++ uint32_t hash, prev_uid = 0; + int ret; + +- while ((ret = strmap_read_block_next(ctx, &crc32)) > 0) { ++ while ((ret = strmap_read_block_next(ctx, &hash)) > 0) { + if (ctx->rec.uid <= ctx->view->last_added_uid) { + if (ctx->rec.uid < ctx->view->last_added_uid || + prev_uid != ctx->rec.uid) { +@@ -685,7 +746,7 @@ mail_index_strmap_view_sync_block(struct + } + prev_uid = ctx->rec.uid; + +- if (strmap_view_sync_block_check_conflicts(ctx, crc32) < 0) { ++ if (strmap_view_sync_block_check_conflicts(ctx, hash) < 0) { + ret = -1; + break; + } +@@ -693,10 +754,10 @@ mail_index_strmap_view_sync_block(struct + + /* add the record to records array */ + array_push_back(&ctx->view->recs, &ctx->rec); +- array_push_back(&ctx->view->recs_crc32, &crc32); ++ array_push_back(&ctx->view->recs_hash, &hash); + + /* add a separate copy of the record to hash */ +- hash_rec = hash2_insert_hash(ctx->view->hash, crc32); ++ hash_rec = hash2_insert_hash(ctx->view->hash, hash); + memcpy(hash_rec, &ctx->rec, sizeof(*hash_rec)); + } + return strmap_read_block_deinit(ctx, ret, TRUE); +@@ -750,6 +811,17 @@ static inline uint32_t crc32_str_nonzero + return value == 0 ? 1 : value; + } + ++static inline uint32_t ++strmap_hash_str(const struct mail_index_strmap_view *view, const char *str) ++{ ++ if (view->format_version < MAIL_INDEX_STRMAP_VERSION_V2) ++ return crc32_str_nonzero(str); ++ ++ uint32_t value = xxh64_to_32(xxh64_data(str, strlen(str), view->hash_iv)); ++ /* 0 is reserved as a sentinel meaning "unique / no hash stored" */ ++ return value == 0 ? 1 : value; ++} ++ + void mail_index_strmap_view_sync_add(struct mail_index_strmap_view_sync *sync, + uint32_t uid, uint32_t ref_index, + const char *key) +@@ -764,7 +836,7 @@ void mail_index_strmap_view_sync_add(str + ref_index > view->last_ref_index)); + + hash_key.str = key; +- hash_key.crc32 = crc32_str_nonzero(key); ++ hash_key.hash = strmap_hash_str(view, key); + + old_rec = hash2_lookup(view->hash, &hash_key); + if (old_rec != NULL) { +@@ -781,7 +853,7 @@ void mail_index_strmap_view_sync_add(str + rec->ref_index = ref_index; + rec->str_idx = str_idx; + array_push_back(&view->recs, rec); +- array_push_back(&view->recs_crc32, &hash_key.crc32); ++ array_push_back(&view->recs_hash, &hash_key.hash); + + view->last_added_uid = uid; + view->last_ref_index = ref_index; +@@ -802,7 +874,7 @@ void mail_index_strmap_view_sync_add_uni + rec.ref_index = ref_index; + rec.str_idx = view->next_str_idx++; + array_push_back(&view->recs, &rec); +- array_append_zero(&view->recs_crc32); ++ array_append_zero(&view->recs_hash); + + view->last_added_uid = uid; + view->last_ref_index = ref_index; +@@ -820,7 +892,7 @@ static void mail_index_strmap_view_renum + { + struct mail_index_strmap_read_context ctx; + struct mail_index_strmap_rec *recs, *hash_rec; +- uint32_t prev_uid, str_idx, *recs_crc32, *renumber_map; ++ uint32_t prev_uid, str_idx, *recs_hash, *renumber_map; + unsigned int i, dest, count, count2; + int ret; + +@@ -833,7 +905,7 @@ static void mail_index_strmap_view_renum + renumber_map = i_new(uint32_t, view->next_str_idx); + str_idx = 0; prev_uid = 0; + recs = array_get_modifiable(&view->recs, &count); +- recs_crc32 = array_get_modifiable(&view->recs_crc32, &count2); ++ recs_hash = array_get_modifiable(&view->recs_hash, &count2); + i_assert(count == count2); + + for (i = dest = 0; i < count; ) { +@@ -856,13 +928,13 @@ static void mail_index_strmap_view_renum + renumber_map[recs[i].str_idx] = ++str_idx; + if (i != dest) { + recs[dest] = recs[i]; +- recs_crc32[dest] = recs_crc32[i]; ++ recs_hash[dest] = recs_hash[i]; + } + i++; dest++; + } + i_assert(renumber_map[0] == 0); + array_delete(&view->recs, dest, i-dest); +- array_delete(&view->recs_crc32, dest, i-dest); ++ array_delete(&view->recs_hash, dest, i-dest); + mail_index_strmap_zero_terminate(view); + + /* notify caller of the renumbering */ +@@ -875,7 +947,7 @@ static void mail_index_strmap_view_renum + hash2_clear(view->hash); + for (i = 0; i < count; i++) { + recs[i].str_idx = renumber_map[recs[i].str_idx]; +- hash_rec = hash2_insert_hash(view->hash, recs_crc32[i]); ++ hash_rec = hash2_insert_hash(view->hash, recs_hash[i]); + memcpy(hash_rec, &recs[i], sizeof(*hash_rec)); + } + +@@ -889,7 +961,7 @@ static void mail_index_strmap_write_bloc + unsigned int i, uint32_t base_uid) + { + const struct mail_index_strmap_rec *recs; +- const uint32_t *crc32; ++ const uint32_t *hashes; + unsigned int j, n, count, count2, uid_rec_count; + uint32_t block_size; + uint8_t *p, packed[MAIL_INDEX_PACK_MAX_SIZE*2]; +@@ -902,7 +974,7 @@ static void mail_index_strmap_write_bloc + + /* write records */ + recs = array_get(&view->recs, &count); +- crc32 = array_get(&view->recs_crc32, &count2); ++ hashes = array_get(&view->recs_hash, &count2); + i_assert(count == count2); + while (i < count) { + /* @UNSAFE: */ +@@ -919,7 +991,7 @@ static void mail_index_strmap_write_bloc + } + view->total_ref_count += uid_rec_count; + +- /* *count *count - ++ /* *count *count - + FIXME: thread index specific code */ + i_assert(recs[i].ref_index == 0); + if (uid_rec_count == 1) { +@@ -938,7 +1010,7 @@ static void mail_index_strmap_write_bloc + mail_index_pack_num(&p, n); + o_stream_nsend(output, packed, p-packed); + for (j = 0; j < uid_rec_count; j++) +- o_stream_nsend(output, &crc32[i+j], sizeof(crc32[i+j])); ++ o_stream_nsend(output, &hashes[i+j], sizeof(hashes[i+j])); + for (j = 0; j < uid_rec_count; j++) { + i_assert(j < 2 || recs[i+j].ref_index == j+1); + o_stream_nsend(output, &recs[i+j].str_idx, +@@ -971,14 +1043,29 @@ mail_index_strmap_recreate_write(struct + { + const struct mail_index_header *idx_hdr; + struct mail_index_strmap_header hdr; ++ size_t hdr_size; + + idx_hdr = mail_index_get_header(view->view); + ++ /* view->format_version was set either at view_open() time (from the ++ strmap-wide enable_xxh64 preference for fresh files) or in ++ mail_index_strmap_open() from the existing file's header. Reuse ++ it as-is so renumber recreates preserve the file's format. */ ++ + /* write header */ + i_zero(&hdr); +- hdr.version = MAIL_INDEX_STRMAP_VERSION; ++ hdr.version = view->format_version; + hdr.uid_validity = idx_hdr->uid_validity; +- o_stream_nsend(output, &hdr, sizeof(hdr)); ++ if (view->format_version >= MAIL_INDEX_STRMAP_VERSION_V2) { ++#ifndef WORDS_BIGENDIAN ++ hdr.compat_flags |= MAIL_INDEX_COMPAT_LITTLE_ENDIAN; ++#endif ++ hdr.hash_iv = view->hash_iv; ++ hdr_size = MAIL_INDEX_STRMAP_HEADER_V2_SIZE; ++ } else { ++ hdr_size = MAIL_INDEX_STRMAP_HEADER_V1_SIZE; ++ } ++ o_stream_nsend(output, &hdr, hdr_size); + + view->total_ref_count = 0; + mail_index_strmap_write_block(view, output, 0, 1); +@@ -1095,7 +1182,7 @@ mail_index_strmap_write_append(struct ma + const struct mail_index_strmap_rec *old_recs; + unsigned int i, old_count; + struct ostream *output; +- uint32_t crc32, next_uid; ++ uint32_t hash, next_uid; + bool full_block; + int ret; + +@@ -1134,7 +1221,7 @@ mail_index_strmap_write_append(struct ma + full_block = TRUE; ret = 0; + while (i < old_count && + (ret = strmap_read_block_init(view, &ctx)) > 0) { +- while ((ret = strmap_read_block_next(&ctx, &crc32)) > 0) { ++ while ((ret = strmap_read_block_next(&ctx, &hash)) > 0) { + if (ctx.rec.uid != old_recs[i].uid || + ctx.rec.str_idx != old_recs[i].str_idx) { + /* mismatch */ +--- a/src/lib-index/mail-index-strmap.h ++++ b/src/lib-index/mail-index-strmap.h +@@ -7,12 +7,22 @@ struct mail_index; + struct mail_index_view; + + struct mail_index_strmap_header { +-#define MAIL_INDEX_STRMAP_VERSION 1 ++/* On-disk format version. The header struct below describes version 2; ++ version 1 files use the same first 8 bytes (version + 3 unused + uid_validity) ++ without the trailing compat_flags / unused / hash_iv fields. */ ++#define MAIL_INDEX_STRMAP_VERSION_V1 1 ++#define MAIL_INDEX_STRMAP_VERSION_V2 2 + uint8_t version; +- uint8_t unused[3]; ++ uint8_t compat_flags; /* enum mail_index_header_compat_flags, v2+ */ ++ uint8_t unused[2]; + + uint32_t uid_validity; ++ ++ /* v2+ fields - not present on disk for v1 files. */ ++ uint64_t hash_iv; /* per-file random IV mixed into the xxh64 hash */ + }; ++#define MAIL_INDEX_STRMAP_HEADER_V1_SIZE 8 ++#define MAIL_INDEX_STRMAP_HEADER_V2_SIZE sizeof(struct mail_index_strmap_header) + + struct mail_index_strmap_rec { + uint32_t uid; +@@ -40,7 +50,8 @@ typedef void mail_index_strmap_remap_t(c + unsigned int new_count, void *context); + + struct mail_index_strmap * +-mail_index_strmap_init(struct mail_index *index, const char *suffix); ++mail_index_strmap_init(struct mail_index *index, const char *suffix, ++ bool enable_xxh64); + void mail_index_strmap_deinit(struct mail_index_strmap **strmap); + + /* Returns strmap records and hash that can be used for read-only access. +--- a/src/lib-storage/index/index-thread.c ++++ b/src/lib-storage/index/index-thread.c +@@ -93,9 +93,11 @@ mail_strmap_rec_get_msgid(struct mail_th + + /* get the nth message-id */ + msgid = message_id_get_next(&msgids); +- if (msgid != NULL) { +- for (; n > 0; n--) ++ if (msgid != NULL && n > 0) { ++ for (; n > 1; n--) T_BEGIN { + msgid = message_id_get_next(&msgids); ++ } T_END; ++ msgid = message_id_get_next(&msgids); + } + + if (msgid == NULL) { +@@ -266,12 +268,18 @@ mail_thread_map_add_mail(struct mail_thr + msgid = message_id_get_next(&references); + if (msgid != NULL) { + ref_index = MAIL_THREAD_NODE_REF_REFERENCES1; ++ mail_index_strmap_view_sync_add(ctx->strmap_sync, ++ mail->uid, ref_index, msgid); + do { +- mail_index_strmap_view_sync_add(ctx->strmap_sync, +- mail->uid, +- ref_index, msgid); +- ref_index++; +- msgid = message_id_get_next(&references); ++ T_BEGIN { ++ ref_index++; ++ msgid = message_id_get_next(&references); ++ if (msgid != NULL) { ++ mail_index_strmap_view_sync_add( ++ ctx->strmap_sync, mail->uid, ++ ref_index, msgid); ++ } ++ } T_END; + } while (msgid != NULL); + } else { + /* no References:, use In-Reply-To: */ +@@ -660,7 +668,8 @@ void index_thread_mailbox_opened(struct + box->v.free = mail_thread_mailbox_free; + + tbox->strmap = mail_index_strmap_init(box->index, +- MAIL_THREAD_INDEX_SUFFIX); ++ MAIL_THREAD_INDEX_SUFFIX, ++ TRUE); + tbox->next_msgid_idx = 1; + + tbox->cache = i_new(struct mail_thread_cache, 1); +--- a/src/lib/Makefile.am ++++ b/src/lib/Makefile.am +@@ -176,6 +176,7 @@ liblib_la_SOURCES = \ + sha1.c \ + sha2.c \ + sha3.c \ ++ xxh64.c \ + sleep.c \ + sort.c \ + stats-dist.c \ +@@ -335,6 +336,7 @@ headers = \ + sha1.h \ + sha2.h \ + sha3.h \ ++ xxh64.h \ + sleep.h \ + sort.h \ + stats-dist.h \ +--- a/src/lib/hash-method.c ++++ b/src/lib/hash-method.c +@@ -6,6 +6,7 @@ + #include "sha1.h" + #include "sha2.h" + #include "sha3.h" ++#include "xxh64.h" + #include "hash-method.h" + + const struct hash_method *hash_method_lookup(const char *name) +@@ -93,6 +94,7 @@ const struct hash_method *hash_methods[] + &hash_method_sha512, + &hash_method_sha3_256, + &hash_method_sha3_512, ++ &hash_method_xxh64, + &hash_method_size, + NULL + }; +--- a/src/lib/hash.c ++++ b/src/lib/hash.c +@@ -5,6 +5,8 @@ + #include "lib.h" + #include "hash.h" + #include "primes.h" ++#include "randgen.h" ++#include "xxh64.h" + + #include + +@@ -58,6 +60,8 @@ enum hash_table_operation{ + HASH_TABLE_OP_RESIZE + }; + ++uint64_t hash_iv; ++ + static bool hash_table_resize(struct hash_table *table, bool grow); + + void hash_table_create(struct hash_table **table_r, pool_t node_pool, +@@ -519,42 +523,32 @@ void hash_table_copy(struct hash_table * + hash_table_thaw(dest); + } + +-/* a char* hash function from ASU -- from glib */ +-unsigned int ATTR_NO_SANITIZE_INTEGER +-str_hash(const char *p) ++void hash_init(void) + { +- const unsigned char *s = (const unsigned char *)p; +- unsigned int g, h = 0; ++ random_fill(&hash_iv, sizeof(hash_iv)); ++} + +- while (*s != '\0') { +- h = (h << 4) + *s; +- if ((g = h & 0xf0000000UL) != 0) { +- h = h ^ (g >> 24); +- h = h ^ g; +- } +- s++; +- } ++unsigned int str_hash(const char *p) ++{ ++ return xxh64_to_32(xxh64_data(p, strlen(p), hash_iv)); ++} + +- return h; ++unsigned int str_stable_hash(const char *p) ++{ ++ return xxh64_to_32(xxh64_data(p, strlen(p), 0)); + } + +-/* a char* hash function from ASU -- from glib */ +-unsigned int ATTR_NO_SANITIZE_INTEGER +-strcase_hash(const char *p) ++unsigned int strcase_hash(const char *p) + { +- const unsigned char *s = (const unsigned char *)p; +- unsigned int g, h = 0; ++ struct xxh64_context ctx; ++ unsigned char c; + +- while (*s != '\0') { +- h = (h << 4) + i_toupper(*s); +- if ((g = h & 0xf0000000UL) != 0) { +- h = h ^ (g >> 24); +- h = h ^ g; +- } +- s++; ++ xxh64_init(&ctx, hash_iv); ++ while (*p != '\0') { ++ c = (unsigned char)i_toupper(*p++); ++ xxh64_loop(&ctx, &c, 1); + } +- +- return h; ++ return xxh64_to_32(xxh64_result(&ctx)); + } + + unsigned int ATTR_NO_SANITIZE_INTEGER +--- a/src/lib/hash.h ++++ b/src/lib/hash.h +@@ -14,6 +14,9 @@ typedef unsigned int hash_callback_t(con + /* Returns 0 if the pointers are equal. */ + typedef int hash_cmp_callback_t(const void *p1, const void *p2); + ++/* Random per-process IV to use for hash functions */ ++extern uint64_t hash_iv; ++ + /* Create a new hash table. If initial_size is 0, the default value is used. + table_pool is used to allocate/free large hash tables, node_pool is used + for smaller allocations and can also be alloconly pool. The pools must not +@@ -160,9 +163,13 @@ void hash_table_copy(struct hash_table * + #define hash_table_copy(table1, table2) \ + hash_table_copy((table1)._table, (table2)._table) + +-/* hash function for strings */ ++/* Hash function for strings. These are safe against collision attacks. They ++ are initialized with a per-process random key. */ + unsigned int str_hash(const char *p) ATTR_PURE; + unsigned int strcase_hash(const char *p) ATTR_PURE; ++/* Like str_hash(), but there is no per-process random key. This isn't as safe ++ against collision attacks. */ ++unsigned int str_stable_hash(const char *p) ATTR_PURE; + + /* fast hash function which uppercases a-z. Does not work well + with input that consists from non number/letter input, as +@@ -172,4 +179,6 @@ unsigned int strfastcase_hash(const char + /* a generic hash for a given memory block */ + unsigned int mem_hash(const void *p, unsigned int size) ATTR_PURE; + ++void hash_init(void); ++ + #endif +--- a/src/lib/lib.c ++++ b/src/lib/lib.c +@@ -5,6 +5,7 @@ + #include "array.h" + #include "event-filter.h" + #include "env-util.h" ++#include "hash.h" + #include "hostpid.h" + #include "ipwd.h" + #include "process-title.h" +@@ -162,6 +163,7 @@ void lib_init(void) + { + i_assert(!lib_initialized); + random_init(); ++ hash_init(); + data_stack_init(); + hostpid_init(); + lib_open_non_stdio_dev_null(); +--- a/src/lib/test-hash-method.c ++++ b/src/lib/test-hash-method.c +@@ -425,6 +425,39 @@ static void test_hash_methods_fips() { + "\x6d\xf6\x54\x5a\x1c\xe8\xba\x00", + 512 / 8, + }, ++ /* xxh64 reference vectors (seed=0) */ ++ { "xxh64", ++ "", ++ 0, ++ 1, ++ "\xef\x46\xdb\x37\x51\xd8\xe9\x99", ++ 64 / 8 ++ }, ++ { "xxh64", ++ "abc", ++ 3, ++ 1, ++ "\x44\xbc\x2c\xf5\xad\x77\x09\x99", ++ 64 / 8 ++ }, ++ /* 62 bytes: exercises the >= 32-byte accumulator path */ ++ { "xxh64", ++ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef" ++ "ghijklmnopqrstuvwxyz0123456789", ++ 62, ++ 1, ++ "\xba\x76\x1a\x9a\xa8\x0e\x0d\x36", ++ 64 / 8 ++ }, ++ /* 16 bytes × 3 rounds: exercises chunked input across the 32-byte block boundary */ ++ { "xxh64", ++ "\x00\x01\x02\x03\x04\x05\x06\x07" ++ "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", ++ 16, ++ 3, ++ "\x32\x0d\xcd\xab\xd8\x29\x7a\x9e", ++ 64 / 8 ++ }, + }; + + for(size_t i = 0; i < N_ELEMENTS(test_vectors); i++) { +--- a/src/lib/var-expand.c ++++ b/src/lib/var-expand.c +@@ -3,7 +3,6 @@ + #include "lib.h" + #include "array.h" + #include "md5.h" +-#include "hash.h" + #include "hex-binary.h" + #include "base64.h" + #include "hostpid.h" +@@ -70,9 +69,28 @@ m_str_reverse(const char *str, struct va + return rev; + } + ++/* a char* hash function from ASU -- from glib */ ++static unsigned int ATTR_NO_SANITIZE_INTEGER ++str_oldhash(const char *p) ++{ ++ const unsigned char *s = (const unsigned char *)p; ++ unsigned int g, h = 0; ++ ++ while (*s != '\0') { ++ h = (h << 4) + *s; ++ if ((g = h & 0xf0000000UL) != 0) { ++ h = h ^ (g >> 24); ++ h = h ^ g; ++ } ++ s++; ++ } ++ ++ return h; ++} ++ + static const char *m_str_hash(const char *str, struct var_expand_context *ctx) + { +- unsigned int value = str_hash(str); ++ unsigned int value = str_oldhash(str); + string_t *hash = t_str_new(20); + + if (ctx->width != 0) { +--- /dev/null ++++ b/src/lib/xxh64.c +@@ -0,0 +1,184 @@ ++/* Copyright (c) 2025 Dovecot authors, see the included COPYING file */ ++ ++/* XXHash64 - Fast non-cryptographic hash function. ++ * Based on Yann Collet's public domain XXHash64 algorithm. ++ * Reference: https://github.com/Cyan4973/xxHash/blob/dev/doc/xxhash_spec.md ++ */ ++ ++#include "lib.h" ++#include "xxh64.h" ++ ++#define XXH64_PRIME1 UINT64_C(0x9E3779B185EBCA87) ++#define XXH64_PRIME2 UINT64_C(0xC2B2AE3D27D4EB4F) ++#define XXH64_PRIME3 UINT64_C(0x165667B19E3779F9) ++#define XXH64_PRIME4 UINT64_C(0x85EBCA77C2B27589) ++#define XXH64_PRIME5 UINT64_C(0x27D4EB2F165667C5) ++ ++#define XXH64_ROTL(x, r) (((x) << (r)) | ((x) >> (64 - (r)))) ++ ++static inline uint64_t xxh64_read64(const void *p) ++{ ++ uint64_t v; ++ memcpy(&v, p, sizeof(v)); ++ return v; ++} ++ ++static inline uint32_t xxh64_read32(const void *p) ++{ ++ uint32_t v; ++ memcpy(&v, p, sizeof(v)); ++ return v; ++} ++ ++static uint64_t ATTR_UNSIGNED_WRAPS xxh64_round(uint64_t acc, uint64_t input) ++{ ++ acc += input * XXH64_PRIME2; ++ acc = XXH64_ROTL(acc, 31); ++ acc *= XXH64_PRIME1; ++ return acc; ++} ++ ++static uint64_t ATTR_UNSIGNED_WRAPS xxh64_merge_acc(uint64_t h64, uint64_t acc) ++{ ++ acc = xxh64_round(0, acc); ++ h64 ^= acc; ++ h64 = h64 * XXH64_PRIME1 + XXH64_PRIME4; ++ return h64; ++} ++ ++void ATTR_UNSIGNED_WRAPS xxh64_init(struct xxh64_context *ctx, uint64_t seed) ++{ ++ ctx->seed = seed; ++ ctx->v1 = seed + XXH64_PRIME1 + XXH64_PRIME2; ++ ctx->v2 = seed + XXH64_PRIME2; ++ ctx->v3 = seed; ++ ctx->v4 = seed - XXH64_PRIME1; ++ ctx->total_len = 0; ++ ctx->buf_used = 0; ++} ++ ++void ATTR_UNSIGNED_WRAPS xxh64_loop(struct xxh64_context *ctx, const void *data, size_t size) ++{ ++ const unsigned char *p = data; ++ const unsigned char *end = p + size; ++ ++ ctx->total_len += size; ++ ++ if (ctx->buf_used + size < 32) { ++ memcpy(ctx->buf + ctx->buf_used, p, size); ++ ctx->buf_used += size; ++ return; ++ } ++ ++ if (ctx->buf_used > 0) { ++ size_t fill = 32 - ctx->buf_used; ++ memcpy(ctx->buf + ctx->buf_used, p, fill); ++ p += fill; ++ ctx->v1 = xxh64_round(ctx->v1, xxh64_read64(ctx->buf)); ++ ctx->v2 = xxh64_round(ctx->v2, xxh64_read64(ctx->buf + 8)); ++ ctx->v3 = xxh64_round(ctx->v3, xxh64_read64(ctx->buf + 16)); ++ ctx->v4 = xxh64_round(ctx->v4, xxh64_read64(ctx->buf + 24)); ++ ctx->buf_used = 0; ++ } ++ ++ while (p + 32 <= end) { ++ ctx->v1 = xxh64_round(ctx->v1, xxh64_read64(p)); ++ ctx->v2 = xxh64_round(ctx->v2, xxh64_read64(p + 8)); ++ ctx->v3 = xxh64_round(ctx->v3, xxh64_read64(p + 16)); ++ ctx->v4 = xxh64_round(ctx->v4, xxh64_read64(p + 24)); ++ p += 32; ++ } ++ ++ if (p < end) { ++ ctx->buf_used = (unsigned int)(end - p); ++ memcpy(ctx->buf, p, ctx->buf_used); ++ } ++} ++ ++uint64_t ATTR_UNSIGNED_WRAPS xxh64_result(struct xxh64_context *ctx) ++{ ++ const unsigned char *p = ctx->buf; ++ const unsigned char *end = p + ctx->buf_used; ++ uint64_t h64; ++ ++ if (ctx->total_len >= 32) { ++ h64 = XXH64_ROTL(ctx->v1, 1) + XXH64_ROTL(ctx->v2, 7) + ++ XXH64_ROTL(ctx->v3, 12) + XXH64_ROTL(ctx->v4, 18); ++ h64 = xxh64_merge_acc(h64, ctx->v1); ++ h64 = xxh64_merge_acc(h64, ctx->v2); ++ h64 = xxh64_merge_acc(h64, ctx->v3); ++ h64 = xxh64_merge_acc(h64, ctx->v4); ++ } else { ++ h64 = ctx->seed + XXH64_PRIME5; ++ } ++ ++ h64 += ctx->total_len; ++ ++ while (p + 8 <= end) { ++ h64 ^= xxh64_round(0, xxh64_read64(p)); ++ h64 = XXH64_ROTL(h64, 27) * XXH64_PRIME1 + XXH64_PRIME4; ++ p += 8; ++ } ++ if (p + 4 <= end) { ++ h64 ^= (uint64_t)xxh64_read32(p) * XXH64_PRIME1; ++ h64 = XXH64_ROTL(h64, 23) * XXH64_PRIME2 + XXH64_PRIME3; ++ p += 4; ++ } ++ while (p < end) { ++ h64 ^= (uint64_t)*p * XXH64_PRIME5; ++ h64 = XXH64_ROTL(h64, 11) * XXH64_PRIME1; ++ p++; ++ } ++ ++ /* Avalanche */ ++ h64 ^= h64 >> 33; ++ h64 *= XXH64_PRIME2; ++ h64 ^= h64 >> 29; ++ h64 *= XXH64_PRIME3; ++ h64 ^= h64 >> 32; ++ ++ return h64; ++} ++ ++uint64_t xxh64_data(const void *data, size_t size, uint64_t seed) ++{ ++ struct xxh64_context ctx; ++ ++ xxh64_init(&ctx, seed); ++ xxh64_loop(&ctx, data, size); ++ return xxh64_result(&ctx); ++} ++ ++static void xxh64_hash_init(void *context) ++{ ++ xxh64_init(context, 0); ++} ++ ++static void xxh64_hash_loop(void *context, const void *data, size_t size) ++{ ++ xxh64_loop(context, data, size); ++} ++ ++static void xxh64_hash_result(void *context, unsigned char *digest_r) ++{ ++ uint64_t hash = xxh64_result(context); ++ ++ digest_r[0] = (hash >> 56) & 0xff; ++ digest_r[1] = (hash >> 48) & 0xff; ++ digest_r[2] = (hash >> 40) & 0xff; ++ digest_r[3] = (hash >> 32) & 0xff; ++ digest_r[4] = (hash >> 24) & 0xff; ++ digest_r[5] = (hash >> 16) & 0xff; ++ digest_r[6] = (hash >> 8) & 0xff; ++ digest_r[7] = (hash >> 0) & 0xff; ++} ++ ++const struct hash_method hash_method_xxh64 = { ++ .name = "xxh64", ++ .block_size = 32, ++ .context_size = sizeof(struct xxh64_context), ++ .digest_size = XXH64_RESULTLEN, ++ .init = xxh64_hash_init, ++ .loop = xxh64_hash_loop, ++ .result = xxh64_hash_result, ++}; +--- /dev/null ++++ b/src/lib/xxh64.h +@@ -0,0 +1,30 @@ ++#ifndef XXH64_H ++#define XXH64_H ++ ++#include "hash-method.h" ++ ++#define XXH64_RESULTLEN 8 ++ ++struct xxh64_context { ++ uint64_t seed; ++ uint64_t v1, v2, v3, v4; ++ uint64_t total_len; ++ unsigned char buf[32]; ++ unsigned int buf_used; ++}; ++ ++void xxh64_init(struct xxh64_context *ctx, uint64_t seed); ++void xxh64_loop(struct xxh64_context *ctx, const void *data, size_t size); ++uint64_t xxh64_result(struct xxh64_context *ctx); ++ ++uint64_t xxh64_data(const void *data, size_t size, uint64_t seed) ATTR_PURE; ++ ++/* XOR-fold the 64-bit hash to 32 bits */ ++static inline uint32_t xxh64_to_32(uint64_t hash) ++{ ++ return (uint32_t)(hash ^ (hash >> 32)); ++} ++ ++extern const struct hash_method hash_method_xxh64; ++ ++#endif diff --git a/mail/dovecot/patches/219-xxh64-endian-fix.patch b/mail/dovecot/patches/219-xxh64-endian-fix.patch new file mode 100644 index 0000000000..f7dc6bd941 --- /dev/null +++ b/mail/dovecot/patches/219-xxh64-endian-fix.patch @@ -0,0 +1,46 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Noah Meyerhans +Subject: [PATCH] lib: xxh64: fix byte ordering issue on big-endian systems + +The fix for CVE-2026-40017 adds xxh64. Without this change it reads its +input in host byte order and computes different hashes on big-endian +systems than on little-endian ones. + +Sent upstream as https://github.com/dovecot/core/pull/314, upstream +fixed it in its own way based on this patch: + https://github.com/dovecot/core/commit/536eb46c065ff6c6cce2ab5ea4af150830c906a4 +Debian bug: + https://bugs.debian.org/1146449 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib/xxh64.c ++++ b/src/lib/xxh64.c +@@ -8,6 +8,8 @@ + #include "lib.h" + #include "xxh64.h" + ++#include ++ + #define XXH64_PRIME1 UINT64_C(0x9E3779B185EBCA87) + #define XXH64_PRIME2 UINT64_C(0xC2B2AE3D27D4EB4F) + #define XXH64_PRIME3 UINT64_C(0x165667B19E3779F9) +@@ -20,14 +22,14 @@ static inline uint64_t xxh64_read64(cons + { + uint64_t v; + memcpy(&v, p, sizeof(v)); +- return v; ++ return le64toh(v); /* Convert from little-endian to host byte order */ + } + + static inline uint32_t xxh64_read32(const void *p) + { + uint32_t v; + memcpy(&v, p, sizeof(v)); +- return v; ++ return le32toh(v); /* Convert from little-endian to host byte order */ + } + + static uint64_t ATTR_UNSIGNED_WRAPS xxh64_round(uint64_t acc, uint64_t input) diff --git a/mail/dovecot/patches/220-CVE-2026-42395.patch b/mail/dovecot/patches/220-CVE-2026-42395.patch new file mode 100644 index 0000000000..4f67645414 --- /dev/null +++ b/mail/dovecot/patches/220-CVE-2026-42395.patch @@ -0,0 +1,92 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-42395 + +Upstream commits: + submission-login: Fix parsing multiple XCLIENT FORWARD parameters + https://github.com/dovecot/core/commit/a1ce604684d5920001a2768dacc00ab00050c8af + pop3/submission-login: Split off a common client_forward_decode_base64() + https://github.com/dovecot/core/commit/ac69e4c3351f8e65e8af18a3befe40a7844aa0e6 + login-common: Fix crash when XCLIENT FORWARD= base64 contains NUL byte + https://github.com/dovecot/core/commit/7fc304a8109fe484ab4026b4cfbe39ce82351319 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/login-common/client-common.c ++++ b/src/login-common/client-common.c +@@ -745,6 +745,23 @@ void client_add_forward_field(struct cli + str_append_tabescaped(client->forward_fields, value); + } + ++bool client_forward_decode_base64(struct client *client, const char *value) ++{ ++ size_t value_len = strlen(value); ++ string_t *str = str_new(client->preproxy_pool, ++ MAX_BASE64_DECODED_SIZE(value_len)); ++ if (base64_decode(value, value_len, NULL, str) < 0) ++ return FALSE; ++ /* Embedded NUL would yield a created-but-empty array, panicking later ++ in array_front() during sasl_server_auth_begin(). */ ++ if (str_len(str) == 0 || ++ memchr(str_data(str), '\0', str_len(str)) != NULL) ++ return FALSE; ++ ++ client->forward_fields = str; ++ return TRUE; ++} ++ + const char *client_get_session_id(struct client *client) + { + buffer_t *buf, *base64_buf; +--- a/src/login-common/client-common.h ++++ b/src/login-common/client-common.h +@@ -319,6 +319,7 @@ struct client *clients_get_first_fd_prox + + void client_add_forward_field(struct client *client, const char *key, + const char *value); ++bool client_forward_decode_base64(struct client *client, const char *value); + void client_set_title(struct client *client); + const char *client_get_extra_disconnect_reason(struct client *client); + +--- a/src/pop3-login/client.c ++++ b/src/pop3-login/client.c +@@ -68,12 +68,7 @@ static bool cmd_xclient(struct pop3_clie + if (str_to_uint(*tmp + 4, &client->common.proxy_ttl) < 0) + args_ok = FALSE; + } else if (strncasecmp(*tmp, "FORWARD=", 8) == 0) { +- size_t value_len = strlen((*tmp)+8); +- client->common.forward_fields = +- str_new(client->common.preproxy_pool, +- MAX_BASE64_DECODED_SIZE(value_len)); +- if (base64_decode((*tmp)+8, value_len, NULL, +- client->common.forward_fields) < 0) ++ if (!client_forward_decode_base64(&client->common, (*tmp)+8)) + args_ok = FALSE; + } + } +--- a/src/submission-login/client.c ++++ b/src/submission-login/client.c +@@ -193,18 +193,9 @@ client_connection_cmd_xclient(void *cont + const char *value = data->extra_fields[i].value; + + if (strcasecmp(name, "FORWARD") == 0) { +- size_t value_len = strlen(value); +- if (client->common.forward_fields != NULL) { +- str_truncate(client->common.forward_fields, 0); +- } else { +- client->common.forward_fields = str_new( +- client->common.preproxy_pool, +- MAX_BASE64_DECODED_SIZE(value_len)); +- if (base64_decode(value, value_len, NULL, +- client->common.forward_fields) < 0) { +- smtp_server_reply(cmd, 501, "5.5.4", +- "Invalid FORWARD parameter"); +- } ++ if (!client_forward_decode_base64(&client->common, value)) { ++ smtp_server_reply(cmd, 501, "5.5.4", ++ "Invalid FORWARD parameter"); + } + } + } diff --git a/mail/dovecot/patches/221-CVE-2026-40014.patch b/mail/dovecot/patches/221-CVE-2026-40014.patch new file mode 100644 index 0000000000..523e5c895c --- /dev/null +++ b/mail/dovecot/patches/221-CVE-2026-40014.patch @@ -0,0 +1,104 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40014 + +Upstream commits: + lib-storage: thread - Limit References: header msgid count to prevent O(N^2) CPU usage + https://github.com/dovecot/core/commit/fe6b8a4c5305b106ae68a197ee301d8fe3f38672 + lib-storage: thread - Limit ancestor chain traversal depth to prevent O(N^2) CPU usage + https://github.com/dovecot/core/commit/2818f84d9e4f93d9997f9cc7b1cc55a7cacb85a0 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-storage/index/index-thread-links.c ++++ b/src/lib-storage/index/index-thread-links.c +@@ -31,12 +31,24 @@ static uint32_t thread_msg_add(struct ma + + static bool thread_node_has_ancestor(struct mail_thread_cache *cache, + const struct mail_thread_node *node, +- const struct mail_thread_node *ancestor) ++ const struct mail_thread_node *ancestor, ++ bool *depth_exceeded_r) + { ++ unsigned int n = 0; ++ ++ *depth_exceeded_r = FALSE; + while (node != ancestor) { + if (node->parent_idx == 0) + return FALSE; +- ++ if (++n > MAIL_THREAD_REFERENCES_MAX) { ++ /* Ancestor chain is deeper than the per-message ++ References limit. Multiple crafted messages can build ++ an arbitrarily deep chain, causing O(N^2) traversals ++ per email even with the per-message limit. Treat the ++ link as unsafe to prevent the DoS. */ ++ *depth_exceeded_r = TRUE; ++ return FALSE; ++ } + node = array_idx(&cache->thread_nodes, node->parent_idx); + } + return TRUE; +@@ -47,6 +59,7 @@ static void thread_link_reference(struct + { + struct mail_thread_node *node, *parent, *child; + uint32_t idx; ++ bool depth_exceeded; + + i_assert(parent_idx < cache->first_invalid_msgid_str_idx); + +@@ -62,7 +75,7 @@ static void thread_link_reference(struct + } + + child->parent_link_refcount++; +- if (thread_node_has_ancestor(cache, parent, child)) { ++ if (thread_node_has_ancestor(cache, parent, child, &depth_exceeded)) { + if (parent == child) { + /* loops to itself - ignore */ + return; +@@ -88,6 +101,18 @@ static void thread_link_reference(struct + node->child_unref_rebuilds = TRUE; + } while (node != child); + return; ++ } else if (depth_exceeded) { ++ /* Ancestor chain exceeded the depth limit; drop this link. ++ parent_link_refcount was already incremented above and is ++ intentionally kept that way: mail_thread_unref_link() ++ walks References blindly at remove time and would hit ++ i_assert(child->parent_link_refcount > 0) on the matching ++ edge if we hadn't bumped it here. The trade-off is that ++ the bumped refcount can leave child->parent_idx attached ++ to a stale parent if another message later sets a real ++ parent edge on this child and is then expunged - threading ++ stays wrong until some other event triggers a rebuild. */ ++ return; + } else if (child->parent_idx == parent_idx) { + /* The same link already exists */ + return; +--- a/src/lib-storage/index/index-thread-private.h ++++ b/src/lib-storage/index/index-thread-private.h +@@ -22,6 +22,10 @@ + #define MAIL_THREAD_NODE_REF_MSGID 0 + #define MAIL_THREAD_NODE_REF_INREPLYTO 1 + #define MAIL_THREAD_NODE_REF_REFERENCES1 2 ++/* Maximum number of References: header message-IDs stored per message. ++ Prevents O(N²) CPU usage in thread_node_has_ancestor() when a single ++ crafted message contains an abnormally long reference chain. */ ++#define MAIL_THREAD_REFERENCES_MAX 1000 + + struct mail_thread_node { + /* UID of the message, or 0 for dummy nodes */ +--- a/src/lib-storage/index/index-thread.c ++++ b/src/lib-storage/index/index-thread.c +@@ -280,7 +280,8 @@ mail_thread_map_add_mail(struct mail_thr + ref_index, msgid); + } + } T_END; +- } while (msgid != NULL); ++ } while (msgid != NULL && ++ ref_index < MAIL_THREAD_NODE_REF_REFERENCES1 + MAIL_THREAD_REFERENCES_MAX); + } else { + /* no References:, use In-Reply-To: */ + if (thread_get_mail_header(mail, HDR_IN_REPLY_TO, diff --git a/mail/dovecot/patches/222-CVE-2026-42393.patch b/mail/dovecot/patches/222-CVE-2026-42393.patch new file mode 100644 index 0000000000..071430f086 --- /dev/null +++ b/mail/dovecot/patches/222-CVE-2026-42393.patch @@ -0,0 +1,147 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-42393 + +Upstream commits: + lib: Add str_equals_timing_safe() + https://github.com/dovecot/core/commit/e07df7e2a832c8f67c14da8bcf7f93e0d6cc5a39 + doveadm: Avoid leaking doveadm_password or doveadm_api_key lengths + https://github.com/dovecot/core/commit/a19f43238d51bd1bca7799328aa51002dca4e96c + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/doveadm/client-connection-http.c ++++ b/src/doveadm/client-connection-http.c +@@ -984,7 +984,7 @@ doveadm_http_server_auth_basic(struct cl + b64_value = t_base64_encode_str(0, UINT_MAX, value); + + if (creds->data != NULL && +- str_equals_timing_almost_safe(str_c(b64_value), creds->data)) ++ str_equals_hash_timing_safe(str_c(b64_value), creds->data)) + return TRUE; + + i_error("Invalid authentication attempt to HTTP API " +@@ -1008,7 +1008,7 @@ doveadm_http_server_auth_api_key(struct + + b64_value = t_base64_encode_str(0, UINT_MAX, set->doveadm_api_key); + if (creds->data != NULL && +- str_equals_timing_almost_safe(creds->data, str_c(b64_value))) ++ str_equals_hash_timing_safe(creds->data, str_c(b64_value))) + return TRUE; + + i_error("Invalid authentication attempt to HTTP API " +--- a/src/doveadm/client-connection-tcp.c ++++ b/src/doveadm/client-connection-tcp.c +@@ -342,7 +342,7 @@ client_connection_tcp_authenticate(struc + return -1; + } + pass = t_strndup(data + 9, size - 9); +- if (!str_equals_timing_almost_safe(pass, set->doveadm_password)) { ++ if (!str_equals_hash_timing_safe(pass, set->doveadm_password)) { + i_error("doveadm client authenticated with wrong password"); + return -1; + } +--- a/src/lib/strfuncs.c ++++ b/src/lib/strfuncs.c +@@ -7,6 +7,9 @@ + #include "printf-format-fix.h" + #include "strfuncs.h" + #include "array.h" ++#include "hash.h" ++#include "hmac.h" ++#include "sha2.h" + + #include + #include +@@ -622,6 +625,32 @@ bool str_equals_timing_almost_safe(const + return ret == 0; + } + ++bool str_equals_hash_timing_safe(const char *s1, const char *s2) ++{ ++ struct hmac_context ctx; ++ unsigned char digest1[SHA256_RESULTLEN]; ++ unsigned char digest2[SHA256_RESULTLEN]; ++ ++ /* Compare HMAC-SHA256 digests of the inputs rather than the inputs ++ themselves. The digest length is constant, so the subsequent ++ mem_equals_timing_safe() leaks no length information. The HMAC ++ times depend on the input lengths, but each side's length is either ++ a deployment constant (for the secret) or already known to the ++ attacker (for their own input), so neither leaks a useful signal. ++ hash_iv keys the HMAC to prevent precomputation. */ ++ hmac_init(&ctx, (const unsigned char *)&hash_iv, sizeof(hash_iv), ++ &hash_method_sha256); ++ hmac_update(&ctx, s1, strlen(s1)); ++ hmac_final(&ctx, digest1); ++ ++ hmac_init(&ctx, (const unsigned char *)&hash_iv, sizeof(hash_iv), ++ &hash_method_sha256); ++ hmac_update(&ctx, s2, strlen(s2)); ++ hmac_final(&ctx, digest2); ++ ++ return mem_equals_timing_safe(digest1, digest2, sizeof(digest1)); ++} ++ + size_t + str_match(const char *p1, const char *p2) + { +--- a/src/lib/strfuncs.h ++++ b/src/lib/strfuncs.h +@@ -85,6 +85,11 @@ bool mem_equals_timing_safe(const void * + the string lengths are the same. If not, the length of the secret string may + be leaked, but otherwise the contents won't be. */ + bool str_equals_timing_almost_safe(const char *s1, const char *s2); ++/* Returns TRUE if the two strings are equal. Safe against timing attacks: ++ neither the contents nor the length of either string is leaked. ++ Implemented by HMAC-SHA256ing both inputs under a random per-process key ++ and comparing the fixed-length digests. */ ++bool str_equals_hash_timing_safe(const char *s1, const char *s2); + + size_t str_match(const char *p1, const char *p2) ATTR_PURE; + static inline ATTR_PURE bool str_begins(const char *haystack, const char *needle) +--- a/src/lib/test-strfuncs.c ++++ b/src/lib/test-strfuncs.c +@@ -436,6 +436,32 @@ static void test_str_equals_timing_almos + test_end(); + } + ++static void test_str_equals_hash_timing_safe(void) ++{ ++ const struct { ++ const char *a, *b; ++ } tests[] = { ++ { "", "" }, ++ { "a", "a" }, ++ { "b", "a" }, ++ { "ab", "ab" }, ++ { "ab", "ba" }, ++ { "ab", "bc" }, ++ { "a", "" }, ++ { "a", "ab" }, ++ { "a", "abc" }, ++ { "ab", "abc" }, ++ }; ++ test_begin("str_equals_hash_timing_safe()"); ++ for (unsigned int i = 0; i < N_ELEMENTS(tests); i++) { ++ test_assert((strcmp(tests[i].a, tests[i].b) == 0) == ++ str_equals_hash_timing_safe(tests[i].a, tests[i].b)); ++ test_assert((strcmp(tests[i].a, tests[i].b) == 0) == ++ str_equals_hash_timing_safe(tests[i].b, tests[i].a)); ++ } ++ test_end(); ++} ++ + static void test_dec2str_buf(void) + { + const uintmax_t test_input[] = { +@@ -616,6 +642,7 @@ void test_strfuncs(void) + test_p_array_const_string_join(); + test_mem_equals_timing_safe(); + test_str_equals_timing_almost_safe(); ++ test_str_equals_hash_timing_safe(); + test_dec2str_buf(); + test_str_match(); + test_memspn(); diff --git a/mail/dovecot/patches/223-CVE-2026-33263.patch b/mail/dovecot/patches/223-CVE-2026-33263.patch new file mode 100644 index 0000000000..a0ae36cee0 --- /dev/null +++ b/mail/dovecot/patches/223-CVE-2026-33263.patch @@ -0,0 +1,482 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-33263 + +Upstream commits: + *-login: Fix error code for "Maximum number of connections from user+IP exceeded" + https://github.com/dovecot/core/commit/906c97993469adf9743b2f25ac8aeddace005a73 + *-commin: Rename LOGIN_PROXY_FAILURE_TYPE_AUTH to LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED + https://github.com/dovecot/core/commit/4d016e968857437ca1a6aa804c473e06079539f2 + *-login: Add LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED + https://github.com/dovecot/core/commit/5fde53de4ebdf791a5fe583d4f8e52b89215bc7c + pop3-login: If mail_max_userip_connections is reached, reply to login with [IN-USE] prefix + https://github.com/dovecot/core/commit/75cfd0a0f0b88b42541570dc18b6a65b67ba9f71 + login-common, *-login: Add proxy_dest_connection_limit error_code to proxy_session_finished + https://github.com/dovecot/core/commit/db0835c84bf754a260ce0d3dca1d69eb90f87518 + submission-login: Handle CLIENT_AUTH_RESULT_LIMIT_REACHED as temporary error + https://github.com/dovecot/core/commit/6b89deb54e197aae41a2a3ad2d3998f2df024866 + login-common: client-common - Add client_disconnect() vfunc + https://github.com/dovecot/core/commit/9cbe5c9a5e0526b799c98e0e299821a3390599d3 + submission-login: client - Fix panic occurring at mail_max_userip_connections limit transgression + https://github.com/dovecot/core/commit/a2b74bac07c8a231b859203fe2e624f3f0806e65 + lib-smtp: smtp-server - Expose smtp_server_connection_reply_immediate + https://github.com/dovecot/core/commit/2a1ae65f59bd462b18d815e1fb5971bb4be86d52 + submission-login: client-authenticate - Reply 421 4.7.0 on mail_max_userip_connections + https://github.com/dovecot/core/commit/cae8cf70d24939f515e2a039acb0b8e2fea5ccb2 + submission-login: submission-proxy - Recognize 421 4.7.0 as connection-limit reply + https://github.com/dovecot/core/commit/432177f997e74843ba8b3c271d28697675b34a0f + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +The Pigeonhole part of this fix is in mail/pigeonhole/patches. + +--- a/src/imap-login/client-authenticate.c ++++ b/src/imap-login/client-authenticate.c +@@ -95,6 +95,10 @@ void imap_client_auth_result(struct clie + client_send_reply_code(client, IMAP_CMD_REPLY_NO, + IMAP_RESP_CODE_UNAVAILABLE, text); + break; ++ case CLIENT_AUTH_RESULT_LIMIT_REACHED: ++ client_send_reply_code(client, IMAP_CMD_REPLY_NO, ++ IMAP_RESP_CODE_LIMIT, text); ++ break; + case CLIENT_AUTH_RESULT_SSL_REQUIRED: + case CLIENT_AUTH_RESULT_MECH_SSL_REQUIRED: + client_send_reply_code(client, IMAP_CMD_REPLY_NO, +--- a/src/imap-login/imap-proxy.c ++++ b/src/imap-login/imap-proxy.c +@@ -254,6 +254,12 @@ static bool auth_resp_code_is_tempfail(c + return strcasecmp(resp_code, IMAP_RESP_CODE_UNAVAILABLE) == 0; + } + ++static bool auth_resp_code_is_limit(const char *resp) ++{ ++ return strncasecmp(resp, IMAP_RESP_CODE_LIMIT"]", ++ strlen(IMAP_RESP_CODE_LIMIT"]")) == 0; ++} ++ + int imap_proxy_parse_line(struct client *client, const char *line) + { + struct imap_client *imap_client = (struct imap_client *)client; +@@ -359,7 +365,7 @@ int imap_proxy_parse_line(struct client + if (strncasecmp(log_line, "NO ", 3) == 0) + log_line += 3; + enum login_proxy_failure_type failure_type = +- LOGIN_PROXY_FAILURE_TYPE_AUTH; ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED; + #define STR_NO_IMAP_RESP_CODE_AUTHFAILED "NO ["IMAP_RESP_CODE_AUTHFAILED"]" + if (str_begins(line, STR_NO_IMAP_RESP_CODE_AUTHFAILED)) { + /* the remote sent a generic "authentication failed" +@@ -376,6 +382,8 @@ int imap_proxy_parse_line(struct client + if (auth_resp_code_is_tempfail(resp_code)) + failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL; + else { ++ if (auth_resp_code_is_limit(line + 4)) ++ failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED; + client_send_raw(client, t_strconcat( + imap_client->cmd_tag, " ", line, "\r\n", NULL)); + } +@@ -486,6 +494,7 @@ imap_proxy_send_failure_reply(struct ima + break; + case LOGIN_PROXY_FAILURE_TYPE_REMOTE_CONFIG: + case LOGIN_PROXY_FAILURE_TYPE_INTERNAL_CONFIG: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED: + client_send_reply_code(&imap_client->common, IMAP_CMD_REPLY_NO, + IMAP_RESP_CODE_SERVERBUG, + LOGIN_PROXY_FAILURE_MSG); +@@ -494,7 +503,8 @@ imap_proxy_send_failure_reply(struct ima + client_send_raw(&imap_client->common, t_strconcat( + imap_client->cmd_tag, " NO ", reason, "\r\n", NULL)); + break; +- case LOGIN_PROXY_FAILURE_TYPE_AUTH: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED: + /* reply was already sent */ + break; + } +--- a/src/lib-smtp/smtp-server-connection.c ++++ b/src/lib-smtp/smtp-server-connection.c +@@ -1303,6 +1303,11 @@ void smtp_server_connection_close(struct + smtp_server_connection_unref(&conn); + } + ++bool smtp_server_connection_is_closed(struct smtp_server_connection *conn) ++{ ++ return conn->closed; ++} ++ + void smtp_server_connection_terminate(struct smtp_server_connection **_conn, + const char *enh_code, const char *reason) + { +--- a/src/lib-smtp/smtp-server-private.h ++++ b/src/lib-smtp/smtp-server-private.h +@@ -325,9 +325,6 @@ void smtp_server_connection_reply_lines( + unsigned int status, + const char *enh_code, + const char *const *text_lines); +-void smtp_server_connection_reply_immediate( +- struct smtp_server_connection *conn, unsigned int status, +- const char *fmt, ...) ATTR_FORMAT(3, 4); + + void smtp_server_connection_reset_state(struct smtp_server_connection *conn); + void smtp_server_connection_set_state(struct smtp_server_connection *conn, +--- a/src/lib-smtp/smtp-server.h ++++ b/src/lib-smtp/smtp-server.h +@@ -473,6 +473,17 @@ void smtp_server_connection_set_ssl_stre + + void smtp_server_connection_close(struct smtp_server_connection **_conn, + const char *reason) ATTR_NULL(2); ++bool smtp_server_connection_is_closed(struct smtp_server_connection *conn); ++/* Send a reply line directly to the output stream, bypassing the per-command ++ reply queue. Useful when the caller is about to close the connection and ++ needs the reply on the wire before close/destroy aborts queued replies. ++ The formatted text must be a single line (no CR/LF); unlike ++ smtp_server_reply_add_text(), this function does not split on \n nor add ++ the SMTP continuation prefix to subsequent lines. */ ++void smtp_server_connection_reply_immediate(struct smtp_server_connection *conn, ++ unsigned int status, ++ const char *fmt, ...) ++ ATTR_FORMAT(3, 4); + void smtp_server_connection_terminate(struct smtp_server_connection **_conn, + const char *enh_code, const char *reason) + ATTR_NULL(3); +--- a/src/login-common/client-common-auth.c ++++ b/src/login-common/client-common-auth.c +@@ -413,7 +413,9 @@ void client_common_proxy_failed(struct c + case LOGIN_PROXY_FAILURE_TYPE_REMOTE_CONFIG: + case LOGIN_PROXY_FAILURE_TYPE_PROTOCOL: + break; +- case LOGIN_PROXY_FAILURE_TYPE_AUTH: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED: + case LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL: + client->proxy_auth_failed = TRUE; + break; +@@ -763,7 +765,8 @@ sasl_callback(struct client *client, enu + + i_assert(!client->destroyed || + sasl_reply == SASL_SERVER_REPLY_AUTH_ABORTED || +- sasl_reply == SASL_SERVER_REPLY_MASTER_FAILED); ++ sasl_reply == SASL_SERVER_REPLY_MASTER_FAILED || ++ sasl_reply == SASL_SERVER_REPLY_MASTER_FAILED_LIMIT); + + client->last_auth_fail = CLIENT_AUTH_FAIL_CODE_NONE; + i_zero(&reply); +@@ -812,11 +815,17 @@ sasl_callback(struct client *client, enu + client_auth_failed(client); + break; + case SASL_SERVER_REPLY_MASTER_FAILED: +- if (data != NULL) { ++ case SASL_SERVER_REPLY_MASTER_FAILED_LIMIT: ++ if (data == NULL) ++ ; ++ else if (sasl_reply == SASL_SERVER_REPLY_MASTER_FAILED) { + /* authentication itself succeeded, we just hit some + internal failure. */ + client_auth_result(client, CLIENT_AUTH_RESULT_TEMPFAIL, + &reply, data); ++ } else { ++ client_auth_result(client, ++ CLIENT_AUTH_RESULT_LIMIT_REACHED, &reply, data); + } + + /* the fd may still be hanging somewhere in kernel or another +--- a/src/login-common/client-common.c ++++ b/src/login-common/client-common.c +@@ -285,6 +285,8 @@ void client_disconnect(struct client *cl + if (!client->login_success) { + bool unref = FALSE; + ++ if (client->v.disconnect != NULL) ++ client->v.disconnect(client, reason); + io_remove(&client->io); + ssl_iostream_destroy(&client->ssl_iostream); + if (client->iostream_fd_proxy != NULL) { +--- a/src/login-common/client-common.h ++++ b/src/login-common/client-common.h +@@ -72,6 +72,7 @@ enum client_auth_result { + CLIENT_AUTH_RESULT_AUTHFAILED_REASON, + CLIENT_AUTH_RESULT_AUTHZFAILED, + CLIENT_AUTH_RESULT_TEMPFAIL, ++ CLIENT_AUTH_RESULT_LIMIT_REACHED, + CLIENT_AUTH_RESULT_PASS_EXPIRED, + CLIENT_AUTH_RESULT_SSL_REQUIRED, + CLIENT_AUTH_RESULT_INVALID_BASE64, +@@ -119,6 +120,7 @@ struct client_auth_reply { + struct client_vfuncs { + struct client *(*alloc)(pool_t pool); + void (*create)(struct client *client, void **other_sets); ++ void (*disconnect)(struct client *client, const char *reason); + void (*destroy)(struct client *client); + void (*notify_auth_ready)(struct client *client); + void (*notify_disconnect)(struct client *client, +--- a/src/login-common/login-proxy.c ++++ b/src/login-common/login-proxy.c +@@ -634,7 +634,9 @@ bool login_proxy_failed(struct login_pro + case LOGIN_PROXY_FAILURE_TYPE_PROTOCOL: + log_prefix = "Remote server sent invalid input: "; + break; +- case LOGIN_PROXY_FAILURE_TYPE_AUTH: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED: + log_prefix = ""; + try_reconnect = FALSE; + break; +@@ -653,7 +655,9 @@ bool login_proxy_failed(struct login_pro + return TRUE; + } + +- if (type != LOGIN_PROXY_FAILURE_TYPE_AUTH && ++ if (type != LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED && ++ type != LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED && ++ type != LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED && + type != LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL) + e_error(event, "%s%s", log_prefix, reason); + else if (proxy->client->set->auth_verbose) +--- a/src/login-common/login-proxy.h ++++ b/src/login-common/login-proxy.h +@@ -41,10 +41,16 @@ enum login_proxy_failure_type { + LOGIN_PROXY_FAILURE_TYPE_PROTOCOL, + /* Authentication failed to backend. The LOGIN/AUTH command reply was + already sent to the client. */ +- LOGIN_PROXY_FAILURE_TYPE_AUTH, ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED, ++ /* Authentication failed to backend. The LOGIN/AUTH command reply was ++ NOT sent to the client yet. */ ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED, + /* Authentication failed with a temporary failure code. Attempting it + again might work. */ + LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL, ++ /* Authentication failed because user has reached some limit. ++ The LOGIN/AUTH command reply was already sent to the client. */ ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED, + }; + + struct login_proxy_settings { +--- a/src/login-common/sasl-server.c ++++ b/src/login-common/sasl-server.c +@@ -226,7 +226,7 @@ anvil_lookup_callback(const char *reply, + const struct login_settings *set = client->set; + const char *errmsg; + unsigned int conn_count; +- int ret; ++ enum sasl_server_reply sasl_reply = SASL_SERVER_REPLY_SUCCESS; + + client->anvil_query = NULL; + client->anvil_request = NULL; +@@ -238,18 +238,18 @@ anvil_lookup_callback(const char *reply, + /* reply=NULL if we didn't need to do anvil lookup, + or if the anvil lookup failed. allow failed anvil lookups in. */ + if (reply == NULL || conn_count < set->mail_max_userip_connections) { +- ret = master_send_request(req); ++ if (master_send_request(req) < 0) ++ sasl_reply = SASL_SERVER_REPLY_MASTER_FAILED; + errmsg = NULL; /* client will see internal error */ + } else { +- ret = -1; ++ sasl_reply = SASL_SERVER_REPLY_MASTER_FAILED_LIMIT; + errmsg = t_strdup_printf(ERR_TOO_MANY_USERIP_CONNECTIONS, + set->mail_max_userip_connections); + } +- if (ret < 0) { ++ if (sasl_reply != SASL_SERVER_REPLY_SUCCESS) { + client->authenticating = FALSE; + auth_client_send_cancel(auth_client, client->master_auth_id); +- call_client_callback(client, SASL_SERVER_REPLY_MASTER_FAILED, +- errmsg, NULL); ++ call_client_callback(client, sasl_reply, errmsg, NULL); + } + i_free(req); + } +--- a/src/login-common/sasl-server.h ++++ b/src/login-common/sasl-server.h +@@ -8,6 +8,7 @@ enum sasl_server_reply { + SASL_SERVER_REPLY_AUTH_FAILED, + SASL_SERVER_REPLY_AUTH_ABORTED, + SASL_SERVER_REPLY_MASTER_FAILED, ++ SASL_SERVER_REPLY_MASTER_FAILED_LIMIT, + SASL_SERVER_REPLY_CONTINUE + }; + +--- a/src/pop3-login/client-authenticate.c ++++ b/src/pop3-login/client-authenticate.c +@@ -59,6 +59,9 @@ void pop3_client_auth_result(struct clie + case CLIENT_AUTH_RESULT_TEMPFAIL: + client_send_reply(client, POP3_CMD_REPLY_TEMPFAIL, text); + break; ++ case CLIENT_AUTH_RESULT_LIMIT_REACHED: ++ client_send_reply(client, POP3_CMD_REPLY_LIMIT, text); ++ break; + case CLIENT_AUTH_RESULT_AUTHFAILED: + case CLIENT_AUTH_RESULT_AUTHFAILED_REASON: + case CLIENT_AUTH_RESULT_AUTHZFAILED: +--- a/src/pop3-login/client.c ++++ b/src/pop3-login/client.c +@@ -292,6 +292,9 @@ void client_send_reply(struct client *cl + case POP3_CMD_REPLY_TEMPFAIL: + prefix = "-ERR [SYS/TEMP]"; + break; ++ case POP3_CMD_REPLY_LIMIT: ++ prefix = "-ERR [IN-USE]"; ++ break; + case POP3_CMD_REPLY_AUTH_ERROR: + if (text[0] == '[') + prefix = "-ERR"; +--- a/src/pop3-login/client.h ++++ b/src/pop3-login/client.h +@@ -31,7 +31,8 @@ enum pop3_cmd_reply { + POP3_CMD_REPLY_OK, + POP3_CMD_REPLY_ERROR, + POP3_CMD_REPLY_AUTH_ERROR, +- POP3_CMD_REPLY_TEMPFAIL ++ POP3_CMD_REPLY_TEMPFAIL, ++ POP3_CMD_REPLY_LIMIT, + }; + + void client_send_reply(struct client *client, enum pop3_cmd_reply reply, +--- a/src/pop3-login/pop3-proxy.c ++++ b/src/pop3-login/pop3-proxy.c +@@ -249,7 +249,7 @@ int pop3_proxy_parse_line(struct client + shouldn't be a real problem since of course everyone will + be using only Dovecot as their backend :) */ + enum login_proxy_failure_type failure_type = +- LOGIN_PROXY_FAILURE_TYPE_AUTH; ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED; + if (!str_begins(line, "-ERR ")) { + client_send_reply(client, POP3_CMD_REPLY_ERROR, + AUTH_FAILED_MSG); +@@ -258,6 +258,8 @@ int pop3_proxy_parse_line(struct client + failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL; + line += 5; + } else { ++ if (str_begins(line, "-ERR [IN-USE]")) ++ failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED; + client_send_raw(client, t_strconcat(line, "\r\n", NULL)); + line += 5; + } +@@ -290,6 +292,7 @@ pop3_proxy_send_failure_reply(struct cli + break; + case LOGIN_PROXY_FAILURE_TYPE_INTERNAL_CONFIG: + case LOGIN_PROXY_FAILURE_TYPE_REMOTE_CONFIG: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED: + client_send_reply(client, POP3_CMD_REPLY_ERROR, + LOGIN_PROXY_FAILURE_MSG); + break; +@@ -297,7 +300,8 @@ pop3_proxy_send_failure_reply(struct cli + /* [SYS/TEMP] prefix is already in the reason string */ + client_send_reply(client, POP3_CMD_REPLY_ERROR, reason); + break; +- case LOGIN_PROXY_FAILURE_TYPE_AUTH: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED: + /* reply was already sent */ + break; + } +--- a/src/submission-login/client-authenticate.c ++++ b/src/submission-login/client-authenticate.c +@@ -135,6 +135,24 @@ void submission_client_auth_result(struc + */ + smtp_server_reply(cmd, 454, "4.7.0", "%s", text); + break; ++ case CLIENT_AUTH_RESULT_LIMIT_REACHED: ++ /* The user has too many concurrent connections. Reply with ++ 421 4.7.0: 421 means "service shutting down, closing ++ transmission channel" (RFC 5321 Section 4.2.1) and ++ signals the client that retrying on this same connection ++ is pointless. The proxy uses the 421 + 4.7.0 combination ++ to recognize this specifically as a connection-limit ++ response (rather than a generic 421 internal/shutdown ++ reply) and avoid reconnecting. ++ ++ Use reply_immediate() rather than the queued ++ smtp_server_reply() because the caller (sasl-server) ++ immediately tears the connection down after this returns, ++ which would abort a queued reply before it reaches the ++ wire. */ ++ smtp_server_connection_reply_immediate(subm_client->conn, ++ 421, "4.7.0 %s", text); ++ break; + case CLIENT_AUTH_RESULT_ABORTED: + /* RFC4954, Section 4: + +--- a/src/submission-login/client.c ++++ b/src/submission-login/client.c +@@ -122,6 +122,21 @@ static void submission_client_create(str + &smtp_set, &smtp_callbacks, subm_client); + } + ++static void ++submission_client_disconnect(struct client *client, const char *reason) ++{ ++ struct submission_client *subm_client = ++ container_of(client, struct submission_client, common); ++ ++ /* If the smtp-server connection is already in its close cascade (i.e. ++ we're being called via its conn_disconnect callback), skip closing ++ it again. Doing so would null subm_client->conn and prevent the ++ conn_free callback from invoking client_destroy(). */ ++ if (subm_client->conn != NULL && ++ !smtp_server_connection_is_closed(subm_client->conn)) ++ smtp_server_connection_close(&subm_client->conn, reason); ++} ++ + static void submission_client_destroy(struct client *client) + { + struct submission_client *subm_client = +@@ -285,6 +300,7 @@ static const struct smtp_server_callback + static struct client_vfuncs submission_client_vfuncs = { + .alloc = submission_client_alloc, + .create = submission_client_create, ++ .disconnect = submission_client_disconnect, + .destroy = submission_client_destroy, + .notify_auth_ready = submission_client_notify_auth_ready, + .notify_disconnect = submission_client_notify_disconnect, +--- a/src/submission-login/submission-proxy.c ++++ b/src/submission-login/submission-proxy.c +@@ -626,8 +626,22 @@ int submission_proxy_parse_line(struct c + shouldn't be a real problem since of course everyone will + be using only Dovecot as their backend :) */ + enum login_proxy_failure_type failure_type = +- LOGIN_PROXY_FAILURE_TYPE_AUTH; +- if ((status / 100) == 4) ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED; ++ if (status == 421) { ++ /* The backend won't accept further AUTH attempts on this ++ connection. If it signaled 4.7.0, the user's connection ++ limit (mail_max_userip_connections) was reached; report ++ that specifically. Otherwise treat as a generic auth ++ reply (e.g. backend shutting down). The reply was ++ prepared from the backend's 421 line; forward it to the ++ client and detach the AUTH command. */ ++ failure_type = (null_strcmp(enh_code, "4.7.0") == 0) ? ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED : ++ LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED; ++ i_assert(subm_client->proxy_reply != NULL); ++ smtp_server_reply_submit(subm_client->proxy_reply); ++ subm_client->pending_auth = NULL; ++ } else if ((status / 100) == 4) + failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL; + else { + i_assert((status / 100) != 2); +@@ -669,6 +683,7 @@ submission_proxy_send_failure_reply(stru + case LOGIN_PROXY_FAILURE_TYPE_REMOTE: + case LOGIN_PROXY_FAILURE_TYPE_REMOTE_CONFIG: + case LOGIN_PROXY_FAILURE_TYPE_PROTOCOL: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_NOT_REPLIED: + i_assert(cmd != NULL); + subm_client->pending_auth = NULL; + smtp_server_reply(cmd, 454, "4.7.0", LOGIN_PROXY_FAILURE_MSG); +@@ -680,7 +695,8 @@ submission_proxy_send_failure_reply(stru + i_assert(subm_client->proxy_reply != NULL); + smtp_server_reply_submit(subm_client->proxy_reply); + break; +- case LOGIN_PROXY_FAILURE_TYPE_AUTH: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED: ++ case LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED: + /* reply was already sent */ + i_assert(cmd == NULL); + break; diff --git a/mail/dovecot/patches/224-CVE-2026-40018.patch b/mail/dovecot/patches/224-CVE-2026-40018.patch new file mode 100644 index 0000000000..c9ea28e71c --- /dev/null +++ b/mail/dovecot/patches/224-CVE-2026-40018.patch @@ -0,0 +1,923 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-40018 + +Upstream commits: + lib-sql: sql-api - Implement async calls for drivers that can't + https://github.com/dovecot/core/commit/a78c015eae67a891a0c14b5434dd1f99838ae4cc + lib-sql: Add sql_result_new_error() helper + https://github.com/dovecot/core/commit/769ad693450742ece44733e64a64122ab2843462 + lib-sql: Extract sql_query_callback_delayed() helper + https://github.com/dovecot/core/commit/37da0240a316bd409d21b303f0a7e8627afd0789 + lib-sql: Add sql_commit_schedule_delayed() helper + https://github.com/dovecot/core/commit/3f9a9f117220b92edb4df0e9ef020092cdf29132 + lib-sql: Make escape_string return int with error_r, fail instead of unsafe fallback + https://github.com/dovecot/core/commit/f6bff126e890499214567cf8de2bf0eef3b0b7dd + auth: passdb_sql: connect before expanding query variables + https://github.com/dovecot/core/commit/77bc7af4cf6e788484423916ebf83b85338f621e + lib-sql: Run sql statement queries in their own data stack frame + https://github.com/dovecot/core/commit/19572f9b36f3b612af105b0eef0f8a0cca398a53 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +Adjusted for this version: + - conflicts in driver-mysql.c, sql-api-private.h, sql-api.c, + driver-cassandra.c resolved following upstream f6bff126 (2.3.21 has + sql_statement_get_log_query and no_log_expanded_values) + +--- a/src/auth/passdb-sql.c ++++ b/src/auth/passdb-sql.c +@@ -142,8 +142,17 @@ passdb_sql_escape(const char *str, const + { + struct passdb_module *_module = auth_request->passdb->passdb; + struct sql_passdb_module *module = (struct sql_passdb_module *)_module; ++ struct auth_request *req = (struct auth_request *)auth_request; ++ const char *output, *error; + +- return sql_escape_string(module->conn->db, str); ++ if (sql_escape_string(module->conn->db, str, &output, &error) < 0) { ++ req->failed = TRUE; ++ req->internal_failure = TRUE; ++ auth_request_log_error(req, AUTH_SUBSYS_DB, ++ "Could not escape string: %s", error == NULL ? "?" : error); ++ return ""; ++ } ++ return output; + } + + static void sql_lookup_pass(struct passdb_sql_request *sql_request) +@@ -153,6 +162,14 @@ static void sql_lookup_pass(struct passd + struct sql_passdb_module *module = (struct sql_passdb_module *)_module; + const char *query, *error; + ++ if (sql_connect(module->conn->db) < 0) { ++ e_error(authdb_event(sql_request->auth_request), ++ "Not connected to database"); ++ sql_request->callback.verify_plain( ++ PASSDB_RESULT_INTERNAL_FAILURE, ++ sql_request->auth_request); ++ return; ++ } + if (t_auth_request_var_expand(module->conn->set.password_query, + sql_request->auth_request, + passdb_sql_escape, &query, &error) <= 0) { +--- a/src/auth/userdb-sql.c ++++ b/src/auth/userdb-sql.c +@@ -94,8 +94,17 @@ userdb_sql_escape(const char *str, const + struct userdb_module *_module = auth_request->userdb->userdb; + struct sql_userdb_module *module = + (struct sql_userdb_module *)_module; ++ struct auth_request *req = (struct auth_request *)auth_request; ++ const char *output, *error; + +- return sql_escape_string(module->conn->db, str); ++ if (sql_escape_string(module->conn->db, str, &output, &error) < 0) { ++ req->failed = TRUE; ++ req->internal_failure = TRUE; ++ auth_request_log_error(req, AUTH_SUBSYS_DB, ++ "Could not escape string: %s", error == NULL ? "?" : error); ++ return ""; ++ } ++ return output; + } + + static void userdb_sql_lookup(struct auth_request *auth_request, +--- a/src/lib-sql/driver-cassandra.c ++++ b/src/lib-sql/driver-cassandra.c +@@ -572,22 +572,26 @@ static void driver_cassandra_disconnect( + driver_cassandra_close(db, "Disconnected"); + } + +-static const char * ++static int + driver_cassandra_escape_string(struct sql_db *db ATTR_UNUSED, +- const char *string) ++ const char *string, const char **output_r, ++ const char **error_r ATTR_UNUSED) + { + string_t *escaped; + unsigned int i; + +- if (strchr(string, '\'') == NULL) +- return string; ++ if (strchr(string, '\'') == NULL) { ++ *output_r = string; ++ return 0; ++ } + escaped = t_str_new(strlen(string)+10); + for (i = 0; string[i] != '\0'; i++) { + if (string[i] == '\'') + str_append_c(escaped, '\''); + str_append_c(escaped, string[i]); + } +- return str_c(escaped); ++ *output_r = str_c(escaped); ++ return 0; + } + + static int driver_cassandra_parse_connect_string(struct cassandra_db *db, +@@ -1985,8 +1989,14 @@ driver_cassandra_transaction_commit(stru + } + + /* just a single query, send it */ +- const char *query = ctx->query != NULL ? +- ctx->query : sql_statement_get_query(&ctx->stmt->stmt); ++ const char *query, *error; ++ if (ctx->query != NULL) ++ query = ctx->query; ++ else if (sql_statement_get_query(&ctx->stmt->stmt, ++ &query, &error) < 0) { ++ transaction_set_failed(ctx, error); ++ return; ++ } + if (strncasecmp(query, "DELETE ", 7) == 0) + query_type = CASSANDRA_QUERY_TYPE_DELETE; + else +@@ -2430,7 +2440,13 @@ driver_cassandra_statement_query(struct + struct cassandra_sql_statement *stmt = + (struct cassandra_sql_statement *)_stmt; + struct cassandra_db *db = (struct cassandra_db *)_stmt->db; +- const char *query = sql_statement_get_query(_stmt); ++ const char *query, *error; ++ if (sql_statement_get_query(_stmt, &query, &error) < 0) { ++ stmt->result->error = i_strdup(error); ++ result_finish(stmt->result); ++ pool_unref(&_stmt->pool); ++ return; ++ } + bool is_prepared = stmt->cass_stmt != NULL || stmt->prep != NULL; + + stmt->result = driver_cassandra_query_init(db, +@@ -2482,7 +2498,13 @@ driver_cassandra_update_stmt(struct sql_ + if (stmt->prep != NULL) + ctx->stmt = stmt; + else { +- ctx->query = i_strdup(sql_statement_get_query(_stmt)); ++ const char *query, *error; ++ if (sql_statement_get_query(_stmt, &query, &error) < 0) { ++ transaction_set_failed(ctx, error); ++ pool_unref(&_stmt->pool); ++ return; ++ } ++ ctx->query = i_strdup(query); + ctx->log_query = i_strdup(sql_statement_get_log_query(_stmt)); + ctx->query_timestamp = stmt->timestamp; + pool_unref(&_stmt->pool); +--- a/src/lib-sql/driver-mysql.c ++++ b/src/lib-sql/driver-mysql.c +@@ -357,8 +357,9 @@ static int driver_mysql_do_query(struct + return -1; + } + +-static const char * +-driver_mysql_escape_string(struct sql_db *_db, const char *string) ++static int ++driver_mysql_escape_string(struct sql_db *_db, const char *string, ++ const char **output_r, const char **error_r) + { + struct mysql_db *db = container_of(_db, struct mysql_db, api); + size_t len = strlen(string); +@@ -370,22 +371,15 @@ driver_mysql_escape_string(struct sql_db + } + + if (_db->state == SQL_DB_STATE_DISCONNECTED) { +- /* FIXME: we don't have a valid connection, so fallback +- to using default escaping. the next query will most +- likely fail anyway so it shouldn't matter that much +- what we return here.. Anyway, this API needs +- changing so that the escaping function could already +- fail the query reliably. */ +- to = t_buffer_get(len * 2 + 1); +- len = mysql_escape_string(to, string, len); +- t_buffer_alloc(len + 1); +- return to; ++ *error_r = SQL_ERRSTR_NOT_CONNECTED; ++ return -1; + } + + to = t_buffer_get(len * 2 + 1); + len = mysql_real_escape_string(db->mysql, to, string, len); + t_buffer_alloc(len + 1); +- return to; ++ *output_r = to; ++ return 0; + } + + static void driver_mysql_exec(struct sql_db *_db, const char *query) +--- a/src/lib-sql/driver-pgsql.c ++++ b/src/lib-sql/driver-pgsql.c +@@ -570,8 +570,9 @@ static void do_query(struct pgsql_result + } + } + +-static const char * +-driver_pgsql_escape_string(struct sql_db *_db, const char *string) ++static int ++driver_pgsql_escape_string(struct sql_db *_db, const char *string, ++ const char **output_r, const char **error_r) + { + struct pgsql_db *db = (struct pgsql_db *)_db; + size_t len = strlen(string); +@@ -587,14 +588,24 @@ driver_pgsql_escape_string(struct sql_db + + to = t_buffer_get(len * 2 + 1); + len = PQescapeStringConn(db->pg, to, string, len, &error); +- } else +-#endif +- { +- to = t_buffer_get(len * 2 + 1); +- len = PQescapeString(to, string, len); ++ if (error != 0) { ++ *error_r = last_error(db); ++ return -1; ++ } ++ t_buffer_alloc(len + 1); ++ *output_r = to; ++ return 0; ++ } else { ++ *error_r = SQL_ERRSTR_NOT_CONNECTED; ++ return -1; + } ++#else ++ to = t_buffer_get(len * 2 + 1); ++ len = PQescapeString(to, string, len); + t_buffer_alloc(len + 1); +- return to; ++ *output_r = to; ++ return 0; ++#endif + } + + static void exec_callback(struct sql_result *_result, +--- a/src/lib-sql/driver-sqlite.c ++++ b/src/lib-sql/driver-sqlite.c +@@ -108,17 +108,20 @@ static void driver_sqlite_deinit_v(struc + pool_unref(&db->pool); + } + +-static const char * ++static int + driver_sqlite_escape_string(struct sql_db *_db ATTR_UNUSED, +- const char *string) ++ const char *string, const char **output_r, ++ const char **error_r ATTR_UNUSED) + { + const char *p; + char *dest, *destbegin; + + /* find the first ' */ + for (p = string; *p != '\''; p++) { +- if (*p == '\0') +- return t_strdup_noconst(string); ++ if (*p == '\0') { ++ *output_r = t_strdup_noconst(string); ++ return 0; ++ } + } + + /* @UNSAFE: escape ' with '' */ +@@ -135,7 +138,8 @@ driver_sqlite_escape_string(struct sql_d + *dest++ = '\0'; + t_buffer_alloc(dest - destbegin); + +- return destbegin; ++ *output_r = destbegin; ++ return 0; + } + + static void driver_sqlite_result_log(const struct sql_result *result, const char *query) +--- a/src/lib-sql/driver-sqlpool.c ++++ b/src/lib-sql/driver-sqlpool.c +@@ -619,8 +619,9 @@ static void driver_sqlpool_disconnect(st + driver_sqlpool_abort_requests(db); + } + +-static const char * +-driver_sqlpool_escape_string(struct sql_db *_db, const char *string) ++static int ++driver_sqlpool_escape_string(struct sql_db *_db, const char *string, ++ const char **output_r, const char **error_r) + { + struct sqlpool_db *db = (struct sqlpool_db *)_db; + const struct sqlpool_connection *conns; +@@ -630,11 +631,12 @@ driver_sqlpool_escape_string(struct sql_ + conns = array_get(&db->all_connections, &count); + for (i = 0; i < count; i++) { + if (SQL_DB_IS_READY(conns[i].db)) +- return sql_escape_string(conns[i].db, string); ++ return sql_escape_string(conns[i].db, string, ++ output_r, error_r); + } + /* no ready connections. just use the first one (we're guaranteed + to always have one) */ +- return sql_escape_string(conns[0].db, string); ++ return sql_escape_string(conns[0].db, string, output_r, error_r); + } + + static void driver_sqlpool_timeout(struct sqlpool_db *db) +--- a/src/lib-sql/driver-test.c ++++ b/src/lib-sql/driver-test.c +@@ -30,10 +30,12 @@ static struct sql_db *driver_test_sqlite + static void driver_test_deinit(struct sql_db *_db); + static int driver_test_connect(struct sql_db *_db); + static void driver_test_disconnect(struct sql_db *_db); +-static const char * +-driver_test_mysql_escape_string(struct sql_db *_db, const char *string); +-static const char * +-driver_test_escape_string(struct sql_db *_db, const char *string); ++static int ++driver_test_mysql_escape_string(struct sql_db *_db, const char *string, ++ const char **output_r, const char **error_r); ++static int ++driver_test_escape_string(struct sql_db *_db, const char *string, ++ const char **output_r, const char **error_r); + static void driver_test_exec(struct sql_db *_db, const char *query); + static void driver_test_query(struct sql_db *_db, const char *query, + sql_query_callback_t *callback, void *context); +@@ -226,9 +228,10 @@ static int driver_test_connect(struct sq + static void driver_test_disconnect(struct sql_db *_db ATTR_UNUSED) + { } + +-static const char * ++static int + driver_test_mysql_escape_string(struct sql_db *_db ATTR_UNUSED, +- const char *string) ++ const char *string, const char **output_r, ++ const char **error_r ATTR_UNUSED) + { + string_t *esc = t_str_new(strlen(string)); + for(const char *ptr = string; *ptr != '\0'; ptr++) { +@@ -237,13 +240,17 @@ driver_test_mysql_escape_string(struct s + str_append_c(esc, '\\'); + str_append_c(esc, *ptr); + } +- return str_c(esc); ++ *output_r = str_c(esc); ++ return 0; + } + +-static const char * +-driver_test_escape_string(struct sql_db *_db ATTR_UNUSED, const char *string) ++static int ++driver_test_escape_string(struct sql_db *_db ATTR_UNUSED, const char *string, ++ const char **output_r, ++ const char **error_r ATTR_UNUSED) + { +- return string; ++ *output_r = string; ++ return 0; + } + + static void driver_test_exec(struct sql_db *_db, const char *query) +--- a/src/lib-sql/sql-api-private.h ++++ b/src/lib-sql/sql-api-private.h +@@ -76,14 +76,19 @@ struct sql_db_vfuncs { + + int (*connect)(struct sql_db *db); + void (*disconnect)(struct sql_db *db); +- const char *(*escape_string)(struct sql_db *db, const char *string); ++ int (*escape_string)(struct sql_db *db, const char *string, ++ const char **output_r, const char **error_r); + + void (*exec)(struct sql_db *db, const char *query); ++ /* Only implement this if the driver can really do asynchronous callbacks, ++ otherwise let sql API handle it. */ + void (*query)(struct sql_db *db, const char *query, + sql_query_callback_t *callback, void *context); + struct sql_result *(*query_s)(struct sql_db *db, const char *query); + + struct sql_transaction_context *(*transaction_begin)(struct sql_db *db); ++ /* Only implement this if the driver can really do asynchronous callbacks, ++ otherwise let sql API handle it. */ + void (*transaction_commit)(struct sql_transaction_context *ctx, + sql_commit_callback_t *callback, + void *context); +@@ -140,6 +145,9 @@ struct sql_db { + struct event *event; + HASH_TABLE(char *, struct sql_prepared_statement *) prepared_stmt_hash; + ++ struct sql_query_result_delayed *query_delayed_list; ++ struct sql_commit_result_delayed *commit_delayed_list; ++ + enum sql_db_state state; + /* last time we started connecting to this server + (which may or may not have succeeded) */ +@@ -192,6 +200,7 @@ struct sql_statement { + pool_t pool; + const char *query_template; + ARRAY_TYPE(const_string) args; ++ ARRAY(bool) args_need_escaping; + + /* Tell the driver to not log this query with expanded values. */ + bool no_log_expanded_values; +@@ -227,6 +236,8 @@ struct sql_transaction_context { + + /* commit() must use this query list if head is non-NULL. */ + struct sql_transaction_query *head, *tail; ++ ++ char *failed_error; + }; + + ARRAY_DEFINE_TYPE(sql_drivers, const struct sql_db *); +@@ -245,7 +256,8 @@ void sql_db_set_state(struct sql_db *db, + void sql_transaction_add_query(struct sql_transaction_context *ctx, pool_t pool, + const char *query, unsigned int *affected_rows); + const char *sql_statement_get_log_query(struct sql_statement *stmt); +-const char *sql_statement_get_query(struct sql_statement *stmt); ++int sql_statement_get_query(struct sql_statement *stmt, ++ const char **query_r, const char **error_r); + + void sql_connection_log_finished(struct sql_db *db); + struct event_passthrough * +--- a/src/lib-sql/sql-api.c ++++ b/src/lib-sql/sql-api.c +@@ -4,12 +4,35 @@ + #include "array.h" + #include "ioloop.h" + #include "hash.h" ++#include "llist.h" + #include "str.h" + #include "time-util.h" + #include "sql-api-private.h" + + #include + ++struct sql_query_result_delayed { ++ struct sql_query_result_delayed *prev, *next; ++ ++ struct sql_db *db; ++ struct timeout *to; ++ ++ struct sql_result *result; ++ sql_query_callback_t *callback; ++ void *context; ++}; ++ ++struct sql_commit_result_delayed { ++ struct sql_commit_result_delayed *prev, *next; ++ ++ struct sql_db *db; ++ struct timeout *to; ++ ++ char *error; ++ sql_commit_callback_t *callback; ++ void *context; ++}; ++ + struct event_category event_category_sql = { + .name = "sql", + }; +@@ -17,6 +40,65 @@ struct event_category event_category_sql + struct sql_db_module_register sql_db_module_register = { 0 }; + ARRAY_TYPE(sql_drivers) sql_drivers; + ++static void sql_query_delayed_callback(struct sql_query_result_delayed *cb); ++static void sql_commit_delayed_callback(struct sql_commit_result_delayed *cb); ++ ++struct sql_result_error { ++ struct sql_result result; ++ char *error; ++}; ++ ++static void sql_result_error_free(struct sql_result *_result) ++{ ++ struct sql_result_error *result = ++ container_of(_result, struct sql_result_error, result); ++ i_free(result->error); ++ i_free(result); ++} ++ ++static int sql_result_error_next_row(struct sql_result *result ATTR_UNUSED) ++{ ++ return -1; ++} ++ ++static const char * ++sql_result_error_get_error(struct sql_result *_result) ++{ ++ struct sql_result_error *result = ++ container_of(_result, struct sql_result_error, result); ++ return result->error; ++} ++ ++static const struct sql_result_vfuncs sql_result_error_vfuncs = { ++ .free = sql_result_error_free, ++ .next_row = sql_result_error_next_row, ++ .get_error = sql_result_error_get_error, ++}; ++ ++static struct sql_result *sql_result_new_error(const char *error) ++{ ++ struct sql_result_error *result = i_new(struct sql_result_error, 1); ++ result->result.v = sql_result_error_vfuncs; ++ result->result.failed = TRUE; ++ result->result.refcount = 1; ++ result->error = i_strdup(error); ++ return &result->result; ++} ++ ++static void ++sql_query_callback_delayed(struct sql_db *db, struct sql_result *result, ++ sql_query_callback_t *callback, void *context) ++{ ++ struct sql_query_result_delayed *cb = ++ i_new(struct sql_query_result_delayed, 1); ++ cb->db = db; ++ cb->result = result; ++ cb->callback = callback; ++ cb->context = context; ++ cb->to = timeout_add_short(0, sql_query_delayed_callback, cb); ++ DLLIST_PREPEND(&db->query_delayed_list, cb); ++} ++ + void sql_drivers_init(void) + { + i_array_init(&sql_drivers, 8); +@@ -195,15 +277,26 @@ int sql_connect(struct sql_db *db) + return db->v.connect(db); + } + ++static void sql_call_delayed_callbacks(struct sql_db *db) ++{ ++ /* flush any pending results */ ++ while (db->query_delayed_list != NULL) ++ sql_query_delayed_callback(db->query_delayed_list); ++ while (db->commit_delayed_list != NULL) ++ sql_commit_delayed_callback(db->commit_delayed_list); ++} ++ + void sql_disconnect(struct sql_db *db) + { + timeout_remove(&db->to_reconnect); ++ sql_call_delayed_callbacks(db); + db->v.disconnect(db); + } + +-const char *sql_escape_string(struct sql_db *db, const char *string) ++int sql_escape_string(struct sql_db *db, const char *string, ++ const char **output_r, const char **error_r) + { +- return db->v.escape_string(db, string); ++ return db->v.escape_string(db, string, output_r, error_r); + } + + const char *sql_escape_blob(struct sql_db *db, +@@ -217,11 +310,26 @@ void sql_exec(struct sql_db *db, const c + db->v.exec(db, query); + } + ++static void sql_query_delayed_callback(struct sql_query_result_delayed *cb) ++{ ++ timeout_remove(&cb->to); ++ DLLIST_REMOVE(&cb->db->query_delayed_list, cb); ++ cb->callback(cb->result, cb->context); ++ sql_result_unref(cb->result); ++ i_free(cb); ++} ++ + #undef sql_query + void sql_query(struct sql_db *db, const char *query, + sql_query_callback_t *callback, void *context) + { +- db->v.query(db, query, callback, context); ++ if (db->v.query != NULL) { ++ db->v.query(db, query, callback, context); ++ return; ++ } ++ ++ sql_query_callback_delayed(db, sql_query_s(db, query), ++ callback, context); + } + + struct sql_result *sql_query_s(struct sql_db *db, const char *query) +@@ -250,18 +358,24 @@ default_sql_statement_init_prepared(stru + + const char *sql_statement_get_log_query(struct sql_statement *stmt) + { ++ const char *query, *error; + if (stmt->no_log_expanded_values) + return stmt->query_template; +- return sql_statement_get_query(stmt); ++ if (sql_statement_get_query(stmt, &query, &error) < 0) ++ return stmt->query_template; ++ return query; + } + +-const char *sql_statement_get_query(struct sql_statement *stmt) ++int sql_statement_get_query(struct sql_statement *stmt, ++ const char **query_r, const char **error_r) + { + string_t *query = t_str_new(128); + const char *const *args; +- unsigned int i, args_count, arg_pos = 0; ++ const bool *need_escaping_flags; ++ unsigned int i, need_escaping_count, args_count, arg_pos = 0; + + args = array_get(&stmt->args, &args_count); ++ need_escaping_flags = array_get(&stmt->args_need_escaping, &need_escaping_count); + + for (i = 0; stmt->query_template[i] != '\0'; i++) { + if (stmt->query_template[i] == '?') { +@@ -270,7 +384,18 @@ const char *sql_statement_get_query(stru + i_panic("lib-sql: Missing bind for arg #%u in statement: %s", + arg_pos, stmt->query_template); + } +- str_append(query, args[arg_pos++]); ++ if (arg_pos < need_escaping_count && need_escaping_flags[arg_pos]) { ++ const char *escaped; ++ if (sql_escape_string(stmt->db, args[arg_pos], ++ &escaped, error_r) < 0) ++ return -1; ++ str_append_c(query, '\''); ++ str_append(query, escaped); ++ str_append_c(query, '\''); ++ } else { ++ str_append(query, args[arg_pos]); ++ } ++ arg_pos++; + } else { + str_append_c(query, stmt->query_template[i]); + } +@@ -279,23 +404,36 @@ const char *sql_statement_get_query(stru + i_panic("lib-sql: Too many bind args (%u) for statement: %s", + args_count, stmt->query_template); + } +- return str_c(query); ++ *query_r = str_c(query); ++ return 0; + } + + static void + default_sql_statement_query(struct sql_statement *stmt, + sql_query_callback_t *callback, void *context) + { +- sql_query(stmt->db, sql_statement_get_query(stmt), +- callback, context); ++ const char *query, *error; ++ if (sql_statement_get_query(stmt, &query, &error) < 0) { ++ sql_query_callback_delayed(stmt->db, ++ sql_result_new_error(error), ++ callback, context); ++ pool_unref(&stmt->pool); ++ return; ++ } ++ sql_query(stmt->db, query, callback, context); + pool_unref(&stmt->pool); + } + + static struct sql_result * + default_sql_statement_query_s(struct sql_statement *stmt) + { +- struct sql_result *result = +- sql_query_s(stmt->db, sql_statement_get_query(stmt)); ++ const char *query, *error; ++ if (sql_statement_get_query(stmt, &query, &error) < 0) { ++ struct sql_result *result = sql_result_new_error(error); ++ pool_unref(&stmt->pool); ++ return result; ++ } ++ struct sql_result *result = sql_query_s(stmt->db, query); + pool_unref(&stmt->pool); + return result; + } +@@ -304,8 +442,14 @@ static void default_sql_update_stmt(stru + struct sql_statement *stmt, + unsigned int *affected_rows) + { +- ctx->db->v.update(ctx, sql_statement_get_query(stmt), +- affected_rows); ++ const char *query, *error; ++ if (sql_statement_get_query(stmt, &query, &error) < 0) { ++ if (ctx->failed_error == NULL) ++ ctx->failed_error = i_strdup(error); ++ pool_unref(&stmt->pool); ++ return; ++ } ++ ctx->db->v.update(ctx, query, affected_rows); + pool_unref(&stmt->pool); + } + +@@ -344,6 +488,7 @@ sql_statement_init_fields(struct sql_sta + { + stmt->db = db; + p_array_init(&stmt->args, stmt->pool, 8); ++ p_array_init(&stmt->args_need_escaping, stmt->pool, 8); + } + + struct sql_statement * +@@ -402,10 +547,10 @@ void sql_statement_set_no_log_expanded_v + void sql_statement_bind_str(struct sql_statement *stmt, + unsigned int column_idx, const char *value) + { +- const char *escaped_value = +- p_strdup_printf(stmt->pool, "'%s'", +- sql_escape_string(stmt->db, value)); +- array_idx_set(&stmt->args, column_idx, &escaped_value); ++ const char *value_dup = p_strdup(stmt->pool, value); ++ array_idx_set(&stmt->args, column_idx, &value_dup); ++ bool needs_escaping = TRUE; ++ array_idx_set(&stmt->args_need_escaping, column_idx, &needs_escaping); + + if (stmt->db->v.statement_bind_str != NULL) + stmt->db->v.statement_bind_str(stmt, column_idx, value); +@@ -441,23 +586,39 @@ void sql_statement_query(struct sql_stat + sql_query_callback_t *callback, void *context) + { + struct sql_statement *stmt = *_stmt; +- + *_stmt = NULL; +- if (stmt->db->v.statement_query != NULL) +- stmt->db->v.statement_query(stmt, callback, context); +- else +- default_sql_statement_query(stmt, callback, context); ++ ++ T_BEGIN { ++ if (stmt->db->v.statement_query != NULL) ++ stmt->db->v.statement_query(stmt, callback, context); ++ else if (stmt->db->v.statement_query_s != NULL) { ++ struct sql_db *db = stmt->db; ++ struct sql_query_result_delayed *cb = ++ i_new(struct sql_query_result_delayed, 1); ++ cb->db = db; ++ cb->callback = callback; ++ cb->context = context; ++ cb->result = sql_statement_query_s(&stmt); ++ cb->to = timeout_add_short(0, sql_query_delayed_callback, cb); ++ DLLIST_PREPEND(&db->query_delayed_list, cb); ++ } else ++ default_sql_statement_query(stmt, callback, context); ++ } T_END; + } + + struct sql_result *sql_statement_query_s(struct sql_statement **_stmt) + { + struct sql_statement *stmt = *_stmt; ++ struct sql_result *result; + + *_stmt = NULL; +- if (stmt->db->v.statement_query_s != NULL) +- return stmt->db->v.statement_query_s(stmt); +- else +- return default_sql_statement_query_s(stmt); ++ T_BEGIN { ++ if (stmt->db->v.statement_query_s != NULL) ++ result = stmt->db->v.statement_query_s(stmt); ++ else ++ result = default_sql_statement_query_s(stmt); ++ } T_END; ++ return result; + } + + void sql_result_ref(struct sql_result *result) +@@ -688,14 +849,54 @@ struct sql_transaction_context *sql_tran + return db->v.transaction_begin(db); + } + ++static void sql_commit_delayed_callback(struct sql_commit_result_delayed *cb) ++{ ++ struct sql_commit_result result = { ++ .error = cb->error, ++ }; ++ timeout_remove(&cb->to); ++ DLLIST_REMOVE(&cb->db->commit_delayed_list, cb); ++ cb->callback(&result, cb->context); ++ i_free(cb->error); ++ i_free(cb); ++} ++ ++static void ++sql_commit_schedule_delayed(struct sql_db *db, const char *error, ++ sql_commit_callback_t *callback, void *context) ++{ ++ struct sql_commit_result_delayed *cb = i_new(struct sql_commit_result_delayed, 1); ++ cb->db = db; ++ cb->error = i_strdup(error); ++ cb->callback = callback; ++ cb->context = context; ++ cb->to = timeout_add_short(0, sql_commit_delayed_callback, cb); ++ DLLIST_PREPEND(&db->commit_delayed_list, cb); ++} ++ + #undef sql_transaction_commit + void sql_transaction_commit(struct sql_transaction_context **_ctx, + sql_commit_callback_t *callback, void *context) + { + struct sql_transaction_context *ctx = *_ctx; +- ++ struct sql_db *db = ctx->db; + *_ctx = NULL; +- ctx->db->v.transaction_commit(ctx, callback, context); ++ ++ if (ctx->failed_error != NULL) { ++ sql_commit_schedule_delayed(db, ctx->failed_error, callback, context); ++ i_free(ctx->failed_error); ++ ctx->db->v.transaction_rollback(ctx); ++ return; ++ } ++ ++ if (ctx->db->v.transaction_commit != NULL) { ++ ctx->db->v.transaction_commit(ctx, callback, context); ++ return; ++ } ++ ++ const char *error = NULL; ++ ctx->db->v.transaction_commit_s(ctx, &error); ++ sql_commit_schedule_delayed(db, error, callback, context); + } + + int sql_transaction_commit_s(struct sql_transaction_context **_ctx, +@@ -704,6 +905,12 @@ int sql_transaction_commit_s(struct sql_ + struct sql_transaction_context *ctx = *_ctx; + + *_ctx = NULL; ++ if (ctx->failed_error != NULL) { ++ *error_r = t_strdup(ctx->failed_error); ++ i_free(ctx->failed_error); ++ ctx->db->v.transaction_rollback(ctx); ++ return -1; ++ } + return ctx->db->v.transaction_commit_s(ctx, error_r); + } + +@@ -712,6 +919,7 @@ void sql_transaction_rollback(struct sql + struct sql_transaction_context *ctx = *_ctx; + + *_ctx = NULL; ++ i_free(ctx->failed_error); + ctx->db->v.transaction_rollback(ctx); + } + +@@ -726,10 +934,12 @@ void sql_update_stmt(struct sql_transact + struct sql_statement *stmt = *_stmt; + + *_stmt = NULL; +- if (ctx->db->v.update_stmt != NULL) +- ctx->db->v.update_stmt(ctx, stmt, NULL); +- else +- default_sql_update_stmt(ctx, stmt, NULL); ++ T_BEGIN { ++ if (ctx->db->v.update_stmt != NULL) ++ ctx->db->v.update_stmt(ctx, stmt, NULL); ++ else ++ default_sql_update_stmt(ctx, stmt, NULL); ++ } T_END; + } + + void sql_update_get_rows(struct sql_transaction_context *ctx, const char *query, +@@ -745,10 +955,12 @@ void sql_update_stmt_get_rows(struct sql + struct sql_statement *stmt = *_stmt; + + *_stmt = NULL; +- if (ctx->db->v.update_stmt != NULL) +- ctx->db->v.update_stmt(ctx, stmt, affected_rows); +- else +- default_sql_update_stmt(ctx, stmt, affected_rows); ++ T_BEGIN { ++ if (ctx->db->v.update_stmt != NULL) ++ ctx->db->v.update_stmt(ctx, stmt, affected_rows); ++ else ++ default_sql_update_stmt(ctx, stmt, affected_rows); ++ } T_END; + } + + void sql_db_set_state(struct sql_db *db, enum sql_db_state state) +@@ -831,6 +1043,7 @@ void sql_wait(struct sql_db *db) + { + if (db->v.wait != NULL) + db->v.wait(db); ++ sql_call_delayed_callbacks(db); + } + + +--- a/src/lib-sql/sql-api.h ++++ b/src/lib-sql/sql-api.h +@@ -112,7 +112,8 @@ int sql_connect(struct sql_db *db); + void sql_disconnect(struct sql_db *db); + + /* Escape the given string if needed and return it. */ +-const char *sql_escape_string(struct sql_db *db, const char *string); ++int sql_escape_string(struct sql_db *db, const char *string, ++ const char **output_r, const char **error_r); + /* Escape the given data as a string. */ + const char *sql_escape_blob(struct sql_db *db, + const unsigned char *data, size_t size); +@@ -121,7 +122,7 @@ const char *sql_escape_blob(struct sql_d + void sql_exec(struct sql_db *db, const char *query); + /* Execute SQL query and return result in callback. If fields list is given, + the returned fields are validated to be of correct type, and you can use +- sql_result_next_row_get() */ ++ sql_result_next_row_get(). The callback is never called immediately. */ + void sql_query(struct sql_db *db, const char *query, + sql_query_callback_t *callback, void *context); + #define sql_query(db, query, callback, context) \ +@@ -220,7 +221,7 @@ enum sql_result_error_type sql_result_ge + /* Begin a new transaction. Currently you're limited to only one open + transaction at a time. */ + struct sql_transaction_context *sql_transaction_begin(struct sql_db *db); +-/* Commit transaction. */ ++/* Commit transaction. The callback is never called immediately. */ + void sql_transaction_commit(struct sql_transaction_context **ctx, + sql_commit_callback_t *callback, void *context); + #define sql_transaction_commit(ctx, callback, context) \ diff --git a/mail/dovecot/patches/225-CVE-2026-40205_CVE-2026-73208.patch b/mail/dovecot/patches/225-CVE-2026-40205_CVE-2026-73208.patch new file mode 100644 index 0000000000..cb02e3a2c6 --- /dev/null +++ b/mail/dovecot/patches/225-CVE-2026-40205_CVE-2026-73208.patch @@ -0,0 +1,765 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Aki Tuomi +Subject: [PATCH] Fix CVE-2026-40205, CVE-2026-73208 + +Upstream commits: + lib-oauth2: Fix recursive field copying + https://github.com/dovecot/core/commit/84be751f5f7d46d34f9a45a00076a6c36324a850 + auth: db-oauth2: Reduce nesting in token_in_scope via early return + https://github.com/dovecot/core/commit/6bce5fdab7c1d6da569db6d5c9f48e37573fbdd8 + auth: db-oauth2: Fix scope check to require all configured scopes + https://github.com/dovecot/core/commit/de6f2c4e2393f856601074ec152dfa6c141042c4 + auth: db-oauth2: Add oauth2_audience setting, deprecate aud-as-scope fallback + https://github.com/dovecot/core/commit/d9aa14dcb24b5d35f1799d6da9c2ff286cca65b6 + auth: db-oauth2: Add local validation unit tests + https://github.com/dovecot/core/commit/e953375267123848ff3969048c6cfc056f104860 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +Left out, already part of 2.3.21.1: + lib-oauth2: Ensure aud field has client_id when set. + https://github.com/dovecot/core/commit/c2dc2f0fca2a9fc15d94281993dba6ccaf62e4b5 + lib-oauth2: Validate scope when configured + https://github.com/dovecot/core/commit/9bb7dd0ceb504637a0892a44f1ed522df79e6cbb + oauth: Accept multiple entries in aud field + https://github.com/dovecot/core/commit/addc1914826c0c4ef754da83ea20fed8e401197a + +--- a/src/auth/Makefile.am ++++ b/src/auth/Makefile.am +@@ -282,6 +282,7 @@ test_auth_SOURCES = \ + test-username-filter.c \ + test-db-dict.c \ + test-lua.c \ ++ test-db-oauth2.c \ + test-mock.c \ + test-main.c + +--- a/src/auth/db-oauth2.c ++++ b/src/auth/db-oauth2.c +@@ -20,6 +20,7 @@ + #include "db-oauth2.h" + #include "dcrypt.h" + #include "dict.h" ++#include + + #include + +@@ -32,6 +33,8 @@ struct passdb_oauth2_settings { + const char *introspection_url; + /* expected scope, optional */ + const char *scope; ++ /* expected audience(s) (aud claim), optional */ ++ const char *audience; + /* mode of introspection, one of get, get-auth, post + - get: append token to url + - get-auth: send token with header Authorization: Bearer token +@@ -114,11 +117,15 @@ static struct db_oauth2 *db_oauth2_head + #define DEF_BOOL(name) DEF_STRUCT_BOOL(name, passdb_oauth2_settings) + #define DEF_INT(name) DEF_STRUCT_INT(name, passdb_oauth2_settings) + ++#define WARN_AUD_FALLBACK_PERIOD 600 ++static time_t last_warned_aud_fallback = 0; ++ + static struct setting_def setting_defs[] = { + DEF_STR(tokeninfo_url), + DEF_STR(grant_url), + DEF_STR(introspection_url), + DEF_STR(scope), ++ DEF_STR(audience), + DEF_BOOL(force_introspection), + DEF_STR(introspection_mode), + DEF_STR(username_format), +@@ -157,6 +164,7 @@ static struct passdb_oauth2_settings def + .grant_url = "", + .introspection_url = "", + .scope = "", ++ .audience = "", + .force_introspection = FALSE, + .introspection_mode = "", + .username_format = "%Lu", +@@ -648,34 +656,78 @@ static bool + db_oauth2_token_in_scope(struct db_oauth2_request *req, + enum passdb_result *result_r, const char **error_r) + { +- if (*req->db->set.scope != '\0') { +- bool found = FALSE; +- const char *value = auth_fields_find(req->fields, "scope"); +- bool has_scope = value != NULL; +- if (!has_scope) +- value = auth_fields_find(req->fields, "aud"); +- e_debug(authdb_event(req->auth_request), +- "Token scope(s): %s", +- value); ++ if (*req->db->set.scope == '\0') ++ return TRUE; ++ ++ const char *value = auth_fields_find(req->fields, "scope"); ++ if (value == NULL && *req->db->set.audience == '\0') { ++ value = auth_fields_find(req->fields, "aud"); + if (value != NULL) { +- const char **wanted_scopes = +- t_strsplit_spaces(req->db->set.scope, " "); +- const char *const *entries = has_scope ? +- t_strsplit_spaces(value, " ") : +- t_strsplit_tabescaped(value); +- for (; !found && *wanted_scopes != NULL; wanted_scopes++) +- found = str_array_find(entries, *wanted_scopes); +- } +- if (!found) { +- *error_r = t_strdup_printf("Token is not valid for scope '%s'", +- req->db->set.scope); +- *result_r = PASSDB_RESULT_USER_DISABLED; +- return FALSE; ++ time_t t0 = time(NULL); ++ if (t0 - last_warned_aud_fallback > WARN_AUD_FALLBACK_PERIOD) { ++ e_warning(authdb_event(req->auth_request), ++ "Token has no 'scope' claim; falling back to " ++ "'aud' for scope check is deprecated - " ++ "use oauth2_audience instead"); ++ last_warned_aud_fallback = t0; ++ } + } + } ++ e_debug(authdb_event(req->auth_request), ++ "Token scope(s): %s", value); ++ ++ bool found = FALSE; ++ if (value != NULL && *value != '\0') { ++ const char **wanted_scopes = ++ t_strsplit_spaces(req->db->set.scope, " "); ++ const char **scopes = t_strsplit_spaces(value, " "); ++ found = TRUE; ++ for (; *wanted_scopes != NULL; wanted_scopes++) ++ if (!str_array_find(scopes, *wanted_scopes)) { ++ found = FALSE; ++ break; ++ } ++ } ++ if (!found) { ++ *error_r = t_strdup_printf("Token is not valid for scope '%s'", ++ req->db->set.scope); ++ *result_r = PASSDB_RESULT_USER_DISABLED; ++ return FALSE; ++ } + return TRUE; + } + ++static bool ++db_oauth2_token_in_audience(struct db_oauth2_request *req, ++ enum passdb_result *result_r, const char **error_r) ++{ ++ if (*req->db->set.audience == '\0') ++ return TRUE; ++ ++ const char *value = auth_fields_find(req->fields, "aud"); ++ e_debug(authdb_event(req->auth_request), ++ "Token audience(s): %s", value != NULL ? value : "(none)"); ++ ++ bool found = FALSE; ++ if (value != NULL && *value != '\0') { ++ const char **wanted = ++ t_strsplit_spaces(req->db->set.audience, " "); ++ const char *const *entries = t_strsplit_tabescaped(value); ++ found = TRUE; ++ for (; *wanted != NULL; wanted++) ++ if (!str_array_find(entries, *wanted)) { ++ found = FALSE; ++ break; ++ } ++ } ++ if (!found) { ++ *error_r = t_strdup_printf("Token audience does not include '%s'", ++ req->db->set.audience); ++ *result_r = PASSDB_RESULT_USER_DISABLED; ++ } ++ return found; ++} ++ + static void db_oauth2_process_fields(struct db_oauth2_request *req, + enum passdb_result *result_r, + const char **error_r) +@@ -685,6 +737,7 @@ static void db_oauth2_process_fields(str + if (db_oauth2_user_is_enabled(req, result_r, error_r) && + db_oauth2_validate_username(req, result_r, error_r) && + db_oauth2_token_in_scope(req, result_r, error_r) && ++ db_oauth2_token_in_audience(req, result_r, error_r) && + db_oauth2_template_export(req, result_r, error_r)) { + *result_r = PASSDB_RESULT_OK; + } else { +--- a/src/auth/test-auth.h ++++ b/src/auth/test-auth.h +@@ -17,6 +17,7 @@ void test_auth_request_fields(void); + void test_db_dict_parse_cache_key(void); + void test_username_filter(void); + void test_db_lua(void); ++void test_db_oauth2(void); + struct auth_passdb *passdb_mock(void); + void passdb_mock_mod_init(void); + void passdb_mock_mod_deinit(void); +--- /dev/null ++++ b/src/auth/test-db-oauth2.c +@@ -0,0 +1,376 @@ ++/* Copyright (c) 2026 Dovecot authors, see the included COPYING file */ ++ ++#include "test-auth.h" ++#include "auth-common.h" ++#include "auth-request.h" ++#include "auth-settings.h" ++#include "settings-parser.h" ++#include "db-oauth2.h" ++#include "passdb.h" ++#include "hmac.h" ++#include "sha2.h" ++#include "base64.h" ++#include "randgen.h" ++#include "str.h" ++#include "dict.h" ++#include "dict-private.h" ++ ++#include "mkdir-parents.h" ++#include "unlink-directory.h" ++#include "write-full.h" ++ ++#include ++#include ++#include ++ ++static char *test_dir = NULL, *test_key_dir = NULL; ++static buffer_t *test_hmac_key = NULL; ++static struct auth_settings set; ++ ++static void write_key_file(const char *path, const buffer_t *key) ++{ ++ const char *dir = t_strdup_until(path, strrchr(path, '/')); ++ if (mkdir_parents(dir, 0700) < 0 && errno != EEXIST) ++ i_fatal("mkdir_parents(%s) failed: %m", dir); ++ ++ buffer_t *b64 = t_base64_encode(0, SIZE_MAX, key->data, key->used); ++ int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); ++ if (fd < 0) ++ i_fatal("open(%s) failed: %m", path); ++ if (write_full(fd, b64->data, b64->used) < 0) ++ i_fatal("write(%s) failed: %m", path); ++ i_close_fd(&fd); ++} ++ ++static void init_local_db(const char *const *extra_settings, ++ struct db_oauth2 **db_r) ++{ ++ test_key_dir = i_strdup_printf("%s/oauth2-keys", test_dir); ++ if (mkdir(test_key_dir, 0700) < 0 && errno != EEXIST) ++ i_fatal("mkdir(%s) failed: %m", test_key_dir); ++ ++ /* generate HMAC key */ ++ test_hmac_key = buffer_create_dynamic(default_pool, 32); ++ void *ptr = buffer_append_space_unsafe(test_hmac_key, 32); ++ random_fill(ptr, 32); ++ ++ /* key file path: /default/HS256/default ++ (fs-dict maps shared/default/HS256/default → default/HS256/default) */ ++ write_key_file(t_strdup_printf("%s/default/HS256/default", test_key_dir), ++ test_hmac_key); ++ ++ /* Copy default settings */ ++ set = *(const struct auth_settings *)auth_setting_parser_info.defaults; ++ global_auth_settings = &set; ++ global_auth_settings->base_dir = "."; ++ memset((&set)->username_chars_map, 1, sizeof((&set)->username_chars_map)); ++ set.username_format = ""; ++ ++ t_array_init(&set.passdbs, 2); ++ struct auth_passdb_settings *mock_set = t_new(struct auth_passdb_settings, 1); ++ *mock_set = mock_passdb_set; ++ array_push_back(&set.passdbs, &mock_set); ++ mock_set = t_new(struct auth_passdb_settings, 1); ++ *mock_set = mock_passdb_set; ++ mock_set->master = TRUE; ++ array_push_back(&set.passdbs, &mock_set); ++ t_array_init(&set.userdbs, 1); ++ ++ /* Disable stats */ ++ set.stats = FALSE; ++ ++ /* For tests of digest-md5. */ ++ set.realms_arr = t_strsplit_spaces("example.com ", " "); ++ /* For tests of mech-anonymous. */ ++ set.anonymous_username = "anonuser"; ++ ++ /* build settings array with base + any extra */ ++ const char *const base_settings[] = { ++ "introspection_mode", "local", ++ "username_attribute", "email", ++ "local_validation_key_dict", t_strdup_printf("fs:posix:prefix=%s/", test_key_dir), ++ NULL ++ }; ++ ++ /* count and merge settings arrays */ ++ unsigned int base_count = str_array_length(base_settings); ++ unsigned int extra_count = extra_settings != NULL ? ++ str_array_length(extra_settings) : 0; ++ const char **all = t_new(const char *, base_count + extra_count + 1); ++ memcpy(all, base_settings, base_count * sizeof(*all)); ++ if (extra_settings != NULL) ++ memcpy(all + base_count, extra_settings, ++ extra_count * sizeof(*all)); ++ all[base_count + extra_count] = NULL; ++ ++ dict_drivers_register_builtin(); ++ ++ const char *config_path = i_strdup_printf("%s/oauth2.conf", test_dir); ++ int fd = open(config_path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600); ++ if (fd < 0) ++ i_fatal("open(%s) failed: %m", config_path); ++ for (unsigned int i = 0; i < base_count + extra_count; i += 2) { ++ if (write_full(fd, all[i], strlen(all[i])) < 0 || ++ write_full(fd, " = ", 3) < 0 || ++ write_full(fd, all[i+1], strlen(all[i+1])) < 0 || ++ write_full(fd, "\n", 1) < 0) { ++ i_fatal("write() failed: %m"); ++ } ++ } ++ ++ i_close_fd(&fd); ++ *db_r = db_oauth2_init(config_path); ++ if (unlink(config_path) < 0) ++ i_error("unlink(%s): %m", config_path); ++} ++ ++static void deinit_local_db(struct db_oauth2 **db_r) ++{ ++ const char *error; ++ ++ dict_drivers_unregister_builtin(); ++ db_oauth2_unref(db_r); ++ mech_deinit(global_auth_settings); ++ ++ if (unlink_directory(test_key_dir, UNLINK_DIRECTORY_FLAG_RMDIR, ++ &error) < 0) ++ i_error("unlink_directory(%s): %s", test_key_dir, error); ++ i_free(test_key_dir); ++ buffer_free(&test_hmac_key); ++} ++ ++static const char * ++build_jwt(time_t exp, const char *email, const char *scope, const char *aud, ++ bool bad_sig) ++{ ++ const char *hdr = "{\"alg\":\"HS256\",\"typ\":\"JWT\"}"; ++ buffer_t *tokenbuf = t_buffer_create(256); ++ ++ base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, ++ (const unsigned char *)hdr, strlen(hdr), tokenbuf); ++ buffer_append(tokenbuf, ".", 1); ++ ++ string_t *body = t_str_new(128); ++ str_printfa(body, ++ "{\"sub\":\"%s\",\"email\":\"%s\"," ++ "\"exp\":%"PRIdTIME_T",\"iat\":%"PRIdTIME_T, ++ email, email, exp, (time_t)(exp - 3600)); ++ if (scope != NULL) ++ str_printfa(body, ",\"scope\":\"%s\"", scope); ++ if (aud != NULL) { ++ const char *const *auds = t_strsplit_spaces(aud, " "); ++ if (auds[0] != NULL && auds[1] != NULL) { ++ str_append(body, ",\"aud\":["); ++ for (unsigned int i = 0; auds[i] != NULL; i++) { ++ if (i > 0) ++ str_append_c(body, ','); ++ str_printfa(body, "\"%s\"", auds[i]); ++ } ++ str_append_c(body, ']'); ++ } else { ++ str_printfa(body, ",\"aud\":\"%s\"", aud); ++ } ++ } ++ str_append_c(body, '}'); ++ ++ base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, ++ str_data(body), str_len(body), ++ tokenbuf); ++ ++ buffer_t *sig = t_hmac_buffer(&hash_method_sha256, ++ test_hmac_key->data, test_hmac_key->used, ++ tokenbuf); ++ if (bad_sig) { ++ unsigned char *p = buffer_get_space_unsafe(sig, sig->used - 1, 1); ++ *p ^= 0xff; ++ } ++ ++ buffer_append(tokenbuf, ".", 1); ++ base64url_encode(BASE64_ENCODE_FLAG_NO_PADDING, SIZE_MAX, ++ sig->data, sig->used, tokenbuf); ++ ++ return str_c(tokenbuf); ++} ++ ++struct test_cb_ctx { ++ enum passdb_result result; ++ bool done; ++}; ++ ++static void ++test_lookup_cb(struct db_oauth2_request *req ATTR_UNUSED, ++ enum passdb_result result, ++ const char *error ATTR_UNUSED, ++ struct test_cb_ctx *ctx) ++{ ++ ctx->result = result; ++ ctx->done = TRUE; ++} ++ ++static enum passdb_result ++run_lookup(struct db_oauth2 *db, const char *user, const char *token) ++{ ++ pool_t pool = pool_alloconly_create("test-oauth2-req", 4096); ++ ++ struct db_oauth2_request *req = p_new(pool, struct db_oauth2_request, 1); ++ req->pool = pool; ++ ++ /* Create a minimal auth_request without going through auth_request_new ++ since global_auth_settings is not initialized in this test binary. */ ++ struct auth_request *ar = p_new(pool, struct auth_request, 1); ++ ar->pool = pool; ++ ar->refcount = 1; ++ ar->event = event_create(auth_event); ++ event_add_category(ar->event, &event_category_auth); ++ ar->fields.extra_fields = auth_fields_init(pool); ++ p_array_init(&ar->authdb_event, pool, 2); ++ ar->fields.user = p_strdup(pool, user); ++ ar->mech_password = p_strdup(req->pool, token); ++ ++ struct test_cb_ctx ctx = { .done = FALSE }; ++ db_oauth2_lookup(db, req, token, ar, test_lookup_cb, &ctx); ++ i_assert(ctx.done); ++ ++ event_unref(&ar->event); ++ pool_unref(&pool); ++ return ctx.result; ++} ++ ++void test_db_oauth2(void) ++{ ++ struct db_oauth2 *db; ++ const char *token; ++ time_t now = time(NULL); ++ ++ char *tmpdir = getenv("TMPDIR"); ++ if (tmpdir == NULL) ++ tmpdir = "/tmp"; ++ test_dir = i_strdup_printf("%s/test-db-oauth2.XXXXXX", tmpdir); ++ if (mkdtemp(test_dir) == NULL) ++ i_fatal("mkdtemp() failed: %m"); ++ ++ test_begin("db-oauth2: local validation - valid token"); ++ init_local_db(NULL, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, NULL, FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == PASSDB_RESULT_OK); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - expired token"); ++ init_local_db(NULL, &db); ++ token = build_jwt(now - 7200, "user@example.com", NULL, NULL, FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_PASSWORD_MISMATCH); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - wrong username"); ++ init_local_db(NULL, &db); ++ token = build_jwt(now + 3600, "other@example.com", NULL, NULL, FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_USER_UNKNOWN); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - bad signature"); ++ init_local_db(NULL, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, NULL, TRUE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_PASSWORD_MISMATCH); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - required scope present"); ++ const char *const scope_req_present[] = { "scope", "email", NULL }; ++ init_local_db(scope_req_present, &db); ++ token = build_jwt(now + 3600, "user@example.com", ++ "email profile", NULL, FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_OK); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - required scope missing"); ++ const char *const scope_req_missing[] = { "scope", "admin", NULL }; ++ init_local_db(scope_req_missing, &db); ++ token = build_jwt(now + 3600, "user@example.com", ++ "email profile", NULL, FALSE); ++ /* JWT-level scope check fails first */ ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_PASSWORD_MISMATCH); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - required audience present"); ++ const char *const aud_req_present[] = { "audience", "dovecot", NULL }; ++ init_local_db(aud_req_present, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, ++ "dovecot", FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_OK); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - required audience missing"); ++ const char *const aud_req_missing[] = { "audience", "dovecot", NULL }; ++ init_local_db(aud_req_missing, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, ++ "other", FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_USER_DISABLED); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - multiple required scopes all present"); ++ const char *const scope_multi_present[] = { ++ "scope", "email profile", ++ NULL ++ }; ++ init_local_db(scope_multi_present, &db); ++ token = build_jwt(now + 3600, "user@example.com", ++ "email profile openid", NULL, FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_OK); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - multiple required scopes one missing"); ++ const char *const scope_multi_missing[] = { ++ "scope", "email admin", ++ NULL ++ }; ++ init_local_db(scope_multi_missing, &db); ++ token = build_jwt(now + 3600, "user@example.com", ++ "email profile", NULL, FALSE); ++ /* JWT-level scope check fails first */ ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_PASSWORD_MISMATCH); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - multiple required audiences all present"); ++ const char *const aud_multi_present[] = { ++ "audience", "dovecot imap", ++ NULL ++ }; ++ init_local_db(aud_multi_present, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, ++ "dovecot imap", FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_OK); ++ deinit_local_db(&db); ++ test_end(); ++ ++ test_begin("db-oauth2: local validation - multiple required audiences one missing"); ++ const char *const aud_multi_missing[] = { ++ "audience", "dovecot admin", ++ NULL ++ }; ++ init_local_db(aud_multi_missing, &db); ++ token = build_jwt(now + 3600, "user@example.com", NULL, ++ "dovecot imap", FALSE); ++ test_assert(run_lookup(db, "user@example.com", token) == ++ PASSDB_RESULT_USER_DISABLED); ++ deinit_local_db(&db); ++ test_end(); ++} +--- a/src/auth/test-main.c ++++ b/src/auth/test-main.c +@@ -16,6 +16,7 @@ int main(int argc, const char *argv[]) + TEST_NAMED(test_auth_request_fields) + TEST_NAMED(test_db_dict_parse_cache_key) + TEST_NAMED(test_username_filter) ++ TEST_NAMED(test_db_oauth2) + #if defined(BUILTIN_LUA) + TEST_NAMED(test_db_lua) + #endif +--- a/src/lib-oauth2/oauth2-jwt.c ++++ b/src/lib-oauth2/oauth2-jwt.c +@@ -312,33 +312,68 @@ oauth2_validate_signature(const struct o + return -1; + } + ++struct jwt_node { ++ const char *prefix; ++ const struct json_tree_node *root; ++ bool array:1; ++}; ++ + static void + oauth2_jwt_copy_fields(ARRAY_TYPE(oauth2_field) *fields, struct json_tree *tree) + { + pool_t pool = array_get_pool(fields); +- ARRAY(const struct json_tree_node*) nodes; +- const struct json_tree_node *root = json_tree_root(tree); +- ++ ARRAY(struct jwt_node) nodes; + t_array_init(&nodes, 1); +- array_push_back(&nodes, &root); ++ struct jwt_node *root = array_append_space(&nodes); ++ root->prefix = ""; ++ root->root = json_tree_root(tree); + + while (array_count(&nodes) > 0) { +- const struct json_tree_node *const *pnode = array_front(&nodes); +- const struct json_tree_node *node = *pnode; +- array_pop_front(&nodes); ++ const struct jwt_node *subroot = array_front(&nodes); ++ const struct json_tree_node *node = subroot->root; + while (node != NULL) { +- if (node->value_type == JSON_TYPE_OBJECT) { +- root = node->value.child; +- array_push_back(&nodes, &root); +- } else if (node->key != NULL) { +- struct oauth2_field *field = +- array_append_space(fields); +- field->name = p_strdup(pool, node->key); +- field->value = p_strdup( +- pool, json_tree_get_value_str(node)); ++ if (node->value_type == JSON_TYPE_OBJECT || ++ node->value_type == JSON_TYPE_ARRAY) { ++ root = array_append_space(&nodes); ++ root->root = node->value.child; ++ root->array = node->value_type == JSON_TYPE_ARRAY; ++ if (node->key == NULL) ++ root->prefix = subroot->prefix; ++ else if (*subroot->prefix != '\0') ++ root->prefix = t_strconcat(subroot->prefix, node->key, "_", NULL); ++ else ++ root->prefix = t_strconcat(node->key, "_", NULL); ++ } else { ++ struct oauth2_field *field; ++ const char *name; ++ if (subroot->array) { ++ name = strrchr(subroot->prefix, '_'); ++ if (name != NULL) ++ name = t_strdup_until(subroot->prefix, name); ++ else ++ name = subroot->prefix; ++ array_foreach_modifiable(fields, field) { ++ if (strcmp(field->name, name) == 0) ++ break; ++ } ++ if (field == NULL || field->name == NULL) { ++ field = array_append_space(fields); ++ field->name = p_strdup(pool, name); ++ } ++ } else { ++ field = array_append_space(fields); ++ field->name = p_strconcat(pool, subroot->prefix, node->key, NULL); ++ } ++ const char *value = str_tabescape(json_tree_get_value_str(node)); ++ if (field->value != NULL) { ++ field->value = p_strconcat(pool, field->value, "\t", value, NULL); ++ } else { ++ field->value = p_strdup(pool, value); ++ } + } + node = node->next; + } ++ array_pop_front(&nodes); + } + } + +--- a/src/lib-oauth2/test-oauth2-jwt.c ++++ b/src/lib-oauth2/test-oauth2-jwt.c +@@ -734,6 +734,78 @@ static void test_jwt_kid_escape(void) + test_end(); + } + ++static void test_jwt_nested_fields(void) ++{ ++ test_begin("JWT nested fields"); ++ ++ buffer_t *tokenbuf = t_str_new(128); ++ const char *error ATTR_UNUSED; ++ bool is_jwt; ++ time_t now = time(NULL); ++ time_t exp = now+500; ++ time_t iat = now-500; ++ time_t nbf = now-250; ++ ++ base64url_encode_str("{\"alg\":\"HS256\",\"typ\":\"JWT\"}", tokenbuf); ++ str_append_c(tokenbuf, '.'); ++ base64url_encode_str(t_strdup_printf("{\"sub\":\"testuser\"," ++ "\"nbf\":%"PRIdTIME_T"," ++ "\"aud\":[\"dacity\",\"iron\"]," ++ "\"user\":{" ++ "\"name\":\"test\"," ++ "\"features\":[\"one\",\"two\",\"tap\tdance\"]," ++ "\"enabled\":true," ++ "\"locations\":{\"shared\":true,\"private\":false}" ++ "}," ++ "\"borders_\":{\"_left\":\"left\"," ++ "\"right_\":{\"_ok_\":\"right\"}," ++ "\"_both_\":\"both\"," ++ "\"middle_one\":\"middle\"," ++ "\"middle_inner\":{\"middle_two\":\"middle_in\"}" ++ "}," ++ "\"exp\":%"PRIdTIME_T"," ++ "\"iat\":%"PRIdTIME_T"}", ++ nbf, exp, iat), ++ tokenbuf); ++ sign_jwt_token_hs256(tokenbuf, hs_sign_key); ++ struct oauth2_request req; ++ ++ test_assert(parse_jwt_token(&req, str_c(tokenbuf), &is_jwt, &error) == 0); ++ test_assert(is_jwt == TRUE); ++ ++ const struct oauth2_field test_fields[] = { ++ { .name = "sub", .value = "testuser" }, ++ { .name = "nbf", .value = dec2str(nbf) }, ++ { .name = "exp", .value = dec2str(exp) }, ++ { .name = "iat", .value = dec2str(iat) }, ++ { .name = "aud", .value = "dacity\tiron" }, ++ { .name = "user_name", .value = "test" }, ++ { .name = "user_enabled", .value = "true" }, ++ { .name = "borders___left", .value = "left" }, ++ { .name = "borders___both_", .value = "both" }, ++ { .name = "borders__middle_one", .value = "middle" }, ++ { .name = "user_features", .value = "one\ttwo\ttap\1tdance" }, ++ { .name = "user_locations_shared", .value = "true" }, ++ { .name = "user_locations_private", .value = "false" }, ++ { .name = "borders__right___ok_", .value = "right" }, ++ { .name = "borders__middle_inner_middle_two", .value = "middle_in" }, ++ { .name = NULL, .value = NULL } ++ }; ++ ++ ++ /* lets see them fields */ ++ const struct oauth2_field *field; ++ unsigned int i = 0; ++ array_foreach(&req.fields, field) { ++ i_assert(i < N_ELEMENTS(test_fields)); ++ test_assert_strcmp_idx(field->name, test_fields[i].name, i); ++ test_assert_strcmp_idx(field->value, test_fields[i].value, i); ++ i++; ++ } ++ test_assert_ucmp(i, ==, N_ELEMENTS(test_fields) - 1); ++ test_end(); ++} ++ + static void test_jwt_rs_token(void) + { + const char *error; +@@ -907,6 +979,7 @@ int main(void) + test_jwt_dates, + test_jwt_key_files, + test_jwt_kid_escape, ++ test_jwt_nested_fields, + test_jwt_rs_token, + test_jwt_ps_token, + test_jwt_ec_token, diff --git a/mail/dovecot/patches/226-CVE-2026-73209.patch b/mail/dovecot/patches/226-CVE-2026-73209.patch new file mode 100644 index 0000000000..3fc103a256 --- /dev/null +++ b/mail/dovecot/patches/226-CVE-2026-73209.patch @@ -0,0 +1,906 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Michael M Slusarz +Subject: [PATCH] Fix CVE-2026-73209 + +Upstream commits: + lib-compression: Don't calculate crc32 if using zlib in deflate mode + https://github.com/dovecot/core/commit/cac140a9e4e12485bde4348b8a8c94a7a96a6e5e + lib-compression: istream-lz4 - Use container_of() macro + https://github.com/dovecot/core/commit/f54d2611567ad7c8f59e04b1190b29800898f1a1 + lib-compression: istream-lz4 - Ensure uncompressed chunk size is not 0 + https://github.com/dovecot/core/commit/86aba25a1159f7ff11480feec287647be78054d1 + lib-compression: istream-lz4 - Try again if no data was decompressed + https://github.com/dovecot/core/commit/f269b3d3051044aec31cef888fcf4c9ddd21c227 + lib-compression: wrap *_read() in for(;;) loop (reindent only) + https://github.com/dovecot/core/commit/a38aabc5790590af3310edc467e7c8892c089875 + lib-compression: Iterate instead of recursing on zero-output decompress chunks + https://github.com/dovecot/core/commit/78c0aa283ae0e4bdb205c8ef7d71f7fa938da4ab + lib-compression: istream-zstd - Guard against no-progress loop in read + https://github.com/dovecot/core/commit/e78ae179b9b979871175792d6cb5ef2ba7aed8b4 + lib-compression: test - Add zero-len frame test for all handlers + https://github.com/dovecot/core/commit/a5573eeb13f86481420be6f2c0763fda67156633 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/lib-compression/istream-bzlib.c ++++ b/src/lib-compression/istream-bzlib.c +@@ -51,88 +51,94 @@ static ssize_t i_stream_bzlib_read(struc + size_t size, out_size; + int ret; + +- high_offset = stream->istream.v_offset + (stream->pos - stream->skip); +- if (zstream->eof_offset == high_offset) { +- stream->istream.eof = TRUE; +- return -1; +- } +- +- if (!zstream->marked) { +- if (!i_stream_try_alloc(stream, CHUNK_SIZE, &out_size)) +- return -2; /* buffer full */ +- } else { +- /* try to avoid compressing, so we can quickly seek backwards */ +- if (!i_stream_try_alloc_avoid_compress(stream, CHUNK_SIZE, &out_size)) +- return -2; /* buffer full */ +- } ++ /* Loop instead of recursing when a decompress step yields no output: ++ a crafted stream can produce an unbounded number of zero-output ++ steps, and tail-call recursion (not guaranteed) would exhaust the ++ stack. */ ++ for (;;) { ++ high_offset = stream->istream.v_offset + (stream->pos - stream->skip); ++ if (zstream->eof_offset == high_offset) { ++ stream->istream.eof = TRUE; ++ return -1; ++ } + +- if (i_stream_read_more(stream->parent, &data, &size) < 0) { +- if (stream->parent->stream_errno != 0) { +- stream->istream.stream_errno = +- stream->parent->stream_errno; ++ if (!zstream->marked) { ++ if (!i_stream_try_alloc(stream, CHUNK_SIZE, &out_size)) ++ return -2; /* buffer full */ + } else { +- i_assert(stream->parent->eof); +- bzlib_read_error(zstream, "unexpected EOF"); +- if (!zstream->hdr_read) +- stream->istream.stream_errno = EINVAL; +- else +- stream->istream.stream_errno = EPIPE; ++ /* try to avoid compressing, so we can quickly seek backwards */ ++ if (!i_stream_try_alloc_avoid_compress(stream, CHUNK_SIZE, &out_size)) ++ return -2; /* buffer full */ ++ } ++ ++ if (i_stream_read_more(stream->parent, &data, &size) < 0) { ++ if (stream->parent->stream_errno != 0) { ++ stream->istream.stream_errno = ++ stream->parent->stream_errno; ++ } else { ++ i_assert(stream->parent->eof); ++ bzlib_read_error(zstream, "unexpected EOF"); ++ if (!zstream->hdr_read) ++ stream->istream.stream_errno = EINVAL; ++ else ++ stream->istream.stream_errno = EPIPE; ++ } ++ return -1; ++ } ++ if (size == 0) { ++ /* no more input */ ++ i_assert(!stream->istream.blocking); ++ return 0; + } +- return -1; +- } +- if (size == 0) { +- /* no more input */ +- i_assert(!stream->istream.blocking); +- return 0; +- } + +- zstream->zs.next_in = (char *)data; +- zstream->zs.avail_in = size; ++ zstream->zs.next_in = (char *)data; ++ zstream->zs.avail_in = size; + +- zstream->zs.next_out = (char *)stream->w_buffer + stream->pos; +- zstream->zs.avail_out = out_size; +- ret = BZ2_bzDecompress(&zstream->zs); +- zstream->hdr_read = TRUE; +- +- out_size -= zstream->zs.avail_out; +- stream->pos += out_size; +- +- i_stream_skip(stream->parent, size - zstream->zs.avail_in); +- +- switch (ret) { +- case BZ_OK: +- break; +- case BZ_PARAM_ERROR: +- i_unreached(); +- case BZ_DATA_ERROR: +- bzlib_read_error(zstream, "corrupted data"); +- stream->istream.stream_errno = EINVAL; +- return -1; +- case BZ_DATA_ERROR_MAGIC: +- bzlib_read_error(zstream, +- "wrong magic in header (not bz2 file?)"); +- stream->istream.stream_errno = EINVAL; +- return -1; +- case BZ_MEM_ERROR: +- i_fatal_status(FATAL_OUTOFMEM, "bzlib.read(%s): Out of memory", +- i_stream_get_name(&stream->istream)); +- case BZ_STREAM_END: +- zstream->eof_offset = stream->istream.v_offset + +- (stream->pos - stream->skip); +- stream->cached_stream_size = zstream->eof_offset; +- if (out_size == 0) { +- stream->istream.eof = TRUE; ++ zstream->zs.next_out = (char *)stream->w_buffer + stream->pos; ++ zstream->zs.avail_out = out_size; ++ ret = BZ2_bzDecompress(&zstream->zs); ++ zstream->hdr_read = TRUE; ++ ++ out_size -= zstream->zs.avail_out; ++ stream->pos += out_size; ++ ++ i_stream_skip(stream->parent, size - zstream->zs.avail_in); ++ ++ switch (ret) { ++ case BZ_OK: ++ break; ++ case BZ_PARAM_ERROR: ++ i_unreached(); ++ case BZ_DATA_ERROR: ++ bzlib_read_error(zstream, "corrupted data"); ++ stream->istream.stream_errno = EINVAL; + return -1; ++ case BZ_DATA_ERROR_MAGIC: ++ bzlib_read_error(zstream, ++ "wrong magic in header (not bz2 file?)"); ++ stream->istream.stream_errno = EINVAL; ++ return -1; ++ case BZ_MEM_ERROR: ++ i_fatal_status(FATAL_OUTOFMEM, "bzlib.read(%s): Out of memory", ++ i_stream_get_name(&stream->istream)); ++ case BZ_STREAM_END: ++ zstream->eof_offset = stream->istream.v_offset + ++ (stream->pos - stream->skip); ++ stream->cached_stream_size = zstream->eof_offset; ++ if (out_size == 0) { ++ stream->istream.eof = TRUE; ++ return -1; ++ } ++ break; ++ default: ++ i_fatal("BZ2_bzDecompress() failed with %d", ret); + } +- break; +- default: +- i_fatal("BZ2_bzDecompress() failed with %d", ret); +- } +- if (out_size == 0) { +- /* read more input */ +- return i_stream_bzlib_read(stream); ++ if (out_size == 0) { ++ /* no output yet; read more input without recursing */ ++ continue; ++ } ++ return out_size; + } +- return out_size; + } + + static void i_stream_bzlib_init(struct bzlib_istream *zstream) +--- a/src/lib-compression/istream-lz4.c ++++ b/src/lib-compression/istream-lz4.c +@@ -25,7 +25,8 @@ struct lz4_istream { + static void i_stream_lz4_close(struct iostream_private *stream, + bool close_parent) + { +- struct lz4_istream *zstream = (struct lz4_istream *)stream; ++ struct lz4_istream *zstream = ++ container_of(stream, struct lz4_istream, istream.iostream); + + buffer_free(&zstream->chunk_buf); + if (close_parent) +@@ -77,9 +78,10 @@ static int i_stream_lz4_read_header(stru + zstream->max_uncompressed_chunk_size = + be32_to_cpu_unaligned(hdr->max_uncompressed_chunk_size); + buffer_set_used_size(zstream->chunk_buf, 0); +- if (zstream->max_uncompressed_chunk_size > ISTREAM_LZ4_CHUNK_SIZE) { ++ if (zstream->max_uncompressed_chunk_size == 0 || ++ zstream->max_uncompressed_chunk_size > ISTREAM_LZ4_CHUNK_SIZE) { + lz4_read_error(zstream, t_strdup_printf( +- "lz4 max chunk size too large (%u > %u)", ++ "invalid lz4 max chunk size (%u, max %u)", + zstream->max_uncompressed_chunk_size, + ISTREAM_LZ4_CHUNK_SIZE)); + zstream->istream.istream.stream_errno = EINVAL; +@@ -131,7 +133,8 @@ static int i_stream_lz4_read_chunk_heade + + static ssize_t i_stream_lz4_read(struct istream_private *stream) + { +- struct lz4_istream *zstream = (struct lz4_istream *)stream; ++ struct lz4_istream *zstream = ++ container_of(stream, struct lz4_istream, istream); + const unsigned char *data; + size_t size; + int ret; +@@ -148,66 +151,77 @@ static ssize_t i_stream_lz4_read(struct + zstream->header_read = TRUE; + } + +- if (zstream->chunk_left == 0) { +- while ((ret = i_stream_lz4_read_chunk_header(zstream)) == 0) { +- if (!stream->istream.blocking) +- return 0; ++ /* Loop over chunks instead of recursing on zero-output chunks: a ++ crafted stream can contain an unbounded number of chunks that each ++ decompress to zero bytes, and tail-call recursion (which is not ++ guaranteed) would let that exhaust the stack. */ ++ for (;;) { ++ if (zstream->chunk_left == 0) { ++ while ((ret = i_stream_lz4_read_chunk_header(zstream)) == 0) { ++ if (!stream->istream.blocking) ++ return 0; ++ } ++ if (ret < 0) ++ return ret; + } +- if (ret < 0) +- return ret; +- } + +- /* read the whole compressed chunk into memory */ +- while (zstream->chunk_left > 0 && +- (ret = i_stream_read_more(zstream->istream.parent, &data, &size)) > 0) { +- if (size > zstream->chunk_left) +- size = zstream->chunk_left; +- buffer_append(zstream->chunk_buf, data, size); +- i_stream_skip(zstream->istream.parent, size); +- zstream->chunk_left -= size; +- } +- if (zstream->chunk_left > 0) { +- if (ret == -1 && zstream->istream.parent->stream_errno == 0) { +- lz4_read_error(zstream, "truncated lz4 chunk"); +- stream->istream.stream_errno = EPIPE; ++ /* read the whole compressed chunk into memory */ ++ while (zstream->chunk_left > 0 && ++ (ret = i_stream_read_more(zstream->istream.parent, &data, &size)) > 0) { ++ if (size > zstream->chunk_left) ++ size = zstream->chunk_left; ++ buffer_append(zstream->chunk_buf, data, size); ++ i_stream_skip(zstream->istream.parent, size); ++ zstream->chunk_left -= size; ++ } ++ if (zstream->chunk_left > 0) { ++ if (ret == -1 && zstream->istream.parent->stream_errno == 0) { ++ lz4_read_error(zstream, "truncated lz4 chunk"); ++ stream->istream.stream_errno = EPIPE; ++ return -1; ++ } ++ zstream->istream.istream.stream_errno = ++ zstream->istream.parent->stream_errno; ++ i_assert(ret != 0 || !stream->istream.blocking); ++ return ret; ++ } ++ /* if we already have max_buffer_size amount of data, fail here */ ++ if (stream->pos - stream->skip >= i_stream_get_max_buffer_size(&stream->istream)) ++ return -2; ++ if (i_stream_get_data_size(zstream->istream.parent) > 0) { ++ /* Parent stream was only partially consumed. Set the ++ stream's IO as pending to avoid hangs. */ ++ i_stream_set_input_pending(&zstream->istream.istream, TRUE); ++ } ++ /* allocate enough space for the old data and the new ++ decompressed chunk. we don't know the original compressed size, ++ so just allocate the max amount of memory. */ ++ void *dest = i_stream_alloc(stream, zstream->max_uncompressed_chunk_size); ++ ret = LZ4_decompress_safe(zstream->chunk_buf->data, dest, ++ zstream->chunk_buf->used, ++ zstream->max_uncompressed_chunk_size); ++ i_assert(ret <= (int)zstream->max_uncompressed_chunk_size); ++ if (ret < 0) { ++ lz4_read_error(zstream, "corrupted lz4 chunk"); ++ stream->istream.stream_errno = EINVAL; + return -1; ++ } else if (ret == 0) { ++ /* chunk decompressed to zero bytes; read the next chunk ++ without recursing so the stack stays bounded. */ ++ buffer_set_used_size(zstream->chunk_buf, 0); ++ continue; + } +- zstream->istream.istream.stream_errno = +- zstream->istream.parent->stream_errno; +- i_assert(ret != 0 || !stream->istream.blocking); ++ i_assert(ret > 0); ++ stream->pos += ret; ++ i_assert(stream->pos <= stream->buffer_size); ++ ++ /* we are going to get next chunk after this, so reset here ++ so we can reuse the chunk buf for reading next buffer prefix */ ++ if (zstream->chunk_left == 0) ++ buffer_set_used_size(zstream->chunk_buf, 0); ++ + return ret; + } +- /* if we already have max_buffer_size amount of data, fail here */ +- if (stream->pos - stream->skip >= i_stream_get_max_buffer_size(&stream->istream)) +- return -2; +- if (i_stream_get_data_size(zstream->istream.parent) > 0) { +- /* Parent stream was only partially consumed. Set the stream's +- IO as pending to avoid hangs. */ +- i_stream_set_input_pending(&zstream->istream.istream, TRUE); +- } +- /* allocate enough space for the old data and the new +- decompressed chunk. we don't know the original compressed size, +- so just allocate the max amount of memory. */ +- void *dest = i_stream_alloc(stream, zstream->max_uncompressed_chunk_size); +- ret = LZ4_decompress_safe(zstream->chunk_buf->data, dest, +- zstream->chunk_buf->used, +- zstream->max_uncompressed_chunk_size); +- i_assert(ret <= (int)zstream->max_uncompressed_chunk_size); +- if (ret < 0) { +- lz4_read_error(zstream, "corrupted lz4 chunk"); +- stream->istream.stream_errno = EINVAL; +- return -1; +- } +- i_assert(ret > 0); +- stream->pos += ret; +- i_assert(stream->pos <= stream->buffer_size); +- +- /* we are going to get next chunk after this, so reset here +- so we can reuse the chunk buf for reading next buffer prefix */ +- if (zstream->chunk_left == 0) +- buffer_set_used_size(zstream->chunk_buf, 0); +- +- return ret; + } + + static void i_stream_lz4_reset(struct lz4_istream *zstream) +@@ -227,7 +241,8 @@ static void i_stream_lz4_reset(struct lz + static void + i_stream_lz4_seek(struct istream_private *stream, uoff_t v_offset, bool mark) + { +- struct lz4_istream *zstream = (struct lz4_istream *) stream; ++ struct lz4_istream *zstream = ++ container_of(stream, struct lz4_istream, istream); + + if (i_stream_nonseekable_try_seek(stream, v_offset)) + return; +@@ -243,7 +258,8 @@ i_stream_lz4_seek(struct istream_private + + static void i_stream_lz4_sync(struct istream_private *stream) + { +- struct lz4_istream *zstream = (struct lz4_istream *) stream; ++ struct lz4_istream *zstream = ++ container_of(stream, struct lz4_istream, istream); + const struct stat *st; + + if (i_stream_stat(stream->parent, FALSE, &st) == 0) { +--- a/src/lib-compression/istream-zlib.c ++++ b/src/lib-compression/istream-zlib.c +@@ -169,153 +169,161 @@ static ssize_t i_stream_zlib_read(struct + size_t size, out_size; + int ret; + +- high_offset = stream->istream.v_offset + (stream->pos - stream->skip); +- if (zstream->eof_offset == high_offset) { +- /* zlib library returned EOF. */ +- if (!zstream->gz) { +- /* deflate - ignore if there's still more data */ +- stream->istream.eof = TRUE; +- return -1; ++ /* Loop instead of recursing when an inflate step yields no output: ++ a crafted stream can produce an unbounded number of zero-output ++ steps, and tail-call recursion (not guaranteed) would exhaust the ++ stack. */ ++ for (;;) { ++ high_offset = stream->istream.v_offset + (stream->pos - stream->skip); ++ if (zstream->eof_offset == high_offset) { ++ /* zlib library returned EOF. */ ++ if (!zstream->gz) { ++ /* deflate - ignore if there's still more data */ ++ stream->istream.eof = TRUE; ++ return -1; ++ } ++ /* gz format - read the trailer */ ++ if (!zstream->trailer_read) { ++ do { ++ ret = i_stream_zlib_read_trailer(zstream); ++ } while (ret == 0 && stream->istream.blocking); ++ if (ret <= 0) ++ return ret; ++ } ++ /* See if there's another concatenated gz stream. */ ++ if (i_stream_read_eof(stream->parent)) { ++ /* EOF or error */ ++ stream->istream.stream_errno = ++ stream->parent->stream_errno; ++ stream->istream.eof = TRUE; ++ return -1; ++ } ++ /* Multiple gz streams concatenated together */ ++ zstream->starting_concated_output = TRUE; ++ } ++ if (zstream->starting_concated_output) { ++ /* make sure there actually is something in parent stream. ++ we don't want to reset the stream unless we actually see ++ some concated output. */ ++ ret = i_stream_read_more(stream->parent, &data, &size); ++ if (ret <= 0) { ++ if (ret == 0) ++ return 0; ++ if (stream->parent->stream_errno != 0) { ++ stream->istream.stream_errno = ++ stream->parent->stream_errno; ++ } ++ stream->istream.eof = TRUE; ++ return -1; ++ } ++ ++ /* gzip file with concatenated content */ ++ stream->cached_stream_size = UOFF_T_MAX; ++ zstream->eof_offset = UOFF_T_MAX; ++ zstream->header_read = FALSE; ++ zstream->trailer_read = FALSE; ++ zstream->crc32 = 0; ++ zstream->starting_concated_output = FALSE; ++ ++ (void)inflateEnd(&zstream->zs); ++ i_stream_zlib_init(zstream); + } +- /* gz format - read the trailer */ +- if (!zstream->trailer_read) { ++ ++ if (!zstream->header_read) { + do { +- ret = i_stream_zlib_read_trailer(zstream); ++ ret = i_stream_zlib_read_header(stream); + } while (ret == 0 && stream->istream.blocking); + if (ret <= 0) + return ret; ++ zstream->header_read = TRUE; + } +- /* See if there's another concatenated gz stream. */ +- if (i_stream_read_eof(stream->parent)) { +- /* EOF or error */ +- stream->istream.stream_errno = +- stream->parent->stream_errno; +- stream->istream.eof = TRUE; +- return -1; ++ ++ if (!zstream->marked) { ++ if (!i_stream_try_alloc(stream, CHUNK_SIZE, &out_size)) ++ return -2; /* buffer full */ ++ } else { ++ /* try to avoid compressing, so we can quickly seek backwards */ ++ if (!i_stream_try_alloc_avoid_compress(stream, CHUNK_SIZE, &out_size)) ++ return -2; /* buffer full */ + } +- /* Multiple gz streams concatenated together */ +- zstream->starting_concated_output = TRUE; +- } +- if (zstream->starting_concated_output) { +- /* make sure there actually is something in parent stream. +- we don't want to reset the stream unless we actually see +- some concated output. */ +- ret = i_stream_read_more(stream->parent, &data, &size); +- if (ret <= 0) { +- if (ret == 0) +- return 0; ++ ++ if (i_stream_read_more(stream->parent, &data, &size) < 0) { + if (stream->parent->stream_errno != 0) { + stream->istream.stream_errno = + stream->parent->stream_errno; ++ } else { ++ i_assert(stream->parent->eof); ++ zlib_read_error(zstream, "unexpected EOF"); ++ stream->istream.stream_errno = EPIPE; + } +- stream->istream.eof = TRUE; + return -1; + } +- +- /* gzip file with concatenated content */ +- stream->cached_stream_size = UOFF_T_MAX; +- zstream->eof_offset = UOFF_T_MAX; +- zstream->header_read = FALSE; +- zstream->trailer_read = FALSE; +- zstream->crc32 = 0; +- zstream->starting_concated_output = FALSE; +- +- (void)inflateEnd(&zstream->zs); +- i_stream_zlib_init(zstream); +- } +- +- if (!zstream->header_read) { +- do { +- ret = i_stream_zlib_read_header(stream); +- } while (ret == 0 && stream->istream.blocking); +- if (ret <= 0) +- return ret; +- zstream->header_read = TRUE; +- } +- +- if (!zstream->marked) { +- if (!i_stream_try_alloc(stream, CHUNK_SIZE, &out_size)) +- return -2; /* buffer full */ +- } else { +- /* try to avoid compressing, so we can quickly seek backwards */ +- if (!i_stream_try_alloc_avoid_compress(stream, CHUNK_SIZE, &out_size)) +- return -2; /* buffer full */ +- } +- +- if (i_stream_read_more(stream->parent, &data, &size) < 0) { +- if (stream->parent->stream_errno != 0) { +- stream->istream.stream_errno = +- stream->parent->stream_errno; +- } else { +- i_assert(stream->parent->eof); +- zlib_read_error(zstream, "unexpected EOF"); +- stream->istream.stream_errno = EPIPE; +- } +- return -1; +- } +- if (size == 0) { +- /* no more input */ +- i_assert(!stream->istream.blocking); +- return 0; +- } +- +- zstream->zs.next_in = (void *)data; +- zstream->zs.avail_in = size; +- +- zstream->zs.next_out = stream->w_buffer + stream->pos; +- zstream->zs.avail_out = out_size; +- ret = inflate(&zstream->zs, Z_SYNC_FLUSH); +- +- out_size -= zstream->zs.avail_out; +- zstream->crc32 = crc32_data_more(zstream->crc32, +- stream->w_buffer + stream->pos, +- out_size); +- stream->pos += out_size; +- +- size_t bytes_consumed = size - zstream->zs.avail_in; +- i_stream_skip(stream->parent, bytes_consumed); +- if (i_stream_get_data_size(stream->parent) > 0 && +- (bytes_consumed > 0 || out_size > 0)) { +- /* Parent stream was only partially consumed. Set the stream's +- IO as pending to avoid hangs. */ +- i_stream_set_input_pending(&stream->istream, TRUE); +- } +- +- switch (ret) { +- case Z_OK: +- break; +- case Z_NEED_DICT: +- zlib_read_error(zstream, "can't read file without dict"); +- stream->istream.stream_errno = EIO; +- return -1; +- case Z_DATA_ERROR: +- zlib_read_error(zstream, "corrupted data"); +- stream->istream.stream_errno = EINVAL; +- return -1; +- case Z_MEM_ERROR: +- i_fatal_status(FATAL_OUTOFMEM, "zlib.read(%s): Out of memory", +- i_stream_get_name(&stream->istream)); +- case Z_STREAM_END: +- zstream->eof_offset = stream->istream.v_offset + +- (stream->pos - stream->skip); +- stream->cached_stream_size = zstream->eof_offset; +- zstream->zs.avail_in = 0; +- +- if (!zstream->trailer_read) { +- /* try to read and verify the trailer, we might not +- be called again. */ +- if (i_stream_zlib_read_trailer(zstream) < 0) +- return -1; ++ if (size == 0) { ++ /* no more input */ ++ i_assert(!stream->istream.blocking); ++ return 0; ++ } ++ ++ zstream->zs.next_in = (void *)data; ++ zstream->zs.avail_in = size; ++ ++ zstream->zs.next_out = stream->w_buffer + stream->pos; ++ zstream->zs.avail_out = out_size; ++ ret = inflate(&zstream->zs, Z_SYNC_FLUSH); ++ ++ out_size -= zstream->zs.avail_out; ++ /* CRC32 is only needed for GZ trailer. */ ++ if (zstream->gz) ++ zstream->crc32 = crc32_data_more(zstream->crc32, ++ stream->w_buffer + stream->pos, ++ out_size); ++ stream->pos += out_size; ++ ++ size_t bytes_consumed = size - zstream->zs.avail_in; ++ i_stream_skip(stream->parent, bytes_consumed); ++ if (i_stream_get_data_size(stream->parent) > 0 && ++ (bytes_consumed > 0 || out_size > 0)) { ++ /* Parent stream was only partially consumed. Set the stream's ++ IO as pending to avoid hangs. */ ++ i_stream_set_input_pending(&stream->istream, TRUE); ++ } ++ ++ switch (ret) { ++ case Z_OK: ++ break; ++ case Z_NEED_DICT: ++ zlib_read_error(zstream, "can't read file without dict"); ++ stream->istream.stream_errno = EIO; ++ return -1; ++ case Z_DATA_ERROR: ++ zlib_read_error(zstream, "corrupted data"); ++ stream->istream.stream_errno = EINVAL; ++ return -1; ++ case Z_MEM_ERROR: ++ i_fatal_status(FATAL_OUTOFMEM, "zlib.read(%s): Out of memory", ++ i_stream_get_name(&stream->istream)); ++ case Z_STREAM_END: ++ zstream->eof_offset = stream->istream.v_offset + ++ (stream->pos - stream->skip); ++ stream->cached_stream_size = zstream->eof_offset; ++ zstream->zs.avail_in = 0; ++ ++ if (!zstream->trailer_read) { ++ /* try to read and verify the trailer, we might not ++ be called again. */ ++ if (i_stream_zlib_read_trailer(zstream) < 0) ++ return -1; ++ } ++ break; ++ default: ++ i_fatal("inflate() failed with %d", ret); ++ } ++ if (out_size == 0) { ++ /* no output yet; read more input without recursing */ ++ continue; + } +- break; +- default: +- i_fatal("inflate() failed with %d", ret); +- } +- if (out_size == 0) { +- /* read more input */ +- return i_stream_zlib_read(stream); ++ return out_size; + } +- return out_size; + } + + static void i_stream_zlib_init(struct zlib_istream *zstream) +--- a/src/lib-compression/istream-zstd.c ++++ b/src/lib-compression/istream-zstd.c +@@ -175,12 +175,20 @@ static ssize_t i_stream_zstd_read(struct + zstream->output.pos = 0; + zstream->output.size = ZSTD_DStreamOutSize(); + ++ size_t old_input_pos = zstream->input.pos; + size_t zret = ZSTD_decompressStream(zstream->dstream, &zstream->output, + &zstream->input); + if (ZSTD_isError(zret) != 0) { + i_stream_zstd_read_error(zstream, zret); + return -1; + } ++ if (zstream->input.pos == old_input_pos && zstream->output.pos == 0) { ++ io_stream_set_error(&zstream->istream.iostream, ++ "zstd.read(%s): decompressor made no progress", ++ i_stream_get_name(&zstream->istream.istream)); ++ zstream->istream.istream.stream_errno = EIO; ++ return -1; ++ } + /* ZSTD magic number is 4 bytes, but it's only defined after v0.8 */ + if (!zstream->hdr_read && zstream->input.size > 4) + zstream->hdr_read = TRUE; +--- a/src/lib-compression/ostream-zlib.c ++++ b/src/lib-compression/ostream-zlib.c +@@ -182,7 +182,9 @@ o_stream_zlib_send_chunk(struct zlib_ost + } + size -= zs->avail_in; + +- zstream->crc = crc32_data_more(zstream->crc, data, size); ++ /* CRC32 is only needed for GZ trailer. */ ++ if (zstream->gz) ++ zstream->crc = crc32_data_more(zstream->crc, data, size); + zstream->bytes32 += size; + zstream->flushed = FALSE; + return size; +--- a/src/lib-compression/test-compression.c ++++ b/src/lib-compression/test-compression.c +@@ -152,6 +152,46 @@ test_compression_handler_empty(const str + } + + static void ++test_compression_handler_zero_frame(const struct compression_handler *handler, ++ bool autodetect) ++{ ++ test_begin(t_strdup_printf("compression handler %s (zero-len frame, autodetect=%s)", ++ handler->name, autodetect ? "yes" : "no")); ++ ++ /* Produce successive empty frames. Each frame needs its own ostream ++ because o_stream_finish() propagates to the parent; compress each ++ into a separate buffer then concatenate. ++ lz4 uses a custom single-stream format and does not support ++ concatenated frames, so limit it to one. */ ++ unsigned int n_frames = strcmp(handler->name, "lz4") == 0 ? 1 : 3; ++ buffer_t *compressed = buffer_create_dynamic(pool_datastack_create(), 256); ++ for (unsigned int i = 0; i < n_frames; i++) { ++ buffer_t *frame_buf = buffer_create_dynamic(pool_datastack_create(), 64); ++ struct ostream *os = test_ostream_create(frame_buf); ++ struct ostream *output = handler->create_ostream(os, 1); ++ o_stream_unref(&os); ++ test_assert_idx(o_stream_finish(output) == 1, i); ++ o_stream_unref(&output); ++ test_assert_idx(frame_buf->used > 0, i); ++ buffer_append(compressed, frame_buf->data, frame_buf->used); ++ } ++ ++ /* Decompress: must yield clean EOF with no error and no loop. */ ++ struct istream *is = test_istream_create_data(compressed->data, compressed->used); ++ is->blocking = TRUE; ++ struct istream *input = !autodetect ? handler->create_istream(is) : ++ i_stream_create_decompress(is, 0); ++ i_stream_unref(&is); ++ ++ test_assert(i_stream_read(input) == -1); ++ test_assert(input->eof); ++ test_assert(input->stream_errno == 0); ++ i_stream_unref(&input); ++ ++ test_end(); ++} ++ ++static void + test_compression_handler_seek(const struct compression_handler *handler, + bool autodetect) + { +@@ -739,6 +779,7 @@ static void test_compression_int(bool au + test_compression_handler_detect(&compression_handlers[i]); + test_compression_handler_short(&compression_handlers[i], autodetect); + test_compression_handler_empty(&compression_handlers[i], autodetect); ++ test_compression_handler_zero_frame(&compression_handlers[i], autodetect); + test_compression_handler(&compression_handlers[i], autodetect); + test_compression_handler_seek(&compression_handlers[i], autodetect); + test_compression_handler_reset(&compression_handlers[i], autodetect); +@@ -995,6 +1036,123 @@ static void test_lz4_small_header(void) + test_end(); + } + ++static const unsigned char lz4_chunk_crash_01[] = { ++ 0x44, 0x6f, 0x76, 0x65, 0x63, 0x6f, 0x74, 0x2d, 0x4c, 0x5a, 0x34, 0x0d, ++ 0x2a, 0x9b, 0xc5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x7a, ++ 0x32, 0x01, 0xff, 0xff, 0x00, 0x30 ++}; ++ ++static const unsigned char lz4_chunk_crash_02[] = { ++ 0x44, 0x6f, 0x76, 0x65, 0x63, 0x6f, 0x74, 0x2d, 0x4c, 0x5a, 0x34, 0x0d, ++ 0x2a, 0x9b, 0xc5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x7a, ++ 0x32, 0x01, 0xff, 0xff, 0x00, 0x30 ++}; ++ ++static const unsigned char lz4_chunk_eof_03[] = { ++ 0x44, 0x6f, 0x76, 0x65, 0x63, 0x6f, 0x74, 0x2d, 0x4c, 0x5a, 0x34, 0x0d, ++ 0x2a, 0x9b, 0xc5, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, ++}; ++ ++static void test_lz4_chunk_size(void) ++{ ++ const struct compression_handler *lz4; ++ struct istream *file_input, *input; ++ ++ if (compression_lookup_handler("lz4", &lz4) <= 0) ++ return; /* not compiled in or unknown */ ++ ++ test_begin("lz4 chunk size"); ++ ++ file_input = test_istream_create_data(lz4_chunk_crash_01, ++ sizeof(lz4_chunk_crash_01)); ++ input = lz4->create_istream(file_input); ++ i_stream_unref(&file_input); ++ i_stream_read(input); ++ ++ test_assert(input->eof); ++ test_assert(input->stream_errno != 0); ++ const char *error = i_stream_get_error(input); ++ test_assert(strstr(error, "invalid lz4 max chunk size") != NULL); ++ ++ i_stream_unref(&input); ++ ++ file_input = test_istream_create_data(lz4_chunk_crash_02, ++ sizeof(lz4_chunk_crash_02)); ++ input = lz4->create_istream(file_input); ++ i_stream_unref(&file_input); ++ i_stream_read(input); ++ ++ test_assert(input->eof); ++ test_assert(input->stream_errno != 0); ++ error = i_stream_get_error(input); ++ test_assert(strstr(error, "invalid lz4 max chunk size") != NULL); ++ ++ i_stream_unref(&input); ++ ++ file_input = test_istream_create_data(lz4_chunk_eof_03, ++ sizeof(lz4_chunk_eof_03)); ++ input = lz4->create_istream(file_input); ++ i_stream_unref(&file_input); ++ i_stream_read(input); ++ ++ /* no error, but no content either */ ++ test_assert(input->eof); ++ test_assert(input->stream_errno == 0); ++ ++ i_stream_unref(&input); ++ ++ test_end(); ++} ++ ++static void test_lz4_many_empty_chunks(void) ++{ ++ const struct compression_handler *lz4; ++ struct istream *file_input, *input; ++ ++ if (compression_lookup_handler("lz4", &lz4) <= 0) ++ return; /* not compiled in or unknown */ ++ ++ test_begin("lz4 many empty chunks"); ++ ++ /* A crafted lz4 stream can contain an unbounded number of chunks that ++ each decompress to zero bytes. i_stream_lz4_read() must iterate over ++ them rather than recurse once per chunk, or the stack is exhausted ++ (tail-call optimization is not guaranteed). */ ++ buffer_t *buf = buffer_create_dynamic(default_pool, 1024*512); ++ struct iostream_lz4_header hdr; ++ memcpy(hdr.magic, IOSTREAM_LZ4_MAGIC, IOSTREAM_LZ4_MAGIC_LEN); ++ /* a valid (64k) max uncompressed chunk size, big-endian */ ++ hdr.max_uncompressed_chunk_size[0] = 0x00; ++ hdr.max_uncompressed_chunk_size[1] = 0x01; ++ hdr.max_uncompressed_chunk_size[2] = 0x00; ++ hdr.max_uncompressed_chunk_size[3] = 0x00; ++ buffer_append(buf, &hdr, sizeof(hdr)); ++ ++ /* Each chunk: 4-byte big-endian compressed length (1), then a single ++ 0x00 byte, which LZ4_decompress_safe() decodes to zero bytes. */ ++ static const unsigned char empty_chunk[] = { ++ 0x00, 0x00, 0x00, 0x01, 0x00 ++ }; ++ for (unsigned int i = 0; i < 100000; i++) ++ buffer_append(buf, empty_chunk, sizeof(empty_chunk)); ++ ++ file_input = test_istream_create_data(buf->data, buf->used); ++ file_input->blocking = TRUE; ++ input = lz4->create_istream(file_input); ++ i_stream_unref(&file_input); ++ ++ /* All chunks are empty: clean EOF, no content, no error - and, with ++ the iterative read, no stack overflow. */ ++ test_assert(i_stream_read(input) == -1); ++ test_assert(input->eof); ++ test_assert(input->stream_errno == 0); ++ ++ i_stream_unref(&input); ++ buffer_free(&buf); ++ ++ test_end(); ++} ++ + static void test_uncompress_file(const char *path) + { + const struct compression_handler *handler; +@@ -1107,6 +1265,8 @@ int main(int argc, char *argv[]) + test_gz_header, + test_gz_large_header, + test_lz4_small_header, ++ test_lz4_chunk_size, ++ test_lz4_many_empty_chunks, + test_compression_ext, + NULL + }; diff --git a/mail/dovecot/patches/227-CVE-2026-40204.patch b/mail/dovecot/patches/227-CVE-2026-40204.patch new file mode 100644 index 0000000000..5c345e641a --- /dev/null +++ b/mail/dovecot/patches/227-CVE-2026-40204.patch @@ -0,0 +1,102 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-40204 + +Upstream commits: + lib-lda: mail-deliver - Autocreate delivery mailbox via explicit mailbox_create() + https://github.com/dovecot/core/commit/8d25b6d54c84d46f919ffde03a16afb72679bb9f + lib-storage: Remove MAILBOX_FLAG_AUTO_CREATE and MAILBOX_FLAG_AUTO_SUBSCRIBE + https://github.com/dovecot/core/commit/72d21003ae49ab7ed2f28438ec73303c0e95cea3 + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +The Pigeonhole part of this fix is in mail/pigeonhole/patches. + +--- a/src/lib-lda/mail-deliver.c ++++ b/src/lib-lda/mail-deliver.c +@@ -241,16 +241,35 @@ int mail_deliver_save_open(struct mail_d + return -1; + } + +- if (ctx->lda_mailbox_autocreate) +- flags |= MAILBOX_FLAG_AUTO_CREATE; +- if (ctx->lda_mailbox_autosubscribe) +- flags |= MAILBOX_FLAG_AUTO_SUBSCRIBE; + *box_r = box = mailbox_alloc_for_user(ctx->user, name, flags); + + if (mailbox_open(box) == 0) + return 0; + *error_str_r = mailbox_get_last_internal_error(box, error_r); +- return -1; ++ ++ /* Autocreate the mailbox if it does not exist yet and ++ lda_mailbox_autocreate is enabled. */ ++ if (*error_r != MAIL_ERROR_NOTFOUND || !ctx->lda_mailbox_autocreate) ++ return -1; ++ ++ if (mailbox_create(box, NULL, FALSE) < 0) { ++ enum mail_error error; ++ ++ *error_str_r = mailbox_get_last_internal_error(box, &error); ++ if (error != MAIL_ERROR_EXISTS) { ++ *error_r = error; ++ return -1; ++ } ++ /* Someone else just created it; fall through and open it. */ ++ } else if (ctx->lda_mailbox_autosubscribe) { ++ (void)mailbox_set_subscribed(box, TRUE); ++ } ++ ++ if (mailbox_open(box) < 0) { ++ *error_str_r = mailbox_get_last_internal_error(box, error_r); ++ return -1; ++ } ++ return 0; + } + + static bool mail_deliver_check_duplicate(struct mail_deliver_session *session, +--- a/src/lib-storage/mail-storage-lua.c ++++ b/src/lib-storage/mail-storage-lua.c +@@ -34,8 +34,6 @@ static struct dlua_table_values lua_stor + DLUA_TABLE_ENUM(MAILBOX_FLAG_NO_INDEX_FILES), + DLUA_TABLE_ENUM(MAILBOX_FLAG_KEEP_LOCKED), + DLUA_TABLE_ENUM(MAILBOX_FLAG_IGNORE_ACLS), +- DLUA_TABLE_ENUM(MAILBOX_FLAG_AUTO_CREATE), +- DLUA_TABLE_ENUM(MAILBOX_FLAG_AUTO_SUBSCRIBE), + + DLUA_TABLE_ENUM(MAILBOX_SYNC_FLAG_FULL_READ), + DLUA_TABLE_ENUM(MAILBOX_SYNC_FLAG_FULL_WRITE), +--- a/src/lib-storage/mail-storage.c ++++ b/src/lib-storage/mail-storage.c +@@ -1095,16 +1095,12 @@ bool mailbox_is_autocreated(struct mailb + { + if (box->inbox_user) + return TRUE; +- if ((box->flags & MAILBOX_FLAG_AUTO_CREATE) != 0) +- return TRUE; + return box->set != NULL && + strcmp(box->set->autocreate, MAILBOX_SET_AUTO_NO) != 0; + } + + bool mailbox_is_autosubscribed(struct mailbox *box) + { +- if ((box->flags & MAILBOX_FLAG_AUTO_SUBSCRIBE) != 0) +- return TRUE; + return box->set != NULL && + strcmp(box->set->autocreate, MAILBOX_SET_AUTO_SUBSCRIBE) == 0; + } +--- a/src/lib-storage/mail-storage.h ++++ b/src/lib-storage/mail-storage.h +@@ -60,10 +60,6 @@ enum mailbox_flags { + quota updates (possibly resulting in broken quota). and This is + useful for example when deleting entire user accounts. */ + MAILBOX_FLAG_DELETE_UNSAFE = 0x400, +- /* Mailbox is created implicitly if it does not exist. */ +- MAILBOX_FLAG_AUTO_CREATE = 0x1000, +- /* Mailbox is subscribed to implicitly when it is created automatically */ +- MAILBOX_FLAG_AUTO_SUBSCRIBE = 0x2000, + /* Run fsck for mailbox index before doing anything else. This may be + useful in fixing index corruption errors that aren't otherwise + detected and that are causing the full mailbox opening to fail. */ diff --git a/mail/dovecot/patches/228-CVE-2026-42394.patch b/mail/dovecot/patches/228-CVE-2026-42394.patch new file mode 100644 index 0000000000..0a573785ce --- /dev/null +++ b/mail/dovecot/patches/228-CVE-2026-42394.patch @@ -0,0 +1,549 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-42394 + +Upstream commits: + lib: i_close_fd*() - Document that it preserves errno + https://github.com/dovecot/core/commit/40a60ac7163180098415644506c62200bbb908a6 + lib: path-util - Add t_openat_safe() for jailed openat() resolution + https://github.com/dovecot/core/commit/3ad0946aacdb6b18927570d1fb29c53e5d157a01 + lib: Add t_openat_safe_dir() + https://github.com/dovecot/core/commit/22379bb0f01a46fb2c0d15e226744b49394fdf78 + acl: dovecot-acl-list is never supposed to be a symlink - use O_NOFOLLOW flag + https://github.com/dovecot/core/commit/0375f6f9851ce0ad6a20bd85449384284728118b + lib: Add comments about memory allocations and string functions preserving errno + https://github.com/dovecot/core/commit/54a9bdf057cf7574bdd6d6ab3e1a6c60eb6584fc + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +The Pigeonhole part of this fix is in mail/pigeonhole/patches. + +--- a/src/lib/data-stack.h ++++ b/src/lib/data-stack.h +@@ -31,6 +31,11 @@ + overflows. + */ + ++/* All data stack allocations - t_malloc(), t_malloc0(), t_buffer_get(), ++ t_try_realloc() etc. - preserve errno. It is therefore safe to allocate ++ temporary memory between a failing syscall and reading errno (or ++ formatting "%m"). */ ++ + #ifndef STATIC_CHECKER + typedef unsigned int data_stack_frame_t; + #else +--- a/src/lib/fd-util.h ++++ b/src/lib/fd-util.h +@@ -17,7 +17,7 @@ void fd_close_maybe_stdio(int *fd_in, in + + /* Close the fd and set it to -1. This assert-crashes if fd == 0, and is a + no-op if fd == -1. Normally fd == 0 would happen only if an uninitialized +- fd is attempted to be closed, which is a bug. */ ++ fd is attempted to be closed, which is a bug. Preserves original errno. */ + void i_close_fd_path(int *fd, const char *path, const char *arg, + const char *func, const char *file, int line); + #define i_close_fd_path(fd, path) i_close_fd_path((fd), (path), #fd, __func__, __FILE__, __LINE__) +--- a/src/lib/imem.h ++++ b/src/lib/imem.h +@@ -3,6 +3,9 @@ + + /* For easy allocation of memory from default memory pool. */ + ++/* Like all pool allocations, i_malloc()/i_realloc()/i_free() and the ++ i_strdup*() helpers preserve errno (see mempool.h). */ ++ + extern pool_t default_pool; + + #define i_new(type, count) p_new(default_pool, type, count) +--- a/src/lib/mempool.h ++++ b/src/lib/mempool.h +@@ -19,6 +19,12 @@ + zeroed, it will cost only a few CPU cycles and may well save some debug + time. */ + ++/* All pool memory operations - p_malloc(), p_realloc(), p_free() and the ++ p_new()/p_strdup*() helpers built on them - preserve errno. This means an ++ allocation between a failing syscall and reading errno (e.g. when building ++ an error string with "%m") will not clobber errno. The same guarantee holds ++ for the t_* (data stack) and i_* (default pool) allocators. */ ++ + typedef struct pool *pool_t; + + struct pool_vfuncs { +--- a/src/lib/path-util.c ++++ b/src/lib/path-util.c +@@ -4,12 +4,17 @@ + #include "str.h" + #include "path-util.h" + ++#include + #include + #include + #include + + #define PATH_UTIL_MAX_PATH 8*1024 + #define PATH_UTIL_MAX_SYMLINKS 80 ++/* Symlink-hop cap for t_openat_safe(). Lower than the realpath cap: ++ t_openat_safe() refuses absolute and escaping targets outright, so a ++ long chain inside the base dir is the only legitimate use. */ ++#define PATH_UTIL_OPENAT_SAFE_MAX_SYMLINKS 16 + + static int t_getcwd_noalloc(char **dir_r, size_t *asize_r, + const char **error_r) ATTR_NULL(2) +@@ -358,6 +363,190 @@ int t_readlink(const char *path, const c + return 0; + } + ++/* Iteratively resolve `path` beneath `cur_fd` using openat() with ++ O_NOFOLLOW per component. Symlinks are resolved manually: their targets ++ are validated (non-absolute, no '..' past the base) and the loop ++ restarts with the target spliced into the remaining path. dir_depth ++ tracks how many directory levels we have descended below the original ++ base; '..' is refused when the depth would go negative. ++ */ ++static int ++path_openat_safe_walk(int cur_fd, const char *path, int flags, ++ const char **error_r) ++{ ++ bool cur_owned = FALSE; ++ unsigned int symlink_count = 0; ++ unsigned int dir_depth = 0; ++ ++ /* Absolute paths cannot stay beneath the base directory. */ ++ if (*path == '/') { ++ errno = ELOOP; ++ *error_r = "Path is absolute (escapes base directory)"; ++ return -1; ++ } ++ ++ for (;;) { ++ while (*path == '/') ++ path++; ++ ++ if (*path == '\0') { ++ /* Empty path or trailing slash: open the current ++ directory itself with the requested flags. */ ++ int fd = openat(cur_fd, ".", ++ flags | O_NOFOLLOW | O_CLOEXEC); ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ if (fd < 0) { ++ *error_r = t_strdup_printf( ++ "openat() failed: %m"); ++ } ++ return fd; ++ } ++ ++ const char *slash = strchr(path, '/'); ++ size_t comp_len = (slash != NULL ? ++ (size_t)(slash - path) : strlen(path)); ++ bool is_last = (slash == NULL); ++ ++ if (comp_len == 1 && path[0] == '.') { ++ path += comp_len; ++ continue; ++ } ++ ++ if (comp_len == 2 && path[0] == '.' && path[1] == '.') { ++ if (dir_depth == 0) { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ errno = ELOOP; ++ *error_r = "Path escapes base directory via '..'"; ++ return -1; ++ } ++ int parent_fd = openat(cur_fd, "..", ++ O_RDONLY | O_DIRECTORY | ++ O_NOFOLLOW | O_CLOEXEC); ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ if (parent_fd < 0) { ++ *error_r = t_strdup_printf( ++ "openat(..) failed: %m"); ++ return -1; ++ } ++ cur_fd = parent_fd; ++ cur_owned = TRUE; ++ dir_depth--; ++ path += comp_len; ++ continue; ++ } ++ ++ const char *comp = t_strdup_until(path, path + comp_len); ++ int next_fd; ++ if (is_last) { ++ next_fd = openat(cur_fd, comp, ++ flags | O_NOFOLLOW | O_CLOEXEC); ++ } else { ++ next_fd = openat(cur_fd, comp, ++ O_RDONLY | O_DIRECTORY | ++ O_NOFOLLOW | O_CLOEXEC); ++ } ++ ++ if (next_fd < 0 && (errno == ELOOP || errno == EMLINK)) { ++ /* Component is a symlink. Resolve it ourselves and ++ restart processing with its target spliced into ++ `path`; that way the target is itself walked ++ component-by-component and the boundary check ++ continues to apply. (O_NOFOLLOW on a symlink reports ++ ELOOP on Linux/macOS but EMLINK on the BSDs, so both ++ must be treated as "this is a symlink".) */ ++ if (++symlink_count > ++ PATH_UTIL_OPENAT_SAFE_MAX_SYMLINKS) { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ errno = ELOOP; ++ *error_r = "Too many symlink dereferences"; ++ return -1; ++ } ++ ++ char buf[PATH_UTIL_MAX_PATH]; ++ ssize_t llen = readlinkat(cur_fd, comp, ++ buf, sizeof(buf) - 1); ++ if (llen < 0) { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ *error_r = t_strdup_printf( ++ "readlinkat(%s) failed: %m", comp); ++ return -1; ++ } ++ buf[llen] = '\0'; ++ ++ if (buf[0] == '/') { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ errno = ELOOP; ++ *error_r = t_strdup_printf( ++ "Symlink '%s' has absolute target " ++ "'%s' (escapes base directory)", ++ comp, buf); ++ return -1; ++ } ++ ++ path = is_last ? t_strdup(buf) : ++ t_strconcat(buf, "/", ++ slash + 1, NULL); ++ continue; ++ } ++ ++ if (next_fd < 0) { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ *error_r = t_strdup_printf( ++ "openat(%s) failed: %m", comp); ++ return -1; ++ } ++ ++ if (is_last) { ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ return next_fd; ++ } ++ ++ if (cur_owned) ++ i_close_fd(&cur_fd); ++ cur_fd = next_fd; ++ cur_owned = TRUE; ++ dir_depth++; ++ path = slash + 1; ++ } ++} ++ ++int t_openat_safe(int base_fd, const char *path, int flags, ++ const char **error_r) ++{ ++ i_assert(base_fd >= 0); ++ i_assert(path != NULL); ++ i_assert(error_r != NULL); ++ ++ return path_openat_safe_walk(base_fd, path, flags, error_r); ++} ++ ++int t_openat_safe_dir(const char *base_dir, const char *path, int flags, ++ const char **error_r) ++{ ++ i_assert(base_dir != NULL); ++ i_assert(path != NULL); ++ i_assert(error_r != NULL); ++ ++ int dir_fd = open(base_dir, ++ O_DIRECTORY | O_RDONLY | O_CLOEXEC | ++ (flags & O_NOFOLLOW)); ++ if (dir_fd < 0) { ++ *error_r = t_strdup_printf("open(%s) failed: %m", base_dir); ++ return -1; ++ } ++ int fd = t_openat_safe(dir_fd, path, flags, error_r); ++ i_close_fd(&dir_fd); ++ return fd; ++} ++ + bool t_binary_abspath(const char **binpath, const char **error_r) + { + const char *path_env, *const *paths; +--- a/src/lib/path-util.h ++++ b/src/lib/path-util.h +@@ -57,6 +57,42 @@ int t_get_working_dir(const char **dir_r + * -1 on failure. error_r is set on failure and cannot be NULL. */ + int t_readlink(const char *path, const char **dest_r, const char **error_r); + ++/* Open `path` relative to `base_fd`, refusing any resolution that escapes ++ the directory referenced by `base_fd`. Each path component is opened with ++ O_NOFOLLOW so symlinks are detected explicitly rather than transparently ++ followed; symlinks are followed only when their (recursively resolved) ++ target also stays beneath `base_fd`. Absolute symlink targets, leading ++ '/', and '..' past the base are rejected. ++ ++ `base_fd` must reference a directory (e.g. obtained via ++ open(dir, O_DIRECTORY|O_RDONLY|O_CLOEXEC)) and remains owned by the ++ caller; this function does not close it. ++ ++ `flags` is OR-ed into the openat() call for the final component (e.g. ++ O_RDONLY). O_NOFOLLOW and O_CLOEXEC are added implicitly. ++ ++ Anchoring resolution at `base_fd` makes the lookup TOCTOU-safe even when ++ intermediate path components are mutated on disk concurrently: the kernel ++ resolves all component lookups relative to the original directory inode ++ `base_fd` references. ++ ++ Returns the new fd (>= 0) on success. On failure returns -1 with errno ++ set and *error_r set to a descriptive message: ++ errno=ELOOP target escapes base, or symlink chain too deep ++ errno=ENOENT file not found ++ errno=EACCES permission denied ++ other errno as set by openat()/readlinkat() ++ */ ++int t_openat_safe(int base_fd, const char *path, int flags, ++ const char **error_r); ++ ++/* Convenience wrapper: opens base_dir as a directory fd, then delegates to ++ t_openat_safe(). If O_NOFOLLOW is present in flags it is also applied to ++ the open() of base_dir itself, refusing a symlink as its final component. ++ Returns the new fd on success, -1 on failure. */ ++int t_openat_safe_dir(const char *base_dir, const char *path, int flags, ++ const char **error_r); ++ + /* Update binpath to be absolute: + * a) begins with '/' -> no change + * b) contains '/' -> assume relative to working directory +--- a/src/lib/strfuncs.h ++++ b/src/lib/strfuncs.h +@@ -12,6 +12,13 @@ extern const unsigned char *uchar_empty_ + int i_snprintf(char *dest, size_t max_chars, const char *format, ...) + ATTR_FORMAT(3, 4); + ++/* The p_/t_/i_ strdup, strconcat and *printf helpers below preserve errno. ++ So this pattern is safe - errno still refers to the failed syscall when ++ "%m" is expanded: ++ ++ if (syscall(...) < 0) ++ error = t_strdup_printf("syscall() failed: %m"); */ ++ + char *p_strdup(pool_t pool, const char *str) ATTR_MALLOC; + void *p_memdup(pool_t pool, const void *data, size_t size) ATTR_MALLOC; + /* return NULL if str = "" */ +--- a/src/lib/test-path-util.c ++++ b/src/lib/test-path-util.c +@@ -233,6 +233,180 @@ static void test_link_alloc2(void) + tmpdir = o_tmpdir; + } + ++static void test_openat_safe(void) ++{ ++ const char *error; ++ int base_fd, fd; ++ ++ base_fd = open(tmpdir, O_RDONLY | O_DIRECTORY | O_CLOEXEC); ++ if (base_fd < 0) ++ i_fatal("open(%s) failed: %m", tmpdir); ++ ++ /* Plain regular file inside base. */ ++ const char *plain = t_strconcat(tmpdir, "/plain", NULL); ++ int wfd = creat(plain, 0600); ++ if (wfd < 0) ++ i_fatal("creat(%s) failed: %m", plain); ++ i_close_fd(&wfd); ++ ++ fd = t_openat_safe(base_fd, "plain", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ /* "./plain" and redundant slashes. */ ++ fd = t_openat_safe(base_fd, "./plain", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ fd = t_openat_safe(base_fd, ".//plain", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ /* Symlink whose target is inside the base: allowed. */ ++ const char *in_link = t_strconcat(tmpdir, "/in-link", NULL); ++ if (symlink("plain", in_link) < 0) ++ i_fatal("symlink(plain, %s) failed: %m", in_link); ++ fd = t_openat_safe(base_fd, "in-link", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ /* Absolute symlink target: refused. */ ++ const char *abs_link = t_strconcat(tmpdir, "/abs-link", NULL); ++ if (symlink("/etc/hostname", abs_link) < 0) ++ i_fatal("symlink failed: %m"); ++ errno = 0; ++ fd = t_openat_safe(base_fd, "abs-link", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ test_assert(error != NULL); ++ ++ /* Relative symlink with '..' that escapes the base: refused. */ ++ const char *escape_link = t_strconcat(tmpdir, "/escape-link", NULL); ++ if (symlink("../../etc/hostname", escape_link) < 0) ++ i_fatal("symlink failed: %m"); ++ errno = 0; ++ fd = t_openat_safe(base_fd, "escape-link", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ test_assert(error != NULL); ++ ++ /* Direct '..' escape attempt: refused. */ ++ errno = 0; ++ fd = t_openat_safe(base_fd, "../plain", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ ++ /* Absolute literal path: refused. */ ++ errno = 0; ++ fd = t_openat_safe(base_fd, "/etc/hostname", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ ++ /* link2's target is an absolute path (tmpdir/link3): refused as an ++ absolute target before the loop is ever followed. */ ++ errno = 0; ++ fd = t_openat_safe(base_fd, "link2", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ ++ /* Relative symlink loop staying inside the base: nothing rejects it ++ except the hop counter, so this exercises ++ PATH_UTIL_OPENAT_SAFE_MAX_SYMLINKS. */ ++ const char *loopa = t_strconcat(tmpdir, "/loopa", NULL); ++ const char *loopb = t_strconcat(tmpdir, "/loopb", NULL); ++ if (symlink("loopb", loopa) < 0) ++ i_fatal("symlink(loopb, %s) failed: %m", loopa); ++ if (symlink("loopa", loopb) < 0) ++ i_fatal("symlink(loopa, %s) failed: %m", loopb); ++ errno = 0; ++ fd = t_openat_safe(base_fd, "loopa", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ test_assert(error != NULL); ++ ++ /* '..' that stays within the base: allowed. Create sub/under and ++ reach back to plain via sub/../plain. */ ++ const char *subdir = t_strconcat(tmpdir, "/sub", NULL); ++ if (mkdir(subdir, 0700) < 0 && errno != EEXIST) ++ i_fatal("mkdir(%s) failed: %m", subdir); ++ fd = t_openat_safe(base_fd, "sub/../plain", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ /* Breaking out of the base via subdirectory. */ ++ errno = 0; ++ fd = t_openat_safe(base_fd, "sub/../../plain", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ ++ /* Nonexistent file inside base: ENOENT, not ELOOP. */ ++ errno = 0; ++ fd = t_openat_safe(base_fd, "no-such-file", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ENOENT); ++ ++ i_close_fd(&base_fd); ++ ++ i_unlink(plain); ++ i_unlink(in_link); ++ i_unlink(abs_link); ++ i_unlink(escape_link); ++ i_unlink(loopa); ++ i_unlink(loopb); ++ if (rmdir(subdir) < 0) ++ i_error("rmdir(%s) failed: %m", subdir); ++} ++ ++static void test_openat_safe_dir(void) ++{ ++ const char *error; ++ int fd; ++ ++ /* Plain file: success. */ ++ const char *plain = t_strconcat(tmpdir, "/plain2", NULL); ++ int wfd = creat(plain, 0600); ++ if (wfd < 0) ++ i_fatal("creat(%s) failed: %m", plain); ++ i_close_fd(&wfd); ++ ++ fd = t_openat_safe_dir(tmpdir, "plain2", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ /* Nonexistent base_dir. */ ++ errno = 0; ++ fd = t_openat_safe_dir(t_strconcat(tmpdir, "/no-such-dir", NULL), ++ "plain2", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ENOENT); ++ test_assert(error != NULL); ++ ++ /* Absolute symlink in relative part: refused. */ ++ const char *abs_link2 = t_strconcat(tmpdir, "/abs-link2", NULL); ++ if (symlink("/etc/hostname", abs_link2) < 0) ++ i_fatal("symlink failed: %m"); ++ errno = 0; ++ fd = t_openat_safe_dir(tmpdir, "abs-link2", O_RDONLY, &error); ++ test_assert(fd == -1); ++ test_assert(errno == ELOOP); ++ ++ /* O_NOFOLLOW: symlink as base_dir final component refused. */ ++ const char *dir_link = t_strconcat(tmpdir, "/dir-link", NULL); ++ if (symlink(tmpdir, dir_link) < 0) ++ i_fatal("symlink failed: %m"); ++ errno = 0; ++ fd = t_openat_safe_dir(dir_link, "plain2", ++ O_RDONLY | O_NOFOLLOW, &error); ++ test_assert(fd == -1); ++ /* Without O_NOFOLLOW the same symlinked base_dir succeeds. */ ++ fd = t_openat_safe_dir(dir_link, "plain2", O_RDONLY, &error); ++ test_assert(fd >= 0); ++ i_close_fd(&fd); ++ ++ i_unlink(plain); ++ i_unlink(abs_link2); ++ i_unlink(dir_link); ++} ++ + static void test_cleanup(void) + { + const char *error; +@@ -272,6 +446,8 @@ void test_path_util(void) + test_abspath_vs_normpath(); + test_link_alloc(); + test_link_alloc2(); ++ test_openat_safe(); ++ test_openat_safe_dir(); + test_cleanup(); + alarm(0); + test_end(); +--- a/src/plugins/acl/acl-backend-vfile-acllist.c ++++ b/src/plugins/acl/acl-backend-vfile-acllist.c +@@ -114,7 +114,7 @@ static int acl_backend_vfile_acllist_rea + return 0; + } + +- fd = open(path, O_RDONLY); ++ fd = open(path, O_RDONLY | O_NOFOLLOW); + if (fd == -1) { + if (errno == ENOENT) { + backend->acllist_mtime = 0; diff --git a/mail/dovecot/patches/229-CVE-2026-52681.patch b/mail/dovecot/patches/229-CVE-2026-52681.patch new file mode 100644 index 0000000000..f92db0f9a9 --- /dev/null +++ b/mail/dovecot/patches/229-CVE-2026-52681.patch @@ -0,0 +1,58 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-52681 + +Upstream commits: + lib-storage: Allow NULL path in mailbox_list_mkdir_root() + https://github.com/dovecot/core/commit/a56d0685ef2e3369b4fdce14e59a2c3dfec8f44e + lib-storage: Simplify mailbox_mkdir() using mailbox_list_mkdir_root(NULL) + https://github.com/dovecot/core/commit/9276a4f55e0ea38c735cf386fa5578891f51b99c + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +The Pigeonhole part of this fix is in mail/pigeonhole/patches. + +--- a/src/lib-storage/mail-storage.c ++++ b/src/lib-storage/mail-storage.c +@@ -3025,12 +3025,10 @@ int mailbox_mkdir(struct mailbox *box, c + enum mailbox_list_path_type type) + { + const struct mailbox_permissions *perm = mailbox_get_permissions(box); +- const char *root_dir; + + if (!perm->gid_origin_is_mailbox_path) { + /* mailbox root directory doesn't exist, create it */ +- root_dir = mailbox_list_get_root_forced(box->list, type); +- if (mailbox_list_mkdir_root(box->list, root_dir, type) < 0) { ++ if (mailbox_list_mkdir_root(box->list, NULL, type) < 0) { + mail_storage_copy_list_error(box->storage, box->list); + return -1; + } +--- a/src/lib-storage/mailbox-list.c ++++ b/src/lib-storage/mailbox-list.c +@@ -1272,6 +1272,10 @@ int mailbox_list_mkdir_root(struct mailb + { + const char *error; + ++ if (path == NULL && ++ !mailbox_list_get_root_path(list, type, &path)) ++ return 0; ++ + if (mailbox_list_try_mkdir_root(list, path, type, &error) < 0) { + mailbox_list_set_critical(list, "%s", error); + return -1; +--- a/src/lib-storage/mailbox-list.h ++++ b/src/lib-storage/mailbox-list.h +@@ -238,7 +238,9 @@ void mailbox_list_get_permissions(struct + void mailbox_list_get_root_permissions(struct mailbox_list *list, + struct mailbox_permissions *permissions_r); + /* mkdir() a root directory of given type with proper permissions. The path can +- be either the root itself or point to a directory under the root. */ ++ be either the root itself or point to a directory under the root. If path is ++ NULL, the root path of the given type is looked up automatically; if there is ++ no such path, nothing is done. */ + int mailbox_list_mkdir_root(struct mailbox_list *list, const char *path, + enum mailbox_list_path_type type); + /* Like mailbox_list_mkdir_root(), but don't log an error if it fails. */ diff --git a/mail/dovecot/patches/230-CVE-2026-42391.patch b/mail/dovecot/patches/230-CVE-2026-42391.patch new file mode 100644 index 0000000000..3f9fcce9a0 --- /dev/null +++ b/mail/dovecot/patches/230-CVE-2026-42391.patch @@ -0,0 +1,82 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-42391 + +Upstream commits: + imap-login: Fix excessive memory growth with pre-login ID command + https://github.com/dovecot/core/commit/dbeb18dfc317be3c9839702c35c3fb77b7af90ff + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +Adjusted for this version: + - also limit the pairs added to the imap_id_log reply to + IMAP_ID_MAX_ACCOUNTED_PAIRS, with a counter of its own, as the + upstream commit does for its log entries. The Debian patch limits + only client_id, which 2.3 already caps by length, so with + imap_id_log set the log reply still grew with every pair. + +--- a/src/imap-login/imap-login-client.h ++++ b/src/imap-login/imap-login-client.h +@@ -53,6 +53,12 @@ struct imap_client_cmd_id { + + char **log_keys; + string_t *log_reply; ++ /* Number of external (non internal x-*) key/value pairs accounted so ++ far. Used to bound the pre-login accounting (logging, event fields, ++ client_id) done per external pair. */ ++ unsigned int processed_pairs_count; ++ /* Number of key/value pairs added to log_reply so far. */ ++ unsigned int logged_pairs_count; + }; + + struct imap_client { +--- a/src/imap-login/imap-login-cmd-id.c ++++ b/src/imap-login/imap-login-cmd-id.c +@@ -7,6 +7,12 @@ + #include "imap-login-settings.h" + #include "imap-login-client.h" + ++/* RFC 2971 says a client SHOULD NOT send more than 30 field-value pairs. ++ Allow that many to be accounted for (logged / kept in client_id); pairs ++ beyond this are still parsed and internal x-* handlers still run, but they ++ are not added to the logging/client_id accounting that grows per pair. */ ++#define IMAP_ID_MAX_ACCOUNTED_PAIRS 30 ++ + struct imap_id_param_handler { + const char *key; + bool key_is_prefix; +@@ -125,7 +131,17 @@ static void cmd_id_handle_keyvalue(struc + + client_id_str = !client_try_update_info(client, key, value); + +- if (client->set->imap_id_retain && client_id_str && ++ /* Only external pairs are logged / kept in client_id, and only those ++ grow per-pair with count, so only they need bounding to avoid a ++ pre-login CPU/memory DoS. Internal x-* handlers must keep running ++ regardless (e.g. a proxy may legitimately forward more than 30 ++ fields) and are not counted against the limit. */ ++ bool account_pair = client_id_str && ++ client->cmd_id->processed_pairs_count < IMAP_ID_MAX_ACCOUNTED_PAIRS; ++ if (account_pair) ++ client->cmd_id->processed_pairs_count++; ++ ++ if (account_pair && client->set->imap_id_retain && + (client->common.client_id == NULL || + str_len(client->common.client_id) + kvlen < LOGIN_MAX_CLIENT_ID_LEN)) { + if (client->common.client_id == NULL) { +@@ -142,9 +158,12 @@ static void cmd_id_handle_keyvalue(struc + } + + if (client->cmd_id->log_reply != NULL && ++ client->cmd_id->logged_pairs_count < IMAP_ID_MAX_ACCOUNTED_PAIRS && + (client->cmd_id->log_keys == NULL || +- str_array_icase_find((void *)client->cmd_id->log_keys, key))) ++ str_array_icase_find((void *)client->cmd_id->log_keys, key))) { ++ client->cmd_id->logged_pairs_count++; + imap_id_log_reply_append(client->cmd_id->log_reply, key, value); ++ } + } + + static int cmd_id_handle_args(struct imap_client *client, diff --git a/mail/dovecot/patches/231-CVE-2026-52687.patch b/mail/dovecot/patches/231-CVE-2026-52687.patch new file mode 100644 index 0000000000..31510fe34f --- /dev/null +++ b/mail/dovecot/patches/231-CVE-2026-52687.patch @@ -0,0 +1,256 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Timo Sirainen +Subject: [PATCH] Fix CVE-2026-52687 + +Upstream commits: + doveadm compress: Move struct client earlier + https://github.com/dovecot/core/commit/429762550939be2128b1c8056fa1bf85543ccd92 + doveadm compress: Refactor line reading + https://github.com/dovecot/core/commit/0b5eea74d4741c86df0342efdc5b3c77002e74e7 + doveadm compress-connect: Fix writing server input to non-blocking stdout + https://github.com/dovecot/core/commit/c781a55de87c78e9aa7cdc1325d7af355bd74e68 + imap: Restrict COMPRESS to DEFLATE only + https://github.com/dovecot/core/commit/a9b051233715577c88155604b516262fed10aa26 + doveadm: compress-connect - Don't hang when server rejects COMPRESS + https://github.com/dovecot/core/commit/2fad1f836b23e15b260ca3e5985aec126d7a90e9 + doveadm compress: Delay failing if used COMPRESS algorithm is not supported locally + https://github.com/dovecot/core/commit/e7ab7a24675a4f0a82fb9d7583eb49f8736e4dfb + +Taken from the Debian bookworm security update (dovecot +1:2.3.19.1+dfsg1-2.1+deb12u7), which carries these fixes for 2.3, and +applied to 2.3.21.1. + +--- a/src/doveadm/doveadm-zlib.c ++++ b/src/doveadm/doveadm-zlib.c +@@ -15,6 +15,24 @@ + #include + #include + ++enum server_input_line_type { ++ SERVER_INPUT_LINE_TYPE_DEFAULT, ++ SERVER_INPUT_LINE_TYPE_COMPRESS, ++ SERVER_INPUT_LINE_TYPE_COMPRESS_FAILED, ++}; ++ ++struct client { ++ int fd; ++ struct io *io_client, *io_server; ++ struct istream *input, *stdin_input; ++ struct ostream *output, *stdout_output; ++ const struct compression_handler *handler; ++ char *algorithm; ++ char *compress_tag; ++ bool compressed; ++ bool compress_waiting; ++}; ++ + static bool test_dump_imapzlib(const char *path) + { + const char *p; +@@ -82,29 +100,31 @@ cmd_dump_imapzlib(const char *path, cons + fflush(stdout); + } + +-struct client { +- int fd; +- struct io *io_client, *io_server; +- struct istream *input, *stdin_input; +- struct ostream *output; +- const struct compression_handler *handler; +- char *algorithm; +- bool compressed; +- bool compress_waiting; +-}; +- + static bool + client_input_get_compress_algorithm(struct client *client, const char *line) + { ++ const char *tag = line; ++ size_t tag_len; ++ + /* skip tag */ + while (*line != ' ' && *line != '\0') + line++; ++ tag_len = line - tag; + if (strncasecmp(line, " COMPRESS ", 10) != 0) + return FALSE; + ++ /* Look up the local handler needed to (de)compress the stream once the ++ server accepts. Don't fail here if the mechanism is unknown or not ++ compiled in: the server may reject it, and this client must still send ++ the command to let the server do so. If the server unexpectedly ++ accepts a mechanism we can't handle, we fail then (see server_input()). */ + if (compression_lookup_handler(t_str_lcase(line+10), + &client->handler) <= 0) +- i_fatal("Unsupported compression mechanism: %s", line+10); ++ client->handler = NULL; ++ /* Remember the tag so we can tell whether the server accepted or ++ rejected this COMPRESS command. */ ++ i_free(client->compress_tag); ++ client->compress_tag = i_strndup(tag, tag_len); + return TRUE; + } + +@@ -165,25 +185,33 @@ static bool server_input_is_compress_rep + return str_begins(line, " OK Begin compression"); + } + +-static bool server_input_uncompressed(struct client *client) ++static bool server_input_is_reply_to_tag(const char *line, const char *tag) + { +- const char *line; ++ size_t tag_len = strlen(tag); + +- while ((line = i_stream_read_next_line(client->input)) != NULL) { +- if (write(STDOUT_FILENO, line, strlen(line)) < 0) +- i_fatal("write(stdout) failed: %m"); +- if (write(STDOUT_FILENO, "\n", 1) < 0) +- i_fatal("write(stdout) failed: %m"); +- if (server_input_is_compress_reply(line)) +- return TRUE; +- } +- return FALSE; ++ return strncmp(line, tag, tag_len) == 0 && line[tag_len] == ' '; ++} ++ ++static enum server_input_line_type ++server_input_line_type(struct client *client, const char *line) ++{ ++ if (!client->compressed && server_input_is_compress_reply(line)) ++ return SERVER_INPUT_LINE_TYPE_COMPRESS; ++ /* The server can reject COMPRESS (e.g. an unsupported mechanism). If we ++ are waiting for its reply, a tagged reply that isn't the "OK Begin ++ compression" above means the command failed - resume sending the ++ pipelined input instead of waiting forever. */ ++ if (client->compress_waiting && client->compress_tag != NULL && ++ server_input_is_reply_to_tag(line, client->compress_tag)) ++ return SERVER_INPUT_LINE_TYPE_COMPRESS_FAILED; ++ return SERVER_INPUT_LINE_TYPE_DEFAULT; + } + + static void server_input(struct client *client) + { + const unsigned char *data; + size_t size; ++ const char *line; + + if (i_stream_read(client->input) == -1) { + if (client->input->stream_errno != 0) { +@@ -196,27 +224,52 @@ static void server_input(struct client * + return; + } + +- if (!client->compressed && server_input_uncompressed(client)) { +- /* start compression */ +- struct istream *input; +- struct ostream *output; +- +- i_info(""); +- input = client->handler->create_istream(client->input); +- output = client->handler->create_ostream(client->output, 6); +- i_stream_unref(&client->input); +- o_stream_unref(&client->output); +- client->input = input; +- client->output = output; +- client->compressed = TRUE; +- client->compress_waiting = FALSE; +- i_stream_set_input_pending(client->stdin_input, TRUE); ++ while ((line = i_stream_next_line(client->input)) != NULL) { ++ o_stream_nsend_str(client->stdout_output, line); ++ o_stream_nsend_str(client->stdout_output, "\n"); ++ ++ switch (server_input_line_type(client, line)) { ++ case SERVER_INPUT_LINE_TYPE_COMPRESS: { ++ /* start compression */ ++ struct istream *input; ++ struct ostream *output; ++ ++ if (client->handler == NULL) ++ i_fatal("Server accepted unsupported compression mechanism"); ++ i_info(""); ++ input = client->handler->create_istream(client->input); ++ output = client->handler->create_ostream(client->output, 6); ++ i_stream_unref(&client->input); ++ o_stream_unref(&client->output); ++ client->input = input; ++ client->output = output; ++ client->compressed = TRUE; ++ client->compress_waiting = FALSE; ++ i_free_and_null(client->compress_tag); ++ i_stream_set_input_pending(client->stdin_input, TRUE); ++ break; ++ } ++ case SERVER_INPUT_LINE_TYPE_COMPRESS_FAILED: ++ /* Server rejected COMPRESS. Resume sending input. */ ++ i_info(""); ++ client->handler = NULL; ++ client->compress_waiting = FALSE; ++ i_free_and_null(client->compress_tag); ++ i_stream_set_input_pending(client->stdin_input, TRUE); ++ break; ++ case SERVER_INPUT_LINE_TYPE_DEFAULT: ++ break; ++ } + } + + data = i_stream_get_data(client->input, &size); +- if (write(STDOUT_FILENO, data, size) < 0) +- i_fatal("write(stdout) failed: %m"); ++ o_stream_nsend(client->stdout_output, data, size); + i_stream_skip(client->input, size); ++ ++ if (o_stream_flush(client->stdout_output) < 0) { ++ i_fatal("write(stdout) failed: %s", ++ o_stream_get_error(client->stdout_output)); ++ } + } + + static void cmd_zlibconnect(struct doveadm_cmd_context *cctx) +@@ -252,6 +305,10 @@ static void cmd_zlibconnect(struct dovea + client.fd = fd; + fd_set_nonblock(STDIN_FILENO, TRUE); + client.stdin_input = i_stream_create_fd(STDIN_FILENO, SIZE_MAX); ++ /* stdin and stdout may point to the same file description (e.g. a ++ pty), in which case stdout is now also non-blocking. Buffer stdout ++ writes and retry them from the ioloop on EAGAIN. */ ++ client.stdout_output = o_stream_create_fd(STDOUT_FILENO, SIZE_MAX); + client.input = i_stream_create_fd(fd, SIZE_MAX); + client.output = o_stream_create_fd(fd, 0); + o_stream_set_no_error_handling(client.output, TRUE); +@@ -260,9 +317,17 @@ static void cmd_zlibconnect(struct dovea + master_service_run(master_service, NULL); + io_remove(&client.io_client); + io_remove(&client.io_server); ++ /* switch stdout back to blocking for the final flush */ ++ fd_set_nonblock(STDOUT_FILENO, FALSE); ++ if (o_stream_finish(client.stdout_output) < 0) { ++ i_fatal("write(stdout) failed: %s", ++ o_stream_get_error(client.stdout_output)); ++ } + i_stream_unref(&client.stdin_input); + i_stream_unref(&client.input); + o_stream_unref(&client.output); ++ o_stream_unref(&client.stdout_output); ++ i_free(client.compress_tag); + if (close(fd) < 0) + i_fatal("close() failed: %m"); + } +--- a/src/plugins/imap-zlib/imap-zlib-plugin.c ++++ b/src/plugins/imap-zlib/imap-zlib-plugin.c +@@ -94,10 +94,14 @@ static bool cmd_compress(struct client_c + } + + ret = compression_lookup_handler(t_str_lcase(mechanism), &handler); +- if (ret <= 0) { ++ /* Only DEFLATE is advertised (RFC 4978) and accepted here. Other ++ algorithms (e.g. zstd) can require far more memory to decompress, ++ which especially matters now that imap-login can handle COMPRESS for ++ proxied connections and an attacker could open many of them. */ ++ if (ret <= 0 || strcmp(handler->name, "deflate") != 0) { + const char * tagline = + t_strdup_printf("NO %s compression mechanism", +- ret == 0 ? "Unsupported" : "Unknown"); ++ ret < 0 ? "Unknown" : "Unsupported"); + client_send_tagline(cmd, tagline); + return TRUE; + }