Coverage Report

Created: 2026-08-15 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-heapmath/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
90
{
49
90
    int err = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
50
51
90
    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
90
    if (ssl != NULL) {
56
90
        #ifndef NO_WOLFSSL_SERVER
57
90
        if (ssl->options.side == WOLFSSL_SERVER_END) {
58
90
            #ifdef WOLFSSL_TLS13
59
90
            if (IsAtLeastTLSv1_3(ssl->version)) {
60
90
                err = wolfSSL_accept_TLSv13(ssl);
61
90
            }
62
0
            else
63
0
            #endif
64
0
            {
65
0
                err = wolfSSL_accept(ssl);
66
0
            }
67
90
        }
68
90
        #endif
69
70
90
        #ifndef NO_WOLFSSL_CLIENT
71
90
        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
90
        #endif
83
90
    }
84
85
90
    WOLFSSL_LEAVE("wolfSSL_negotiate", err);
86
87
90
    return err;
88
90
}
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_ASYNC_CRYPT
135
        /* do not send buffered or advance state if last error was an
136
            async pending operation */
137
        && (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
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_ASYNC_CRYPT
205
        /* do not send buffered or advance state if last error was an
206
            async pending operation */
207
        && (ssl->error != WC_NO_ERR_TRACE(WC_PENDING_E))
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
0
        ssl->options.connectState = SECOND_REPLY_DONE;
693
0
        WOLFSSL_MSG("connect state: SECOND_REPLY_DONE");
694
0
        FALL_THROUGH;
695
696
0
    case SECOND_REPLY_DONE:
697
0
        if (wolfssl_handshake_done(ssl) != 0) {
698
0
            return WOLFSSL_FATAL_ERROR;
699
0
        }
700
701
0
        ssl->error = 0; /* clear the error */
702
703
0
        WOLFSSL_LEAVE("wolfSSL_connect", WOLFSSL_SUCCESS);
704
0
        return WOLFSSL_SUCCESS;
705
0
        #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS */
706
707
0
    default:
708
0
        WOLFSSL_MSG("Unknown connect state ERROR");
709
0
        return WOLFSSL_FATAL_ERROR; /* unknown connect state */
710
0
    }
711
0
    #endif /* !WOLFSSL_NO_TLS12 || !NO_OLD_TLS || !WOLFSSL_TLS13 */
712
0
}
713
714
715
/* Perform enough of the handshake to get the peer's certificate chain.
716
 *
717
 * The handshake stops once the server's certificate has been processed, so no
718
 * secure connection is established.
719
 *
720
 * @param [in, out] ssl  SSL/TLS object.
721
 * @return  WOLFSSL_SUCCESS when the certificate chain was received.
722
 * @return  WOLFSSL_FAILURE when ssl is NULL.
723
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails.
724
 */
725
int wolfSSL_connect_cert(WOLFSSL* ssl)
726
0
{
727
0
    int ret;
728
729
0
    if (ssl == NULL) {
730
0
        ret = WOLFSSL_FAILURE;
731
0
    }
732
0
    else {
733
0
        ssl->options.certOnly = 1;
734
0
        ret = wolfSSL_connect(ssl);
735
0
        ssl->options.certOnly = 0;
736
0
    }
737
738
0
    return ret;
739
0
}
740
#endif /* !NO_WOLFSSL_CLIENT && !NO_TLS */
741
/* end client only parts */
742
743
/* server only parts */
744
#if !defined(NO_WOLFSSL_SERVER) && !defined(NO_TLS)
745
746
/* Only called from the TLS 1.2 and earlier accept path, so it is guarded to
747
 * match: a TLS 1.3-only build returns before reaching it. */
748
#if !(defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
749
      defined(WOLFSSL_TLS13))
750
/* Check the server has the credentials needed to perform a handshake.
751
 *
752
 * A certificate and private key are required unless an anonymous or PSK cipher
753
 * suite may be chosen, the object is multicast, a certificate setup callback
754
 * will supply them, or the private key is held externally.
755
 *
756
 * Checked on every call in case wolfSSL_set_accept_state() was used after the
757
 * object was initialized.
758
 *
759
 * @param [in, out] ssl  SSL/TLS object.
760
 * @return  0 when the credentials can be used.
761
 * @return  WOLFSSL_FATAL_ERROR when the certificate or private key is missing.
762
 */
763
static int wolfssl_accept_check_creds(WOLFSSL* ssl)
764
0
{
765
0
    int ret = 0;
766
0
    #ifndef NO_CERTS
767
0
    word16 havePSK = 0;
768
0
    word16 haveAnon = 0;
769
0
    word16 haveMcast = 0;
770
771
    #ifndef NO_PSK
772
    havePSK = ssl->options.havePSK;
773
    #endif
774
775
    #ifdef HAVE_ANON
776
    haveAnon = ssl->options.useAnon;
777
    #endif
778
779
    #ifdef WOLFSSL_MULTICAST
780
    haveMcast = ssl->options.haveMcast;
781
    #endif
782
783
0
    if ((!havePSK) && (!haveAnon) && (!haveMcast)) {
784
        #ifdef WOLFSSL_CERT_SETUP_CB
785
        if (ssl->ctx->certSetupCb != NULL) {
786
            WOLFSSL_MSG("CertSetupCb set. server cert and "
787
                        "key not checked");
788
        }
789
        else
790
        #endif
791
0
        {
792
0
            if ((ssl->buffers.certificate == NULL) ||
793
0
                    (ssl->buffers.certificate->buffer == NULL)) {
794
0
                WOLFSSL_MSG("accept error: server cert required");
795
0
                ssl->error = NO_PRIVATE_KEY;
796
0
                WOLFSSL_ERROR(ssl->error);
797
0
                ret = WOLFSSL_FATAL_ERROR;
798
0
            }
799
0
            else if ((ssl->buffers.key == NULL) ||
800
0
                    (ssl->buffers.key->buffer == NULL)) {
801
                /* allow no private key if using existing key */
802
0
                #ifdef WOLF_PRIVATE_KEY_ID
803
0
                if ((ssl->devId != INVALID_DEVID)
804
                #ifdef HAVE_PK_CALLBACKS
805
                    || (wolfSSL_CTX_IsPrivatePkSet(ssl->ctx))
806
                #endif
807
0
                ) {
808
0
                    WOLFSSL_MSG("Allowing no server private key "
809
0
                                "(external)");
810
0
                }
811
0
                else
812
0
                #endif
813
0
                {
814
0
                    WOLFSSL_MSG("accept error: server key required");
815
0
                    ssl->error = NO_PRIVATE_KEY;
816
0
                    WOLFSSL_ERROR(ssl->error);
817
0
                    ret = WOLFSSL_FATAL_ERROR;
818
0
                }
819
0
            }
820
0
        }
821
0
    }
822
    #else
823
    (void)ssl;
824
    #endif /* !NO_CERTS */
825
826
0
    return ret;
827
0
}
828
#endif /* !(WOLFSSL_NO_TLS12 && NO_OLD_TLS && WOLFSSL_TLS13) */
829
830
/* Accept a connection from a client.
831
 *
832
 * Performs the server side of the handshake, resuming from where it last
833
 * stopped when non-blocking. Dispatches to the TLS 1.3 or DTLS handshake
834
 * when negotiated.
835
 *
836
 * @param [in, out] ssl  SSL/TLS object.
837
 * @return  WOLFSSL_SUCCESS when the handshake completes.
838
 * @return  WOLFSSL_FATAL_ERROR when ssl is NULL or the handshake fails.
839
 *          Call wolfSSL_get_error() for the reason. WOLFSSL_ERROR_WANT_READ
840
 *          and WOLFSSL_ERROR_WANT_WRITE mean call again.
841
 * @return  The error from ReinitSSL(), unchanged, when the object cannot be
842
 *          prepared for a handshake. This is a raw error code rather than
843
 *          WOLFSSL_FATAL_ERROR, and ssl->error is not set with it.
844
 *
845
 * Unlike the rest of this file, the handshake state machine below
846
 * returns from each step rather than using a single exit. Each step
847
 * must stop the handshake where it failed, and several of the steps
848
 * return from inside a receive loop, where a break would only leave
849
 * the loop.
850
 */
