Coverage Report

Created: 2026-11-12 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/suricata8/src/app-layer-ssl.c
Line
Count
Source
1
/* Copyright (C) 2007-2024 Open Information Security Foundation
2
 *
3
 * You can copy, redistribute or modify this Program under the terms of
4
 * the GNU General Public License version 2 as published by the Free
5
 * Software Foundation.
6
 *
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 * GNU General Public License for more details.
11
 *
12
 * You should have received a copy of the GNU General Public License
13
 * version 2 along with this program; if not, write to the Free Software
14
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15
 * 02110-1301, USA.
16
 */
17
18
/**
19
 * \file
20
 *
21
 * \author Anoop Saldanha <anoopsaldanha@gmail.com>
22
 * \author Pierre Chifflier <pierre.chifflier@ssi.gouv.fr>
23
 * \author Mats Klepsland <mats.klepsland@gmail.com>
24
 *
25
 */
26
27
#include "suricata-common.h"
28
#include "decode.h"
29
30
#include "app-layer.h"
31
#include "app-layer-detect-proto.h"
32
#include "app-layer-protos.h"
33
#include "app-layer-parser.h"
34
#include "app-layer-frames.h"
35
#include "app-layer-events.h"
36
#include "app-layer-ssl.h"
37
38
#include "conf.h"
39
40
#include "feature.h"
41
42
#include "util-debug.h"
43
#include "util-ja3.h"
44
#include "util-enum.h"
45
#include "util-validate.h"
46
47
static SCEnumCharMap tls_state_client_table[] = {
48
    {
49
            "client_in_progress",
50
            TLS_STATE_CLIENT_IN_PROGRESS,
51
    },
52
    {
53
            "client_hello_done",
54
            TLS_STATE_CLIENT_HELLO_DONE,
55
    },
56
    {
57
            "client_cert_done",
58
            TLS_STATE_CLIENT_CERT_DONE,
59
    },
60
    {
61
            "client_handshake_done",
62
            TLS_STATE_CLIENT_HANDSHAKE_DONE,
63
    },
64
    {
65
            "client_finished",
66
            TLS_STATE_CLIENT_FINISHED,
67
    },
68
    { NULL, -1 },
69
};
70
71
static SCEnumCharMap tls_state_server_table[] = {
72
    {
73
            "server_in_progress",
74
            TLS_STATE_SERVER_IN_PROGRESS,
75
    },
76
    {
77
            "server_hello",
78
            TLS_STATE_SERVER_HELLO,
79
    },
80
    {
81
            "server_cert_done",
82
            TLS_STATE_SERVER_CERT_DONE,
83
    },
84
    {
85
            "server_hello_done",
86
            TLS_STATE_SERVER_HELLO_DONE,
87
    },
88
    {
89
            "server_handshake_done",
90
            TLS_STATE_SERVER_HANDSHAKE_DONE,
91
    },
92
    {
93
            "server_finished",
94
            TLS_STATE_SERVER_FINISHED,
95
    },
96
    { NULL, -1 },
97
};
98
99
SCEnumCharMap tls_frame_table[] = {
100
    {
101
            "pdu",
102
            TLS_FRAME_PDU,
103
    },
104
    {
105
            "hdr",
106
            TLS_FRAME_HDR,
107
    },
108
    {
109
            "data",
110
            TLS_FRAME_DATA,
111
    },
112
    {
113
            "alert",
114
            TLS_FRAME_ALERT_DATA,
115
    },
116
    {
117
            "heartbeat",
118
            TLS_FRAME_HB_DATA,
119
    },
120
    {
121
            "ssl2.hdr",
122
            TLS_FRAME_SSLV2_HDR,
123
    },
124
    {
125
            "ssl2.pdu",
126
            TLS_FRAME_SSLV2_PDU,
127
    },
128
    { NULL, -1 },
129
};
130
131
SCEnumCharMap tls_decoder_event_table[] = {
132
    /* TLS protocol messages */
133
    { "INVALID_SSLV2_HEADER", TLS_DECODER_EVENT_INVALID_SSLV2_HEADER },
134
    { "INVALID_TLS_HEADER", TLS_DECODER_EVENT_INVALID_TLS_HEADER },
135
    { "INVALID_RECORD_VERSION", TLS_DECODER_EVENT_INVALID_RECORD_VERSION },
136
    { "INVALID_RECORD_TYPE", TLS_DECODER_EVENT_INVALID_RECORD_TYPE },
137
    { "INVALID_RECORD_LENGTH", TLS_DECODER_EVENT_INVALID_RECORD_LENGTH },
138
    { "INVALID_HANDSHAKE_MESSAGE", TLS_DECODER_EVENT_INVALID_HANDSHAKE_MESSAGE },
139
    { "HEARTBEAT_MESSAGE", TLS_DECODER_EVENT_HEARTBEAT },
140
    { "INVALID_HEARTBEAT_MESSAGE", TLS_DECODER_EVENT_INVALID_HEARTBEAT },
141
    { "OVERFLOW_HEARTBEAT_MESSAGE", TLS_DECODER_EVENT_OVERFLOW_HEARTBEAT },
142
    { "DATALEAK_HEARTBEAT_MISMATCH", TLS_DECODER_EVENT_DATALEAK_HEARTBEAT_MISMATCH },
143
    { "HANDSHAKE_INVALID_LENGTH", TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH },
144
    { "MULTIPLE_SNI_EXTENSIONS", TLS_DECODER_EVENT_MULTIPLE_SNI_EXTENSIONS },
145
    { "INVALID_SNI_TYPE", TLS_DECODER_EVENT_INVALID_SNI_TYPE },
146
    { "INVALID_SNI_LENGTH", TLS_DECODER_EVENT_INVALID_SNI_LENGTH },
147
    { "TOO_MANY_RECORDS_IN_PACKET", TLS_DECODER_EVENT_TOO_MANY_RECORDS_IN_PACKET },
148
    { "INVALID_ALERT_MESSAGE", TLS_DECODER_EVENT_INVALID_ALERT },
149
    /* certificate decoding messages */
150
    { "INVALID_CERTIFICATE", TLS_DECODER_EVENT_INVALID_CERTIFICATE },
151
    { "CERTIFICATE_INVALID_LENGTH", TLS_DECODER_EVENT_CERTIFICATE_INVALID_LENGTH },
152
    { "CERTIFICATE_INVALID_VERSION", TLS_DECODER_EVENT_CERTIFICATE_INVALID_VERSION },
153
    { "CERTIFICATE_INVALID_SERIAL", TLS_DECODER_EVENT_CERTIFICATE_INVALID_SERIAL },
154
    { "CERTIFICATE_INVALID_ALGORITHMIDENTIFIER",
155
            TLS_DECODER_EVENT_CERTIFICATE_INVALID_ALGORITHMIDENTIFIER },
156
    { "CERTIFICATE_INVALID_X509NAME", TLS_DECODER_EVENT_CERTIFICATE_INVALID_X509NAME },
157
    { "CERTIFICATE_INVALID_DATE", TLS_DECODER_EVENT_CERTIFICATE_INVALID_DATE },
158
    { "CERTIFICATE_INVALID_EXTENSIONS", TLS_DECODER_EVENT_CERTIFICATE_INVALID_EXTENSIONS },
159
    { "CERTIFICATE_INVALID_DER", TLS_DECODER_EVENT_CERTIFICATE_INVALID_DER },
160
    { "CERTIFICATE_INVALID_SUBJECT", TLS_DECODER_EVENT_CERTIFICATE_INVALID_SUBJECT },
161
    { "CERTIFICATE_INVALID_ISSUER", TLS_DECODER_EVENT_CERTIFICATE_INVALID_ISSUER },
162
    { "CERTIFICATE_INVALID_VALIDITY", TLS_DECODER_EVENT_CERTIFICATE_INVALID_VALIDITY },
163
    { "ERROR_MESSAGE_ENCOUNTERED", TLS_DECODER_EVENT_ERROR_MSG_ENCOUNTERED },
164
    { "TOO_MANY_SUBJECT_ALTERNATIVE_NAMES", TLS_DECODER_EVENT_TOO_MANY_SUBJECT_ALTERNATIVE_NAMES },
165
    /* used as a generic error event */
166
    { "INVALID_SSL_RECORD", TLS_DECODER_EVENT_INVALID_SSL_RECORD },
167
    { NULL, -1 },
168
};
169
170
enum {
171
    /* X.509 error codes, returned by decoder
172
     * THESE CONSTANTS MUST MATCH rust/src/x509/mod.rs ! */
173
    ERR_INVALID_CERTIFICATE=1,
174
    ERR_INVALID_LENGTH,
175
    ERR_INVALID_VERSION,
176
    ERR_INVALID_SERIAL,
177
    ERR_INVALID_ALGORITHMIDENTIFIER,
178
    ERR_INVALID_X509NAME,
179
    ERR_INVALID_DATE,
180
    ERR_INVALID_EXTENSIONS,
181
    ERR_INVALID_DER,
182
183
    /* error getting data */
184
    ERR_EXTRACT_SUBJECT,
185
    ERR_EXTRACT_ISSUER,
186
    ERR_EXTRACT_VALIDITY,
187
};
188
189
/* JA3 and JA4 fingerprints are disabled by default */
190
28
#define SSL_CONFIG_DEFAULT_JA3 0
191
#ifdef HAVE_JA4
192
28
#define SSL_CONFIG_DEFAULT_JA4 0
193
#endif
194
195
enum SslConfigEncryptHandling {
196
    SSL_CNF_ENC_HANDLE_TRACK_ONLY = 0, /**< disable raw content, continue tracking */
197
    SSL_CNF_ENC_HANDLE_BYPASS = 1,     /**< skip processing of flow, bypass if possible */
198
    SSL_CNF_ENC_HANDLE_FULL = 2,       /**< handle fully like any other proto */
199
};
200
201
typedef struct SslConfig_ {
202
    enum SslConfigEncryptHandling encrypt_mode;
203
    /** dynamic setting for ja3 and ja4: can be enabled on demand if not
204
     *  explicitly disabled. */
205
    SC_ATOMIC_DECLARE(int, enable_ja3);
206
    bool disable_ja3; /**< ja3 explicitly disabled. Don't enable on demand. */
207
    SC_ATOMIC_DECLARE(int, enable_ja4);
208
    bool disable_ja4; /**< ja4 explicitly disabled. Don't enable on demand. */
209
} SslConfig;
210
211
SslConfig ssl_config;
212
213
/* SSLv3 record types */
214
36.8k
#define SSLV3_CHANGE_CIPHER_SPEC       20
215
25.9k
#define SSLV3_ALERT_PROTOCOL           21
216
272k
#define SSLV3_HANDSHAKE_PROTOCOL       22
217
262k
#define SSLV3_APPLICATION_PROTOCOL     23
218
184k
#define SSLV3_HEARTBEAT_PROTOCOL       24
219
220
/* SSLv3 handshake protocol types */
221
113k
#define SSLV3_HS_HELLO_REQUEST          0
222
38.7k
#define SSLV3_HS_CLIENT_HELLO           1
223
53.6k
#define SSLV3_HS_SERVER_HELLO           2
224
104k
#define SSLV3_HS_NEW_SESSION_TICKET     4
225
67.5k
#define SSLV3_HS_CERTIFICATE           11
226
51.4k
#define SSLV3_HS_SERVER_KEY_EXCHANGE   12
227
102k
#define SSLV3_HS_CERTIFICATE_REQUEST   13
228
109k
#define SSLV3_HS_SERVER_HELLO_DONE     14
229
100k
#define SSLV3_HS_CERTIFICATE_VERIFY    15
230
55.3k
#define SSLV3_HS_CLIENT_KEY_EXCHANGE   16
231
101k
#define SSLV3_HS_FINISHED              20
232
102k
#define SSLV3_HS_CERTIFICATE_URL       21
233
104k
#define SSLV3_HS_CERTIFICATE_STATUS    22
234
235
/* SSLv2 protocol message types */
236
832
#define SSLV2_MT_ERROR                  0
237
3.96k
#define SSLV2_MT_CLIENT_HELLO           1
238
738
#define SSLV2_MT_CLIENT_MASTER_KEY      2
239
26.4k
#define SSLV2_MT_CLIENT_FINISHED        3
240
1.09k
#define SSLV2_MT_SERVER_HELLO           4
241
3.31k
#define SSLV2_MT_SERVER_VERIFY          5
242
23.3k
#define SSLV2_MT_SERVER_FINISHED        6
243
27.0k
#define SSLV2_MT_REQUEST_CERTIFICATE    7
244
13.5k
#define SSLV2_MT_CLIENT_CERTIFICATE     8
245
246
3.22M
#define SSLV3_RECORD_HDR_LEN 5
247
/** max length according to RFC 5246 6.2.2 is 2^14 + 1024 */
248
179k
#define SSLV3_RECORD_MAX_LEN ((1 << 14) + 1024)
249
250
42.9k
#define SSLV3_CLIENT_HELLO_VERSION_LEN  2
251
40.7k
#define SSLV3_CLIENT_HELLO_RANDOM_LEN  32
252
253
/* TLS heartbeat protocol types */
254
5.21k
#define TLS_HB_REQUEST                  1
255
537
#define TLS_HB_RESPONSE                 2
256
257
#define SSL_RECORD_MINIMUM_LENGTH       6
258
259
930
#define SHA1_STRING_LENGTH             60
260
261
1.37M
#define HAS_SPACE(n) ((uint64_t)(input - initial_input) + (uint64_t)(n) <= (uint64_t)(input_len))
262
263
struct SSLDecoderResult {
264
    int retval;      // nr bytes consumed from input, or < 0 on error
265
    uint32_t needed; // more bytes needed
266
};
267
#define SSL_DECODER_ERROR(e)                                                                       \
268
1.54k
    (struct SSLDecoderResult)                                                                      \
269
1.54k
    {                                                                                              \
270
1.54k
        (e), 0                                                                                     \
271
1.54k
    }
272
#define SSL_DECODER_OK(c)                                                                          \
273
760k
    (struct SSLDecoderResult)                                                                      \
274
760k
    {                                                                                              \
275
760k
        (uint32_t)(c), 0                                                                           \
276
760k
    }
277
#define SSL_DECODER_INCOMPLETE(c, n)                                                               \
278
101k
    (struct SSLDecoderResult)                                                                      \
279
101k
    {                                                                                              \
280
101k
        (uint32_t)(c), (n)                                                                         \
281
101k
    }
282
283
static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size,
284
        const void *src, size_t src_offset, size_t src_size, size_t src_tocopy) WARN_UNUSED;
285
286
static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size,
287
        const void *src, size_t src_offset, size_t src_size, size_t src_tocopy)
288
63.3k
{
289
63.3k
    DEBUG_VALIDATE_BUG_ON(dst_offset >= dst_size);
290
63.3k
    DEBUG_VALIDATE_BUG_ON(src_offset >= src_size);
291
63.3k
    DEBUG_VALIDATE_BUG_ON(src_tocopy > (src_size - src_offset));
292
63.3k
    DEBUG_VALIDATE_BUG_ON(src_tocopy > (dst_size - dst_offset));
293
294
63.3k
    if (dst_offset < dst_size && src_offset < src_size &&
295
63.3k
        src_tocopy <= (src_size - src_offset) &&
296
63.3k
        src_tocopy <= (dst_size - dst_offset)) {
297
63.3k
        memcpy(dst + dst_offset, src + src_offset, src_tocopy);
298
63.3k
        return 0;
299
63.3k
    }
300
0
    return -1;
301
63.3k
}
302
303
#ifdef DEBUG_VALIDATION
304
#define ValidateRecordState(connp)                                              \
305
345k
    do {                                                                        \
306
345k
        DEBUG_VALIDATE_BUG_ON(((connp)->record_length + SSLV3_RECORD_HDR_LEN) < \
307
345k
                (connp)->bytes_processed);                                      \
308
345k
    } while(0);
309
#else
310
#define ValidateRecordState(...)
311
#endif
312
313
#define SSLParserHSReset(connp)                                                                    \
314
299k
    do {                                                                                           \
315
299k
        (connp)->handshake_type = 0;                                                               \
316
299k
        (connp)->message_length = 0;                                                               \
317
299k
    } while (0)
318
319
#define SSLParserReset(state)                       \
320
222k
    do {                                            \
321
222k
        SCLogDebug("resetting state");              \
322
222k
        (state)->curr_connp->bytes_processed = 0;   \
323
222k
        SSLParserHSReset((state)->curr_connp);      \
324
222k
    } while(0)
325
326
#define SSLSetEvent(ssl_state, event)                                                              \
327
208k
    do {                                                                                           \
328
208k
        SCLogDebug("setting event %u", (event));                                                   \
329
208k
        if ((ssl_state) == NULL) {                                                                 \
330
0
            SCLogDebug("could not set decoder event %u", event);                                   \
331
208k
        } else {                                                                                   \
332
208k
            AppLayerDecoderEventsSetEventRaw(&(ssl_state)->tx_data.events, (event));               \
333
208k
            (ssl_state)->events++;                                                                 \
334
208k
        }                                                                                          \
335
208k
    } while (0)
336
337
static void *SSLGetTx(void *state, uint64_t tx_id)
338
2.22M
{
339
2.22M
    SSLState *ssl_state = (SSLState *)state;
340
2.22M
    return ssl_state;
341
2.22M
}
342
343
static uint64_t SSLGetTxCnt(void *state)
344
3.61M
{
345
    /* single tx */
346
3.61M
    return 1;
347
3.61M
}
348
349
static void UpdateClientState(SSLState *ssl_state, enum TlsStateClient s)
350
14.8k
{
351
#ifdef DEBUG
352
    enum TlsStateClient old = ssl_state->client_state;
353
#endif
354
14.8k
    ssl_state->client_state = s;
355
#ifdef DEBUG
356
    SCLogDebug("toserver: state updated to %u from %u", s, old);
357
#endif
358
14.8k
}
359
360
static void UpdateServerState(SSLState *ssl_state, enum TlsStateServer s)
361
15.4k
{
362
#ifdef DEBUG
363
    enum TlsStateServer old = ssl_state->server_state;
364
#endif
365
15.4k
    ssl_state->server_state = s;
366
#ifdef DEBUG
367
    SCLogDebug("toclient: state updated to %u from %u", s, old);
368
#endif
369
15.4k
}
370
371
static int SSLGetAlstateProgress(void *tx, uint8_t direction)
372
3.21M
{
373
3.21M
    SSLState *ssl_state = (SSLState *)tx;
374
3.21M
    if (direction & STREAM_TOCLIENT) {
375
2.19M
        return ssl_state->server_state;
376
2.19M
    } else {
377
1.01M
        return ssl_state->client_state;
378
1.01M
    }
379
3.21M
}
380
381
static AppLayerTxData *SSLGetTxData(void *vtx)
382
6.15M
{
383
6.15M
    SSLState *ssl_state = (SSLState *)vtx;
384
6.15M
    return &ssl_state->tx_data;
385
6.15M
}
386
387
static AppLayerStateData *SSLGetStateData(void *vstate)
388
13.9k
{
389
13.9k
    SSLState *ssl_state = (SSLState *)vstate;
390
13.9k
    return &ssl_state->state_data;
391
13.9k
}
392
393
static void TlsDecodeHSCertificateErrSetEvent(SSLState *ssl_state, uint32_t err)
394
3.52k
{
395
3.52k
    switch(err) {
396
0
        case ERR_EXTRACT_VALIDITY:
397
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_VALIDITY);
398
0
            break;
399
0
        case ERR_EXTRACT_ISSUER:
400
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_ISSUER);
401
0
            break;
402
0
        case ERR_EXTRACT_SUBJECT:
403
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_SUBJECT);
404
0
            break;
405
358
        case ERR_INVALID_DER:
406
358
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_DER);
407
358
            break;
408
31
        case ERR_INVALID_EXTENSIONS:
409
31
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_EXTENSIONS);
410
31
            break;
411
171
        case ERR_INVALID_DATE:
412
171
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_DATE);
413
171
            break;
414
0
        case ERR_INVALID_X509NAME:
415
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_X509NAME);
416
0
            break;
417
12
        case ERR_INVALID_ALGORITHMIDENTIFIER:
418
12
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_ALGORITHMIDENTIFIER);
419
12
            break;
420
20
        case ERR_INVALID_SERIAL:
421
20
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_SERIAL);
422
20
            break;
423
18
        case ERR_INVALID_VERSION:
424
18
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_VERSION);
425
18
            break;
426
2.49k
        case ERR_INVALID_LENGTH:
427
2.49k
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_LENGTH);
428
2.49k
            break;
429
421
        case ERR_INVALID_CERTIFICATE:
430
421
        default:
431
421
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_CERTIFICATE);
432
421
            break;
433
3.52k
    }
