Coverage Report

Created: 2026-11-12 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-sp-math/src/ssl_api_hs.c
Line
Count
Source
1
/* ssl_api_hs.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#if !defined(WOLFSSL_SSL_API_HS_INCLUDED)
25
    #ifndef WOLFSSL_IGNORE_FILE_WARN
26
        #warning ssl_api_hs.c does not need to be compiled separately from ssl.c
27
    #endif
28
#else
29
30
#ifndef WOLFCRYPT_ONLY
31
32
#ifndef NO_TLS
33
/* Perform the handshake, calling connect or accept as appropriate.
34
 *
35
 * The side must already have been established, either by the method used to
36
 * create the object or with wolfSSL_set_connect_state() or
37
 * wolfSSL_set_accept_state().
38
 *
39
 * @param [in, out] ssl  SSL/TLS object.
40
 * @return  WOLFSSL_SUCCESS when the handshake completes.
41
 * @return  WOLFSSL_FATAL_ERROR when ssl is NULL, no side has been established
42
 *          or the handshake fails.
43
 * @return  Any other error passed through from wolfSSL_connect() or
44
 *          wolfSSL_accept(), such as the raw error from their ReinitSSL()
45
 *          step.
46
 */
47
int wolfSSL_negotiate(WOLFSSL* ssl)
48
0
{
49
0
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
50
51
0
    WOLFSSL_ENTER("wolfSSL_negotiate");
52
53
    /* err starts as a failure, which is what a NULL object and an object with
54
     * no side established both report. */
55
0
    if (ssl != NULL) {
56
0
        #ifndef NO_WOLFSSL_SERVER
57
0
        if (ssl->options.side == WOLFSSL_SERVER_END) {
58
0
            #ifdef WOLFSSL_TLS13
59
0
            if (IsAtLeastTLSv1_3(ssl->version)) {
60
0
                err = wolfSSL_accept_TLSv13(ssl);
61
0
            }
62
0
            else
63
0
            #endif
64
0
            {
65
0
                err = wolfSSL_accept(ssl);
66
0
            }
67
0
        }
68
0
        #endif
69
70
0
        #ifndef NO_WOLFSSL_CLIENT
71
0
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
72
0
            #ifdef WOLFSSL_TLS13
73
0
            if (IsAtLeastTLSv1_3(ssl->version)) {
74
0
                err = wolfSSL_connect_TLSv13(ssl);
75
0
            }
76
0
            else
77
0
            #endif
78
0
            {
79
0
                err = wolfSSL_connect(ssl);
80
0
            }
81
0
        }
82
0
        #endif
83
0
    }
84
85
0
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
86
87
0
    return err;
88
0
}
89
#endif /* !NO_TLS */
90
91
#if !defined(NO_TLS) && !(defined(WOLFSSL_NO_TLS12) && \
92
      defined(NO_OLD_TLS) && defined(WOLFSSL_TLS13)) && \
93
      (!defined(NO_WOLFSSL_CLIENT) || !defined(NO_WOLFSSL_SERVER))
94
95
#ifndef NO_WOLFSSL_CLIENT
96
/* Send any buffered output and retry a pending alert, for the client.
97
 *
98
 * Called once on entry to wolfSSL_connect(), before the state machine runs,
99
 * so that a message left unsent by a previous call is flushed before the next
100
 * one is built. The steps inside fall through to each other without coming
101
 * back here.
102
 *
103
 * Whether the state may be advanced is decided before the send, which is what
104
 * the client did before these two flushes were split out of their callers.
105
 * The server decides after; see wolfssl_accept_flush().
106
 *
107
 * @param [in, out] ssl  SSL/TLS object.
108
 * @return  0 when there was nothing to send or everything was sent.
109
 * @return  WOLFSSL_FATAL_ERROR when sending fails. ssl->error holds the reason.
110
 */
111
static int wolfssl_connect_flush(WOLFSSL* ssl)
112
0
{
113
0
    int ret = 0;
114
0
    byte advanceState;
115
116
    /* fragOffset is non-zero when sending fragments. On the last fragment,
117
     * fragOffset is zero again, and the state can be advanced. */
118
0
    advanceState = (byte)((ssl->fragOffset == 0) &&
119
0
        ((ssl->options.connectState == CONNECT_BEGIN) ||
120
0
         (ssl->options.connectState == HELLO_AGAIN) ||
121
0
         ((ssl->options.connectState >= FIRST_REPLY_DONE) &&
122
0
          (ssl->options.connectState <= FIRST_REPLY_FOURTH))));
123
124
    #ifdef WOLFSSL_DTLS13
125
    /* A DTLS 1.3 ACK or retransmit is not a step of the handshake, so
126
     * finishing one does not move the state on. */
127
    if ((ssl->options.dtls) && (IsAtLeastTLSv1_3(ssl->version))) {
128
        advanceState = (byte)((advanceState) &&
129
            (!ssl->dtls13SendingAckOrRtx));
130
    }
131
    #endif /* WOLFSSL_DTLS13 */
132
133
0
    if ((ssl->buffers.outputBuffer.length > 0)
134
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
135
        /* do not send buffered or advance state if the last error
136
           suspended the handshake - advancing frees the saved state */
137
        && !IsHsSuspendErr(ssl->error)
138
    #endif
139
0
    ) {
140
0
        ret = SendBuffered(ssl);
141
0
        if (ret == 0) {
142
0
            if ((ssl->fragOffset == 0) && (!ssl->options.buildingMsg)) {
143
0
                if (advanceState) {
144
0
                    ssl->options.connectState++;
145
0
                    WOLFSSL_MSG("connect state: Advanced from last buffered "
146
0
                                "fragment send");
147
0
                    #ifdef WOLFSSL_ASYNC_IO
148
                    /* Cleanup async */
149
0
                    FreeAsyncCtx(ssl, 0);
150
0
                    #endif
151
0
                }
152
0
            }
153
0
            else {
154
0
                WOLFSSL_MSG("connect state: Not advanced, more fragments to "
155
0
                            "send");
156
0
            }
157
            #ifdef WOLFSSL_DTLS13
158
            if (ssl->options.dtls) {
159
                ssl->dtls13SendingAckOrRtx = 0;
160
            }
161
            #endif /* WOLFSSL_DTLS13 */
162
0
        }
163
0
        else {
164
0
            ssl->error = ret;
165
0
            WOLFSSL_ERROR(ssl->error);
166
0
            ret = WOLFSSL_FATAL_ERROR;
167
0
        }
168
0
    }
169
170
0
    if (ret == 0) {
171
0
        ret = RetrySendAlert(ssl);
172
0
        if (ret != 0) {
173
0
            ssl->error = ret;
174
0
            WOLFSSL_ERROR(ssl->error);
175
0
            ret = WOLFSSL_FATAL_ERROR;
176
0
        }
177
0
    }
178
179
0
    return ret;
180
0
}
181
#endif /* !NO_WOLFSSL_CLIENT */
182
183
#ifndef NO_WOLFSSL_SERVER
184
/* Send any buffered output and retry a pending alert, for the server.
185
 *
186
 * Called once on entry to wolfSSL_accept(), before the state machine runs, so
187
 * that a message left unsent by a previous call is flushed before the next
188
 * one is built. The steps inside fall through to each other without coming
189
 * back here.
190
 *
191
 * Whether the state may be advanced is decided after the send, which is what
192
 * the server did before these two flushes were split out of their callers.
193
 * The client decides before; see wolfssl_connect_flush().
194
 *
195
 * @param [in, out] ssl  SSL/TLS object.
196
 * @return  0 when there was nothing to send or everything was sent.
197
 * @return  WOLFSSL_FATAL_ERROR when sending fails. ssl->error holds the reason.
198
 */
199
static int wolfssl_accept_flush(WOLFSSL* ssl)
200
{
201
    int ret = 0;
202
203
    if ((ssl->buffers.outputBuffer.length > 0)
204
    #ifdef WOLFSSL_HAVE_HS_SUSPEND
205
        /* do not send buffered or advance state if the last error
206
           suspended the handshake - advancing frees the saved state */
207
        && !IsHsSuspendErr(ssl->error)
208
    #endif
209
    ) {
210
        ret = SendBuffered(ssl);
211
        if (ret == 0) {
212
            /* fragOffset is non-zero when sending fragments. On the last
213
             * fragment, fragOffset is zero again, and the state can be
214
             * advanced. */
215
            if ((ssl->fragOffset == 0) && (!ssl->options.buildingMsg)) {
216
                /* The accept states listed here are the ones reached after a
217
                 * message has been sent, so they are the ones that may be
218
                 * advanced. */
219
                if ((ssl->options.acceptState == ACCEPT_FIRST_REPLY_DONE) ||
220
                    (ssl->options.acceptState == SERVER_HELLO_SENT) ||
221
                    (ssl->options.acceptState == CERT_SENT) ||
222
                    (ssl->options.acceptState == CERT_STATUS_SENT) ||
223
                    (ssl->options.acceptState == KEY_EXCHANGE_SENT) ||
224
                    (ssl->options.acceptState == CERT_REQ_SENT) ||
225
                    (ssl->options.acceptState == ACCEPT_SECOND_REPLY_DONE) ||
226
                    (ssl->options.acceptState == TICKET_SENT) ||
227
                    (ssl->options.acceptState == CHANGE_CIPHER_SENT)) {
228
                    ssl->options.acceptState++;
229
                    WOLFSSL_MSG("accept state: Advanced from last buffered "
230
                                "fragment send");
231
                    #ifdef WOLFSSL_ASYNC_IO
232
                    /* Cleanup async */
233
                    FreeAsyncCtx(ssl, 0);
234
                    #endif
235
                }
236
            }
237
            else {
238
                WOLFSSL_MSG("accept state: Not advanced, more fragments to "
239
                            "send");
240
            }
241
            #ifdef WOLFSSL_DTLS13
242
            if (ssl->options.dtls) {
243
                ssl->dtls13SendingAckOrRtx = 0;
244
            }
245
            #endif /* WOLFSSL_DTLS13 */
246
        }
247
        else {
248
            ssl->error = ret;
249
            WOLFSSL_ERROR(ssl->error);
250
            ret = WOLFSSL_FATAL_ERROR;
251
        }
252
    }
253
254
    if (ret == 0) {
255
        ret = RetrySendAlert(ssl);
256
        if (ret != 0) {
257
            ssl->error = ret;
258
            WOLFSSL_ERROR(ssl->error);
259
            ret = WOLFSSL_FATAL_ERROR;
260
        }
261
    }
262
263
    return ret;
264
}
265
#endif /* !NO_WOLFSSL_SERVER */
266
267
/* Only reached from the server's accept, and from the client's connect when
268
 * a pre-TLS-1.3 version is built, so it is guarded more tightly than the
269
 * flush above. */
270
#if !defined(NO_WOLFSSL_SERVER) || \
271
    (!defined(NO_WOLFSSL_CLIENT) && \
272
     (!defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)))
273
/* Finish the handshake.
274
 *
275
 * Notifies the application, releases the memory used only during the handshake
276
 * and discards any asynchronous state.
277
 *
278
 * @param [in, out] ssl  SSL/TLS object.
279
 * @return  0 when the handshake is finished.
280
 * @return  WOLFSSL_FATAL_ERROR when the handshake done callback asks to stop.
281
 *          ssl->error holds the value the callback returned.
282
 */
283
static int wolfssl_handshake_done(WOLFSSL* ssl)
284
0
{
285
0
    int ret = 0;
286
287
0
    #ifndef NO_HANDSHAKE_DONE_CB
288
0
    if (ssl->hsDoneCb != NULL) {
289
0
        int cbret = ssl->hsDoneCb(ssl, ssl->hsDoneCtx);
290
0
        if (cbret < 0) {
291
0
            ssl->error = cbret;
292
0
            WOLFSSL_MSG("HandShake Done Cb don't continue error");
293
            /* The caller reports the failure, so don't trace it here too. */
294
0
            ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
295
0
        }
296
0
    }
297
0
    #endif /* NO_HANDSHAKE_DONE_CB */
298
299
0
    if (ret == 0) {
300
0
        if (!ssl->options.dtls) {
301
0
            if (!ssl->options.keepResources) {
302
0
                FreeHandshakeResources(ssl);
303
0
            }
304
0
        }
305
        #ifdef WOLFSSL_DTLS
306
        else {
307
            ssl->options.dtlsHsRetain = 1;
308
        }
309
        #endif /* WOLFSSL_DTLS */
310
311
        #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_SECURE_RENEGOTIATION)
312
        /* This may be necessary in async so that we don't try to
313
         * renegotiate again */
314
        if ((ssl->secure_renegotiation != NULL) &&
315
                (ssl->secure_renegotiation->startScr)) {
316
            ssl->secure_renegotiation->startScr = 0;
317
        }
318
        #endif /* WOLFSSL_ASYNC_CRYPT && HAVE_SECURE_RENEGOTIATION */
319
0
        #if defined(WOLFSSL_ASYNC_IO) && !defined(WOLFSSL_ASYNC_CRYPT)
320
        /* Free the remaining async context if not using it for crypto */
321
0
        FreeAsyncCtx(ssl, 1);
322
0
        #endif
323
0
    }
324
325
0
    return ret;
326
0
}
327
#endif /* !NO_WOLFSSL_SERVER || (!NO_WOLFSSL_CLIENT &&
328
        * (!WOLFSSL_NO_TLS12 || !NO_OLD_TLS)) */