851
WOLFSSL_ABI
852
int wolfSSL_accept(WOLFSSL* ssl)
853
{
854
    int ret = 0;
855
856
    (void)ret;
857
858
    if (ssl == NULL) {
859
        return WOLFSSL_FATAL_ERROR;
860
    }
861
862
    #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EITHER_SIDE)
863
    if (ssl->options.side == WOLFSSL_NEITHER_END) {
864
        WOLFSSL_MSG("Setting WOLFSSL_SSL to be server side");
865
        ssl->error = InitSSL_Side(ssl, WOLFSSL_SERVER_END);
866
        if (ssl->error != WOLFSSL_SUCCESS) {
867
            WOLFSSL_ERROR(ssl->error);
868
            return WOLFSSL_FATAL_ERROR;
869
        }
870
        ssl->error = 0; /* expected to be zero here */
871
    }
872
    #endif /* OPENSSL_EXTRA || WOLFSSL_EITHER_SIDE */
873
874
    #if defined(WOLFSSL_NO_TLS12) && defined(NO_OLD_TLS) && \
875
        defined(WOLFSSL_TLS13)
876
    return wolfSSL_accept_TLSv13(ssl);
877
    #else
878
    #ifdef WOLFSSL_TLS13
879
    if (ssl->options.tls1_3) {
880
        return wolfSSL_accept_TLSv13(ssl);
881
    }
882
    #endif
883
    WOLFSSL_ENTER("wolfSSL_accept");
884
885
    /* make sure this wolfSSL object has arrays and rng setup. Protects
886
     * case where the WOLFSSL object is reused via wolfSSL_clear() */
887
    if ((ret = ReinitSSL(ssl, ssl->ctx, 0)) != 0) {
888
        return ret;
889
    }
890
891
    #ifdef WOLFSSL_WOLFSENTRY_HOOKS
892
    if ((ssl->AcceptFilter != NULL) &&
893
        ((ssl->options.acceptState == ACCEPT_BEGIN)
894
    #ifdef HAVE_SECURE_RENEGOTIATION
895
         || (ssl->options.acceptState == ACCEPT_BEGIN_RENEG)
896
    #endif
897
            ))
898
    {
899
        wolfSSL_netfilter_decision_t res;
900
        if ((ssl->AcceptFilter(ssl, ssl->AcceptFilter_arg, &res) ==
901
             WOLFSSL_SUCCESS) &&
902
            (res == WOLFSSL_NETFILTER_REJECT)) {
903
            ssl->error = SOCKET_FILTERED_E;
904
            WOLFSSL_ERROR(ssl->error);
905
            return WOLFSSL_FATAL_ERROR;
906
        }
907
    }
908
    #endif /* WOLFSSL_WOLFSENTRY_HOOKS */
909
910
    #ifdef HAVE_ERRNO_H
911
    errno = 0;
912
    #endif
913
914
    if (ssl->options.side != WOLFSSL_SERVER_END) {
915
        ssl->error = SIDE_ERROR;
916
        WOLFSSL_ERROR(ssl->error);
917
        return WOLFSSL_FATAL_ERROR;
918
    }
919
920
    ret = wolfssl_accept_check_creds(ssl);
921
    if (ret != 0) {
922
        return ret;
923
    }
924
925
    #ifdef WOLFSSL_DTLS
926
    if (ssl->version.major == DTLS_MAJOR) {
927
        ssl->options.dtls   = 1;
928
        ssl->options.tls    = 1;
929
        ssl->options.tls1_1 = 1;
930
        if ((!IsDtlsNotSctpMode(ssl)) || (IsSCR(ssl))) {
931
            ssl->options.dtlsStateful = 1;
932
        }
933
    }
934
    #endif
935
936
    ret = wolfssl_accept_flush(ssl);
937
    if (ret != 0) {
938
        return ret;
939
    }
940
941
    switch (ssl->options.acceptState) {
942
943
    case ACCEPT_BEGIN :
944
        #ifdef HAVE_SECURE_RENEGOTIATION
945
    case ACCEPT_BEGIN_RENEG:
946
        #endif
947
        /* get response */
948
        while (ssl->options.clientState < CLIENT_HELLO_COMPLETE) {
949
            if ((ssl->error = ProcessReply(ssl)) < 0) {
950
                WOLFSSL_ERROR(ssl->error);
951
                return WOLFSSL_FATAL_ERROR;
952
            }
953
        }
954
        #ifdef WOLFSSL_TLS13
955
        ssl->options.acceptState = ACCEPT_CLIENT_HELLO_DONE;
956
        WOLFSSL_MSG("accept state ACCEPT_CLIENT_HELLO_DONE");
957
        FALL_THROUGH;
958
959
    case ACCEPT_CLIENT_HELLO_DONE :
960
        if (ssl->options.tls1_3) {
961
            return wolfSSL_accept_TLSv13(ssl);
962
        }
963
        #endif
964
965
        ssl->options.acceptState = ACCEPT_FIRST_REPLY_DONE;
966
        WOLFSSL_MSG("accept state ACCEPT_FIRST_REPLY_DONE");
967
        FALL_THROUGH;
968
969
    case ACCEPT_FIRST_REPLY_DONE :
970
        if (ssl->options.returnOnGoodCh) {
971
            /* Higher level in stack wants us to return. Simulate a
972
             * WANT_WRITE to accomplish this. */
973
            ssl->error = WANT_WRITE;
974
            return WOLFSSL_FATAL_ERROR;
975
        }
976
        if ((ssl->error = SendServerHello(ssl)) != 0) {
977
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
978
            WOLFSSL_ERROR(ssl->error);
979
            return WOLFSSL_FATAL_ERROR;
980
        }
981
        ssl->options.acceptState = SERVER_HELLO_SENT;
982
        WOLFSSL_MSG("accept state SERVER_HELLO_SENT");
983
        FALL_THROUGH;
984
985
    case SERVER_HELLO_SENT :
986
        #ifdef WOLFSSL_TLS13
987
        if (ssl->options.tls1_3) {
988
            return wolfSSL_accept_TLSv13(ssl);
989
        }
990
        #endif
991
        #ifndef NO_CERTS
992
        if (!ssl->options.resuming) {
993
            if ((ssl->error = SendCertificate(ssl)) != 0) {
994
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
995
                WOLFSSL_ERROR(ssl->error);
996
                return WOLFSSL_FATAL_ERROR;
997
            }
998
        }
999
        #endif
1000
        ssl->options.acceptState = CERT_SENT;
1001
        WOLFSSL_MSG("accept state CERT_SENT");
1002
        FALL_THROUGH;
1003
1004
    case CERT_SENT :
1005
        #ifndef NO_CERTS
1006
        if (!ssl->options.resuming) {
1007
            if ((ssl->error = SendCertificateStatus(ssl)) != 0) {
1008
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1009
                WOLFSSL_ERROR(ssl->error);
1010
                return WOLFSSL_FATAL_ERROR;
1011
            }
1012
        }
1013
        #endif
1014
        ssl->options.acceptState = CERT_STATUS_SENT;
1015
        WOLFSSL_MSG("accept state CERT_STATUS_SENT");
1016
        FALL_THROUGH;
1017
1018
    case CERT_STATUS_SENT :
1019
        #ifdef WOLFSSL_TLS13
1020
        if (ssl->options.tls1_3) {
1021
            return wolfSSL_accept_TLSv13(ssl);
1022
        }
1023
        #endif
1024
        if (!ssl->options.resuming) {
1025
            if ((ssl->error = SendServerKeyExchange(ssl)) != 0) {
1026
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1027
                WOLFSSL_ERROR(ssl->error);
1028
                return WOLFSSL_FATAL_ERROR;
1029
            }
1030
        }
1031
        ssl->options.acceptState = KEY_EXCHANGE_SENT;
1032
        WOLFSSL_MSG("accept state KEY_EXCHANGE_SENT");
1033
        FALL_THROUGH;
1034
1035
    case KEY_EXCHANGE_SENT :
1036
        #ifndef NO_CERTS
1037
        if (!ssl->options.resuming) {
1038
            if (ssl->options.verifyPeer) {
1039
                if ((ssl->error = SendCertificateRequest(ssl)) != 0) {
1040
                    wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1041
                    WOLFSSL_ERROR(ssl->error);
1042
                    return WOLFSSL_FATAL_ERROR;
1043
                }
1044
            }
1045
            else {
1046
                /* SERVER: Peer auth good if not verifying client. */
1047
                ssl->options.peerAuthGood = 1;
1048
            }
1049
        }
1050
        #endif
1051
        ssl->options.acceptState = CERT_REQ_SENT;
1052
        WOLFSSL_MSG("accept state CERT_REQ_SENT");
1053
        FALL_THROUGH;
1054
1055
    case CERT_REQ_SENT :
1056
        if (!ssl->options.resuming) {
1057
            if ((ssl->error = SendServerHelloDone(ssl)) != 0) {
1058
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1059
                WOLFSSL_ERROR(ssl->error);
1060
                return WOLFSSL_FATAL_ERROR;
1061
            }
1062
        }
1063
        ssl->options.acceptState = SERVER_HELLO_DONE;
1064
        WOLFSSL_MSG("accept state SERVER_HELLO_DONE");
1065
        FALL_THROUGH;
1066
1067
    case SERVER_HELLO_DONE :
1068
        if (!ssl->options.resuming) {
1069
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
1070
                if ((ssl->error = ProcessReply(ssl)) < 0) {
1071
                    WOLFSSL_ERROR(ssl->error);
1072
                    return WOLFSSL_FATAL_ERROR;
1073
                }
1074
            }
1075
        }
1076
        ssl->options.acceptState = ACCEPT_SECOND_REPLY_DONE;
1077
        WOLFSSL_MSG("accept state  ACCEPT_SECOND_REPLY_DONE");
1078
        FALL_THROUGH;
1079
1080
    case ACCEPT_SECOND_REPLY_DONE :
1081
        #ifndef NO_CERTS
1082
        /* SERVER: When not resuming and verifying peer but no certificate
1083
         * received and not failing when not received then peer auth good.
1084
         */
1085
        if ((!ssl->options.resuming) && (ssl->options.verifyPeer) &&
1086
                (!ssl->options.havePeerCert) &&
1087
                (!ssl->options.failNoCert)) {
1088
            ssl->options.peerAuthGood = 1;
1089
        }
1090
        #endif /* !NO_CERTS  */
1091
        #ifdef WOLFSSL_NO_CLIENT_AUTH
1092
        if (!ssl->options.resuming) {
1093
            ssl->options.peerAuthGood = 1;
1094
        }
1095
        #endif
1096
1097
        #ifdef HAVE_SESSION_TICKET
1098
        if ((ssl->options.createTicket) &&
1099
                (!ssl->options.noTicketTls12)) {
1100
            if ((ssl->error = SendTicket(ssl)) != 0) {
1101
                wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1102
                WOLFSSL_MSG("Thought we need ticket but failed");
1103
                WOLFSSL_ERROR(ssl->error);
1104
                return WOLFSSL_FATAL_ERROR;
1105
            }
1106
        }
1107
        #endif /* HAVE_SESSION_TICKET */
1108
        ssl->options.acceptState = TICKET_SENT;
1109
        WOLFSSL_MSG("accept state  TICKET_SENT");
1110
        FALL_THROUGH;
1111
1112
    case TICKET_SENT:
1113
        /* SERVER: Fail-safe for CLient Authentication. */
1114
        if (!ssl->options.peerAuthGood) {
1115
            WOLFSSL_MSG("Client authentication did not happen");
1116
            return WOLFSSL_FATAL_ERROR;
1117
        }
1118
1119
        if ((ssl->error = SendChangeCipher(ssl)) != 0) {
1120
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1121
            WOLFSSL_ERROR(ssl->error);
1122
            return WOLFSSL_FATAL_ERROR;
1123
        }
1124
        ssl->options.acceptState = CHANGE_CIPHER_SENT;
1125
        WOLFSSL_MSG("accept state  CHANGE_CIPHER_SENT");
1126
        FALL_THROUGH;
1127
1128
    case CHANGE_CIPHER_SENT :
1129
        if ((ssl->error = SendFinished(ssl)) != 0) {
1130
            wolfssl_local_MaybeCheckAlertOnErr(ssl, ssl->error);
1131
            WOLFSSL_ERROR(ssl->error);
1132
            return WOLFSSL_FATAL_ERROR;
1133
        }
1134
1135
        ssl->options.acceptState = ACCEPT_FINISHED_DONE;
1136
        WOLFSSL_MSG("accept state ACCEPT_FINISHED_DONE");
1137
        FALL_THROUGH;
1138
1139
    case ACCEPT_FINISHED_DONE :
1140
        if (ssl->options.resuming) {
1141
            while (ssl->options.clientState < CLIENT_FINISHED_COMPLETE) {
1142
                if ((ssl->error = ProcessReply(ssl)) < 0) {
1143
                    WOLFSSL_ERROR(ssl->error);
1144
                    return WOLFSSL_FATAL_ERROR;
1145
                }
1146
            }
1147
        }
1148
        ssl->options.acceptState = ACCEPT_THIRD_REPLY_DONE;
1149
        WOLFSSL_MSG("accept state ACCEPT_THIRD_REPLY_DONE");
1150
        FALL_THROUGH;
1151
1152
    case ACCEPT_THIRD_REPLY_DONE :
1153
        if (wolfssl_handshake_done(ssl) != 0) {
1154
            return WOLFSSL_FATAL_ERROR;
1155
        }
1156
1157
        #if defined(WOLFSSL_SESSION_EXPORT) && defined(WOLFSSL_DTLS)
1158
        if (ssl->dtls_export) {
1159
            if ((ssl->error = wolfSSL_send_session(ssl)) != 0) {
1160
                WOLFSSL_MSG("Export DTLS session error");
1161
                WOLFSSL_ERROR(ssl->error);
1162
                return WOLFSSL_FATAL_ERROR;
1163
            }
1164
        }
1165
        #endif
1166
        ssl->error = 0; /* clear the error */
1167
1168
        WOLFSSL_LEAVE("wolfSSL_accept", WOLFSSL_SUCCESS);
1169
        return WOLFSSL_SUCCESS;
1170
1171
    default:
1172
        WOLFSSL_MSG("Unknown accept state ERROR");
1173
        return WOLFSSL_FATAL_ERROR;
1174
    }