434
3.52k
}
435
436
static inline int TlsDecodeHSCertificateFingerprint(
437
        SSLStateConnp *connp, const uint8_t *input, uint32_t cert_len)
438
930
{
439
930
    if (unlikely(connp->cert0_fingerprint != NULL))
440
0
        return 0;
441
442
930
    connp->cert0_fingerprint = SCCalloc(1, SHA1_STRING_LENGTH);
443
930
    if (connp->cert0_fingerprint == NULL)
444
0
        return -1;
445
446
930
    uint8_t hash[SC_SHA1_LEN];
447
930
    if (SCSha1HashBuffer(input, cert_len, hash, sizeof(hash)) == 1) {
448
930
        SCToHex_sep(
449
930
                (uint8_t *)connp->cert0_fingerprint, SHA1_STRING_LENGTH, ':', hash, SC_SHA1_LEN);
450
930
    }
451
930
    return 0;
452
930
}
453
454
static inline int TlsDecodeHSCertificateAddCertToChain(
455
        SSLStateConnp *connp, const uint8_t *input, uint32_t cert_len)
456
7.26k
{
457
7.26k
    SSLCertsChain *cert = SCCalloc(1, sizeof(SSLCertsChain));
458
7.26k
    if (cert == NULL)
459
0
        return -1;
460
461
7.26k
    cert->cert_data = (uint8_t *)input;
462
7.26k
    cert->cert_len = cert_len;
463
7.26k
    TAILQ_INSERT_TAIL(&connp->certs, cert, next);
464
465
7.26k
    return 0;
466
7.26k
}
467
468
static int TlsDecodeHSCertificate(SSLState *ssl_state, SSLStateConnp *connp,
469
        const uint8_t *const initial_input, const uint32_t input_len, const int certn)
470
3.08k
{
471
3.08k
    const uint8_t *input = (uint8_t *)initial_input;
472
3.08k
    uint32_t err_code = 0;
473
3.08k
    X509 *x509 = NULL;
474
3.08k
    int rc = 0;
475
476
3.08k
    if (!(HAS_SPACE(3)))
477
9
        goto invalid_cert;
478
479
3.07k
    uint32_t cert_len = *input << 16 | *(input + 1) << 8 | *(input + 2);
480
3.07k
    input += 3;
481
482
3.07k
    if (!(HAS_SPACE(cert_len)))
483
181
        goto invalid_cert;
484
485
    /* only store fields from the first certificate in the chain */
486
2.89k
    if (certn == 0 && connp->cert0_subject == NULL && connp->cert0_issuerdn == NULL &&
487
2.01k
            connp->cert0_serial == NULL) {
488
2.01k
        x509 = SCX509Decode(input, cert_len, &err_code);
489
2.01k
        if (x509 == NULL) {
490
1.08k
            TlsDecodeHSCertificateErrSetEvent(ssl_state, err_code);
491
1.08k
            goto next;
492
1.08k
        }
493
494
930
        SCX509GetSubject(x509, &connp->cert0_subject, &connp->cert0_subject_len);
495
930
        if (connp->cert0_subject == NULL) {
496
0
            err_code = ERR_EXTRACT_SUBJECT;
497
0
            goto error;
498
0
        }
499
500
930
        SCX509GetIssuer(x509, &connp->cert0_issuerdn, &connp->cert0_issuerdn_len);
501
930
        if (connp->cert0_issuerdn == NULL) {
502
0
            err_code = ERR_EXTRACT_ISSUER;
503
0
            goto error;
504
0
        }
505
506
930
        connp->cert0_sans_num = SCX509GetSubjectAltNameLen(x509);
507
930
        if (connp->cert0_sans_num == TLS_MAX_SAN) {
508
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_TOO_MANY_SUBJECT_ALTERNATIVE_NAMES);
509
0
        }
510
930
        connp->cert0_sans = SCCalloc(connp->cert0_sans_num, sizeof(SSLSubjectAltName));
511
930
        if (connp->cert0_sans == NULL) {
512
0
            connp->cert0_sans_num = 0;
513
0
            goto error;
514
0
        }
515
17.8k
        for (uint16_t i = 0; i < connp->cert0_sans_num; i++) {
516
16.9k
            SCX509GetSubjectAltNameAt(
517
16.9k
                    x509, i, &connp->cert0_sans[i].san, &connp->cert0_sans[i].san_len);
518
16.9k
        }
519
520
930
        SCX509GetSerial(x509, &connp->cert0_serial, &connp->cert0_serial_len);
521
930
        if (connp->cert0_serial == NULL) {
522
0
            err_code = ERR_INVALID_SERIAL;
523
0
            goto error;
524
0
        }
525
526
930
        rc = SCX509GetValidity(x509, &connp->cert0_not_before, &connp->cert0_not_after);
527
930
        if (rc != 0) {
528
0
            err_code = ERR_EXTRACT_VALIDITY;
529
0
            goto error;
530
0
        }
531
532
930
        SCX509Free(x509);
533
930
        x509 = NULL;
534
535
930
        rc = TlsDecodeHSCertificateFingerprint(connp, input, cert_len);
536
930
        if (rc != 0) {
537
0
            SCLogDebug("TlsDecodeHSCertificateFingerprint failed with %d", rc);
538
0
            goto error;
539
0
        }
540
930
    }
541
542
1.81k
    rc = TlsDecodeHSCertificateAddCertToChain(connp, input, cert_len);
543
1.81k
    if (rc != 0) {
544
0
        SCLogDebug("TlsDecodeHSCertificateAddCertToChain failed with %d", rc);
545
0
        goto error;
546
0
    }
547
548
2.89k
next:
549
2.89k
    input += cert_len;
550
2.89k
    return (int)(input - initial_input);
551
552
0
error:
553
0
    if (err_code != 0)
554
0
        TlsDecodeHSCertificateErrSetEvent(ssl_state, err_code);
555
0
    if (x509 != NULL)
556
0
        SCX509Free(x509);
557
558
0
    return -1;
559
560
190
invalid_cert:
561
190
    SCLogDebug("TLS invalid certificate");
562
190
    SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_CERTIFICATE);
563
190
    return -1;
564
1.81k
}
565
566
/** \internal
567
 * \brief parse cert data in a certificate handshake message
568
 *        will be called with all data.
569
 * \retval consumed bytes consumed or -1 on error
570
 */
571
static int TlsDecodeHSCertificates(SSLState *ssl_state, SSLStateConnp *connp,
572
        const uint8_t *const initial_input, const uint32_t input_len)
573
1.97k
{
574
1.97k
    const uint8_t *input = (uint8_t *)initial_input;
575
576
1.97k
    if (!(HAS_SPACE(3)))
577
79
        return -1;
578
579
1.89k
    const uint32_t cert_chain_len = *input << 16 | *(input + 1) << 8 | *(input + 2);
580
1.89k
    input += 3;
581
582
1.89k
    if (!(HAS_SPACE(cert_chain_len)))
583
254
        return -1;
584
585
1.64k
    if (connp->certs_buffer != NULL) {
586
        // TODO should we set an event here?
587
487
        return -1;
588
487
    }
589
590
1.15k
    connp->certs_buffer = SCCalloc(1, cert_chain_len);
591
1.15k
    if (connp->certs_buffer == NULL) {
592
0
        return -1;
593
0
    }
594
1.15k
    connp->certs_buffer_size = cert_chain_len;
595
1.15k
    memcpy(connp->certs_buffer, input, cert_chain_len);
596
597
1.15k
    int cert_cnt = 0;
598
1.15k
    uint32_t processed_len = 0;
599
    /* coverity[tainted_data] */
600
4.04k
    while (processed_len < cert_chain_len) {
601
3.08k
        int rc = TlsDecodeHSCertificate(ssl_state, connp, connp->certs_buffer + processed_len,
602
3.08k
                connp->certs_buffer_size - processed_len, cert_cnt);
603
3.08k
        if (rc <= 0) { // 0 should be impossible, but lets be defensive
604
190
            return -1;
605
190
        }
606
2.89k
        DEBUG_VALIDATE_BUG_ON(processed_len + (uint32_t)rc > cert_chain_len);
607
2.89k
        if (processed_len + (uint32_t)rc > cert_chain_len) {
608
0
            return -1;
609
0
        }
610
611
2.89k
        processed_len += (uint32_t)rc;
612
2.89k
    }
613
614
965
    return processed_len + 3;
615
1.15k
}
616
617
/**
618
 * \inline
619
 * \brief Check if value is GREASE.
620
 *
621
 * http://tools.ietf.org/html/draft-davidben-tls-grease-00
622
 *
623
 * \param value Value to check.
624
 *
625
 * \retval 1 if is GREASE.
626
 * \retval 0 if not is GREASE.
627
 */
628
static inline int TLSDecodeValueIsGREASE(const uint16_t value)
629
658k
{
630
658k
    switch (value)
631
658k
    {
632
2.80k
        case 0x0a0a:
633
3.64k
        case 0x1a1a:
634
7.08k
        case 0x2a2a:
635
8.74k
        case 0x3a3a:
636
9.76k
        case 0x4a4a:
637
10.9k
        case 0x5a5a:
638
11.8k
        case 0x6a6a:
639
12.7k
        case 0x7a7a:
640
13.8k
        case 0x8a8a:
641
14.3k
        case 0x9a9a:
642
15.6k
        case 0xaaaa:
643
16.6k
        case 0xbaba:
644
17.5k
        case 0xcaca:
645
18.2k
        case 0xdada:
646
19.1k
        case 0xeaea:
647
20.7k
        case 0xfafa:
648
20.7k
            return 1;
649
637k
        default:
650
637k
            return 0;
651
658k
    }
652
658k
}
653
654
static inline int TLSDecodeHSHelloVersion(SSLState *ssl_state,
655
                                          const uint8_t * const initial_input,
656
                                          const uint32_t input_len)
657
47.4k
{
658
47.4k
    uint8_t *input = (uint8_t *)initial_input;
659
660
47.4k
    if (!(HAS_SPACE(SSLV3_CLIENT_HELLO_VERSION_LEN))) {
661
4.51k
        SCLogDebug("TLS handshake invalid length");
662
4.51k
        SSLSetEvent(ssl_state,
663
4.51k
                    TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
664
4.51k
        return -1;
665
4.51k
    }
666
667
42.9k
    uint16_t version = (uint16_t)(*input << 8) | *(input + 1);
668
42.9k
    ssl_state->curr_connp->version = version;
669
670
42.9k
    if (ssl_state->current_flags &
671
42.9k
            (SSL_AL_FLAG_STATE_CLIENT_HELLO | SSL_AL_FLAG_STATE_SERVER_HELLO)) {
672
42.9k
        SCTLSHandshakeSetTLSVersion(ssl_state->curr_connp->hs, version);
673
42.9k
    }
674
675
    /* TLSv1.3 draft1 to draft21 use the version field as earlier TLS
676
       versions, instead of using the supported versions extension. */
677
42.9k
    if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) &&
678
14.8k
            ((ssl_state->curr_connp->version == TLS_VERSION_13) ||
679
14.7k
            (((ssl_state->curr_connp->version >> 8) & 0xff) == 0x7f))) {
680
903
        ssl_state->flags |= SSL_AL_FLAG_LOG_WITHOUT_CERT;
681
903
    }
682
683
    /* Catch some early TLSv1.3 draft implementations that does not conform
684
       to the draft version. */
685
42.9k
    if ((ssl_state->curr_connp->version >= 0x7f01) &&
686
2.72k
            (ssl_state->curr_connp->version < 0x7f10)) {
687
281
        ssl_state->curr_connp->version = TLS_VERSION_13_PRE_DRAFT16;
688
281
    }
689
690
    /* TLSv1.3 drafts from draft1 to draft15 use 0x0304 (TLSv1.3) as the
691
       version number, which makes it hard to accurately pinpoint the
692
       exact draft version. */
693
42.6k
    else if (ssl_state->curr_connp->version == TLS_VERSION_13) {
694
237
        ssl_state->curr_connp->version = TLS_VERSION_13_PRE_DRAFT16;
695
237
    }
696
697
42.9k
    if (SC_ATOMIC_GET(ssl_config.enable_ja3) && ssl_state->curr_connp->ja3_str == NULL) {
698
16.8k
        ssl_state->curr_connp->ja3_str = Ja3BufferInit();
699
16.8k
        if (ssl_state->curr_connp->ja3_str == NULL)
700
0
            return -1;
701
702
16.8k
        int rc = Ja3BufferAddValue(&ssl_state->curr_connp->ja3_str, version);
703
16.8k
        if (rc != 0)
704
0
            return -1;
705
16.8k
    }
706
707
42.9k
    input += SSLV3_CLIENT_HELLO_VERSION_LEN;
708
709
42.9k
    return (int)(input - initial_input);
710
42.9k
}
711
712
static inline int TLSDecodeHSHelloRandom(SSLState *ssl_state,
713
                                         const uint8_t * const initial_input,
714
                                         const uint32_t input_len)
715
42.9k
{
716
42.9k
    uint8_t *input = (uint8_t *)initial_input;
717
718
42.9k
    if (!(HAS_SPACE(SSLV3_CLIENT_HELLO_RANDOM_LEN))) {
719
2.19k
        SCLogDebug("TLS handshake invalid length");
720
2.19k
        SSLSetEvent(ssl_state,
721
2.19k
                    TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
722
2.19k
        return -1;
723
2.19k
    }
724
725
40.7k
    if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) {
726
12.9k
        memcpy(ssl_state->server_connp.random, input, TLS_RANDOM_LEN);
727
12.9k
        ssl_state->flags |= TLS_TS_RANDOM_SET;
728
27.7k
    } else if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
729
27.7k
        memcpy(ssl_state->client_connp.random, input, TLS_RANDOM_LEN);
730
27.7k
        ssl_state->flags |= TLS_TC_RANDOM_SET;
731
27.7k
    }
732
733
    /* Skip random */
734
40.7k
    input += SSLV3_CLIENT_HELLO_RANDOM_LEN;
735
736
40.7k
    return (int)(input - initial_input);
737
42.9k
}
738
739
static inline int TLSDecodeHSHelloSessionID(SSLState *ssl_state,
740
                                            const uint8_t * const initial_input,
741
                                            const uint32_t input_len)
742
40.4k
{
743
40.4k
    uint8_t *input = (uint8_t *)initial_input;
744
745
40.4k
    if (!(HAS_SPACE(1)))
746
207
        goto invalid_length;
747
748
40.2k
    uint8_t session_id_length = *input;
749
40.2k
    input += 1;
750
751
40.2k
    if (!(HAS_SPACE(session_id_length)))
752
1.88k
        goto invalid_length;
753
754
38.3k
    if (session_id_length != 0 && ssl_state->curr_connp->session_id == NULL) {
755
10.6k
        ssl_state->curr_connp->session_id = SCMalloc(session_id_length);
756
757
10.6k
        if (unlikely(ssl_state->curr_connp->session_id == NULL)) {
758
0
            return -1;
759
0
        }
760
761
10.6k
        if (SafeMemcpy(ssl_state->curr_connp->session_id, 0, session_id_length,
762
10.6k
                    input, 0, input_len, session_id_length) != 0) {
763
0
            return -1;
764
0
        }
765
10.6k
        ssl_state->curr_connp->session_id_length = session_id_length;
766
767
10.6k
        if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) &&
768
5.40k
                ssl_state->client_connp.session_id != NULL &&
769
4.40k
                ssl_state->server_connp.session_id != NULL) {
770
3.24k
            if ((ssl_state->client_connp.session_id_length ==
771
3.24k
                    ssl_state->server_connp.session_id_length) &&
772
3.17k
                    (memcmp(ssl_state->server_connp.session_id,
773
3.17k
                    ssl_state->client_connp.session_id, session_id_length) == 0)) {
774
2.09k
                ssl_state->flags |= SSL_AL_FLAG_SESSION_RESUMED;
775
2.09k
            }
776
3.24k
        }
777
10.6k
    }
778
779
38.3k
    input += session_id_length;
780
781
38.3k
    return (int)(input - initial_input);
782
783
2.09k
invalid_length:
784
2.09k
    SCLogDebug("TLS handshake invalid length");
785
2.09k
    SSLSetEvent(ssl_state,
786
2.09k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
787
2.09k
    return -1;
788
38.3k
}
789
790
static inline int TLSDecodeHSHelloCipherSuites(SSLState *ssl_state,
791
                                           const uint8_t * const initial_input,
792
                                           const uint32_t input_len)
793
38.6k
{
794
38.6k
    const uint8_t *input = initial_input;
795
796
38.6k
    if (!(HAS_SPACE(2)))
797
915
        goto invalid_length;
798
799
37.7k
    uint16_t cipher_suites_length;
800
801
37.7k
    if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) {
802
11.6k
        cipher_suites_length = 2;
803
26.0k
    } else if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
804
26.0k
        cipher_suites_length = (uint16_t)(*input << 8) | *(input + 1);
805
26.0k
        input += 2;
806
26.0k
    } else {
807
0
        return -1;
808
0
    }
809
810
37.7k
    if (!(HAS_SPACE(cipher_suites_length)))
811
1.30k
        goto invalid_length;
812
813
    /* Cipher suites length should always be divisible by 2 */
814
36.4k
    if ((cipher_suites_length % 2) != 0) {
815
727
        goto invalid_length;
816
727
    }
817
818
35.7k
    const bool enable_ja3 =
819
35.7k
            SC_ATOMIC_GET(ssl_config.enable_ja3) && ssl_state->curr_connp->ja3_hash == NULL;
820
821
35.7k
    JA3Buffer *ja3_cipher_suites = NULL;
822
823
35.7k
    if (enable_ja3) {
824
16.9k
        ja3_cipher_suites = Ja3BufferInit();
825
16.9k
        if (ja3_cipher_suites == NULL)
826
0
            return -1;
827
16.9k
    }
828
829
35.7k
    uint16_t processed_len = 0;
830
    /* coverity[tainted_data] */
831
419k
    while (processed_len < cipher_suites_length) {
832
383k
        if (!(HAS_SPACE(2))) {
833
0
            if (enable_ja3) {
834
0
                Ja3BufferFree(&ja3_cipher_suites);
835
0
            }
836
0
            goto invalid_length;
837
0
        }
838
839
383k
        uint16_t cipher_suite = (uint16_t)(*input << 8) | *(input + 1);
840
383k
        input += 2;
841
842
383k
        if (TLSDecodeValueIsGREASE(cipher_suite) != 1) {
843
365k
            if (ssl_state->current_flags &
844
365k
                    (SSL_AL_FLAG_STATE_CLIENT_HELLO | SSL_AL_FLAG_STATE_SERVER_HELLO)) {
845
365k
                SCTLSHandshakeAddCipher(ssl_state->curr_connp->hs, cipher_suite);
846
365k
            }
847
365k
            if (enable_ja3) {
848
243k
                int rc = Ja3BufferAddValue(&ja3_cipher_suites, cipher_suite);
849
243k
                if (rc != 0) {
850
0
                    return -1;
851
0
                }
852
243k
            }
853
365k
        }
854
383k
        processed_len += 2;
855
383k
    }
856
857
35.7k
    if (enable_ja3) {
858
16.9k
        int rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, &ja3_cipher_suites);
859
16.9k
        if (rc == -1) {
860
0
            return -1;
861
0
        }
862
16.9k
    }
863
864
35.7k
    return (int)(input - initial_input);
865
866
2.94k
invalid_length:
867
2.94k
    SCLogDebug("TLS handshake invalid length");
868
2.94k
    SSLSetEvent(ssl_state,
869
2.94k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
870
2.94k
    return -1;
871
35.7k
}
872
873
static inline int TLSDecodeHSHelloCompressionMethods(SSLState *ssl_state,
874
                                           const uint8_t * const initial_input,
875
                                           const uint32_t input_len)
876
35.3k
{
877
35.3k
    const uint8_t *input = initial_input;
878
879
35.3k
    if (!(HAS_SPACE(1)))
880
559
        goto invalid_length;
881
882
    /* Skip compression methods */
883
34.8k
    if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) {
884
11.3k
        input += 1;
885
23.4k
    } else {
886
23.4k
        uint8_t compression_methods_length = *input;
887
23.4k
        input += 1;
888
889
23.4k
        if (!(HAS_SPACE(compression_methods_length)))
890
698
            goto invalid_length;
891
892
22.8k
        input += compression_methods_length;
893
22.8k
    }
894
895
34.1k
    return (int)(input - initial_input);
896
897
1.25k
invalid_length:
898
1.25k
    SCLogDebug("TLS handshake invalid_length");
899
1.25k
    SSLSetEvent(ssl_state,
900
1.25k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
901
1.25k
    return -1;
902
34.8k
}
903
904
static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state,
905
                                           const uint8_t * const initial_input,