329
#endif /* !NO_TLS && !(WOLFSSL_NO_TLS12 && NO_OLD_TLS && WOLFSSL_TLS13) &&
330
        * (!NO_WOLFSSL_CLIENT || !NO_WOLFSSL_SERVER) */
331
332
/* client only parts */
333
#if !defined(NO_WOLFSSL_CLIENT) && !defined(NO_TLS)
334
335
/* Perform the client side of the handshake.
336
 *
337
 * Drives the handshake state machine, resuming from wherever the previous call
338
 * stopped. When non-blocking I/O is in use, the call returns before the
339
 * handshake completes and must be called again.
340
 *
341
 * Please see the note at the top of README if you get an error from connect.
342
 *
343
 * @param [in, out] ssl  SSL/TLS object.
344
 * @return  WOLFSSL_SUCCESS when the handshake completes.
345
 * @return  BAD_FUNC_ARG when ssl is NULL.
346
 * @return  WOLFSSL_FATAL_ERROR when the object is not a client, a message
347
 *          cannot be sent or received, or the peer reports an error. Call
348
 *          wolfSSL_get_error() to determine whether the operation should be
349
 *          retried.
350
 * @return  The error from ReinitSSL(), unchanged, when the object cannot be
351
 *          prepared for a handshake. This is a raw error code rather than
352
 *          WOLFSSL_FATAL_ERROR, and ssl->error is not set with it.
353
 *
354
 * Unlike the rest of this file, the handshake state machine below
355
 * returns from each step rather than using a single exit. Each step
356
 * must stop the handshake where it failed, and several of the steps
357
 * return from inside a receive loop, where a break would only leave
358
 * the loop.
359
 */
360
WOLFSSL_ABI
361
int wolfSSL_connect(WOLFSSL* ssl)
362
0
{
363
0
    #if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
364
0
      defined(WOLFSSL_TLS13))
365
0
    int neededState;
366
0
    #endif
367
0
    int ret = 0;
368
369
0
    (void)ret;
370
371
0
    #ifdef HAVE_ERRNO_H
372
0
    errno = 0;
373
0
    #endif
374
375
0
    if (ssl == NULL) {
376
0
        return BAD_FUNC_ARG;
377
0
    }
378
379
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
380
    if (ssl->options.side == WOLFSSL_NEITHER_END) {
381
        ssl->error = InitSSL_Side(ssl, WOLFSSL_CLIENT_END);
382
        if (ssl->error != WOLFSSL_SUCCESS) {
383
            WOLFSSL_ERROR(ssl->error);
384
            return WOLFSSL_FATAL_ERROR;
385
        }
386
        ssl->error = 0; /* expected to be zero here */
387
    }
388
389
    #ifdef OPENSSL_EXTRA
390
    if (ssl->CBIS != NULL) {
391
        ssl->CBIS(ssl, WOLFSSL_ST_CONNECT, WOLFSSL_SUCCESS);
392
        ssl->cbmode = WOLFSSL_CB_WRITE;
393
    }
394
    #endif
395
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
396
397
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
398
        defined(WOLFSSL_TLS13)
399
    return wolfSSL_connect_TLSv13(ssl);
400
    #else
401
0
    #ifdef WOLFSSL_TLS13
402
0
    if (ssl->options.tls1_3) {
403
0
        WOLFSSL_MSG("TLS 1.3");
404
0
        return wolfSSL_connect_TLSv13(ssl);
405
0
    }
406
0
    #endif
407
408
0
    WOLFSSL_MSG("TLS 1.2 or lower");
409
0
    WOLFSSL_ENTER("wolfSSL_connect");
410
411
    /* make sure this wolfSSL object has arrays and rng setup. Protects
412
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
413
0
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
414
0
        return ret;
415
0
    }
416
417
    #ifdef WOLFSSL_WOLFSENTRY_HOOKS
418
    if ((ssl->ConnectFilter != NULL) &&
419
        (ssl->options.connectState == CONNECT_BEGIN)) {
420
        wolfSSL_netfilter_decision_t res;
421
        if ((ssl->ConnectFilter(ssl, ssl->ConnectFilter_arg, &res) ==
422
             WOLFSSL_SUCCESS) &&
423
            (res == WOLFSSL_NETFILTER_REJECT)) {
424
            ssl->error = SOCKET_FILTERED_E;
425
            WOLFSSL_ERROR(ssl->error);
426
            return WOLFSSL_FATAL_ERROR;
427
        }
428
    }
429
    #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
430
431
0
    if (ssl->options.side != WOLFSSL_CLIENT_END) {
432
0
        ssl->error = SIDE_ERROR;
433
0
        WOLFSSL_ERROR(ssl->error);
434
0
        return WOLFSSL_FATAL_ERROR;
435
0
    }
436
437
    #ifdef WOLFSSL_DTLS
438
    if (ssl->version.major == DTLS_MAJOR) {
439
        ssl->options.dtls   = 1;
440
        ssl->options.tls    = 1;
441
        ssl->options.tls1_1 = 1;
442
        ssl->options.dtlsStateful = 1;
443
    }
444
    #endif
445
446
0
    ret = wolfssl_connect_flush(ssl);
447
0
    if (ret != 0) {
448
0
        return ret;
449
0
    }
450
451
0
    switch (ssl->options.connectState) {
452
453
0
    case CONNECT_BEGIN :
454
        /* always send client hello first */
455
0
        if ((ssl->error = SendClientHello(ssl)) != 0) {
456
0
            WOLFSSL_ERROR(ssl->error);
457
0
            return WOLFSSL_FATAL_ERROR;
458
0
        }
459
0
        ssl->options.connectState = CLIENT_HELLO_SENT;
460
0
        WOLFSSL_MSG("connect state: CLIENT_HELLO_SENT");
461
0
        FALL_THROUGH;
462
463
0
    case CLIENT_HELLO_SENT :
464
0
        neededState = ssl->options.resuming ? SERVER_FINISHED_COMPLETE :
465
0
                                              SERVER_HELLODONE_COMPLETE;
466
        #ifdef WOLFSSL_DTLS
467
        /* In DTLS, when resuming, we can go straight to FINISHED,
468
         * or do a cookie exchange and then skip to FINISHED, assume
469
         * we need the cookie exchange first. */
470
        if (IsDtlsNotSctpMode(ssl)) {
471
            neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
472
        }
473
        #endif
474
        /* get response */
475
0
        WOLFSSL_MSG("Server state up to needed state.");
476
0
        while (ssl->options.serverState < neededState) {
477
0
            WOLFSSL_MSG("Progressing server state...");
478
0
            #ifdef WOLFSSL_TLS13
479
0
            if (ssl->options.tls1_3) {
480
0
                return wolfSSL_connect_TLSv13(ssl);
481
0
            }
482
0
            #endif
483
0
            WOLFSSL_MSG("ProcessReply...");
484
0
            if ((ssl->error = ProcessReply(ssl)) < 0) {
485
0
                WOLFSSL_ERROR(ssl->error);
486
0
                return WOLFSSL_FATAL_ERROR;
487
0
            }
488
            /* if resumption failed, reset needed state */
489
0
            else if (neededState == SERVER_FINISHED_COMPLETE) {
490
0
                if (!ssl->options.resuming) {
491
                    #ifdef WOLFSSL_DTLS
492
                    if (IsDtlsNotSctpMode(ssl)) {
493
                        neededState = SERVER_HELLOVERIFYREQUEST_COMPLETE;
494
                    }
495
                    else
496
                    #endif
497
0
                        neededState = SERVER_HELLODONE_COMPLETE;
498
0
                }
499
0
            }
500
0
            WOLFSSL_MSG("ProcessReply done.");
501
502
            #ifdef WOLFSSL_DTLS13
503
            if ((ssl->options.dtls) && (IsAtLeastTLSv1_3(ssl->version))
504
                && (ssl->dtls13Rtx.sendAcks == 1)
505
                && (ssl->options.seenUnifiedHdr)) {
506
                /* we aren't negotiated the version yet, so we aren't sure
507
                 * the other end can speak v1.3. On the other side we have
508
                 * received a unified records, assuming that the
509
                 * ServerHello got lost, we will send an empty ACK. In case
510
                 * the server is a DTLS with version less than 1.3, it
511
                 * should just ignore the message */
512
                ssl->dtls13Rtx.sendAcks = 0;
513
                if ((ssl->error = SendDtls13Ack(ssl)) < 0) {
514
                    if (ssl->error == WC_NO_ERR_TRACE(WANT_WRITE)) {
515
                        ssl->dtls13SendingAckOrRtx = 1;
516
                    }
517
                    WOLFSSL_ERROR(ssl->error);
518
                    return WOLFSSL_FATAL_ERROR;
519
                }
520
            }
521
            #endif /* WOLFSSL_DTLS13 */
522
0
        }
523
524
0
        ssl->options.connectState = HELLO_AGAIN;
525
0
        WOLFSSL_MSG("connect state: HELLO_AGAIN");
526
0
        FALL_THROUGH;
527
528
0
    case HELLO_AGAIN :
529
530
0
        #ifdef WOLFSSL_TLS13
531
0
        if (ssl->options.tls1_3) {
532
0
            return wolfSSL_connect_TLSv13(ssl);
533
0
        }
534
0
        #endif
535
536
        #ifdef WOLFSSL_DTLS
537
        if (ssl->options.serverState ==
538
                SERVER_HELLOVERIFYREQUEST_COMPLETE) {
539
            if (IsDtlsNotSctpMode(ssl)) {
540
                /* re-init hashes, exclude first hello and verify request */
541
                if ((ssl->error = InitHandshakeHashes(ssl)) != 0) {
542
                    WOLFSSL_ERROR(ssl->error);
543
                    return WOLFSSL_FATAL_ERROR;
544
                }
545
                if ((ssl->error = SendClientHello(ssl)) != 0) {
546
                    WOLFSSL_ERROR(ssl->error);
547
                    return WOLFSSL_FATAL_ERROR;
548
                }
549
            }
550
        }
551
        #endif
552
553
0
        ssl->options.connectState = HELLO_AGAIN_REPLY;
554
0
        WOLFSSL_MSG("connect state: HELLO_AGAIN_REPLY");
555
0
        FALL_THROUGH;
556
557
0
    case HELLO_AGAIN_REPLY :
558
        #ifdef WOLFSSL_DTLS
559
        if (IsDtlsNotSctpMode(ssl)) {
560
            neededState = ssl->options.resuming ?
561
                SERVER_FINISHED_COMPLETE : SERVER_HELLODONE_COMPLETE;
562
563
            /* get response */
564
            while (ssl->options.serverState < neededState) {
565
                if ((ssl->error = ProcessReply(ssl)) < 0) {
566
                    WOLFSSL_ERROR(ssl->error);
567
                    return WOLFSSL_FATAL_ERROR;
568
                }
569
                /* if resumption failed, reset needed state */
570
                if (neededState == SERVER_FINISHED_COMPLETE) {
571
                    if (!ssl->options.resuming) {
572
                        neededState = SERVER_HELLODONE_COMPLETE;
573
                    }
574
                }
575
            }
576
        }
577
        #endif
578
579
0
        ssl->options.connectState = FIRST_REPLY_DONE;
580
0
        WOLFSSL_MSG("connect state: FIRST_REPLY_DONE");
581
0
        FALL_THROUGH;
582
583
0
    case FIRST_REPLY_DONE :
584
0
        if (ssl->options.certOnly) {
585
0
            return WOLFSSL_SUCCESS;
586
0
        }
587
0
        #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
588
0
        #ifdef WOLFSSL_TLS13
589
0
        if (ssl->options.tls1_3) {
590
0
            return wolfSSL_connect_TLSv13(ssl);
591
0
        }
592
0
        #endif
593
0
        if (ssl->options.sendVerify) {
594
0
            if ((ssl->error = SendCertificate(ssl)) != 0) {
595
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
596
0
                WOLFSSL_ERROR(ssl->error);
597
0
                return WOLFSSL_FATAL_ERROR;
598
0
            }
599
0
            WOLFSSL_MSG("sent: certificate");
600
0
        }
601
602
0
        #endif
603
0
        ssl->options.connectState = FIRST_REPLY_FIRST;
604
0
        WOLFSSL_MSG("connect state: FIRST_REPLY_FIRST");
605
0
        FALL_THROUGH;
606
607
0
    case FIRST_REPLY_FIRST :
608
0
        #ifdef WOLFSSL_TLS13
609
0
        if (ssl->options.tls1_3) {
610
0
            return wolfSSL_connect_TLSv13(ssl);
611
0
        }
612
0
        #endif
613
0
        if (!ssl->options.resuming) {
614
0
            if ((ssl->error = SendClientKeyExchange(ssl)) != 0) {
615
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
616
                #ifdef WOLFSSL_EXTRA_ALERTS
617
                if ((ssl->error == WC_NO_ERR_TRACE(NO_PEER_KEY)) ||
618
                    (ssl->error == WC_NO_ERR_TRACE(PSK_KEY_ERROR))) {
619
                    SendAlert(ssl, alert_fatal, handshake_failure);
620
                }
621
                #endif
622
0
                WOLFSSL_ERROR(ssl->error);
623
0
                return WOLFSSL_FATAL_ERROR;
624
0
            }
625
0
            WOLFSSL_MSG("sent: client key exchange");
626
0
        }