1175
    #endif /* !WOLFSSL_NO_TLS12 */
1176
}
1177
1178
#endif /* !NO_WOLFSSL_SERVER && !NO_TLS */
1179
/* end server only parts */
1180
1181
#ifndef NO_HANDSHAKE_DONE_CB
1182
1183
/* Set the callback to call when the handshake completes.
1184
 *
1185
 * @param [in, out] ssl       SSL/TLS object.
1186
 * @param [in]      cb        Callback to call. NULL to clear.
1187
 * @param [in]      user_ctx  Context to pass to the callback.
1188
 * @return  WOLFSSL_SUCCESS on success.
1189
 * @return  BAD_FUNC_ARG when ssl is NULL.
1190
 */
1191
int wolfSSL_SetHsDoneCb(WOLFSSL* ssl, HandShakeDoneCb cb, void* user_ctx)
1192
0
{
1193
0
    int ret = WOLFSSL_SUCCESS;
1194
1195
0
    WOLFSSL_ENTER("wolfSSL_SetHsDoneCb");
1196
1197
0
    if (ssl == NULL) {
1198
0
        ret = BAD_FUNC_ARG;
1199
0
    }
1200
0
    else {
1201
0
        ssl->hsDoneCb  = cb;
1202
0
        ssl->hsDoneCtx = user_ctx;
1203
0
    }
1204
1205
0
    return ret;
1206
0
}
1207
1208
#endif /* NO_HANDSHAKE_DONE_CB */
1209
1210
#ifdef WOLFSSL_CALLBACKS
1211
1212
typedef struct itimerval Itimerval;
1213
1214
/* don't keep calling simple functions while setting up timer and signals
1215
   if no inlining these are the next best */
1216
1217
#define SubtractTimes(a, b, c)                  \
1218
    do {                                        \
1219
        (c).tv_sec  = (a).tv_sec - (b).tv_sec;  \
1220
        (c).tv_usec = (a).tv_usec - (b).tv_usec;\
1221
        if ((c).tv_usec < 0) {                  \
1222
            (c).tv_sec--;                       \
1223
            (c).tv_usec += 1000000;             \
1224
        }                                       \
1225
    } while (0)
1226
1227
#define CmpTimes(a, b, cmp)                     \
1228
    (((a).tv_sec  ==  (b).tv_sec) ?             \
1229
        ((a).tv_usec cmp (b).tv_usec) :         \
1230
        ((a).tv_sec  cmp (b).tv_sec))           \
1231
1232
1233
/* Signal handler that does nothing.
1234
 *
1235
 * Installed for SIGALRM so that the timer interrupts a blocking call rather
1236
 * than terminating the process.
1237
 *
1238
 * @param [in] signo  Signal number. Unused.
1239
 */
1240
static void myHandler(int signo)
1241
{
1242
    (void)signo;
1243
    return;
1244
}
1245
1246
1247
/* Replace any running timer with one that expires after the timeout.
1248
 *
1249
 * When a timer is already running and would expire first, the timeout is
1250
 * shortened to match it so the existing timer is not delayed.
1251
 *
1252
 * @param [in, out] timeout     Maximum time to take. Shortened when a timer
1253
 *                              already running would expire sooner.
1254
 * @param [out]     oldTimeout  Timer that was running, to be restored later.
1255
 * @param [out]     timerWasOn  Set to 1 when a timer was already running, 0
1256
 *                              when not.
1257
 * @param [out]     oact        Signal handler that was replaced.
1258
 * @return  0 on success.
1259
 * @return  SETITIMER_ERROR when the timer cannot be read or set.
1260
 * @return  SIGACT_ERROR when the signal handler cannot be installed.
1261
 */
1262
static int wolfssl_ex_wrapper_set_timer(WOLFSSL_TIMEVAL* timeout,
1263
    Itimerval* oldTimeout, int* timerWasOn, struct sigaction* oact)
1264
{
1265
    int ret = 0;
1266
    Itimerval myTimeout;
1267
    struct sigaction act;
1268
1269
    *timerWasOn = 0;
1270
1271
    /* use setitimer to simulate getitimer, init 0 myTimeout */
1272
    myTimeout.it_interval.tv_sec  = 0;
1273
    myTimeout.it_interval.tv_usec = 0;
1274
    myTimeout.it_value.tv_sec     = 0;
1275
    myTimeout.it_value.tv_usec    = 0;
1276
    if (setitimer(ITIMER_REAL, &myTimeout, oldTimeout) < 0) {
1277
        ret = SETITIMER_ERROR;
1278
    }
1279
1280
    if (ret == 0) {
1281
        if ((oldTimeout->it_value.tv_sec) ||
1282
                (oldTimeout->it_value.tv_usec)) {
1283
            *timerWasOn = 1;
1284
1285
            /* is old timer going to expire before ours */
1286
            if (CmpTimes(oldTimeout->it_value, *timeout, <)) {
1287
                timeout->tv_sec  = oldTimeout->it_value.tv_sec;
1288
                timeout->tv_usec = oldTimeout->it_value.tv_usec;
1289
            }
1290
        }
1291
        myTimeout.it_value.tv_sec  = timeout->tv_sec;
1292
        myTimeout.it_value.tv_usec = timeout->tv_usec;
1293
1294
        /* set up signal handler, don't restart socket send/recv */
1295
        act.sa_handler = myHandler;
1296
        sigemptyset(&act.sa_mask);
1297
        act.sa_flags = 0;
1298
        #ifdef SA_INTERRUPT
1299
        act.sa_flags |= SA_INTERRUPT;
1300
        #endif
1301
        if (sigaction(SIGALRM, &act, oact) < 0) {
1302
            ret = SIGACT_ERROR;
1303
        }
1304
    }
1305
1306
    if (ret == 0) {
1307
        if (setitimer(ITIMER_REAL, &myTimeout, 0) < 0) {
1308
            ret = SETITIMER_ERROR;
1309
        }
1310
    }
1311
1312
    return ret;
1313
}
1314
1315
/* Restore the timer and signal handler that were replaced.
1316
 *
1317
 * A restored timer is adjusted for the time that has since elapsed.
1318
 *
1319
 * @param [in]      startTime   When the handshake started.
1320
 * @param [in]      endTime     When the handshake finished. Only read when
1321
 *                              oldTimerOn is set.
1322
 * @param [in, out] oldTimeout  Timer to restore.
1323
 * @param [in]      oldTimerOn  Whether a timer was already running.
1324
 * @param [in]      oact        Signal handler to restore.
1325
 * @return  0 on success.
1326
 * @return  SIGACT_ERROR when the signal handler cannot be restored.
1327
 * @return  SETITIMER_ERROR when the timer cannot be restored.
1328
 */
1329
static int wolfssl_ex_wrapper_reset_timer(const WOLFSSL_TIMEVAL* startTime,
1330
    const WOLFSSL_TIMEVAL* endTime, Itimerval* oldTimeout, int oldTimerOn,
1331
    struct sigaction* oact)
1332
{
1333
    int ret = 0;
1334
    WOLFSSL_TIMEVAL totalTime;
1335
1336
    if (oldTimerOn) {
1337
        SubtractTimes(*endTime, *startTime, totalTime);
1338
        /* adjust old timer for elapsed time */
1339
        if (CmpTimes(totalTime, oldTimeout->it_value, <)) {
1340
            SubtractTimes(oldTimeout->it_value, totalTime,
1341
                          oldTimeout->it_value);
1342
        }
1343
        else {
1344
            /* reset value to interval, may be off */
1345
            oldTimeout->it_value.tv_sec = oldTimeout->it_interval.tv_sec;
1346
            oldTimeout->it_value.tv_usec = oldTimeout->it_interval.tv_usec;
1347
        }
1348
    /* keep iter the same whether there or not */
1349
    }
1350
1351
    /* restore old handler */
1352
    if (sigaction(SIGALRM, oact, 0) < 0) {
1353
        ret = SIGACT_ERROR;    /* more pressing error, stomp */
1354
    }
1355
    else {
1356
        /* use old settings which may turn off (expired or not there) */
1357
        if (setitimer(ITIMER_REAL, oldTimeout, 0) < 0) {
1358
            ret = SETITIMER_ERROR;
1359
        }
1360
    }
1361
1362
    return ret;
1363
}
1364
1365
/* Perform a handshake with monitoring callbacks and a timeout.
1366
 *
1367
 * An interval timer is used to abort the handshake when it takes longer
1368
 * than the timeout. Any existing timer is restored afterwards.
1369
 *
1370
 * @param [in, out] ssl      SSL/TLS object.
1371
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1372
 * @param [in]      toCb     Timeout callback. May be NULL.
1373
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1374
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1375
 * @return  WOLFSSL_FATAL_ERROR when ssl is NULL, the timeout value is bad,
1376
 *          setting the timer fails or the handshake fails.
1377
 */