906
                                           const uint32_t input_len)
907
28.5k
{
908
28.5k
    uint8_t *input = (uint8_t *)initial_input;
909
910
    /* Empty extension */
911
28.5k
    if (input_len == 0)
912
18.1k
        return 0;
913
914
10.3k
    if (!(HAS_SPACE(2)))
915
460
        goto invalid_length;
916
917
    /* Skip sni_list_length */
918
9.93k
    input += 2;
919
920
9.93k
    if (!(HAS_SPACE(1)))
921
529
        goto invalid_length;
922
923
9.40k
    uint8_t sni_type = *input;
924
9.40k
    input += 1;
925
926
    /* Currently the only type allowed is host_name
927
       (RFC6066 section 3). */
928
9.40k
    if (sni_type != SSL_SNI_TYPE_HOST_NAME) {
929
197
        SCLogDebug("Unknown SNI type");
930
197
        SSLSetEvent(ssl_state,
931
197
                TLS_DECODER_EVENT_INVALID_SNI_TYPE);
932
197
        return -1;
933
197
    }
934
935
9.20k
    if (!(HAS_SPACE(2)))
936
927
        goto invalid_length;
937
938
8.28k
    uint16_t sni_len = (uint16_t)(*input << 8) | *(input + 1);
939
8.28k
    input += 2;
940
941
    /* host_name contains the fully qualified domain name,
942
       and should therefore be limited by the maximum domain
943
       name length. */
944
8.28k
    if (!(HAS_SPACE(sni_len)) || sni_len > 255 || sni_len == 0) {
945
795
        SSLSetEvent(ssl_state,
946
795
                TLS_DECODER_EVENT_INVALID_SNI_LENGTH);
947
795
        return -1;
948
795
    }
949
950
    /* There must not be more than one extension of the same
951
       type (RFC5246 section 7.4.1.4). */
952
7.48k
    if (ssl_state->curr_connp->sni) {
953
493
        SCLogDebug("Multiple SNI extensions");
954
493
        SSLSetEvent(ssl_state,
955
493
                TLS_DECODER_EVENT_MULTIPLE_SNI_EXTENSIONS);
956
493
        input += sni_len;
957
493
        return (int)(input - initial_input);
958
493
    }
959
960
6.99k
    ssl_state->curr_connp->sni_len = sni_len;
961
6.99k
    ssl_state->curr_connp->sni = SCMalloc(sni_len);
962
6.99k
    if (unlikely(ssl_state->curr_connp->sni == NULL))
963
0
        return -1;
964
965
6.99k
    const size_t consumed = input - initial_input;
966
6.99k
    if (SafeMemcpy(ssl_state->curr_connp->sni, 0, sni_len, initial_input, consumed, input_len,
967
6.99k
                sni_len) != 0) {
968
0
        SCFree(ssl_state->curr_connp->sni);
969
0
        ssl_state->curr_connp->sni = NULL;
970
0
        return -1;
971
0
    }
972
6.99k
    input += sni_len;
973
974
6.99k
    return (int)(input - initial_input);
975
976
1.91k
invalid_length:
977
1.91k
    SCLogDebug("TLS handshake invalid length");
978
1.91k
    SSLSetEvent(ssl_state,
979
1.91k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
980
981
982
1.91k
    return -1;
983
6.99k
}
984
985
static inline int TLSDecodeHSHelloExtensionSupportedVersions(SSLState *ssl_state,
986
                                             const uint8_t * const initial_input,
987
                                             const uint32_t input_len)
988
11.8k
{
989
11.8k
    const uint8_t *input = initial_input;
990
991
    /* Empty extension */
992
11.8k
    if (input_len == 0)
993
247
        return 0;
994
995
11.5k
    if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
996
10.5k
        if (!(HAS_SPACE(1)))
997
0
            goto invalid_length;
998
999
10.5k
        uint8_t supported_ver_len = *input;
1000
10.5k
        input += 1;
1001
1002
10.5k
        if (supported_ver_len < 2)
1003
243
            goto invalid_length;
1004
1005
10.3k
        if (!(HAS_SPACE(supported_ver_len)))
1006
533
            goto invalid_length;
1007
1008
        /* Use the first (and preferred) valid version as client version,
1009
         * skip over GREASE and other possible noise. */
1010
9.79k
        uint16_t i = 0;
1011
28.3k
        while (i + 1 < (uint16_t)supported_ver_len) {
1012
26.0k
            uint16_t ver = (uint16_t)(input[i] << 8) | input[i + 1];
1013
26.0k
            if (TLSVersionValid(ver)) {
1014
7.50k
                ssl_state->curr_connp->version = ver;
1015
7.50k
                SCTLSHandshakeSetTLSVersion(ssl_state->curr_connp->hs, ver);
1016
7.50k
                break;
1017
7.50k
            }
1018
18.5k
            i += 2;
1019
18.5k
        }
1020
1021
        /* Set a flag to indicate that we have seen this extension */
1022
9.79k
        ssl_state->flags |= SSL_AL_FLAG_CH_VERSION_EXTENSION;
1023
1024
9.79k
        input += supported_ver_len;
1025
9.79k
    }
1026
987
    else if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) {
1027
987
        if (!(HAS_SPACE(2)))
1028
707
            goto invalid_length;
1029
1030
280
        uint16_t ver = (uint16_t)(*input << 8) | *(input + 1);
1031
1032
280
        if ((ssl_state->flags & SSL_AL_FLAG_CH_VERSION_EXTENSION) &&
1033
228
                (ver > TLS_VERSION_12)) {
1034
226
            ssl_state->flags |= SSL_AL_FLAG_LOG_WITHOUT_CERT;
1035
226
        }
1036
1037
280
        ssl_state->curr_connp->version = ver;
1038
280
        input += 2;
1039
280
    }
1040
1041
10.0k
    return (int)(input - initial_input);
1042
1043
1.48k
invalid_length:
1044
1.48k
    SCLogDebug("TLS handshake invalid length");
1045
1.48k
    SSLSetEvent(ssl_state,
1046
1.48k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1047
1048
1.48k
    return -1;
1049
11.5k
}
1050
1051
static inline int TLSDecodeHSHelloExtensionEllipticCurves(SSLState *ssl_state,
1052
        const uint8_t *const initial_input, const uint32_t input_len,
1053
        JA3Buffer **ja3_elliptic_curves)
1054
8.50k
{
1055
8.50k
    const uint8_t *input = initial_input;
1056
1057
    /* Empty extension */
1058
8.50k
    if (input_len == 0)
1059
273
        return 0;
1060
1061
8.23k
    if (!(HAS_SPACE(2)))
1062
251
        goto invalid_length;
1063
1064
7.98k
    uint16_t elliptic_curves_len = (uint16_t)(*input << 8) | *(input + 1);
1065
7.98k
    input += 2;
1066
1067
7.98k
    if (!(HAS_SPACE(elliptic_curves_len)))
1068
123
        goto invalid_length;
1069
1070
7.85k
    if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) &&
1071
7.83k
            *ja3_elliptic_curves != NULL) {
1072
7.60k
        uint16_t ec_processed_len = 0;
1073
        /* coverity[tainted_data] */
1074
40.7k
        while (ec_processed_len < elliptic_curves_len)
1075
33.1k
        {
1076
33.1k
            if (!(HAS_SPACE(2)))
1077
3
                goto invalid_length;
1078
1079
33.1k
            uint16_t elliptic_curve = (uint16_t)(*input << 8) | *(input + 1);
1080
33.1k
            input += 2;
1081
1082
33.1k
            if (TLSDecodeValueIsGREASE(elliptic_curve) != 1) {
1083
32.6k
                int rc = Ja3BufferAddValue(ja3_elliptic_curves, elliptic_curve);
1084
32.6k
                if (rc != 0)
1085
0
                    return -1;
1086
32.6k
            }
1087
1088
33.1k
            ec_processed_len += 2;
1089
33.1k
        }
1090
1091
7.60k
    } else {
1092
        /* Skip elliptic curves */
1093
257
        input += elliptic_curves_len;
1094
257
    }
1095
1096
7.85k
    return (int)(input - initial_input);
1097
1098
377
invalid_length:
1099
377
    SCLogDebug("TLS handshake invalid length");
1100
377
    SSLSetEvent(ssl_state,
1101
377
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1102
1103
377
    return -1;
1104
7.85k
}
1105
1106
static inline int TLSDecodeHSHelloExtensionEllipticCurvePF(SSLState *ssl_state,
1107
        const uint8_t *const initial_input, const uint32_t input_len,
1108
        JA3Buffer **ja3_elliptic_curves_pf)
1109
11.9k
{
1110
11.9k
    const uint8_t *input = initial_input;
1111
1112
    /* Empty extension */
1113
11.9k
    if (input_len == 0)
1114
101
        return 0;
1115
1116
11.8k
    if (!(HAS_SPACE(1)))
1117
0
        goto invalid_length;
1118
1119
11.8k
    uint8_t ec_pf_len = *input;
1120
11.8k
    input += 1;
1121
1122
11.8k
    if (!(HAS_SPACE(ec_pf_len)))
1123
165
        goto invalid_length;
1124
1125
11.6k
    if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) &&
1126
8.27k
            *ja3_elliptic_curves_pf != NULL) {
1127
7.59k
        uint8_t ec_pf_processed_len = 0;
1128
        /* coverity[tainted_data] */
1129
16.8k
        while (ec_pf_processed_len < ec_pf_len)
1130
9.22k
        {
1131
9.22k
            uint8_t elliptic_curve_pf = *input;
1132
9.22k
            input += 1;
1133
1134
9.22k
            if (TLSDecodeValueIsGREASE(elliptic_curve_pf) != 1) {
1135
9.22k
                int rc = Ja3BufferAddValue(ja3_elliptic_curves_pf, elliptic_curve_pf);
1136
9.22k
                if (rc != 0)
1137
0
                    return -1;
1138
9.22k
            }
1139
1140
9.22k
            ec_pf_processed_len += 1;
1141
9.22k
        }
1142
1143
7.59k
    } else {
1144
        /* Skip elliptic curve point formats */
1145
4.07k
        input += ec_pf_len;
1146
4.07k
    }
1147
1148
11.6k
    return (int)(input - initial_input);
1149
1150
165
invalid_length:
1151
165
    SCLogDebug("TLS handshake invalid length");
1152
165
    SSLSetEvent(ssl_state,
1153
165
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1154
1155
165
    return -1;
1156
11.6k
}
1157
1158
static inline int TLSDecodeHSHelloExtensionSigAlgorithms(
1159
        SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len)
1160
6.65k
{
1161
6.65k
    const uint8_t *input = initial_input;
1162
1163
    /* Empty extension */
1164
6.65k
    if (input_len == 0)
1165
388
        return 0;
1166
1167
6.26k
    if (!(HAS_SPACE(2)))
1168
76
        goto invalid_length;
1169
1170
6.18k
    uint16_t sigalgo_len = (uint16_t)(*input << 8) | *(input + 1);
1171
6.18k
    input += 2;
1172
1173
    /* Signature algorithms length should always be divisible by 2 */
1174
6.18k
    if ((sigalgo_len % 2) != 0) {
1175
471
        goto invalid_length;
1176
471
    }
1177
1178
5.71k
    if (!(HAS_SPACE(sigalgo_len)))
1179
168
        goto invalid_length;
1180
1181
5.54k
    if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
1182
5.52k
        uint16_t sigalgo_processed_len = 0;
1183
59.6k
        while (sigalgo_processed_len < sigalgo_len) {
1184
54.1k
            uint16_t sigalgo = (uint16_t)(*input << 8) | *(input + 1);
1185
54.1k
            input += 2;
1186
54.1k
            sigalgo_processed_len += 2;
1187
1188
54.1k
            SCTLSHandshakeAddSigAlgo(ssl_state->curr_connp->hs, sigalgo);
1189
54.1k
        }
1190
5.52k
    } else {
1191
        /* Skip signature algorithms */
1192
20
        input += sigalgo_len;
1193
20
    }
1194
1195
5.54k
    return (int)(input - initial_input);
1196
1197
715
invalid_length:
1198
715
    SCLogDebug("Signature algorithm list invalid length");
1199
715
    SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1200
1201
715
    return -1;
1202
5.71k
}
1203
1204
static inline int TLSDecodeHSHelloExtensionALPN(
1205
        SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len)
1206
8.11k
{
1207
8.11k
    const uint8_t *input = initial_input;
1208
1209
    /* Empty extension */
1210
8.11k
    if (input_len == 0)
1211
304
        return 0;
1212
1213
7.80k
    if (!(HAS_SPACE(2)))
1214
428
        goto invalid_length;
1215
1216
7.37k
    uint16_t alpn_len = (uint16_t)(*input << 8) | *(input + 1);
1217
7.37k
    input += 2;
1218
1219
7.37k
    if (!(HAS_SPACE(alpn_len)))
1220
233
        goto invalid_length;
1221
1222
    /* We use 32 bits here to avoid potentially overflowing a value that
1223
       needs to be compared to an unsigned 16-bit value. */
1224
7.14k
    uint32_t alpn_processed_len = 0;
1225
18.4k
    while (alpn_processed_len < alpn_len) {
1226
11.6k
        uint8_t protolen = *input;
1227
11.6k
        input += 1;
1228
11.6k
        alpn_processed_len += 1;
1229
1230
11.6k
        if (!(HAS_SPACE(protolen)))
1231
249
            goto invalid_length;
1232
1233
        /* Check if reading another protolen bytes would exceed the
1234
           overall ALPN length; if so, skip and continue */
1235
11.4k
        if (alpn_processed_len + protolen > ((uint32_t)alpn_len)) {
1236
79
            input += alpn_len - alpn_processed_len;
1237
79
            break;
1238
79
        }
1239
11.3k
        SCTLSHandshakeAddALPN(ssl_state->curr_connp->hs, (const char *)input, protolen);
1240
1241
11.3k
        alpn_processed_len += protolen;
1242
11.3k
        input += protolen;
1243
11.3k
    }
1244
1245
6.89k
    return (int)(input - initial_input);
1246
1247
910
invalid_length:
1248
910
    SCLogDebug("ALPN list invalid length");
1249
910
    SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1250
1251
910
    return -1;
1252
7.14k
}
1253
1254
static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state,
1255
                                         const uint8_t * const initial_input,
1256
                                         const uint32_t input_len)
1257
34.4k
{
1258
34.4k
    const uint8_t *input = initial_input;
1259
1260
34.4k
    int ret;
1261
34.4k
    int rc;
1262
    // if ja3_hash is already computed, do not use new hello to augment ja3_str
1263
34.4k
    const bool ja3 =
1264
34.4k
            (SC_ATOMIC_GET(ssl_config.enable_ja3) == 1) && ssl_state->curr_connp->ja3_hash == NULL;
1265
1266
34.4k
    JA3Buffer *ja3_extensions = NULL;
1267
34.4k
    JA3Buffer *ja3_elliptic_curves = NULL;
1268
34.4k
    JA3Buffer *ja3_elliptic_curves_pf = NULL;
1269
1270
34.4k
    if (ja3) {
1271
16.7k
        ja3_extensions = Ja3BufferInit();
1272
16.7k
        if (ja3_extensions == NULL)
1273
0
            goto error;
1274
1275
16.7k
        if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
1276
8.54k
            ja3_elliptic_curves = Ja3BufferInit();
1277
8.54k
            if (ja3_elliptic_curves == NULL)
1278
0
                goto error;
1279
1280
8.54k
            ja3_elliptic_curves_pf = Ja3BufferInit();
1281
8.54k
            if (ja3_elliptic_curves_pf == NULL)
1282
0
                goto error;
1283
8.54k
        }
1284
16.7k
    }
1285
1286
    /* Extensions are optional (RFC5246 section 7.4.1.2) */
1287
34.4k
    if (!(HAS_SPACE(2)))
1288
1.09k
        goto end;
1289
1290
33.3k
    uint16_t extensions_len = (uint16_t)(*input << 8) | *(input + 1);
1291
33.3k
    input += 2;
1292
1293
33.3k
    if (!(HAS_SPACE(extensions_len)))
1294
1.70k
        goto invalid_length;
1295
1296
31.6k
    uint32_t processed_len = 0;
1297
    /* coverity[tainted_data] */
1298
165k
    while (processed_len < (uint32_t)extensions_len) {
1299
147k
        if (!(HAS_SPACE(2)))
1300
771
            goto invalid_length;
1301
1302
147k
        uint16_t ext_type = (uint16_t)(*input << 8) | *(input + 1);
1303
147k
        input += 2;
1304
1305
147k
        if (!(HAS_SPACE(2)))
1306
2.71k
            goto invalid_length;
1307
1308
144k
        uint16_t ext_len = (uint16_t)(*input << 8) | *(input + 1);
1309
144k
        input += 2;
1310
1311
144k
        if (!(HAS_SPACE(ext_len)))
1312
2.92k
            goto invalid_length;
1313
1314
141k
        if (processed_len + 4UL + (uint32_t)ext_len > (uint32_t)extensions_len)
1315
1.29k
            goto invalid_length;
1316
1317
140k
        switch (ext_type) {
1318
28.5k
            case SSL_EXTENSION_SNI:
1319
28.5k
            {
1320
                /* coverity[tainted_data] */
1321
28.5k
                ret = TLSDecodeHSHelloExtensionSni(ssl_state, input,
1322
28.5k
                                                   ext_len);
1323
28.5k
                if (ret < 0)
1324
2.90k
                    goto end;
1325
1326
25.6k
                input += ext_len;
1327
1328
25.6k
                break;
1329
28.5k
            }
1330
1331
8.50k
            case SSL_EXTENSION_ELLIPTIC_CURVES:
1332
8.50k
            {
1333
                /* coverity[tainted_data] */
1334
8.50k
                ret = TLSDecodeHSHelloExtensionEllipticCurves(
1335
8.50k
                        ssl_state, input, ext_len, &ja3_elliptic_curves);
1336
8.50k
                if (ret < 0)
1337
377
                    goto error;
1338
1339
8.12k
                input += ext_len;
1340
1341
8.12k
                break;
1342
8.50k
            }
1343
1344
11.9k
            case SSL_EXTENSION_EC_POINT_FORMATS:
1345
11.9k
            {
1346
                /* coverity[tainted_data] */
1347
11.9k
                ret = TLSDecodeHSHelloExtensionEllipticCurvePF(
1348
11.9k
                        ssl_state, input, ext_len, &ja3_elliptic_curves_pf);
1349
11.9k
                if (ret < 0)
1350
165
                    goto error;
1351
1352
11.7k
                input += ext_len;
1353
1354
11.7k
                break;
1355
11.9k
            }
1356
1357
6.65k
            case SSL_EXTENSION_SIGNATURE_ALGORITHMS: {
1358
                /* coverity[tainted_data] */
1359
6.65k
                ret = TLSDecodeHSHelloExtensionSigAlgorithms(ssl_state, input, ext_len);
1360
6.65k
                if (ret < 0)
1361
715
                    goto end;
1362
1363
5.93k
                input += ext_len;
1364
1365
5.93k
                break;
1366
6.65k
            }
1367
1368
8.11k
            case SSL_EXTENSION_ALPN: {
1369
                /* coverity[tainted_data] */
1370
8.11k
                ret = TLSDecodeHSHelloExtensionALPN(ssl_state, input, ext_len);
1371
8.11k
                if (ret < 0)
1372
910
                    goto end;
1373
1374
7.20k
                input += ext_len;
1375
1376
7.20k
                break;
1377
8.11k
            }
1378
1379
572
            case SSL_EXTENSION_EARLY_DATA:
1380
572
            {
1381
572
                if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
1382
                    /* Used by 0-RTT to indicate that encrypted data will
1383
                       be sent right after the ClientHello record. */
1384
394
                    ssl_state->flags |= SSL_AL_FLAG_EARLY_DATA;
1385
394
                }
1386
1387
572
                input += ext_len;
1388
1389
572
                break;
1390
8.11k
            }
1391
1392
11.8k
            case SSL_EXTENSION_SUPPORTED_VERSIONS:
1393
11.8k
            {
1394
11.8k
                ret = TLSDecodeHSHelloExtensionSupportedVersions(ssl_state, input,
1395
11.8k
                                                                 ext_len);
1396
11.8k
                if (ret < 0)
1397
1.48k
                    goto end;
1398
1399
10.3k
                input += ext_len;
1400
1401
10.3k
                break;
1402
11.8k
            }
1403
1404
9.40k
            case SSL_EXTENSION_SESSION_TICKET:
1405
9.40k
            {
1406
9.40k
                if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
1407
                    /* This has to be verified later on by checking if a
1408
                       certificate record has been sent by the server. */
1409
6.64k
                    ssl_state->flags |= SSL_AL_FLAG_SESSION_RESUMED;
1410
6.64k
                }
1411
1412
9.40k
                input += ext_len;
1413
1414
9.40k
                break;
1415
11.8k
            }
