Skip to content

Commit 273e707

Browse files
committed
Fix f-2762 constant timing in BrokerStrCompare
1 parent c77cf02 commit 273e707

1 file changed

Lines changed: 11 additions & 8 deletions

File tree

src/mqtt_broker.c

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -131,17 +131,18 @@
131131
#endif
132132

133133
#ifdef WOLFMQTT_BROKER_AUTH
134-
/* Constant-time string comparison to prevent timing attacks on auth.
135-
* Compares all bytes regardless of where differences occur.
136-
* Returns 0 if equal, non-zero if different. */
137-
static int BrokerStrCompare(const char* a, const char* b)
134+
/* Constant-time string comparison for authentication.
135+
* Iterates exactly cmp_len times so loop duration is independent of
136+
* either input's length; cmp_len is a caller-supplied fixed bound
137+
* (the credential buffer size). Length mismatch is folded in via the
138+
* final XOR. Returns 0 if equal, non-zero if different. */
139+
static int BrokerStrCompare(const char* a, const char* b, int cmp_len)
138140
{
139141
int result = 0;
140142
int len_a = (int)XSTRLEN(a);
141143
int len_b = (int)XSTRLEN(b);
142-
int max_len = (len_a > len_b) ? len_a : len_b;
143144
int i;
144-
for (i = 0; i < max_len; i++) {
145+
for (i = 0; i < cmp_len; i++) {
145146
/* Branchless index clamp: when i >= len, reads position 0.
146147
* Length mismatch is caught by the final XOR below. */
147148
unsigned int maskA = 0u - (unsigned int)(i < len_a);
@@ -2920,15 +2921,17 @@ static int BrokerHandle_Connect(BrokerClient* bc, int rx_len,
29202921
bc->username == NULL ||
29212922
#endif
29222923
bc->username[0] == '\0' ||
2923-
BrokerStrCompare(broker->auth_user, bc->username) != 0)) {
2924+
BrokerStrCompare(broker->auth_user, bc->username,
2925+
BROKER_MAX_USERNAME_LEN) != 0)) {
29242926
auth_ok = 0;
29252927
}
29262928
if (broker->auth_pass && (
29272929
#ifndef WOLFMQTT_STATIC_MEMORY
29282930
bc->password == NULL ||
29292931
#endif
29302932
bc->password[0] == '\0' ||
2931-
BrokerStrCompare(broker->auth_pass, bc->password) != 0)) {
2933+
BrokerStrCompare(broker->auth_pass, bc->password,
2934+
BROKER_MAX_PASSWORD_LEN) != 0)) {
29322935
auth_ok = 0;
29332936
}
29342937
if (!auth_ok) {

0 commit comments

Comments
 (0)