1378
static int wolfSSL_ex_wrapper(WOLFSSL* ssl, HandShakeCallBack hsCb,
1379
                             TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1380
{
1381
    int       ret        = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
1382
    int       oldTimerOn = 0;   /* was timer already on */
1383
    WOLFSSL_TIMEVAL startTime;
1384
    /* Only filled in, and only read, when a timer was already running. Zeroed
1385
     * so the helper is never handed uninitialized storage. */
1386
    WOLFSSL_TIMEVAL endTime;
1387
    Itimerval oldTimeout; /* if old timer adjust from total time to reset */
1388
    struct sigaction oact;
1389
1390
#define ERR_OUT(x) \
1391
    do { ssl->hsInfoOn = 0; ssl->toInfoOn = 0; return x; } while (0)
1392
1393
    XMEMSET(&endTime, 0, sizeof(endTime));
1394
1395
    if (hsCb) {
1396
        ssl->hsInfoOn = 1;
1397
        InitHandShakeInfo(&ssl->handShakeInfo, ssl);
1398
    }
1399
    if (toCb) {
1400
        /* Kept out of ret so the fatal default survives to the dispatch
1401
         * below, which leaves ret alone when no side has been established. */
1402
        int sret;
1403
1404
        ssl->toInfoOn = 1;
1405
        InitTimeoutInfo(&ssl->timeoutInfo);
1406
1407
        if (gettimeofday(&startTime, 0) < 0) {
1408
            ERR_OUT(GETTIME_ERROR);
1409
        }
1410
1411
        sret = wolfssl_ex_wrapper_set_timer(&timeout, &oldTimeout,
1412
            &oldTimerOn, &oact);
1413
        if (sret != 0) {
1414
            ERR_OUT(sret);
1415
        }
1416
    }
1417
1418
    /* do main work */
1419
    #ifndef NO_WOLFSSL_CLIENT
1420
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1421
        ret = wolfSSL_connect(ssl);
1422
    }
1423
    #endif
1424
    #ifndef NO_WOLFSSL_SERVER
1425
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1426
        ret = wolfSSL_accept(ssl);
1427
    }
1428
    #endif
1429
1430
    /* do callbacks */
1431
    if (toCb) {
1432
        int tret;
1433
1434
        if (oldTimerOn) {
1435
            if (gettimeofday(&endTime, 0) < 0) {
1436
                ERR_OUT(SYSLIB_FAILED_E);
1437
            }
1438
        }
1439
1440
        tret = wolfssl_ex_wrapper_reset_timer(&startTime, &endTime,
1441
            &oldTimeout, oldTimerOn, &oact);
1442
        if (tret != 0) {
1443
            ret = tret;    /* more pressing error, stomp */
1444
        }
1445
1446
        /* if we had a timeout call callback */
1447
        if (ssl->timeoutInfo.timeoutName[0]) {
1448
            ssl->timeoutInfo.timeoutValue.tv_sec  = timeout.tv_sec;
1449
            ssl->timeoutInfo.timeoutValue.tv_usec = timeout.tv_usec;
1450
            (toCb)(&ssl->timeoutInfo);
1451
        }
1452
        ssl->toInfoOn = 0;
1453
    }
1454
1455
    /* clean up buffers allocated by AddPacketInfo */
1456
    FreeTimeoutInfo(&ssl->timeoutInfo, ssl->heap);
1457
1458
    if (hsCb) {
1459
        FinishHandShakeInfo(&ssl->handShakeInfo);
1460
        (hsCb)(&ssl->handShakeInfo);
1461
        ssl->hsInfoOn = 0;
1462
    }
1463
    return ret;
1464
}
1465
1466
1467
#ifndef NO_WOLFSSL_CLIENT
1468
1469
/* Connect to a server with monitoring callbacks and a timeout.
1470
 *
1471
 * @param [in, out] ssl      SSL/TLS object.
1472
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1473
 * @param [in]      toCb     Timeout callback. May be NULL.
1474
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1475
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1476
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails or times out.
1477
 */
1478
int wolfSSL_connect_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
1479
                      TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1480
{
1481
    WOLFSSL_ENTER("wolfSSL_connect_ex");
1482
    return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
1483
}
1484
1485
#endif
1486
1487
1488
#ifndef NO_WOLFSSL_SERVER
1489
1490
/* Accept a connection from a client with monitoring callbacks and a
1491
 * timeout.
1492
 *
1493
 * @param [in, out] ssl      SSL/TLS object.
1494
 * @param [in]      hsCb     Handshake information callback. May be NULL.
1495
 * @param [in]      toCb     Timeout callback. May be NULL.
1496
 * @param [in]      timeout  Maximum time to take. Zero for no timeout.
1497
 * @return  WOLFSSL_SUCCESS when the handshake completes.
1498
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails or times out.
1499
 */
1500
int wolfSSL_accept_ex(WOLFSSL* ssl, HandShakeCallBack hsCb,
1501
                     TimeoutCallBack toCb, WOLFSSL_TIMEVAL timeout)
1502
{
1503
    WOLFSSL_ENTER("wolfSSL_accept_ex");
1504
    return wolfSSL_ex_wrapper(ssl, hsCb, toCb, timeout);
1505
}
1506
1507
#endif
1508
1509
/* Local to this file, which is compiled into ssl.c, so do not leave them
1510
 * defined for the files included after it. */
1511
#undef ERR_OUT
1512
#undef SubtractTimes
1513
#undef CmpTimes
1514
1515
#endif /* WOLFSSL_CALLBACKS */
1516
1517
1518
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_EXTRA) || \
1519
    defined(WOLFSSL_WPAS_SMALL)
1520
1521
/* Set the SSL/TLS object to be a server.
1522
 *
1523
 * Resets the handshake state and cipher suites. Must be called before the
1524
 * handshake starts.
1525
 *
1526
 * @param [in, out] ssl  SSL/TLS object.
1527
 */
1528
void wolfSSL_set_accept_state(WOLFSSL* ssl)
1529
{
1530
    WOLFSSL_ENTER("wolfSSL_set_accept_state");
1531
1532
    if (ssl == NULL) {
1533
        return;
1534
    }
1535
1536
    if (ssl->options.side == WOLFSSL_CLIENT_END) {
1537
        #ifdef HAVE_ECC
1538
        WC_DECLARE_VAR(key, ecc_key, 1, 0);
1539
        word32 idx = 0;
1540
1541
        #ifdef WOLFSSL_SMALL_STACK
1542
        key = (ecc_key*)XMALLOC(sizeof(ecc_key), ssl->heap,
1543
                                DYNAMIC_TYPE_ECC);
1544
        if (key == NULL) {
1545
            WOLFSSL_MSG("Error allocating memory for ecc_key");
1546
        }
1547
        #endif
1548
        if ((ssl->options.haveStaticECC) && (ssl->buffers.key != NULL)) {
1549
            if (wc_ecc_init(key) >= 0) {
1550
                DerBuffer* privKey = ssl->buffers.key;
1551
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
1552
                DerBuffer* unblinded = NULL;
1553
1554
                /* Only a key that has a mask is masked. Without one - after
1555
                 * wolfSSL_use_PrivateKey_Id(), for example - the buffer is
1556
                 * stored as-is and is used directly, so that this build
1557
                 * behaves the same as one without key blinding. */
1558
                if (ssl->buffers.keyMask != NULL) {
1559
                    /* The stored key is masked, so work on a plain copy. */
1560
                    unblinded = wolfssl_priv_der_unblind(ssl->buffers.key,
1561
                        ssl->buffers.keyMask);
1562
                    privKey = unblinded;
1563
                }
1564
                #endif
1565
1566
                if (privKey == NULL) {
1567
                    /* Only an allocation failure gets here, and that says
1568
                     * nothing about the key. Leave the capabilities as they
1569
                     * are rather than withdraw them, which is also what a
1570
                     * failure to allocate the ecc_key above does - that skips
1571
                     * the check entirely. */
1572
                    WOLFSSL_MSG("Unable to unmask private key");
1573
                }
1574
                /* Not an EC key, so withdraw the ECC capabilities. */
1575
                else if (wc_EccPrivateKeyDecode(privKey->buffer, &idx, key,
1576
                        privKey->length) != 0) {
1577
                    ssl->options.haveECDSAsig = 0;
1578
                    ssl->options.haveECC = 0;
1579
                    ssl->options.haveStaticECC = 0;
1580
                }
1581
1582
                #ifdef WOLFSSL_BLIND_PRIVATE_KEY
1583
                /* Only the plain copy is disposed of - the stored key is
1584
                 * not ours to free. */
1585
                wolfssl_priv_der_unblind_free(unblinded);
1586
                #endif
1587
                wc_ecc_free(key);
1588
            }
1589
        }
1590
        WC_FREE_VAR_EX(key, ssl->heap, DYNAMIC_TYPE_ECC);
1591
        #endif
1592
1593
        #ifndef NO_DH
1594
        if ((!ssl->options.haveDH) && (ssl->ctx->haveDH)) {
1595
            ssl->buffers.serverDH_P = ssl->ctx->serverDH_P;
1596
            ssl->buffers.serverDH_G = ssl->ctx->serverDH_G;
1597
            ssl->options.haveDH = 1;
1598
        }
1599
        #endif
1600
    }
1601
1602
    if (InitSSL_Side(ssl, WOLFSSL_SERVER_END) != WOLFSSL_SUCCESS) {
1603
        WOLFSSL_MSG("Error initializing server side");
1604
    }
1605
}
1606
1607
#endif /* OPENSSL_EXTRA || WOLFSSL_EXTRA || WOLFSSL_WPAS_SMALL */
1608
1609
/* Determine whether the handshake has completed.
1610
 *
1611
 * Works for both TLS and DTLS.
1612
 *
1613
 * @param [in] ssl  SSL/TLS object.
1614
 * @return  1 when the handshake has completed.
1615
 * @return  0 when the handshake has not completed or ssl is NULL.
1616
 */
1617
int wolfSSL_is_init_finished(const WOLFSSL* ssl)
1618
0
{
1619
0
    int ret = 0;
1620
1621
0
    if (ssl != NULL) {
1622
        #if defined(WOLFSSL_DTLS13) && !defined(NO_WOLFSSL_CLIENT)
1623
        if ((ssl->options.side == WOLFSSL_CLIENT_END) && (ssl->options.dtls)
1624
                && (IsAtLeastTLSv1_3(ssl->version))) {
1625
            ret = (ssl->options.serverState == SERVER_FINISHED_ACKED);
1626
        }
1627
        else
1628
        #endif /* WOLFSSL_DTLS13 && !NO_WOLFSSL_CLIENT */
1629
0
        {
1630
            /* Can't use ssl->options.connectState and ssl->options.acceptState
1631
             * because they differ in meaning for TLS <=1.2 and 1.3 */
1632
0
            if (ssl->options.handShakeState == HANDSHAKE_DONE) {
1633
0
                ret = 1;
1634
0
            }
1635
0
        }
1636
0
    }
1637
1638
0
    return ret;
1639
0
}
1640
1641
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
1642
/* Set the SSL/TLS object to be a client.
1643
 *
1644
 * Resets the handshake state and cipher suites. Must be called before the
1645
 * handshake starts.
1646
 *
1647
 * @param [in, out] ssl  SSL/TLS object.
1648
 */