1416
1417
54.6k
            default:
1418
54.6k
            {
1419
54.6k
                input += ext_len;
1420
54.6k
                break;
1421
11.8k
            }
1422
140k
        }
1423
1424
133k
        if (ja3) {
1425
98.7k
            if (TLSDecodeValueIsGREASE(ext_type) != 1) {
1426
97.8k
                rc = Ja3BufferAddValue(&ja3_extensions, ext_type);
1427
97.8k
                if (rc != 0)
1428
0
                    goto error;
1429
97.8k
            }
1430
98.7k
        }
1431
1432
133k
        if (ssl_state->current_flags &
1433
133k
                (SSL_AL_FLAG_STATE_CLIENT_HELLO | SSL_AL_FLAG_STATE_SERVER_HELLO)) {
1434
133k
            if (TLSDecodeValueIsGREASE(ext_type) != 1) {
1435
132k
                SCTLSHandshakeAddExtension(ssl_state->curr_connp->hs, ext_type);
1436
132k
            }
1437
133k
        }
1438
1439
133k
        processed_len += (uint32_t)ext_len + 4UL;
1440
133k
    }
1441
1442
24.4k
end:
1443
24.4k
    if (ja3) {
1444
15.5k
        rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str,
1445
15.5k
                                   &ja3_extensions);
1446
15.5k
        if (rc == -1)
1447
0
            goto error;
1448
1449
15.5k
        if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) {
1450
7.78k
            rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str,
1451
7.78k
                                       &ja3_elliptic_curves);
1452
7.78k
            if (rc == -1)
1453
0
                goto error;
1454
1455
7.78k
            rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str,
1456
7.78k
                                       &ja3_elliptic_curves_pf);
1457
7.78k
            if (rc == -1)
1458
0
                goto error;
1459
7.78k
        }
1460
15.5k
    }
1461
1462
24.4k
    return (int)(input - initial_input);
1463
1464
9.41k
invalid_length:
1465
9.41k
    SCLogDebug("TLS handshake invalid length");
1466
9.41k
    SSLSetEvent(ssl_state,
1467
9.41k
                TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH);
1468
1469
9.95k
error:
1470
9.95k
    if (ja3_extensions != NULL)
1471
1.19k
        Ja3BufferFree(&ja3_extensions);
1472
9.95k
    if (ja3_elliptic_curves != NULL)
1473
760
        Ja3BufferFree(&ja3_elliptic_curves);
1474
9.95k
    if (ja3_elliptic_curves_pf != NULL)
1475
760
        Ja3BufferFree(&ja3_elliptic_curves_pf);
1476
1477
9.95k
    return -1;
1478
9.41k
}
1479
1480
static int TLSDecodeHandshakeHello(SSLState *ssl_state,
1481
                                   const uint8_t * const input,
1482
                                   const uint32_t input_len)
1483
14.0k
{
1484
14.0k
    int ret;
1485
14.0k
    uint32_t parsed = 0;
1486
1487
14.0k
    ret = TLSDecodeHSHelloVersion(ssl_state, input, input_len);
1488
14.0k
    if (ret < 0)
1489
2.51k
        goto end;
1490
1491
11.4k
    parsed += ret;
1492
1493
11.4k
    ret = TLSDecodeHSHelloRandom(ssl_state, input + parsed, input_len - parsed);
1494
11.4k
    if (ret < 0)
1495
965
        goto end;
1496
1497
10.5k
    parsed += ret;
1498
1499
    /* The session id field in the server hello record was removed in
1500
       TLSv1.3 draft1, but was readded in draft22. */
1501
10.5k
    if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) ||
1502
3.25k
            ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) &&
1503
10.4k
            ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) {
1504
10.4k
        ret = TLSDecodeHSHelloSessionID(ssl_state, input + parsed,
1505
10.4k
                                        input_len - parsed);
1506
10.4k
        if (ret < 0)
1507
201
            goto end;
1508
1509
10.2k
        parsed += ret;
1510
10.2k
    }
1511
1512
10.3k
    ret = TLSDecodeHSHelloCipherSuites(ssl_state, input + parsed,
1513
10.3k
                                       input_len - parsed);
1514
10.3k
    if (ret < 0)
1515
558
        goto end;
1516
1517
9.76k
    parsed += ret;
1518
1519
   /* The compression methods field in the server hello record was
1520
      removed in TLSv1.3 draft1, but was readded in draft22. */
1521
9.76k
   if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) ||
1522
2.67k
              ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) &&
1523
9.64k
              ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) {
1524
9.64k
        ret = TLSDecodeHSHelloCompressionMethods(ssl_state, input + parsed,
1525
9.64k
                                                 input_len - parsed);
1526
9.64k
        if (ret < 0)
1527
717
            goto end;
1528
1529
8.92k
        parsed += ret;
1530
8.92k
    }
1531
1532
9.04k
    ret = TLSDecodeHSHelloExtensions(ssl_state, input + parsed,
1533
9.04k
                                     input_len - parsed);
1534
9.04k
    if (ret < 0)
1535
2.20k
        goto end;
1536
1537
6.84k
    if (SC_ATOMIC_GET(ssl_config.enable_ja3) && ssl_state->curr_connp->ja3_hash == NULL) {
1538
3.64k
        ssl_state->curr_connp->ja3_hash = Ja3GenerateHash(ssl_state->curr_connp->ja3_str);
1539
3.64k
    }
1540
1541
6.84k
    if (ssl_state->curr_connp == &ssl_state->client_connp) {
1542
2.83k
        UpdateClientState(ssl_state, TLS_STATE_CLIENT_HELLO_DONE);
1543
4.01k
    } else {
1544
4.01k
        UpdateServerState(ssl_state, TLS_STATE_SERVER_HELLO);
1545
4.01k
    }
1546
14.0k
end:
1547
14.0k
    return 0;
1548
6.84k
}
1549
1550
#ifdef DEBUG_VALIDATION
1551
static inline bool
1552
RecordAlreadyProcessed(const SSLStateConnp *curr_connp)
1553
107k
{
1554
107k
    return ((curr_connp->record_length + SSLV3_RECORD_HDR_LEN) <
1555
107k
            curr_connp->bytes_processed);
1556
107k
}
1557
#endif
1558
1559
static inline int SSLv3ParseHandshakeTypeCertificate(SSLState *ssl_state, SSLStateConnp *connp,
1560
        const uint8_t *const initial_input, const uint32_t input_len)
1561
1.97k
{
1562
1.97k
    int rc = TlsDecodeHSCertificates(ssl_state, connp, initial_input, input_len);
1563
1.97k
    SCLogDebug("rc %d", rc);
1564
1.97k
    if (rc > 0) {
1565
965
        DEBUG_VALIDATE_BUG_ON(rc > (int)input_len);
1566
965
        SSLParserHSReset(connp);
1567
1.01k
    } else if (rc < 0) {
1568
1.01k
        SCLogDebug("error parsing cert, reset state");
1569
1.01k
        SSLParserHSReset(connp);
1570
        /* fall through to still consume the cert bytes */
1571
1.01k
    }
1572
1.97k
    if (connp == &ssl_state->client_connp) {
1573
785
        UpdateClientState(ssl_state, TLS_STATE_CLIENT_CERT_DONE);
1574
1.19k
    } else {
1575
1.19k
        UpdateServerState(ssl_state, TLS_STATE_SERVER_CERT_DONE);
1576
1.19k
    }
1577
1.97k
    return input_len;
1578
1.97k
}
1579
1580
static int SupportedHandshakeType(const uint8_t type)
1581
142k
{
1582
142k
    switch (type) {
1583
30.6k
        case SSLV3_HS_CLIENT_HELLO:
1584
47.8k
        case SSLV3_HS_SERVER_HELLO:
1585
50.7k
        case SSLV3_HS_SERVER_KEY_EXCHANGE:
1586
54.4k
        case SSLV3_HS_CLIENT_KEY_EXCHANGE:
1587
65.6k
        case SSLV3_HS_CERTIFICATE:
1588
96.9k
        case SSLV3_HS_HELLO_REQUEST:
1589
100k
        case SSLV3_HS_CERTIFICATE_REQUEST:
1590
100k
        case SSLV3_HS_CERTIFICATE_VERIFY:
1591
101k
        case SSLV3_HS_FINISHED:
1592
101k
        case SSLV3_HS_CERTIFICATE_URL:
1593
103k
        case SSLV3_HS_CERTIFICATE_STATUS:
1594
104k
        case SSLV3_HS_NEW_SESSION_TICKET:
1595
108k
        case SSLV3_HS_SERVER_HELLO_DONE:
1596
108k
            return true;
1597
0
            break;
1598
1599
34.0k
        default:
1600
34.0k
            return false;
1601
0
            break;
1602
142k
    }
1603
142k
}
1604
1605
/**
1606
 *  \param input_len length of bytes after record header. Can be 0 (e.g. for server hello done).
1607
 *  \retval parsed number of consumed bytes
1608
 *  \retval < 0 error
1609
 */
1610
static int SSLv3ParseHandshakeType(SSLState *ssl_state, const uint8_t *input,
1611
                                   uint32_t input_len, uint8_t direction)
1612
39.0k
{
1613
39.0k
    const uint8_t *initial_input = input;
1614
39.0k
    int rc;
1615
1616
39.0k
    DEBUG_VALIDATE_BUG_ON(RecordAlreadyProcessed(ssl_state->curr_connp));
1617
1618
39.0k
    switch (ssl_state->curr_connp->handshake_type) {
1619
8.11k
        case SSLV3_HS_CLIENT_HELLO:
1620
8.11k
            ssl_state->current_flags = SSL_AL_FLAG_STATE_CLIENT_HELLO;
1621
1622
8.11k
            rc = TLSDecodeHandshakeHello(ssl_state, input, input_len);
1623
8.11k
            if (rc < 0)
1624
0
                return rc;
1625
8.11k
            break;
1626
1627
8.11k
        case SSLV3_HS_SERVER_HELLO:
1628
5.88k
            ssl_state->current_flags = SSL_AL_FLAG_STATE_SERVER_HELLO;
1629
1630
5.88k
            DEBUG_VALIDATE_BUG_ON(ssl_state->curr_connp->message_length != input_len);
1631
5.88k
            rc = TLSDecodeHandshakeHello(ssl_state, input, input_len);
1632
5.88k
            if (rc < 0)
1633
0
                return rc;
1634
5.88k
            break;
1635
1636
5.88k
        case SSLV3_HS_SERVER_KEY_EXCHANGE:
1637
732
            ssl_state->current_flags = SSL_AL_FLAG_STATE_SERVER_KEYX;
1638
732
            break;
1639
1640
920
        case SSLV3_HS_CLIENT_KEY_EXCHANGE:
1641
920
            ssl_state->current_flags = SSL_AL_FLAG_STATE_CLIENT_KEYX;
1642
920
            break;
1643
1644
1.97k
        case SSLV3_HS_CERTIFICATE:
1645
1.97k
            rc = SSLv3ParseHandshakeTypeCertificate(ssl_state,
1646
1.97k
                    direction ? &ssl_state->server_connp : &ssl_state->client_connp, initial_input,
1647
1.97k
                    input_len);
1648
1.97k
            if (rc < 0)
1649
0
                return rc;
1650
1.97k
            break;
1651
1652
16.5k
        case SSLV3_HS_HELLO_REQUEST:
1653
16.5k
            break;
1654
1.96k
        case SSLV3_HS_CERTIFICATE_REQUEST:
1655
1.96k
            if (direction) {
1656
885
                ssl_state->current_flags = SSL_AL_FLAG_NEED_CLIENT_CERT;
1657
885
            }
1658
1.96k
            break;
1659
120
        case SSLV3_HS_CERTIFICATE_VERIFY:
1660
474
        case SSLV3_HS_FINISHED:
1661
618
        case SSLV3_HS_CERTIFICATE_URL:
1662
1.29k
        case SSLV3_HS_CERTIFICATE_STATUS:
1663
1.29k
            break;
1664
411
        case SSLV3_HS_NEW_SESSION_TICKET:
1665
411
            SCLogDebug("new session ticket");
1666
411
            break;
1667
1.18k
        case SSLV3_HS_SERVER_HELLO_DONE:
1668
1.18k
            if (direction) {
1669
917
                UpdateServerState(ssl_state, TLS_STATE_SERVER_HELLO_DONE);
1670
917
            }
1671
1.18k
            break;
1672
0
        default:
1673
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSL_RECORD);
1674
0
            return -1;
1675
39.0k
    }
1676
1677
39.0k
    ssl_state->flags |= ssl_state->current_flags;
1678
1679
39.0k
    SCLogDebug("message: length %u", ssl_state->curr_connp->message_length);
1680
39.0k
    SCLogDebug("input_len %u ssl_state->curr_connp->bytes_processed %u", input_len, ssl_state->curr_connp->bytes_processed);
1681
1682
39.0k
    return input_len;
1683
39.0k
}
1684
1685
static int SSLv3ParseHandshakeProtocol(SSLState *ssl_state, const uint8_t *input,
1686
                                       uint32_t input_len, uint8_t direction)
1687
37.5k
{
1688
37.5k
    const uint8_t *initial_input = input;
1689
1690
37.5k
    if (input_len == 0 || ssl_state->curr_connp->bytes_processed ==
1691
37.5k
            (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN)) {
1692
0
        SCReturnInt(0);
1693
0
    }
1694
1695
109k
    while (input_len) {
1696
74.8k
        SCLogDebug("input_len %u", input_len);
1697
1698
74.8k
        if (ssl_state->curr_connp->hs_buffer != NULL) {
1699
19.9k
            SCLogDebug("partial handshake record in place");
1700
19.9k
            const uint32_t need = ssl_state->curr_connp->hs_buffer_message_size -
1701
19.9k
                                  ssl_state->curr_connp->hs_buffer_offset;
1702
19.9k
            const uint32_t add = MIN(need, input_len);
1703
1704
            /* grow buffer to next multiple of 4k that fits all data we have */
1705
19.9k
            if (ssl_state->curr_connp->hs_buffer_offset + add >
1706
19.9k
                    ssl_state->curr_connp->hs_buffer_size) {
1707
267
                const uint32_t avail = ssl_state->curr_connp->hs_buffer_offset + add;
1708
267
                const uint32_t new_size = avail + (4096 - (avail % 4096));
1709
267
                SCLogDebug("new_size %u, avail %u", new_size, avail);
1710
267
                void *ptr = SCRealloc(ssl_state->curr_connp->hs_buffer, new_size);
1711
267
                if (ptr == NULL)
1712
0
                    return -1;
1713
267
                ssl_state->curr_connp->hs_buffer = ptr;
1714
267
                ssl_state->curr_connp->hs_buffer_size = new_size;
1715
267
            }
1716
1717
19.9k
            SCLogDebug("ssl_state->curr_connp->hs_buffer_offset %u "
1718
19.9k
                       "ssl_state->curr_connp->hs_buffer_size %u",
1719
19.9k
                    ssl_state->curr_connp->hs_buffer_offset, ssl_state->curr_connp->hs_buffer_size);
1720
19.9k
            SCLogDebug("to add %u total %u", add, ssl_state->curr_connp->hs_buffer_offset + add);
1721
1722
19.9k
            if (SafeMemcpy(ssl_state->curr_connp->hs_buffer,
1723
19.9k
                        ssl_state->curr_connp->hs_buffer_offset,
1724
19.9k
                        ssl_state->curr_connp->hs_buffer_size, input, 0, add, add) != 0) {
1725
0
                SCLogDebug("copy failed");
1726
0
                return -1;
1727
0
            }
1728
19.9k
            ssl_state->curr_connp->hs_buffer_offset += add;
1729
1730
19.9k
            if (ssl_state->curr_connp->hs_buffer_message_size <=
1731
19.9k
                    ssl_state->curr_connp->hs_buffer_offset) {
1732
1.30k
                DEBUG_VALIDATE_BUG_ON(ssl_state->curr_connp->hs_buffer_message_size !=
1733
1.30k
                                      ssl_state->curr_connp->hs_buffer_offset);
1734
1735
1.30k
                ssl_state->curr_connp->handshake_type =
1736
1.30k
                        ssl_state->curr_connp->hs_buffer_message_type;
1737
1.30k
                ssl_state->curr_connp->message_length =
1738
1.30k
                        ssl_state->curr_connp->hs_buffer_message_size;
1739
1740
1.30k
                SCLogDebug("got all data now: handshake_type %u message_length %u",
1741
1.30k
                        ssl_state->curr_connp->handshake_type,
1742
1.30k
                        ssl_state->curr_connp->message_length);
1743
1744
1.30k
                int retval = SSLv3ParseHandshakeType(ssl_state, ssl_state->curr_connp->hs_buffer,
1745
1.30k
                        ssl_state->curr_connp->hs_buffer_offset, direction);
1746
1.30k
                if (retval < 0) {
1747
0
                    SSLParserHSReset(ssl_state->curr_connp);
1748
0
                    return (retval);
1749
0
                }
1750
1.30k
                SCLogDebug("retval %d", retval);
1751
1752
                /* data processed, reset buffer */
1753
1.30k
                SCFree(ssl_state->curr_connp->hs_buffer);
1754
1.30k
                ssl_state->curr_connp->hs_buffer = NULL;
1755
1.30k
                ssl_state->curr_connp->hs_buffer_size = 0;
1756
1.30k
                ssl_state->curr_connp->hs_buffer_message_size = 0;
1757
1.30k
                ssl_state->curr_connp->hs_buffer_message_type = 0;
1758
1.30k
                ssl_state->curr_connp->hs_buffer_offset = 0;
1759
18.6k
            } else {
1760
18.6k
                SCLogDebug("partial data");
1761
18.6k
            }
1762
1763
19.9k
            input += add;
1764
19.9k
            input_len -= add;
1765
19.9k
            SCLogDebug("input_len %u", input_len);
1766
19.9k
            SSLParserHSReset(ssl_state->curr_connp);
1767
19.9k
            continue;
1768
19.9k
        }
1769
1770
54.9k
        SCLogDebug("bytes_processed %u", ssl_state->curr_connp->bytes_processed);
1771
54.9k
        SCLogDebug("input %p input_len %u", input, input_len);
1772
1773
54.9k
        const uint8_t *hs_hdr = input;
1774
54.9k
        if (input_len < 4 || ssl_state->curr_connp->hs_hdr_len > 0) {
1775
1.35k
            DEBUG_VALIDATE_BUG_ON(ssl_state->curr_connp->hs_hdr_len >= 4);
1776
1.35k
            uint32_t add = MIN(input_len, (uint32_t)(4 - ssl_state->curr_connp->hs_hdr_len));
1777
1.35k
            if (SafeMemcpy(ssl_state->curr_connp->hs_hdr, ssl_state->curr_connp->hs_hdr_len, 4,
1778
1.35k
                        input, 0, input_len, add) != 0) {
1779
0
                return -1;
1780
0
            }
1781
1.35k
            ssl_state->curr_connp->hs_hdr_len += add;
1782
1.35k
            input += add;
1783
1.35k
            input_len -= add;
1784
1.35k
            if (ssl_state->curr_connp->hs_hdr_len < 4) {
1785
                /* partial header received, not enough input len, return */
1786
919
                SSLParserHSReset(ssl_state->curr_connp);
1787
919
                return (int)(input - initial_input);
1788
919
            }
1789
432
            hs_hdr = ssl_state->curr_connp->hs_hdr;
1790
432
            ssl_state->curr_connp->hs_hdr_len = 0;
1791
53.5k
        } else {
1792
53.5k
            input += 4;
1793
53.5k
            input_len -= 4;
1794
53.5k
        }
1795
1796
54.0k
        ssl_state->curr_connp->handshake_type = hs_hdr[0];
1797
54.0k
        ssl_state->curr_connp->message_length = hs_hdr[1] << 16 | hs_hdr[2] << 8 | hs_hdr[3];
1798
54.0k
        SCLogDebug("handshake_type %u message len %u input %p input_len %u",
1799
54.0k
                ssl_state->curr_connp->handshake_type, ssl_state->curr_connp->message_length, input,
1800
54.0k
                input_len);
1801
1802
54.0k
        const uint32_t record_len = ssl_state->curr_connp->message_length;
1803
        /* see if we support this type. We check here to not use the fragment
1804
         * handling on things we don't support. */
1805
54.0k
        const bool supported_type = SupportedHandshakeType(ssl_state->curr_connp->handshake_type);
1806
54.0k
        SCLogDebug("supported_type %s handshake_type %u/%02x", supported_type ? "true" : "false",
1807
54.0k
                ssl_state->curr_connp->handshake_type, ssl_state->curr_connp->handshake_type);
1808
54.0k
        if (!supported_type) {
1809
14.2k
            uint32_t avail_record_len = MIN(input_len, record_len);
1810
14.2k
            input += avail_record_len;
1811
14.2k
            input_len -= avail_record_len;
1812
1813
14.2k
            SSLParserHSReset(ssl_state->curr_connp);
1814
1815
14.2k
            if ((direction && (ssl_state->flags & SSL_AL_FLAG_SERVER_CHANGE_CIPHER_SPEC)) ||
1816
14.1k
                    (!direction && (ssl_state->flags & SSL_AL_FLAG_CLIENT_CHANGE_CIPHER_SPEC))) {
1817
                // after Change Cipher Spec we get Encrypted Handshake Messages
1818
14.0k
            } else {
1819
14.0k
                SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HANDSHAKE_MESSAGE);
1820
14.0k
            }
1821
14.2k
            continue;
1822
14.2k
        }
1823
1824
        /* if the message length exceeds our input_len, we have a tls fragment. */
1825
39.7k
        if (record_len > input_len) {
1826
2.02k
            const uint32_t avail = input_len;
1827
2.02k
            const uint32_t size = avail + (4096 - (avail % 4096));
1828
2.02k
            SCLogDebug("initial buffer size %u, based on input %u", size, avail);
1829
2.02k
            ssl_state->curr_connp->hs_buffer = SCCalloc(1, size);
1830
2.02k
            if (ssl_state->curr_connp->hs_buffer == NULL) {
1831
0
                return -1;
1832
0
            }
1833
2.02k
            ssl_state->curr_connp->hs_buffer_size = size;
1834
2.02k
            ssl_state->curr_connp->hs_buffer_message_size = record_len;
1835
2.02k
            ssl_state->curr_connp->hs_buffer_message_type = ssl_state->curr_connp->handshake_type;
1836
1837
2.02k
            if (input_len > 0) {
1838
1.97k
                if (SafeMemcpy(ssl_state->curr_connp->hs_buffer, 0,
1839
1.97k
                            ssl_state->curr_connp->hs_buffer_size, input, 0, input_len,
1840
1.97k
                            input_len) != 0) {
1841
0
                    return -1;
1842
0
                }
1843
1.97k
                ssl_state->curr_connp->hs_buffer_offset = input_len;
1844
1.97k
            }
1845
2.02k
            SCLogDebug("opened record buffer %p size %u offset %u type %u msg_size %u",
1846
2.02k
                    ssl_state->curr_connp->hs_buffer, ssl_state->curr_connp->hs_buffer_size,
1847
2.02k
                    ssl_state->curr_connp->hs_buffer_offset,
1848
2.02k
                    ssl_state->curr_connp->hs_buffer_message_type,
1849
2.02k
                    ssl_state->curr_connp->hs_buffer_message_size);
1850
2.02k
            input += input_len;
1851
2.02k
            SSLParserHSReset(ssl_state->curr_connp);
1852
2.02k
            return (int)(input - initial_input);
1853
1854
37.7k
        } else {
1855
            /* full record, parse it now */
1856
37.7k
            int retval = SSLv3ParseHandshakeType(
1857
37.7k
                    ssl_state, input, ssl_state->curr_connp->message_length, direction);
1858
37.7k
            if (retval < 0 || retval > (int)input_len) {
1859
0
                DEBUG_VALIDATE_BUG_ON(retval > (int)input_len);
1860
0
                return (retval);
1861
0
            }
1862
37.7k
            SCLogDebug("retval %d input_len %u", retval, input_len);
1863
37.7k
            input += retval;
1864
37.7k
            input_len -= retval;
1865
1866
37.7k
            SSLParserHSReset(ssl_state->curr_connp);
1867
37.7k
        }
1868
37.7k
        SCLogDebug("input_len left %u", input_len);
1869
37.7k
    }
