Debian Codegraph @

src/proto/eap.c

raw symbols SCIP
1 /* librist. Copyright © 2020 SipRadius LLC. All right reserved.
2 * Author: Gijs Peskens <[email protected]>
3 * Author: Sergio Ammirata, Ph.D. <[email protected]>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8 #include "eap.h"
9 #include "common/attributes.h"
10 #include "config.h"
11 #include "crypto/psk.h"
12 #include "crypto/eap_v4_crypto.h"
13 #include "endian-shim.h"
14 #include "crypto/crypto-private.h"
15 #include "crypto/srp.h"
16 #include "crypto/srp_constants.h"
17 #include "librist_srp.h"
18 #include "rist-private.h"
19 #include "udp-private.h"
20 #include "transport-private.h"
21 #include "log-private.h"
22 #include "proto/rist_time.h"
23 #include "peer.h"
24 #include "protocol_gre.h"
25
26 #include <stddef.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stdbool.h>
30 #include <assert.h>
31 #include <limits.h>
32 #include <inttypes.h>
33
34 #define HASH_ALGO SRP_SHA256
35 #define DIGEST_LENGTH SHA256_DIGEST_LENGTH
36 #define EAP_LOG_PREFIX "[EAP-SRP] "
37 #define EAP_AUTH_RETRY_MAX 3
38 #define EAP_AUTH_TIMEOUT_RETRY_MAX 5
39 #define EAP_AUTH_TIMEOUT 500//ms
40 #define EAP_REAUTH_PERIOD 60000 // ms
41 #define EAP_AUTH_FAILED_RECOVERY 30000 // ms, soft-FAILED -> UNAUTH after this quiet
42 #define EAP_IDENTITY_REPLY_INTERVAL 200 // ms, rate-limit pre-auth IDENTITY replies
43 #define EAP_SRP_OP_INTERVAL 200 // ms, rate-limit pre-auth SRP modexp operations
44 #define EAP_REAUTH_PROBE_MAX 2000 // ms, forget a stale authenticated-side identity-request probe after this gap
45 #define EAP_MAX_MODULUS_BYTES 1024 // largest RFC 5054 group (NG_8192) is 1024 bytes
46
47 /* Permanent-failure sentinel for ctx->tries; fixed point under eap_tries_inc(). */
48 #define EAP_AUTH_TRIES_PERMANENT UINT_MAX
49
50 /* v4 (AES-256-GCM passphrase channel) needs a real crypto backend; else stay v3. */
51 #if HAVE_MBEDTLS || HAVE_NETTLE
52 #define EAP_V4_GCM_AVAILABLE 1
53 #else
54 #define EAP_V4_GCM_AVAILABLE 0
55 #endif
56 /* Highest EAP version we originate; -DEAP_VERSION_MAX=3 forces a v3 peer for interop. */
57 #ifndef EAP_VERSION_MAX
58 #define EAP_VERSION_MAX (EAP_V4_GCM_AVAILABLE ? 4 : 3)
59 #endif
60 #define EAP_V4_NONCE_LEN 12
61 #define EAP_V4_TAG_LEN 16
62 #define EAP_V4_AAD_LEN (5 + EAP_V4_NONCE_LEN)
63 /* Max v4 plaintext in one EAPOL frame; the send bound and receive buffer share it. */
64 #define EAP_V4_MAX_PLAINTEXT (1500 - (EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr) + 1 + EAP_V4_NONCE_LEN + EAP_V4_TAG_LEN))
65
66 static int eap_request_passphrase(struct eapsrp_ctx *ctx, bool start);
67
68 struct eapsrp_ctx
69 {
70 pthread_mutex_t eap_lock;
71 struct {
72 char username[256];
73 char password[256];
74 user_verifier_lookup_t lookup_func_old;
75 user_verifier_lookup_2_t lookup_func;
76 void *lookup_func_userdata_old;
77 void *lookup_func_userdata;
78 struct rist_logging_settings *logging_settings;
79 bool use_key_as_passphrase;
80 uint8_t role;
81 } config;
82
83 int authentication_state;
84 uint8_t last_identifier;
85 unsigned int tries;
86 bool may_rollover_passphrase;
87 bool did_first_auth;
88
89 uint64_t failed_state_timestamp; /* 0 = not in soft-FAILED */
90 uint64_t last_identity_reply_timestamp; /* rate-limit pre-auth IDENTITY replies */
91 uint64_t last_srp_op_timestamp; /* rate-limit pre-auth SRP modexp operations */
92
93 /* Authenticatee-only bounded EAPOL START retransmit; 0 = idle. */
94 uint64_t authee_start_timer;
95 int authee_start_tries;
96
97 /* Authenticatee-only: start of the current run of identity requests seen
98 * while already authenticated; 0 = none in progress. Gates re-auth after
99 * an authenticator restart without honoring a lone forged reset packet. */
100 uint64_t reauth_probe_timer;
101
102 uint64_t passphrase_request_timer;
103 int passphrase_request_times;
104 uint8_t passphrase_request_identifier;
105
106 uint64_t unsollicited_passphrase_response_timer;
107 int unsollicited_passphrase_response_times;
108 uint8_t unsollicited_passphrase_response_identifier;
109 uint8_t unsollicited_passphrase[128];
110 size_t unsollicited_passphrase_len;
111 int unsollicited_passphrase_state;
112
113 uint8_t *last_pkt;
114 size_t last_pkt_size;
115 uint8_t timeout_retries;
116 uint64_t last_timestamp;
117 uint64_t last_auth_timestamp;
118
119 uint64_t generation;
120 struct librist_crypto_srp_authenticator_ctx *auth_ctx;
121 struct librist_crypto_srp_client_ctx *client_ctx;
122 bool authenticated;
123
124 struct rist_peer *peer;
125 char ip_string[46];
126
127 // authenticator data (single user mode) this doesn't need to be in config &
128 // cloned because the lookup function keeps a pointer to the original
129 // eap_ctx
130 char authenticator_username[256];
131 #if HAVE_MBEDTLS
132 size_t authenticator_len_verifier_old;
133 uint8_t *authenticator_bytes_verifier_old;
134 size_t authenticator_len_salt_old;
135 uint8_t *authenticator_bytes_salt_old;
136 #endif
137 size_t authenticator_len_verifier;
138 uint8_t *authenticator_bytes_verifier;
139 size_t authenticator_len_salt;
140 uint8_t *authenticator_bytes_salt;
141
142 bool eapversion3;//EAPv3 signalled. old libRIST used v2, so use this to ensure compat with broken hashing
143
144 bool srp_legacy_pad; //srp-compat=1 URL opt-in
145 bool srp_legacy_peer_warned; //one-shot latch for the M1/M2 hint
146
147 /* EAP v4 (AEAD passphrase channel) state. */
148 uint8_t peer_eap_version; //highest EAP version the peer has advertised
149 uint64_t tx_nonce_counter; //next 96-bit GCM nonce to assign for our send direction
150 uint64_t unsollicited_passphrase_nonce; //cached nonce for the unsolicited push (stable across retransmits)
151 uint64_t rx_last_nonce; //highest v4 nonce accepted from the peer (this direction)
152 bool rx_nonce_seen; //whether rx_last_nonce is valid yet
153 };
154
155 static inline void eap_tries_inc(struct eapsrp_ctx *ctx)
156 {
157 /* Saturating: stays parked at EAP_AUTH_TRIES_PERMANENT instead of wrapping. */
158 if (ctx->tries < EAP_AUTH_TRIES_PERMANENT)
159 ctx->tries++;
160 }
161
162 /* v2 for a legacy session, else the highest we support. A v3 peer reads a
163 * v4-tagged packet as v3 (checks only >= 3), so advertising 4 is safe. */
164 static inline uint8_t eap_tx_version(struct eapsrp_ctx *ctx)
165 {
166 if (!ctx->eapversion3)
167 return 2;
168 return (uint8_t)EAP_VERSION_MAX;
169 }
170
171 /* Print a wire-supplied username safely: replace anything outside
172 * printable ASCII so CR/LF can't forge log lines. */
173 static const char *eap_sanitize_log(const char *in, char *buf, size_t buflen)
174 {
175 size_t i;
176 for (i = 0; i + 1 < buflen && in[i]; i++) {
177 char c = in[i];
178 buf[i] = (c >= 32 && c < 127) ? c : '?';
179 }
180 buf[i] = '\0';
181 return buf;
182 }
183
184 /* Both ends can run v4: we originate it, the session is v3-hashed, and the peer
185 * advertised >= 4. Version is negotiated in the clear (outside the SRP proof),
186 * so a MITM can force a v3 downgrade -- integrity, not confidentiality. */
187 static inline bool eap_use_v4(struct eapsrp_ctx *ctx)
188 {
189 return EAP_VERSION_MAX >= 4 && ctx->eapversion3 && ctx->peer_eap_version >= 4;
190 }
191
192 /* Per-direction v4 key from K via HKDF-Expand-SHA256; the label separates the
193 * two directions so they never share a (key, nonce) pair. */
194 static int eap_v4_dir_key(struct eapsrp_ctx *ctx, bool client_to_server, uint8_t out[32])
195 {
196 const uint8_t *K = (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
197 ? librist_crypto_srp_authenticator_get_key(ctx->auth_ctx)
198 : librist_crypto_srp_client_get_key(ctx->client_ctx);
199 if (K == NULL)
200 return -1;
201 const char *label = client_to_server ? "RIST-EAP-v4 pass c2s" : "RIST-EAP-v4 pass s2c";
202 return _librist_crypto_hkdf_expand_sha256(K, SHA256_DIGEST_LENGTH,
203 (const uint8_t *)label, strlen(label), out, 32);
204 }
205
206 /* AAD binds the wire-carried fields (identifier, flags, nonce). code/type/subtype
207 * are fixed constants pinned by both ends, so they frame the tag, not detect edits. */
208 static void eap_v4_build_aad(uint8_t aad[EAP_V4_AAD_LEN], uint8_t identifier,
209 uint8_t flags, const uint8_t nonce[EAP_V4_NONCE_LEN])
210 {
211 aad[0] = EAP_CODE_RESPONSE;
212 aad[1] = identifier;
213 aad[2] = EAP_TYPE_SRP_SHA1;
214 aad[3] = EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE;
215 aad[4] = flags;
216 memcpy(&aad[5], nonce, EAP_V4_NONCE_LEN);
217 }
218
219 static void eap_v4_encode_nonce(uint64_t counter, uint8_t nonce[EAP_V4_NONCE_LEN])
220 {
221 memset(nonce, 0, EAP_V4_NONCE_LEN); //top 4 octets stay zero
222 for (int i = 0; i < 8; i++)
223 nonce[EAP_V4_NONCE_LEN - 1 - i] = (uint8_t)(counter >> (8 * i));
224 }
225
226 static uint64_t eap_v4_decode_nonce(const uint8_t nonce[EAP_V4_NONCE_LEN])
227 {
228 uint64_t v = 0;
229 for (int i = 0; i < 8; i++)
230 v = (v << 8) | nonce[EAP_V4_NONCE_LEN - 8 + i];
231 return v;
232 }
233
234 void eap_reset_data(struct eapsrp_ctx *ctx)
235 {
236 if (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
237 {
238 #if HAVE_MBEDTLS
239 free(ctx->authenticator_bytes_salt_old);
240 free(ctx->authenticator_bytes_verifier_old);
241 ctx->authenticator_bytes_salt_old = NULL;
242 ctx->authenticator_bytes_verifier_old = NULL;
243 #endif
244 free(ctx->authenticator_bytes_salt);
245 free(ctx->authenticator_bytes_verifier);
246 ctx->authenticator_bytes_salt = NULL;
247 ctx->authenticator_bytes_verifier = NULL;
248 }
249 librist_crypto_srp_authenticator_ctx_free(ctx->auth_ctx);
250 ctx->auth_ctx = NULL;
251 librist_crypto_srp_client_ctx_free(ctx->client_ctx);
252 ctx->client_ctx = NULL;
253 free(ctx->last_pkt);
254
255 ctx->last_pkt = NULL;
256
257 ctx->authenticated = false;
258
259 /* Re-auth derives a fresh K, so restart the v4 nonce space; the new epoch
260 * re-baselines rx_last_nonce (else a re-authing ctx rejects the peer's
261 * restarted nonces despite a valid tag). */
262 ctx->tx_nonce_counter = 0;
263 ctx->rx_last_nonce = 0;
264 ctx->rx_nonce_seen = false;
265
266 /* Drop any armed unsolicited-passphrase retransmit: it caches the old
267 * epoch's plaintext and nonce, and resending it under the new K would
268 * reuse that nonce value once the restarted counter catches up -- the
269 * GCM forbidden state. The app layer can re-push after re-auth. */
270 ctx->unsollicited_passphrase_response_timer = 0;
271 ctx->unsollicited_passphrase_response_times = 0;
272 ctx->unsollicited_passphrase_state = 0;
273 }
274
275 static int send_eapol_pkt(struct eapsrp_ctx *ctx, uint8_t eapoltype, uint8_t eapcode, uint8_t identifier, size_t payload_len, uint8_t buf[], uint8_t eap_version)
276 {
277 size_t offset = 0;
278 struct eapol_hdr *eapol_hdr = (struct eapol_hdr *)&buf[offset];
279 offset += sizeof(*eapol_hdr);
280 struct eap_hdr *eap_hdr = (struct eap_hdr *)&buf[offset];
281 offset += sizeof(*eap_hdr);
282 eapol_hdr->eapversion = eap_version;
283 eapol_hdr->eaptype = eapoltype;
284 eap_hdr->code = eapcode;
285 eap_hdr->identifier = identifier;
286 eapol_hdr->length = eap_hdr->length = htobe16(payload_len + sizeof(*eap_hdr));
287
288 //Store last pkt so we can retransmit it if needed
289 if (identifier == ctx->last_identifier)
290 {
291 free(ctx->last_pkt);
292 ctx->last_pkt = malloc((payload_len + EAPOL_EAP_HDRS_OFFSET));
293 if (ctx->last_pkt == NULL) {
294 // OOM: skip caching the retransmit copy
295 ctx->last_pkt_size = 0;
296 } else {
297 memcpy(ctx->last_pkt, buf, (payload_len + EAPOL_EAP_HDRS_OFFSET));
298 ctx->last_pkt_size = (payload_len + EAPOL_EAP_HDRS_OFFSET);
299 ctx->last_timestamp = timestampNTP_u64();
300 ctx->timeout_retries = 0;
301 }
302 }
303 if (_librist_proto_gre_send_data(ctx->peer, 0, RIST_GRE_PROTOCOL_TYPE_EAPOL, buf, (EAPOL_EAP_HDRS_OFFSET + payload_len), 0, 0, ctx->peer->rist_gre_version) < 0)
304 return -1;
305
306 return 0;
307 }
308
309
310 //EAP REQUEST HANDLING
311 static int process_eap_request_identity(struct eapsrp_ctx *ctx, uint8_t identifier)
312 {
313 if (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
314 return EAP_UNEXPECTEDREQUEST;
315 uint64_t now = timestampNTP_u64();
316 /* An identity request while authenticated is either a forged reset or a sign
317 * the authenticator lost our session; we can't tell on the wire. Don't tear
318 * down inline (a lone forged packet must not): arm reauth_probe_timer and
319 * keep refusing, letting eap_periodic_impl drive one bounded re-auth if it
320 * persists. */
321 if (ctx->authentication_state >= EAP_AUTH_STATE_SUCCESS) {
322 if (ctx->reauth_probe_timer == 0 ||
323 now - ctx->reauth_probe_timer > (uint64_t)EAP_REAUTH_PROBE_MAX * RIST_CLOCK)
324 ctx->reauth_probe_timer = now;
325 return EAP_UNEXPECTEDREQUEST;
326 }
327 /* Rate-limit pre-auth replies (caps username echo + eap_reset_data work). */
328 if (ctx->last_identity_reply_timestamp != 0 &&
329 now < ctx->last_identity_reply_timestamp + (uint64_t)EAP_IDENTITY_REPLY_INTERVAL * RIST_CLOCK) {
330 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_DEBUG,
331 EAP_LOG_PREFIX"Rate-limiting EAP IDENTITY response (last sent %u ms ago)\n",
332 (unsigned)((now - ctx->last_identity_reply_timestamp) / RIST_CLOCK));
333 return 0;
334 }
335 ctx->last_identity_reply_timestamp = now;
336 eap_reset_data(ctx);
337 uint8_t eapolpkt[512];
338 size_t offset = EAPOL_EAP_HDRS_OFFSET;
339 eapolpkt[offset] = EAP_TYPE_IDENTITY;
340 offset += 1;
341 memcpy(&eapolpkt[offset], ctx->config.username, strlen(ctx->config.username));
342 offset += strlen(ctx->config.username);
343 size_t len = offset;
344 len -= EAPOL_EAP_HDRS_OFFSET;
345 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_RESPONSE, identifier, len, eapolpkt, eap_tx_version(ctx));
346 }
347
348 static int process_eap_request_srp_challenge(struct eapsrp_ctx *ctx, uint8_t identifier, size_t len, uint8_t pkt[], uint8_t eap_version)
349 {
350 if (len < 6)
351 return EAP_LENERR;
352
353 /* Rate-limit: each challenge costs a full client-side modexp (g^a) and
354 * the packet is forgeable pre-auth. */
355 uint64_t now = timestampNTP_u64();
356 if (ctx->last_srp_op_timestamp != 0 &&
357 now < ctx->last_srp_op_timestamp + (uint64_t)EAP_SRP_OP_INTERVAL * RIST_CLOCK)
358 return 0;
359 ctx->last_srp_op_timestamp = now;
360
361 #if HAVE_MBEDTLS
362 ctx->eapversion3 = (eap_version >= 3);
363 #elif HAVE_NETTLE
364 (void)(eap_version);
365 #endif
366 // each TLV is prefixed with a 2-byte big-endian length, account for it
367 size_t offset = 0;
368 if (offset + 2 > len)
369 return EAP_LENERR;
370 uint16_t *tmp_swap = (uint16_t *)&pkt[offset];
371 size_t name_len = be16toh(*tmp_swap);
372 offset += 2;
373 //name can be ignored
374 if (name_len > len - offset)
375 return EAP_LENERR;
376 offset += name_len;
377 if (offset + 2 > len)
378 return EAP_LENERR;
379 tmp_swap = (uint16_t *)&pkt[offset];
380 size_t salt_len = be16toh(*tmp_swap);
381 offset += 2;
382 if (salt_len > len - offset)
383 return EAP_LENERR;
384
385 uint8_t *salt = &pkt[offset];
386 uint8_t *g = NULL;
387 uint8_t *N = NULL;
388 size_t N_len = 0;
389 offset += salt_len;
390 if (offset + 2 > len)
391 return EAP_LENERR;
392 tmp_swap = (uint16_t *)&pkt[offset];
393 size_t generator_len = be16toh(*tmp_swap);
394 offset += 2;
395 if (generator_len != 0)
396 {
397 if (generator_len > len - offset)
398 return EAP_LENERR;
399 if (generator_len > EAP_MAX_MODULUS_BYTES)
400 return EAP_LENERR;
401
402 g = &pkt[offset];
403 offset += generator_len;
404 N = &pkt[offset];
405 N_len = len - offset;
406 if (N_len > EAP_MAX_MODULUS_BYTES)
407 return EAP_LENERR;
408 }
409 bool use_default_ng = (generator_len == 0);
410 librist_crypto_srp_client_ctx_free(ctx->client_ctx);
411 ctx->client_ctx = librist_crypto_srp_client_ctx_create(use_default_ng, N, N_len, g, generator_len, salt, salt_len, ctx->eapversion3, ctx->srp_legacy_pad);
412 if (ctx->client_ctx == NULL)
413 return EAP_INTERNALERR;
414 uint8_t response[1500] = {0};
415 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&response[EAPOL_EAP_HDRS_OFFSET];
416 hdr->type = EAP_TYPE_SRP_SHA1;
417 hdr->subtype = EAP_SRP_SUBTYPE_CHALLENGE;
418 int len_A = librist_crypto_srp_client_write_A_bytes(ctx->client_ctx, &response[EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr)], sizeof(response) -(EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr)));
419 if (len_A < 0)
420 return -1;
421 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_RESPONSE, identifier, ((size_t)len_A + sizeof(*hdr)), response, eap_tx_version(ctx));
422 }
423
424 static int process_eap_request_srp_server_key(struct eapsrp_ctx *ctx, uint8_t identifier, size_t len, uint8_t pkt[])
425 {
426 if (!ctx->client_ctx)
427 {
428 /* No SRP client state: either no CHALLENGE was processed or the
429 * state was reset. A spoofed SERVER_KEY request must not reach
430 * the bignum layer with a NULL ctx. */
431 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
432 return EAP_INTERNALERR;
433 }
434 if (librist_crypto_srp_client_handle_B(ctx->client_ctx, pkt, len, ctx->config.username, ctx->config.password) != 0)
435 {
436 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
437 //"must disconnect immediately, set tries past limit"
438 ctx->tries = EAP_AUTH_TRIES_PERMANENT;
439 return EAP_AUTH_TERMINATED;
440 }
441 size_t out_len = sizeof(struct eap_srp_hdr) + 4 + DIGEST_LENGTH;
442 uint8_t response[(EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr) + 4 + DIGEST_LENGTH)];
443 size_t offset = EAPOL_EAP_HDRS_OFFSET;
444 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&response[offset];
445 offset += sizeof(*hdr);
446 memset(&response[offset], 0, 4);
447 offset += 4;
448 hdr->type = EAP_TYPE_SRP_SHA1;
449 hdr->subtype = EAP_SRP_SUBTYPE_SERVER_KEY;
450 if (ctx->config.use_key_as_passphrase && ctx->eapversion3) {
451 SET_BIT(response[(EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr) + 3)], 0);
452 librist_peer_update_tx_passphrase(ctx->peer, librist_crypto_srp_client_get_key(ctx->client_ctx), SHA256_DIGEST_LENGTH, !ctx->did_first_auth);
453 ctx->did_first_auth = true;
454 }
455 librist_crypto_srp_client_write_M1_bytes(ctx->client_ctx, &response[offset]);
456 int ret = send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_RESPONSE, identifier, out_len, response, eap_tx_version(ctx));
457 return ret;
458 }
459
460 static int process_eap_request_srp_server_validator(struct eapsrp_ctx *ctx, uint8_t identifier, size_t len, uint8_t pkt[])
461 {
462 if (len < (4 + DIGEST_LENGTH))
463 return EAP_LENERR;
464 if (!ctx->client_ctx)
465 {
466 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
467 return EAP_INTERNALERR;
468 }
469 if (librist_crypto_srp_client_verify_m2(ctx->client_ctx, &pkt[4]) == 0)
470 {
471 if (ctx->authentication_state < EAP_AUTH_STATE_SUCCESS)
472 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO, EAP_LOG_PREFIX"Successfully authenticated\n");
473 bool set_passphrase = CHECK_BIT(pkt[3], 0);
474 if (set_passphrase && ctx->eapversion3) {
475 librist_peer_update_rx_passphrase(ctx->peer, librist_crypto_srp_client_get_key(ctx->client_ctx), SHA256_DIGEST_LENGTH, !ctx->did_first_auth);
476 }
477
478 if (ctx->config.use_key_as_passphrase && ctx->eapversion3)
479 ctx->may_rollover_passphrase = true;
480
481 ctx->did_first_auth = true;
482 ctx->authentication_state = EAP_AUTH_STATE_SUCCESS;
483 ctx->last_auth_timestamp = timestampNTP_u64();
484 ctx->tries = 0;
485 ctx->failed_state_timestamp = 0;
486 uint8_t outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr))] = {0};
487 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[EAPOL_EAP_HDRS_OFFSET];
488 if (ctx->eapversion3) {
489 int ret = send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_SUCCESS, identifier, sizeof(*hdr), outpkt, eap_tx_version(ctx));
490 eap_request_passphrase(ctx, true);
491 return ret;
492 }
493 hdr->type = EAP_TYPE_SRP_SHA1;
494 hdr->subtype = EAP_SRP_SUBTYPE_SERVER_VALIDATOR;
495 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_RESPONSE, identifier, sizeof(*hdr), outpkt, eap_tx_version(ctx));
496 }
497 //perm failure
498 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
499 EAP_LOG_PREFIX"Server M2 verification failed for server@%s\n", ctx->ip_string);
500 /* Advisory hint, latched: see srp-compat note in NEWS for v0.2.18. */
501 if (!ctx->srp_legacy_peer_warned) {
502 ctx->srp_legacy_peer_warned = true;
503 if (ctx->srp_legacy_pad) {
504 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
505 EAP_LOG_PREFIX" Hint: this side is configured with srp-compat=1. If the server is running librist 0.2.16+ (PAD-compliant, the default), drop ?srp-compat=1 on both sides.\n");
506 } else {
507 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
508 EAP_LOG_PREFIX" Hint: if the server is running librist 0.2.15 or earlier, the SRP wire format changed in 0.2.16 for RFC 5054 / TR-06-2 compliance. To interoperate with an older server, add ?srp-compat=1 on BOTH URLs. Otherwise check the password.\n");
509 }
510 }
511 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
512 ctx->tries = EAP_AUTH_TRIES_PERMANENT;
513
514 return -1;
515 }
516
517 /* Send an EAP SRP Passphrase Response: AES-256-GCM for v4 (per-direction key,
518 * caller-supplied nonce, header as AAD), else the v3 AES-CTR form. The nonce is
519 * used only on v4; reuse it verbatim when retransmitting identical plaintext. */
520 static int eap_srp_send_password(struct eapsrp_ctx *ctx, uint8_t identifier, const uint8_t *password, size_t password_len, uint64_t nonce) {
521 bool v4 = (password_len > 0) && eap_use_v4(ctx);
522 size_t overhead = EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr) + 1 +
523 (v4 ? (EAP_V4_NONCE_LEN + EAP_V4_TAG_LEN) : 0);
524 if (password_len > (1500 - overhead))
525 return -1;
526 uint8_t outpkt[1500] = {0};
527 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[EAPOL_EAP_HDRS_OFFSET];
528 hdr->type = EAP_TYPE_SRP_SHA1;
529 hdr->subtype = EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE;
530 uint8_t *flags = &outpkt[EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr)];
531 size_t payload_len;
532 uint8_t send_version = eap_tx_version(ctx);
533 if (password_len == 0) { //Use session key (U bit); no ciphertext either version
534 SET_BIT(*flags, 7);
535 payload_len = sizeof(*hdr) + 1;
536 } else if (v4) {
537 SET_BIT(*flags, 6); //H = 256-bit (reserved-1 in v4)
538 uint8_t *noncep = flags + 1;
539 uint8_t *ct = noncep + EAP_V4_NONCE_LEN;
540 uint8_t *tag = ct + password_len;
541 eap_v4_encode_nonce(nonce, noncep);
542 uint8_t key[32];
543 bool c2s = (ctx->config.role == EAP_ROLE_AUTHENTICATEE); //we send client->server
544 if (eap_v4_dir_key(ctx, c2s, key) != 0)
545 return -1;
546 uint8_t aad[EAP_V4_AAD_LEN];
547 eap_v4_build_aad(aad, identifier, *flags, noncep);
548 int rc = _librist_crypto_aes_gcm_encrypt(key, noncep, EAP_V4_NONCE_LEN,
549 aad, sizeof(aad), password, password_len, ct, tag, EAP_V4_TAG_LEN);
550 _librist_crypto_secure_zero(key, sizeof(key));
551 if (rc != 0) {
552 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR,
553 EAP_LOG_PREFIX"v4 passphrase GCM encrypt failed\n");
554 return -1;
555 }
556 payload_len = sizeof(*hdr) + 1 + EAP_V4_NONCE_LEN + password_len + EAP_V4_TAG_LEN;
557 send_version = 4; //payload format must match the version byte
558 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_DEBUG,
559 EAP_LOG_PREFIX"v4 passphrase sent under AES-256-GCM (nonce=%" PRIu64 ", %zu bytes)\n",
560 nonce, password_len);
561 } else { //v3 AES-CTR
562 SET_BIT(*flags, 6); //aes_256
563 const uint8_t *key = (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
564 ? librist_crypto_srp_authenticator_get_key(ctx->auth_ctx)
565 : librist_crypto_srp_client_get_key(ctx->client_ctx);
566 uint8_t iv[AES_BLOCK_SIZE] = {0};
567 iv[AES_BLOCK_SIZE-1] = identifier;
568 _librist_crypto_aes_ctr(key, 256, iv, password, flags + 1, password_len);
569 payload_len = sizeof(*hdr) + 1 + password_len;
570 send_version = ctx->eapversion3 ? 3 : 2; //never tag a v3 payload as v4
571 }
572 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_RESPONSE, identifier, payload_len, outpkt, send_version);
573 }
574
575 static int process_eap_request_srp_passphrase(struct eapsrp_ctx *ctx, uint8_t identifier) {
576 if (ctx->authentication_state == EAP_AUTH_STATE_SUCCESS) {
577 if (ctx->config.use_key_as_passphrase)
578 return eap_srp_send_password(ctx, identifier, NULL, 0, 0);
579
580 const uint8_t *passphrase = NULL;
581 size_t passphrase_len = 0;
582 librist_peer_get_current_tx_passphrase(ctx->peer, &passphrase, &passphrase_len);
583 /* Solicited response: fresh nonce per send. Same-plaintext-different-nonce
584 * is safe under GCM; this path is not self-retransmitted (the peer re-requests). */
585 return eap_srp_send_password(ctx, identifier, passphrase, passphrase_len, ctx->tx_nonce_counter++);
586 }
587
588 uint8_t buf[EAPOL_EAP_HDRS_OFFSET];
589 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_FAILURE, identifier, 0, buf, eap_tx_version(ctx));
590 }
591
592 static int process_eap_request(struct eapsrp_ctx *ctx, uint8_t pkt[], size_t len, uint8_t identifier, uint8_t eap_version)
593 {
594 if (len < 1)
595 return EAP_LENERR;
596 uint8_t type = pkt[0];
597 if (type == EAP_TYPE_IDENTITY)
598 return process_eap_request_identity(ctx, identifier);
599 if (type == EAP_TYPE_SRP_SHA1)
600 {
601 if (len < 2)
602 return EAP_LENERR;
603 uint8_t subtype = pkt[1];
604 if (subtype != EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE && ctx->config.role == EAP_ROLE_AUTHENTICATOR)
605 return EAP_UNEXPECTEDREQUEST;
606
607 /* Record identifier for FAILURE matching only after validation
608 * passes. Moving this out of the prologue prevents an
609 * unauthenticated spoofed REQUEST from priming last_identifier
610 * and defeating the FAILURE-identifier gate. */
611 ctx->last_identifier = identifier;
612 switch (subtype)
613 {
614 case EAP_SRP_SUBTYPE_CHALLENGE:
615 return process_eap_request_srp_challenge(ctx, identifier, (len -2), &pkt[2], eap_version);
616 break;
617 case EAP_SRP_SUBTYPE_SERVER_KEY:
618 return process_eap_request_srp_server_key(ctx, identifier, (len -2), &pkt[2]);
619 break;
620 case EAP_SRP_SUBTYPE_SERVER_VALIDATOR:
621 return process_eap_request_srp_server_validator(ctx, identifier, (len -2), &pkt[2]);
622 break;
623 case EAP_SRP_SUBTYPE_LWRECHALLENGE:
624 //handle SRP lw rechallenge
625 break;
626 case EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE:
627 return process_eap_request_srp_passphrase(ctx, identifier);
628 break;
629 default:
630 return EAP_SRP_WRONGSUBTYPE;
631 }
632 }
633 return -1;
634 }
635
636 //EAP RESPONSE HANDLING
637
638 static int process_eap_response_identity(struct eapsrp_ctx *ctx, size_t len, uint8_t pkt[], uint8_t eap_version)
639 {
640 if (len > 255)
641 return -1;
642 /* On the authenticatee side ctx->config.lookup_func is NULL (calloc'd
643 * in rist_enable_eap_srp_2 and never assigned for that role); refuse the
644 * IDENTITY response here so we don't deref it further down. */
645 if (ctx->config.role != EAP_ROLE_AUTHENTICATOR || !ctx->config.lookup_func)
646 return -1;
647 memcpy(ctx->config.username, pkt, len);
648 ctx->config.username[len] = '\0';
649 #if HAVE_MBEDTLS
650 int hashversion = eap_version >= 3 ? 1 : 0;
651 #elif HAVE_NETTLE
652 (void)eap_version;
653 int hashversion = 1;
654 #endif
655 uint64_t generation = 0;
656 librist_verifier_lookup_data_t verifier_data = {0};
657 ctx->config.lookup_func(ctx->config.username, &verifier_data, &hashversion, &generation, ctx->config.lookup_func_userdata);
658 #if HAVE_NETTLE
659 if (hashversion == 0) {
660 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR, EAP_LOG_PREFIX"Lookup from SRP File got hashversion 0 response, Nettle backend does not support this, authentication likely to fail\n");
661 }
662 hashversion = 1;
663 #endif
664 ctx->generation = generation;
665 ctx->eapversion3 = (hashversion >= 1);
666 const char *n_hex = verifier_data.n_modulus_ascii;
667 const char *g_hex = verifier_data.generator_ascii;
668 bool found = (verifier_data.verifier_len != 0 && verifier_data.verifier && verifier_data.salt_len != 0 && verifier_data.salt);
669 uint8_t outpkt[1500] = { 0 };//TUNE THIS
670 size_t offset = EAPOL_EAP_HDRS_OFFSET;
671 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[offset];
672 offset += sizeof(*hdr);
673 hdr->type = EAP_TYPE_SRP_SHA1;
674 hdr->subtype = EAP_SRP_SUBTYPE_CHALLENGE;
675 int rc = -1;
676 if (found)
677 {
678 struct librist_crypto_srp_authenticator_ctx *auth_ctx = NULL;
679 if (verifier_data.default_ng)
680 librist_get_ng_constants(LIBRIST_SRP_NG_DEFAULT, &n_hex, &g_hex);
681
682 auth_ctx = librist_crypto_srp_authenticator_ctx_create(n_hex, g_hex, verifier_data.verifier, verifier_data.verifier_len, verifier_data.salt, verifier_data.salt_len, ctx->eapversion3, ctx->srp_legacy_pad);
683 if (!auth_ctx)
684 goto out;
685 librist_crypto_srp_authenticator_ctx_free(ctx->auth_ctx);
686 ctx->auth_ctx = auth_ctx;
687 memset(&outpkt[offset], 0, 2);
688 offset += 2;//we dont send the server name
689 uint16_t *tmp_swap = (uint16_t *)&outpkt[offset];
690 *tmp_swap = htobe16(verifier_data.salt_len);
691 offset += 2;
692 memcpy(&outpkt[offset], verifier_data.salt, verifier_data.salt_len);
693 offset += verifier_data.salt_len;
694 if (verifier_data.default_ng)
695 {
696 memset(&outpkt[offset], 0, 2);
697 offset += 2;
698 } else {
699 tmp_swap = (uint16_t *)&outpkt[offset];
700 offset += 2;
701 int g_size = librist_crypto_srp_authenticator_write_g_bytes(auth_ctx, &outpkt[offset], sizeof(outpkt) -offset);
702 if (g_size < 0)
703 goto out;
704 *tmp_swap = htobe16(g_size);
705 offset += g_size;
706
707 int n_len = librist_crypto_srp_authenticator_write_n_bytes(auth_ctx, &outpkt[offset], sizeof(outpkt) -offset);
708 if (n_len < 0)
709 goto out;
710 offset += n_len;
711 }
712 ctx->last_identifier++;
713 size_t out_len = offset - EAPOL_EAP_HDRS_OFFSET;
714 rc = send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_REQUEST, ctx->last_identifier, out_len, outpkt, eap_tx_version(ctx));
715 }
716 out:
717 free(verifier_data.verifier);
718 free(verifier_data.salt);
719 free(verifier_data.generator_ascii);
720 free(verifier_data.n_modulus_ascii);
721 return rc;
722 }
723
724 static int process_eap_response_client_key(struct eapsrp_ctx *ctx, size_t len, uint8_t pkt[])
725 {
726 if (!ctx->auth_ctx) {
727 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
728 return EAP_INTERNALERR;
729 }
730
731 /* Rate-limit: each client key costs a full server-side modexp
732 * (B = kv + g^b) and the packet is forgeable pre-auth. */
733 uint64_t now = timestampNTP_u64();
734 if (ctx->last_srp_op_timestamp != 0 &&
735 now < ctx->last_srp_op_timestamp + (uint64_t)EAP_SRP_OP_INTERVAL * RIST_CLOCK)
736 return 0;
737 ctx->last_srp_op_timestamp = now;
738
739 if (librist_crypto_srp_authenticator_handle_A(ctx->auth_ctx, pkt, len) != 0) {
740 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
741 ctx->tries = EAP_AUTH_TRIES_PERMANENT;
742 return EAP_AUTH_TERMINATED;
743 }
744
745 uint8_t outpkt[1500];
746 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[EAPOL_EAP_HDRS_OFFSET];
747 hdr->type = EAP_TYPE_SRP_SHA1;
748 hdr->subtype = EAP_SRP_SUBTYPE_SERVER_KEY;
749 int len_B = librist_crypto_srp_authenticator_write_B_bytes(ctx->auth_ctx, &outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr))], sizeof(outpkt) - (EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr)));
750 if (len_B < 0)
751 return -1;
752 ctx->last_identifier++;
753 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_REQUEST, ctx->last_identifier, (sizeof(struct eap_srp_hdr) + (size_t)len_B), outpkt, eap_tx_version(ctx));
754 }
755
756 static int process_eap_response_client_validator(struct eapsrp_ctx *ctx, size_t len, uint8_t pkt[])
757 {
758 if (len < (4 + DIGEST_LENGTH))
759 return EAP_LENERR;
760
761 if (!ctx->auth_ctx) {
762 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
763 return EAP_INTERNALERR;
764 }
765
766 if (librist_crypto_srp_authenticator_verify_m1(ctx->auth_ctx, ctx->config.username, &pkt[4]) != 0) {
767 char ubuf[256];
768 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN, EAP_LOG_PREFIX"Authentication failed for %s@%s\n", eap_sanitize_log(ctx->config.username, ubuf, sizeof(ubuf)), ctx->ip_string);
769 /* Advisory hint, latched: see srp-compat note in NEWS for v0.2.18. */
770 if (!ctx->srp_legacy_peer_warned) {
771 ctx->srp_legacy_peer_warned = true;
772 if (ctx->srp_legacy_pad) {
773 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
774 EAP_LOG_PREFIX" Hint: this side is configured with srp-compat=1. If %s is running librist 0.2.16+ (PAD-compliant, the default), drop ?srp-compat=1 on both sides.\n",
775 ctx->ip_string);
776 } else {
777 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
778 EAP_LOG_PREFIX" Hint: if %s is running librist 0.2.15 or earlier, the SRP wire format changed in 0.2.16 for RFC 5054 / TR-06-2 compliance. To interoperate with an older peer, add ?srp-compat=1 on BOTH URLs. Otherwise check the password.\n",
779 ctx->ip_string);
780 }
781 }
782 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
783 eap_tries_inc(ctx);
784 int ret = EAP_AUTH_FAILED;
785 if (ctx->tries > EAP_AUTH_RETRY_MAX) {
786 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR, EAP_LOG_PREFIX"Authentication retry count exceeded\n");
787 ret = EAP_AUTH_TERMINATED;
788 }
789 uint8_t buf[EAPOL_EAP_HDRS_OFFSET];
790 send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_FAILURE, ctx->last_identifier, 0, buf, eap_tx_version(ctx));
791 eap_reset_data(ctx);
792 return ret;
793 }
794 ctx->authenticated = true;
795 bool set_passphrase = CHECK_BIT(pkt[3], 0);
796 if (set_passphrase) {
797 librist_peer_update_rx_passphrase(ctx->peer, librist_crypto_srp_authenticator_get_key(ctx->auth_ctx), SHA256_DIGEST_LENGTH, !ctx->did_first_auth);
798 }
799 ctx->did_first_auth = true;
800 uint8_t outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr) + 4 + DIGEST_LENGTH)];
801 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[EAPOL_EAP_HDRS_OFFSET];
802 hdr->type = EAP_TYPE_SRP_SHA1;
803 hdr->subtype = EAP_SRP_SUBTYPE_SERVER_VALIDATOR;
804 memset(&outpkt[EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr)], 0, 4);
805 if (ctx->config.use_key_as_passphrase) {
806 SET_BIT(outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr) + 3)], 0);
807 librist_peer_update_tx_passphrase(ctx->peer, librist_crypto_srp_authenticator_get_key(ctx->auth_ctx), SHA256_DIGEST_LENGTH, !ctx->did_first_auth);
808 ctx->did_first_auth = true;
809 }
810 librist_crypto_srp_authenticator_write_M2_bytes(ctx->auth_ctx, &outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(*hdr) + 4)]);
811 ctx->last_identifier++;
812 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_REQUEST, ctx->last_identifier, (sizeof(*hdr) + 4 + DIGEST_LENGTH), outpkt, eap_tx_version(ctx));
813 }
814
815 static int process_eap_response_srp_server_validator(struct eapsrp_ctx *ctx)
816 {
817 if (ctx->authenticated)
818 {
819 if (ctx->authentication_state < EAP_AUTH_STATE_SUCCESS) {
820 char ubuf[256];
821 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO, EAP_LOG_PREFIX"Successfully authenticated %s@%s\n", eap_sanitize_log(ctx->config.username, ubuf, sizeof(ubuf)), ctx->ip_string);
822 }
823
824 if (ctx->config.use_key_as_passphrase && ctx->eapversion3)
825 ctx->may_rollover_passphrase = true;
826
827 ctx->authentication_state = EAP_AUTH_STATE_SUCCESS;
828 ctx->last_auth_timestamp = timestampNTP_u64();
829 ctx->tries = 0;
830 ctx->failed_state_timestamp = 0;
831 ctx->last_identifier++;
832 }
833 return 0;
834 }
835
836 static int process_eap_response_passphrase(struct eapsrp_ctx *ctx, uint8_t identifier, size_t len, uint8_t pkt[], uint8_t eap_version) {
837 if (ctx->authentication_state != EAP_AUTH_STATE_SUCCESS)
838 return 0;
839
840 /* If a solicited passphrase request is outstanding, only accept a
841 * response whose identifier matches the request. This prevents
842 * replay or spoofed RESPONSEs from hijacking an active exchange.
843 *
844 * When no request is active the RESPONSE is an unsolicited
845 * passphrase push (the protocol explicitly allows this — see
846 * rist_eap_send_passphrase). Its payload is encrypted under the SRP
847 * session key: v3 AES-CTR (confidentiality only) or, when both peers
848 * are v4, AES-256-GCM (integrity + authenticity + replay protection). */
849 bool matches_request = (ctx->passphrase_request_timer != 0 &&
850 identifier == ctx->passphrase_request_identifier);
851 if (ctx->passphrase_request_timer != 0 && !matches_request)
852 return 0;
853
854 if (len < 1)
855 return EAP_LENERR;
856 bool use_derived_key = CHECK_BIT(pkt[0], 7);
857 const uint8_t *skey = (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
858 ? librist_crypto_srp_authenticator_get_key(ctx->auth_ctx)
859 : librist_crypto_srp_client_get_key(ctx->client_ctx);
860 /* Dispatch on the NEGOTIATED session version, never on the per-packet
861 * EAPOL version byte (cleartext, attacker-controlled): once v4 is
862 * negotiated, downgraded frames (v3 CTR, no integrity) and the U-bit
863 * derived-key install (no verification at all) are refused. */
864 bool session_v4 = eap_use_v4(ctx);
865 bool installed = false;
866 if (use_derived_key) {
867 if (session_v4)
868 return 0;
869 installed = (librist_peer_update_rx_passphrase(ctx->peer, skey, SHA256_DIGEST_LENGTH, matches_request) == 0);
870 } else if (session_v4) {
871 if (eap_version < 4)
872 return 0;
873 /* v4 layout after the SRP header: [flags][nonce 12][ciphertext..][tag 16] */
874 if (len < (size_t)(1 + EAP_V4_NONCE_LEN + EAP_V4_TAG_LEN))
875 return EAP_LENERR;
876 size_t ct_len = len - 1 - EAP_V4_NONCE_LEN - EAP_V4_TAG_LEN;
877 const uint8_t *noncep = &pkt[1];
878 const uint8_t *ct = noncep + EAP_V4_NONCE_LEN;
879 const uint8_t *tag = ct + ct_len;
880 uint8_t plain[EAP_V4_MAX_PLAINTEXT];
881 if (ct_len == 0 || ct_len > sizeof(plain))
882 return EAP_LENERR;
883 uint8_t key[32];
884 bool c2s = (ctx->config.role == EAP_ROLE_AUTHENTICATOR); //we receive client->server
885 if (eap_v4_dir_key(ctx, c2s, key) != 0)
886 return EAP_INTERNALERR;
887 uint8_t aad[EAP_V4_AAD_LEN];
888 eap_v4_build_aad(aad, identifier, pkt[0], noncep);
889 if (_librist_crypto_aes_gcm_decrypt(key, noncep, EAP_V4_NONCE_LEN,
890 aad, sizeof(aad), ct, ct_len, tag, EAP_V4_TAG_LEN, plain) != 0) {
891 /* Tag failed: drop without ACK so the sender retransmits; never
892 * install unverified material (plain already zeroed by decrypt). */
893 _librist_crypto_secure_zero(key, sizeof(key));
894 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
895 EAP_LOG_PREFIX"v4 passphrase authentication tag failed; dropping\n");
896 return 0;
897 }
898 uint64_t rx_nonce = eap_v4_decode_nonce(noncep);
899 /* Strictly-increasing nonces only; a byte-identical retransmit is
900 * re-ACKed without reinstalling. */
901 if (!ctx->rx_nonce_seen || rx_nonce > ctx->rx_last_nonce) {
902 ctx->rx_last_nonce = rx_nonce;
903 ctx->rx_nonce_seen = true;
904 installed = (librist_peer_update_rx_passphrase(ctx->peer, plain, ct_len, matches_request) == 0);
905 if (installed)
906 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_DEBUG,
907 EAP_LOG_PREFIX"v4 passphrase verified and installed (AES-256-GCM, nonce=%" PRIu64 ")\n",
908 rx_nonce);
909 } else {
910 installed = true;
911 }
912 _librist_crypto_secure_zero(key, sizeof(key));
913 _librist_crypto_secure_zero(plain, sizeof(plain));
914 } else {
915 bool aes_256 = CHECK_BIT(pkt[0], 6);
916 uint8_t iv[16] = {0};
917 iv[15] = identifier;
918 _librist_crypto_aes_ctr(skey, aes_256? 256: 128, iv, &pkt[1], &pkt[1], len -1);
919 installed = (librist_peer_update_rx_passphrase(ctx->peer, &pkt[1], len-1, matches_request) == 0);
920 }
921 uint8_t buf[EAPOL_EAP_HDRS_OFFSET];
922 if (ctx->passphrase_request_timer)
923 ctx->passphrase_request_timer = 0;
924 if (!installed) {
925 /* The key slot refused the passphrase (e.g. oversize): answer
926 * FAILURE, never confirm a rotation that did not happen. */
927 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
928 EAP_LOG_PREFIX"passphrase install failed; answering FAILURE\n");
929 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_FAILURE, identifier, 0, buf, eap_tx_version(ctx));
930 }
931 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_SUCCESS, identifier, 0, buf, eap_tx_version(ctx));
932 }
933
934 static int eap_request_passphrase(struct eapsrp_ctx *ctx, bool start) {
935 if (start) {
936 ctx->unsollicited_passphrase_response_times = 0;
937 ctx->passphrase_request_identifier++;
938 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE)
939 SET_BIT(ctx->passphrase_request_identifier, 7);
940 SET_BIT(ctx->passphrase_request_identifier, 6);
941 }
942 uint8_t outpkt[(EAPOL_EAP_HDRS_OFFSET + sizeof(struct eap_srp_hdr))];
943 struct eap_srp_hdr *hdr = (struct eap_srp_hdr *)&outpkt[EAPOL_EAP_HDRS_OFFSET];
944 hdr->type = EAP_TYPE_SRP_SHA1;
945 hdr->subtype = EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE;
946 ctx->passphrase_request_times++;
947 ctx->passphrase_request_timer = timestampNTP_u64();
948 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_REQUEST, ctx->passphrase_request_identifier, sizeof(*hdr), outpkt, eap_tx_version(ctx));
949 }
950
951 static int process_eap_response(struct eapsrp_ctx *ctx, uint8_t pkt[], size_t len, uint8_t identifier, uint8_t eap_version)
952 {
953 if (len < 1)
954 return EAP_LENERR;
955 uint8_t type = pkt[0];
956 /* Invalidate the retransmit cache only for a response matching the
957 * in-flight exchange identifier; junk responses (spoofed or stale)
958 * must not flush it, otherwise a spoofer blasting one response per
959 * retransmit period starves the cache and stalls the handshake
960 * indefinitely. */
961 if (identifier == ctx->last_identifier) {
962 ctx->timeout_retries = 0;
963 free(ctx->last_pkt);
964 ctx->last_pkt_size = 0;
965 ctx->last_pkt = NULL;
966 }
967 if (type == EAP_TYPE_IDENTITY) {
968 /* Only an authenticator should ever process IDENTITY RESPONSE; on the
969 * authenticatee side ctx->config.lookup_func is NULL (set up via
970 * calloc + role/username/password assignment in rist_enable_eap_srp_2)
971 * and process_eap_response_identity would dereference it. */
972 if (ctx->config.role != EAP_ROLE_AUTHENTICATOR || !ctx->config.lookup_func)
973 return EAP_UNEXPECTEDRESPONSE;
974 if (identifier != ctx->last_identifier)
975 return EAP_WRONGIDENTIFIER;
976 return process_eap_response_identity(ctx, (len -1), &pkt[1], eap_version);
977 }
978 if (type == EAP_TYPE_SRP_SHA1)
979 {
980 if (len < 2)
981 return EAP_LENERR;
982 uint8_t subtype = pkt[1];
983
984 if (subtype != EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE && ctx->config.role == EAP_ROLE_AUTHENTICATEE)
985 return EAP_UNEXPECTEDRESPONSE;
986
987 //A password response can be send unsollicited!
988 if (subtype != EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE && identifier != ctx->last_identifier)
989 return EAP_WRONGIDENTIFIER;
990
991 switch (subtype)
992 {
993 case EAP_SRP_SUBTYPE_CLIENT_KEY:
994 return process_eap_response_client_key(ctx, (len -2), &pkt[2]);
995 break;
996 case EAP_SRP_SYPTYPE_CLIENT_VALIDATOR:
997 return process_eap_response_client_validator(ctx, (len -2), &pkt[2]);
998 break;
999 case EAP_SRP_SUBTYPE_SERVER_VALIDATOR:
1000 return process_eap_response_srp_server_validator(ctx);
1001 break;
1002 case EAP_SRP_SUBTYPE_LWRECHALLENGE:
1003 //handle SRP lw rechallenge
1004 break;
1005 case EAP_SRP_SUBTYPE_PASSWORD_REQUEST_RESPONSE:
1006 return process_eap_response_passphrase(ctx, identifier, (len -2), &pkt[2], eap_version);
1007 break;
1008 default:
1009 return EAP_SRP_WRONGSUBTYPE;
1010 }
1011 }
1012 return -1;
1013 }
1014
1015 static int process_eap_succes(struct eapsrp_ctx *ctx, uint8_t identifier) {
1016 if (identifier == ctx->unsollicited_passphrase_response_identifier && ctx->unsollicited_passphrase_response_timer != 0) {
1017 ctx->unsollicited_passphrase_state = EAP_PASSPHRASE_STATE_SUCCESS;
1018 ctx->unsollicited_passphrase_response_identifier = 0;
1019 ctx->unsollicited_passphrase_response_timer = 0;
1020 ctx->unsollicited_passphrase_response_times = 0;
1021 return 0;
1022 }
1023 if (identifier ==ctx->last_identifier)//The spec mandates we use the success packet on reception of the server_validator
1024 return process_eap_response_srp_server_validator(ctx);
1025 return 0;
1026 }
1027
1028 static int process_eap_pkt(struct eapsrp_ctx *ctx, uint8_t pkt[], size_t len, uint8_t eap_version)
1029 {
1030 if (ctx == NULL)
1031 return -1;
1032 if (ctx->authentication_state == EAP_AUTH_STATE_FAILED && ctx->tries >EAP_AUTH_RETRY_MAX)
1033 return EAP_AUTH_TERMINATED;
1034 if (len < sizeof(struct eap_hdr))
1035 return EAP_LENERR;
1036 /* Record the peer's advertised EAP version for v4 negotiation. */
1037 if (eap_version > ctx->peer_eap_version)
1038 ctx->peer_eap_version = eap_version;
1039 struct eap_hdr *hdr = (struct eap_hdr *)pkt;
1040 uint8_t code = hdr->code;
1041 uint8_t identifier = hdr->identifier;
1042 uint16_t length = be16toh(hdr->length);
1043 if (length != len)
1044 return EAP_LENERR;
1045
1046 switch (code)
1047 {
1048 case EAP_CODE_REQUEST:
1049 return process_eap_request(ctx, &pkt[sizeof(*hdr)], (len - sizeof(*hdr)), identifier, eap_version);
1050 break;
1051 case EAP_CODE_RESPONSE:
1052 return process_eap_response(ctx, &pkt[sizeof(*hdr)], (len - sizeof(*hdr)),identifier, eap_version);
1053 break;
1054 case EAP_CODE_SUCCESS:
1055 return process_eap_succes(ctx, identifier);
1056 break;
1057 case EAP_CODE_FAILURE:
1058 /* Drop FAILUREs whose identifier doesn't match the in-flight exchange. */
1059 if (identifier != ctx->last_identifier) {
1060 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_DEBUG,
1061 EAP_LOG_PREFIX"Dropping FAILURE with stale identifier %u (expected %u)\n",
1062 identifier, ctx->last_identifier);
1063 return 0;
1064 }
1065 // rate-limit, otherwise a spoofed FAILURE can loop us forever
1066 eap_tries_inc(ctx);
1067 eap_reset_data(ctx);
1068 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR, EAP_LOG_PREFIX"Authentication failed\n");
1069 if (ctx->tries > EAP_AUTH_RETRY_MAX) {
1070 ctx->authentication_state = EAP_AUTH_STATE_FAILED;
1071 ctx->failed_state_timestamp = timestampNTP_u64();
1072 return EAP_AUTH_TERMINATED;
1073 }
1074 return _librist_proto_eap_start(ctx);//try to restart the process
1075 default:
1076 return -1;
1077 }
1078 return -1;
1079 }
1080
1081 int eap_request_identity(struct eapsrp_ctx *ctx)
1082 {
1083 uint8_t outpkt[EAPOL_EAP_HDRS_OFFSET +1];
1084 outpkt[EAPOL_EAP_HDRS_OFFSET] = EAP_TYPE_IDENTITY;
1085 uint32_t id_rand;
1086 if (_librist_crypto_random_u32(&id_rand) != 0)
1087 return -1;
1088 ctx->last_identifier = (uint8_t)(id_rand >> 24);
1089 return send_eapol_pkt(ctx, EAPOL_TYPE_EAP, EAP_CODE_REQUEST, ctx->last_identifier, 1, outpkt, eap_tx_version(ctx));
1090 }
1091
1092 /* EAPOL is exempt from encryption, so START still reaches a peer that has
1093 * lost our session key (e.g. a restarted authenticator). */
1094 static int eap_send_start_pkt(struct eapsrp_ctx *ctx)
1095 {
1096 struct eapol_hdr eapol;
1097 eapol.eapversion = 3;
1098 eapol.eaptype = EAPOL_TYPE_START;
1099 eapol.length = 0;
1100 if (_librist_proto_gre_send_data(ctx->peer, 0, RIST_GRE_PROTOCOL_TYPE_EAPOL, (uint8_t*)&eapol, sizeof(eapol), 0, 0, ctx->peer->rist_gre_version) < 0)
1101 return -1;
1102 return 0;
1103 }
1104
1105 int _librist_proto_eap_start(struct eapsrp_ctx *ctx)
1106 {
1107 if (ctx->authentication_state == EAP_AUTH_STATE_SUCCESS)
1108 ctx->authentication_state = EAP_AUTH_STATE_REAUTH;
1109 int ret = eap_send_start_pkt(ctx);
1110 /* Authenticatees have no other periodic START driver; arm the bounded
1111 * retransmit (eap_periodic_impl). Inbound EAP re-arms it. */
1112 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE) {
1113 ctx->authee_start_timer = timestampNTP_u64();
1114 ctx->authee_start_tries = 0;
1115 }
1116 return ret;
1117 }
1118
1119 /* Force an authenticatee (caller/supplicant) to re-run the full SRP
1120 * handshake from scratch and re-initiate it right now.
1121 *
1122 * Used after a caller socket rebind (NAT source-port change or a peer
1123 * restart): the previously authenticated session is bound to the old
1124 * source tuple and to per-session crypto the far end no longer has (a
1125 * restarted listener has forgotten everything). Keeping the stale
1126 * SUCCESS state would leave us sending data the authenticator drops as
1127 * unauthenticated, and the authenticator-driven re-auth never fires for
1128 * a peer it does not know about. So drop all per-session state back to
1129 * UNAUTH and send a fresh EAPOL START, exactly as on a cold connect, so
1130 * the authenticator challenges us immediately on the new socket.
1131 *
1132 * Authenticator contexts are left untouched (re-auth there is driven by
1133 * eap_periodic and the listener-side reassociation path). */
1134 void eap_reset_authenticatee(struct eapsrp_ctx *ctx)
1135 {
1136 if (ctx == NULL)
1137 return;
1138 pthread_mutex_lock(&ctx->eap_lock);
1139 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE) {
1140 eap_reset_data(ctx); /* frees client crypto, authenticated=false */
1141 ctx->authentication_state = EAP_AUTH_STATE_UNAUTH;
1142 ctx->tries = 0; /* clear any parked failure count */
1143 ctx->timeout_retries = 0;
1144 ctx->failed_state_timestamp = 0;
1145 ctx->last_identity_reply_timestamp = 0; /* don't rate-limit the fresh handshake */
1146 ctx->last_identifier = 0;
1147 ctx->did_first_auth = false;/* install the new session key as a first auth */
1148 if (_librist_proto_eap_start(ctx) < 0)
1149 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
1150 EAP_LOG_PREFIX"Failed to send EAPOL START after socket rebind; "
1151 "periodic retransmit will retry\n");
1152 }
1153 pthread_mutex_unlock(&ctx->eap_lock);
1154 }
1155
1156 void eap_set_ip_string(struct eapsrp_ctx *ctx, char ip_string[])
1157 {
1158 if (ctx != NULL) {
1159 strncpy(ctx->ip_string, ip_string, sizeof(ctx->ip_string) - 1);
1160 ctx->ip_string[sizeof(ctx->ip_string) - 1] = '\0';
1161 }
1162 }
1163
1164 int eap_clone_ctx(struct eapsrp_ctx *in, struct rist_peer *peer)
1165 {
1166 if (in == NULL)
1167 return 0;
1168 if (peer->eap_ctx != NULL)
1169 return -1;
1170 struct eapsrp_ctx *ctx = calloc(1, sizeof(*ctx));
1171 if (!ctx)
1172 return -1;
1173
1174 if (pthread_mutex_init(&ctx->eap_lock, NULL) != 0) {
1175 free(ctx);
1176 return -1;
1177 }
1178 memcpy(&ctx->config, &in->config, sizeof(in->config));
1179 ctx->srp_legacy_pad = in->srp_legacy_pad;
1180 peer->eap_ctx = ctx;
1181 ctx->peer = peer;
1182 ctx->eapversion3 = true;
1183 return 0;
1184 }
1185
1186 void eap_delete_ctx(struct eapsrp_ctx **in)
1187 {
1188 if (*in == NULL)
1189 return;
1190
1191 struct eapsrp_ctx *ctx = *in;
1192 eap_reset_data(ctx);
1193
1194 free(ctx);
1195 *in = NULL;
1196 }
1197
1198 int eap_process_eapol(struct eapsrp_ctx* ctx, uint8_t pkt[], size_t len)
1199 {
1200 assert(ctx != NULL);
1201 if (len < sizeof(struct eapol_hdr))
1202 return EAP_LENERR;
1203 struct eapol_hdr *hdr = (struct eapol_hdr *)pkt;
1204 uint8_t eap_version = hdr->eapversion;
1205 size_t body_len = be16toh(hdr->length);
1206 // the on-the-wire body_len must fit inside what we actually received
1207 if (body_len + sizeof(struct eapol_hdr) > len)
1208 return EAP_LENERR;
1209
1210 pthread_mutex_lock(&ctx->eap_lock);
1211 int ret = -1;
1212 switch (hdr->eaptype)
1213 {
1214 case EAPOL_TYPE_EAP:
1215 ret = process_eap_pkt(ctx, &pkt[sizeof(*hdr)], body_len, eap_version);
1216 break;
1217 case EAPOL_TYPE_START:
1218 /* START (re)drives the handshake; only an authenticatee sends it.
1219 * Always re-challenge with IDENTITY and reset the retransmit
1220 * bookkeeping so a caller recovering from a restart or rebind is
1221 * driven anew rather than ignored for a stale last_pkt. Do NOT
1222 * reset tries: it is the brute-force cap, and START is reachable
1223 * pre-auth, so clearing it here would hand an attacker unlimited
1224 * online password guesses (and unlimited server-side modexps). */
1225 if (ctx->config.role == EAP_ROLE_AUTHENTICATOR) {
1226 if (ctx->authentication_state == EAP_AUTH_STATE_SUCCESS)
1227 ctx->authentication_state = EAP_AUTH_STATE_REAUTH;
1228 ctx->timeout_retries = 0;
1229 ret = eap_request_identity(ctx);
1230 } else {
1231 ret = 0;
1232 }
1233 break;
1234 case EAPOL_TYPE_LOGOFF:
1235 /* Refuse LOGOFF once authenticated; re-auth runs from eap_periodic.
1236 * A soft-FAILED ctx stays FAILED: walking it back to UNAUTH from
1237 * the wire bypasses the brute-force kill path, and clearing tries
1238 * would hand out unlimited online guesses. Recovery stays with
1239 * the quiet-period path in eap_periodic. */
1240 if (ctx->authentication_state >= EAP_AUTH_STATE_SUCCESS) {
1241 ret = EAP_UNEXPECTEDREQUEST;
1242 break;
1243 }
1244 if (ctx->authentication_state != EAP_AUTH_STATE_FAILED)
1245 ctx->authentication_state = EAP_AUTH_STATE_UNAUTH;
1246 ret = 0;
1247 break;
1248 default:
1249 break;
1250 }
1251 /* Far end is engaged: while still handshaking (UNAUTH) push the START
1252 * retransmit timer out so it only fires on true silence; once
1253 * authenticated, disarm it. */
1254 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE) {
1255 if (ctx->authentication_state == EAP_AUTH_STATE_UNAUTH) {
1256 ctx->authee_start_timer = timestampNTP_u64();
1257 ctx->authee_start_tries = 0;
1258 } else {
1259 ctx->authee_start_timer = 0;
1260 }
1261 }
1262 pthread_mutex_unlock(&ctx->eap_lock);
1263 return ret;
1264 }
1265
1266 bool eap_is_authenticated(struct eapsrp_ctx *ctx)
1267 {
1268 if (ctx == NULL)
1269 return true;
1270
1271 pthread_mutex_lock(&ctx->eap_lock);
1272 bool authenticated = (ctx->authentication_state >= EAP_AUTH_STATE_SUCCESS);
1273 pthread_mutex_unlock(&ctx->eap_lock);
1274 return authenticated;
1275 }
1276
1277 static void eap_periodic_impl(struct eapsrp_ctx *ctx)
1278 {
1279 uint64_t now = timestampNTP_u64();
1280 uint64_t retry_period = EAP_AUTH_TIMEOUT * RIST_CLOCK;
1281 uint64_t reauth_period = EAP_REAUTH_PERIOD * RIST_CLOCK;//3 seconds
1282
1283 /* Authenticator-restart recovery: once the identity-request probe armed by
1284 * process_eap_request_identity has persisted one retry period, drop to UNAUTH
1285 * and re-run the SRP handshake (bounds a lone forged packet to one re-auth). */
1286 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE &&
1287 ctx->authentication_state >= EAP_AUTH_STATE_SUCCESS &&
1288 ctx->reauth_probe_timer != 0 &&
1289 now > ctx->reauth_probe_timer + retry_period) {
1290 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
1291 EAP_LOG_PREFIX"Authenticator re-requested identity while authenticated "
1292 "(it likely restarted); re-authenticating\n");
1293 ctx->reauth_probe_timer = 0;
1294 eap_reset_data(ctx);
1295 ctx->authentication_state = EAP_AUTH_STATE_UNAUTH;
1296 ctx->tries = 0;
1297 ctx->timeout_retries = 0;
1298 ctx->failed_state_timestamp = 0;
1299 ctx->last_identity_reply_timestamp = 0;
1300 ctx->did_first_auth = false;
1301 if (_librist_proto_eap_start(ctx) < 0)
1302 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
1303 EAP_LOG_PREFIX"Failed to send EAPOL START for re-auth; "
1304 "periodic retransmit will retry\n");
1305 }
1306
1307 /* Retransmit START while stuck UNAUTH and the authenticator is silent
1308 * (e.g. a restarted listener that missed our first START). Bounded; when
1309 * exhausted the caller-side socket rebind re-arms us on its next cycle. */
1310 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE &&
1311 ctx->authentication_state == EAP_AUTH_STATE_UNAUTH &&
1312 ctx->authee_start_timer != 0 &&
1313 now > ctx->authee_start_timer + retry_period) {
1314 if (ctx->authee_start_tries >= EAP_AUTH_TIMEOUT_RETRY_MAX) {
1315 ctx->authee_start_timer = 0;
1316 } else {
1317 eap_send_start_pkt(ctx);
1318 ctx->authee_start_timer = now;
1319 ctx->authee_start_tries++;
1320 }
1321 }
1322
1323 if (ctx->authentication_state == EAP_AUTH_STATE_SUCCESS && ctx->passphrase_request_timer != 0 && ctx->passphrase_request_timer + retry_period < now) {
1324 if (ctx->passphrase_request_times > EAP_AUTH_TIMEOUT_RETRY_MAX) {
1325 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN, EAP_LOG_PREFIX"Failed to receive requested passphrase in a timely manner\n");
1326 ctx->passphrase_request_timer = 0;
1327 } else {
1328 eap_request_passphrase(ctx, false);
1329 }
1330 }
1331
1332 if (ctx->authentication_state == EAP_AUTH_STATE_SUCCESS && ctx->unsollicited_passphrase_response_timer != 0 && ctx->unsollicited_passphrase_response_timer + retry_period < now) {
1333 if (ctx->unsollicited_passphrase_response_times > EAP_AUTH_TIMEOUT_RETRY_MAX) {
1334 rist_log(ctx->config.logging_settings, RIST_LOG_ERROR, EAP_LOG_PREFIX"Failed to update passphrase for client\n");
1335 ctx->unsollicited_passphrase_response_timer = 0;
1336 ctx->unsollicited_passphrase_state = EAP_PASSPHRASE_STATE_FAILED;
1337 } else {
1338 /* Retransmit reuses the cached nonce so a v4 payload is byte-identical. */
1339 eap_srp_send_password(ctx, ctx->unsollicited_passphrase_response_identifier, ctx->unsollicited_passphrase, ctx->unsollicited_passphrase_len, ctx->unsollicited_passphrase_nonce);
1340 ctx->unsollicited_passphrase_response_timer = timestampNTP_u64();
1341 ctx->unsollicited_passphrase_response_times++;
1342 }
1343 }
1344
1345 if (ctx->unsollicited_passphrase_response_timer == 0 &&
1346 ctx->passphrase_request_timer &&
1347 ((ctx->unsollicited_passphrase_response_identifier & 0x3f) == 0x3f ||
1348 (ctx->unsollicited_passphrase_response_identifier & 0x3f) == 0x3f)) {
1349 if (ctx->config.role == EAP_ROLE_AUTHENTICATEE)
1350 _librist_proto_eap_start(ctx);
1351 else
1352 eap_request_identity(ctx);
1353 }
1354 if (ctx->config.role == EAP_ROLE_AUTHENTICATOR && ctx->authentication_state != 1 && ctx->last_timestamp + retry_period < now &&
1355 ctx->timeout_retries < EAP_AUTH_TIMEOUT_RETRY_MAX && ctx->tries <= EAP_AUTH_RETRY_MAX)
1356 {
1357 if (ctx->last_pkt)
1358 {
1359 rist_transport_sendto(ctx->peer, ctx->last_pkt, ctx->last_pkt_size, 0);
1360 //check
1361 ctx->timeout_retries++;
1362 ctx->last_timestamp = now;
1363 return;
1364 } else {
1365 eap_request_identity(ctx);
1366 return;
1367 }
1368 } else if (ctx->config.role == EAP_ROLE_AUTHENTICATOR && ctx->authentication_state == EAP_AUTH_STATE_SUCCESS &&
1369 now > ctx->last_auth_timestamp + reauth_period) {
1370 if (ctx->generation > 0) {
1371 uint64_t generation = ctx->generation;
1372 int hashversion = ctx->eapversion3? 1 : 0;
1373 //If our cached data matches whatever lookup function would return re-auth is pointless.
1374 ctx->config.lookup_func(ctx->config.username, NULL, &hashversion, &generation, ctx->config.lookup_func_userdata);
1375 if (generation == ctx->generation) {
1376 ctx->last_auth_timestamp = now;
1377 return;
1378 }
1379 }
1380 ctx->authentication_state = EAP_AUTH_STATE_REAUTH;
1381 eap_request_identity(ctx);
1382 return;
1383 }
1384 uint64_t reauth_time_out = ctx->last_auth_timestamp + reauth_period + EAP_AUTH_RETRY_MAX * retry_period;
1385 if (ctx->authentication_state == EAP_AUTH_STATE_REAUTH && now > reauth_time_out) {
1386 ctx->authentication_state = EAP_AUTH_STATE_UNAUTH;
1387 return;
1388 }
1389 /* Soft-FAILED (tries bumped past max but not parked at PERMANENT) -> UNAUTH after quiet. */
1390 if (ctx->authentication_state == EAP_AUTH_STATE_FAILED &&
1391 ctx->tries > EAP_AUTH_RETRY_MAX &&
1392 ctx->tries < EAP_AUTH_TRIES_PERMANENT &&
1393 ctx->failed_state_timestamp != 0 &&
1394 now > ctx->failed_state_timestamp + (uint64_t)EAP_AUTH_FAILED_RECOVERY * RIST_CLOCK) {
1395 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO,
1396 EAP_LOG_PREFIX"Recovered from soft FAILED state after %d ms of quiet\n",
1397 EAP_AUTH_FAILED_RECOVERY);
1398 ctx->tries = 0;
1399 ctx->failed_state_timestamp = 0;
1400 ctx->authentication_state = EAP_AUTH_STATE_UNAUTH;
1401 }
1402 }
1403 void eap_periodic(struct eapsrp_ctx *ctx) {
1404 if (ctx == NULL)
1405 return;
1406 pthread_mutex_lock(&ctx->eap_lock);
1407 eap_periodic_impl(ctx);
1408 pthread_mutex_unlock(&ctx->eap_lock);
1409 }
1410
1411 static void internal_user_verifier_lookup(char * username,
1412 librist_verifier_lookup_data_t *lookup_data,
1413 int *hashversion,
1414 uint64_t *generation,
1415 void *user_data)
1416 {
1417 if (user_data == NULL)
1418 return;
1419
1420 if (*generation == 1)
1421 return;
1422 //This is static data so it can be permanently cached
1423 *generation = 1;
1424
1425 struct eapsrp_ctx *ctx = (struct eapsrp_ctx *)user_data;
1426
1427 uint8_t *decoded_verifier = NULL;
1428 uint8_t *decoded_salt = NULL;
1429
1430 if (strcmp(username, ctx->authenticator_username) != 0)
1431 goto fail_decode;
1432
1433 if (*hashversion == 0 && HAVE_MBEDTLS) {
1434 #if HAVE_MBEDTLS
1435 decoded_verifier = malloc(ctx->authenticator_len_verifier_old);
1436 decoded_salt = malloc(ctx->authenticator_len_salt_old);
1437 if (!decoded_verifier || !decoded_salt)
1438 goto fail_decode;
1439 memcpy(decoded_verifier, ctx->authenticator_bytes_verifier_old, ctx->authenticator_len_verifier_old);
1440 memcpy(decoded_salt, ctx->authenticator_bytes_salt_old, ctx->authenticator_len_salt_old);
1441 lookup_data->verifier_len = ctx->authenticator_len_verifier_old;
1442 lookup_data->salt_len = ctx->authenticator_len_salt_old;
1443 #endif
1444 } else {
1445 decoded_verifier = malloc(ctx->authenticator_len_verifier);
1446 decoded_salt = malloc(ctx->authenticator_len_salt);
1447 if (!decoded_verifier || !decoded_salt)
1448 goto fail_decode;
1449 memcpy(decoded_verifier, ctx->authenticator_bytes_verifier, ctx->authenticator_len_verifier);
1450 memcpy(decoded_salt, ctx->authenticator_bytes_salt, ctx->authenticator_len_salt);
1451 lookup_data->verifier_len = ctx->authenticator_len_verifier;
1452 lookup_data->salt_len = ctx->authenticator_len_salt;
1453 }
1454 lookup_data->verifier = decoded_verifier;
1455 lookup_data->salt = decoded_salt;
1456
1457 lookup_data->default_ng = true;
1458 goto out;
1459
1460 fail_decode:
1461 lookup_data->verifier_len = 0;
1462 lookup_data->salt_len = 0;
1463 free(decoded_verifier);
1464 free(decoded_salt);
1465 out:
1466 return;
1467 }
1468
1469 static void old_user_verifier_lookup_wrapper(char * username,
1470 librist_verifier_lookup_data_t *lookup_data,
1471 int *hashversion,
1472 uint64_t *generation,
1473 void *user_data)
1474 {
1475 *hashversion = 0;
1476 *generation = 0;
1477 struct eapsrp_ctx *ctx = (struct eapsrp_ctx *)user_data;
1478 ctx->config.lookup_func_old(username, &lookup_data->verifier_len,(char **)&lookup_data->verifier, &lookup_data->salt_len, (char **)&lookup_data->salt, &lookup_data->default_ng, &lookup_data->n_modulus_ascii, &lookup_data->generator_ascii, user_data);
1479 }
1480
1481 //PUBLIC
1482 int rist_enable_eap_srp_2(struct rist_peer *peer, const char *username, const char *password, user_verifier_lookup_2_t lookup_func, void *userdata) {
1483 if (!peer)
1484 return RIST_ERR_NULL_PEER;
1485 struct rist_common_ctx *cctx = get_cctx(peer);
1486 if (cctx->profile == RIST_PROFILE_SIMPLE)
1487 return RIST_ERR_INVALID_PROFILE;
1488 if ((peer->listening && !peer->multicast_receiver) || peer->multicast_sender)
1489 {
1490 struct eapsrp_ctx *ctx = calloc(1, sizeof(*ctx));
1491 if (ctx == NULL)
1492 return RIST_ERR_MALLOC;
1493 ctx->config.logging_settings = get_cctx(peer)->logging_settings;
1494 if (pthread_mutex_init(&ctx->eap_lock, NULL) != 0) {
1495 free(ctx);
1496 return RIST_ERR_MALLOC;
1497 }
1498 if (lookup_func == NULL && username != NULL && password != NULL)
1499 {
1500 size_t u_len = strlen(username);
1501 size_t p_len = strlen(password);
1502 if (u_len == 0 || u_len > 255 || p_len == 0 || p_len > 255) {
1503 free(ctx);
1504 return RIST_ERR_INVALID_STRING_LENGTH;
1505 }
1506 lookup_func = internal_user_verifier_lookup;
1507 const char *n = NULL;
1508 const char *g = NULL;
1509 int ret;
1510 ret = librist_get_ng_constants(LIBRIST_SRP_NG_2048, &n, &g);
1511 assert(ret == 0);
1512 #if HAVE_MBEDTLS
1513 ret = librist_crypto_srp_create_verifier(n, g, username, password, &ctx->authenticator_bytes_salt_old, &ctx->authenticator_len_salt_old, &ctx->authenticator_bytes_verifier_old, &ctx->authenticator_len_verifier_old, false);
1514 assert(ret == 0);
1515 #endif
1516 ret = librist_crypto_srp_create_verifier(n, g, username, password, &ctx->authenticator_bytes_salt, &ctx->authenticator_len_salt, &ctx->authenticator_bytes_verifier, &ctx->authenticator_len_verifier, true);
1517 assert(ret == 0);
1518 strcpy(ctx->authenticator_username, username);
1519 userdata = (void *)ctx;
1520 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO, EAP_LOG_PREFIX"EAP Authentication enabled, role = authenticator, single user\n");
1521 }
1522 else if (lookup_func == NULL) {
1523 free(ctx);
1524 return RIST_ERR_MISSING_CALLBACK_FUNCTION;
1525 }
1526 else
1527 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO, EAP_LOG_PREFIX"EAP Authentication enabled, role = authenticator, srp file\n");
1528 ctx->config.lookup_func = lookup_func;
1529 ctx->config.lookup_func_userdata = userdata;
1530 ctx->config.role = EAP_ROLE_AUTHENTICATOR;
1531 ctx->config.use_key_as_passphrase = peer->key_tx.password_len == 0;
1532 ctx->eapversion3 = true;
1533 ctx->srp_legacy_pad = (peer->config.srp_compat_legacy != 0);
1534 if (ctx->srp_legacy_pad)
1535 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
1536 EAP_LOG_PREFIX"SRP legacy compat mode ACTIVE on this authenticator (srp-compat=1). Wire format is the pre-0.2.16 unpadded form — NOT TR-06-2 / RFC 5054 compliant. For transitional interop only.\n");
1537 peer->eap_ctx = ctx;
1538 struct rist_peer *child = peer->child;
1539 peer->eap_authentication_state = 1;
1540 ctx->peer = peer;
1541 while (child != NULL)
1542 {
1543 eap_clone_ctx(ctx, child);
1544 child = child->sibling_next;
1545 }
1546 return 0;
1547 }
1548 if (username == NULL || password == NULL)
1549 return RIST_ERR_NULL_CREDENTIALS;
1550 size_t u_len = strlen(username);
1551 size_t p_len = strlen(password);
1552 if (u_len == 0 || u_len > 255 || p_len == 0 || p_len > 255)
1553 return RIST_ERR_INVALID_STRING_LENGTH;
1554 struct eapsrp_ctx *ctx = calloc(1, sizeof(*ctx));
1555 if (ctx == NULL)
1556 return RIST_ERR_MALLOC;
1557 if (pthread_mutex_init(&ctx->eap_lock, NULL) != 0) {
1558 free(ctx);
1559 return RIST_ERR_MALLOC;
1560 }
1561 ctx->peer = peer;
1562 ctx->config.logging_settings = get_cctx(peer)->logging_settings;
1563 ctx->config.role = EAP_ROLE_AUTHENTICATEE;
1564 strcpy(ctx->config.username, username);
1565 strcpy(ctx->config.password, password);
1566 ctx->srp_legacy_pad = (peer->config.srp_compat_legacy != 0);
1567 peer->eap_ctx = ctx;
1568 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_INFO, EAP_LOG_PREFIX"EAP Authentication enabled, role = authenticatee\n");
1569 if (ctx->srp_legacy_pad)
1570 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_WARN,
1571 EAP_LOG_PREFIX"SRP legacy compat mode ACTIVE on this client (srp-compat=1). Wire format is the pre-0.2.16 unpadded form — NOT TR-06-2 / RFC 5054 compliant. For transitional interop only.\n");
1572 ctx->eapversion3 = true;
1573 if (!peer->multicast_receiver)
1574 _librist_proto_eap_start(ctx);
1575 return 0;
1576 }
1577
1578 int rist_enable_eap_srp(struct rist_peer *peer, const char *username, const char *password, user_verifier_lookup_t lookup_func, void *userdata)
1579 {
1580 if (!peer)
1581 return RIST_ERR_NULL_PEER;
1582
1583 user_verifier_lookup_2_t pass_lookup = lookup_func? old_user_verifier_lookup_wrapper : NULL;
1584 int ret = rist_enable_eap_srp_2(peer, username, password, pass_lookup, NULL);
1585 if (ret == 0) {
1586 peer->eap_ctx->config.lookup_func_old = lookup_func;
1587 peer->eap_ctx->config.lookup_func_userdata = peer->eap_ctx;
1588 peer->eap_ctx->config.lookup_func_userdata_old = userdata;
1589 }
1590 return ret;
1591 }
1592
1593 //returns true when either succesfull or failed
1594 bool rist_eap_password_sending_done(struct eapsrp_ctx *ctx) {
1595 pthread_mutex_lock(&ctx->eap_lock);
1596 bool success = ctx->unsollicited_passphrase_state >= EAP_PASSPHRASE_STATE_SUCCESS;
1597 pthread_mutex_unlock(&ctx->eap_lock);
1598 return success;
1599 }
1600
1601 bool rist_eap_may_rollover_tx(struct eapsrp_ctx *ctx) {
1602 pthread_mutex_lock(&ctx->eap_lock);
1603 bool rollover = ctx->may_rollover_passphrase;
1604 ctx->may_rollover_passphrase = false;
1605 pthread_mutex_unlock(&ctx->eap_lock);
1606 return rollover;
1607 }
1608
1609 void rist_eap_send_passphrase(struct eapsrp_ctx *ctx, const char *passphrase) {
1610 pthread_mutex_lock(&ctx->eap_lock);
1611 /* Sending pre-auth would derive direction keys from a crypto ctx that
1612 * does not exist yet (NULL) and install nothing meaningful; the peer
1613 * version byte can even be pre-armed by a spoofed packet. Require a
1614 * completed authentication. */
1615 if (ctx->authentication_state != EAP_AUTH_STATE_SUCCESS) {
1616 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR,
1617 EAP_LOG_PREFIX"Passphrase push refused: not authenticated\n");
1618 pthread_mutex_unlock(&ctx->eap_lock);
1619 return;
1620 }
1621 size_t plen = strlen(passphrase);
1622 if (plen > sizeof(ctx->unsollicited_passphrase)) {
1623 rist_log_priv2(ctx->config.logging_settings, RIST_LOG_ERROR,
1624 EAP_LOG_PREFIX"Passphrase too long (%zu > %zu), dropping\n",
1625 plen, sizeof(ctx->unsollicited_passphrase));
1626 pthread_mutex_unlock(&ctx->eap_lock);
1627 return;
1628 }
1629 ctx->unsollicited_passphrase_len = plen;
1630 memcpy(ctx->unsollicited_passphrase, passphrase, plen);
1631 ctx->unsollicited_passphrase_response_timer = timestampNTP_u64();
1632 ctx->unsollicited_passphrase_response_times = 1;
1633 ctx->unsollicited_passphrase_response_identifier++;
1634 ctx->unsollicited_passphrase_state = 0;
1635 if (ctx->config.role == EAP_ROLE_AUTHENTICATOR)
1636 SET_BIT(ctx->unsollicited_passphrase_response_identifier, 7);
1637 UNSET_BIT(ctx->unsollicited_passphrase_response_identifier, 6);
1638 /* Assign a fresh nonce for this new passphrase; retransmits reuse it. */
1639 ctx->unsollicited_passphrase_nonce = ctx->tx_nonce_counter++;
1640 eap_srp_send_password(ctx, ctx->unsollicited_passphrase_response_identifier, ctx->unsollicited_passphrase, ctx->unsollicited_passphrase_len, ctx->unsollicited_passphrase_nonce);
1641 pthread_mutex_unlock(&ctx->eap_lock);
1642 }