627
628
0
        ssl->options.connectState = FIRST_REPLY_SECOND;
629
0
        WOLFSSL_MSG("connect state: FIRST_REPLY_SECOND");
630
0
        FALL_THROUGH;
631
632
0
        #if !defined(WOLFSSL_NO_TLS12) || !defined(NO_OLD_TLS)
633
0
    case FIRST_REPLY_SECOND :
634
        /* CLIENT: Fail-safe for Server Authentication. */
635
0
        if (!ssl->options.peerAuthGood) {
636
0
            WOLFSSL_MSG("Server authentication did not happen");
637
0
            ssl->error = NO_PEER_VERIFY;
638
0
            return WOLFSSL_FATAL_ERROR;
639
0
        }
640
641
0
        #if !defined(NO_CERTS) && !defined(WOLFSSL_NO_CLIENT_AUTH)
642
0
        if (ssl->options.sendVerify) {
643
0
            if ((ssl->error = SendCertificateVerify(ssl)) != 0) {
644
0
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
645
0
                WOLFSSL_ERROR(ssl->error);
646
0
                return WOLFSSL_FATAL_ERROR;
647
0
            }
648
0
            WOLFSSL_MSG("sent: certificate verify");
649
0
        }
650
0
        #endif /* !NO_CERTS && !WOLFSSL_NO_CLIENT_AUTH */
651
0
        ssl->options.connectState = FIRST_REPLY_THIRD;
652
0
        WOLFSSL_MSG("connect state: FIRST_REPLY_THIRD");
653
0
        FALL_THROUGH;
654
655
0
    case FIRST_REPLY_THIRD :
656
0
        if ((ssl->error = SendChangeCipher(ssl)) != 0) {
657
0
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
658
0
            WOLFSSL_ERROR(ssl->error);
659
0
            return WOLFSSL_FATAL_ERROR;
660
0
        }
661
0
        WOLFSSL_MSG("sent: change cipher spec");
662
0
        ssl->options.connectState = FIRST_REPLY_FOURTH;
663
0
        WOLFSSL_MSG("connect state: FIRST_REPLY_FOURTH");
664
0
        FALL_THROUGH;
665
666
0
    case FIRST_REPLY_FOURTH :
667
0
        if ((ssl->error = SendFinished(ssl)) != 0) {
668
0
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
669
0
            WOLFSSL_ERROR(ssl->error);
670
0
            return WOLFSSL_FATAL_ERROR;
671
0
        }
672
0
        WOLFSSL_MSG("sent: finished");
673
0
        ssl->options.connectState = FINISHED_DONE;
674
0
        WOLFSSL_MSG("connect state: FINISHED_DONE");
675
0
        FALL_THROUGH;
676
677
        #ifdef WOLFSSL_DTLS13
678
    case WAIT_FINISHED_ACK:
679
        ssl->options.connectState = FINISHED_DONE;
680
        FALL_THROUGH;
681
        #endif /* WOLFSSL_DTLS13 */
682
683
0
    case FINISHED_DONE :
684
        /* get response */
685
0
        while (ssl->options.serverState < SERVER_FINISHED_COMPLETE) {
686
0
            if ((ssl->error = ProcessReply(ssl)) < 0) {
687
0
                WOLFSSL_ERROR(ssl->error);
688
0
                return WOLFSSL_FATAL_ERROR;
689
0
            }
690
0
        }
691
692
        #if defined(HAVE_ECH)
693
        /* RFC 9849 s6.1.4: negotiating below TLS 1.3 means the server rejected
694
         * ECH. Abort with ech_required instead of reporting success. */
695
        if (EchRejected(ssl)) {
696
            SendAlert(ssl, alert_fatal, ech_required);
697
            ssl->error = ECH_REQUIRED_E;
698
            WOLFSSL_ERROR_VERBOSE(ECH_REQUIRED_E);
699
            return WOLFSSL_FATAL_ERROR;
700
        }
701
        #endif /* HAVE_ECH */
702
703
0
        ssl->options.connectState = SECOND_REPLY_DONE;
704
0
        WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
705
0
        FALL_THROUGH;
706
707
0
    case SECOND_REPLY_DONE:
708
0
        if (wolfssl_handshake_done(ssl) != 0) {
709
0
            return WOLFSSL_FATAL_ERROR;
710
0
        }
711
712
0
        ssl->error = 0; /* clear the error */
713
714
0
        WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
715
0
        return WOLFSSL_SUCCESS;
716
0
        #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
717
718
0
    default:
719
0
        WOLFSSL_MSG("Unknown connect state ERROR");
720
0
        return WOLFSSL_FATAL_ERROR; /* unknown connect state */
721
0
    }
722
0
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
723
0
}
724
725
726
/* Perform enough of the handshake to get the peer's certificate chain.
727
 *
728
 * The handshake stops once the server's certificate has been processed, so no
729
 * secure connection is established.
730
 *
731
 * @param [in, out] ssl  SSL/TLS object.
732
 * @return  WOLFSSL_SUCCESS when the certificate chain was received.
733
 * @return  WOLFSSL_FAILURE when ssl is NULL.
734
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails.
735
 */
736
int wolfSSL_connect_cert(WOLFSSL* ssl)
737
0
{
738
0
    int ret;
739
740
0
    if (ssl == NULL) {
741
0
        ret = WOLFSSL_FAILURE;
742
0
    }
743
0
    else {
744
0
        ssl->options.certOnly = 1;
745
0
        ret = wolfSSL_connect(ssl);
746
0
        ssl->options.certOnly = 0;
747
0
    }
748
749
0
    return ret;
750
0
}
751
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
752
/* end client only parts */
753
754
/* server only parts */
755
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
756
757
/* Only called from the TLS 1.2 and earlier accept path, so it is guarded to
758
 * match: a TLS 1.3-only build returns before reaching it. */
759
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
760
      defined(WOLFSSL_TLS13))
761
/* Check the server has the credentials needed to perform a handshake.
762
 *
763
 * A certificate and private key are required unless an anonymous or PSK cipher
764
 * suite may be chosen, the object is multicast, a certificate setup callback
765
 * will supply them, or the private key is held externally.
766
 *
767
 * Checked on every call in case wolfSSL_set_accept_state() was used after the
768
 * object was initialized.
769
 *
770
 * @param [in, out] ssl  SSL/TLS object.
771
 * @return  0 when the credentials can be used.
772
 * @return  WOLFSSL_FATAL_ERROR when the certificate or private key is missing.
773
 */