1870
34.6k
    return (int)(input - initial_input);
1871
37.5k
}
1872
1873
/**
1874
 * \internal
1875
 * \brief TLS Alert parser
1876
 *
1877
 * \param sslstate  Pointer to the SSL state.
1878
 * \param input     Pointer to the received input data.
1879
 * \param input_len Length in bytes of the received data.
1880
 * \param direction 1 toclient, 0 toserver
1881
 *
1882
 * \retval The number of bytes parsed on success, 0 if nothing parsed, -1 on failure.
1883
 */
1884
static int SSLv3ParseAlertProtocol(
1885
        SSLState *ssl_state, const uint8_t *input, uint32_t input_len, uint8_t direction)
1886
3.69k
{
1887
3.69k
    if (input_len < 2) {
1888
4
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_ALERT);
1889
4
        return -1;
1890
4
    }
1891
1892
    /* assume a record > 2 to be an encrypted alert record */
1893
3.68k
    if (input_len == 2) {
1894
1.06k
        uint8_t level = input[0];
1895
        // uint8_t desc = input[1];
1896
1897
        /* if level Fatal, we consider the tx finished */
1898
1.06k
        if (level == 2) {
1899
666
            UpdateClientState(ssl_state, TLS_STATE_CLIENT_FINISHED);
1900
666
            UpdateServerState(ssl_state, TLS_STATE_SERVER_FINISHED);
1901
666
        }
1902
1.06k
    }
1903
3.68k
    return 0;
1904
3.69k
}
1905
1906
/**
1907
 * \internal
1908
 * \brief TLS Heartbeat parser (see RFC 6520)
1909
 *
1910
 * \param sslstate  Pointer to the SSL state.
1911
 * \param input     Pointer to the received input data.
1912
 * \param input_len Length in bytes of the received data.
1913
 * \param direction 1 toclient, 0 toserver
1914
 *
1915
 * \retval The number of bytes parsed on success, 0 if nothing parsed, -1 on failure.
1916
 */
1917
static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input,
1918
                                       uint32_t input_len, uint8_t direction)
1919
4.50k
{
1920
4.50k
    uint8_t hb_type;
1921
4.50k
    uint16_t payload_len;
1922
4.50k
    uint32_t padding_len;
1923
1924
    /* expect at least 3 bytes: heartbeat type (1) + length (2) */
1925
4.50k
    if (input_len < 3) {
1926
271
        return 0;
1927
271
    }
1928
1929
4.23k
    hb_type = *input++;
1930
1931
4.23k
    if (!(ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC)) {
1932
2.60k
        if (!(hb_type == TLS_HB_REQUEST || hb_type == TLS_HB_RESPONSE)) {
1933
7
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT);
1934
7
            return -1;
1935
7
        }
1936
2.60k
    }
1937
1938
4.22k
    if ((ssl_state->flags & SSL_AL_FLAG_HB_INFLIGHT) == 0) {
1939
2.14k
        ssl_state->flags |= SSL_AL_FLAG_HB_INFLIGHT;
1940
1941
2.14k
        if (direction) {
1942
985
            SCLogDebug("HeartBeat Record type sent in the toclient direction!");
1943
985
            ssl_state->flags |= SSL_AL_FLAG_HB_SERVER_INIT;
1944
1.16k
        } else {
1945
1.16k
            SCLogDebug("HeartBeat Record type sent in the toserver direction!");
1946
1.16k
            ssl_state->flags |= SSL_AL_FLAG_HB_CLIENT_INIT;
1947
1.16k
        }
1948
1949
        /* if we reach this point, then we can assume that the HB request
1950
           is encrypted. If so, let's set the HB record length */
1951
2.14k
        if (ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC) {
1952
819
            ssl_state->hb_record_len = ssl_state->curr_connp->record_length;
1953
819
            SCLogDebug("Encrypted HeartBeat Request In-flight. Storing len %u",
1954
819
                       ssl_state->hb_record_len);
1955
819
            return (ssl_state->curr_connp->record_length - 3);
1956
819
        }
1957
1958
1.32k
        payload_len = (uint16_t)(*input << 8) | *(input + 1);
1959
1960
        /* check that the requested payload length is really present in
1961
           the record (CVE-2014-0160) */
1962
1.32k
        if ((uint32_t)(payload_len+3) > ssl_state->curr_connp->record_length) {
1963
17
            SCLogDebug("We have a short record in HeartBeat Request");
1964
17
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_OVERFLOW_HEARTBEAT);
1965
17
            return -1;
1966
17
        }
1967
1968
        /* check the padding length. It must be at least 16 bytes
1969
           (RFC 6520, section 4) */
1970
1.31k
        padding_len = ssl_state->curr_connp->record_length - payload_len - 3;
1971
1.31k
        if (padding_len < 16) {
1972
2
            SCLogDebug("We have a short record in HeartBeat Request");
1973
2
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT);
1974
2
            return -1;
1975
2
        }
1976
1977
        /* we don't have the payload */
1978
1.30k
        if (input_len < payload_len + padding_len) {
1979
0
            return 0;
1980
0
        }
1981
1982
    /* OpenSSL still seems to discard multiple in-flight
1983
       heartbeats although some tools send multiple at once */
1984
2.08k
    } else if (direction == 1 && (ssl_state->flags & SSL_AL_FLAG_HB_INFLIGHT) &&
1985
1.12k
            (ssl_state->flags & SSL_AL_FLAG_HB_SERVER_INIT)) {
1986
5
        SCLogDebug("Multiple in-flight server initiated HeartBeats");
1987
5
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT);
1988
5
        return -1;
1989
1990
2.07k
    } else if (direction == 0 && (ssl_state->flags & SSL_AL_FLAG_HB_INFLIGHT) &&
1991
960
            (ssl_state->flags & SSL_AL_FLAG_HB_CLIENT_INIT)) {
1992
10
        SCLogDebug("Multiple in-flight client initiated HeartBeats");
1993
10
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT);
1994
10
        return -1;
1995
1996
2.06k
    } else {
1997
        /* we have a HB record in the opposite direction of the request,
1998
           let's reset our flags */
1999
2.06k
        ssl_state->flags &= ~SSL_AL_FLAG_HB_INFLIGHT;
2000
2.06k
        ssl_state->flags &= ~SSL_AL_FLAG_HB_SERVER_INIT;
2001
2.06k
        ssl_state->flags &= ~SSL_AL_FLAG_HB_CLIENT_INIT;
2002
2003
        /* if we reach this point, then we can assume that the HB request
2004
           is encrypted. If so, let's set the HB record length */
2005
2.06k
        if (ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC) {
2006
            /* check to see if the encrypted response is longer than the
2007
               encrypted request */
2008
803
            if (ssl_state->hb_record_len > 0 && ssl_state->hb_record_len <
2009
798
                    ssl_state->curr_connp->record_length) {
2010
3
                SCLogDebug("My heart is bleeding.. OpenSSL HeartBleed response (%u)",
2011
3
                        ssl_state->hb_record_len);
2012
3
                SSLSetEvent(ssl_state,
2013
3
                        TLS_DECODER_EVENT_DATALEAK_HEARTBEAT_MISMATCH);
2014
3
                ssl_state->hb_record_len = 0;
2015
3
                return -1;
2016
3
            }
2017
803
        }
2018
2019
        /* reset the HB record length in case we have a legit HB followed
2020
           by a bad one */
2021
2.06k
        ssl_state->hb_record_len = 0;
2022
2.06k
    }
2023
2024
    /* skip the HeartBeat, 3 bytes were already parsed,
2025
       e.g |18 03 02| for TLS 1.2 */
2026
3.37k
    return (ssl_state->curr_connp->record_length - 3);
2027
4.22k
}
2028
2029
static int SSLv3ParseRecord(uint8_t direction, SSLState *ssl_state,
2030
                            const uint8_t *input, uint32_t input_len)
2031
705k
{
2032
705k
    const uint8_t *initial_input = input;
2033
2034
705k
    if (input_len == 0) {
2035
0
        return 0;
2036
0
    }
2037
2038
705k
    uint8_t skip_version = 0;
2039
2040
    /* Only set SSL/TLS version here if it has not already been set in
2041
       client/server hello. */
2042
705k
    if (direction == 0) {
2043
136k
        if ((ssl_state->flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) &&
2044
69.1k
                (ssl_state->client_connp.version != TLS_VERSION_UNKNOWN)) {
2045
61.9k
            skip_version = 1;
2046
61.9k
        }
2047
568k
    } else {
2048
568k
        if ((ssl_state->flags & SSL_AL_FLAG_STATE_SERVER_HELLO) &&
2049
517k
                (ssl_state->server_connp.version != TLS_VERSION_UNKNOWN)) {
2050
511k
            skip_version = 1;
2051
511k
        }
2052
568k
    }
2053
2054
705k
    switch (ssl_state->curr_connp->bytes_processed) {
2055
340k
        case 0:
2056
340k
            if (input_len >= 5) {
2057
234k
                ssl_state->curr_connp->content_type = input[0];
2058
234k
                if (!skip_version) {
2059
121k
                    ssl_state->curr_connp->version = (uint16_t)(input[1] << 8) | input[2];
2060
121k
                }
2061
234k
                ssl_state->curr_connp->record_length = input[3] << 8;
2062
234k
                ssl_state->curr_connp->record_length |= input[4];
2063
234k
                ssl_state->curr_connp->bytes_processed += SSLV3_RECORD_HDR_LEN;
2064
234k
                return SSLV3_RECORD_HDR_LEN;
2065
234k
            } else {
2066
106k
                ssl_state->curr_connp->content_type = *(input++);
2067
106k
                if (--input_len == 0)
2068
97.6k
                    break;
2069
106k
            }
2070
2071
            /* fall through */
2072
105k
        case 1:
2073
105k
            if (!skip_version) {
2074
5.58k
                ssl_state->curr_connp->version = (uint16_t)(*(input++) << 8);
2075
100k
            } else {
2076
100k
                input++;
2077
100k
            }
2078
105k
            if (--input_len == 0)
2079
88.2k
                break;
2080
2081
            /* fall through */
2082
105k
        case 2:
2083
105k
            if (!skip_version) {
2084
5.21k
                ssl_state->curr_connp->version |= *(input++);
2085
100k
            } else {
2086
100k
                input++;
2087
100k
            }
2088
105k
            if (--input_len == 0)
2089
91.0k
                break;
2090
2091
            /* fall through */
2092
105k
        case 3:
2093
105k
            ssl_state->curr_connp->record_length = *(input++) << 8;
2094
105k
            if (--input_len == 0)
2095
88.1k
                break;
2096
2097
            /* fall through */
2098
105k
        case 4:
2099
105k
            ssl_state->curr_connp->record_length |= *(input++);
2100
105k
            if (--input_len == 0)
2101
85.8k
                break;
2102
2103
            /* fall through */
2104
705k
    }
2105
2106
470k
    ssl_state->curr_connp->bytes_processed += (input - initial_input);
2107
2108
470k
    return (int)(input - initial_input);
2109
705k
}
2110
2111
static int SSLv2ParseRecord(uint8_t direction, SSLState *ssl_state,
2112
                            const uint8_t *input, uint32_t input_len)
2113
53.2k
{
2114
53.2k
    const uint8_t *initial_input = input;
2115
2116
53.2k
    if (input_len == 0) {
2117
0
        return 0;
2118
0
    }
2119
2120
53.2k
    if (ssl_state->curr_connp->record_lengths_length == 2) {
2121
23.3k
        switch (ssl_state->curr_connp->bytes_processed) {
2122
22.5k
            case 0:
2123
22.5k
                if (input_len >= ssl_state->curr_connp->record_lengths_length + 1) {
2124
21.7k
                    ssl_state->curr_connp->record_length = (0x7f & input[0]) << 8 | input[1];
2125
21.7k
                    ssl_state->curr_connp->content_type = input[2];
2126
21.7k
                    ssl_state->curr_connp->version = SSL_VERSION_2;
2127
21.7k
                    ssl_state->curr_connp->bytes_processed += 3;
2128
21.7k
                    return 3;
2129
21.7k
                } else {
2130
792
                    ssl_state->curr_connp->record_length = (0x7f & *(input++)) << 8;
2131
792
                    if (--input_len == 0)
2132
438
                        break;
2133
792
                }
2134
2135
                /* fall through */
2136
709
            case 1:
2137
709
                ssl_state->curr_connp->record_length |= *(input++);
2138
709
                if (--input_len == 0)
2139
369
                    break;
2140
2141
                /* fall through */
2142
734
            case 2:
2143
734
                ssl_state->curr_connp->content_type = *(input++);
2144
734
                ssl_state->curr_connp->version = SSL_VERSION_2;
2145
734
                if (--input_len == 0)
2146
39
                    break;
2147
2148
                /* fall through */
2149
23.3k
        }
2150
2151
29.9k
    } else {
2152
29.9k
        switch (ssl_state->curr_connp->bytes_processed) {
2153
24.6k
            case 0:
2154
24.6k
                if (input_len >= ssl_state->curr_connp->record_lengths_length + 1) {
2155
20.0k
                    ssl_state->curr_connp->record_length = (0x3f & input[0]) << 8 | input[1];
2156
20.0k
                    ssl_state->curr_connp->content_type = input[3];
2157
20.0k
                    ssl_state->curr_connp->version = SSL_VERSION_2;
2158
20.0k
                    ssl_state->curr_connp->bytes_processed += 4;
2159
20.0k
                    return 4;
2160
20.0k
                } else {
2161
4.68k
                    ssl_state->curr_connp->record_length = (0x3f & *(input++)) << 8;
2162
4.68k
                    if (--input_len == 0)
2163
1.04k
                        break;
2164
4.68k
                }
2165
2166
                /* fall through */
2167
4.55k
            case 1:
2168
4.55k
                ssl_state->curr_connp->record_length |= *(input++);
2169
4.55k
                if (--input_len == 0)
2170
3.08k
                    break;
2171
2172
                /* fall through */
2173
4.57k
            case 2:
2174
                /* padding */
2175
4.57k
                input++;
2176
4.57k
                if (--input_len == 0)
2177
1.32k
                    break;
2178
2179
                /* fall through */
2180
4.50k
            case 3:
2181
4.50k
                ssl_state->curr_connp->content_type = *(input++);
2182
4.50k
                ssl_state->curr_connp->version = SSL_VERSION_2;
2183
4.50k
                if (--input_len == 0)
2184
407
                    break;
2185
2186
                /* fall through */
2187
29.9k
        }
2188
29.9k
    }
2189
2190
11.5k
    ssl_state->curr_connp->bytes_processed += (input - initial_input);
2191
2192
11.5k
    return (int)(input - initial_input);
2193
53.2k
}
2194
2195
static struct SSLDecoderResult SSLv2Decode(uint8_t direction, SSLState *ssl_state,
2196
        AppLayerParserState *pstate, const uint8_t *input, uint32_t input_len,
2197
        const StreamSlice stream_slice)
2198
116k
{
2199
116k
    const uint8_t *initial_input = input;
2200
2201
116k
    if (ssl_state->curr_connp->bytes_processed == 0) {
2202
47.2k
        if (input[0] & 0x80) {
2203
22.5k
            ssl_state->curr_connp->record_lengths_length = 2;
2204
24.6k
        } else {
2205
24.6k
            ssl_state->curr_connp->record_lengths_length = 3;
2206
24.6k
        }
2207
2208
47.2k
        SCLogDebug("record start: ssl2.hdr frame");
2209
47.2k
        AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input,
2210
47.2k
                ssl_state->curr_connp->record_lengths_length + 1, direction, TLS_FRAME_SSLV2_HDR);
2211
47.2k
    }
2212
2213
116k
    SCLogDebug("direction %u ssl_state->curr_connp->record_lengths_length + 1 %u, "
2214
116k
               "ssl_state->curr_connp->bytes_processed %u",
2215
116k
            direction, ssl_state->curr_connp->record_lengths_length + 1,
2216
116k
            ssl_state->curr_connp->bytes_processed);
2217
    /* the +1 is because we read one extra byte inside SSLv2ParseRecord
2218
       to read the msg_type */
2219
116k
    if (ssl_state->curr_connp->bytes_processed <
2220
116k
            (ssl_state->curr_connp->record_lengths_length + 1)) {
2221
53.2k
        const int retval = SSLv2ParseRecord(direction, ssl_state, input, input_len);
2222
53.2k
        SCLogDebug("retval %d ssl_state->curr_connp->record_length %u", retval,
2223
53.2k
                ssl_state->curr_connp->record_length);
2224
53.2k
        if (retval < 0 || retval > (int)input_len) {
2225
0
            DEBUG_VALIDATE_BUG_ON(retval > (int)input_len);
2226
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSLV2_HEADER);
2227
0
            return SSL_DECODER_ERROR(-1);
2228
0
        }
2229
2230
53.2k
        AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input,
2231
53.2k
                ssl_state->curr_connp->record_lengths_length + ssl_state->curr_connp->record_length,
2232
53.2k
                direction, TLS_FRAME_SSLV2_PDU);