1649
void wolfSSL_set_connect_state(WOLFSSL* ssl)
1650
{
1651
    WOLFSSL_ENTER("wolfSSL_set_connect_state");
1652
    if (ssl == NULL) {
1653
        WOLFSSL_MSG("WOLFSSL struct pointer passed in was null");
1654
        return;
1655
    }
1656
1657
    #ifndef NO_DH
1658
    /* client creates its own DH parameters on handshake */
1659
    if ((ssl->buffers.serverDH_P.buffer != NULL) &&
1660
            (ssl->buffers.weOwnDH)) {
1661
        XFREE(ssl->buffers.serverDH_P.buffer, ssl->heap,
1662
            DYNAMIC_TYPE_PUBLIC_KEY);
1663
    }
1664
    ssl->buffers.serverDH_P.buffer = NULL;
1665
    if ((ssl->buffers.serverDH_G.buffer != NULL) &&
1666
            (ssl->buffers.weOwnDH)) {
1667
        XFREE(ssl->buffers.serverDH_G.buffer, ssl->heap,
1668
            DYNAMIC_TYPE_PUBLIC_KEY);
1669
    }
1670
    ssl->buffers.serverDH_G.buffer = NULL;
1671
    #endif
1672
1673
    if (InitSSL_Side(ssl, WOLFSSL_CLIENT_END) != WOLFSSL_SUCCESS) {
1674
        WOLFSSL_MSG("Error initializing client side");
1675
    }
1676
}
1677
#endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
1678
1679
#ifdef OPENSSL_EXTRA
1680
1681
#define STATE_STRINGS_PROTO(s) \
1682
    {                          \
1683
        {"SSLv3 " s,           \
1684
         "SSLv3 " s,           \
1685
         "SSLv3 " s},          \
1686
        {"TLSv1 " s,           \
1687
         "TLSv1 " s,           \
1688
         "TLSv1 " s},          \
1689
        {"TLSv1_1 " s,         \
1690
         "TLSv1_1 " s,         \
1691
         "TLSv1_1 " s},        \
1692
        {"TLSv1_2 " s,         \
1693
         "TLSv1_2 " s,         \
1694
         "TLSv1_2 " s},        \
1695
        {"TLSv1_3 " s,         \
1696
         "TLSv1_3 " s,         \
1697
         "TLSv1_3 " s},        \
1698
        {"DTLSv1 " s,          \
1699
         "DTLSv1 " s,          \
1700
         "DTLSv1 " s},         \
1701
        {"DTLSv1_2 " s,        \
1702
         "DTLSv1_2 " s,        \
1703
         "DTLSv1_2 " s},       \
1704
        {"DTLSv1_3 " s,        \
1705
         "DTLSv1_3 " s,        \
1706
         "DTLSv1_3 " s},       \
1707
    }
1708
1709
#define STATE_STRINGS_PROTO_RW(s) \
1710
    {                             \
1711
        {"SSLv3 read " s,         \
1712
         "SSLv3 write " s,        \
1713
         "SSLv3 " s},             \
1714
        {"TLSv1 read " s,         \
1715
         "TLSv1 write " s,        \
1716
         "TLSv1 " s},             \
1717
        {"TLSv1_1 read " s,       \
1718
         "TLSv1_1 write " s,      \
1719
         "TLSv1_1 " s},           \
1720
        {"TLSv1_2 read " s,       \
1721
         "TLSv1_2 write " s,      \
1722
         "TLSv1_2 " s},           \
1723
        {"TLSv1_3 read " s,       \
1724
         "TLSv1_3 write " s,      \
1725
         "TLSv1_3 " s},           \
1726
        {"DTLSv1 read " s,        \
1727
         "DTLSv1 write " s,       \
1728
         "DTLSv1 " s},            \
1729
        {"DTLSv1_2 read " s,      \
1730
         "DTLSv1_2 write " s,     \
1731
         "DTLSv1_2 " s},          \
1732
        {"DTLSv1_3 read " s,      \
1733
         "DTLSv1_3 write " s,     \
1734
         "DTLSv1_3 " s},          \
1735
    }
1736
1737
/* Indices into OUTPUT_STR in wolfSSL_state_string_long().
1738
 *
1739
 * These are shared by that function and its helpers below, so they cannot be
1740
 * local to any one of them. This file is compiled as part of ssl.c, which
1741
 * makes them visible to every other file included into it, hence the
1742
 * WOLFSSL_SS_ ("state string") prefix on the enumerators, whose names would
1743
 * otherwise be far too generic to sit in that namespace. The enum tags
1744
 * follow the naming of those in wolfssl/ssl.h.
1745
 */
1746
enum StateStringProtocol {
1747
    WOLFSSL_SS_SSL_V3 = 0,
1748
    WOLFSSL_SS_TLS_V1,
1749
    WOLFSSL_SS_TLS_V1_1,
1750
    WOLFSSL_SS_TLS_V1_2,
1751
    WOLFSSL_SS_TLS_V1_3,
1752
    WOLFSSL_SS_DTLS_V1,
1753
    WOLFSSL_SS_DTLS_V1_2,
1754
    WOLFSSL_SS_DTLS_V1_3,
1755
    /* Number of protocols above - the second dimension of OUTPUT_STR in
1756
     * wolfSSL_state_string_long(). Keep last of the indices. */
1757
    WOLFSSL_SS_PROTO_CNT,
1758
    WOLFSSL_SS_UNKNOWN = 100
1759
};
1760
1761
enum StateStringIoMode {
1762
    WOLFSSL_SS_READ = 0,
1763
    WOLFSSL_SS_WRITE,
1764
    WOLFSSL_SS_NEITHER,
1765
    /* Number of modes above - the third dimension of OUTPUT_STR. */
1766
    WOLFSSL_SS_IO_CNT
1767
};
1768
1769
enum StateStringState {
1770
    WOLFSSL_SS_NULL_STATE = 0,
1771
    WOLFSSL_SS_SERVER_HELLOREQUEST,
1772
    WOLFSSL_SS_SERVER_HELLOVERIFY,
1773
    WOLFSSL_SS_SERVER_HELLORETRYREQUEST,
1774
    WOLFSSL_SS_SERVER_HELLO,
1775
    WOLFSSL_SS_SERVER_CERTIFICATESTATUS,
1776
    WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS,
1777
    WOLFSSL_SS_SERVER_SESSIONTICKET,
1778
    WOLFSSL_SS_SERVER_CERTREQUEST,
1779
    WOLFSSL_SS_SERVER_CERT,
1780
    WOLFSSL_SS_SERVER_KEYEXCHANGE,
1781
    WOLFSSL_SS_SERVER_HELLODONE,
1782
    WOLFSSL_SS_SERVER_CHANGECIPHERSPEC,
1783
    WOLFSSL_SS_SERVER_FINISHED,
1784
    WOLFSSL_SS_SERVER_KEYUPDATE,
1785
    WOLFSSL_SS_CLIENT_HELLO,
1786
    WOLFSSL_SS_CLIENT_KEYEXCHANGE,
1787
    WOLFSSL_SS_CLIENT_CERT,
1788
    WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC,
1789
    WOLFSSL_SS_CLIENT_CERTVERIFY,
1790
    WOLFSSL_SS_CLIENT_ENDOFEARLYDATA,
1791
    WOLFSSL_SS_CLIENT_FINISHED,
1792
    WOLFSSL_SS_CLIENT_KEYUPDATE,
1793
    WOLFSSL_SS_HANDSHAKE_DONE,
1794
    /* Number of states above - the first dimension of OUTPUT_STR. Each state
1795
     * indexes a row of that table, so the two must stay the same size. */
1796
    WOLFSSL_SS_STATE_CNT
1797
};
1798
1799
/* Determine which direction the last handshake message travelled.
1800
 *
1801
 * @param [in] ssl  SSL/TLS object.
1802
 * @return  WOLFSSL_SS_READ when the last message was read.
1803
 * @return  WOLFSSL_SS_WRITE when the last message was written.
1804
 * @return  WOLFSSL_SS_NEITHER when no message has been read or written.
1805
 */
1806
static int wolfssl_state_string_io_mode(const WOLFSSL* ssl)
1807
{
1808
    int cbmode = WOLFSSL_SS_NEITHER;
1809
1810
    if (ssl->cbmode == WOLFSSL_CB_MODE_WRITE) {
1811
        cbmode = WOLFSSL_SS_WRITE;
1812
    }
1813
    else if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
1814
        cbmode = WOLFSSL_SS_READ;
1815
    }
1816
1817
    return cbmode;
1818
}
1819
1820
/* Determine the protocol version in use.
1821
 *
1822
 * @param [in] ssl  SSL/TLS object.
1823
 * @return  Index of the protocol version in the state string table.
1824
 * @return  WOLFSSL_SS_UNKNOWN when the version is not recognized.
1825
 */
1826
static int wolfssl_state_string_protocol(const WOLFSSL* ssl)
1827
{
1828
    int protocol = WOLFSSL_SS_UNKNOWN;
1829
1830
    switch (ssl->version.major) {
1831
    case SSLv3_MAJOR:
1832
        switch (ssl->version.minor) {
1833
        case SSLv3_MINOR:
1834
            protocol = WOLFSSL_SS_SSL_V3;
1835
            break;
1836
        case TLSv1_MINOR:
1837
            protocol = WOLFSSL_SS_TLS_V1;
1838
            break;
1839
        case TLSv1_1_MINOR:
1840
            protocol = WOLFSSL_SS_TLS_V1_1;
1841
            break;
1842
        case TLSv1_2_MINOR:
1843
            protocol = WOLFSSL_SS_TLS_V1_2;
1844
            break;
1845
        case TLSv1_3_MINOR:
1846
            protocol = WOLFSSL_SS_TLS_V1_3;
1847
            break;
1848
        default:
1849
            protocol = WOLFSSL_SS_UNKNOWN;
1850
        }
1851
        break;
1852
    case DTLS_MAJOR:
1853
        switch (ssl->version.minor) {
1854
        case DTLS_MINOR:
1855
            protocol = WOLFSSL_SS_DTLS_V1;
1856
            break;
1857
        case DTLSv1_2_MINOR:
1858
            protocol = WOLFSSL_SS_DTLS_V1_2;
1859
            break;
1860
        case DTLSv1_3_MINOR:
1861
            protocol = WOLFSSL_SS_DTLS_V1_3;
1862
            break;
1863
        default:
1864
            protocol = WOLFSSL_SS_UNKNOWN;
1865
        }
1866
        break;
1867
    default:
1868
        protocol = WOLFSSL_SS_UNKNOWN;
1869
    }
1870
1871
    return protocol;
1872
}
1873
1874
/* Map the type of the last message read to a state string table index.
1875
 *
1876
 * @param [in] ssl  SSL/TLS object.
1877
 * @return  Index of the message in the state string table.
1878
 * @return  WOLFSSL_SS_NULL_STATE when the message type is not recognized.
1879
 */
