Coverage Report

Created: 2026-09-28 07:39

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