2233
53.2k
        SCLogDebug("record start: ssl2.pdu frame");
2234
2235
53.2k
        input += retval;
2236
53.2k
        input_len -= retval;
2237
53.2k
    }
2238
2239
    /* if we don't have the full record, we return incomplete */
2240
116k
    if (ssl_state->curr_connp->record_lengths_length + ssl_state->curr_connp->record_length >
2241
116k
            input_len + ssl_state->curr_connp->bytes_processed) {
2242
71.5k
        uint32_t needed = ssl_state->curr_connp->record_length;
2243
71.5k
        SCLogDebug("record len %u input_len %u parsed %u: need %u bytes more data",
2244
71.5k
                ssl_state->curr_connp->record_length, input_len, (uint32_t)(input - initial_input),
2245
71.5k
                needed);
2246
71.5k
        return SSL_DECODER_INCOMPLETE((input - initial_input), needed);
2247
71.5k
    }
2248
2249
44.9k
    if (input_len == 0) {
2250
894
        return SSL_DECODER_OK((input - initial_input));
2251
894
    }
2252
2253
    /* record_length should never be zero */
2254
44.0k
    if (ssl_state->curr_connp->record_length == 0) {
2255
28
        SCLogDebug("SSLv2 record length is zero");
2256
28
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSLV2_HEADER);
2257
28
        return SSL_DECODER_ERROR(-1);
2258
28
    }
2259
2260
    /* record_lengths_length should never be zero */
2261
44.0k
    if (ssl_state->curr_connp->record_lengths_length == 0) {
2262
4
        SCLogDebug("SSLv2 record lengths length is zero");
2263
4
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSLV2_HEADER);
2264
4
        return SSL_DECODER_ERROR(-1);
2265
4
    }
2266
2267
44.0k
    switch (ssl_state->curr_connp->content_type) {
2268
832
        case SSLV2_MT_ERROR:
2269
832
            SCLogDebug("SSLV2_MT_ERROR msg_type received. Error encountered "
2270
832
                       "in establishing the sslv2 session, may be version");
2271
832
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_ERROR_MSG_ENCOUNTERED);
2272
2273
832
            break;
2274
2275
3.96k
        case SSLV2_MT_CLIENT_HELLO:
2276
            /* record_length does not count the msg_type byte.  CLIENT_HELLO
2277
             * body starts with 3 fixed fields: client_version (2) +
2278
             * cipher_spec_length (2) + session_id_length (2).  We need at
2279
             * least those 6 bytes after the msg_type, so record_length
2280
             * must be >= 7. */
2281
3.96k
            if (input_len < 6 || ssl_state->curr_connp->record_length < 7) {
2282
12
                SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSL_RECORD);
2283
12
                return SSL_DECODER_ERROR(-1);
2284
12
            }
2285
2286
3.95k
            ssl_state->current_flags = SSL_AL_FLAG_STATE_CLIENT_HELLO;
2287
3.95k
            ssl_state->current_flags |= SSL_AL_FLAG_SSL_CLIENT_HS;
2288
3.95k
            UpdateClientState(ssl_state, TLS_STATE_CLIENT_HELLO_DONE);
2289
2290
3.95k
            const uint16_t version = (uint16_t)(input[0] << 8) | input[1];
2291
3.95k
            SCLogDebug("SSLv2: version %04x", version);
2292
3.95k
            ssl_state->curr_connp->version = version;
2293
3.95k
            uint16_t session_id_length = (input[5]) | (uint16_t)(input[4] << 8);
2294
3.95k
            input += 6;
2295
3.95k
            input_len -= 6;
2296
3.95k
            ssl_state->curr_connp->bytes_processed += 6;
2297
3.95k
            if (session_id_length == 0) {
2298
687
                ssl_state->current_flags |= SSL_AL_FLAG_SSL_NO_SESSION_ID;
2299
687
            }
2300
3.95k
            break;
2301
2302
738
        case SSLV2_MT_CLIENT_MASTER_KEY:
2303
738
            if (!(ssl_state->flags & SSL_AL_FLAG_SSL_CLIENT_HS)) {
2304
526
                SCLogDebug("Client hello is not seen before master key "
2305
526
                           "message!");
2306
526
            }
2307
738
            ssl_state->current_flags = SSL_AL_FLAG_SSL_CLIENT_MASTER_KEY;
2308
2309
738
            break;
2310
2311
2.52k
        case SSLV2_MT_CLIENT_CERTIFICATE:
2312
2.52k
            if (direction == 1) {
2313
1.11k
                SCLogDebug("Incorrect SSL Record type sent in the toclient "
2314
1.11k
                           "direction!");
2315
1.40k
            } else {
2316
1.40k
                ssl_state->current_flags = SSL_AL_FLAG_STATE_CLIENT_KEYX;
2317
1.40k
            }
2318
2.52k
            UpdateServerState(ssl_state, TLS_STATE_SERVER_CERT_DONE);
2319
2320
            /* fall through */
2321
3.31k
        case SSLV2_MT_SERVER_VERIFY:
2322
23.3k
        case SSLV2_MT_SERVER_FINISHED:
2323
23.3k
            if (direction == 0 &&
2324
11.0k
                    !(ssl_state->curr_connp->content_type &
2325
11.0k
                    SSLV2_MT_CLIENT_CERTIFICATE)) {
2326
9.61k
                SCLogDebug("Incorrect SSL Record type sent in the toserver "
2327
9.61k
                           "direction!");
2328
9.61k
            }
2329
2330
            /* fall through */
2331
26.4k
        case SSLV2_MT_CLIENT_FINISHED:
2332
27.0k
        case SSLV2_MT_REQUEST_CERTIFICATE:
2333
            /* both client hello and server hello must be seen */
2334
27.0k
            if ((ssl_state->flags & SSL_AL_FLAG_SSL_CLIENT_HS) &&
2335
11.1k
                    (ssl_state->flags & SSL_AL_FLAG_SSL_SERVER_HS)) {
2336
2337
9.34k
                if (direction == 0) {
2338
5.28k
                    if (ssl_state->flags & SSL_AL_FLAG_SSL_NO_SESSION_ID) {
2339
596
                        ssl_state->current_flags |= SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED;
2340
596
                        SCLogDebug("SSLv2 client side has started the encryption");
2341
4.68k
                    } else if (ssl_state->flags & SSL_AL_FLAG_SSL_CLIENT_MASTER_KEY) {
2342
2.62k
                        ssl_state->current_flags = SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED;
2343
2.62k
                        SCLogDebug("SSLv2 client side has started the encryption");
2344
2.62k
                    }
2345
5.28k
                } else {
2346
4.06k
                    ssl_state->current_flags = SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED;
2347
4.06k
                    SCLogDebug("SSLv2 Server side has started the encryption");
2348
4.06k
                }
2349
2350
9.34k
                if ((ssl_state->flags & SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED) &&
2351
3.42k
                    (ssl_state->flags & SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED))
2352
2.41k
                {
2353
2.41k
                    if (ssl_config.encrypt_mode != SSL_CNF_ENC_HANDLE_FULL) {
2354
2.41k
                        SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION);
2355
2.41k
                    }
2356
2357
2.41k
                    if (ssl_config.encrypt_mode == SSL_CNF_ENC_HANDLE_BYPASS) {
2358
0
                        SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_REASSEMBLY);
2359
0
                        SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_BYPASS_READY);
2360
0
                    }
2361
2.41k
                    SCLogDebug("SSLv2 No reassembly & inspection has been set");
2362
2.41k
                }
2363
9.34k
            }
2364
2365
27.0k
            break;
2366
2367
1.09k
        case SSLV2_MT_SERVER_HELLO:
2368
1.09k
            ssl_state->current_flags = SSL_AL_FLAG_STATE_SERVER_HELLO;
2369
1.09k
            ssl_state->current_flags |= SSL_AL_FLAG_SSL_SERVER_HS;
2370
1.09k
            UpdateServerState(ssl_state, TLS_STATE_SERVER_HELLO);
2371
2372
1.09k
            break;
2373
44.0k
    }
2374
2375
44.0k
    ssl_state->flags |= ssl_state->current_flags;
2376
2377
44.0k
    if (ssl_state->curr_connp->bytes_processed >
2378
44.0k
            ssl_state->curr_connp->record_length + ssl_state->curr_connp->record_lengths_length) {
2379
0
        SCLogDebug("SSLv2 bytes_processed (%u) exceeds record+hdr "
2380
0
                   "len (record_length=%u, lengths_length=%u)",
2381
0
                ssl_state->curr_connp->bytes_processed, ssl_state->curr_connp->record_length,
2382
0
                ssl_state->curr_connp->record_lengths_length);
2383
0
        SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSL_RECORD);
2384
0
        return SSL_DECODER_ERROR(-1);
2385
0
    }
2386
2387
44.0k
    if (input_len + ssl_state->curr_connp->bytes_processed >=
2388
44.0k
            (ssl_state->curr_connp->record_length +
2389
44.0k
            ssl_state->curr_connp->record_lengths_length)) {
2390
2391
        /* looks like we have another record after this */
2392
44.0k
        uint32_t diff = ssl_state->curr_connp->record_length +
2393
44.0k
                ssl_state->curr_connp->record_lengths_length + -
2394
44.0k
                ssl_state->curr_connp->bytes_processed;
2395
44.0k
        input += diff;
2396
44.0k
        SSLParserReset(ssl_state);
2397
2398
        /* we still don't have the entire record for the one we are
2399
           currently parsing */
2400
44.0k
    } else {
2401
0
        input += input_len;
2402
0
        ssl_state->curr_connp->bytes_processed += input_len;
2403
0
    }
2404
44.0k
    return SSL_DECODER_OK((input - initial_input));
2405
44.0k
}
2406
2407
static struct SSLDecoderResult SSLv3Decode(uint8_t direction, SSLState *ssl_state,
2408
        AppLayerParserState *pstate, const uint8_t *input, const uint32_t input_len,
2409
        const StreamSlice stream_slice)
2410
747k
{
2411
747k
    uint32_t parsed = 0;
2412
747k
    uint32_t record_len; /* slice of input_len for the current record */
2413
747k
    const bool first_call = (ssl_state->curr_connp->bytes_processed == 0);
2414
2415
747k
    if (ssl_state->curr_connp->bytes_processed < SSLV3_RECORD_HDR_LEN) {
2416
705k
        const uint16_t prev_version = ssl_state->curr_connp->version;
2417
2418
705k
        int retval = SSLv3ParseRecord(direction, ssl_state, input, input_len);
2419
705k
        if (retval < 0 || retval > (int)input_len) {
2420
0
            DEBUG_VALIDATE_BUG_ON(retval > (int)input_len);
2421
0
            SCLogDebug("SSLv3ParseRecord returned %d", retval);
2422
0
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_TLS_HEADER);
2423
0
            return SSL_DECODER_ERROR(-1);
2424
0
        }
2425
705k
        parsed = retval;
2426
2427
705k
        SCLogDebug("%s input %p record_length %u", (direction == 0) ? "toserver" : "toclient",
2428
705k
                input, ssl_state->curr_connp->record_length);
2429
2430
        /* first the hdr frame at our first chance */
2431
705k
        if (first_call) {
2432
340k
            AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input, SSLV3_RECORD_HDR_LEN,
2433
340k
                    direction, TLS_FRAME_HDR);
2434
340k
        }
2435
2436
        /* parser is streaming for the initial header, then switches to incomplete
2437
         * API: so if we don't have the hdr yet, return consumed bytes and wait
2438
         * until we are called again with new data. */
2439
705k
        if (ssl_state->curr_connp->bytes_processed < SSLV3_RECORD_HDR_LEN) {
2440
365k
            SCLogDebug(
2441
365k
                    "incomplete header, return %u bytes consumed and wait for more data", parsed);
2442
365k
            return SSL_DECODER_OK(parsed);
2443
365k
        }
2444
2445
        /* pdu frame needs record length, so only create it when hdr fully parsed. */
2446
339k
        AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input,
2447
339k
                ssl_state->curr_connp->record_length + retval, direction, TLS_FRAME_PDU);
2448
339k
        record_len = MIN(input_len - parsed, ssl_state->curr_connp->record_length);
2449
339k
        SCLogDebug(
2450
339k
                "record_len %u (input_len %u, parsed %u, ssl_state->curr_connp->record_length %u)",
2451
339k
                record_len, input_len, parsed, ssl_state->curr_connp->record_length);
2452
2453
339k
        bool unknown_record = false;
2454
339k
        switch (ssl_state->curr_connp->content_type) {
2455
18.4k
            case SSLV3_CHANGE_CIPHER_SPEC:
2456
22.2k
            case SSLV3_ALERT_PROTOCOL:
2457
147k
            case SSLV3_HANDSHAKE_PROTOCOL:
2458
175k
            case SSLV3_APPLICATION_PROTOCOL:
2459
179k
            case SSLV3_HEARTBEAT_PROTOCOL:
2460
179k
                break;
2461
160k
            default:
2462
160k
                unknown_record = true;
2463
160k
                break;
2464
339k
        }
2465
2466
        /* unknown record type. For TLS 1.0, 1.1 and 1.2 this is ok. For the rest it is fatal. Based
2467
         * on Wireshark logic. */
2468
339k
        if (prev_version == TLS_VERSION_10 || prev_version == TLS_VERSION_11) {
2469
225k
            if (unknown_record) {
2470
159k
                SCLogDebug("unknown record, ignore it");
2471
159k
                SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_RECORD_TYPE);
2472
2473
159k
                ssl_state->curr_connp->bytes_processed = 0; // TODO review this reset logic
2474
159k
                ssl_state->curr_connp->content_type = 0;
2475
159k
                ssl_state->curr_connp->record_length = 0;
2476
                // restore last good version
2477
159k
                ssl_state->curr_connp->version = prev_version;
2478
159k
                return SSL_DECODER_OK(input_len); // consume everything
2479
159k
            }
2480
225k
        } else {
2481
114k
            if (unknown_record) {
2482
1.23k
                SCLogDebug("unknown record, fatal");
2483
1.23k
                SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_RECORD_TYPE);
2484
1.23k
                return SSL_DECODER_ERROR(-1);
2485
1.23k
            }
2486
114k
        }
2487
2488
        /* record_length should never be zero */
2489
179k
        if (ssl_state->curr_connp->record_length == 0) {
2490
29
            SCLogDebug("SSLv3 Record length is 0");
2491
29
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_RECORD_LENGTH);
2492
29
            return SSL_DECODER_ERROR(-1);
2493
29
        }
2494
2495
179k
        if (!TLSVersionValid(ssl_state->curr_connp->version)) {
2496
137
            SCLogDebug("ssl_state->curr_connp->version %04x", ssl_state->curr_connp->version);
2497
137
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_RECORD_VERSION);
2498
137
            return SSL_DECODER_ERROR(-1);
2499
137
        }
2500
2501
179k
        if (ssl_state->curr_connp->bytes_processed == SSLV3_RECORD_HDR_LEN &&
2502
179k
                ssl_state->curr_connp->record_length > SSLV3_RECORD_MAX_LEN) {
2503
61
            SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_RECORD_LENGTH);
2504
61
            return SSL_DECODER_ERROR(-1);
2505
61
        }
2506
179k
        DEBUG_VALIDATE_BUG_ON(ssl_state->curr_connp->bytes_processed > SSLV3_RECORD_HDR_LEN);
2507
179k
    } else {
2508
42.7k
        ValidateRecordState(ssl_state->curr_connp);
2509
2510
42.7k
        record_len = (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN)- ssl_state->curr_connp->bytes_processed;
2511
42.7k
        record_len = MIN(input_len, record_len);
2512
42.7k
    }
2513
222k
    SCLogDebug("record length %u processed %u got %u",
2514
222k
            ssl_state->curr_connp->record_length, ssl_state->curr_connp->bytes_processed, record_len);
2515
2516
    /* if we don't have the full record, we return incomplete */
2517
222k
    if (ssl_state->curr_connp->record_length > input_len - parsed) {
2518
        /* no need to use incomplete api buffering for application
2519
         * records that we'll not use anyway. */
2520
46.7k
        if (ssl_state->curr_connp->content_type == SSLV3_APPLICATION_PROTOCOL) {
2521
16.5k
            SCLogDebug("application record");
2522
30.2k
        } else {
2523
30.2k
            uint32_t needed = ssl_state->curr_connp->record_length;
2524
30.2k
            SCLogDebug("record len %u input_len %u parsed %u: need %u bytes more data",
2525
30.2k
                    ssl_state->curr_connp->record_length, input_len, parsed, needed);
2526
30.2k
            DEBUG_VALIDATE_BUG_ON(needed > SSLV3_RECORD_MAX_LEN);
2527
30.2k
            return SSL_DECODER_INCOMPLETE(parsed, needed);
2528
30.2k
        }
2529
46.7k
    }
2530
2531
191k
    if (record_len == 0) {
2532
248
        return SSL_DECODER_OK(parsed);
2533
248
    }
2534
2535
191k
    AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input + parsed,
2536
191k
            ssl_state->curr_connp->record_length, direction, TLS_FRAME_DATA);
2537
2538
191k
    switch (ssl_state->curr_connp->content_type) {
2539
        /* we don't need any data from these types */
2540
18.4k
        case SSLV3_CHANGE_CIPHER_SPEC:
2541
18.4k
            ssl_state->flags |= SSL_AL_FLAG_CHANGE_CIPHER_SPEC;
2542
2543
18.4k
            if (direction) {
2544
10.7k
                ssl_state->flags |= SSL_AL_FLAG_SERVER_CHANGE_CIPHER_SPEC;
2545
10.7k
            } else {
2546
7.69k
                ssl_state->flags |= SSL_AL_FLAG_CLIENT_CHANGE_CIPHER_SPEC;
2547
2548
                // TODO TLS 1.3
2549
7.69k
                UpdateClientState(ssl_state, TLS_STATE_CLIENT_HANDSHAKE_DONE);
2550
7.69k
            }
2551
18.4k
            break;
2552
2553
3.69k
        case SSLV3_ALERT_PROTOCOL: {
2554
3.69k
            AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input + parsed,
2555
3.69k
                    ssl_state->curr_connp->record_length, direction, TLS_FRAME_ALERT_DATA);
2556
2557
3.69k
            int retval = SSLv3ParseAlertProtocol(ssl_state, input + parsed, record_len, direction);
2558
3.69k
            if (retval < 0) {
2559
4
                SCLogDebug("SSLv3ParseAlertProtocol returned %d", retval);
2560
4
                return SSL_DECODER_ERROR(-1);
2561
4
            }
2562
3.68k
            break;
2563
3.69k
        }
2564
40.7k
        case SSLV3_APPLICATION_PROTOCOL:
2565
            /* In TLSv1.3 early data (0-RTT) could be sent before the
2566
               handshake is complete (rfc8446, section 2.3). We should
2567
               therefore not mark the handshake as done before we have
2568
               seen the ServerHello record. */
2569
40.7k
            if ((ssl_state->flags & SSL_AL_FLAG_EARLY_DATA) &&
2570
963
                    ((ssl_state->flags & SSL_AL_FLAG_STATE_SERVER_HELLO) == 0))
2571
407
                break;
2572
2573
            /* if we see (encrypted) application data, then this means the
2574
               handshake must be done */
2575
40.3k
            if (ssl_state->curr_connp == &ssl_state->client_connp) {
2576
13.8k
                UpdateClientState(ssl_state, TLS_STATE_CLIENT_HANDSHAKE_DONE);
2577
26.4k
            } else {
2578
26.4k
                UpdateServerState(ssl_state, TLS_STATE_SERVER_HANDSHAKE_DONE);
2579
26.4k
            }
2580
2581
40.3k
            if (ssl_config.encrypt_mode != SSL_CNF_ENC_HANDLE_FULL) {
2582
40.3k
                SCLogDebug("setting APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD");
2583
40.3k
                SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD);
2584
40.3k
            }
2585
2586
            /* Encrypted data, reassembly not asked, bypass asked, let's sacrifice
2587
             * heartbeat lke inspection to be able to be able to bypass the flow */
2588
40.3k
            if (ssl_config.encrypt_mode == SSL_CNF_ENC_HANDLE_BYPASS) {
2589
0
                SCLogDebug("setting APP_LAYER_PARSER_NO_REASSEMBLY");
2590
0
                SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_REASSEMBLY);
2591
0
                SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION);
2592
0
                SCAppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_BYPASS_READY);
2593
0
            }
2594
40.3k
            break;