1880
static int wolfssl_state_string_recv_state(const WOLFSSL* ssl)
1881
{
1882
    int state = ssl->cbtype;
1883
1884
    switch (state) {
1885
    case hello_request:
1886
        state = WOLFSSL_SS_SERVER_HELLOREQUEST;
1887
        break;
1888
    case client_hello:
1889
        state = WOLFSSL_SS_CLIENT_HELLO;
1890
        break;
1891
    case server_hello:
1892
        state = WOLFSSL_SS_SERVER_HELLO;
1893
        break;
1894
    case hello_verify_request:
1895
        state = WOLFSSL_SS_SERVER_HELLOVERIFY;
1896
        break;
1897
    case session_ticket:
1898
        state = WOLFSSL_SS_SERVER_SESSIONTICKET;
1899
        break;
1900
    case end_of_early_data:
1901
        state = WOLFSSL_SS_CLIENT_ENDOFEARLYDATA;
1902
        break;
1903
    case hello_retry_request:
1904
        state = WOLFSSL_SS_SERVER_HELLORETRYREQUEST;
1905
        break;
1906
    case encrypted_extensions:
1907
        state = WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS;
1908
        break;
1909
    case certificate:
1910
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1911
            state = WOLFSSL_SS_CLIENT_CERT;
1912
        }
1913
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1914
            state = WOLFSSL_SS_SERVER_CERT;
1915
        }
1916
        else {
1917
            WOLFSSL_MSG("Unknown State");
1918
            state = WOLFSSL_SS_NULL_STATE;
1919
        }
1920
        break;
1921
    case server_key_exchange:
1922
        state = WOLFSSL_SS_SERVER_KEYEXCHANGE;
1923
        break;
1924
    case certificate_request:
1925
        state = WOLFSSL_SS_SERVER_CERTREQUEST;
1926
        break;
1927
    case server_hello_done:
1928
        state = WOLFSSL_SS_SERVER_HELLODONE;
1929
        break;
1930
    case certificate_verify:
1931
        state = WOLFSSL_SS_CLIENT_CERTVERIFY;
1932
        break;
1933
    case client_key_exchange:
1934
        state = WOLFSSL_SS_CLIENT_KEYEXCHANGE;
1935
        break;
1936
    case finished:
1937
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1938
            state = WOLFSSL_SS_CLIENT_FINISHED;
1939
        }
1940
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1941
            state = WOLFSSL_SS_SERVER_FINISHED;
1942
        }
1943
        else {
1944
            WOLFSSL_MSG("Unknown State");
1945
            state = WOLFSSL_SS_NULL_STATE;
1946
        }
1947
        break;
1948
    case certificate_status:
1949
        state = WOLFSSL_SS_SERVER_CERTIFICATESTATUS;
1950
        break;
1951
    case key_update:
1952
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1953
            state = WOLFSSL_SS_CLIENT_KEYUPDATE;
1954
        }
1955
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1956
            state = WOLFSSL_SS_SERVER_KEYUPDATE;
1957
        }
1958
        else {
1959
            WOLFSSL_MSG("Unknown State");
1960
            state = WOLFSSL_SS_NULL_STATE;
1961
        }
1962
        break;
1963
    case change_cipher_hs:
1964
        if (ssl->options.side == WOLFSSL_SERVER_END) {
1965
            state = WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC;
1966
        }
1967
        else if (ssl->options.side == WOLFSSL_CLIENT_END) {
1968
            state = WOLFSSL_SS_SERVER_CHANGECIPHERSPEC;
1969
        }
1970
        else {
1971
            WOLFSSL_MSG("Unknown State");
1972
            state = WOLFSSL_SS_NULL_STATE;
1973
        }
1974
        break;
1975
    default:
1976
        WOLFSSL_MSG("Unknown State");
1977
        state = WOLFSSL_SS_NULL_STATE;
1978
    }
1979
1980
    return state;
1981
}
1982
1983
/* Map the handshake state reached while sending to a state string table index.
1984
 *
1985
 * @param [in] ssl  SSL/TLS object.
1986
 * @return  Index of the message in the state string table.
1987
 * @return  WOLFSSL_SS_NULL_STATE when the state is not recognized.
1988
 */
1989
static int wolfssl_state_string_send_state(const WOLFSSL* ssl)
1990
{
1991
    int state;
1992
1993
    if (ssl->options.side == WOLFSSL_SERVER_END) {
1994
        state = ssl->options.serverState;
1995
    }
1996
    else {
1997
        state = ssl->options.clientState;
1998
    }
1999
2000
    switch (state) {
2001
    case SERVER_HELLOVERIFYREQUEST_COMPLETE:
2002
        state = WOLFSSL_SS_SERVER_HELLOVERIFY;
2003
        break;
2004
    case SERVER_HELLO_RETRY_REQUEST_COMPLETE:
2005
        state = WOLFSSL_SS_SERVER_HELLORETRYREQUEST;
2006
        break;
2007
    case SERVER_HELLO_COMPLETE:
2008
        state = WOLFSSL_SS_SERVER_HELLO;
2009
        break;
2010
    case SERVER_ENCRYPTED_EXTENSIONS_COMPLETE:
2011
        state = WOLFSSL_SS_SERVER_ENCRYPTEDEXTENSIONS;
2012
        break;
2013
    case SERVER_CERT_COMPLETE:
2014
        state = WOLFSSL_SS_SERVER_CERT;
2015
        break;
2016
    case SERVER_KEYEXCHANGE_COMPLETE:
2017
        state = WOLFSSL_SS_SERVER_KEYEXCHANGE;
2018
        break;
2019
    case SERVER_HELLODONE_COMPLETE:
2020
        state = WOLFSSL_SS_SERVER_HELLODONE;
2021
        break;
2022
    case SERVER_CHANGECIPHERSPEC_COMPLETE:
2023
        state = WOLFSSL_SS_SERVER_CHANGECIPHERSPEC;
2024
        break;
2025
    case SERVER_FINISHED_COMPLETE:
2026
        state = WOLFSSL_SS_SERVER_FINISHED;
2027
        break;
2028
    case CLIENT_HELLO_RETRY:
2029
    case CLIENT_HELLO_COMPLETE:
2030
        state = WOLFSSL_SS_CLIENT_HELLO;
2031
        break;
2032
    case CLIENT_KEYEXCHANGE_COMPLETE:
2033
        state = WOLFSSL_SS_CLIENT_KEYEXCHANGE;
2034
        break;
2035
    case CLIENT_CHANGECIPHERSPEC_COMPLETE:
2036
        state = WOLFSSL_SS_CLIENT_CHANGECIPHERSPEC;
2037
        break;
2038
    case CLIENT_FINISHED_COMPLETE:
2039
        state = WOLFSSL_SS_CLIENT_FINISHED;
2040
        break;
2041
    case HANDSHAKE_DONE:
2042
        state = WOLFSSL_SS_HANDSHAKE_DONE;
2043
        break;
2044
    default:
2045
        WOLFSSL_MSG("Unknown State");
2046
        state = WOLFSSL_SS_NULL_STATE;
2047
    }
2048
2049
    return state;
2050
}
2051
2052
/* Get a human readable description of the current handshake state.
2053
 *
2054
 * The description names the protocol version, whether the last message was
2055
 * read or written, and the message itself.
2056
 *
2057
 * @param [in] ssl  SSL/TLS object.
2058
 * @return  A human readable string describing the state.
2059
 * @return  An empty string when the protocol version is not one this can
2060
 *          name, so the result is always safe to print.
2061
 * @return  NULL when ssl is NULL. That is the only case that returns NULL.
2062
 */
2063
const char* wolfSSL_state_string_long(const WOLFSSL* ssl)
2064
{
2065
    static const char* OUTPUT_STR[24][8][3] = {
2066
        STATE_STRINGS_PROTO("Initialization"),
2067
        STATE_STRINGS_PROTO_RW("Server Hello Request"),
2068
        STATE_STRINGS_PROTO_RW("Server Hello Verify Request"),
2069
        STATE_STRINGS_PROTO_RW("Server Hello Retry Request"),
2070
        STATE_STRINGS_PROTO_RW("Server Hello"),
2071
        STATE_STRINGS_PROTO_RW("Server Certificate Status"),
2072
        STATE_STRINGS_PROTO_RW("Server Encrypted Extensions"),
2073
        STATE_STRINGS_PROTO_RW("Server Session Ticket"),
2074
        STATE_STRINGS_PROTO_RW("Server Certificate Request"),
2075
        STATE_STRINGS_PROTO_RW("Server Cert"),
2076
        STATE_STRINGS_PROTO_RW("Server Key Exchange"),
2077
        STATE_STRINGS_PROTO_RW("Server Hello Done"),
2078
        STATE_STRINGS_PROTO_RW("Server Change CipherSpec"),
2079
        STATE_STRINGS_PROTO_RW("Server Finished"),
2080
        STATE_STRINGS_PROTO_RW("server Key Update"),
2081
        STATE_STRINGS_PROTO_RW("Client Hello"),
2082
        STATE_STRINGS_PROTO_RW("Client Key Exchange"),
2083
        STATE_STRINGS_PROTO_RW("Client Cert"),
2084
        STATE_STRINGS_PROTO_RW("Client Change CipherSpec"),
2085
        STATE_STRINGS_PROTO_RW("Client Certificate Verify"),
2086
        STATE_STRINGS_PROTO_RW("Client End Of Early Data"),
2087
        STATE_STRINGS_PROTO_RW("Client Finished"),
2088
        STATE_STRINGS_PROTO_RW("Client Key Update"),
2089
        STATE_STRINGS_PROTO("Handshake Done"),
2090
    };
2091
    int protocol;
2092
    int cbmode;
2093
    int state;
2094
    const char* ret = NULL;
2095
2096
    /* The three indices below come from enumerations declared at the top of
2097
     * this file, well away from the table they index. Adding an entry to one
2098
     * of them without adding the matching entry here is a build error rather
2099
     * than a read off the end of the table. */
2100
    wc_static_assert(XELEM_CNT(OUTPUT_STR) == WOLFSSL_SS_STATE_CNT);
2101
    wc_static_assert(XELEM_CNT(OUTPUT_STR[0]) == WOLFSSL_SS_PROTO_CNT);
2102
    wc_static_assert(XELEM_CNT(OUTPUT_STR[0][0]) == WOLFSSL_SS_IO_CNT);
2103
2104
    WOLFSSL_ENTER("wolfSSL_state_string_long");
2105
2106
    if (ssl == NULL) {
2107
        WOLFSSL_MSG("Null argument passed in");
2108
    }
2109
    else {
2110
        cbmode = wolfssl_state_string_io_mode(ssl);
2111
        protocol = wolfssl_state_string_protocol(ssl);
2112
2113
        if (ssl->cbmode == WOLFSSL_CB_MODE_READ) {
2114
            state = wolfssl_state_string_recv_state(ssl);
2115
        }
2116
        else {
2117
            state = wolfssl_state_string_send_state(ssl);
2118
        }
2119
2120
        if (protocol == WOLFSSL_SS_UNKNOWN) {
2121
            WOLFSSL_MSG("Unknown protocol");
2122
            ret = "";
2123
        }
2124
        else {
2125
            ret = OUTPUT_STR[state][protocol][cbmode];
2126
        }
2127
    }
2128
2129
    return ret;
2130
}
2131
2132
/* Only used by the table above, and this file is compiled into ssl.c,
2133
 * so do not leave them defined for the files included after it. */
