|
131 | 131 | #endif |
132 | 132 |
|
133 | 133 | #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) |
138 | 140 | { |
139 | 141 | int result = 0; |
140 | 142 | int len_a = (int)XSTRLEN(a); |
141 | 143 | int len_b = (int)XSTRLEN(b); |
142 | | - int max_len = (len_a > len_b) ? len_a : len_b; |
143 | 144 | int i; |
144 | | - for (i = 0; i < max_len; i++) { |
| 145 | + for (i = 0; i < cmp_len; i++) { |
145 | 146 | /* Branchless index clamp: when i >= len, reads position 0. |
146 | 147 | * Length mismatch is caught by the final XOR below. */ |
147 | 148 | unsigned int maskA = 0u - (unsigned int)(i < len_a); |
@@ -2920,15 +2921,17 @@ static int BrokerHandle_Connect(BrokerClient* bc, int rx_len, |
2920 | 2921 | bc->username == NULL || |
2921 | 2922 | #endif |
2922 | 2923 | 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)) { |
2924 | 2926 | auth_ok = 0; |
2925 | 2927 | } |
2926 | 2928 | if (broker->auth_pass && ( |
2927 | 2929 | #ifndef WOLFMQTT_STATIC_MEMORY |
2928 | 2930 | bc->password == NULL || |
2929 | 2931 | #endif |
2930 | 2932 | 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)) { |
2932 | 2935 | auth_ok = 0; |
2933 | 2936 | } |
2934 | 2937 | if (!auth_ok) { |
|
0 commit comments