pigeonhole: backport security fixes

Take the Pigeonhole parts of the Dovecot security fixes from the Debian
bookworm security updates, up to 1:2.3.19.1+dfsg1-2.1+deb12u7, and apply
them to 0.5.21.1, one patch per CVE.

Fixes:
  - CVE-2025-59032
  - CVE-2026-27857
  - CVE-2026-27858
  - CVE-2026-33263
  - CVE-2026-33605
  - CVE-2026-40013
  - CVE-2026-40016
  - CVE-2026-40204
  - CVE-2026-42007
  - CVE-2026-42394
  - CVE-2026-52681

The patch for CVE-2026-52681 needed a small change for 0.5.21.1,
described in its header. It also moves the Sieve CPU usage tracking from
the compiled scripts to a sieve-rusage file per user.

The patches add source files, so the build runs autoreconf now.

Signed-off-by: Josef Schlehofer <pepe.schlehofer@gmail.com>
This commit is contained in:
Josef Schlehofer committed 2026-11-18 08:20:53 +01:00
1 parent 30c761530f
commit d40b3e8eb3
12 files changed
+2133 -1

No files matched your search

+2 -1
View File
@@ -9,7 +9,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=dovecot-pigeonhole
PKG_VERSION:=0.5.21.1
PKG_RELEASE:=2
PKG_RELEASE:=3
DOVECOT_VERSION:=2.3
@@ -23,6 +23,7 @@ PKG_LICENSE_FILES:=COPYING COPYING.LGPL
PKG_CPE_ID:=cpe:/a:dovecot:pigeonhole
PKG_BUILD_DIR:=$(BUILD_DIR)/dovecot-$(DOVECOT_VERSION)-pigeonhole-$(PKG_VERSION)
PKG_FIXUP:=autoreconf
PKG_INSTALL:=1
include $(INCLUDE_DIR)/package.mk
@@ -0,0 +1,29 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2025-59032
Upstream commits:
managesieve-login: Fix crash when command didn't finish on the first call
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 Pigeonhole 0.5.21.1.
--- a/src/managesieve-login/client.c
+++ b/src/managesieve-login/client.c
@@ -330,10 +330,12 @@ static bool managesieve_client_input_nex
if (args[0].type != MANAGESIEVE_ARG_EOL)
ret = -1;
}
- }
- if (ret > 0) {
+ if (ret > 0)
+ ret = client->cmd->func(client, args);
+ } else {
+ /* Continue unfinished command */
i_assert(client->cmd != NULL);
- ret = client->cmd->func(client, args);
+ ret = client->cmd->func(client, NULL);
}
if (ret != 0)
@@ -0,0 +1,25 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-27857
Upstream commits:
plugins: imap-filter-sieve: imap-filter-sieve - Adjust to imap_parser_create() API change
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 Pigeonhole 0.5.21.1.
The Dovecot part of this fix is in mail/dovecot/patches.
--- a/src/plugins/imap-filter-sieve/cmd-filter-sieve.c
+++ b/src/plugins/imap-filter-sieve/cmd-filter-sieve.c
@@ -379,7 +379,8 @@ bool cmd_filter_sieve(struct client_comm
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);
@@ -0,0 +1,25 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-27858
Upstream commits:
managesieve-login: Verify AUTHENTICATE initial response size isn't too large
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 Pigeonhole 0.5.21.1.
--- a/src/managesieve-login/client-authenticate.c
+++ b/src/managesieve-login/client-authenticate.c
@@ -189,6 +189,11 @@ static int managesieve_client_auth_read_
if ( i_stream_get_size
(msieve_client->auth_response_input, FALSE, &resp_size) <= 0 )
resp_size = 0;
+ else if (resp_size > LOGIN_MAX_AUTH_BUF_SIZE) {
+ client_destroy(client,
+ "Authentication response too large");
+ return -1;
+ }
if (client->auth_response == NULL)
client->auth_response = str_new(default_pool, I_MAX(resp_size+1, 256));
@@ -0,0 +1,235 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-40016
Upstream commits:
lib-sieve: Enforce CPU time limit within :contains and :matches matcher loops
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 Pigeonhole 0.5.21.1.
--- a/src/lib-sieve/mcht-contains.c
+++ b/src/lib-sieve/mcht-contains.c
@@ -8,6 +8,7 @@
#include "sieve-match-types.h"
#include "sieve-comparators.h"
+#include "sieve-interpreter.h"
#include "sieve-match.h"
#include <string.h>
@@ -38,7 +39,14 @@ const struct sieve_match_type_def contai
/* FIXME: Naive substring match implementation. Should switch to more
* efficient algorithm if large values need to be searched (e.g. message body).
+ *
+ * The inner loop polls the interpreter CPU time limit periodically so that a
+ * single O(N*M) match on a large value cannot run for many times the
+ * configured sieve_max_cpu_time (which is otherwise only checked between
+ * bytecode operations).
*/
+#define SIEVE_CONTAINS_CPU_CHECK_INTERVAL 4096
+
static int mcht_contains_match_key
(struct sieve_match_context *mctx, const char *val, size_t val_size,
const char *key, size_t key_size)
@@ -48,6 +56,7 @@ static int mcht_contains_match_key
const char *kend = (const char *) key + key_size;
const char *vp = val;
const char *kp = key;
+ unsigned int counter = 0;
if ( val_size == 0 )
return ( key_size == 0 ? 1 : 0 );
@@ -58,6 +67,18 @@ static int mcht_contains_match_key
while ( (vp < vend) && (kp < kend) ) {
if ( !cmp->def->char_match(cmp, &vp, vend, &kp, kend) )
vp++;
+
+ if ( ++counter >= SIEVE_CONTAINS_CPU_CHECK_INTERVAL ) {
+ counter = 0;
+ if ( sieve_runtime_cpu_limit_exceeded(mctx->runenv) ) {
+ sieve_runtime_error(
+ mctx->runenv, NULL,
+ "execution exceeded CPU time limit");
+ mctx->exec_status =
+ SIEVE_EXEC_RESOURCE_LIMIT;
+ return -1;
+ }
+ }
}
return ( kp == kend ? 1 : 0 );
--- a/src/lib-sieve/mcht-matches.c
+++ b/src/lib-sieve/mcht-matches.c
@@ -9,6 +9,7 @@
#include "sieve-match-types.h"
#include "sieve-comparators.h"
+#include "sieve-interpreter.h"
#include "sieve-match.h"
#include <string.h>
@@ -46,16 +47,38 @@ const struct sieve_match_type_def matche
#endif
/* FIXME: Naive implementation, substitute this with dovecot src/lib/str-find.c
+ *
+ * The inner loop polls the interpreter CPU time limit periodically so that a
+ * single O(N*M) search on a large value cannot run for many times the
+ * configured sieve_max_cpu_time. Returns 1 on match, 0 on exhaustion, or -1
+ * when the CPU time limit was exceeded (mctx->exec_status is set).
*/
-static inline bool _string_find(const struct sieve_comparator *cmp,
- const char **valp, const char *vend, const char **keyp, const char *kend)
+#define SIEVE_MATCHES_CPU_CHECK_INTERVAL 4096
+
+static int
+_string_find(struct sieve_match_context *mctx,
+ const struct sieve_comparator *cmp,
+ const char **valp, const char *vend,
+ const char **keyp, const char *kend,
+ unsigned int *counter)
{
while ( (*valp < vend) && (*keyp < kend) ) {
if ( !cmp->def->char_match(cmp, valp, vend, keyp, kend) )
(*valp)++;
+ if (++(*counter) >= SIEVE_MATCHES_CPU_CHECK_INTERVAL) {
+ *counter = 0;
+ if (sieve_runtime_cpu_limit_exceeded(mctx->runenv)) {
+ sieve_runtime_error(
+ mctx->runenv, NULL,
+ "execution exceeded CPU time limit");
+ mctx->exec_status =
+ SIEVE_EXEC_RESOURCE_LIMIT;
+ return -1;
+ }
+ }
}
- return (*keyp == kend);
+ return (*keyp == kend ? 1 : 0);
}
static char _scan_key_section
@@ -93,6 +116,7 @@ static int mcht_matches_match_key
char wcard = '\0'; /* Current wildcard */
char next_wcard = '\0'; /* Next widlcard */
unsigned int key_offset = 0;
+ unsigned int counter = 0;
if ( cmp->def == NULL || cmp->def->char_match == NULL )
return 0;
@@ -134,6 +158,19 @@ static int mcht_matches_match_key
while (kp < kend && vp < vend ) {
const char *needle, *nend;
+ if (++counter >= SIEVE_MATCHES_CPU_CHECK_INTERVAL) {
+ counter = 0;
+ if (sieve_runtime_cpu_limit_exceeded(mctx->runenv)) {
+ sieve_runtime_error(
+ mctx->runenv, NULL,
+ "execution exceeded CPU time limit");
+ mctx->exec_status =
+ SIEVE_EXEC_RESOURCE_LIMIT;
+ sieve_match_values_abort(&mvalues);
+ return -1;
+ }
+ }
+
if ( !backtrack ) {
/* Search the next '*' wildcard in the key string */
@@ -268,10 +305,20 @@ static int mcht_matches_match_key
/* Match may happen at any offset (>= key offset): find substring */
vp += key_offset;
- if ( (vp >= vend) || !_string_find(cmp, &vp, vend, &needle, nend) ) {
+ if (vp >= vend) {
debug_printf(" failed to find needle at an offset\n");
break;
}
+ int fres = _string_find(mctx, cmp, &vp, vend,
+ &needle, nend, &counter);
+ if (fres < 0) {
+ sieve_match_values_abort(&mvalues);
+ return -1;
+ }
+ if (fres == 0) {
+ debug_printf(" failed to find needle at an offset\n");
+ break;
+ }
prv = vp - str_len(section);
prk = kp;
--- a/src/lib-sieve/sieve-interpreter.c
+++ b/src/lib-sieve/sieve-interpreter.c
@@ -85,6 +85,13 @@ struct sieve_interpreter {
struct sieve_runtime_trace trace;
struct sieve_resource_usage rusage;
+ /* CPU time limit for the current sieve_interpreter_continue() call;
+ NULL when no limit is configured or not currently executing. Exposed
+ via sieve_runtime_cpu_limit_exceeded() so long-running runtime code
+ can enforce the limit without waiting for the next bytecode
+ boundary. */
+ struct cpu_limit *climit;
+
/* Current operation */
struct sieve_operation oprtn;
@@ -362,6 +369,15 @@ sieve_interpreter_svinst(struct sieve_in
return interp->runenv.exec_env->svinst;
}
+bool sieve_runtime_cpu_limit_exceeded(const struct sieve_runtime_env *renv)
+{
+ struct sieve_interpreter *interp = renv->interp;
+
+ if (interp->climit == NULL)
+ return FALSE;
+ return cpu_limit_exceeded(interp->climit);
+}
+
/* Do not use this function for normal sieve extensions. This is intended for
* the testsuite only.
*/
@@ -939,6 +955,7 @@ int sieve_interpreter_continue(struct si
climit = cpu_limit_init(svinst->max_cpu_time_secs,
CPU_LIMIT_TYPE_USER);
}
+ interp->climit = climit;
while (ret == SIEVE_EXEC_OK && !interp->interrupted &&
*address < sieve_binary_block_get_size(renv->sblock)) {
@@ -959,6 +976,8 @@ int sieve_interpreter_continue(struct si
ret = sieve_interpreter_operation_execute(interp);
}
+ interp->climit = NULL;
+
if (climit != NULL) {
sieve_resource_usage_init(&rusage);
rusage.cpu_time_msecs =
--- a/src/lib-sieve/sieve-interpreter.h
+++ b/src/lib-sieve/sieve-interpreter.h
@@ -165,6 +165,18 @@ int sieve_interpreter_run(struct sieve_i
struct sieve_result *result);
/*
+ * CPU limit
+ */
+
+/* Returns TRUE if the current interpreter execution has exceeded its CPU
+ time limit (sieve_max_cpu_time). Callable from within long-running runtime
+ code (e.g. matcher inner loops) so that limit enforcement is not deferred
+ until the next bytecode boundary. Returns FALSE if no limit is active or
+ no execution is currently in progress. Cheap: does not call getrusage()
+ on each invocation. */
+bool sieve_runtime_cpu_limit_exceeded(const struct sieve_runtime_env *renv);
+
+/*
* Error handling
*/
@@ -0,0 +1,45 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-33263
Upstream commits:
managesieve-login: Adjust to core's login_proxy_failure_type changes
https://github.com/dovecot/pigeonhole/commit/33f5a95c0448e0d104f2cd7591e7f42c19b33199
managesieve-login: Support LOGIN_PROXY_FAILURE_TYPE_AUTH_LIMIT_REACHED_REPLIED
https://github.com/dovecot/pigeonhole/commit/25e1e0adfa4ad44e3205fc8c62ca26a73cf6ee41
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 Pigeonhole 0.5.21.1.
The Dovecot part of this fix is in mail/dovecot/patches.
--- a/src/managesieve-login/managesieve-proxy.c
+++ b/src/managesieve-login/managesieve-proxy.c
@@ -612,7 +612,7 @@ int managesieve_proxy_parse_line(struct
if (try_later)
failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_TEMPFAIL;
else {
- failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH;
+ failure_type = LOGIN_PROXY_FAILURE_TYPE_AUTH_REPLIED;
client_send_no(client, AUTH_FAILED_MSG);
}
@@ -655,6 +655,7 @@ managesieve_proxy_send_failure_reply(str
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_code(client, MANAGESIEVE_CMD_REPLY_NO,
NULL, LOGIN_PROXY_FAILURE_MSG);
break;
@@ -662,7 +663,8 @@ managesieve_proxy_send_failure_reply(str
client_send_reply_code(client, MANAGESIEVE_CMD_REPLY_NO,
"TRYLATER", 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;
}
@@ -0,0 +1,179 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-40204
Upstream commits:
lib-sieve: actions - Split mailbox creation into sieve_act_store_create_mailbox()
https://github.com/dovecot/pigeonhole/commit/4010e318939b557b0cdf7da3ae0f320d408aea65
lib-sieve: actions - Create fileinto mailbox without the autocreate flag
https://github.com/dovecot/pigeonhole/commit/eec184745fabe1b2da0d5cc343f2a46710b70fc7
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 Pigeonhole 0.5.21.1.
The Dovecot part of this fix is in mail/dovecot/patches.
--- a/src/lib-sieve/plugins/mailbox/tag-mailbox-create.c
+++ b/src/lib-sieve/plugins/mailbox/tag-mailbox-create.c
@@ -150,36 +150,8 @@ seff_mailbox_create_pre_execute(
return SIEVE_EXEC_FAILURE;
}
- trans->error = NULL;
- trans->error_code = MAIL_ERROR_NONE;
-
- /* Create mailbox */
- if (mailbox_create(box, NULL, FALSE) < 0) {
- sieve_act_store_get_storage_error(aenv, trans);
- if (trans->error_code == MAIL_ERROR_EXISTS) {
- trans->error = NULL;
- trans->error_code = MAIL_ERROR_NONE;
- } else {
- return (trans->error_code == MAIL_ERROR_TEMP ?
- SIEVE_EXEC_TEMP_FAILURE : SIEVE_EXEC_FAILURE);
- }
- }
-
- /* Subscribe to it if necessary */
- if (eenv->scriptenv->mailbox_autosubscribe) {
- (void)mailbox_list_set_subscribed(
- mailbox_get_namespace(box)->list,
- mailbox_get_name(box), TRUE);
- }
-
- /* Try opening again */
- if (mailbox_open(box) < 0) {
- /* Failed definitively */
- sieve_act_store_get_storage_error(aenv, trans);
- return (trans->error_code == MAIL_ERROR_TEMP ?
- SIEVE_EXEC_TEMP_FAILURE : SIEVE_EXEC_FAILURE);
- }
- return SIEVE_EXEC_OK;
+ /* Create the mailbox */
+ return sieve_act_store_create_mailbox(aenv, trans);
}
--- a/src/lib-sieve/sieve-actions.c
+++ b/src/lib-sieve/sieve-actions.c
@@ -373,6 +373,68 @@ void sieve_act_store_get_storage_error(c
&trans->error_code));
}
+int sieve_act_store_create_error_status(
+ const struct sieve_action_exec_env *aenv, enum mail_error error_code)
+{
+ const struct sieve_execute_env *eenv = aenv->exec_env;
+
+ switch (error_code) {
+ case MAIL_ERROR_NONE:
+ return SIEVE_EXEC_OK;
+ case MAIL_ERROR_TEMP:
+ return SIEVE_EXEC_TEMP_FAILURE;
+ case MAIL_ERROR_PERM:
+ /* The mailbox cannot be created because of insufficient
+ permissions. This is a permanent condition. For a user's
+ personal script, fall through to implicit keep rather than
+ deferring the message. For a global (administrator-defined)
+ script, defer instead, so that the administrator notices the
+ script is behaving in a way they did not intend. */
+ if ((eenv->flags & SIEVE_EXECUTE_FLAG_NOGLOBAL) != 0)
+ return SIEVE_EXEC_FAILURE;
+ return SIEVE_EXEC_TEMP_FAILURE;
+ default:
+ return SIEVE_EXEC_FAILURE;
+ }
+}
+
+int sieve_act_store_create_mailbox(const struct sieve_action_exec_env *aenv,
+ struct act_store_transaction *trans)
+{
+ const struct sieve_execute_env *eenv = aenv->exec_env;
+ struct mailbox *box = trans->box;
+
+ trans->error = NULL;
+ trans->error_code = MAIL_ERROR_NONE;
+
+ /* Create mailbox */
+ if (mailbox_create(box, NULL, FALSE) < 0) {
+ sieve_act_store_get_storage_error(aenv, trans);
+ if (trans->error_code != MAIL_ERROR_EXISTS) {
+ return sieve_act_store_create_error_status(
+ aenv, trans->error_code);
+ }
+ /* Lost a race with another session; the mailbox exists now. */
+ trans->error = NULL;
+ trans->error_code = MAIL_ERROR_NONE;
+ }
+
+ /* Subscribe to it if necessary */
+ if (eenv->scriptenv->mailbox_autosubscribe) {
+ (void)mailbox_list_set_subscribed(
+ mailbox_get_namespace(box)->list,
+ mailbox_get_name(box), TRUE);
+ }
+
+ /* Try opening again */
+ if (mailbox_open(box) < 0) {
+ sieve_act_store_get_storage_error(aenv, trans);
+ return sieve_act_store_create_error_status(
+ aenv, trans->error_code);
+ }
+ return SIEVE_EXEC_OK;
+}
+
static bool
act_store_mailbox_alloc(const struct sieve_action_exec_env *aenv,
const char *mailbox, struct mailbox **box_r,
@@ -397,10 +459,6 @@ act_store_mailbox_alloc(const struct sie
return FALSE;
}
- if (eenv->scriptenv->mailbox_autocreate)
- flags |= MAILBOX_FLAG_AUTO_CREATE;
- if (eenv->scriptenv->mailbox_autosubscribe)
- flags |= MAILBOX_FLAG_AUTO_SUBSCRIBE;
*box_r = box = mailbox_alloc_for_user(eenv->scriptenv->user, mailbox,
flags);
*storage = mailbox_get_storage(box);
@@ -603,6 +661,16 @@ act_store_execute(const struct sieve_act
}
}
+ /* Create the mailbox if it does not exist yet and autocreation is
+ enabled (e.g. lda_mailbox_autocreate=yes). The :create side effect
+ creates it earlier; this handles a plain fileinto. */
+ if (trans->error_code == MAIL_ERROR_NOTFOUND &&
+ eenv->scriptenv->mailbox_autocreate) {
+ int cstatus = sieve_act_store_create_mailbox(aenv, trans);
+ if (cstatus != SIEVE_EXEC_OK)
+ return cstatus;
+ }
+
/* Exit early if transaction already failed */
switch (trans->error_code) {
case MAIL_ERROR_NONE:
--- a/src/lib-sieve/sieve-actions.h
+++ b/src/lib-sieve/sieve-actions.h
@@ -246,6 +246,20 @@ void sieve_act_store_add_flags(const str
void sieve_act_store_get_storage_error(const struct sieve_action_exec_env *aenv,
struct act_store_transaction *trans);
+/* Map a failure to create the target mailbox to an execution status. A
+ permanent failure (e.g. the user lacks permission to create the mailbox)
+ makes a user's personal script fall through to implicit keep, but is
+ deferred for a global (administrator-defined) script, so that the
+ unintended behaviour is surfaced to the administrator. */
+int sieve_act_store_create_error_status(
+ const struct sieve_action_exec_env *aenv, enum mail_error error_code);
+
+/* Create the target mailbox of the store transaction (and subscribe to it
+ when configured). Returns SIEVE_EXEC_OK on success, or the status from
+ sieve_act_store_create_error_status() on failure. */
+int sieve_act_store_create_mailbox(const struct sieve_action_exec_env *aenv,
+ struct act_store_transaction *trans);
+
/*
* Redirect action
*/
@@ -0,0 +1,42 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Stephan Bosch <stephan.bosch@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-33605
Upstream commits:
lib-managesieve: managesieve-parser - Fix handling of lone CR character
https://github.com/dovecot/pigeonhole/commit/4ef39dbda7ed2c4f48e8aa91420075132ea723cf
managesieve-login: client_skip_line() - Discard data when newline is not found
https://github.com/dovecot/pigeonhole/commit/19dc05d272c7d30cd80828f304dd9e9e7516063c
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 Pigeonhole 0.5.21.1.
--- a/src/lib-managesieve/managesieve-parser.c
+++ b/src/lib-managesieve/managesieve-parser.c
@@ -441,6 +441,15 @@ static bool managesieve_parser_read_arg(
switch (data[0]) {
case '\r':
+ if (data_size == 1) {
+ /* Wait for LF */
+ return FALSE;
+ }
+ if (data[1] != '\n') {
+ parser->error = "CR sent without LF";
+ return FALSE;
+ }
+ /* Fall through */
case '\n':
/* Unexpected end of line */
parser->eol = TRUE;
--- a/src/managesieve-login/client.c
+++ b/src/managesieve-login/client.c
@@ -49,6 +49,7 @@ bool client_skip_line(struct managesieve
}
}
+ i_stream_skip(client->common.input, data_size);
return FALSE;
}
@@ -0,0 +1,38 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Stephan Bosch <stephan.bosch@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-40013
Upstream commits:
lib-sieve: sieve-binary-code - Fix single byte oob stack buffer write in sieve_binary_emit_integer()
https://github.com/dovecot/pigeonhole/commit/3f0af33abcc9911b586be9b5adc0afb3e9f18d25
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 Pigeonhole 0.5.21.1.
--- a/src/lib-sieve/sieve-binary-code.c
+++ b/src/lib-sieve/sieve-binary-code.c
@@ -124,7 +124,7 @@ sieve_size_t sieve_binary_emit_integer(s
sieve_number_t integer)
{
sieve_size_t address = _sieve_binary_block_get_size(sblock);
- uint8_t buffer[sizeof(sieve_number_t) + 1];
+ uint8_t buffer[sizeof(sieve_number_t) * 8 / 7 + 1];
int bufpos = sizeof(buffer) - 1;
/* Encode last byte [0xxxxxxx]; msb == 0 marks the last byte */
--- a/tests/test-size.svtest
+++ b/tests/test-size.svtest
@@ -72,3 +72,12 @@ test "Exact size" {
}
}
+/*
+ * TEST: Extreme size
+ */
+
+test "Extreme size" {
+ if size :over 18446744073709551615 {
+ test_fail "size :over matched extreme size";
+ }
+}
@@ -0,0 +1,295 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-42007
Upstream commits:
lib-sieve: util: edit-mail - Fix writing to freed memory
https://github.com/dovecot/pigeonhole/commit/444972cfac3246b25c133c8868cfc013902cd1f3
lib-sieve: edit_mail_headers_parse() - Fix info leak via NUL-truncated header copy
https://github.com/dovecot/pigeonhole/commit/b49656de9a7b766b7fa2736ad8dbcf05057b3732
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 Pigeonhole 0.5.21.1.
--- a/Makefile.am
+++ b/Makefile.am
@@ -155,10 +155,12 @@ test_cases = \
tests/extensions/ihave/restrictions.svtest \
tests/extensions/editheader/addheader.svtest \
tests/extensions/editheader/deleteheader.svtest \
+ tests/extensions/editheader/deleteheader-snapshot.svtest \
tests/extensions/editheader/alternating.svtest \
tests/extensions/editheader/utf8.svtest \
tests/extensions/editheader/protected.svtest \
tests/extensions/editheader/errors.svtest \
+ tests/extensions/editheader/nul-value.svtest \
tests/extensions/editheader/execute.svtest \
tests/extensions/duplicate/errors.svtest \
tests/extensions/duplicate/execute.svtest \
--- a/src/lib-sieve/util/edit-mail.c
+++ b/src/lib-sieve/util/edit-mail.c
@@ -550,8 +550,9 @@ edit_mail_header_field_create(struct edi
&field->body_offset);
/* Copy to new field */
- field->data = i_strndup(str_data(data), str_len(data));
field->size = str_len(data);
+ field->data = i_malloc(field->size + 1);
+ memcpy(field->data, str_data(data), field->size);
field->virtual_size = (edmail->crlf ?
field->size : field->size + lines);
field->lines = lines;
@@ -828,8 +829,9 @@ static int edit_mail_headers_parse(struc
field->size = str_len(hdr_data);
field->virtual_size = field->size + vsize_diff;
- field->data = i_strndup(str_data(hdr_data),
- field->size);
+ field->data = i_malloc(field->size + 1);
+ memcpy(field->data, str_data(hdr_data),
+ field->size);
field->offset = offset;
field->lines = lines;
@@ -887,7 +889,17 @@ static int edit_mail_headers_parse(struc
}
}
- /* Rebuild header index */
+ /* Rebuild header index. Reset first pointers before rebuilding so that
+ the actual first occurrence in the final list is used. Without this,
+ a snapshot's pre-set first pointer may refer to an appended field
+ that sits later in the list than a parsed field with the same header,
+ causing deleteheader to miss the parsed fields while still freeing
+ the header_index — leaving stale field_idx->header pointers. */
+ struct _header_index *hidx = edmail->headers_head;
+ while (hidx != NULL) {
+ hidx->first = NULL;
+ hidx = hidx->next;
+ }
current = edmail->header_fields_head;
while (current != NULL) {
if (current->header->first == NULL)
--- a/src/lib-sieve/util/test-edit-mail.c
+++ b/src/lib-sieve/util/test-edit-mail.c
@@ -809,12 +809,91 @@ static void test_edit_mail_small_buffer(
test_end();
}
+static void test_edit_mail_nul_in_header(void)
+{
+ /* Message with a NUL byte embedded in the X-Has-NUL header value.
+ * sizeof() - 1 gives the true byte count, skipping the C string's
+ * trailing NUL terminator, while preserving the embedded \x00. */
+ static const unsigned char message[] =
+ "From: sender@example.com\n"
+ "X-Has-NUL: value\x00" "afterNUL\n"
+ "Subject: Test\n"
+ "\n"
+ "Body\n";
+ /* Expected output after deleting the Subject header. */
+ static const unsigned char expected[] =
+ "From: sender@example.com\n"
+ "X-Has-NUL: value\x00" "afterNUL\n"
+ "\n"
+ "Body\n";
+ struct istream *input_msg, *input_mail;
+ buffer_t *buffer;
+ struct mail_raw *rawmail;
+ struct edit_mail *edmail;
+ struct mail *mail;
+
+ test_begin("edit-mail - NUL byte in header value");
+ test_init();
+
+ /* sizeof - 1 excludes the trailing C-string NUL terminator */
+ input_msg = i_stream_create_from_data(message, sizeof(message) - 1);
+
+ rawmail = mail_raw_open_stream(test_raw_mail_user, input_msg);
+ edmail = edit_mail_wrap(rawmail->mail);
+
+ /* Deleting any header triggers edit_mail_headers_parse(), which with
+ * the old i_strndup() allocated only strlen("X-Has-NUL: value")+1=17
+ * bytes for X-Has-NUL's field->data even though field->size=26.
+ * Streaming then called memcpy(dst, field->data, 26), reading 9 bytes
+ * past the end of the allocation and producing garbage in place of
+ * "afterNUL\n". */
+ edit_mail_header_delete(edmail, "Subject", 0);
+
+ mail = edit_mail_get_mail(edmail);
+
+ if (mail_get_stream(mail, NULL, NULL, &input_mail) < 0) {
+ i_fatal("Failed to open mail stream: %s",
+ mailbox_get_last_internal_error(mail->box, NULL));
+ }
+
+ buffer = buffer_create_dynamic(default_pool, 128);
+
+ /* normal */
+
+ i_stream_seek(input_mail, 0);
+ test_stream_data(input_mail, buffer);
+
+ test_out("nul in header",
+ buffer->used == sizeof(expected) - 1 &&
+ memcmp(buffer->data, expected, sizeof(expected) - 1) == 0);
+
+ /* slow (byte-by-byte) */
+
+ i_stream_seek(input_mail, 0);
+ buffer_set_used_size(buffer, 0);
+ test_stream_data_slow(input_mail, buffer);
+
+ test_out("nul in header, slow",
+ buffer->used == sizeof(expected) - 1 &&
+ memcmp(buffer->data, expected, sizeof(expected) - 1) == 0);
+
+ /* clean up */
+
+ buffer_free(&buffer);
+ edit_mail_unwrap(&edmail);
+ mail_raw_close(&rawmail);
+ i_stream_unref(&input_msg);
+ test_deinit();
+ test_end();
+}
+
int main(int argc, char *argv[])
{
static void (*test_functions[])(void) = {
test_edit_mail_concatenated,
test_edit_mail_big_header,
test_edit_mail_small_buffer,
+ test_edit_mail_nul_in_header,
NULL
};
const enum master_service_flags service_flags =
--- /dev/null
+++ b/tests/extensions/editheader/deleteheader-snapshot.svtest
@@ -0,0 +1,76 @@
+require "vnd.dovecot.testsuite";
+require "editheader";
+require "fileinto";
+require "mailbox";
+
+/*
+ * Regression test: heap use-after-free in edit_mail_snapshot when
+ * deleteheader is called after a fileinto snapshot on an edit_mail
+ * whose headers have not yet been parsed.
+ */
+
+test_set "message" text:
+From: sender@example.com
+To: recipient@example.com
+Cc: original@example.com
+Subject: Test
+
+Body.
+.
+;
+
+test "deleteheader all: snapshot stale first pointer after parse" {
+ /* Add a Cc header while headers are not yet parsed. The snapshot
+ * created by the next fileinto has H_clone_cc->first pointing at
+ * this appended field. */
+ addheader :last "Cc" "appended@example.com";
+
+ /* fileinto sets edit_snapshot=TRUE. The next call to
+ * sieve_message_edit creates a snapshot (edmail_snap) and the
+ * fileinto action retains the pre-snapshot version for delivery. */
+ fileinto :create "folder1";
+
+ /* sieve_message_edit creates edmail_snap here. edit_mail_headers_parse
+ * inserts the parsed "Cc: original@example.com" before the appended
+ * field in the list. Without the fix the rebuild skips resetting
+ * ->first; the delete loop then only removes the appended field,
+ * frees H_clone_cc (index==0), and leaves the parsed field_idx with
+ * a dangling ->header pointer. */
+ deleteheader "Cc";
+
+ /* A second fileinto + edit operation takes another snapshot of the
+ * same edmail_snap. edit_mail_snapshot walks header_fields_head and
+ * reads field_idx->header->header on the orphaned entry.
+ * Without the fix: use-after-free crash.
+ * With the fix: clean run, both Cc occurrences are correctly gone. */
+ fileinto :create "folder2";
+ deleteheader "Subject";
+
+ if not test_result_execute {
+ test_fail "failed to execute result";
+ }
+
+ /* folder1 was snapshotted before deleteheader "Cc": both Cc headers
+ * must be present. */
+ if not test_message :folder "folder1" 0 {
+ test_fail "message not stored in folder1";
+ }
+
+ if not header :is "Cc" "original@example.com" {
+ test_fail "original Cc missing in folder1 snapshot";
+ }
+
+ if not header :is "Cc" "appended@example.com" {
+ test_fail "appended Cc missing in folder1 snapshot";
+ }
+
+ /* folder2 was snapshotted after deleteheader "Cc": both Cc headers
+ * must be absent. */
+ if not test_message :folder "folder2" 0 {
+ test_fail "message not stored in folder2";
+ }
+
+ if exists "Cc" {
+ test_fail "Cc header not fully deleted in folder2 snapshot";
+ }
+}
--- /dev/null
+++ b/tests/extensions/editheader/nul-value.svtest
@@ -0,0 +1,46 @@
+require "vnd.dovecot.testsuite";
+require "encoded-character";
+require "variables";
+require "fileinto";
+require "mailbox";
+
+require "editheader";
+
+/*
+ * Regression test: edit_mail_headers_parse() used i_strndup() to copy the
+ * raw header data, which stopped at the first NUL byte and allocated a buffer
+ * shorter than field->size. When the modified message was subsequently
+ * streamed (e.g. fileinto), memcpy() read field->size bytes out of that
+ * under-sized buffer, causing an invalid heap read detectable by valgrind.
+ */
+
+/* Construct a raw message that has a NUL byte inside a header value.
+ * ${hex:00} = NUL. field->size covers the full header line including
+ * bytes after the NUL; the old i_strndup() only allocated up to the NUL. */
+test_set "message" text:
+From: sender@example.com
+X-Has-NUL: value${hex:00}afterNUL
+Subject: Test
+
+Body
+.
+;
+
+test "editheader - NUL byte in header value" {
+ /* deleteheader calls edit_mail_headers_parse(), which allocates
+ * field->data for every header including X-Has-NUL. With the old
+ * i_strndup() code, X-Has-NUL's allocation is only strlen("value")+1
+ * bytes, but field->size covers the full extent including bytes after
+ * the NUL. deleteheader also sets modified=TRUE. */
+ deleteheader "Subject";
+
+ fileinto :create "nul-test";
+
+ /* Streaming iterates over all remaining parsed headers including
+ * X-Has-NUL, reading field->size bytes from field->data. With the
+ * old under-sized allocation this is an invalid heap read that
+ * valgrind detects. */
+ if not test_result_execute {
+ test_fail "failed to execute result";
+ }
+}
@@ -0,0 +1,327 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-42394
Upstream commits:
lib-sieve: storage: file - Refuse symlinks escaping personal storage directory
https://github.com/dovecot/pigeonhole/commit/abfb0c1fe180f0edd5527c05cb7dd97840a31ea1
lib-sieve: storage: file - Validate script stat path through dir_fd
https://github.com/dovecot/pigeonhole/commit/915cb2edc90da04d8a7a122fef7932cd55e3fff2
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 Pigeonhole 0.5.21.1.
The Dovecot part of this fix is in mail/dovecot/patches.
--- a/src/lib-sieve/storage/file/sieve-file-script.c
+++ b/src/lib-sieve/storage/file/sieve-file-script.c
@@ -273,6 +273,57 @@ static int sieve_file_script_stat
return 0;
}
+/* TOCTOU-safe variant of sieve_file_script_stat() for directory storages.
+ Resolves the script entry beneath fstorage->dir_fd, refusing symlinks
+ whose target escapes the storage directory. *st gets the (resolved)
+ target's stat; *lnk_st gets the directory entry's own stat (i.e.
+ AT_SYMLINK_NOFOLLOW), matching the semantics of the unsafe variant. */
+static int
+sieve_file_script_stat_safe(struct sieve_file_storage *fstorage,
+ const char *filename, struct stat *st,
+ struct stat *lnk_st, const char **error_r)
+{
+ int fd, saved_errno;
+
+ i_assert(fstorage->dir_fd >= 0);
+
+ if (fstatat(fstorage->dir_fd, filename, lnk_st,
+ AT_SYMLINK_NOFOLLOW) < 0) {
+ *error_r = t_strdup_printf(
+ "fstatat(%s/%s) failed: %m",
+ fstorage->path, filename);
+ return -1;
+ }
+
+ if (!S_ISLNK(lnk_st->st_mode)) {
+ *st = *lnk_st;
+ return 0;
+ }
+
+ /* Symlink: open it via the safe walker (which refuses any target
+ that leaves fstorage->dir_fd) and read st from the resulting fd.
+ The fd is only used to fetch the resolved stat and is closed
+ immediately. Open with O_NONBLOCK so that a target which resolves
+ to a FIFO or other special file inside the storage directory only
+ yields its stat instead of blocking the delivery process. */
+ if (sieve_file_storage_open_safe(fstorage, filename,
+ O_RDONLY | O_NONBLOCK,
+ &fd, error_r) < 0)
+ return -1;
+
+ if (fstat(fd, st) < 0) {
+ saved_errno = errno;
+ *error_r = t_strdup_printf(
+ "fstat() failed for '%s/%s': %m",
+ fstorage->path, filename);
+ i_close_fd(&fd);
+ errno = saved_errno;
+ return -1;
+ }
+ i_close_fd(&fd);
+ return 0;
+}
+
static const char *
path_split_filename(const char *path, const char **dirpath_r)
{
@@ -342,7 +393,25 @@ static int sieve_file_script_open
dirpath = path;
path = sieve_file_storage_path_extend(fstorage, filename);
- ret = sieve_file_script_stat(path, &st, &lnk_st);
+ if (fstorage->dir_fd >= 0) {
+ const char *serror;
+
+ ret = sieve_file_script_stat_safe(
+ fstorage, filename, &st,
+ &lnk_st, &serror);
+ if (ret < 0 && errno == ELOOP) {
+ sieve_script_set_critical(
+ script,
+ "Failed to open sieve script: %s",
+ serror);
+ script->storage->error_code =
+ SIEVE_ERROR_NO_PERMISSION;
+ success = FALSE;
+ }
+ } else {
+ ret = sieve_file_script_stat(
+ path, &st, &lnk_st);
+ }
}
} else {
@@ -425,15 +494,51 @@ static int sieve_file_script_get_stream
(struct sieve_script *script, struct istream **stream_r,
enum sieve_error *error_r)
{
- struct sieve_file_script *fscript = (struct sieve_file_script *)script;
+ struct sieve_file_script *fscript =
+ container_of(script, struct sieve_file_script, script);
+ struct sieve_file_storage *fstorage =
+ container_of(script->storage, struct sieve_file_storage,
+ storage);
struct stat st;
struct istream *result;
+ const char *error;
int fd;
- if ( (fd=open(fscript->path, O_RDONLY)) < 0 ) {
- sieve_file_script_handle_error
- (fscript, "open", fscript->path, fscript->script.name, error_r);
- return -1;
+ /* For directory-based storage, open the script via the storage
+ directory fd so that path resolution refuses to follow symlinks
+ whose (recursive) target leaves the storage directory. The fd-based
+ walk also makes this TOCTOU-safe: even if intermediate path
+ components are mutated between the stat in sieve_file_script_open()
+ and this call, the resolution stays within the original directory.
+ Single-file storages have no dir_fd, so fall back to a plain open(). */
+ if (fstorage->dir_fd >= 0 && fscript->filename != NULL &&
+ *fscript->filename != '\0') {
+ if (sieve_file_storage_open_safe(fstorage, fscript->filename,
+ O_RDONLY, &fd, &error) < 0) {
+ if (errno == ELOOP) {
+ sieve_script_set_critical(
+ script,
+ "Failed to open sieve script: %s",
+ error);
+ script->storage->error_code =
+ SIEVE_ERROR_NO_PERMISSION;
+ return -1;
+ }
+ sieve_file_script_handle_error(fscript, "open",
+ fscript->path,
+ fscript->script.name,
+ error_r);
+ return -1;
+ }
+ } else {
+ fd = open(fscript->path, O_RDONLY);
+ if (fd < 0) {
+ sieve_file_script_handle_error(fscript, "open",
+ fscript->path,
+ fscript->script.name,
+ error_r);
+ return -1;
+ }
}
if ( fstat(fd, &st) != 0 ) {
--- a/src/lib-sieve/storage/file/sieve-file-storage.c
+++ b/src/lib-sieve/storage/file/sieve-file-storage.c
@@ -21,6 +21,7 @@
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
+#include <fcntl.h>
#include <utime.h>
#include <sys/time.h>
@@ -42,6 +43,33 @@ const char *sieve_file_storage_path_exte
return t_strconcat(path, "/", filename , NULL);
}
+int sieve_file_storage_open_safe(struct sieve_file_storage *fstorage,
+ const char *path, int flags, int *fd_r,
+ const char **error_r)
+{
+ const char *walk_error;
+ int fd;
+
+ *fd_r = -1;
+
+ if (fstorage->dir_fd < 0) {
+ *error_r = "storage directory fd not available";
+ errno = ENOTSUP;
+ return -1;
+ }
+
+ fd = t_openat_safe(fstorage->dir_fd, path, flags, &walk_error);
+ if (fd < 0) {
+ *error_r = t_strdup_printf(
+ "Failed to open '%s/%s': %s",
+ fstorage->path, path, walk_error);
+ return -1;
+ }
+
+ *fd_r = fd;
+ return 0;
+}
+
/*
*
*/
@@ -221,10 +249,19 @@ static struct sieve_storage *sieve_file_
fstorage = p_new(pool, struct sieve_file_storage, 1);
fstorage->storage = sieve_file_storage;
fstorage->storage.pool = pool;
+ fstorage->dir_fd = -1;
return &fstorage->storage;
}
+static void sieve_file_storage_destroy(struct sieve_storage *storage)
+{
+ struct sieve_file_storage *fstorage =
+ container_of(storage, struct sieve_file_storage, storage);
+
+ i_close_fd(&fstorage->dir_fd);
+}
+
static int sieve_file_storage_get_full_path
(struct sieve_file_storage *fstorage, const char **storage_path,
enum sieve_error *error_r)
@@ -477,6 +514,46 @@ static int sieve_file_storage_init_commo
fstorage->link_path = p_strdup(storage->pool, link_path);
}
+
+ /* For personal (user-writable) storage, open a fd to the
+ canonical storage directory. This fd anchors TOCTOU-safe
+ path resolution for script lookups: the inode it refers to
+ cannot change underneath us, so even if the user mutates
+ intermediate path components on disk afterwards, we still
+ resolve relative to the original directory. The walker that
+ uses this fd refuses script paths that escape the storage
+ directory through symlinks or `..`, which would otherwise
+ let an unprivileged user redirect e.g. include "name" to a
+ file outside their own sieve storage.
+
+ Non-personal (e.g. admin-configured global) storage is
+ trusted; dir_fd stays unset there so legitimate
+ admin-managed symlinks crossing the storage boundary keep
+ working.
+
+ Only open the fd when storage_path actually resolves to a
+ directory: autodetect can leave is_file=FALSE while
+ storage_path still points at a regular file (see the
+ storage_path == active_path fallback in
+ sieve_file_storage_do_autodetect()). In that case there is
+ no directory to anchor to and lookups by name will fail
+ with ENOENT later anyway. */
+ /* 2.3.19 sets main_storage=TRUE for personal scripts, see
+ ext_include_get_script_storage() in
+ src/lib-sieve/plugins/include/cmd-include.c so we can safely
+ use storage->main_storage here. */
+ if (storage->main_storage &&
+ S_ISDIR(fstorage->st.st_mode)) {
+ fstorage->dir_fd = open(storage_path,
+ O_RDONLY | O_DIRECTORY |
+ O_CLOEXEC);
+ if (fstorage->dir_fd < 0) {
+ sieve_storage_set_critical(storage,
+ "Failed to open storage directory: "
+ "open(%s) failed: %m", storage_path);
+ return -1;
+ }
+ }
}
fstorage->path = p_strdup(storage->pool, storage_path);
@@ -881,6 +958,7 @@ const struct sieve_storage sieve_file_st
.v = {
.alloc = sieve_file_storage_alloc,
.init = sieve_file_storage_init,
+ .destroy = sieve_file_storage_destroy,
.get_last_change = sieve_file_storage_get_last_change,
.set_modified = sieve_file_storage_set_modified,
--- a/src/lib-sieve/storage/file/sieve-file-storage.h
+++ b/src/lib-sieve/storage/file/sieve-file-storage.h
@@ -40,6 +40,13 @@ struct sieve_file_storage {
gid_t file_create_gid;
time_t prev_mtime;
+
+ /* fd referencing the canonical (realpath'd) storage directory. Used to
+ anchor TOCTOU-safe path resolution for script files: lookups that
+ escape this directory via symlinks (or `..`) are refused. -1 if the
+ storage is a single-file storage or this protection is unavailable.
+ */
+ int dir_fd;
};
const char *sieve_file_storage_path_extend
@@ -53,6 +60,31 @@ struct sieve_file_storage *sieve_file_st
int sieve_file_storage_pre_modify
(struct sieve_storage *storage);
+/* Open a script file that lives under the storage directory, refusing any
+ path resolution that escapes that directory through symlinks or `..`.
+
+ The path is resolved component-by-component using openat() relative to
+ fstorage->dir_fd, with O_NOFOLLOW per component. Symlinks are followed
+ only if their (recursively resolved) target also stays beneath dir_fd;
+ absolute symlink targets and `..` past the storage root are refused.
+
+ Anchoring the resolution at dir_fd makes the check TOCTOU-safe: even if
+ the user mutates path components on disk between calls, dir_fd still
+ refers to the original directory inode.
+
+ `flags` is OR-ed into the openat() call for the final component (e.g.
+ O_RDONLY). O_NOFOLLOW and O_CLOEXEC are added automatically.
+
+ Returns 0 on success and stores the new fd in *fd_r. Returns -1 on
+ failure with errno set; *error_r is set to a descriptive message.
+ errno=ELOOP indicates either too many symlinks or an attempted escape.
+ errno=ENOTSUP indicates fstorage->dir_fd is not available; the caller
+ may fall back to opening fstorage->path directly.
+ */
+int sieve_file_storage_open_safe(struct sieve_file_storage *fstorage,
+ const char *path, int flags, int *fd_r,
+ const char **error_r);
+
/* Active script */
int sieve_file_storage_active_replace_link
@@ -0,0 +1,891 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Aki Tuomi <aki.tuomi@open-xchange.com>
Subject: [PATCH] Fix CVE-2026-52681
Upstream commits:
lib-sieve: Reduce CPU limit check interval in :contains and :matches matchers
https://github.com/dovecot/pigeonhole/commit/01c95a5503ec53c40f12d40de0b508838f6b041d
lib-sieve: Add per-user sieve-rusage file for cumulative CPU tracking
https://github.com/dovecot/pigeonhole/commit/da28fa5a900dc521a7f6cadf9320650dcad3cf18
lib-sieve: Drop binary-header resource usage tracking
https://github.com/dovecot/pigeonhole/commit/64e1f7af273809f484fb983d4a6edb1af1a85c99
lib-sieve: Rename on-disk header rusage fields to unused_*
https://github.com/dovecot/pigeonhole/commit/e0c8bcd5d0d8bbd39edb2bc78cd15f469834660a
lib-sieve: Switch sieve_max_cpu_time enforcement to time-decayed re-enable
https://github.com/dovecot/pigeonhole/commit/7a55953924c54dc116150ae809b976456977db75
lib-sieve: file storage: Remove orphan compiled binaries on delete and rename
https://github.com/dovecot/pigeonhole/commit/88470b80fb4079cd2207bc8c4e986b816218421e
lib-sieve: Log a warning when cumulative CPU exceeds the limit
https://github.com/dovecot/pigeonhole/commit/025233779751d7ba8cff7c615f8e229b604d92a5
lib-sieve: Log an info line when opening a CPU-disabled script
https://github.com/dovecot/pigeonhole/commit/800697eaa3b753d7a449fb7da62f41a21b02925e
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 Pigeonhole 0.5.21.1.
The Dovecot part of this fix is in mail/dovecot/patches.
Adjusted for this version:
- sieve-binary.c, kept the comparison without the (time_t) cast of
0.5.21.1 (the cast comes from the Debian-only
Fix-32bit-sign-comparisons patch), switched i_zero to
sbin->persisted_rusage as upstream
--- a/src/lib-sieve/Makefile.am
+++ b/src/lib-sieve/Makefile.am
@@ -108,6 +108,7 @@ libdovecot_sieve_la_SOURCES = \
sieve-ast.c \
sieve-binary.c \
sieve-binary-file.c \
+ sieve-rusage.c \
sieve-binary-code.c \
sieve-binary-debug.c \
sieve-parser.c \
@@ -156,6 +157,7 @@ headers = \
sieve-ast.h \
sieve-binary.h \
sieve-binary-private.h \
+ sieve-rusage.h \
sieve-parser.h \
sieve-address.h \
sieve-validator.h \
--- a/src/lib-sieve/mcht-contains.c
+++ b/src/lib-sieve/mcht-contains.c
@@ -45,7 +45,7 @@ const struct sieve_match_type_def contai
* configured sieve_max_cpu_time (which is otherwise only checked between
* bytecode operations).
*/
-#define SIEVE_CONTAINS_CPU_CHECK_INTERVAL 4096
+#define SIEVE_CONTAINS_CPU_CHECK_INTERVAL 64
static int mcht_contains_match_key
(struct sieve_match_context *mctx, const char *val, size_t val_size,
--- a/src/lib-sieve/mcht-matches.c
+++ b/src/lib-sieve/mcht-matches.c
@@ -53,7 +53,7 @@ const struct sieve_match_type_def matche
* configured sieve_max_cpu_time. Returns 1 on match, 0 on exhaustion, or -1
* when the CPU time limit was exceeded (mctx->exec_status is set).
*/
-#define SIEVE_MATCHES_CPU_CHECK_INTERVAL 4096
+#define SIEVE_MATCHES_CPU_CHECK_INTERVAL 64
static int
_string_find(struct sieve_match_context *mctx,
--- a/src/lib-sieve/sieve-binary-dumper.c
+++ b/src/lib-sieve/sieve-binary-dumper.c
@@ -6,7 +6,6 @@
#include "ostream.h"
#include "array.h"
#include "buffer.h"
-#include "time-util.h"
#include "sieve-common.h"
#include "sieve-extensions.h"
@@ -117,17 +116,6 @@ bool sieve_binary_dumper_run(struct siev
"flags = 0x%08"PRIx32"\n",
header->version_major, header->version_minor,
header->flags);
- if (header->resource_usage.update_time != 0) {
- time_t update_time =
- (time_t)header->resource_usage.update_time;
- sieve_binary_dumpf(denv,
- "resource usage:\n"
- " update time = %s\n"
- " cpu time = %"PRIu32" ms\n",
- t_strflocaltime("%Y-%m-%d %H:%M:%S",
- update_time),
- header->resource_usage.cpu_time_msecs);
- }
/* Dump list of binary blocks */
--- a/src/lib-sieve/sieve-binary-file.c
+++ b/src/lib-sieve/sieve-binary-file.c
@@ -18,6 +18,9 @@
#include "sieve-extensions.h"
#include "sieve-code.h"
#include "sieve-script.h"
+#include "sieve-script-private.h"
+#include "sieve-storage-private.h"
+#include "sieve-rusage.h"
#include "sieve-binary-private.h"
@@ -147,49 +150,16 @@ sieve_binary_file_read_header(struct sie
return 0;
}
-static int
-sieve_binary_file_write_header(struct sieve_binary *sbin, int fd,
- struct sieve_binary_header *header,
- enum sieve_error *error_r) ATTR_NULL(4)
-{
- ssize_t wret;
-
- wret = pwrite(fd, header, sizeof(*header), 0);
- if (wret < 0) {
- e_error(sbin->event, "update: "
- "failed to write to binary: %m");
- if (error_r != NULL)
- *error_r = SIEVE_ERROR_TEMP_FAILURE;
- return -1;
- } else if (wret != sizeof(*header)) {
- e_error(sbin->event, "update: "
- "header written partially %zd/%zu",
- wret, sizeof(*header));
- if (error_r != NULL)
- *error_r = SIEVE_ERROR_TEMP_FAILURE;
- return -1;
- }
- return 0;
-}
-
-static void sieve_binary_file_update_header(struct sieve_binary *sbin)
+/* The on-disk binary header carries unused resource_usage fields for
+ backward compatibility. Tracking lives in the per-user sieve-rusage file. */
+static void sieve_binary_file_zero_header_rusage(struct sieve_binary *sbin)
{
struct sieve_binary_header *header = &sbin->header;
- struct sieve_resource_usage rusage;
-
- sieve_binary_get_resource_usage(sbin, &rusage);
-
- i_zero(&header->resource_usage);
- if (HAS_ALL_BITS(header->flags, SIEVE_BINARY_FLAG_RESOURCE_LIMIT) ||
- sieve_resource_usage_is_high(sbin->svinst, &rusage)) {
- header->resource_usage.update_time = ioloop_time;
- header->resource_usage.cpu_time_msecs = rusage.cpu_time_msecs;
- }
+ header->unused_update_time = 0;
+ header->unused_cpu_time_msecs = 0;
sieve_resource_usage_init(&sbin->rusage);
sbin->rusage_updated = FALSE;
-
- (void)sieve_binary_check_resource_usage(sbin);
}
/*
@@ -348,8 +318,8 @@ sieve_binary_save_to_stream(struct sieve
header->blocks = blk_count;
header->hdr_size = sizeof(*header);
- header->flags &= ENUM_NEGATE(SIEVE_BINARY_FLAG_RESOURCE_LIMIT);
- sieve_binary_file_update_header(sbin);
+ header->flags = 0;
+ sieve_binary_file_zero_header_rusage(sbin);
if (!_save_aligned(sbin, stream, header, sizeof(*header), NULL)) {
e_error(sbin->event, "save: failed to save header");
@@ -863,6 +833,12 @@ _sieve_binary_open(struct sieve_binary *
return FALSE;
offset = sbin->header.hdr_size;
+ /* Resource usage tracking is no longer kept in the binary file;
+ discard any data from older versions. */
+ sbin->header.unused_update_time = 0;
+ sbin->header.unused_cpu_time_msecs = 0;
+ sbin->header.flags = 0;
+
/* Load block index */
for (i = 0; i < sbin->header.blocks && result; i++) {
@@ -959,14 +935,24 @@ int sieve_binary_check_executable(struct
{
if (error_r != NULL)
*error_r = SIEVE_ERROR_NONE;
+
+ struct sieve_resource_usage rusage;
+ struct sieve_script *script = sbin->script;
+
*client_error_r = NULL;
- if (HAS_ALL_BITS(sbin->header.flags,
- SIEVE_BINARY_FLAG_RESOURCE_LIMIT)) {
- e_debug(sbin->event,
- "Binary execution is blocked: "
- "Cumulative resource usage limit exceeded "
- "(resource limit flag is set)");
+ sieve_binary_get_resource_usage(sbin, &rusage);
+ if (sieve_resource_usage_is_excessive(sbin->svinst, &rusage)) {
+ /* Cumulative resource usage is only tracked for personal
+ scripts. */
+ i_assert(script != NULL);
+ i_assert(script->storage->main_storage);
+
+ e_info(sbin->event,
+ "Personal sieve processing disabled for script '%s': "
+ "cumulative resource usage limit exceeded (%s)",
+ sieve_script_location(script),
+ sieve_resource_usage_get_summary(&rusage));
if (error_r != NULL)
*error_r = SIEVE_ERROR_RESOURCE_LIMIT;
*client_error_r = "cumulative resource usage limit exceeded";
@@ -979,64 +965,47 @@ int sieve_binary_check_executable(struct
* Resource usage
*/
-static int
-sieve_binary_file_do_update_resource_usage(
- struct sieve_binary *sbin, int fd, enum sieve_error *error_r)
-{
- struct sieve_binary_header *header = &sbin->header;
- struct file_lock *lock;
- const char *error;
- int ret;
-
- struct file_lock_settings lock_set = {
- .lock_method = FILE_LOCK_METHOD_FCNTL,
- };
- ret = file_wait_lock(fd, sbin->path, F_WRLCK, &lock_set,
- SIEVE_BINARY_FILE_LOCK_TIMEOUT, &lock, &error);
- if (ret <= 0) {
- e_error(sbin->event, "%s", error);
- *error_r = SIEVE_ERROR_TEMP_FAILURE;
- return -1;
- }
-
- ret = sieve_binary_file_read_header(sbin, fd, header, error_r);
- if (ret == 0) {
- sieve_binary_file_update_header(sbin);
- ret = sieve_binary_file_write_header(sbin, fd, header, error_r);
- }
-
- file_lock_free(&lock);
-
- return ret;
-}
-
int sieve_binary_file_update_resource_usage(struct sieve_binary *sbin,
- enum sieve_error *error_r)
+ enum sieve_error *error_code_r)
{
enum sieve_error error;
- int fd, ret = 0;
+ struct sieve_storage *storage;
+ struct sieve_resource_usage delta;
- if (error_r == NULL)
- error_r = &error;
- *error_r = SIEVE_ERROR_NONE;
+ if (error_code_r == NULL)
+ error_code_r = &error;
+ *error_code_r = SIEVE_ERROR_NONE;
sieve_binary_file_close(&sbin->file);
- if (sbin->path == NULL)
+ if (sbin->script == NULL || sbin->script->storage == NULL ||
+ sbin->script->storage->rusage_path == NULL) {
+ /* No per-user file: tracking discarded. */
+ sieve_resource_usage_init(&sbin->rusage);
+ sbin->rusage_updated = FALSE;
return 0;
- if (sbin->header.version_major != SIEVE_BINARY_VERSION_MAJOR)
- return sieve_binary_save(sbin, sbin->path, TRUE, 0600, error_r);
+ }
+ storage = sbin->script->storage;
- fd = sieve_binary_fd_open(sbin, sbin->path, O_RDWR, error_r);
- if (fd < 0)
- return -1;
+ delta = sbin->rusage;
- ret = sieve_binary_file_do_update_resource_usage(sbin, fd, error_r);
+ /* Persist only when this run consumed a meaningful amount of CPU.
+ Critically, refused-without-running attempts (delta == 0) must not
+ touch the file - otherwise the file's update_time would be refreshed
+ on every blocked attempt, preventing the resource_usage_timeout from
+ ever decaying the persisted CPU time and re-enabling the user. */
+ if (!sieve_resource_usage_is_high(sbin->svinst, &delta)) {
+ sieve_resource_usage_init(&sbin->rusage);
+ sbin->rusage_updated = FALSE;
+ return 0;
+ }
- if (close(fd) < 0) {
- e_error(sbin->event, "update: "
- "failed to close: close() failed: %m");
+ if (sieve_rusage_storage_add(storage, &delta) < 0) {
+ *error_code_r = SIEVE_ERROR_TEMP_FAILURE;
+ return -1;
}
- return ret;
+ sieve_resource_usage_init(&sbin->rusage);
+ sbin->rusage_updated = FALSE;
+ return 0;
}
--- a/src/lib-sieve/sieve-binary-private.h
+++ b/src/lib-sieve/sieve-binary-private.h
@@ -13,10 +13,6 @@
* Binary file
*/
-enum SIEVE_BINARY_FLAGS {
- SIEVE_BINARY_FLAG_RESOURCE_LIMIT = BIT(0),
-};
-
struct sieve_binary_header {
uint32_t magic;
uint16_t version_major;
@@ -26,10 +22,11 @@ struct sieve_binary_header {
uint32_t hdr_size;
uint32_t flags;
- struct {
- uint64_t update_time;
- uint32_t cpu_time_msecs;
- } resource_usage;
+ /* Resource usage tracking moved to per-user sieve-rusage file. These
+ fields are kept zeroed and present only for on-disk format
+ compatibility with older .svbin files. */
+ uint64_t unused_update_time;
+ uint32_t unused_cpu_time_msecs;
};
struct sieve_binary_file {
@@ -98,6 +95,12 @@ struct sieve_binary {
struct sieve_binary_header header;
struct sieve_resource_usage rusage;
+ /* Cumulative CPU usage loaded from per-user sieve-rusage file */
+ struct {
+ time_t update_time;
+ uint32_t cpu_time_msecs;
+ } persisted_rusage;
+
/* When the binary is loaded into memory or when it is being constructed
by the generator, extensions can be associated to the binary. The
extensions array is a sequential list of all linked extensions. The
--- a/src/lib-sieve/sieve-binary.c
+++ b/src/lib-sieve/sieve-binary.c
@@ -9,6 +9,7 @@
#include "hash.h"
#include "array.h"
#include "ostream.h"
+#include "ioloop.h"
#include "eacces-error.h"
#include "safe-mkstemp.h"
@@ -16,6 +17,9 @@
#include "sieve-extensions.h"
#include "sieve-code.h"
#include "sieve-script.h"
+#include "sieve-script-private.h"
+#include "sieve-storage-private.h"
+#include "sieve-rusage.h"
#include "sieve-binary-private.h"
@@ -189,39 +193,61 @@ void sieve_binary_close(struct sieve_bin
* Resource usage
*/
+static struct sieve_storage *
+sieve_binary_get_user_storage(struct sieve_binary *sbin)
+{
+ if (sbin->script == NULL)
+ return NULL;
+ if (sbin->script->storage == NULL)
+ return NULL;
+ if (sbin->script->storage->rusage_path == NULL)
+ return NULL;
+ return sbin->script->storage;
+}
+
+void sieve_binary_apply_persisted_rusage(struct sieve_binary *sbin)
+{
+ struct sieve_storage *storage = sieve_binary_get_user_storage(sbin);
+ struct sieve_resource_usage rusage;
+
+ if (storage == NULL)
+ return;
+ if (sieve_rusage_storage_load(storage, &rusage) <= 0)
+ return;
+
+ sbin->persisted_rusage.cpu_time_msecs = rusage.cpu_time_msecs;
+ sbin->persisted_rusage.update_time = ioloop_time;
+ sieve_resource_usage_init(&sbin->rusage);
+ sbin->rusage_updated = FALSE;
+}
+
void sieve_binary_get_resource_usage(struct sieve_binary *sbin,
struct sieve_resource_usage *rusage_r)
{
- struct sieve_binary_header *header = &sbin->header;
- time_t update_time = header->resource_usage.update_time;
+ time_t update_time = sbin->persisted_rusage.update_time;
unsigned int timeout = sbin->svinst->resource_usage_timeout_secs;
if (update_time != 0 && (ioloop_time - update_time) > timeout)
- i_zero(&header->resource_usage);
+ i_zero(&sbin->persisted_rusage);
sieve_resource_usage_init(rusage_r);
- rusage_r->cpu_time_msecs = header->resource_usage.cpu_time_msecs;
+ rusage_r->cpu_time_msecs = sbin->persisted_rusage.cpu_time_msecs;
sieve_resource_usage_add(rusage_r, &sbin->rusage);
}
bool sieve_binary_check_resource_usage(struct sieve_binary *sbin)
{
- struct sieve_binary_header *header = &sbin->header;
struct sieve_resource_usage rusage;
sieve_binary_get_resource_usage(sbin, &rusage);
-
- if (sieve_resource_usage_is_excessive(sbin->svinst, &rusage)) {
- header->flags |= SIEVE_BINARY_FLAG_RESOURCE_LIMIT;
- return FALSE;
- }
- return TRUE;
+ return !sieve_resource_usage_is_excessive(sbin->svinst, &rusage);
}
bool sieve_binary_record_resource_usage(
struct sieve_binary *sbin, const struct sieve_resource_usage *rusage)
{
struct sieve_resource_usage rusage_total;
+ struct sieve_script *script;
if (sbin == NULL)
return TRUE;
@@ -236,15 +262,27 @@ bool sieve_binary_record_resource_usage(
e_debug(sbin->event, "Updated cumulative resource usage: %s",
sieve_resource_usage_get_summary(&rusage_total));
- return sieve_binary_check_resource_usage(sbin);
+ if (!sieve_resource_usage_is_excessive(sbin->svinst, &rusage_total))
+ return TRUE;
+
+ /* Cumulative resource usage is only tracked for personal scripts;
+ all callers gate this on the user's own script. */
+ script = sbin->script;
+ i_assert(script != NULL);
+ i_assert(script->storage->main_storage);
+
+ e_warning(sbin->event,
+ "Personal sieve processing disabled for script '%s': "
+ "cumulative resource usage limit exceeded (%s)",
+ sieve_script_location(script),
+ sieve_resource_usage_get_summary(&rusage_total));
+ return FALSE;
}
void sieve_binary_set_resource_usage(struct sieve_binary *sbin,
const struct sieve_resource_usage *rusage)
{
- struct sieve_binary_header *header = &sbin->header;
-
- i_zero(&header->resource_usage);
+ i_zero(&sbin->persisted_rusage);
sbin->rusage = *rusage;
sbin->rusage_updated = TRUE;
--- a/src/lib-sieve/sieve-binary.h
+++ b/src/lib-sieve/sieve-binary.h
@@ -37,6 +37,11 @@ bool sieve_binary_record_resource_usage(
ATTR_NULL(1);
void sieve_binary_set_resource_usage(struct sieve_binary *sbin,
const struct sieve_resource_usage *rusage);
+
+/* Apply persisted per-user rusage and limit flag from sieve-rusage file
+ into the binary header. No-op when the storage has no per-user file. */
+void sieve_binary_apply_persisted_rusage(struct sieve_binary *sbin);
+
/*
* Accessors
*/
--- /dev/null
+++ b/src/lib-sieve/sieve-rusage.c
@@ -0,0 +1,257 @@
+/* Copyright (c) 2026 Pigeonhole authors, see the included COPYING file
+ */
+
+#include "lib.h"
+#include "str.h"
+#include "strnum.h"
+#include "ioloop.h"
+#include "eacces-error.h"
+#include "file-dotlock.h"
+#include "mail-namespace.h"
+#include "mail-storage.h"
+#include "mailbox-list.h"
+
+#include "sieve-common.h"
+#include "sieve-settings.h"
+#include "sieve-storage-private.h"
+#include "sieve-rusage.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+#define SIEVE_RUSAGE_FILENAME "sieve-rusage"
+#define SIEVE_RUSAGE_VERSION_TAG "V1"
+#define SIEVE_RUSAGE_LOCK_TIMEOUT 10
+#define SIEVE_RUSAGE_LOCK_STALE_TIMEOUT 60
+
+/* Maximum size of the on-disk file. Single-line ASCII format with three
+ space-separated tokens; anything larger is treated as corrupt. */
+#define SIEVE_RUSAGE_MAX_FILE_SIZE 128
+
+struct sieve_rusage_record {
+ uint32_t cpu_time_msecs;
+ time_t update_time;
+};
+
+void sieve_rusage_storage_init(struct sieve_storage *storage,
+ struct mail_user *user)
+{
+ struct mail_namespace *ns;
+ const char *root;
+
+ if (!storage->main_storage || user == NULL)
+ return;
+
+ ns = mail_namespace_find_inbox(user->namespaces);
+ if (ns == NULL)
+ return;
+
+ if (!mailbox_list_get_root_path(ns->list, MAILBOX_LIST_PATH_TYPE_DIR,
+ &root) || root == NULL)
+ return;
+
+ storage->user = user;
+ storage->inbox_list = ns->list;
+ storage->rusage_path = p_strconcat(storage->pool, root, "/",
+ SIEVE_RUSAGE_FILENAME, NULL);
+}
+
+static bool
+sieve_rusage_parse(const char *line, struct sieve_rusage_record *rec)
+{
+ const char *const *tokens;
+ uint32_t cpu_secs;
+ bool ok = FALSE;
+
+ T_BEGIN {
+ tokens = t_strsplit_spaces(line, " \t");
+ if (tokens[0] == NULL ||
+ strcmp(tokens[0], SIEVE_RUSAGE_VERSION_TAG) != 0)
+ break;
+ if (tokens[1] == NULL || tokens[2] == NULL ||
+ tokens[3] != NULL)
+ break;
+ if (str_to_uint32(tokens[1], &cpu_secs) < 0)
+ break;
+ if (str_to_time(tokens[2], &rec->update_time) < 0)
+ break;
+ if (cpu_secs > UINT32_MAX / 1000)
+ rec->cpu_time_msecs = UINT32_MAX;
+ else
+ rec->cpu_time_msecs = cpu_secs * 1000;
+ ok = TRUE;
+ } T_END;
+
+ return ok;
+}
+
+static int
+sieve_rusage_read(struct sieve_storage *storage,
+ struct sieve_rusage_record *rec_r)
+{
+ char buf[SIEVE_RUSAGE_MAX_FILE_SIZE + 1];
+ char *nl;
+ ssize_t ret;
+ int fd;
+
+ i_zero(rec_r);
+
+ fd = open(storage->rusage_path, O_RDONLY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ return 0;
+ e_error(storage->event, "open(%s) failed: %m",
+ storage->rusage_path);
+ return -1;
+ }
+
+ ret = read(fd, buf, sizeof(buf) - 1);
+ i_close_fd(&fd);
+ if (ret < 0) {
+ e_error(storage->event, "read(%s) failed: %m",
+ storage->rusage_path);
+ return -1;
+ }
+ if (ret == 0)
+ return 0;
+ if (ret >= (ssize_t)(sizeof(buf) - 1)) {
+ e_warning(storage->event, "%s: file too large; resetting",
+ storage->rusage_path);
+ return 0;
+ }
+ buf[ret] = '\0';
+
+ nl = strchr(buf, '\n');
+ if (nl != NULL)
+ *nl = '\0';
+
+ if (!sieve_rusage_parse(buf, rec_r)) {
+ e_warning(storage->event, "%s: malformed content; resetting",
+ storage->rusage_path);
+ i_zero(rec_r);
+ }
+ return 0;
+}
+
+static void
+sieve_rusage_dotlock_settings(struct dotlock_settings *set_r)
+{
+ i_zero(set_r);
+ set_r->timeout = SIEVE_RUSAGE_LOCK_TIMEOUT;
+ set_r->stale_timeout = SIEVE_RUSAGE_LOCK_STALE_TIMEOUT;
+ set_r->use_excl_lock = TRUE;
+}
+
+int sieve_rusage_storage_load(struct sieve_storage *storage,
+ struct sieve_resource_usage *rusage_r)
+{
+ struct sieve_rusage_record rec;
+ unsigned int timeout;
+
+ sieve_resource_usage_init(rusage_r);
+
+ if (storage->rusage_path == NULL)
+ return 0;
+
+ if (sieve_rusage_read(storage, &rec) < 0)
+ return -1;
+
+ timeout = storage->svinst->resource_usage_timeout_secs;
+ if (rec.update_time != 0 &&
+ (ioloop_time - rec.update_time) > (time_t)timeout) {
+ /* decayed */
+ return 1;
+ }
+
+ rusage_r->cpu_time_msecs = rec.cpu_time_msecs;
+ return 1;
+}
+
+int sieve_rusage_storage_add(struct sieve_storage *storage,
+ const struct sieve_resource_usage *delta_rusage)
+{
+ struct sieve_rusage_record rec;
+ struct dotlock_settings dlset;
+ struct dotlock *dotlock;
+ unsigned int timeout;
+ uint32_t old_cpu, cpu_secs;
+ string_t *out;
+ ssize_t wret;
+ int fd;
+
+ if (storage->rusage_path == NULL)
+ return 0;
+
+ sieve_rusage_dotlock_settings(&dlset);
+
+ /* The namespace root may not exist yet on the very first update for
+ a user (e.g. LDA refused execution before any mail was delivered).
+ Create it on demand so file_dotlock_open does not fail with ENOENT. */
+ if (storage->inbox_list != NULL &&
+ mailbox_list_mkdir_root(storage->inbox_list, NULL,
+ MAILBOX_LIST_PATH_TYPE_DIR) < 0)
+ return -1;
+
+ fd = file_dotlock_open_mode(&dlset, storage->rusage_path, 0,
+ 0600, (uid_t)-1, (gid_t)-1, &dotlock);
+ if (fd == -1) {
+ if (errno == EACCES) {
+ e_error(storage->event, "%s",
+ eacces_error_get_creating("file_dotlock_open",
+ storage->rusage_path));
+ } else {
+ e_error(storage->event,
+ "file_dotlock_open(%s) failed: %m",
+ storage->rusage_path);
+ }
+ return -1;
+ }
+
+ if (sieve_rusage_read(storage, &rec) < 0) {
+ file_dotlock_delete(&dotlock);
+ return -1;
+ }
+
+ timeout = storage->svinst->resource_usage_timeout_secs;
+ if (rec.update_time != 0 &&
+ (ioloop_time - rec.update_time) > (time_t)timeout) {
+ /* decayed: discard previous values */
+ rec.cpu_time_msecs = 0;
+ }
+
+ old_cpu = rec.cpu_time_msecs;
+ if ((UINT32_MAX - old_cpu) < delta_rusage->cpu_time_msecs)
+ rec.cpu_time_msecs = UINT32_MAX;
+ else
+ rec.cpu_time_msecs = old_cpu + delta_rusage->cpu_time_msecs;
+ rec.update_time = ioloop_time;
+
+ /* Round CPU time up to whole seconds for persistence. */
+ if (rec.cpu_time_msecs >= UINT32_MAX - 999)
+ cpu_secs = UINT32_MAX / 1000;
+ else
+ cpu_secs = (rec.cpu_time_msecs + 999) / 1000;
+
+ out = t_str_new(64);
+ str_printfa(out, "%s %u %lld\n", SIEVE_RUSAGE_VERSION_TAG,
+ cpu_secs, (long long)rec.update_time);
+
+ wret = write(fd, str_data(out), str_len(out));
+ if (wret != (ssize_t)str_len(out)) {
+ e_error(storage->event,
+ "write(%s) failed: %m (wrote %zd/%zu)",
+ storage->rusage_path, wret, str_len(out));
+ file_dotlock_delete(&dotlock);
+ return -1;
+ }
+
+ if (file_dotlock_replace(&dotlock, 0) < 0) {
+ e_error(storage->event,
+ "file_dotlock_replace(%s) failed: %m",
+ storage->rusage_path);
+ return -1;
+ }
+ return 1;
+}
--- /dev/null
+++ b/src/lib-sieve/sieve-rusage.h
@@ -0,0 +1,28 @@
+#ifndef SIEVE_RUSAGE_H
+#define SIEVE_RUSAGE_H
+
+#include "sieve-common.h"
+
+struct sieve_storage;
+struct mail_user;
+
+/* Per-user resource usage file lives at <INBOX-namespace-root>/sieve-rusage.
+ It survives script renames, deletions, and re-uploads under a different
+ name, preventing CPU-budget bypass. Tracking is enabled only for personal
+ user-controlled storage. */
+
+void sieve_rusage_storage_init(struct sieve_storage *storage,
+ struct mail_user *user);
+
+/* Load persisted resource usage from the per-user file. Returns 1 on success,
+ 0 if the storage has no rusage file (no INBOX namespace path), -1 on error.
+ Applies the resource_usage_timeout decay. */
+int sieve_rusage_storage_load(struct sieve_storage *storage,
+ struct sieve_resource_usage *rusage_r);
+
+/* Atomically add delta_rusage to the persisted per-user rusage file.
+ Returns 1 on success, 0 if no rusage file is configured, -1 on error. */
+int sieve_rusage_storage_add(struct sieve_storage *storage,
+ const struct sieve_resource_usage *delta_rusage);
+
+#endif
--- a/src/lib-sieve/sieve-storage-private.h
+++ b/src/lib-sieve/sieve-storage-private.h
@@ -112,6 +112,17 @@ struct sieve_storage {
struct mail_namespace *sync_inbox_ns;
+ /* Per-user resource usage tracking. Set when storage is personal and
+ the user's INBOX namespace has a filesystem path. NULL otherwise.
+ inbox_list is kept so the namespace root directory can be created
+ on demand before the rusage file is updated; LDA may close the
+ sieve binary (and therefore persist rusage) before any mail has
+ been delivered, in which case the namespace root may not exist
+ yet. */
+ struct mail_user *user;
+ struct mailbox_list *inbox_list;
+ const char *rusage_path;
+
enum sieve_storage_flags flags;
/* this is the main personal storage */
--- a/src/lib-sieve/sieve-storage.c
+++ b/src/lib-sieve/sieve-storage.c
@@ -15,6 +15,7 @@
#include "sieve-script-private.h"
#include "sieve-storage-private.h"
+#include "sieve-rusage.h"
#include <sys/types.h>
#include <sys/stat.h>
@@ -482,6 +483,7 @@ sieve_storage_do_create_main(struct siev
return NULL;
(void)sieve_storage_sync_init(storage, user);
+ sieve_rusage_storage_init(storage, user);
/* Get quota settings if storage driver provides none */
--- a/src/lib-sieve/sieve.c
+++ b/src/lib-sieve/sieve.c
@@ -30,6 +30,7 @@
#include "sieve-generator.h"
#include "sieve-interpreter.h"
#include "sieve-binary-dumper.h"
+#include "sieve-rusage.h"
#include "sieve.h"
#include "sieve-common.h"
@@ -394,6 +395,8 @@ sieve_open_script_real(struct sieve_scri
/* Try to open the matching binary */
sbin = sieve_script_binary_load(script, error_r);
if (sbin != NULL) {
+ /* Per-user rusage file (if any) overrides binary header */
+ sieve_binary_apply_persisted_rusage(sbin);
sieve_binary_get_resource_usage(sbin, &rusage);
/* Ok, it exists; now let's see if it is up to date */
@@ -425,6 +428,8 @@ sieve_open_script_real(struct sieve_scri
sieve_script_location(script));
sieve_binary_set_resource_usage(sbin, &rusage);
+ /* Per-user rusage file (if any) overrides any carry-forward */
+ sieve_binary_apply_persisted_rusage(sbin);
}
/* Check whether binary can be executed. */
--- a/src/lib-sieve/storage/file/sieve-file-script.c
+++ b/src/lib-sieve/storage/file/sieve-file-script.c
@@ -693,6 +693,14 @@ static int sieve_file_storage_script_del
fscript->path);
}
}
+
+ /* Best-effort: drop the compiled binary as well so it does not
+ linger as a stale orphan. */
+ if (fscript->binpath != NULL &&
+ unlink(fscript->binpath) < 0 && errno != ENOENT) {
+ e_error(script->event,
+ "unlink(%s) failed: %m", fscript->binpath);
+ }
return ret;
}
@@ -821,6 +829,16 @@ static int sieve_file_storage_script_ren
"unlink(%s) failed: %m", fscript->path);
}
+ /* Drop the old compiled binary; the renamed
+ script will recompile under its new name. */
+ if (fscript->binpath != NULL &&
+ unlink(fscript->binpath) < 0 &&
+ errno != ENOENT) {
+ e_error(script->event,
+ "unlink(%s) failed: %m",
+ fscript->binpath);
+ }
+
if ( script->name != NULL && *script->name != '\0' )
script->name = p_strdup(script->pool, newname);
fscript->path = p_strdup(script->pool, newpath);