2134
#undef STATE_STRINGS_PROTO
2135
#undef STATE_STRINGS_PROTO_RW
2136
#endif /* OPENSSL_EXTRA */
2137
2138
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) \
2139
    || defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY)
2140
2141
#ifndef NO_TLS
2142
/* Perform the handshake.
2143
 *
2144
 * Calls the connect or accept for the side of the object.
2145
 *
2146
 * @param [in, out] s  SSL/TLS object.
2147
 * @return  WOLFSSL_SUCCESS when the handshake completes.
2148
 * @return  WOLFSSL_FATAL_ERROR when the side is not set or the handshake
2149
 *          fails.
2150
 */
2151
int wolfSSL_SSL_do_handshake_internal(WOLFSSL *s)
2152
{
2153
    int ret;
2154
2155
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake_internal");
2156
2157
    if (s == NULL) {
2158
        ret = WOLFSSL_FAILURE;
2159
    }
2160
    else if (s->options.side == WOLFSSL_CLIENT_END) {
2161
        #ifndef NO_WOLFSSL_CLIENT
2162
        ret = wolfSSL_connect(s);
2163
        #else
2164
        WOLFSSL_MSG("Client not compiled in");
2165
        ret = WOLFSSL_FAILURE;
2166
        #endif
2167
    }
2168
    else {
2169
        #ifndef NO_WOLFSSL_SERVER
2170
        ret = wolfSSL_accept(s);
2171
        #else
2172
        WOLFSSL_MSG("Server not compiled in");
2173
        ret = WOLFSSL_FAILURE;
2174
        #endif
2175
    }
2176
2177
    return ret;
2178
}
2179
2180
/* Perform the handshake.
2181
 *
2182
 * @param [in, out] s  SSL/TLS object.
2183
 * @return  WOLFSSL_SUCCESS when the handshake completes.
2184
 * @return  WOLFSSL_FATAL_ERROR when the handshake fails. Call
2185
 *          wolfSSL_get_error() for the reason.
2186
 */
2187
int wolfSSL_SSL_do_handshake(WOLFSSL *s)
2188
{
2189
    int ret;
2190
2191
    WOLFSSL_ENTER("wolfSSL_SSL_do_handshake");
2192
2193
    #ifdef WOLFSSL_QUIC
2194
    if (WOLFSSL_IS_QUIC(s)) {
2195
        ret = wolfSSL_quic_do_handshake(s);
2196
    }
2197
    else
2198
    #endif
2199
    {
2200
        ret = wolfSSL_SSL_do_handshake_internal(s);
2201
    }
2202
2203
    return ret;
2204
}
2205
#endif /* !NO_TLS */
2206
2207
/* Determine whether the handshake has not completed.
2208
 *
2209
 * @param [in] ssl  SSL/TLS object.
2210
 * @return  1 when the handshake has not completed.
2211
 * @return  0 when the handshake has completed.
2212
 */
2213
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
2214
int wolfSSL_SSL_in_init(const WOLFSSL *ssl)
2215
#else
2216
int wolfSSL_SSL_in_init(WOLFSSL *ssl)
2217
#endif
2218
{
2219
    WOLFSSL_ENTER("wolfSSL_SSL_in_init");
2220
2221
    return !wolfSSL_is_init_finished(ssl);
2222
}
2223
2224
/* Determine whether the handshake has not started.
2225
 *
2226
 * @param [in] ssl  SSL/TLS object.
2227
 * @return  1 when the handshake has not started.
2228
 * @return  0 when the handshake has started or ssl is NULL.
2229
 */
2230
int wolfSSL_SSL_in_before(const WOLFSSL *ssl)
2231
{
2232
    int ret;
2233
2234
    WOLFSSL_ENTER("wolfSSL_SSL_in_before");
2235
2236
    if (ssl != NULL) {
2237
        ret = (ssl->options.handShakeState == NULL_STATE);
2238
    }
2239
    else {
2240
        ret = WOLFSSL_FAILURE;
2241
    }
2242
2243
    return ret;
2244
}
2245
2246
/* Determine whether the handshake is in progress.
2247
 *
2248
 * @param [in] ssl  SSL/TLS object.
2249
 * @return  1 when the handshake has started but not completed.
2250
 * @return  0 otherwise or when ssl is NULL.
2251
 */
2252
int wolfSSL_SSL_in_connect_init(WOLFSSL* ssl)
2253
{
2254
    int ret;
2255
2256
    WOLFSSL_ENTER("wolfSSL_SSL_in_connect_init");
2257
2258
    if (ssl != NULL) {
2259
        if (ssl->options.side == WOLFSSL_CLIENT_END) {
2260
            ret = (ssl->options.connectState > CONNECT_BEGIN) &&
2261
                  (ssl->options.connectState < SECOND_REPLY_DONE);
2262
        }
2263
        else {
2264
            ret = (ssl->options.acceptState > ACCEPT_BEGIN) &&
2265
                  (ssl->options.acceptState < ACCEPT_THIRD_REPLY_DONE);
2266
        }
2267
    }
2268
    else {
2269
        ret = WOLFSSL_FAILURE;
2270
    }
2271
2272
    return ret;
2273
}
2274
2275
#endif /* OPENSSL_ALL || WOLFSSL_NGINX || WOLFSSL_HAPROXY ||
2276
    OPENSSL_EXTRA || HAVE_LIGHTY */
2277
2278
2279
#ifndef NO_CERTS
2280
#ifdef  HAVE_PK_CALLBACKS
2281
2282
/* Set the premaster secret generation callback.
2283
 *
2284
 * @param [in, out] ctx  SSL/TLS CTX object.
2285
 * @param [in]      cb   Callback to call. NULL to clear.
2286
 */
2287
void  wolfSSL_CTX_SetGenPreMasterCb(WOLFSSL_CTX* ctx, CallbackGenPreMaster cb)
2288
{
2289
    if (ctx != NULL) {
2290
        ctx->GenPreMasterCb = cb;
2291
    }
2292
}
2293
/* Set the context to pass to the premaster secret generation callback.
2294
 *
2295
 * @param [in, out] ssl  SSL/TLS object.
2296
 * @param [in]      ctx  Context to pass to the callback.
2297
 */
2298
void  wolfSSL_SetGenPreMasterCtx(WOLFSSL* ssl, void *ctx)
2299
{
2300
    if (ssl != NULL) {
2301
        ssl->GenPreMasterCtx = ctx;
2302
    }
2303
}
2304
/* Get the context passed to the premaster secret generation callback.
2305
 *
2306
 * @param [in] ssl  SSL/TLS object.
2307
 * @return  Context on success.
2308
 * @return  NULL when ssl is NULL.
2309
 */
2310
void* wolfSSL_GetGenPreMasterCtx(WOLFSSL* ssl)
2311
{
2312
    void* ret = NULL;
2313
2314
    if (ssl != NULL) {
2315
        ret = ssl->GenPreMasterCtx;
2316
    }
2317
2318
    return ret;
2319
}
2320
2321
/* Set the master secret generation callback.
2322
 *
2323
 * @param [in, out] ctx  SSL/TLS CTX object.
2324
 * @param [in]      cb   Callback to call. NULL to clear.
2325
 */
2326
void  wolfSSL_CTX_SetGenMasterSecretCb(WOLFSSL_CTX* ctx,
2327
    CallbackGenMasterSecret cb)
2328
{
2329
    if (ctx != NULL) {
2330
        ctx->GenMasterCb = cb;
2331
    }
2332
}
2333
/* Set the context to pass to the master secret generation callback.
2334
 *
2335
 * @param [in, out] ssl  SSL/TLS object.
2336
 * @param [in]      ctx  Context to pass to the callback.
2337
 */
2338
void  wolfSSL_SetGenMasterSecretCtx(WOLFSSL* ssl, void *ctx)
2339
{
2340
    if (ssl != NULL) {
2341
        ssl->GenMasterCtx = ctx;
2342
    }
2343
}
2344
/* Get the context passed to the master secret generation callback.
2345
 *
2346
 * @param [in] ssl  SSL/TLS object.
2347
 * @return  Context on success.
2348
 * @return  NULL when ssl is NULL.
2349
 */
2350
void* wolfSSL_GetGenMasterSecretCtx(WOLFSSL* ssl)
2351
{
2352
    void* ret = NULL;
2353
2354
    if (ssl != NULL) {
2355
        ret = ssl->GenMasterCtx;
2356
    }
2357
2358
    return ret;
2359
}
2360
2361
/* Set the extended master secret generation callback.
2362
 *
2363
 * @param [in, out] ctx  SSL/TLS CTX object.
2364
 * @param [in]      cb   Callback to call. NULL to clear.
2365
 */
2366
void  wolfSSL_CTX_SetGenExtMasterSecretCb(WOLFSSL_CTX* ctx,
2367
    CallbackGenExtMasterSecret cb)
2368
{
2369
    if (ctx != NULL) {
2370
        ctx->GenExtMasterCb = cb;
2371
    }
2372
}
2373
/* Set the context to pass to the extended master secret generation callback.
2374
 *
2375
 * @param [in, out] ssl  SSL/TLS object.
2376
 * @param [in]      ctx  Context to pass to the callback.
2377
 */
2378
void  wolfSSL_SetGenExtMasterSecretCtx(WOLFSSL* ssl, void *ctx)
2379
{
2380
    if (ssl != NULL) {
2381
        ssl->GenExtMasterCtx = ctx;
2382
    }
2383
}
2384
/* Get the context passed to the extended master secret generation callback.
2385
 *
2386
 * @param [in] ssl  SSL/TLS object.
2387
 * @return  Context on success.
2388
 * @return  NULL when ssl is NULL.
2389
 */