774
static int wolfssl_accept_check_creds(WOLFSSL* ssl)
775
0
{
776
0
    int ret = 0;
777
0
    #ifndef NO_CERTS
778
0
    word16 havePSK = 0;
779
0
    word16 haveAnon = 0;
780
0
    word16 haveMcast = 0;
781
782
    #ifndef NO_PSK
783
    havePSK = ssl->options.havePSK;
784
    #endif
785
786
    #ifdef HAVE_ANON
787
    haveAnon = ssl->options.useAnon;
788
    #endif
789
790
    #ifdef WOLFSSL_MULTICAST
791
    haveMcast = ssl->options.haveMcast;
792
    #endif
793
794
0
    if ((!havePSK) && (!haveAnon) && (!haveMcast)) {
795
        #ifdef WOLFSSL_CERT_SETUP_CB
796
        if (ssl->ctx->certSetupCb != NULL) {
797
            WOLFSSL_MSG("CertSetupCb set. server cert and "
798
                        "key not checked");
799
        }
800
        else
801
        #endif
802
0
        {
803
0
            if ((ssl->buffers.certificate == NULL) ||
804
0
                    (ssl->buffers.certificate->buffer == NULL)) {
805
0
                WOLFSSL_MSG("accept error: server cert required");
806
0
                ssl->error = NO_PRIVATE_KEY;
807
0
                WOLFSSL_ERROR(ssl->error);
808
0
                ret = WOLFSSL_FATAL_ERROR;
809
0
            }
810
0
            else if ((ssl->buffers.key == NULL) ||
811
0
                    (ssl->buffers.key->buffer == NULL)) {
812
                /* allow no private key if using existing key */
813
0
                #ifdef WOLF_PRIVATE_KEY_ID
814
0
                if ((ssl->devId != INVALID_DEVID)
815
                #ifdef HAVE_PK_CALLBACKS
816
                    || (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
817
                #endif
818
0
                ) {
819
0
                    WOLFSSL_MSG("Allowing no server private key "
820
0
                                "(external)");
821
0
                }
822
0
                else
823
0
                #endif
824
0
                {
825
0
                    WOLFSSL_MSG("accept error: server key required");
826
0
                    ssl->error = NO_PRIVATE_KEY;
827
0
                    WOLFSSL_ERROR(ssl->error);
828
0
                    ret = WOLFSSL_FATAL_ERROR;
829
0
                }
830
0
            }
831
0
        }
832
0
    }
833
    #else
834
    (void)ssl;
835
    #endif /* !NO_CERTS */
836
837
0
    return ret;
838
0
}
839
#endif /* !(WOLFSSL_NO_TLS12 && NO_OLD_TLS && WOLFSSL_TLS13) */
840
841
/* Accept a connection from a client.
842
 *
843
 * Performs the server side of the handshake, resuming from where it last
844
 * stopped when non-blocking. Dispatches to the TLS 1.3 or DTLS handshake
845
 * when negotiated.
846
 *
847
 * @param [in, out] ssl  SSL/TLS object.
848
 * @return  WOLFSSL_SUCCESS when the handshake completes.
849
 * @return  WOLFSSL_FATAL_ERROR when ssl is NULL or the handshake fails.
850
 *          Call wolfSSL_get_error() for the reason. WOLFSSL_ERROR_WANT_READ
851
 *          and WOLFSSL_ERROR_WANT_WRITE mean call again.
852
 * @return  The error from ReinitSSL(), unchanged, when the object cannot be
853
 *          prepared for a handshake. This is a raw error code rather than
854
 *          WOLFSSL_FATAL_ERROR, and ssl->error is not set with it.
855
 *
856
 * Unlike the rest of this file, the handshake state machine below
857
 * returns from each step rather than using a single exit. Each step
858
 * must stop the handshake where it failed, and several of the steps
859
 * return from inside a receive loop, where a break would only leave
860
 * the loop.
861
 */
862
WOLFSSL_ABI
863
int wolfSSL_accept(WOLFSSL* ssl)
864
{
865
    int ret = 0;
866
867
    (void)ret;
868
869
    if (ssl == NULL) {
870
        return WOLFSSL_FATAL_ERROR;
871
    }
872
873
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
874
    if (ssl->options.side == WOLFSSL_NEITHER_END) {
875
        WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
876
        ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
877
        if (ssl->error != WOLFSSL_SUCCESS) {
878
            WOLFSSL_ERROR(ssl->error);
879
            return WOLFSSL_FATAL_ERROR;
880
        }
881
        ssl->error = 0; /* expected to be zero here */
882
    }
883
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
884
885
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
886
        defined(WOLFSSL_TLS13)
887
    return wolfSSL_accept_TLSv13(ssl);
888
    #else
889
    #ifdef WOLFSSL_TLS13
890
    if (ssl->options.tls1_3) {
891
        return wolfSSL_accept_TLSv13(ssl);
892
    }
893
    #endif
894
    WOLFSSL_ENTER("wolfSSL_accept");
895
896
    /* make sure this wolfSSL object has arrays and rng setup. Protects
897
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
898
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
899
        return ret;
900
    }
901
902
    #ifdef WOLFSSL_WOLFSENTRY_HOOKS
903
    if ((ssl->AcceptFilter != NULL) &&
904
        ((ssl->options.acceptState == ACCEPT_BEGIN)
905
    #ifdef HAVE_SECURE_RENEGOTIATION
906
         || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
907
    #endif
908
            ))
909
    {
910
        wolfSSL_netfilter_decision_t res;
911
        if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
912
             WOLFSSL_SUCCESS) &&
913
            (res == WOLFSSL_NETFILTER_REJECT)) {
914
            ssl->error = SOCKET_FILTERED_E;
915
            WOLFSSL_ERROR(ssl->error);
916
            return WOLFSSL_FATAL_ERROR;
917
        }
918
    }
919
    #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
920
921
    #ifdef HAVE_ERRNO_H
922
    errno = 0;
923
    #endif
924
925
    if (ssl->options.side != WOLFSSL_SERVER_END) {
926
        ssl->error = SIDE_ERROR;
927
        WOLFSSL_ERROR(ssl->error);
928
        return WOLFSSL_FATAL_ERROR;
929
    }
930
931
    ret = wolfssl_accept_check_creds(ssl);
932
    if (ret != 0) {
933
        return ret;
934
    }
935
936
    #ifdef WOLFSSL_DTLS
937
    if (ssl->version.major == DTLS_MAJOR) {
938
        ssl->options.dtls   = 1;
939
        ssl->options.tls    = 1;
940
        ssl->options.tls1_1 = 1;
941
        if (!ssl->options.sendCookie)
942
            ssl->options.dtlsStateful = 1;
943
        if ((!IsDtlsNotSctpMode(ssl)) || (IsSCR(ssl))) {
944
            ssl->options.dtlsStateful = 1;
945
        }
946
    #if defined(WOLFSSL_TLS13) && defined(HAVE_ECH)
947
        if (!ssl->options.disableECH && ssl->ctx->echConfigs != NULL) {
948
            WOLFSSL_MSG("ECH configs set but ECH is not supported with DTLS");
949
            ssl->error = BAD_STATE_E;
950
            WOLFSSL_ERROR(ssl->error);
951
            return WOLFSSL_FATAL_ERROR;
952
        }
953
    #endif
954
    }
955
    #endif
956
957
    ret = wolfssl_accept_flush(ssl);
958
    if (ret != 0) {
959
        return ret;
960
    }
961
962
    switch (ssl->options.acceptState) {
963
964
    case ACCEPT_BEGIN :
965
        #ifdef HAVE_SECURE_RENEGOTIATION
966
    case ACCEPT_BEGIN_RENEG:
967
        #endif
968
        /* get response */
969
        while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
970
            if ((ssl->error = ProcessReply(ssl)) < 0) {
971
                WOLFSSL_ERROR(ssl->error);
972
                return WOLFSSL_FATAL_ERROR;
973
            }
974
        }
975
        #ifdef WOLFSSL_DTLS
976
        /* Notify before the existing first CH transition. */
977
        if (ssl->options.acceptState == ACCEPT_BEGIN) {
978
            if ((ssl->error = DtlsNoCookieChGood(ssl)) < 0) {
979
                WOLFSSL_ERROR(ssl->error);
980
                return WOLFSSL_FATAL_ERROR;
981
            }
982
        }
983
        #endif
984
        #ifdef WOLFSSL_TLS13
985
        ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
986
        WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
987
        FALL_THROUGH;
988
989
    case ACCEPT_CLIENT_HELLO_DONE :
990
        if (ssl->options.tls1_3) {
991
            return wolfSSL_accept_TLSv13(ssl);
992
        }
993
        #endif
994
995
        ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
996
        WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
997
        FALL_THROUGH;
998
999
    case ACCEPT_FIRST_REPLY_DONE :
1000
        if (ssl->options.returnOnGoodCh) {
1001
            /* Higher level in stack wants us to return. Simulate a
1002
             * WANT_WRITE to accomplish this. */
1003
            ssl->error = WANT_WRITE;
1004
            return WOLFSSL_FATAL_ERROR;
1005
        }
1006
        if ((ssl->error = SendServerHello(ssl)) != 0) {
1007
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1008
            WOLFSSL_ERROR(ssl->error);
1009
            return WOLFSSL_FATAL_ERROR;
1010
        }
1011
        ssl->options.acceptState = SERVER_HELLO_SENT;
1012
        WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
1013
        FALL_THROUGH;
1014
1015
    case SERVER_HELLO_SENT :
1016
        #ifdef WOLFSSL_TLS13
1017
        if (ssl->options.tls1_3) {
1018
            return wolfSSL_accept_TLSv13(ssl);
1019
        }
1020
        #endif
1021
        #ifndef NO_CERTS
1022
        if (!ssl->options.resuming) {
1023
            if ((ssl->error = SendCertificate(ssl)) != 0) {
1024
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1025
                WOLFSSL_ERROR(ssl->error);
1026
                return WOLFSSL_FATAL_ERROR;
1027
            }
1028
        }
1029
        #endif
1030
        ssl->options.acceptState = CERT_SENT;
1031
        WOLFSSL_MSG("accept state CERT_SENT");
1032
        FALL_THROUGH;
1033
1034
    case CERT_SENT :
1035
        #ifndef NO_CERTS
1036
        if (!ssl->options.resuming) {
1037
            if ((ssl->error = SendCertificateStatus(ssl)) != 0) {
1038
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1039
                WOLFSSL_ERROR(ssl->error);
1040
                return WOLFSSL_FATAL_ERROR;
1041
            }
1042
        }
1043
        #endif
1044
        ssl->options.acceptState = CERT_STATUS_SENT;
1045
        WOLFSSL_MSG("accept state CERT_STATUS_SENT");
1046
        FALL_THROUGH;
1047
1048
    case CERT_STATUS_SENT :
1049
        #ifdef WOLFSSL_TLS13
1050
        if (ssl->options.tls1_3) {
1051
            return wolfSSL_accept_TLSv13(ssl);
1052
        }
1053
        #endif
1054
        if (!ssl->options.resuming) {
1055
            if ((ssl->error = SendServerKeyExchange(ssl)) != 0) {
1056
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1057
                WOLFSSL_ERROR(ssl->error);
1058
                return WOLFSSL_FATAL_ERROR;
1059
            }
1060
        }
1061
        ssl->options.acceptState = KEY_EXCHANGE_SENT;
1062
        WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
1063
        FALL_THROUGH;
1064
1065
    case KEY_EXCHANGE_SENT :
1066
        #ifndef NO_CERTS
1067
        if (!ssl->options.resuming) {
1068
            if (ssl->options.verifyPeer) {
1069
                if ((ssl->error = SendCertificateRequest(ssl)) != 0) {
1070
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1071
                    WOLFSSL_ERROR(ssl->error);
1072
                    return WOLFSSL_FATAL_ERROR;
1073
                }
1074
            }
1075
            else {
1076
                /* SERVER: Peer auth good if not verifying client. */
1077
                ssl->options.peerAuthGood = 1;
1078
            }
1079
        }
1080
        #endif
1081
        ssl->options.acceptState = CERT_REQ_SENT;
1082
        WOLFSSL_MSG("accept state CERT_REQ_SENT");
1083
        FALL_THROUGH;
1084
1085
    case CERT_REQ_SENT :
1086
        if (!ssl->options.resuming) {
1087
            if ((ssl->error = SendServerHelloDone(ssl)) != 0) {
1088
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1089
                WOLFSSL_ERROR(ssl->error);
1090
                return WOLFSSL_FATAL_ERROR;
1091
            }
1092
        }
1093
        ssl->options.acceptState = SERVER_HELLO_DONE;
1094
        WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
1095
        FALL_THROUGH;
1096
1097
    case SERVER_HELLO_DONE :
1098
        if (!ssl->options.resuming) {
1099
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
1100
                if ((ssl->error = ProcessReply(ssl)) < 0) {
1101
                    WOLFSSL_ERROR(ssl->error);
1102
                    return WOLFSSL_FATAL_ERROR;
1103
                }
1104
            }
1105
        }
1106
        ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
1107
        WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
1108
        FALL_THROUGH;
1109
1110
    case ACCEPT_SECOND_REPLY_DONE :
1111
        #ifndef NO_CERTS
1112
        /* SERVER: When not resuming and verifying peer but no certificate
1113
         * received and none was required then peer auth good.
1114
         */
1115
        if ((!ssl->options.resuming) && (ssl->options.verifyPeer) &&
1116
                (!ssl->options.havePeerCert) &&
1117
                (!ClientAuthRequired(ssl, ssl->options.usingPSK_cipher))) {
1118
            ssl->options.peerAuthGood = 1;
1119
        }
1120
        #endif /* !NO_CERTS  */
1121
        #ifdef WOLFSSL_NO_CLIENT_AUTH
1122
        if (!ssl->options.resuming) {
1123
            ssl->options.peerAuthGood = 1;
1124
        }
1125
        #endif
1126
1127
        #ifdef HAVE_SESSION_TICKET
1128
        if ((ssl->options.createTicket) &&
1129
                (!ssl->options.noTicketTls12)) {
1130
            if ((ssl->error = SendTicket(ssl)) != 0) {
1131
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1132
                WOLFSSL_MSG("Thought we need ticket but failed");
1133
                WOLFSSL_ERROR(ssl->error);
1134
                return WOLFSSL_FATAL_ERROR;
1135
            }
1136
        }
1137
        #endif /* HAVE_SESSION_TICKET */
1138
        ssl->options.acceptState = TICKET_SENT;
1139
        WOLFSSL_MSG("accept state  TICKET_SENT");
1140
        FALL_THROUGH;
1141
1142
    case TICKET_SENT:
1143
        /* SERVER: Fail-safe for CLient Authentication. */
1144
        if (!ssl->options.peerAuthGood) {
1145
            WOLFSSL_MSG("Client authentication did not happen");
1146
            return WOLFSSL_FATAL_ERROR;
1147
        }
1148
1149
        if ((ssl->error = SendChangeCipher(ssl)) != 0) {
1150
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1151
            WOLFSSL_ERROR(ssl->error);
1152
            return WOLFSSL_FATAL_ERROR;
1153
        }
1154
        ssl->options.acceptState = CHANGE_CIPHER_SENT;
1155
        WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
1156
        FALL_THROUGH;
1157
1158
    case CHANGE_CIPHER_SENT :
1159
        if ((ssl->error = SendFinished(ssl)) != 0) {
1160
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1161
            WOLFSSL_ERROR(ssl->error);
1162
            return WOLFSSL_FATAL_ERROR;
1163
        }
1164
1165
        ssl->options.acceptState = ACCEPT_FINISHED_DONE;
1166
        WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
1167
        FALL_THROUGH;
1168
1169
    case ACCEPT_FINISHED_DONE :
1170
        if (ssl->options.resuming) {
1171
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
1172
                if ((ssl->error = ProcessReply(ssl)) < 0) {
1173
                    WOLFSSL_ERROR(ssl->error);
1174
                    return WOLFSSL_FATAL_ERROR;
1175
                }
1176
            }
1177
        }
1178
        ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
1179
        WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
1180
        FALL_THROUGH;
1181
1182
    case ACCEPT_THIRD_REPLY_DONE :
1183
        if (wolfssl_handshake_done(ssl) != 0) {
1184
            return WOLFSSL_FATAL_ERROR;
1185
        }
1186
1187
        #if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
1188
        if (ssl->dtls_export) {
1189
            if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
1190
                WOLFSSL_MSG("Export DTLS session error");
1191
                WOLFSSL_ERROR(ssl->error);
1192
                return WOLFSSL_FATAL_ERROR;
1193
            }
1194
        }
1195
        #endif
1196
        ssl->error = 0; /* clear the error */
1197
1198
        WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
1199
        return WOLFSSL_SUCCESS;
1200
1201
    default:
1202
        WOLFSSL_MSG("Unknown accept state ERROR");
1203
        return WOLFSSL_FATAL_ERROR;
1204
    }
1205
    #endif /* !WOLFSSL_NO_TLS12 */
1206
}
1207
1208
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
1209
/* end server only parts */
1210
1211
#ifndef NO_HANDSHAKE_DONE_CB
1212
1213
/* Set the callback to call when the handshake completes.
1214
 *
1215
 * @param [in, out] ssl       SSL/TLS object.
1216
 * @param [in]      cb        Callback to call. NULL to clear.
1217
 * @param [in]      user_ctx  Context to pass to the callback.
1218
 * @return  WOLFSSL_SUCCESS on success.
1219
 * @return  BAD_FUNC_ARG when ssl is NULL.
1220
 */
1221
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
1222
0
{
1223
0
    int ret = WOLFSSL_SUCCESS;
1224
1225
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
1226
1227
0
    if (ssl == NULL) {
1228
0
        ret = BAD_FUNC_ARG;
1229
0
    }
1230
0
    else {
1231
0
        ssl->hsDoneCb  = cb;
1232
0
        ssl->hsDoneCtx = user_ctx;
1233
0
    }
1234
1235
0
    return ret;
1236
0
}
1237
1238
#endif /* NO_HANDSHAKE_DONE_CB */
1239
1240
#ifdef WOLFSSL_CALLBACKS
1241
1242
typedef struct itimerval Itimerval;
1243
1244
/* don't keep calling simple functions while setting up timer and signals
1245
   if no inlining these are the next best */