2595
2596
124k
        case SSLV3_HANDSHAKE_PROTOCOL: {
2597
124k
            if (ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC) {
2598
                /* In TLSv1.3, ChangeCipherSpec is only used for middlebox
2599
                   compatibility (rfc8446, appendix D.4). */
2600
                // Client hello flags is needed to have a valid version
2601
14.3k
                if ((ssl_state->flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) &&
2602
11.1k
                        (ssl_state->client_connp.version > TLS_VERSION_12) &&
2603
5.79k
                        ((ssl_state->flags & SSL_AL_FLAG_STATE_SERVER_HELLO) == 0)) {
2604
                    /* do nothing */
2605
13.7k
                } else {
2606
                    // if we started parsing this, we must stop
2607
13.7k
                    break;
2608
13.7k
                }
2609
14.3k
            }
2610
2611
110k
            int retval = SSLv3ParseHandshakeProtocol(ssl_state, input + parsed,
2612
110k
                                                     record_len, direction);
2613
110k
            SCLogDebug("retval %d", retval);
2614
110k
            if (retval < 0 || retval > (int)record_len) {
2615
0
                DEBUG_VALIDATE_BUG_ON(retval > (int)record_len);
2616
0
                SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HANDSHAKE_MESSAGE);
2617
0
                SCLogDebug("SSLv3ParseHandshakeProtocol returned %d", retval);
2618
0
                return SSL_DECODER_ERROR(-1);
2619
0
            }
2620
110k
            ValidateRecordState(ssl_state->curr_connp);
2621
110k
            break;
2622
110k
        }
2623
4.50k
        case SSLV3_HEARTBEAT_PROTOCOL: {
2624
4.50k
            AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input + parsed,
2625
4.50k
                    ssl_state->curr_connp->record_length, direction, TLS_FRAME_HB_DATA);
2626
4.50k
            int retval = SSLv3ParseHeartbeatProtocol(ssl_state, input + parsed,
2627
4.50k
                                                 record_len, direction);
2628
4.50k
            if (retval < 0) {
2629
44
                SCLogDebug("SSLv3ParseHeartbeatProtocol returned %d", retval);
2630
44
                return SSL_DECODER_ERROR(-1);
2631
44
            }
2632
4.46k
            break;
2633
4.50k
        }
2634
4.46k
        default:
2635
            // should be unreachable now that we check after header parsing
2636
0
            DEBUG_VALIDATE_BUG_ON(1);
2637
0
            SCLogDebug("unsupported record type");
2638
0
            return SSL_DECODER_ERROR(-1);
2639
191k
    }
2640
2641
191k
    parsed += record_len;
2642
191k
    ssl_state->curr_connp->bytes_processed += record_len;
2643
2644
191k
    if (ssl_state->curr_connp->bytes_processed >=
2645
191k
            ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN) {
2646
177k
        SCLogDebug("record complete, trigger RAW");
2647
177k
        AppLayerParserTriggerRawStreamInspection(
2648
177k
                ssl_state->f, direction == 0 ? STREAM_TOSERVER : STREAM_TOCLIENT);
2649
177k
        SSLParserReset(ssl_state);
2650
177k
        ValidateRecordState(ssl_state->curr_connp);
2651
177k
        return SSL_DECODER_OK(parsed);
2652
2653
177k
    } else {
2654
        /* we still don't have the entire record for the one we are
2655
           currently parsing */
2656
13.9k
        ValidateRecordState(ssl_state->curr_connp);
2657
13.9k
        return SSL_DECODER_OK(parsed);
2658
13.9k
    }
2659
191k
}
2660
2661
/**
2662
 * \internal
2663
 * \brief SSLv2, SSLv23, SSLv3, TLSv1.1, TLSv1.2, TLSv1.3 parser.
2664
 *
2665
 *        On parsing error, this should be the only function that should reset
2666
 *        the parser state, to avoid multiple functions in the chain resetting
2667
 *        the parser state.
2668
 *
2669
 * \param direction 0 for toserver, 1 for toclient.
2670
 * \param alstate   Pointer to the state.
2671
 * \param pstate    Application layer parser state for this session.
2672
 * \param output    Pointer to the list of parsed output elements.
2673
 *
2674
 * \todo On reaching an inconsistent state, check if the input has
2675
 *  another new record, instead of just returning after the reset
2676
 *
2677
 * \retval >=0 On success.
2678
 */
2679
static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate,
2680
        AppLayerParserState *pstate, StreamSlice stream_slice)
2681
145k
{
2682
145k
    SSLState *ssl_state = (SSLState *)alstate;
2683
145k
    ssl_state->tx_data.updated_tc = true;
2684
145k
    ssl_state->tx_data.updated_ts = true;
2685
145k
    uint32_t counter = 0;
2686
145k
    ssl_state->f = f;
2687
145k
    const uint8_t *input = StreamSliceGetData(&stream_slice);
2688
145k
    const uint8_t *init_input = input;
2689
145k
    int32_t input_len = (int32_t)StreamSliceGetDataLen(&stream_slice);
2690
2691
145k
    if ((input == NULL || input_len == 0) &&
2692
1.59k
            ((direction == 0 && SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS)) ||
2693
876
                    (direction == 1 &&
2694
1.59k
                            SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC)))) {
2695
        /* flag session as finished if APP_LAYER_PARSER_EOF is set */
2696
1.59k
        if (direction == 0)
2697
722
            UpdateClientState(ssl_state, TLS_STATE_CLIENT_FINISHED);
2698
876
        else
2699
876
            UpdateServerState(ssl_state, TLS_STATE_SERVER_FINISHED);
2700
1.59k
        SCReturnStruct(APP_LAYER_OK);
2701
144k
    } else if (input == NULL || input_len == 0) {
2702
0
        SCReturnStruct(APP_LAYER_ERROR);
2703
0
    }
2704
2705
144k
    if (direction == 0)
2706
78.5k
        ssl_state->curr_connp = &ssl_state->client_connp;
2707
65.7k
    else
2708
65.7k
        ssl_state->curr_connp = &ssl_state->server_connp;
2709
2710
    /* If entering on a new record, reset the current flags. */
2711
144k
    if (ssl_state->curr_connp->bytes_processed == 0) {
2712
53.0k
        ssl_state->current_flags = 0;
2713
53.0k
    }
2714
2715
    /* if we have more than one record */
2716
144k
    uint32_t max_records = MAX((input_len / SSL_RECORD_MINIMUM_LENGTH),1);
2717
275k
    while (input_len > 0) {
2718
204k
        if (counter > max_records) {
2719
8
            SCLogDebug("Looks like we have looped quite a bit. Reset state "
2720
8
                       "and get out of here");
2721
8
            SSLParserReset(ssl_state);
2722
8
            SSLSetEvent(ssl_state,
2723
8
                        TLS_DECODER_EVENT_TOO_MANY_RECORDS_IN_PACKET);
2724
8
            return APP_LAYER_ERROR;
2725
8
        }
2726
2727
        /* ssl_state->bytes_processed is zero for a fresh record or
2728
           positive to indicate a record currently being parsed */
2729
2730
204k
        if (ssl_state->curr_connp->bytes_processed == 0) {
2731
113k
            if ((input[0] & 0x80) || (input[0] & 0x40)) {
2732
                /* only SSLv2, has one of the top 2 bits set */
2733
17.3k
                ssl_state->curr_connp->version = SSL_VERSION_2;
2734
17.3k
                SCLogDebug("SSLv2 detected");
2735
95.7k
            } else if (ssl_state->curr_connp->version == SSL_VERSION_2) {
2736
658
                ssl_state->curr_connp->version = TLS_VERSION_UNKNOWN;
2737
658
                SCLogDebug("SSL/TLS version reset");
2738
658
            }
2739
113k
        }
2740
204k
        SCLogDebug("record %u: bytes_processed %u, version %02X, input_len %u", counter,
2741
204k
                ssl_state->curr_connp->bytes_processed, ssl_state->curr_connp->version, input_len);
2742
2743
204k
        if (ssl_state->curr_connp->version == SSL_VERSION_2) {
2744
68.0k
            if (ssl_state->curr_connp->bytes_processed == 0) {
2745
17.3k
                SCLogDebug("New SSLv2 record parsing");
2746
50.7k
            } else {
2747
50.7k
                SCLogDebug("Continuing parsing SSLv2 record");
2748
50.7k
            }
2749
68.0k
            struct SSLDecoderResult r =
2750
68.0k
                    SSLv2Decode(direction, ssl_state, pstate, input, input_len, stream_slice);
2751
68.0k
            if (r.retval < 0 || r.retval > input_len) {
2752
19
                DEBUG_VALIDATE_BUG_ON(r.retval > input_len);
2753
19
                SCLogDebug("Error parsing SSLv2. Resetting parser "
2754
19
                           "state. Let's get outta here");
2755
19
                SSLParserReset(ssl_state);
2756
19
                SSLSetEvent(ssl_state,
2757
19
                        TLS_DECODER_EVENT_INVALID_SSL_RECORD);
2758
19
                return APP_LAYER_ERROR;
2759
68.0k
            } else if (r.needed) {
2760
50.7k
                input += r.retval;
2761
50.7k
                SCLogDebug("returning consumed %" PRIuMAX " needed %u",
2762
50.7k
                        (uintmax_t)(input - init_input), r.needed);
2763
50.7k
                SCReturnStruct(APP_LAYER_INCOMPLETE((uint32_t)(input - init_input), r.needed));
2764
50.7k
            }
2765
17.2k
            input_len -= r.retval;
2766
17.2k
            input += r.retval;
2767
17.2k
            SCLogDebug("SSLv2 decoder consumed %d bytes: %u left", r.retval, input_len);
2768
136k
        } else {
2769
136k
            if (ssl_state->curr_connp->bytes_processed == 0) {
2770
95.7k
                SCLogDebug("New TLS record: record_length %u",
2771
95.7k
                        ssl_state->curr_connp->record_length);
2772
95.7k
            } else {
2773
40.5k
                SCLogDebug("Continuing parsing TLS record: record_length %u, bytes_processed %u",
2774
40.5k
                        ssl_state->curr_connp->record_length, ssl_state->curr_connp->bytes_processed);
2775
40.5k
            }
2776
136k
            struct SSLDecoderResult r =
2777
136k
                    SSLv3Decode(direction, ssl_state, pstate, input, input_len, stream_slice);
2778
136k
            if (r.retval < 0 || r.retval > input_len) {
2779
782
                DEBUG_VALIDATE_BUG_ON(r.retval > input_len);
2780
782
                SCLogDebug("Error parsing TLS. Resetting parser "
2781
782
                           "state.  Let's get outta here");
2782
782
                SSLParserReset(ssl_state);
2783
782
                return APP_LAYER_ERROR;
2784
135k
            } else if (r.needed) {
2785
21.3k
                input += r.retval;
2786
21.3k
                SCLogDebug("returning consumed %" PRIuMAX " needed %u",
2787
21.3k
                        (uintmax_t)(input - init_input), r.needed);
2788
21.3k
                SCReturnStruct(APP_LAYER_INCOMPLETE((uint32_t)(input - init_input), r.needed));
2789
21.3k
            }
2790
114k
            input_len -= r.retval;
2791
114k
            input += r.retval;
2792
114k
            SCLogDebug("TLS decoder consumed %d bytes: %u left", r.retval, input_len);
2793
2794
114k
            if (ssl_state->curr_connp->bytes_processed == SSLV3_RECORD_HDR_LEN
2795
47
                    && ssl_state->curr_connp->record_length == 0) {
2796
0
                SCLogDebug("TLS empty record");
2797
                /* empty record */
2798
0
                SSLParserReset(ssl_state);
2799
0
            }
2800
114k
        }
2801
131k
        counter++;
2802
131k
    } /* while (input_len) */
2803
2804
    /* mark handshake as done if we have subject and issuer */
2805
71.3k
    if ((ssl_state->flags & SSL_AL_FLAG_NEED_CLIENT_CERT) &&
2806
19.0k
            ssl_state->client_connp.cert0_subject && ssl_state->client_connp.cert0_issuerdn) {
2807
        /* update both sides to keep existing behavior */
2808
0
        UpdateClientState(ssl_state, TLS_STATE_CLIENT_HANDSHAKE_DONE);
2809
0
        UpdateServerState(ssl_state, TLS_STATE_SERVER_HANDSHAKE_DONE);
2810
71.3k
    } else if ((ssl_state->flags & SSL_AL_FLAG_NEED_CLIENT_CERT) == 0 &&
2811
52.3k
               ssl_state->server_connp.cert0_subject && ssl_state->server_connp.cert0_issuerdn) {
2812
        /* update both sides to keep existing behavior */
2813
1.73k
        UpdateClientState(ssl_state, TLS_STATE_CLIENT_HANDSHAKE_DONE);
2814
1.73k
        UpdateServerState(ssl_state, TLS_STATE_SERVER_HANDSHAKE_DONE);
2815
1.73k
    }
2816
2817
    /* flag session as finished if APP_LAYER_PARSER_EOF is set */
2818
71.3k
    if (SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) &&
2819
446
            SCAppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC)) {
2820
        /* update both sides to keep existing behavior */
2821
85
        UpdateClientState(ssl_state, TLS_STATE_CLIENT_FINISHED);
2822
85
        UpdateServerState(ssl_state, TLS_STATE_SERVER_FINISHED);
2823
85
    }
2824
2825
71.3k
    return APP_LAYER_OK;
2826
144k
}
2827
2828
static AppLayerResult SSLParseClientRecord(Flow *f, void *alstate, AppLayerParserState *pstate,
2829
        StreamSlice stream_slice, void *local_data)
2830
136k
{
2831
136k
    return SSLDecode(f, 0 /* toserver */, alstate, pstate, stream_slice);
2832
136k
}
2833
2834
static AppLayerResult SSLParseServerRecord(Flow *f, void *alstate, AppLayerParserState *pstate,
2835
        StreamSlice stream_slice, void *local_data)
2836
554k
{
2837
554k
    return SSLDecode(f, 1 /* toclient */, alstate, pstate, stream_slice);
2838
554k
}
2839
2840
/**
2841
 * \internal
2842
 * \brief Function to allocate the SSL state memory.
2843
 */
2844
static void *SSLStateAlloc(void *orig_state, AppProto proto_orig)
2845
15.2k
{
2846
15.2k
    SSLState *ssl_state = SCCalloc(1, sizeof(SSLState));
2847
15.2k
    if (unlikely(ssl_state == NULL))
2848
0
        return NULL;
2849
15.2k
    ssl_state->client_connp.cert_log_flag = 0;
2850
15.2k
    ssl_state->server_connp.cert_log_flag = 0;
2851
15.2k
    memset(ssl_state->client_connp.random, 0, TLS_RANDOM_LEN);
2852
15.2k
    memset(ssl_state->server_connp.random, 0, TLS_RANDOM_LEN);
2853
15.2k
    ssl_state->client_connp.hs = SCTLSHandshakeNew();
2854
15.2k
    ssl_state->server_connp.hs = SCTLSHandshakeNew();
2855
15.2k
    TAILQ_INIT(&ssl_state->server_connp.certs);
2856
15.2k
    TAILQ_INIT(&ssl_state->client_connp.certs);
2857
2858
15.2k
    return (void *)ssl_state;
2859
15.2k
}
2860
2861
static void SSLStateCertSANFree(SSLStateConnp *connp)
2862
30.4k
{
2863
30.4k
    if (connp->cert0_sans) {
2864
46.8k
        for (uint16_t i = 0; i < connp->cert0_sans_num; i++) {
2865
43.8k
            SCX509ArrayFree(connp->cert0_sans[i].san, connp->cert0_sans[i].san_len);
2866
43.8k
        }
2867
2.98k
        SCFree(connp->cert0_sans);
2868
2.98k
    }
2869
30.4k
}
2870
2871
/**
2872
 * \internal
2873
 * \brief Function to free the SSL state memory.
2874
 */
2875
static void SSLStateFree(void *p)
2876
15.2k
{
2877
15.2k
    SSLState *ssl_state = (SSLState *)p;
2878
15.2k
    SSLCertsChain *item;
2879
2880
15.2k
    if (ssl_state->client_connp.cert0_subject)
2881
419
        SCX509ArrayFree(
2882
419
                ssl_state->client_connp.cert0_subject, ssl_state->client_connp.cert0_subject_len);
2883
15.2k
    if (ssl_state->client_connp.cert0_issuerdn)
2884
419
        SCX509ArrayFree(
2885
419
                ssl_state->client_connp.cert0_issuerdn, ssl_state->client_connp.cert0_issuerdn_len);
2886
15.2k
    if (ssl_state->client_connp.cert0_serial)
2887
419
        SCX509ArrayFree(
2888
419
                ssl_state->client_connp.cert0_serial, ssl_state->client_connp.cert0_serial_len);
2889
15.2k
    if (ssl_state->client_connp.cert0_fingerprint)
2890
419
        SCFree(ssl_state->client_connp.cert0_fingerprint);
2891
15.2k
    if (ssl_state->client_connp.sni)
2892
6.96k
        SCFree(ssl_state->client_connp.sni);
2893
15.2k
    if (ssl_state->client_connp.session_id)
2894
6.27k
        SCFree(ssl_state->client_connp.session_id);
2895
15.2k
    if (ssl_state->client_connp.hs_buffer)
2896
863
        SCFree(ssl_state->client_connp.hs_buffer);
2897
2898
15.2k
    if (ssl_state->server_connp.cert0_subject)
2899
3.22k
        SCX509ArrayFree(
2900
3.22k
                ssl_state->server_connp.cert0_subject, ssl_state->server_connp.cert0_subject_len);
2901
15.2k
    if (ssl_state->server_connp.cert0_issuerdn)
2902
3.22k
        SCX509ArrayFree(
2903
3.22k
                ssl_state->server_connp.cert0_issuerdn, ssl_state->server_connp.cert0_issuerdn_len);
2904
15.2k
    if (ssl_state->server_connp.cert0_serial)
2905
3.22k
        SCX509ArrayFree(
2906
3.22k
                ssl_state->server_connp.cert0_serial, ssl_state->server_connp.cert0_serial_len);
2907
15.2k
    if (ssl_state->server_connp.cert0_fingerprint)
2908
3.22k
        SCFree(ssl_state->server_connp.cert0_fingerprint);
2909
15.2k
    if (ssl_state->server_connp.sni)
2910
26
        SCFree(ssl_state->server_connp.sni);
2911
15.2k
    if (ssl_state->server_connp.session_id)
2912
4.33k
        SCFree(ssl_state->server_connp.session_id);
2913
2914
15.2k
    if (ssl_state->client_connp.hs)
2915
13.2k
        SCTLSHandshakeFree(ssl_state->client_connp.hs);
2916
15.2k
    if (ssl_state->client_connp.ja3_str)
2917
10.3k
        Ja3BufferFree(&ssl_state->client_connp.ja3_str);
2918
15.2k
    if (ssl_state->client_connp.ja3_hash)
2919
9.26k
        SCFree(ssl_state->client_connp.ja3_hash);
2920
15.2k
    if (ssl_state->server_connp.hs)
2921
10.4k
        SCTLSHandshakeFree(ssl_state->server_connp.hs);
2922
15.2k
    if (ssl_state->server_connp.ja3_str)
2923
6.54k
        Ja3BufferFree(&ssl_state->server_connp.ja3_str);
2924
15.2k
    if (ssl_state->server_connp.ja3_hash)
2925
6.33k
        SCFree(ssl_state->server_connp.ja3_hash);
2926
15.2k
    if (ssl_state->server_connp.hs_buffer)
2927
530
        SCFree(ssl_state->server_connp.hs_buffer);
2928
2929
15.2k
    SSLStateCertSANFree(&ssl_state->server_connp);
2930
15.2k
    SSLStateCertSANFree(&ssl_state->client_connp);
2931
2932
15.2k
    SCAppLayerTxDataCleanup(&ssl_state->tx_data);
2933
2934
    /* Free certificate chain */
2935
15.2k
    if (ssl_state->server_connp.certs_buffer)
2936
3.82k
        SCFree(ssl_state->server_connp.certs_buffer);
2937
21.6k
    while ((item = TAILQ_FIRST(&ssl_state->server_connp.certs))) {
2938
6.44k
        TAILQ_REMOVE(&ssl_state->server_connp.certs, item, next);
2939
6.44k
        SCFree(item);
2940
6.44k
    }
2941
15.2k
    TAILQ_INIT(&ssl_state->server_connp.certs);
2942
    /* Free certificate chain */
2943
15.2k
    if (ssl_state->client_connp.certs_buffer)
2944
676
        SCFree(ssl_state->client_connp.certs_buffer);
2945
16.0k
    while ((item = TAILQ_FIRST(&ssl_state->client_connp.certs))) {
2946
819
        TAILQ_REMOVE(&ssl_state->client_connp.certs, item, next);
2947
819
        SCFree(item);
2948
819
    }
2949
15.2k
    TAILQ_INIT(&ssl_state->client_connp.certs);
2950
2951
15.2k
    SCFree(ssl_state);
2952
15.2k
}
2953
2954
static void SSLStateTransactionFree(void *state, uint64_t tx_id)
2955
778
{
2956
    /* do nothing */
2957
778
}
2958
2959
static AppProto SSLProbingParser(
2960
        const Flow *f, uint8_t direction, const uint8_t *input, uint32_t ilen, uint8_t *rdir)