2390
void* wolfSSL_GetGenExtMasterSecretCtx(WOLFSSL* ssl)
2391
{
2392
    void* ret = NULL;
2393
2394
    if (ssl != NULL) {
2395
        ret = ssl->GenExtMasterCtx;
2396
    }
2397
2398
    return ret;
2399
}
2400
2401
2402
/* Set the session key generation callback.
2403
 *
2404
 * @param [in, out] ctx  SSL/TLS CTX object.
2405
 * @param [in]      cb   Callback to call. NULL to clear.
2406
 */
2407
void  wolfSSL_CTX_SetGenSessionKeyCb(WOLFSSL_CTX* ctx, CallbackGenSessionKey cb)
2408
{
2409
    if (ctx != NULL) {
2410
        ctx->GenSessionKeyCb = cb;
2411
    }
2412
}
2413
/* Set the context to pass to the session key generation callback.
2414
 *
2415
 * @param [in, out] ssl  SSL/TLS object.
2416
 * @param [in]      ctx  Context to pass to the callback.
2417
 */
2418
void  wolfSSL_SetGenSessionKeyCtx(WOLFSSL* ssl, void *ctx)
2419
{
2420
    if (ssl != NULL) {
2421
        ssl->GenSessionKeyCtx = ctx;
2422
    }
2423
}
2424
/* Get the context passed to the session key generation callback.
2425
 *
2426
 * @param [in] ssl  SSL/TLS object.
2427
 * @return  Context on success.
2428
 * @return  NULL when ssl is NULL.
2429
 */
2430
void* wolfSSL_GetGenSessionKeyCtx(WOLFSSL* ssl)
2431
{
2432
    void* ret = NULL;
2433
2434
    if (ssl != NULL) {
2435
        ret = ssl->GenSessionKeyCtx;
2436
    }
2437
2438
    return ret;
2439
}
2440
2441
/* Set the encryption key setting callback.
2442
 *
2443
 * @param [in, out] ctx  SSL/TLS CTX object.
2444
 * @param [in]      cb   Callback to call. NULL to clear.
2445
 */
2446
void  wolfSSL_CTX_SetEncryptKeysCb(WOLFSSL_CTX* ctx, CallbackEncryptKeys cb)
2447
{
2448
    if (ctx != NULL) {
2449
        ctx->EncryptKeysCb = cb;
2450
    }
2451
}
2452
/* Set the context to pass to the encryption key setting callback.
2453
 *
2454
 * @param [in, out] ssl  SSL/TLS object.
2455
 * @param [in]      ctx  Context to pass to the callback.
2456
 */
2457
void  wolfSSL_SetEncryptKeysCtx(WOLFSSL* ssl, void *ctx)
2458
{
2459
    if (ssl != NULL) {
2460
        ssl->EncryptKeysCtx = ctx;
2461
    }
2462
}
2463
/* Get the context passed to the encryption key setting callback.
2464
 *
2465
 * @param [in] ssl  SSL/TLS object.
2466
 * @return  Context on success.
2467
 * @return  NULL when ssl is NULL.
2468
 */
2469
void* wolfSSL_GetEncryptKeysCtx(WOLFSSL* ssl)
2470
{
2471
    void* ret = NULL;
2472
2473
    if (ssl != NULL) {
2474
        ret = ssl->EncryptKeysCtx;
2475
    }
2476
2477
    return ret;
2478
}
2479
2480
/* Set the TLS Finished message building callback.
2481
 *
2482
 * @param [in, out] ctx  SSL/TLS CTX object.
2483
 * @param [in]      cb   Callback to call. NULL to clear.
2484
 */
2485
void  wolfSSL_CTX_SetTlsFinishedCb(WOLFSSL_CTX* ctx, CallbackTlsFinished cb)
2486
{
2487
    if (ctx != NULL) {
2488
        ctx->TlsFinishedCb = cb;
2489
    }
2490
}
2491
/* Set the context to pass to the TLS Finished message building callback.
2492
 *
2493
 * @param [in, out] ssl  SSL/TLS object.
2494
 * @param [in]      ctx  Context to pass to the callback.
2495
 */
2496
void  wolfSSL_SetTlsFinishedCtx(WOLFSSL* ssl, void *ctx)
2497
{
2498
    if (ssl != NULL) {
2499
        ssl->TlsFinishedCtx = ctx;
2500
    }
2501
}
2502
/* Get the context passed to the TLS Finished message building callback.
2503
 *
2504
 * @param [in] ssl  SSL/TLS object.
2505
 * @return  Context on success.
2506
 * @return  NULL when ssl is NULL.
2507
 */
2508
void* wolfSSL_GetTlsFinishedCtx(WOLFSSL* ssl)
2509
{
2510
    void* ret = NULL;
2511
2512
    if (ssl != NULL) {
2513
        ret = ssl->TlsFinishedCtx;
2514
    }
2515
2516
    return ret;
2517
}
2518
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
2519
/* Set the MAC verification callback.
2520
 *
2521
 * @param [in, out] ctx  SSL/TLS CTX object.
2522
 * @param [in]      cb   Callback to call. NULL to clear.
2523
 */
2524
void  wolfSSL_CTX_SetVerifyMacCb(WOLFSSL_CTX* ctx, CallbackVerifyMac cb)
2525
{
2526
    if (ctx != NULL) {
2527
        ctx->VerifyMacCb = cb;
2528
    }
2529
}
2530
2531
/* Set the context to pass to the MAC verification callback.
2532
 *
2533
 * @param [in, out] ssl  SSL/TLS object.
2534
 * @param [in]      ctx  Context to pass to the callback.
2535
 */
2536
void  wolfSSL_SetVerifyMacCtx(WOLFSSL* ssl, void *ctx)
2537
{
2538
    if (ssl != NULL) {
2539
        ssl->VerifyMacCtx = ctx;
2540
    }
2541
}
2542
/* Get the context passed to the MAC verification callback.
2543
 *
2544
 * @param [in] ssl  SSL/TLS object.
2545
 * @return  Context on success.
2546
 * @return  NULL when ssl is NULL.
2547
 */
2548
void* wolfSSL_GetVerifyMacCtx(WOLFSSL* ssl)
2549
{
2550
    void* ret = NULL;
2551
2552
    if (ssl != NULL) {
2553
        ret = ssl->VerifyMacCtx;
2554
    }
2555
2556
    return ret;
2557
}
2558
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
2559
2560
/* Set the HKDF expand label callback.
2561
 *
2562
 * @param [in, out] ctx  SSL/TLS CTX object.
2563
 * @param [in]      cb   Callback to call. NULL to clear.
2564
 */
2565
void wolfSSL_CTX_SetHKDFExpandLabelCb(WOLFSSL_CTX* ctx,
2566
                                      CallbackHKDFExpandLabel cb)
2567
{
2568
    if (ctx != NULL) {
2569
        ctx->HKDFExpandLabelCb = cb;
2570
    }
2571
}
2572
#ifdef WOLFSSL_PUBLIC_ASN
2573
/* Set the callback to call to process the peer's certificate.
2574
 *
2575
 * @param [in, out] ctx  SSL/TLS CTX object.
2576
 * @param [in]      cb   Callback to call. NULL to clear.
2577
 */
2578
void wolfSSL_CTX_SetProcessPeerCertCb(WOLFSSL_CTX* ctx,
2579
                                        CallbackProcessPeerCert cb)
2580
{
2581
    if (ctx != NULL) {
2582
        ctx->ProcessPeerCertCb = cb;
2583
    }
2584
}
2585
#endif /* WOLFSSL_PUBLIC_ASN */
2586
/* Set the callback to call to process the server's signature and key
2587
 * exchange.
2588
 *
2589
 * @param [in, out] ctx  SSL/TLS CTX object.
2590
 * @param [in]      cb   Callback to call. NULL to clear.
2591
 */
2592
void wolfSSL_CTX_SetProcessServerSigKexCb(WOLFSSL_CTX* ctx,
2593
                                       CallbackProcessServerSigKex cb)
2594
{
2595
    if (ctx != NULL) {
2596
        ctx->ProcessServerSigKexCb = cb;
2597
    }
2598
}
2599
/* Set the callback to call to encrypt and decrypt TLS records.
2600
 *
2601
 * @param [in, out] ctx  SSL/TLS CTX object.
2602
 * @param [in]      cb   Callback to call. NULL to clear.
2603
 */
2604
void wolfSSL_CTX_SetPerformTlsRecordProcessingCb(WOLFSSL_CTX* ctx,
2605
                                          CallbackPerformTlsRecordProcessing cb)
2606
{
2607
    if (ctx != NULL) {
2608
        ctx->PerformTlsRecordProcessingCb = cb;
2609
    }
2610
}
2611
#endif /* HAVE_PK_CALLBACKS */
2612
#endif /* NO_CERTS */
2613
2614
#if defined(HAVE_PK_CALLBACKS) && defined(HAVE_HKDF)
2615
2616
/* Set the callback to call to perform the HKDF extract operation.
2617
 *
2618
 * @param [in, out] ctx  SSL/TLS CTX object.
2619
 * @param [in]      cb   Callback to call. NULL to clear.
2620
 */
2621
void wolfSSL_CTX_SetHKDFExtractCb(WOLFSSL_CTX* ctx, CallbackHKDFExtract cb)
2622
{
2623
    if (ctx != NULL) {
2624
        ctx->HkdfExtractCb = cb;
2625
    }
2626
}
2627
2628
/* Set the context to pass to the HKDF extract callback.
2629
 *
2630
 * @param [in, out] ssl  SSL/TLS object.
2631
 * @param [in]      ctx  Context to pass to the callback.
2632
 */
2633
void wolfSSL_SetHKDFExtractCtx(WOLFSSL* ssl, void *ctx)
2634
{
2635
    if (ssl != NULL) {
2636
        ssl->HkdfExtractCtx = ctx;
2637
    }
2638
}
2639
2640
/* Get the context passed to the HKDF extract callback.
2641
 *
2642
 * @param [in] ssl  SSL/TLS object.
2643
 * @return  Context on success.
2644
 * @return  NULL when ssl is NULL.
2645
 */
2646
void* wolfSSL_GetHKDFExtractCtx(WOLFSSL* ssl)
2647
{
2648
    void* ret = NULL;
2649
2650
    if (ssl != NULL) {
2651
        ret = ssl->HkdfExtractCtx;
2652
    }
2653
2654
    return ret;
2655
}
2656
#endif /* HAVE_PK_CALLBACKS && HAVE_HKDF */
2657
2658
#endif /* !WOLFCRYPT_ONLY */
2659
2660
#endif /* !WOLFSSL_SSL_API_HS_INCLUDED */