1246
1247
#define SubtractTimes(a, b, c)                  \
1248
    do {                                        \
1249
        (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
1250
        (c).tv_usec = (a).tv_usec - (b).tv_usec;\
1251
        if ((c).tv_usec < 0) {                  \
1252
            (c).tv_sec--;                       \
1253
            (c).tv_usec += 1000000;             \
1254
        }                                       \
1255
    } while (0)
1256
1257
#define CmpTimes(a, b, cmp)                     \
1258
    (((a).tv_sec  ==  (b).tv_sec) ?             \
1259
        ((a).tv_usec cmp (b).tv_usec) :         \
1260
        ((a).tv_sec  cmp (b).tv_sec))           \
1261
1262
1263
/* Signal handler that does nothing.
1264
 *
1265
 * Installed for SIGALRM so that the timer interrupts a blocking call rather
1266
 * than terminating the process.
1267
 *
1268
 * @param [in] signo  Signal number. Unused.
1269
 */
1270
static void myHandler(int signo)
1271
{
1272
    (void)signo;
1273
    return;
1274
}
1275
1276
1277
/* Replace any running timer with one that expires after the timeout.
1278
 *
1279
 * When a timer is already running and would expire first, the timeout is
1280
 * shortened to match it so the existing timer is not delayed.
1281
 *
1282
 * @param [in, out] timeout     Maximum time to take. Shortened when a timer
1283
 *                              already running would expire sooner.
1284
 * @param [out]     oldTimeout  Timer that was running, to be restored later.
1285
 * @param [out]     timerWasOn  Set to 1 when a timer was already running, 0
1286
 *                              when not.
1287
 * @param [out]     oact        Signal handler that was replaced.
1288
 * @return  0 on success.
1289
 * @return  SETITIMER_ERROR when the timer cannot be read or set.
1290
 * @return  SIGACT_ERROR when the signal handler cannot be installed.
1291
 */
1292
static int wolfssl_ex_wrapper_set_timer(WOLFSSL_TIMEVAL* timeout,
1293
    Itimerval* oldTimeout, int* timerWasOn, struct sigaction* oact)
1294
{
1295
    int ret = 0;
1296
    Itimerval myTimeout;
1297
    struct sigaction act;
1298
1299
    *timerWasOn = 0;
1300
1301
    /* use setitimer to simulate getitimer, init 0 myTimeout */
1302
    myTimeout.it_interval.tv_sec  = 0;
1303
    myTimeout.it_interval.tv_usec = 0;
1304
    myTimeout.it_value.tv_sec     = 0;
1305
    myTimeout.it_value.tv_usec    = 0;
1306
    if (setitimer(ITIMER_REAL, &myTimeout, oldTimeout) < 0) {
1307
        ret = SETITIMER_ERROR;
1308
    }
1309
1310
    if (ret == 0) {
1311
        if ((oldTimeout->it_value.tv_sec) ||
1312
                (oldTimeout->it_value.tv_usec)) {
1313
            *timerWasOn = 1;
1314
1315
            /* is old timer going to expire before ours */
1316
            if (CmpTimes(oldTimeout->it_value, *timeout, <)) {
1317
                timeout->tv_sec  = oldTimeout->it_value.tv_sec;
1318
                timeout->tv_usec = oldTimeout->it_value.tv_usec;
1319
            }
1320
        }
1321
        myTimeout.it_value.tv_sec  = timeout->tv_sec;
1322
        myTimeout.it_value.tv_usec = timeout->tv_usec;
1323
1324
        /* set up signal handler, don't restart socket send/recv */
1325
        act.sa_handler = myHandler;
1326
        sigemptyset(&act.sa_mask);
1327
        act.sa_flags = 0;
1328
        #ifdef SA_INTERRUPT
1329
        act.sa_flags |= SA_INTERRUPT;
1330
        #endif
1331
        if (sigaction(SIGALRM, &act, oact) < 0) {
1332
            ret = SIGACT_ERROR;
1333
        }
1334
    }
1335
1336
    if (ret == 0) {
1337
        if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0) {
1338
            ret = SETITIMER_ERROR;
1339
        }
1340
    }
1341
1342
    return ret;
1343
}
1344
1345
/* Restore the timer and signal handler that were replaced.
1346
 *
1347
 * A restored timer is adjusted for the time that has since elapsed.
1348
 *
1349
 * @param [in]      startTime   When the handshake started.
1350
 * @param [in]      endTime     When the handshake finished. Only read when
1351
 *                              oldTimerOn is set.
1352
 * @param [in, out] oldTimeout  Timer to restore.
1353
 * @param [in]      oldTimerOn  Whether a timer was already running.
1354
 * @param [in]      oact        Signal handler to restore.
1355
 * @return  0 on success.
1356
 * @return  SIGACT_ERROR when the signal handler cannot be restored.
1357
 * @return  SETITIMER_ERROR when the timer cannot be restored.
1358
 */
1359
static int wolfssl_ex_wrapper_reset_timer(const WOLFSSL_TIMEVAL* startTime,
1360
    const WOLFSSL_TIMEVAL* endTime, Itimerval* oldTimeout, int oldTimerOn,
1361
    struct sigaction* oact)
1362
{
1363
    int ret = 0;
1364
    WOLFSSL_TIMEVAL totalTime;
1365
1366
    if (oldTimerOn) {
1367
        SubtractTimes(*endTime, *startTime, totalTime);
1368
        /* adjust old timer for elapsed time */
1369
        if (CmpTimes(totalTime, oldTimeout->it_value, <)) {
1370
            SubtractTimes(oldTimeout->it_value, totalTime,
1371
                          oldTimeout->it_value);
1372
        }
1373
        else {
1374
            /* reset value to interval, may be off */
1375
            oldTimeout->it_value.tv_sec = oldTimeout->it_interval.tv_sec;
1376
            oldTimeout->it_value.tv_usec = oldTimeout->it_interval.tv_usec;
1377
        }
1378
    /* keep iter the same whether there or not */
1379
    }
1380
1381
    /* restore old handler */
1382
    if (sigaction(SIGALRM, oact, 0) < 0) {
1383
        ret = SIGACT_ERROR;    /* more pressing error, stomp */
1384
    }
1385
    else {
1386
        /* use old settings which may turn off (expired or not there) */
1387
        if (setitimer(ITIMER_REAL, oldTimeout, 0) < 0) {
1388
            ret = SETITIMER_ERROR;
1389
        }
1390
    }
1391
1392
    return ret;
1393
}
1394
1395
/* Perform a handshake with monitoring callbacks and a timeout.
1396
 *
1397
 * An interval timer is used to abort the handshake when it takes longer
1398
 * than the timeout. Any existing timer is restored afterwards.
1399
 *
1400
 * @param [in, out] ssl      SSL/TLS object.
1401
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1402
 * @param [in]      toCb     Timeout callback. May be NULL.
1403
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1404
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1405
 * @return  WOLFSSL_FATAL_ERROR when ssl is NULL, the timeout value is bad,
1406
 *          setting the timer fails or the handshake fails.
1407
 */
1408
static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
1409
                             TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1410
{
1411
    int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
1412
    int       oldTimerOn = 0;   /* was timer already on */
1413
    WOLFSSL_TIMEVAL startTime;
1414
    /* Only filled in, and only read, when a timer was already running. Zeroed
1415
     * so the helper is never handed uninitialized storage. */
1416
    WOLFSSL_TIMEVAL endTime;
1417
    Itimerval oldTimeout; /* if old timer adjust from total time to reset */
1418
    struct sigaction oact;
1419
1420
#define ERR_OUT(x) \
1421
    do { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; } while (0)
1422
1423
    XMEMSET(&endTime, 0, sizeof(endTime));
1424
1425
    if (hsCb) {
1426
        ssl->hsInfoOn = 1;
1427
        InitHandShakeInfo(&ssl->handShakeInfo, ssl);
1428
    }
1429
    if (toCb) {
1430
        /* Kept out of ret so the fatal default survives to the dispatch
1431
         * below, which leaves ret alone when no side has been established. */
1432
        int sret;
1433
1434
        ssl->toInfoOn = 1;
1435
        InitTimeoutInfo(&ssl->timeoutInfo);
1436
1437
        if (gettimeofday(&startTime, 0) < 0) {
1438
            ERR_OUT(GETTIME_ERROR);
1439
        }
1440
1441
        sret = wolfssl_ex_wrapper_set_timer(&timeout, &oldTimeout,
1442
            &oldTimerOn, &oact);
1443
        if (sret != 0) {
1444
            ERR_OUT(sret);
1445
        }
1446
    }
1447
1448
    /* do main work */
1449
    #ifndef NO_WOLFSSL_CLIENT
1450
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1451
        ret = wolfSSL_connect(ssl);
1452
    }
1453
    #endif
1454
    #ifndef NO_WOLFSSL_SERVER
1455
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1456
        ret = wolfSSL_accept(ssl);
1457
    }
1458
    #endif
1459
1460
    /* do callbacks */
1461
    if (toCb) {
1462
        int tret;
1463
1464
        if (oldTimerOn) {
1465
            if (gettimeofday(&endTime, 0) < 0) {
1466
                ERR_OUT(SYSLIB_FAILED_E);
1467
            }
1468
        }
1469
1470
        tret = wolfssl_ex_wrapper_reset_timer(&startTime, &endTime,
1471
            &oldTimeout, oldTimerOn, &oact);
1472
        if (tret != 0) {
1473
            ret = tret;    /* more pressing error, stomp */
1474
        }
1475
1476
        /* if we had a timeout call callback */
1477
        if (ssl->timeoutInfo.timeoutName[0]) {
1478
            ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
1479
            ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
1480
            (toCb)(&ssl->timeoutInfo);
1481
        }
1482
        ssl->toInfoOn = 0;
1483
    }
1484
1485
    /* clean up buffers allocated by AddPacketInfo */
1486
    FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
1487
1488
    if (hsCb) {
1489
        FinishHandShakeInfo(&ssl->handShakeInfo);
1490
        (hsCb)(&ssl->handShakeInfo);
1491
        ssl->hsInfoOn = 0;
1492
    }
1493
    return ret;
1494
}
1495
1496
1497
#ifndef NO_WOLFSSL_CLIENT
1498
1499
/* Connect to a server with monitoring callbacks and a timeout.
1500
 *
1501
 * @param [in, out] ssl      SSL/TLS object.
1502
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1503
 * @param [in]      toCb     Timeout callback. May be NULL.
1504
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1505
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1506
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails or times out.
1507
 */
1508
int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
1509
                      TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1510
{
1511
    WOLFSSL_ENTER("wolfSSL_connect_ex");
1512
    return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
1513
}
1514
1515
#endif
1516
1517
1518
#ifndef NO_WOLFSSL_SERVER
1519
1520
/* Accept a connection from a client with monitoring callbacks and a
1521
 * timeout.
1522
 *
1523
 * @param [in, out] ssl      SSL/TLS object.
1524
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1525
 * @param [in]      toCb     Timeout callback. May be NULL.
1526
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1527
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1528
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails or times out.
1529
 */
1530
int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
1531
                     TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1532
{
1533
    WOLFSSL_ENTER("wolfSSL_accept_ex");
1534
    return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
1535
}
1536
1537
#endif
1538
1539
/* Local to this file, which is compiled into ssl.c, so do not leave them
1540
 * defined for the files included after it. */
1541
#undef ERR_OUT
1542
#undef SubtractTimes
1543
#undef CmpTimes
1544
1545
#endif /* WOLFSSL_CALLBACKS */
1546
1547
1548
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
1549
    defined(WOLFSSL_WPAS_SMALL)
1550
1551
/* Set the SSL/TLS object to be a server.
1552
 *
1553
 * Resets the handshake state and cipher suites. Must be called before the
1554
 * handshake starts.
1555
 *
1556
 * @param [in, out] ssl  SSL/TLS object.
1557
 */
1558
void wolfSSL_set_accept_state(WOLFSSL* ssl)
1559
{
1560
    WOLFSSL_ENTER("wolfSSL_set_accept_state");
1561
1562
    if (ssl == NULL) {
1563
        return;
1564
    }
1565
1566
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1567
        #ifdef HAVE_ECC
1568
        WC_DECLARE_VAR(key, ecc_key, 1, 0);
1569
        word32 idx = 0;
1570
1571
        #ifdef WOLFSSL_SMALL_STACK
1572
        key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
1573
                                DYNAMIC_TYPE_ECC);
1574
        if (key == NULL) {
1575
            WOLFSSL_MSG("Error allocating memory for ecc_key");
1576
        }
1577
        #endif
1578
        if ((ssl->options.haveStaticECC) && (ssl->buffers.key != NULL)) {
1579
            if (wc_ecc_init(key) >= 0) {
1580
                DerBuffer* privKey = ssl->buffers.key;
1581
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
1582
                DerBuffer* unblinded = NULL;
1583
1584
                /* Only a key that has a mask is masked. Without one - after
1585
                 * wolfSSL_use_PrivateKey_Id(), for example - the buffer is
1586
                 * stored as-is and is used directly, so that this build
1587
                 * behaves the same as one without key blinding. */
1588
                if (ssl->buffers.keyMask != NULL) {
1589
                    /* The stored key is masked, so work on a plain copy. */
1590
                    unblinded = wolfssl_priv_der_unblind(ssl->buffers.key,
1591
                        ssl->buffers.keyMask);
1592
                    privKey = unblinded;
1593
                }
1594
                #endif
1595
1596
                if (privKey == NULL) {
1597
                    /* Only an allocation failure gets here, and that says
1598
                     * nothing about the key. Leave the capabilities as they
1599
                     * are rather than withdraw them, which is also what a
1600
                     * failure to allocate the ecc_key above does - that skips
1601
                     * the check entirely. */
1602
                    WOLFSSL_MSG("Unable to unmask private key");
1603
                }
1604
                /* Not an EC key, so withdraw the ECC capabilities. */
1605
                else if (wc_EccPrivateKeyDecode(privKey->buffer, &idx, key,
1606
                        privKey->length) != 0) {
1607
                    ssl->options.haveECDSAsig = 0;
1608
                    ssl->options.haveECC = 0;
1609
                    ssl->options.haveStaticECC = 0;
1610
                }
1611
1612
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
1613
                /* Only the plain copy is disposed of - the stored key is
1614
                 * not ours to free. */
1615
                wolfssl_priv_der_unblind_free(unblinded);
1616
                #endif
1617
                wc_ecc_free(key);
1618
            }
1619
        }