2961
13.5k
{
2962
    /* probably a rst/fin sending an eof */
2963
13.5k
    if (ilen < 3)
2964
1.94k
        return ALPROTO_UNKNOWN;
2965
2966
    /* for now just the 3 byte header ones */
2967
    /* \todo Detect the 2 byte ones */
2968
11.6k
    if ((input[0] & 0x80) && (input[2] == 0x01)) {
2969
295
        return ALPROTO_TLS;
2970
295
    }
2971
2972
11.3k
    return ALPROTO_FAILED;
2973
11.6k
}
2974
2975
static int SSLStateGetStateIdByName(const char *name, const uint8_t direction)
2976
76
{
2977
76
    SCEnumCharMap *map =
2978
76
            direction == STREAM_TOSERVER ? tls_state_client_table : tls_state_server_table;
2979
2980
76
    int id = SCMapEnumNameToValue(name, map);
2981
76
    if (id < 0) {
2982
70
        return -1;
2983
70
    }
2984
6
    return id;
2985
76
}
2986
2987
static const char *SSLStateGetStateNameById(const int id, const uint8_t direction)
2988
1.97k
{
2989
1.97k
    SCEnumCharMap *map =
2990
1.97k
            direction == STREAM_TOSERVER ? tls_state_client_table : tls_state_server_table;
2991
1.97k
    const char *name = SCMapEnumValueToName(id, map);
2992
1.97k
    return name;
2993
1.97k
}
2994
2995
static int SSLStateGetFrameIdByName(const char *frame_name)
2996
345
{
2997
345
    int id = SCMapEnumNameToValue(frame_name, tls_frame_table);
2998
345
    if (id < 0) {
2999
94
        return -1;
3000
94
    }
3001
251
    return id;
3002
345
}
3003
3004
static const char *SSLStateGetFrameNameById(const uint8_t frame_id)
3005
69
{
3006
69
    const char *name = SCMapEnumValueToName(frame_id, tls_frame_table);
3007
69
    return name;
3008
69
}
3009
3010
static int SSLStateGetEventInfo(
3011
        const char *event_name, uint8_t *event_id, AppLayerEventType *event_type)
3012
18.7k
{
3013
18.7k
    if (SCAppLayerGetEventIdByName(event_name, tls_decoder_event_table, event_id) == 0) {
3014
17.1k
        *event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
3015
17.1k
        return 0;
3016
17.1k
    }
3017
1.58k
    return -1;
3018
18.7k
}
3019
3020
static int SSLStateGetEventInfoById(
3021
        uint8_t event_id, const char **event_name, AppLayerEventType *event_type)
3022
17.8k
{
3023
17.8k
    *event_name = SCMapEnumValueToName(event_id, tls_decoder_event_table);
3024
17.8k
    if (*event_name == NULL) {
3025
0
        SCLogError("event \"%d\" not present in "
3026
0
                   "ssl's enum map table.",
3027
0
                event_id);
3028
        /* yes this is fatal */
3029
0
        return -1;
3030
0
    }
3031
3032
17.8k
    *event_type = APP_LAYER_EVENT_TYPE_TRANSACTION;
3033
3034
17.8k
    return 0;
3035
17.8k
}
3036
3037
static int SSLRegisterPatternsForProtocolDetection(void)
3038
14
{
3039
14
    if (SCAppLayerProtoDetectPMRegisterPatternCSwPP(IPPROTO_TCP, ALPROTO_TLS, "|01 00 02|", 5, 2,
3040
14
                STREAM_TOSERVER, SSLProbingParser, 0, 3) < 0) {
3041
0
        return -1;
3042
0
    }
3043
3044
    /** SSLv3 */
3045
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3046
14
                IPPROTO_TCP, ALPROTO_TLS, "|01 03 00|", 3, 0, STREAM_TOSERVER) < 0) {
3047
0
        return -1;
3048
0
    }
3049
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3050
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 00|", 3, 0, STREAM_TOSERVER) < 0) {
3051
0
        return -1;
3052
0
    }
3053
3054
    /** TLSv1 */
3055
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3056
14
                IPPROTO_TCP, ALPROTO_TLS, "|01 03 01|", 3, 0, STREAM_TOSERVER) < 0) {
3057
0
        return -1;
3058
0
    }
3059
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3060
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 01|", 3, 0, STREAM_TOSERVER) < 0) {
3061
0
        return -1;
3062
0
    }
3063
3064
    /** TLSv1.1 */
3065
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3066
14
                IPPROTO_TCP, ALPROTO_TLS, "|01 03 02|", 3, 0, STREAM_TOSERVER) < 0) {
3067
0
        return -1;
3068
0
    }
3069
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3070
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 02|", 3, 0, STREAM_TOSERVER) < 0) {
3071
0
        return -1;
3072
0
    }
3073
3074
    /** TLSv1.2 */
3075
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3076
14
                IPPROTO_TCP, ALPROTO_TLS, "|01 03 03|", 3, 0, STREAM_TOSERVER) < 0) {
3077
0
        return -1;
3078
0
    }
3079
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3080
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 03|", 3, 0, STREAM_TOSERVER) < 0) {
3081
0
        return -1;
3082
0
    }
3083
3084
    /***** toclient direction *****/
3085
3086
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3087
14
                IPPROTO_TCP, ALPROTO_TLS, "|15 03 00|", 3, 0, STREAM_TOCLIENT) < 0) {
3088
0
        return -1;
3089
0
    }
3090
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3091
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 00|", 3, 0, STREAM_TOCLIENT) < 0) {
3092
0
        return -1;
3093
0
    }
3094
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3095
14
                IPPROTO_TCP, ALPROTO_TLS, "|17 03 00|", 3, 0, STREAM_TOCLIENT) < 0) {
3096
0
        return -1;
3097
0
    }
3098
3099
    /** TLSv1 */
3100
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3101
14
                IPPROTO_TCP, ALPROTO_TLS, "|15 03 01|", 3, 0, STREAM_TOCLIENT) < 0) {
3102
0
        return -1;
3103
0
    }
3104
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3105
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 01|", 3, 0, STREAM_TOCLIENT) < 0) {
3106
0
        return -1;
3107
0
    }
3108
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3109
14
                IPPROTO_TCP, ALPROTO_TLS, "|17 03 01|", 3, 0, STREAM_TOCLIENT) < 0) {
3110
0
        return -1;
3111
0
    }
3112
3113
    /** TLSv1.1 */
3114
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3115
14
                IPPROTO_TCP, ALPROTO_TLS, "|15 03 02|", 3, 0, STREAM_TOCLIENT) < 0) {
3116
0
        return -1;
3117
0
    }
3118
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3119
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 02|", 3, 0, STREAM_TOCLIENT) < 0) {
3120
0
        return -1;
3121
0
    }
3122
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3123
14
                IPPROTO_TCP, ALPROTO_TLS, "|17 03 02|", 3, 0, STREAM_TOCLIENT) < 0) {
3124
0
        return -1;
3125
0
    }
3126
3127
    /** TLSv1.2 */
3128
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3129
14
                IPPROTO_TCP, ALPROTO_TLS, "|15 03 03|", 3, 0, STREAM_TOCLIENT) < 0) {
3130
0
        return -1;
3131
0
    }
3132
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3133
14
                IPPROTO_TCP, ALPROTO_TLS, "|16 03 03|", 3, 0, STREAM_TOCLIENT) < 0) {
3134
0
        return -1;
3135
0
    }
3136
14
    if (SCAppLayerProtoDetectPMRegisterPatternCS(
3137
14
                IPPROTO_TCP, ALPROTO_TLS, "|17 03 03|", 3, 0, STREAM_TOCLIENT) < 0) {
3138
0
        return -1;
3139
0
    }
3140
3141
    /* Subsection - SSLv2 style record by client, but informing the server
3142
     * the max version it supports.
3143
     * Updated by Anoop Saldanha.  Disabled it for now.  We'll get back to
3144
     * it after some tests */
3145
#if 0
3146
    if (SCAppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS,
3147
                                               "|01 03 00|", 5, 2, STREAM_TOSERVER) < 0)
3148
    {
3149
        return -1;
3150
    }
3151
    if (SCAppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS,
3152
                                               "|00 02|", 7, 5, STREAM_TOCLIENT) < 0)
3153
    {
3154
        return -1;
3155
    }
3156
#endif
3157
3158
14
    return 0;
3159
14
}
3160
3161
#ifdef HAVE_JA3
3162
static void CheckJA3Enabled(void)
3163
14
{
3164
14
    const char *strval = NULL;
3165
    /* Check if we should generate JA3 fingerprints */
3166
14
    int enable_ja3 = SSL_CONFIG_DEFAULT_JA3;
3167
14
    if (SCConfGetNonNull("app-layer.protocols.tls.ja3-fingerprints", &strval) != 1) {
3168
14
        enable_ja3 = SSL_CONFIG_DEFAULT_JA3;
3169
14
    } else if (strcmp(strval, "auto") == 0) {
3170
0
        enable_ja3 = SSL_CONFIG_DEFAULT_JA3;
3171
0
    } else if (SCConfValIsFalse(strval)) {
3172
0
        enable_ja3 = 0;
3173
0
        ssl_config.disable_ja3 = true;
3174
0
    } else if (SCConfValIsTrue(strval)) {
3175
0
        enable_ja3 = true;
3176
0
    }
3177
14
    SC_ATOMIC_SET(ssl_config.enable_ja3, enable_ja3);
3178
14
    if (!ssl_config.disable_ja3 && !g_disable_hashing) {
3179
        /* The feature is available, i.e. _could_ be activated by a rule or
3180
            even is enabled in the configuration. */
3181
14
        ProvidesFeature(FEATURE_JA3);
3182
14
    }
3183
14
}
3184
#endif /* HAVE_JA3 */
3185
3186
#ifdef HAVE_JA4
3187
static void CheckJA4Enabled(void)
3188
14
{
3189
14
    const char *strval = NULL;
3190
    /* Check if we should generate JA4 fingerprints */
3191
14
    int enable_ja4 = SSL_CONFIG_DEFAULT_JA4;
3192
14
    if (SCConfGetNonNull("app-layer.protocols.tls.ja4-fingerprints", &strval) != 1) {
3193
14
        enable_ja4 = SSL_CONFIG_DEFAULT_JA4;
3194
14
    } else if (strcmp(strval, "auto") == 0) {
3195
0
        enable_ja4 = SSL_CONFIG_DEFAULT_JA4;
3196
0
    } else if (SCConfValIsFalse(strval)) {
3197
0
        enable_ja4 = 0;
3198
0
        ssl_config.disable_ja4 = true;
3199
0
    } else if (SCConfValIsTrue(strval)) {
3200
0
        enable_ja4 = true;
3201
0
    }
3202
14
    SC_ATOMIC_SET(ssl_config.enable_ja4, enable_ja4);
3203
14
    if (!ssl_config.disable_ja4 && !g_disable_hashing) {
3204
        /* The feature is available, i.e. _could_ be activated by a rule or
3205
            even is enabled in the configuration. */
3206
14
        ProvidesFeature(FEATURE_JA4);
3207
14
    }
3208
14
}
3209
#endif /* HAVE_JA4 */
3210
3211
/**
3212
 * \brief Function to register the SSL protocol parser and other functions
3213
 */
3214
void RegisterSSLParsers(void)
3215
14
{
3216
14
    const char *proto_name = "tls";
3217
3218
14
    SC_ATOMIC_INIT(ssl_config.enable_ja3);
3219
3220
    /** SSLv2  and SSLv23*/
3221
14
    if (SCAppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) {
3222
14
        AppLayerProtoDetectRegisterProtocol(ALPROTO_TLS, proto_name);
3223
3224
14
        if (SSLRegisterPatternsForProtocolDetection() < 0)
3225
0
            return;
3226
3227
14
        if (RunmodeIsUnittests()) {
3228
0
            SCAppLayerProtoDetectPPRegister(
3229
0
                    IPPROTO_TCP, "443", ALPROTO_TLS, 0, 3, STREAM_TOSERVER, SSLProbingParser, NULL);
3230
14
        } else {
3231
14
            if (SCAppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, proto_name, ALPROTO_TLS,
3232
14
                        0, 3, SSLProbingParser, NULL) == 0) {
3233
14
                SCLogConfig("no TLS config found, "
3234
14
                            "enabling TLS detection on port 443.");
3235
14
                SCAppLayerProtoDetectPPRegister(IPPROTO_TCP, "443", ALPROTO_TLS, 0, 3,
3236
14
                        STREAM_TOSERVER, SSLProbingParser, NULL);
3237
14
            }
3238
14
        }
3239
14
    } else {
3240
0
        SCLogConfig("Protocol detection and parser disabled for %s protocol",
3241
0
                  proto_name);
3242
0
        return;
3243
0
    }
3244
3245
14
    if (SCAppLayerParserConfParserEnabled("tcp", proto_name)) {
3246
14
        AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER,
3247
14
                                     SSLParseClientRecord);
3248
3249
14
        AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_TLS, STREAM_TOCLIENT,
3250
14
                                     SSLParseServerRecord);
3251
14
        AppLayerParserRegisterGetStateFuncs(
3252
14
                IPPROTO_TCP, ALPROTO_TLS, SSLStateGetStateIdByName, SSLStateGetStateNameById);
3253
14
        AppLayerParserRegisterGetFrameFuncs(
3254
14
                IPPROTO_TCP, ALPROTO_TLS, SSLStateGetFrameIdByName, SSLStateGetFrameNameById);
3255
14
        AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_TLS, SSLStateGetEventInfo);
3256
14
        AppLayerParserRegisterGetEventInfoById(IPPROTO_TCP, ALPROTO_TLS, SSLStateGetEventInfoById);
3257
3258
14
        AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_TLS, SSLStateAlloc, SSLStateFree);
3259
3260
14
        SCAppLayerParserRegisterParserAcceptableDataDirection(
3261
14
                IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER);
3262
3263
14
        AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_TLS, SSLStateTransactionFree);
3264
3265
14
        AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_TLS, SSLGetTx);
3266
14
        AppLayerParserRegisterTxDataFunc(IPPROTO_TCP, ALPROTO_TLS, SSLGetTxData);
3267
14
        AppLayerParserRegisterStateDataFunc(IPPROTO_TCP, ALPROTO_TLS, SSLGetStateData);
3268
3269
14
        AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_TLS, SSLGetTxCnt);
3270
3271
14
        AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_TLS, SSLGetAlstateProgress);
3272
3273
14
        AppLayerParserRegisterStateProgressCompletionStatus(
3274
14
                ALPROTO_TLS, TLS_STATE_CLIENT_FINISHED, TLS_STATE_SERVER_FINISHED);
3275
3276
14
        SCConfNode *enc_handle = SCConfGetNode("app-layer.protocols.tls.encryption-handling");
3277
14
        if (enc_handle != NULL && enc_handle->val != NULL) {
3278
0
            SCLogDebug("have app-layer.protocols.tls.encryption-handling = %s", enc_handle->val);
3279
0
            if (strcmp(enc_handle->val, "full") == 0) {
3280
0
                ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_FULL;
3281
0
            } else if (strcmp(enc_handle->val, "bypass") == 0) {
3282
0
                ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_BYPASS;
3283
0
            } else if (strcmp(enc_handle->val, "track-only") == 0) {
3284
0
                ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_TRACK_ONLY;
3285
0
            } else if (strcmp(enc_handle->val, "default") == 0) {
3286
0
                SCLogWarning("app-layer.protocols.tls.encryption-handling = default is deprecated "
3287
0
                             "and will be removed in Suricata 9, use \"track-only\" instead, "
3288
0
                             "(see ticket #7642)");
3289
0
                ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_TRACK_ONLY;
3290
0
            } else {
3291
0
                ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_TRACK_ONLY;
3292
0
            }
3293
14
        } else {
3294
            /* Get the value of no reassembly option from the config file */
3295
14
            if (SCConfGetNode("app-layer.protocols.tls.no-reassemble") == NULL) {
3296
14
                int value = 0;
3297
14
                if (SCConfGetBool("tls.no-reassemble", &value) == 1 && value == 1)
3298
0
                    ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_BYPASS;
3299
14
            } else {
3300
0
                int value = 0;
3301
0
                if (SCConfGetBool("app-layer.protocols.tls.no-reassemble", &value) == 1 &&
3302
0
                        value == 1)
3303
0
                    ssl_config.encrypt_mode = SSL_CNF_ENC_HANDLE_BYPASS;
3304
0
            }
3305
14
        }
3306
14
        SCLogDebug("ssl_config.encrypt_mode %u", ssl_config.encrypt_mode);
3307
3308
14
#ifdef HAVE_JA3
3309
14
        CheckJA3Enabled();
3310
14
#endif /* HAVE_JA3 */
3311
14
#ifdef HAVE_JA4
3312
14
        CheckJA4Enabled();
3313
14
#endif /* HAVE_JA4 */
3314
3315
14
        if (g_disable_hashing) {
3316
0
            if (SC_ATOMIC_GET(ssl_config.enable_ja3)) {
3317
0
                SCLogWarning("MD5 calculation has been disabled, disabling JA3");
3318
0
                SC_ATOMIC_SET(ssl_config.enable_ja3, 0);
3319
0
            }
3320
0
            if (SC_ATOMIC_GET(ssl_config.enable_ja4)) {
3321
0
                SCLogWarning("Hashing has been disabled, disabling JA4");
3322
0
                SC_ATOMIC_SET(ssl_config.enable_ja4, 0);
3323
0
            }
3324
14
        } else {
3325
14
            if (RunmodeIsUnittests()) {
3326
0
#ifdef HAVE_JA3
3327
0
                SC_ATOMIC_SET(ssl_config.enable_ja3, 1);
3328
0
#endif /* HAVE_JA3 */
3329
0
#ifdef HAVE_JA4
3330
0
                SC_ATOMIC_SET(ssl_config.enable_ja4, 1);
3331
0
#endif /* HAVE_JA4 */
3332
0
            }
3333
14
        }
3334
14
    } else {
3335
0
        SCLogConfig("Parser disabled for %s protocol. Protocol detection still on.", proto_name);
3336
0
    }
3337
14
}
3338
3339
/**
3340
 * \brief if not explicitly disabled in config, enable ja3 support
3341
 *
3342
 * Implemented using atomic to allow rule reloads to do this at
3343
 * runtime.
3344
 */
3345
void SSLEnableJA3(void)
3346
7.28k
{
3347
7.28k
    if (g_disable_hashing || ssl_config.disable_ja3) {
3348
0
        return;
3349
0
    }
3350
7.28k
    if (SC_ATOMIC_GET(ssl_config.enable_ja3)) {
3351
7.27k
        return;
3352
7.27k
    }
3353
6
    SC_ATOMIC_SET(ssl_config.enable_ja3, 1);
3354
6
}
3355
3356
/**
3357
 * \brief if not explicitly disabled in config, enable ja4 support
3358
 *
3359
 * Implemented using atomic to allow rule reloads to do this at
3360
 * runtime.
3361
 */
3362
void SSLEnableJA4(void)
3363
1.09k
{
3364
    // only caller has #ifdef HAVE_JA4
3365
1.09k
    if (g_disable_hashing || ssl_config.disable_ja4) {
3366
0
        return;
3367
0
    }
3368
1.09k
    if (SC_ATOMIC_GET(ssl_config.enable_ja4)) {
3369
1.08k
        return;
3370
1.08k
    }
3371
7
    SC_ATOMIC_SET(ssl_config.enable_ja4, 1);
3372
7
}
3373
3374
/**
3375
 * \brief return whether ja3 is effectively enabled
3376
 *
3377
 * This means that it either has been enabled explicitly or has been
3378
 * enabled by having loaded a rule while not being explicitly disabled.
3379
 *
3380
 * \retval true if enabled, false otherwise
3381
 */
3382
bool SSLJA3IsEnabled(void)
3383
7.28k
{
3384
7.28k
    return SC_ATOMIC_GET(ssl_config.enable_ja3);
3385
7.28k
}
3386
3387
/**
3388
 * \brief return whether ja4 is effectively enabled
3389
 *
3390
 * This means that it either has been enabled explicitly or has been
3391
 * enabled by having loaded a rule while not being explicitly disabled.
3392
 *
3393
 * \retval true if enabled, false otherwise
3394
 */
3395
bool SSLJA4IsEnabled(void)
3396
1.09k
{
3397
    return SC_ATOMIC_GET(ssl_config.enable_ja4);
3398
1.09k
}