1620
        WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
1621
        #endif
1622
1623
        #ifndef NO_DH
1624
        if ((!ssl->options.haveDH) && (ssl->ctx->haveDH)) {
1625
            /* Nothing to return the failure through, so leave the object
1626
             * without DH rather than claim parameters it does not have. */
1627
            if (CopySSL_CTX_DhParams(ssl, ssl->ctx) == 0) {
1628
                ssl->options.haveDH = 1;
1629
            }
1630
            else {
1631
                WOLFSSL_MSG("Unable to copy DH parameters from context");
1632
            }
1633
        }
1634
        #endif
1635
    }
1636
1637
    if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
1638
        WOLFSSL_MSG("Error initializing server side");
1639
    }
1640
}
1641
1642
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
1643
1644
/* Determine whether the handshake has completed.
1645
 *
1646
 * Works for both TLS and DTLS.
1647
 *
1648
 * @param [in] ssl  SSL/TLS object.
1649
 * @return  1 when the handshake has completed.
1650
 * @return  0 when the handshake has not completed or ssl is NULL.
1651
 */
1652
int wolfSSL_is_init_finished(const WOLFSSL* ssl)
1653
0
{
1654
0
    int ret = 0;
1655
1656
0
    if (ssl != NULL) {
1657
        #if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
1658
        if ((ssl->options.side == WOLFSSL_CLIENT_END) && (ssl->options.dtls)
1659
                && (IsAtLeastTLSv1_3(ssl->version))) {
1660
            ret = (ssl->options.serverState == SERVER_FINISHED_ACKED);
1661
        }
1662
        else
1663
        #endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT */
1664
0
        #if defined(WOLFSSL_TLS13) && !defined(NO_WOLFSSL_CLIENT)
1665
0
        if ((ssl->options.side == WOLFSSL_CLIENT_END) && (!ssl->options.dtls)
1666
0
                && (IsAtLeastTLSv1_3(ssl->version))) {
1667
            /* handShakeState is set before the Finished is flushed,
1668
             * so only connectState tells us if the record actually went out. */
1669
0
            ret = (ssl->options.handShakeState == HANDSHAKE_DONE) &&
1670
0
                  (ssl->options.connectState >= FINISHED_DONE);
1671
0
        }
1672
0
        else
1673
0
        #endif /* WOLFSSL_TLS13 && !NO_WOLFSSL_CLIENT */
1674
0
        {
1675
            /* Can't use ssl->options.connectState and ssl->options.acceptState
1676
             * because they differ in meaning for TLS <=1.2 and 1.3 */
1677
0
            if (ssl->options.handShakeState == HANDSHAKE_DONE) {
1678
0
                ret = 1;
1679
0
            }
1680
0
        }
1681
0
    }
1682
1683
0
    return ret;
1684
0
}
1685
1686
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
1687
/* Set the SSL/TLS object to be a client.
1688
 *
1689
 * Resets the handshake state and cipher suites. Must be called before the
1690
 * handshake starts.
1691
 *
1692
 * @param [in, out] ssl  SSL/TLS object.
1693
 */
1694
void wolfSSL_set_connect_state(WOLFSSL* ssl)
1695
{
1696
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
1697
    if (ssl == NULL) {
1698
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
1699
        return;
1700
    }
1701
1702
    #ifndef NO_DH
1703
    /* client creates its own DH parameters on handshake */
1704
    if ((ssl->buffers.serverDH_P.buffer != NULL) &&
1705
            (ssl->buffers.weOwnDH)) {
1706
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
1707
            DYNAMIC_TYPE_PUBLIC_KEY);
1708
    }
1709
    ssl->buffers.serverDH_P.buffer = NULL;
1710
    if ((ssl->buffers.serverDH_G.buffer != NULL) &&
1711
            (ssl->buffers.weOwnDH)) {
1712
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
1713
            DYNAMIC_TYPE_PUBLIC_KEY);
1714
    }
1715
    ssl->buffers.serverDH_G.buffer = NULL;
1716
    #endif
1717
1718
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
1719
        WOLFSSL_MSG("Error initializing client side");
1720
    }
1721
}
1722
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
1723
1724
#ifdef OPENSSL_EXTRA
1725
1726
#define STATE_STRINGS_PROTO(s) \
1727
    {                          \
1728
        {"SSLv3 " s,           \
1729
         "SSLv3 " s,           \
1730
         "SSLv3 " s},          \
1731
        {"TLSv1 " s,           \
1732
         "TLSv1 " s,           \
1733
         "TLSv1 " s},          \
1734
        {"TLSv1_1 " s,         \
1735
         "TLSv1_1 " s,         \
1736
         "TLSv1_1 " s},        \
1737
        {"TLSv1_2 " s,         \
1738
         "TLSv1_2 " s,         \
1739
         "TLSv1_2 " s},        \
1740
        {"TLSv1_3 " s,         \
1741
         "TLSv1_3 " s,         \
1742
         "TLSv1_3 " s},        \
1743
        {"DTLSv1 " s,          \
1744
         "DTLSv1 " s,          \
1745
         "DTLSv1 " s},         \
1746
        {"DTLSv1_2 " s,        \
1747
         "DTLSv1_2 " s,        \
1748
         "DTLSv1_2 " s},       \
1749
        {"DTLSv1_3 " s,        \
1750
         "DTLSv1_3 " s,        \
1751
         "DTLSv1_3 " s},       \
1752
    }
1753
1754
#define STATE_STRINGS_PROTO_RW(s) \
1755
    {                             \
1756
        {"SSLv3 read " s,         \
1757
         "SSLv3 write " s,        \
1758
         "SSLv3 " s},             \
1759
        {"TLSv1 read " s,         \
1760
         "TLSv1 write " s,        \
1761
         "TLSv1 " s},             \
1762
        {"TLSv1_1 read " s,       \
1763
         "TLSv1_1 write " s,      \
1764
         "TLSv1_1 " s},           \
1765
        {"TLSv1_2 read " s,       \
1766
         "TLSv1_2 write " s,      \
1767
         "TLSv1_2 " s},           \
1768
        {"TLSv1_3 read " s,       \
1769
         "TLSv1_3 write " s,      \
1770
         "TLSv1_3 " s},           \
1771
        {"DTLSv1 read " s,        \
1772
         "DTLSv1 write " s,       \
1773
         "DTLSv1 " s},            \
1774
        {"DTLSv1_2 read " s,      \
1775
         "DTLSv1_2 write " s,     \
1776
         "DTLSv1_2 " s},          \
1777
        {"DTLSv1_3 read " s,      \
1778
         "DTLSv1_3 write " s,     \
1779
         "DTLSv1_3 " s},          \
1780
    }
1781
1782
/* Indices into OUTPUT_STR in wolfSSL_state_string_long().
1783
 *
1784
 * These are shared by that function and its helpers below, so they cannot be
1785
 * local to any one of them. This file is compiled as part of ssl.c, which
1786
 * makes them visible to every other file included into it, hence the
1787
 * WOLFSSL_SS_ ("state string") prefix on the enumerators, whose names would
1788
 * otherwise be far too generic to sit in that namespace. The enum tags
1789
 * follow the naming of those in wolfssl/ssl.h.
1790
 */
1791
enum StateStringProtocol {
1792
    WOLFSSL_SS_SSL_V3 = 0,
1793
    WOLFSSL_SS_TLS_V1,
1794
    WOLFSSL_SS_TLS_V1_1,
1795
    WOLFSSL_SS_TLS_V1_2,
1796
    WOLFSSL_SS_TLS_V1_3,
1797
    WOLFSSL_SS_DTLS_V1,
1798
    WOLFSSL_SS_DTLS_V1_2,
1799
    WOLFSSL_SS_DTLS_V1_3,
1800
    /* Number of protocols above - the second dimension of OUTPUT_STR in
1801
     * wolfSSL_state_string_long(). Keep last of the indices. */
1802
    WOLFSSL_SS_PROTO_CNT,
1803
    WOLFSSL_SS_UNKNOWN = 100
1804
};
1805
1806
enum StateStringIoMode {
1807
    WOLFSSL_SS_READ = 0,
1808
    WOLFSSL_SS_WRITE,
1809
    WOLFSSL_SS_NEITHER,
1810
    /* Number of modes above - the third dimension of OUTPUT_STR. */
1811
    WOLFSSL_SS_IO_CNT
1812
};
1813
1814
enum StateStringState {
1815
    WOLFSSL_SS_NULL_STATE = 0,
1816
    WOLFSSL_SS_SERVER_HELLOREQUEST,
1817
    WOLFSSL_SS_SERVER_HELLOVERIFY,
1818
    WOLFSSL_SS_SERVER_HELLORETRYREQUEST,
1819
    WOLFSSL_SS_SERVER_HELLO,
1820
    WOLFSSL_SS_SERVER_CERTIFICATESTATUS,
1821
    WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS,
1822
    WOLFSSL_SS_SERVER_SESSIONTICKET,
1823
    WOLFSSL_SS_SERVER_CERTREQUEST,
1824
    WOLFSSL_SS_SERVER_CERT,
1825
    WOLFSSL_SS_SERVER_KEYEXCHANGE,
1826
    WOLFSSL_SS_SERVER_HELLODONE,
1827
    WOLFSSL_SS_SERVER_CHANGECIPHERSPEC,
1828
    WOLFSSL_SS_SERVER_FINISHED,
1829
    WOLFSSL_SS_SERVER_KEYUPDATE,
1830
    WOLFSSL_SS_CLIENT_HELLO,
1831
    WOLFSSL_SS_CLIENT_KEYEXCHANGE,
1832
    WOLFSSL_SS_CLIENT_CERT,
1833
    WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC,
1834
    WOLFSSL_SS_CLIENT_CERTVERIFY,
1835
    WOLFSSL_SS_CLIENT_ENDOFEARLYDATA,
1836
    WOLFSSL_SS_CLIENT_FINISHED,
1837
    WOLFSSL_SS_CLIENT_KEYUPDATE,
1838
    WOLFSSL_SS_HANDSHAKE_DONE,
1839
    /* Number of states above - the first dimension of OUTPUT_STR. Each state
1840
     * indexes a row of that table, so the two must stay the same size. */
1841
    WOLFSSL_SS_STATE_CNT
1842
};
1843
1844
/* Determine which direction the last handshake message travelled.
1845
 *
1846
 * @param [in] ssl  SSL/TLS object.
1847
 * @return  WOLFSSL_SS_READ when the last message was read.
1848
 * @return  WOLFSSL_SS_WRITE when the last message was written.
1849
 * @return  WOLFSSL_SS_NEITHER when no message has been read or written.
1850
 */
1851
static int wolfssl_state_string_io_mode(const WOLFSSL* ssl)
1852
{
1853
    int cbmode = WOLFSSL_SS_NEITHER;
1854
1855
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
1856
        cbmode = WOLFSSL_SS_WRITE;
1857
    }
1858
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
1859
        cbmode = WOLFSSL_SS_READ;
1860
    }
1861
1862
    return cbmode;
1863
}
1864
1865
/* Determine the protocol version in use.
1866
 *
1867
 * @param [in] ssl  SSL/TLS object.
1868
 * @return  Index of the protocol version in the state string table.
1869
 * @return  WOLFSSL_SS_UNKNOWN when the version is not recognized.
1870
 */
1871
static int wolfssl_state_string_protocol(const WOLFSSL* ssl)
1872
{
1873
    int protocol = WOLFSSL_SS_UNKNOWN;
1874
1875
    switch (ssl->version.major) {
1876
    case SSLv3_MAJOR:
1877
        switch (ssl->version.minor) {
1878
        case SSLv3_MINOR:
1879
            protocol = WOLFSSL_SS_SSL_V3;
1880
            break;
1881
        case TLSv1_MINOR:
1882
            protocol = WOLFSSL_SS_TLS_V1;
1883
            break;
1884
        case TLSv1_1_MINOR:
1885
            protocol = WOLFSSL_SS_TLS_V1_1;
1886
            break;
1887
        case TLSv1_2_MINOR:
1888
            protocol = WOLFSSL_SS_TLS_V1_2;
1889
            break;
1890
        case TLSv1_3_MINOR:
1891
            protocol = WOLFSSL_SS_TLS_V1_3;
1892
            break;
1893
        default:
1894
            protocol = WOLFSSL_SS_UNKNOWN;
1895
        }
1896
        break;
1897
    case DTLS_MAJOR:
1898
        switch (ssl->version.minor) {
1899
        case DTLS_MINOR:
1900
            protocol = WOLFSSL_SS_DTLS_V1;
1901
            break;
1902
        case DTLSv1_2_MINOR:
1903
            protocol = WOLFSSL_SS_DTLS_V1_2;
1904
            break;
1905
        case DTLSv1_3_MINOR:
1906
            protocol = WOLFSSL_SS_DTLS_V1_3;
1907
            break;
1908
        default:
1909
            protocol = WOLFSSL_SS_UNKNOWN;
1910
        }
1911
        break;
1912
    default:
1913
        protocol = WOLFSSL_SS_UNKNOWN;
1914
    }
1915
1916
    return protocol;
1917
}
1918
1919
/* Map the type of the last message read to a state string table index.
1920
 *
1921
 * @param [in] ssl  SSL/TLS object.
1922
 * @return  Index of the message in the state string table.
1923
 * @return  WOLFSSL_SS_NULL_STATE when the message type is not recognized.
1924
 */
1925
static int wolfssl_state_string_recv_state(const WOLFSSL* ssl)
1926
{
1927
    int state = ssl->cbtype;
1928
1929
    switch (state) {
1930
    case hello_request:
1931
        state = WOLFSSL_SS_SERVER_HELLOREQUEST;
1932
        break;
1933
    case client_hello:
1934
        state = WOLFSSL_SS_CLIENT_HELLO;
1935
        break;
1936
    case server_hello:
1937
        state = WOLFSSL_SS_SERVER_HELLO;
1938
        break;
1939
    case hello_verify_request:
1940
        state = WOLFSSL_SS_SERVER_HELLOVERIFY;
1941
        break;
1942
    case session_ticket:
1943
        state = WOLFSSL_SS_SERVER_SESSIONTICKET;
1944
        break;
1945
    case end_of_early_data:
1946
        state = WOLFSSL_SS_CLIENT_ENDOFEARLYDATA;
1947
        break;
1948
    case hello_retry_request:
1949
        state = WOLFSSL_SS_SERVER_HELLORETRYREQUEST;
1950
        break;
1951
    case encrypted_extensions:
1952
        state = WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS;
1953
        break;
1954
    case certificate:
1955
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1956
            state = WOLFSSL_SS_CLIENT_CERT;
1957
        }
1958
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1959
            state = WOLFSSL_SS_SERVER_CERT;
1960
        }
1961
        else {
1962
            WOLFSSL_MSG("Unknown State");
1963
            state = WOLFSSL_SS_NULL_STATE;
1964
        }
1965
        break;
1966
    case server_key_exchange:
1967
        state = WOLFSSL_SS_SERVER_KEYEXCHANGE;
1968
        break;
1969
    case certificate_request:
1970
        state = WOLFSSL_SS_SERVER_CERTREQUEST;
1971
        break;
1972
    case server_hello_done:
1973
        state = WOLFSSL_SS_SERVER_HELLODONE;
1974
        break;
1975
    case certificate_verify:
1976
        state = WOLFSSL_SS_CLIENT_CERTVERIFY;
1977
        break;
1978
    case client_key_exchange:
1979
        state = WOLFSSL_SS_CLIENT_KEYEXCHANGE;
1980
        break;
1981
    case finished:
1982
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1983
            state = WOLFSSL_SS_CLIENT_FINISHED;
1984
        }
1985
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1986
            state = WOLFSSL_SS_SERVER_FINISHED;
1987
        }
1988
        else {
1989
            WOLFSSL_MSG("Unknown State");
1990
            state = WOLFSSL_SS_NULL_STATE;
1991
        }
1992
        break;
1993
    case certificate_status:
1994
        state = WOLFSSL_SS_SERVER_CERTIFICATESTATUS;
1995
        break;
1996
    case key_update:
1997
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1998
            state = WOLFSSL_SS_CLIENT_KEYUPDATE;
1999
        }
2000
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
2001
            state = WOLFSSL_SS_SERVER_KEYUPDATE;
2002
        }
2003
        else {
2004
            WOLFSSL_MSG("Unknown State");
2005
            state = WOLFSSL_SS_NULL_STATE;
2006
        }
2007
        break;
2008
    case change_cipher_hs:
2009
        if (ssl->options.side == WOLFSSL_SERVER_END) {
2010
            state = WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC;
2011
        }
2012
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
2013
            state = WOLFSSL_SS_SERVER_CHANGECIPHERSPEC;
2014
        }
2015
        else {
2016
            WOLFSSL_MSG("Unknown State");
2017
            state = WOLFSSL_SS_NULL_STATE;
2018
        }
2019
        break;
2020
    default:
2021
        WOLFSSL_MSG("Unknown State");
2022
        state = WOLFSSL_SS_NULL_STATE;
2023
    }
2024
2025
    return state;
2026
}
2027
2028
/* Map the handshake state reached while sending to a state string table index.
2029
 *
2030
 * @param [in] ssl  SSL/TLS object.
2031
 * @return  Index of the message in the state string table.
2032
 * @return  WOLFSSL_SS_NULL_STATE when the state is not recognized.
2033
 */
2034
static int wolfssl_state_string_send_state(const WOLFSSL* ssl)
2035
{
2036
    int state;
2037
2038
    if (ssl->options.side == WOLFSSL_SERVER_END) {
2039
        state = ssl->options.serverState;
2040
    }
2041
    else {
2042
        state = ssl->options.clientState;
2043
    }
2044
2045
    switch (state) {
2046
    case SERVER_HELLOVERIFYREQUEST_COMPLETE:
2047
        state = WOLFSSL_SS_SERVER_HELLOVERIFY;
2048
        break;
2049
    case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
2050
        state = WOLFSSL_SS_SERVER_HELLORETRYREQUEST;
2051
        break;
2052
    case SERVER_HELLO_COMPLETE:
2053
        state = WOLFSSL_SS_SERVER_HELLO;
2054
        break;
2055
    case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
2056
        state = WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS;
2057
        break;
2058
    case SERVER_CERT_COMPLETE:
2059
        state = WOLFSSL_SS_SERVER_CERT;
2060
        break;
2061
    case SERVER_KEYEXCHANGE_COMPLETE:
2062
        state = WOLFSSL_SS_SERVER_KEYEXCHANGE;
2063
        break;
2064
    case SERVER_HELLODONE_COMPLETE:
2065
        state = WOLFSSL_SS_SERVER_HELLODONE;
2066
        break;
2067
    case SERVER_CHANGECIPHERSPEC_COMPLETE:
2068
        state = WOLFSSL_SS_SERVER_CHANGECIPHERSPEC;
2069
        break;
2070
    case SERVER_FINISHED_COMPLETE:
2071
        state = WOLFSSL_SS_SERVER_FINISHED;
2072
        break;
2073
    case CLIENT_HELLO_RETRY:
2074
    case CLIENT_HELLO_COMPLETE:
2075
        state = WOLFSSL_SS_CLIENT_HELLO;
2076
        break;
2077
    case CLIENT_KEYEXCHANGE_COMPLETE:
2078
        state = WOLFSSL_SS_CLIENT_KEYEXCHANGE;
2079
        break;
2080
    case CLIENT_CHANGECIPHERSPEC_COMPLETE:
2081
        state = WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC;
2082
        break;
2083
    case CLIENT_FINISHED_COMPLETE:
2084
        state = WOLFSSL_SS_CLIENT_FINISHED;
2085
        break;
2086
    case HANDSHAKE_DONE:
2087
        state = WOLFSSL_SS_HANDSHAKE_DONE;
2088
        break;
2089
    default:
2090
        WOLFSSL_MSG("Unknown State");
2091
        state = WOLFSSL_SS_NULL_STATE;
2092
    }
2093
2094
    return state;
2095
}
2096
2097
/* Get a human readable description of the current handshake state.
2098
 *
2099
 * The description names the protocol version, whether the last message was
2100
 * read or written, and the message itself.
2101
 *
2102
 * @param [in] ssl  SSL/TLS object.
2103
 * @return  A human readable string describing the state.
2104
 * @return  An empty string when the protocol version is not one this can
2105
 *          name, so the result is always safe to print.
2106
 * @return  NULL when ssl is NULL. That is the only case that returns NULL.
2107
 */
2108
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
2109
{
2110
    static const char* OUTPUT_STR[24][8][3] = {
2111
        STATE_STRINGS_PROTO("Initialization"),
2112
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
2113
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
2114
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
2115
        STATE_STRINGS_PROTO_RW("Server Hello"),
2116
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
2117
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
2118
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
2119
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
2120
        STATE_STRINGS_PROTO_RW("Server Cert"),
2121
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
2122
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
2123
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
2124
        STATE_STRINGS_PROTO_RW("Server Finished"),
2125
        STATE_STRINGS_PROTO_RW("server Key Update"),
2126
        STATE_STRINGS_PROTO_RW("Client Hello"),
2127
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
2128
        STATE_STRINGS_PROTO_RW("Client Cert"),
2129
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
2130
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
2131
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
2132
        STATE_STRINGS_PROTO_RW("Client Finished"),
2133
        STATE_STRINGS_PROTO_RW("Client Key Update"),
2134
        STATE_STRINGS_PROTO("Handshake Done"),
2135
    };
2136
    int protocol;
2137
    int cbmode;
2138
    int state;
2139
    const char* ret = NULL;
2140
2141
    /* The three indices below come from enumerations declared at the top of
2142
     * this file, well away from the table they index. Adding an entry to one
2143
     * of them without adding the matching entry here is a build error rather
2144
     * than a read off the end of the table. */
2145
    wc_static_assert(XELEM_CNT(OUTPUT_STR) == WOLFSSL_SS_STATE_CNT);
2146
    wc_static_assert(XELEM_CNT(OUTPUT_STR[0]) == WOLFSSL_SS_PROTO_CNT);
2147
    wc_static_assert(XELEM_CNT(OUTPUT_STR[0][0]) == WOLFSSL_SS_IO_CNT);
2148
2149
    WOLFSSL_ENTER("wolfSSL_state_string_long");
2150
2151
    if (ssl == NULL) {
2152
        WOLFSSL_MSG("Null argument passed in");
2153
    }
2154
    else {
2155
        cbmode = wolfssl_state_string_io_mode(ssl);
2156
        protocol = wolfssl_state_string_protocol(ssl);
2157
2158
        if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
2159
            state = wolfssl_state_string_recv_state(ssl);
2160
        }
2161
        else {
2162
            state = wolfssl_state_string_send_state(ssl);
2163
        }
2164
2165
        if (protocol == WOLFSSL_SS_UNKNOWN) {
2166
            WOLFSSL_MSG("Unknown protocol");
2167
            ret = "";
2168
        }
2169
        else {
2170
            ret = OUTPUT_STR[state][protocol][cbmode];
2171
        }
2172
    }
2173
2174
    return ret;
2175
}
2176
2177
/* Only used by the table above, and this file is compiled into ssl.c,
2178
 * so do not leave them defined for the files included after it. */
2179
#undef STATE_STRINGS_PROTO
2180
#undef STATE_STRINGS_PROTO_RW
2181
#endif /* OPENSSL_EXTRA */
2182
2183
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
2184
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
2185
2186
#ifndef NO_TLS
2187
/* Perform the handshake.
2188
 *
2189
 * Calls the connect or accept for the side of the object.
2190
 *
2191
 * @param [in, out] s  SSL/TLS object.
2192
 * @return  WOLFSSL_SUCCESS when the handshake completes.
2193
 * @return  WOLFSSL_FATAL_ERROR when the side is not set or the handshake
2194
 *          fails.
2195
 */
2196
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
2197
{
2198
    int ret;
2199
2200
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
2201
2202
    if (s == NULL) {
2203
        ret = WOLFSSL_FAILURE;
2204
    }
2205
    else if (s->options.side == WOLFSSL_CLIENT_END) {
2206
        #ifndef NO_WOLFSSL_CLIENT
2207
        ret = wolfSSL_connect(s);
2208
        #else
2209
        WOLFSSL_MSG("Client not compiled in");
2210
        ret = WOLFSSL_FAILURE;
2211
        #endif
2212
    }
2213
    else {
2214
        #ifndef NO_WOLFSSL_SERVER
2215
        ret = wolfSSL_accept(s);
2216
        #else
2217
        WOLFSSL_MSG("Server not compiled in");
2218
        ret = WOLFSSL_FAILURE;
2219
        #endif
2220
    }
2221
2222
    return ret;
2223
}
2224
2225
/* Perform the handshake.
2226
 *
2227
 * @param [in, out] s  SSL/TLS object.
2228
 * @return  WOLFSSL_SUCCESS when the handshake completes.
2229
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails. Call
2230
 *          wolfSSL_get_error() for the reason.
2231
 */
2232
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
2233
{
2234
    int ret;
2235
2236
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
2237
2238
    #ifdef WOLFSSL_QUIC
2239
    if (WOLFSSL_IS_QUIC(s)) {
2240
        ret = wolfSSL_quic_do_handshake(s);
2241
    }
2242
    else
2243
    #endif
2244
    {
2245
        ret = wolfSSL_SSL_do_handshake_internal(s);
2246
    }
2247
2248
    return ret;
2249
}
2250
#endif /* !NO_TLS */
2251
2252
/* Determine whether the handshake has not completed.
2253
 *
2254
 * @param [in] ssl  SSL/TLS object.
2255
 * @return  1 when the handshake has not completed.
2256
 * @return  0 when the handshake has completed.
2257
 */
2258
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
2259
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
2260
#else
2261
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
2262
#endif
2263
{
2264
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
2265
2266
    return !wolfSSL_is_init_finished(ssl);
2267
}
2268
2269
/* Determine whether the handshake has not started.
2270
 *
2271
 * @param [in] ssl  SSL/TLS object.
2272
 * @return  1 when the handshake has not started.
2273
 * @return  0 when the handshake has started or ssl is NULL.
2274
 */
2275
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
2276
{
2277
    int ret;
2278
2279
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
2280
2281
    if (ssl != NULL) {
2282
        ret = (ssl->options.handShakeState == NULL_STATE);
2283
    }
2284
    else {
2285
        ret = WOLFSSL_FAILURE;
2286
    }
2287
2288
    return ret;
2289
}
2290
2291
/* Determine whether the handshake is in progress.
2292
 *
2293
 * @param [in] ssl  SSL/TLS object.
2294
 * @return  1 when the handshake has started but not completed.
2295
 * @return  0 otherwise or when ssl is NULL.
2296
 */
2297
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
2298
{
2299
    int ret;
2300
2301
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
2302
2303
    if (ssl != NULL) {
2304
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
2305
            ret = (ssl->options.connectState > CONNECT_BEGIN) &&
2306
                  (ssl->options.connectState < SECOND_REPLY_DONE);
2307
        }
2308
        else {
2309
            ret = (ssl->options.acceptState > ACCEPT_BEGIN) &&
2310
                  (ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE);
2311
        }
2312
    }
2313
    else {
2314
        ret = WOLFSSL_FAILURE;
2315
    }
2316
2317
    return ret;
2318
}
2319
2320
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
2321
    OPENSSL_EXTRA || HAVE_LIGHTY */
2322
2323
2324
#ifndef NO_CERTS
2325
#ifdef  HAVE_PK_CALLBACKS
2326
2327
/* Set the premaster secret generation callback.
2328
 *
2329
 * @param [in, out] ctx  SSL/TLS CTX object.
2330
 * @param [in]      cb   Callback to call. NULL to clear.
2331
 */
2332
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
2333
{
2334
    if (ctx != NULL) {
2335
        ctx->GenPreMasterCb = cb;
2336
    }
2337
}
2338
/* Set the context to pass to the premaster secret generation callback.
2339
 *
2340
 * @param [in, out] ssl  SSL/TLS object.
2341
 * @param [in]      ctx  Context to pass to the callback.
2342
 */
2343
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
2344
{
2345
    if (ssl != NULL) {
2346
        ssl->GenPreMasterCtx = ctx;
2347
    }
2348
}
2349
/* Get the context passed to the premaster secret generation callback.
2350
 *
2351
 * @param [in] ssl  SSL/TLS object.
2352
 * @return  Context on success.
2353
 * @return  NULL when ssl is NULL.
2354
 */
2355
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
2356
{
2357
    void* ret = NULL;
2358
2359
    if (ssl != NULL) {
2360
        ret = ssl->GenPreMasterCtx;
2361
    }
2362
2363
    return ret;
2364
}
2365
2366
/* Set the master secret generation callback.
2367
 *
2368
 * @param [in, out] ctx  SSL/TLS CTX object.
2369
 * @param [in]      cb   Callback to call. NULL to clear.
2370
 */
2371
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
2372
    CallbackGenMasterSecret cb)
2373
{
2374
    if (ctx != NULL) {
2375
        ctx->GenMasterCb = cb;
2376
    }
2377
}
2378
/* Set the context to pass to the master secret generation callback.
2379
 *
2380
 * @param [in, out] ssl  SSL/TLS object.
2381
 * @param [in]      ctx  Context to pass to the callback.
2382
 */
2383
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
2384
{
2385
    if (ssl != NULL) {
2386
        ssl->GenMasterCtx = ctx;
2387
    }
2388
}
2389
/* Get the context passed to the master secret generation callback.
2390
 *
2391
 * @param [in] ssl  SSL/TLS object.
2392
 * @return  Context on success.
2393
 * @return  NULL when ssl is NULL.
2394
 */
2395
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
2396
{
2397
    void* ret = NULL;
2398
2399
    if (ssl != NULL) {
2400
        ret = ssl->GenMasterCtx;
2401
    }
2402
2403
    return ret;
2404
}
2405
2406
/* Set the extended master secret generation callback.
2407
 *
2408
 * @param [in, out] ctx  SSL/TLS CTX object.
2409
 * @param [in]      cb   Callback to call. NULL to clear.
2410
 */
2411
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
2412
    CallbackGenExtMasterSecret cb)
2413
{
2414
    if (ctx != NULL) {
2415
        ctx->GenExtMasterCb = cb;
2416
    }
2417
}
2418
/* Set the context to pass to the extended master secret generation callback.
2419
 *
2420
 * @param [in, out] ssl  SSL/TLS object.
2421
 * @param [in]      ctx  Context to pass to the callback.
2422
 */
2423
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
2424
{
2425
    if (ssl != NULL) {
2426
        ssl->GenExtMasterCtx = ctx;
2427
    }
2428
}
2429
/* Get the context passed to the extended master secret generation callback.
2430
 *
2431
 * @param [in] ssl  SSL/TLS object.
2432
 * @return  Context on success.
2433
 * @return  NULL when ssl is NULL.
2434
 */
2435
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
2436
{
2437
    void* ret = NULL;
2438
2439
    if (ssl != NULL) {
2440
        ret = ssl->GenExtMasterCtx;
2441
    }
2442
2443
    return ret;
2444
}
2445
2446
2447
/* Set the session key generation callback.
2448
 *
2449
 * @param [in, out] ctx  SSL/TLS CTX object.
2450
 * @param [in]      cb   Callback to call. NULL to clear.
2451
 */
2452
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
2453
{
2454
    if (ctx != NULL) {
2455
        ctx->GenSessionKeyCb = cb;
2456
    }
2457
}
2458
/* Set the context to pass to the session key generation callback.
2459
 *
2460
 * @param [in, out] ssl  SSL/TLS object.
2461
 * @param [in]      ctx  Context to pass to the callback.
2462
 */
2463
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
2464
{
2465
    if (ssl != NULL) {
2466
        ssl->GenSessionKeyCtx = ctx;
2467
    }
2468
}
2469
/* Get the context passed to the session key generation callback.
2470
 *
2471
 * @param [in] ssl  SSL/TLS object.
2472
 * @return  Context on success.
2473
 * @return  NULL when ssl is NULL.
2474
 */
2475
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
2476
{
2477
    void* ret = NULL;
2478
2479
    if (ssl != NULL) {
2480
        ret = ssl->GenSessionKeyCtx;
2481
    }
2482
2483
    return ret;
2484
}
2485
2486
/* Set the encryption key setting callback.
2487
 *
2488
 * @param [in, out] ctx  SSL/TLS CTX object.
2489
 * @param [in]      cb   Callback to call. NULL to clear.
2490
 */
2491
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
2492
{
2493
    if (ctx != NULL) {
2494
        ctx->EncryptKeysCb = cb;
2495
    }
2496
}
2497
/* Set the context to pass to the encryption key setting callback.
2498
 *
2499
 * @param [in, out] ssl  SSL/TLS object.
2500
 * @param [in]      ctx  Context to pass to the callback.
2501
 */
2502
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
2503
{
2504
    if (ssl != NULL) {
2505
        ssl->EncryptKeysCtx = ctx;
2506
    }
2507
}
2508
/* Get the context passed to the encryption key setting callback.
2509
 *
2510
 * @param [in] ssl  SSL/TLS object.
2511
 * @return  Context on success.
2512
 * @return  NULL when ssl is NULL.
2513
 */
2514
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
2515
{
2516
    void* ret = NULL;
2517
2518
    if (ssl != NULL) {
2519
        ret = ssl->EncryptKeysCtx;
2520
    }
2521
2522
    return ret;
2523
}
2524
2525
/* Set the TLS Finished message building callback.
2526
 *
2527
 * @param [in, out] ctx  SSL/TLS CTX object.
2528
 * @param [in]      cb   Callback to call. NULL to clear.
2529
 */
2530
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
2531
{
2532
    if (ctx != NULL) {
2533
        ctx->TlsFinishedCb = cb;
2534
    }
2535
}
2536
/* Set the context to pass to the TLS Finished message building callback.
2537
 *
2538
 * @param [in, out] ssl  SSL/TLS object.
2539
 * @param [in]      ctx  Context to pass to the callback.
2540
 */
2541
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
2542
{
2543
    if (ssl != NULL) {
2544
        ssl->TlsFinishedCtx = ctx;
2545
    }
2546
}
2547
/* Get the context passed to the TLS Finished message building callback.
2548
 *
2549
 * @param [in] ssl  SSL/TLS object.
2550
 * @return  Context on success.
2551
 * @return  NULL when ssl is NULL.
2552
 */
2553
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
2554
{
2555
    void* ret = NULL;
2556
2557
    if (ssl != NULL) {
2558
        ret = ssl->TlsFinishedCtx;
2559
    }
2560
2561
    return ret;
2562
}
2563
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
2564
/* Set the MAC verification callback.
2565
 *
2566
 * @param [in, out] ctx  SSL/TLS CTX object.
2567
 * @param [in]      cb   Callback to call. NULL to clear.
2568
 */
2569
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
2570
{
2571
    if (ctx != NULL) {
2572
        ctx->VerifyMacCb = cb;
2573
    }
2574
}
2575
2576
/* Set the context to pass to the MAC verification callback.
2577
 *
2578
 * @param [in, out] ssl  SSL/TLS object.
2579
 * @param [in]      ctx  Context to pass to the callback.
2580
 */
2581
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
2582
{
2583
    if (ssl != NULL) {
2584
        ssl->VerifyMacCtx = ctx;
2585
    }
2586
}
2587
/* Get the context passed to the MAC verification callback.
2588
 *
2589
 * @param [in] ssl  SSL/TLS object.
2590
 * @return  Context on success.
2591
 * @return  NULL when ssl is NULL.
2592
 */
2593
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
2594
{
2595
    void* ret = NULL;
2596
2597
    if (ssl != NULL) {
2598
        ret = ssl->VerifyMacCtx;
2599
    }
2600
2601
    return ret;
2602
}
2603
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
2604
2605
/* Set the HKDF expand label callback.
2606
 *
2607
 * @param [in, out] ctx  SSL/TLS CTX object.
2608
 * @param [in]      cb   Callback to call. NULL to clear.
2609
 */
2610
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
2611
                                      CallbackHKDFExpandLabel cb)
2612
{
2613
    if (ctx != NULL) {
2614
        ctx->HKDFExpandLabelCb = cb;
2615
    }
2616
}
2617
#ifdef WOLFSSL_PUBLIC_ASN
2618
/* Set the callback to call to process the peer's certificate.
2619
 *
2620
 * @param [in, out] ctx  SSL/TLS CTX object.
2621
 * @param [in]      cb   Callback to call. NULL to clear.
2622
 */
2623
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
2624
                                        CallbackProcessPeerCert cb)
2625
{
2626
    if (ctx != NULL) {
2627
        ctx->ProcessPeerCertCb = cb;
2628
    }
2629
}
2630
#endif /* WOLFSSL_PUBLIC_ASN */
2631
/* Set the callback to call to process the server's signature and key
2632
 * exchange.
2633
 *
2634
 * @param [in, out] ctx  SSL/TLS CTX object.
2635
 * @param [in]      cb   Callback to call. NULL to clear.
2636
 */
2637
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
2638
                                       CallbackProcessServerSigKex cb)
2639
{
2640
    if (ctx != NULL) {
2641
        ctx->ProcessServerSigKexCb = cb;
2642
    }
2643
}
2644
/* Set the callback to call to encrypt and decrypt TLS records.
2645
 *
2646
 * @param [in, out] ctx  SSL/TLS CTX object.
2647
 * @param [in]      cb   Callback to call. NULL to clear.
2648
 */
2649
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
2650
                                          CallbackPerformTlsRecordProcessing cb)
2651
{
2652
    if (ctx != NULL) {
2653
        ctx->PerformTlsRecordProcessingCb = cb;
2654
    }
2655
}
2656
#endif /* HAVE_PK_CALLBACKS */
2657
#endif /* NO_CERTS */
2658
2659
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
2660
2661
/* Set the callback to call to perform the HKDF extract operation.
2662
 *
2663
 * @param [in, out] ctx  SSL/TLS CTX object.
2664
 * @param [in]      cb   Callback to call. NULL to clear.
2665
 */
2666
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
2667
{
2668
    if (ctx != NULL) {
2669
        ctx->HkdfExtractCb = cb;
2670
    }
2671
}
2672
2673
/* Set the context to pass to the HKDF extract callback.
2674
 *
2675
 * @param [in, out] ssl  SSL/TLS object.
2676
 * @param [in]      ctx  Context to pass to the callback.
2677
 */
2678
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
2679
{
2680
    if (ssl != NULL) {
2681
        ssl->HkdfExtractCtx = ctx;
2682
    }
2683
}
2684
2685
/* Get the context passed to the HKDF extract callback.
2686
 *
2687
 * @param [in] ssl  SSL/TLS object.
2688
 * @return  Context on success.
2689
 * @return  NULL when ssl is NULL.
2690
 */
2691
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
2692
{
2693
    void* ret = NULL;
2694
2695
    if (ssl != NULL) {
2696
        ret = ssl->HkdfExtractCtx;
2697
    }
2698
2699
    return ret;
2700
}
2701
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
2702
2703
#endif /* !WOLFCRYPT_ONLY */
2704
2705
#endif /* !WOLFSSL_SSL_API_HS_INCLUDED */