Coverage Report

Created: 2026-11-12 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wireshark/epan/dissectors/packet-tls.c
Line
Count
Source
1
/* packet-tls.c
2
 * Routines for TLS dissection
3
 * Copyright (c) 2000-2001, Scott Renfro <scott@renfro.org>
4
 * Copyright 2013-2019, Peter Wu <peter@lekensteyn.nl>
5
 *
6
 * Wireshark - Network traffic analyzer
7
 * By Gerald Combs <gerald@wireshark.org>
8
 * Copyright 1998 Gerald Combs
9
 *
10
 * SPDX-License-Identifier: GPL-2.0-or-later
11
 */
12
13
/*
14
 * Supported protocol versions:
15
 *
16
 *  TLS 1.3, 1.2, 1.0, and SSL 3.0. SSL 2.0 is no longer supported, except for
17
 *  the SSL 2.0-compatible Client Hello.
18
 *
19
 * Primary protocol specifications:
20
 *
21
 *  https://tools.ietf.org/html/draft-hickman-netscape-ssl-00 - SSL 2.0
22
 *  https://tools.ietf.org/html/rfc6101 - SSL 3.0
23
 *  https://tools.ietf.org/html/rfc2246 - TLS 1.0
24
 *  https://tools.ietf.org/html/rfc4346 - TLS 1.1
25
 *  https://tools.ietf.org/html/rfc5246 - TLS 1.2
26
 *  https://tools.ietf.org/html/rfc8446 - TLS 1.3
27
 *
28
 * Important IANA registries:
29
 *
30
 *  https://www.iana.org/assignments/tls-parameters/
31
 *  https://www.iana.org/assignments/tls-extensiontype-values/
32
 *
33
 * Notes:
34
 *
35
 *    - Decryption needs to be performed 'sequentially', so it's done
36
 *      at packet reception time. This may cause a significant packet capture
37
 *      slow down. This also causes dissection of some ssl info that in previous
38
 *      dissector versions was dissected only when a proto_tree context was
39
 *      available
40
 *
41
 *     We are at Packet reception if time pinfo->fd->visited == 0
42
 *
43
 *    - Many dissection and decryption operations are implemented in
44
 *      epan/dissectors/packet-tls-utils.c and
45
 *      epan/dissectors/packet-tls-utils.h due to an overlap of functionality
46
 *      with DTLS (epan/dissectors/packet-dtls.c).
47
 *
48
 */
49
50
#include "config.h"
51
52
#include <epan/packet.h>
53
#include <epan/reassemble.h>
54
#include <epan/asn1.h>
55
#include <epan/tap.h>
56
#include <epan/uat.h>
57
#include <epan/addr_resolv.h>
58
#include <epan/follow.h>
59
#include <epan/exported_pdu.h>
60
#include <epan/proto_data.h>
61
#include <epan/decode_as.h>
62
#include <epan/prefs-int.h>
63
#include <epan/secrets.h>
64
#include <wiretap/secrets-types.h>
65
66
#include <wsutil/utf8_entities.h>
67
#include <wsutil/str_util.h>
68
#include <wsutil/strtoi.h>
69
#include <wsutil/rsa.h>
70
#include <wsutil/ws_assert.h>
71
#include <wsutil/filesystem.h>
72
#include <wsutil/report_message.h>
73
#include "conversation.h"
74
#include "packet-tcp.h"
75
#include "packet-x509af.h"
76
#include "packet-tls.h"
77
#include "packet-tls-utils.h"
78
#include "packet-ber.h"
79
80
void proto_register_tls(void);
81
82
#ifdef HAVE_LIBGNUTLS
83
static ssldecrypt_assoc_t *tlskeylist_uats;
84
static unsigned ntlsdecrypt;
85
#endif
86
87
static bool tls_desegment          = true;
88
static bool tls_desegment_app_data = true;
89
static bool tls_ignore_mac_failed;
90
91
16
#define PORT_HEUR_DEFAULT "443"
92
/* Try heuristic dissectors before dissectors assigned to a port.
93
 * Dissectors assigned via ALPN always take precedence. */
94
static range_t *tls_try_heuristic_first;
95
96
/*********************************************************************
97
 *
98
 * Protocol Constants, Variables, Data Structures
99
 *
100
 *********************************************************************/
101
102
/* Initialize the protocol and registered fields */
103
static int tls_follow_tap                    = -1;
104
static int exported_pdu_tap                  = -1;
105
static int proto_tls;
106
static int hf_tls_stream;
107
static int hf_tls_record;
108
static int hf_tls_record_content_type;
109
static int hf_tls_record_opaque_type;
110
static int hf_tls_record_version;
111
static int hf_tls_record_length;
112
static int hf_tls_record_sequence_number;
113
static int hf_tls_record_appdata;
114
static int hf_tls_record_appdata_proto;
115
static int hf_ssl2_record;
116
static int hf_ssl2_record_is_escape;
117
static int hf_ssl2_record_padding_length;
118
static int hf_ssl2_msg_type;
119
static int hf_tls_alert_message;
120
static int hf_tls_alert_message_level;
121
static int hf_tls_alert_message_description;
122
static int hf_tls_handshake_protocol;
123
static int hf_tls_handshake_type;
124
static int hf_tls_handshake_length;
125
static int hf_tls_handshake_npn_selected_protocol_len;
126
static int hf_tls_handshake_npn_selected_protocol;
127
static int hf_tls_handshake_npn_padding_len;
128
static int hf_tls_handshake_npn_padding;
129
static int hf_ssl2_handshake_cipher_spec_len;
130
static int hf_ssl2_handshake_session_id_len;
131
static int hf_ssl2_handshake_challenge_len;
132
static int hf_ssl2_handshake_cipher_spec;
133
static int hf_ssl2_handshake_challenge;
134
static int hf_ssl2_handshake_clear_key_len;
135
static int hf_ssl2_handshake_enc_key_len;
136
static int hf_ssl2_handshake_key_arg_len;
137
static int hf_ssl2_handshake_clear_key;
138
static int hf_ssl2_handshake_enc_key;
139
static int hf_ssl2_handshake_key_arg;
140
static int hf_ssl2_handshake_session_id_hit;
141
static int hf_ssl2_handshake_cert_type;
142
static int hf_ssl2_handshake_connection_id_len;
143
static int hf_ssl2_handshake_connection_id;
144
145
static int hf_tls_reassembled_in;
146
static int hf_tls_reassembled_length;
147
static int hf_tls_reassembled_data;
148
static int hf_tls_segments;
149
static int hf_tls_segment;
150
static int hf_tls_segment_overlap;
151
static int hf_tls_segment_overlap_conflict;
152
static int hf_tls_segment_multiple_tails;
153
static int hf_tls_segment_too_long_fragment;
154
static int hf_tls_segment_error;
155
static int hf_tls_segment_count;
156
static int hf_tls_segment_data;
157
158
static int hf_tls_handshake_reassembled_in;
159
static int hf_tls_handshake_fragments;
160
static int hf_tls_handshake_fragment;
161
static int hf_tls_handshake_fragment_count;
162
163
static int hf_tls_heartbeat_message;
164
static int hf_tls_heartbeat_message_type;
165
static int hf_tls_heartbeat_message_payload_length;
166
static int hf_tls_heartbeat_message_payload;
167
static int hf_tls_heartbeat_message_padding;
168
169
static ssl_hfs_t ssl_hfs;
170
171
/* Initialize the subtree pointers */
172
static int ett_tls;
173
static int ett_tls_record;
174
static int ett_tls_alert;
175
static int ett_tls_handshake;
176
static int ett_tls_heartbeat;
177
static int ett_tls_certs;
178
static int ett_tls_segments;
179
static int ett_tls_segment;
180
static int ett_tls_hs_fragments;
181
static int ett_tls_hs_fragment;
182
183
static expert_field ei_ssl2_handshake_session_id_len_error;
184
static expert_field ei_ssl3_heartbeat_payload_length;
185
static expert_field ei_tls_unexpected_message;
186
187
/* Generated from convert_proto_tree_add_text.pl */
188
static expert_field ei_tls_ignored_unknown_record;
189
190
/* not all of the hf_fields below make sense for TLS but we have to provide
191
   them anyways to comply with the api (which was aimed for ip fragment
192
   reassembly) */
193
static const fragment_items ssl_segment_items = {
194
    &ett_tls_segment,
195
    &ett_tls_segments,
196
    &hf_tls_segments,
197
    &hf_tls_segment,
198
    &hf_tls_segment_overlap,
199
    &hf_tls_segment_overlap_conflict,
200
    &hf_tls_segment_multiple_tails,
201
    &hf_tls_segment_too_long_fragment,
202
    &hf_tls_segment_error,
203
    &hf_tls_segment_count,
204
    &hf_tls_reassembled_in,
205
    &hf_tls_reassembled_length,
206
    &hf_tls_reassembled_data,
207
    "Segments"
208
};
209
210
/* Fragmented handshake messages. */
211
static const fragment_items tls_hs_fragment_items = {
212
    &ett_tls_hs_fragment,
213
    &ett_tls_hs_fragments,
214
    &hf_tls_handshake_fragments,
215
    &hf_tls_handshake_fragment,
216
    &hf_tls_segment_overlap,    // Do not care about the errors, should not happen.
217
    &hf_tls_segment_overlap_conflict,
218
    &hf_tls_segment_multiple_tails,
219
    &hf_tls_segment_too_long_fragment,
220
    &hf_tls_segment_error,
221
    &hf_tls_handshake_fragment_count,
222
    NULL,                           /* unused - &hf_tls_handshake_reassembled_in, */
223
    NULL,                           /* do not display redundant length */
224
    NULL,                           /* do not display redundant data */
225
    "Fragments"
226
};
227
228
static SSL_COMMON_LIST_T(dissect_ssl3_hf);
229
230
static void
231
ssl_proto_tree_add_segment_data(
232
    proto_tree  *tree,
233
    tvbuff_t    *tvb,
234
    int          offset,
235
    int          length,
236
    const char *prefix)
237
205
{
238
205
    proto_tree_add_bytes_format(
239
205
        tree,
240
205
        hf_tls_segment_data,
241
205
        tvb,
242
205
        offset,
243
205
        length,
244
205
        NULL,
245
205
        "%sTLS segment data (%u %s)",
246
205
        prefix != NULL ? prefix : "",
247
205
        length,
248
205
        plurality(length, "byte", "bytes"));
249
205
}
250
251
252
static ssl_master_key_map_t       ssl_master_key_map;
253
254
#ifdef HAVE_LIBGNUTLS
255
static GHashTable         *ssl_key_hash;
256
static wmem_stack_t       *key_list_stack;
257
static uat_t              *ssldecrypt_uat;
258
#endif
259
static dissector_table_t   ssl_associations;
260
static dissector_handle_t  tls_handle;
261
static dissector_handle_t  tls13_handshake_handle;
262
static StringInfo          ssl_compressed_data;
263
static StringInfo          ssl_decrypted_data;
264
static unsigned            ssl_decrypted_data_avail;
265
static FILE               *ssl_keylog_file;
266
static ssl_common_options_t ssl_options;
267
268
/* List of dissectors to call for TLS data */
269
static heur_dissector_list_t ssl_heur_subdissector_list;
270
271
static const char *ssl_debug_file_name;
272
273
static uint32_t tls_stream_count;
274
275
/* Forward declaration we need below */
276
void proto_reg_handoff_ssl(void);
277
278
/* Desegmentation of TLS streams */
279
/* table to hold defragmented TLS streams */
280
static reassembly_table ssl_reassembly_table;
281
282
/* Table to hold fragmented TLS handshake records. */
283
static reassembly_table tls_hs_reassembly_table;
284
static uint32_t hs_reassembly_id_count;
285
286
/* Fragment TLS handshake reassembly functions. The records are
287
 * organized by session and direction; this allows reassembly across
288
 * QUIC connection migration when addresses and ports change.
289
 */
290
typedef struct _tls_hs_fragment_key {
291
        const SslSession *session;
292
        uint32_t id;
293
        bool from_server;
294
} tls_hs_fragment_key;
295
296
static unsigned
297
tls_hs_fragment_hash(const void *k)
298
7.12k
{
299
7.12k
        const tls_hs_fragment_key* key = (const tls_hs_fragment_key*) k;
300
7.12k
        return key->id;
301
7.12k
}
302
303
static int
304
tls_hs_fragment_equal(const void *k1, const void *k2)
305
3.13k
{
306
3.13k
        const tls_hs_fragment_key* key1 = (const tls_hs_fragment_key*) k1;
307
3.13k
        const tls_hs_fragment_key* key2 = (const tls_hs_fragment_key*) k2;
308
309
        /* The ids are unique across the capture. The direction can change
310
         * within a frame (ssl_set_server() on a ClientHello), so it must not
311
         * take part in the comparison. */
312
3.13k
        return key1->id == key2->id;
313
3.13k
}
314
315
static void *
316
tls_hs_fragment_temporary_key(const packet_info *pinfo, const uint32_t id,
317
                     const void *data)
318
7.05k
{
319
7.05k
        tls_hs_fragment_key *key = g_slice_new0(tls_hs_fragment_key);
320
7.05k
        SslSession *session = (SslSession *)data;
321
7.05k
        key->id = id;
322
7.05k
        key->session = session;
323
7.05k
        key->from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
324
7.05k
        return key;
325
7.05k
}
326
327
static void
328
tls_hs_fragment_free_temporary_key(void *ptr)
329
5.12k
{
330
5.12k
        tls_hs_fragment_key *key = (tls_hs_fragment_key *)ptr;
331
5.12k
        g_slice_free(tls_hs_fragment_key, key);
332
5.12k
}
333
334
static const reassembly_table_functions
335
tls_hs_reassembly_table_functions = {
336
        tls_hs_fragment_hash,
337
        tls_hs_fragment_equal,
338
        tls_hs_fragment_temporary_key,
339
        tls_hs_fragment_temporary_key,
340
        tls_hs_fragment_free_temporary_key,
341
        tls_hs_fragment_free_temporary_key,
342
};
343
344
static uint32_t get_tls_stream_count(void)
345
0
{
346
0
    return tls_stream_count;
347
0
}
348
349
uint32_t tls_increment_stream_count(void)
350
46
{
351
46
    return tls_stream_count++;
352
46
}
353
354
/* initialize/reset per capture state data (ssl sessions cache) */
355
static void
356
ssl_init(void)
357
16
{
358
16
    ssl_common_init(&ssl_master_key_map,
359
16
                    &ssl_decrypted_data, &ssl_compressed_data);
360
16
    ssl_debug_flush();
361
362
    /* Reset the identifier for a group of handshake fragments. */
363
16
    hs_reassembly_id_count = 0;
364
365
16
    tls_stream_count = 0;
366
16
}
367
368
static void
369
ssl_cleanup(void)
370
0
{
371
#ifdef HAVE_LIBGNUTLS
372
    if (key_list_stack != NULL) {
373
        wmem_destroy_stack(key_list_stack);
374
        key_list_stack = NULL;
375
    }
376
#endif
377
0
    ssl_common_cleanup(&ssl_master_key_map, &ssl_keylog_file,
378
0
                       &ssl_decrypted_data, &ssl_compressed_data);
379
0
}
380
381
static unsigned
382
ssl_session_key_count(void)
383
0
{
384
0
    unsigned count = 0;
385
0
    ssl_master_key_map_t* mk_map = tls_get_master_key_map(false);
386
0
    if (!mk_map || !mk_map->used_crandom)
387
0
        return count;
388
389
0
    GHashTableIter iter;
390
0
    void* key;
391
392
0
    g_hash_table_iter_init(&iter, mk_map->used_crandom);
393
0
    while (g_hash_table_iter_next(&iter, &key, NULL)) {
394
0
        if (g_hash_table_contains(mk_map->crandom, key)) {
395
0
            count++;
396
0
        }
397
0
        if (g_hash_table_contains(mk_map->tls13_client_early, key)) {
398
0
            count++;
399
0
        }
400
0
        if (g_hash_table_contains(mk_map->tls13_client_handshake, key)) {
401
0
            count++;
402
0
        }
403
0
        if (g_hash_table_contains(mk_map->tls13_server_handshake, key)) {
404
0
            count++;
405
0
        }
406
0
        if (g_hash_table_contains(mk_map->tls13_client_appdata, key)) {
407
0
            count++;
408
0
        }
409
0
        if (g_hash_table_contains(mk_map->tls13_server_appdata, key)) {
410
0
            count++;
411
0
        }
412
0
        if (g_hash_table_contains(mk_map->ech_secret, key)) {
413
0
            count++;
414
0
        }
415
0
        if (g_hash_table_contains(mk_map->ech_config, key)) {
416
0
            count++;
417
0
        }
418
0
    }
419
0
    return count;
420
0
}
421
422
static void
423
tls_export_client_randoms_func(void* key, void* value, void* user_data, const char* label)
424
0
{
425
0
    unsigned i;
426
0
    StringInfo* client_random = (StringInfo*)key;
427
0
    StringInfo* master_secret = (StringInfo*)value;
428
0
    GString* keylist = (GString*)user_data;
429
430
0
    g_string_append(keylist, label);
431
432
0
    for (i = 0; i < client_random->data_len; i++) {
433
0
        g_string_append_printf(keylist, "%.2x", client_random->data[i]);
434
0
    }
435
436
0
    g_string_append_c(keylist, ' ');
437
438
0
    for (i = 0; i < master_secret->data_len; i++) {
439
0
        g_string_append_printf(keylist, "%.2x", master_secret->data[i]);
440
0
    }
441
442
0
    g_string_append_c(keylist, '\n');
443
0
}
444
445
static char*
446
ssl_export_sessions(size_t* length)
447
0
{
448
    /* Output format is:
449
     * "CLIENT_RANDOM zzzz yyyy\n"
450
     * Where zzzz is the client random (always 64 chars)
451
     * Where yyyy is same as above
452
     * So length will always be 13+1+64+1+96+2 = 177 chars
453
     *
454
     * Wireshark can read CLIENT_RANDOM since v1.8.0.
455
     * Both values are exported in case you use the Session-ID for resuming a
456
     * session in a different capture.
457
     *
458
     * TLS 1.3 derived secrets are similar to the CLIENT_RANDOM master secret
459
     * export, but with a (longer) label indicating the type of derived secret
460
     * to which the client random maps, e.g.
461
     * "CLIENT_HANDSHAKE_TRAFFIC_SECRET zzzz yyyy\n"
462
     *
463
     * The TLS 1.3 values are obtained from an existing key log, but exporting
464
     * them is useful in order to filter actually used secrets or add a DSB.
465
     */
466
0
    ssl_master_key_map_t* mk_map = tls_get_master_key_map(false);
467
468
0
    if (!mk_map) {
469
0
        *length = 0;
470
0
        return g_strdup("");
471
0
    }
472
473
0
    size_t len = 177 * (size_t)ssl_session_key_count();
474
0
    GString* keylist = g_string_sized_new(len);
475
476
0
    GHashTableIter iter;
477
0
    void* key, * value;
478
479
0
    g_hash_table_iter_init(&iter, mk_map->used_crandom);
480
0
    while (g_hash_table_iter_next(&iter, &key, NULL)) {
481
0
        if ((value = g_hash_table_lookup(mk_map->crandom, key))) {
482
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "CLIENT_RANDOM ");
483
0
        }
484
0
        if ((value = g_hash_table_lookup(mk_map->tls13_client_early, key))) {
485
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "CLIENT_EARLY_TRAFFIC_SECRET ");
486
0
        }
487
0
        if ((value = g_hash_table_lookup(mk_map->tls13_client_handshake, key))) {
488
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "CLIENT_HANDSHAKE_TRAFFIC_SECRET ");
489
0
        }
490
0
        if ((value = g_hash_table_lookup(mk_map->tls13_server_handshake, key))) {
491
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "SERVER_HANDSHAKE_TRAFFIC_SECRET ");
492
0
        }
493
0
        if ((value = g_hash_table_lookup(mk_map->tls13_server_appdata, key))) {
494
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "SERVER_TRAFFIC_SECRET_0 ");
495
0
        }
496
0
        if ((value = g_hash_table_lookup(mk_map->tls13_client_appdata, key))) {
497
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "CLIENT_TRAFFIC_SECRET_0 ");
498
0
        }
499
0
        if ((value = g_hash_table_lookup(mk_map->tls13_early_exporter, key))) {
500
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "EARLY_EXPORTER_SECRET ");
501
0
        }
502
0
        if ((value = g_hash_table_lookup(mk_map->tls13_exporter, key))) {
503
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "EXPORTER_SECRET ");
504
0
        }
505
0
        if ((value = g_hash_table_lookup(mk_map->ech_secret, key))) {
506
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "ECH_SECRET ");
507
0
        }
508
0
        if ((value = g_hash_table_lookup(mk_map->ech_config, key))) {
509
0
            tls_export_client_randoms_func(key, value, (void*)keylist, "ECH_CONFIG ");
510
0
        }
511
0
    }
512
513
0
    *length = keylist->len;
514
0
    return g_string_free(keylist, FALSE);
515
0
}
516
517
/** Add a DSB with the used TLS secrets to a capture file.
518
 *
519
 * @param wth Wiretap data
520
 */
521
static bool
522
tls_export_dsb(wtap* wth)
523
0
{
524
0
    wtap_block_t block;
525
0
    wtapng_dsb_mandatory_t* dsb;
526
0
    size_t secrets_len;
527
0
    char* secrets = ssl_export_sessions(&secrets_len);
528
529
0
    block = wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS);
530
0
    dsb = (wtapng_dsb_mandatory_t*)wtap_block_get_mandatory_data(block);
531
532
0
    dsb->secrets_type = SECRETS_TYPE_TLS;
533
0
    dsb->secrets_data = g_memdup2(secrets, secrets_len);
534
0
    dsb->secrets_len = (unsigned)secrets_len;
535
0
    g_free(secrets);
536
537
    /* XXX - support replacing the DSB of the same type instead of adding? */
538
0
    wtap_file_add_decryption_secrets(wth, block);
539
540
0
    return true;
541
0
}
542
543
ssl_master_key_map_t *
544
tls_get_master_key_map(bool load_secrets)
545
17
{
546
    // Try to load new keys.
547
17
    if (load_secrets) {
548
11
        ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
549
11
    }
550
17
    return &ssl_master_key_map;
551
17
}
552
553
#ifdef HAVE_LIBGNUTLS
554
/* parse ssl related preferences (private keys and ports association strings) */
555
static void
556
ssl_parse_uat(void)
557
{
558
    unsigned           i;
559
    uint16_t           port;
560
    dissector_handle_t handle;
561
562
    ssl_set_debug(ssl_debug_file_name);
563
564
    if (ssl_key_hash)
565
    {
566
        g_hash_table_destroy(ssl_key_hash);
567
    }
568
569
    /* remove only associations created from key list */
570
    if (key_list_stack != NULL) {
571
        while (wmem_stack_count(key_list_stack) > 0) {
572
          port = GPOINTER_TO_UINT(wmem_stack_pop(key_list_stack));
573
          handle = dissector_get_uint_handle(ssl_associations, port);
574
          if (handle != NULL)
575
              ssl_association_remove("tls.port", tls_handle, handle, port, false);
576
        }
577
    }
578
    /* parse private keys string, load available keys and put them in key hash*/
579
    ssl_key_hash = privkey_hash_table_new();
580
581
582
    if (ntlsdecrypt > 0) {
583
        if (key_list_stack == NULL)
584
            key_list_stack = wmem_stack_new(NULL);
585
        for (i = 0; i < ntlsdecrypt; i++) {
586
            ssldecrypt_assoc_t *ssl_uat = &(tlskeylist_uats[i]);
587
            ssl_parse_key_list(ssl_uat, ssl_key_hash, "tls.port", tls_handle, true);
588
            if (key_list_stack && ws_strtou16(ssl_uat->port, NULL, &port) && port > 0)
589
                wmem_stack_push(key_list_stack, GUINT_TO_POINTER(port));
590
        }
591
    }
592
593
    ssl_debug_flush();
594
}
595
596
static void
597
ssl_reset_uat(void)
598
{
599
    g_hash_table_destroy(ssl_key_hash);
600
    ssl_key_hash = NULL;
601
}
602
#endif  /* HAVE_LIBGNUTLS */
603
604
/*********************************************************************
605
 *
606
 * Follow Stream support
607
 *
608
 *********************************************************************/
609
610
static char *
611
tls_follow_conv_filter(epan_dissect_t *edt _U_, packet_info *pinfo, unsigned *stream, unsigned *sub_stream _U_)
612
0
{
613
    /* This function wants to return "the" TLS stream for the frame.
614
     * If there are multiple, we prefer the inner one. While edt should
615
     * be non-NULL, because the pinfo lifetime is tied to the epan_dissect_t,
616
     * edt->tree can be NULL (e.g., when called by sharkd), which makes
617
     * it impossible to use anything in the tree as opposed to pinfo. */
618
619
0
    char *filter = NULL;
620
0
    const SslPacketInfo *pi = NULL;
621
0
    uint8_t max_layer_num = proto_get_layer_num(pinfo, proto_tls);
622
623
    /* The result from proto_get_layer_num is 1-indexed, and
624
     * includes times that the TLS dissector is called for times
625
     * that represent multiple PDUs in a frame (e.g., due to TCP
626
     * segmentation) in addition to times that represent nesting.
627
     */
628
0
    for (uint8_t curr_layer_num = max_layer_num; curr_layer_num; --curr_layer_num) {
629
        /* The (nesting) layer number in p_get_proto_data is 0-indexed. */
630
0
        pi = p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num - 1);
631
0
        if (pi) {
632
0
            *stream = pi->stream;
633
0
            filter = ws_strdup_printf("tls.stream eq %u", *stream);
634
0
            break;
635
0
        }
636
0
    }
637
638
0
    return filter;
639
0
}
640
641
static char *
642
tls_follow_index_filter(unsigned stream, unsigned sub_stream _U_)
643
0
{
644
0
    return ws_strdup_printf("tls.stream eq %u", stream);
645
0
}
646
647
tap_packet_status
648
ssl_follow_tap_listener(void *tapdata, packet_info *pinfo, epan_dissect_t *edt _U_, const void *ssl, tap_flags_t flags _U_)
649
0
{
650
0
    follow_info_t *      follow_info = (follow_info_t*) tapdata;
651
0
    follow_record_t * follow_record = NULL;
652
0
    const SslRecordInfo *appl_data = NULL;
653
0
    const SslPacketInfo *pi = (const SslPacketInfo*)ssl;
654
0
    show_stream_t        from = FROM_CLIENT;
655
656
    /* Skip packets without decrypted payload data. */
657
0
    if (!pi || !pi->records) return TAP_PACKET_DONT_REDRAW;
658
659
0
    if (follow_info->stream_id != pi->stream) return TAP_PACKET_DONT_REDRAW;
660
661
    /* Compute the packet's sender. */
662
0
    if (follow_info->client_port == 0) {
663
0
        follow_info->client_port = PINFO_SRCPORT(pinfo);
664
0
        copy_address(&follow_info->client_ip, PINFO_SRC(pinfo));
665
0
        follow_info->server_port = PINFO_DESTPORT(pinfo);
666
0
        copy_address(&follow_info->server_ip, PINFO_DST(pinfo));
667
0
    }
668
0
    if (addresses_equal(&follow_info->client_ip, PINFO_SRC(pinfo)) &&
669
0
            follow_info->client_port == PINFO_SRCPORT(pinfo)) {
670
0
        from = FROM_CLIENT;
671
0
    } else {
672
0
        from = FROM_SERVER;
673
0
    }
674
675
0
    for (appl_data = pi->records; appl_data != NULL; appl_data = appl_data->next) {
676
677
        /* Include only application data in the record, skipping things like
678
         * Handshake messages and alerts. */
679
0
        if (appl_data->type != SSL_ID_APP_DATA) continue;
680
681
        /* TCP segments that contain the end of two or more TLS PDUs will be
682
           queued to TLS taps for each of those PDUs. Therefore a single
683
           packet could be processed by this TLS tap listener multiple times.
684
           The following test handles that scenario by treating the
685
           follow_info->bytes_written[] values as the next expected
686
           appl_data->seq. Any appl_data instances that fall below that have
687
           already been processed and must be skipped. */
688
        /* XXX - If instead of tapping at the end of the entire frame,
689
         * the TLS (and DTLS) dissector tapped after each SSL_ID_APP_DATA
690
         * record (i.e., in dissect_dtls_appdata and process_ssl_payload,
691
         * as is done for the export PDU tap), we could skip the for loop
692
         * and these checks.
693
         *
694
         * Alternatively, instead of using the byte sequence here, we could
695
         * track record number instead, which might allow performing record
696
         * replay detection on DTLS and should still work on TLS.
697
         */
698
0
        if (appl_data->seq < follow_info->bytes_written[from]) continue;
699
700
        /* Allocate a follow_record_t to hold the current appl_data
701
           instance's decrypted data. Even though it would be possible to
702
           consolidate multiple appl_data instances into a single record, it is
703
           beneficial to use a one-to-one mapping. This affords the Follow
704
           Stream dialog view modes (ASCII, EBCDIC, Hex Dump, C Arrays, Raw)
705
           the opportunity to accurately reflect TLS PDU boundaries. Currently
706
           the Hex Dump view does by starting a new line, and the C Arrays
707
           view does by starting a new array declaration. */
708
0
        follow_record = g_new(follow_record_t,1);
709
710
0
        follow_record->is_server = (from == FROM_SERVER);
711
0
        follow_record->packet_num = pinfo->num;
712
0
        follow_record->abs_ts = pinfo->abs_ts;
713
714
0
        follow_record->data = g_byte_array_sized_new(appl_data->content_len);
715
0
        follow_record->data = g_byte_array_append(follow_record->data,
716
0
                                              appl_data->plain_data,
717
0
                                              appl_data->content_len);
718
719
        /* Add the record to the follow_info structure. */
720
0
        follow_info->payload = g_list_prepend(follow_info->payload, follow_record);
721
0
        follow_info->bytes_written[from] += appl_data->content_len;
722
0
    }
723
724
0
    return TAP_PACKET_DONT_REDRAW;
725
0
}
726
727
/*********************************************************************
728
 *
729
 * Forward Declarations
730
 *
731
 *********************************************************************/
732
733
/*
734
 * SSL version 3 and TLS dissectors
735
 *
736
 */
737
/* record layer dissector */
738
static int dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
739
                                proto_tree *tree, uint32_t offset,
740
                                SslSession *session, int is_from_server,
741
                                bool *need_desegmentation,
742
                                SslDecryptSession *conv_data,
743
                                uint8_t curr_layer_num_ssl,
744
                                struct tlsinfo *tlsinfo);
745
746
/* alert message dissector */
747
static void dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
748
                               proto_tree *tree, uint32_t offset,
749
                               uint32_t record_length, const SslSession *session,
750
                               struct tlsinfo *tlsinfo);
751
752
/* handshake protocol dissector */
753
static void dissect_tls_handshake(tvbuff_t *tvb, packet_info *pinfo,
754
                       proto_tree *tree, uint32_t offset,
755
                       uint32_t offset_end, bool maybe_encrypted,
756
                       unsigned record_id, uint8_t curr_layer_num_tls,
757
                       SslSession *session, int is_from_server,
758
                       SslDecryptSession *ssl,
759
                       const uint16_t version);
760
761
static void dissect_tls_handshake_full(tvbuff_t *tvb, packet_info *pinfo,
762
                                  proto_tree *tree, uint32_t offset,
763
                                  SslSession *session, int is_from_server,
764
                                  SslDecryptSession *conv_data,
765
                                  const uint16_t version,
766
                                  bool is_first_msg, uint8_t curr_layer_num_tls);
767
768
/* heartbeat message dissector */
769
static void dissect_ssl3_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
770
                                   proto_tree *tree, uint32_t offset,
771
                                   const SslSession *session, uint32_t record_length,
772
                                   bool decrypted);
773
774
static void dissect_ssl3_hnd_encrypted_exts(tvbuff_t *tvb,
775
                                            proto_tree *tree,
776
                                            uint32_t offset);
777
778
/*
779
 * SSL version 2 dissectors
780
 *
781
 */
782
783
/* record layer dissector */
784
static int dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo,
785
                                proto_tree *tree, uint32_t offset,
786
                                SslSession *session,
787
                                bool *need_desegmentation,
788
                                SslDecryptSession *ssl);
789
790
/* client hello dissector */
791
static void dissect_ssl2_hnd_client_hello(tvbuff_t *tvb, packet_info *pinfo,
792
                                          proto_tree *tree,
793
                                          uint32_t offset,
794
                                          SslDecryptSession *ssl);
795
796
/* client master key dissector */
797
static void dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
798
                                               proto_tree *tree,
799
                                               uint32_t offset);
800
801
/* server hello dissector */
802
static void dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
803
                                          proto_tree *tree,
804
                                          uint32_t offset, packet_info *pinfo);
805
806
807
/*
808
 * Support Functions
809
 *
810
 */
811
static int   ssl_is_valid_ssl_version(const uint16_t version);
812
static int   ssl_is_v2_client_hello(tvbuff_t *tvb, const uint32_t offset);
813
static int   ssl_looks_like_sslv2(tvbuff_t *tvb, const uint32_t offset);
814
static int   ssl_looks_like_sslv3(tvbuff_t *tvb, const uint32_t offset);
815
static int   ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb,
816
                                               const uint32_t offset,
817
                                               const uint32_t record_length);
818
819
static void
820
process_ssl_payload(tvbuff_t *tvb, int offset, packet_info *pinfo,
821
                    proto_tree *tree, SslSession *session,
822
                    dissector_handle_t app_handle_port,
823
                    struct tlsinfo *tlsinfo);
824
static uint32_t
825
tls_msp_fragment_id(struct tcp_multisegment_pdu *msp);
826
827
static void
828
print_tls_fragment_tree(fragment_head *ipfd_head, proto_tree *tree, proto_tree *tls_tree, packet_info *pinfo, tvbuff_t *next_tvb);
829
830
/*********************************************************************
831
 *
832
 * Main dissector
833
 *
834
 *********************************************************************/
835
/*
836
 * Code to actually dissect the packets
837
 */
838
static int
839
dissect_ssl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
840
5.11k
{
841
842
5.11k
    conversation_t    *conversation;
843
5.11k
    proto_item        *ti;
844
5.11k
    proto_tree        *ssl_tree;
845
5.11k
    uint32_t           offset;
846
5.11k
    bool               need_desegmentation;
847
5.11k
    SslDecryptSession *ssl_session, *ssl_session_save;
848
5.11k
    SslSession        *session;
849
5.11k
    int                is_from_server;
850
5.11k
    struct tcpinfo    *tcpinfo;
851
5.11k
    struct tlsinfo     tlsinfo;
852
853
    /*
854
     * A single packet may contain multiple TLS records. Two possible scenarios:
855
     *
856
     * - Multiple TLS records belonging to the same TLS session.
857
     * - TLS within a different encrypted TLS tunnel.
858
     *
859
     * To support the second case, 'curr_layer_num_ssl' is used as identifier
860
     * for the current TLS layer.
861
     */
862
5.11k
    uint8_t            curr_layer_num_ssl = p_get_proto_depth(pinfo, proto_tls);
863
864
5.11k
    ti = NULL;
865
5.11k
    ssl_tree   = NULL;
866
5.11k
    offset = 0;
867
5.11k
    ssl_session = NULL;
868
869
5.11k
    memset(&tlsinfo, 0, sizeof(tlsinfo));
870
5.11k
    tcpinfo = (struct tcpinfo*)data;
871
872
5.11k
    if (tvb_captured_length(tvb) > 4) {
873
4.60k
        const uint8_t *tmp = tvb_get_ptr(tvb, 0, 4);
874
4.60k
        if (g_ascii_isprint(tmp[0]) &&
875
4.60k
                g_ascii_isprint(tmp[1]) &&
876
4.60k
                g_ascii_isprint(tmp[2]) &&
877
4.60k
                g_ascii_isprint(tmp[3])) {
878
            /* it is extremely unlikely that real TLS traffic starts with four
879
             * printable ascii characters; this looks like it's unencrypted
880
             * text, so assume it's not ours (SSL does have some unencrypted
881
             * text fields in certain packets, but you'd have to get very
882
             * unlucky with TCP fragmentation to have one of those fields at the
883
             * beginning of a TCP payload at the beginning of the capture where
884
             * reassembly hasn't started yet) */
885
44
            return 0;
886
44
        }
887
4.60k
    }
888
889
5.07k
    ssl_debug_printf("\ndissect_ssl enter frame #%u (%s)\n", pinfo->num, (pinfo->fd->visited)?"already visited":"first time");
890
891
    /* Track the version using conversations to reduce the
892
     * chance that a packet that simply *looks* like a v2 or
893
     * v3 packet is dissected improperly.  This also allows
894
     * us to more frequently set the protocol column properly
895
     * for continuation data frames.
896
     *
897
     * Also: We use the copy in conv_version as our cached copy,
898
     *       so that we don't have to search the conversation
899
     *       table every time we want the version; when setting
900
     *       the conv_version, must set the copy in the conversation
901
     *       in addition to conv_version
902
     */
903
    /* Get the conversation with the deinterlacing strategy,
904
     * assuming it does exist, as created by an underlying proto.
905
     */
906
5.07k
    conversation = find_or_create_conversation_strat(pinfo);
907
908
5.07k
    ssl_session_save = ssl_session = ssl_get_session(conversation, tls_handle, curr_layer_num_ssl);
909
5.07k
    session = &ssl_session->session;
910
5.07k
    is_from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
911
912
5.07k
    if (session->last_nontls_frame != 0 &&
913
8
        session->last_nontls_frame >= pinfo->num) {
914
        /* This conversation started at a different protocol and STARTTLS was
915
         * used, but this packet comes too early. */
916
0
        return 0;
917
0
    }
918
919
    /* try decryption only the first time we see this packet
920
     * (to keep cipher synchronized) */
921
5.07k
    if (pinfo->fd->visited)
922
0
         ssl_session = NULL;
923
924
5.07k
    ssl_debug_printf("  conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl_session);
925
926
    /* Increment the proto depth, so any nested TLS gets the new depth.
927
     * Make sure to decrement this when leaving the function.
928
     * (XXX - Do we need a TRY...FINALLY or CLEANUP_CB_PUSH?) */
929
5.07k
    p_set_proto_depth(pinfo, proto_tls, curr_layer_num_ssl + 1);
930
931
    /* Initialize the protocol column; we'll override it later when we
932
     * detect a different version or flavor of TLS (assuming we don't
933
     * throw an exception before we get the chance to do so). */
934
5.07k
    col_set_str(pinfo->cinfo, COL_PROTOCOL,
935
5.07k
             val_to_str_const(session->version, ssl_version_short_names, "SSL"));
936
    /* clear the info column */
937
5.07k
    col_clear(pinfo->cinfo, COL_INFO);
938
939
    /* TCP packets and TLS records are orthogonal.
940
     * A tcp packet may contain multiple ssl records and an ssl
941
     * record may be spread across multiple tcp packets.
942
     *
943
     * This loop accounts for multiple ssl records in a single
944
     * frame, but not a single ssl record across multiple tcp
945
     * packets.
946
     *
947
     * Handling the single ssl record across multiple packets
948
     * may be possible using wireshark conversations, but
949
     * probably not cleanly.  May have to wait for tcp stream
950
     * reassembly.
951
     */
952
953
    /* Create display subtree for TLS as a whole */
954
5.07k
    if (tree)
955
5.07k
    {
956
5.07k
        ti = proto_tree_add_item(tree, proto_tls, tvb, 0, -1, ENC_NA);
957
5.07k
        ssl_tree = proto_item_add_subtree(ti, ett_tls);
958
959
5.07k
        ti = proto_tree_add_uint(ssl_tree, hf_tls_stream, tvb, 0, 0, session->stream);
960
5.07k
        proto_item_set_generated(ti);
961
5.07k
    }
962
    /* iterate through the records in this tvbuff */
963
11.1k
    while (tvb_reported_length_remaining(tvb, offset) > 0)
964
7.28k
    {
965
7.28k
        ssl_debug_printf("  record: offset = %d, reported_length_remaining = %d\n", offset, tvb_reported_length_remaining(tvb, offset));
966
967
        /*
968
         * Assume, for now, that this doesn't need desegmentation.
969
         */
970
7.28k
        need_desegmentation = false;
971
972
        /* first try to dispatch off the cached version
973
         * known to be associated with the conversation
974
         */
975
7.28k
        switch (session->version) {
976
41
        case SSLV2_VERSION:
977
41
            offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
978
41
                                         offset, session,
979
41
                                         &need_desegmentation,
980
41
                                         ssl_session);
981
41
            break;
982
983
437
        case SSLV3_VERSION:
984
720
        case TLSV1_VERSION:
985
1.60k
        case TLSV1DOT1_VERSION:
986
4.10k
        case TLSV1DOT2_VERSION:
987
5.02k
        case TLCPV1_VERSION:
988
            /* SSLv3/TLS record headers need at least 1+2+2 = 5 bytes. */
989
5.02k
            if (tvb_reported_length_remaining(tvb, offset) < 5) {
990
401
                if (tls_desegment && pinfo->can_desegment) {
991
0
                    pinfo->desegment_offset = offset;
992
0
                    pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
993
0
                    need_desegmentation = true;
994
401
                } else {
995
                    /* Not enough bytes available. Stop here. */
996
401
                    offset = tvb_reported_length(tvb);
997
401
                }
998
401
                break;
999
401
            }
1000
1001
            /* the version tracking code works too well ;-)
1002
             * at times, we may visit a v2 client hello after
1003
             * we already know the version of the connection;
1004
             * work around that here by detecting and calling
1005
             * the v2 dissector instead
1006
             */
1007
4.61k
            if (ssl_is_v2_client_hello(tvb, offset))
1008
95
            {
1009
95
                offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
1010
95
                                             offset, session,
1011
95
                                             &need_desegmentation,
1012
95
                                             ssl_session);
1013
95
            }
1014
4.52k
            else
1015
4.52k
            {
1016
4.52k
                offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
1017
4.52k
                                             offset, session, is_from_server,
1018
4.52k
                                             &need_desegmentation,
1019
4.52k
                                             ssl_session,
1020
4.52k
                                             curr_layer_num_ssl, &tlsinfo);
1021
4.52k
            }
1022
4.61k
            break;
1023
1024
            /* that failed, so apply some heuristics based
1025
             * on this individual packet
1026
             */
1027
2.22k
        default:
1028
            /*
1029
             * If the version is unknown, assume SSLv3/TLS which has a record
1030
             * size of at least 5 bytes (SSLv2 record header is two or three
1031
             * bytes, but the data will hopefully be larger than three bytes).
1032
             */
1033
2.22k
            if (tvb_reported_length_remaining(tvb, offset) < 5) {
1034
185
                if (tls_desegment && pinfo->can_desegment) {
1035
25
                    pinfo->desegment_offset = offset;
1036
25
                    pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
1037
25
                    need_desegmentation = true;
1038
160
                } else {
1039
                    /* Not enough bytes available. Stop here. */
1040
160
                    offset = tvb_reported_length(tvb);
1041
160
                }
1042
185
                break;
1043
185
            }
1044
1045
2.04k
            if (ssl_looks_like_sslv2(tvb, offset))
1046
222
            {
1047
                /* looks like sslv2 client hello */
1048
222
                offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
1049
222
                                             offset, session,
1050
222
                                             &need_desegmentation,
1051
222
                                             ssl_session);
1052
222
            }
1053
1.82k
            else if (ssl_looks_like_sslv3(tvb, offset))
1054
1.25k
            {
1055
                /* looks like sslv3 or tls */
1056
1.25k
                offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
1057
1.25k
                                             offset, session, is_from_server,
1058
1.25k
                                             &need_desegmentation,
1059
1.25k
                                             ssl_session,
1060
1.25k
                                             curr_layer_num_ssl, &tlsinfo);
1061
1.25k
            }
1062
565
            else
1063
565
            {
1064
                /* looks like something unknown, so lump into
1065
                 * continuation data
1066
                 */
1067
565
                offset = tvb_reported_length(tvb);
1068
565
                col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
1069
565
            }
1070
2.04k
            break;
1071
7.28k
        }
1072
1073
        /* Desegmentation return check */
1074
6.06k
        if (need_desegmentation) {
1075
25
            ssl_debug_printf("  need_desegmentation: offset = %d, reported_length_remaining = %d\n",
1076
25
                           offset, tvb_reported_length_remaining(tvb, offset));
1077
            /* Make data available to ssl_follow_tap_listener */
1078
25
            tap_queue_packet(tls_follow_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_ssl));
1079
25
            p_set_proto_depth(pinfo, proto_tls, curr_layer_num_ssl);
1080
25
            return tvb_captured_length(tvb);
1081
25
        }
1082
6.06k
    }
1083
1084
3.82k
    unsigned ret = tvb_captured_length(tvb);
1085
1086
    /* Check for needing to reassemble at end of stream */
1087
3.82k
    ssl_session = ssl_session_save;
1088
3.82k
    if (ssl_session) {
1089
3.82k
        SslDecoder *decoder;
1090
        /* retrieve decoder for this packet direction. Retrieve it
1091
         * here because the decoder could have been created while
1092
         * processing the records (e.g., an Early Data HTTP request
1093
         * and response, with no Content-Length.) */
1094
3.82k
        if (is_from_server != 0) {
1095
12
            decoder = ssl_session->server;
1096
12
        }
1097
3.81k
        else {
1098
3.81k
            decoder = ssl_session->client;
1099
3.81k
        }
1100
1101
3.82k
        if (decoder && decoder->flow && decoder->flow->flags & TCP_FLOW_REASSEMBLE_UNTIL_FIN) {
1102
            /* We want to reassemble at the end of the stream. Are we
1103
             * there? */
1104
            /* There might be more than one record, and we don't want to tell
1105
             * the application dissector that we got a TCP FIN if there are
1106
             * more app data records to come. We add the FIN here.
1107
             * XXX: We could have some logic to do so in dissect_ssl3_record()
1108
             * when we're on the last record. Note that the last record could
1109
             * be an alert, or this could be a FIN with no data, so we'd still
1110
             * have to check here anyway.)
1111
             */
1112
0
            if (tcpinfo) {
1113
0
                tlsinfo.end_of_stream |= (tcpinfo->flags & TH_FIN);
1114
0
            }
1115
0
            if (!tlsinfo.end_of_stream) {
1116
                /* No. Tell the TCP dissector that we want to desegment
1117
                 * at FIN, so that it will call the TLS dissector at FIN
1118
                 * even if there is no TCP payload.
1119
                 *
1120
                 * However, tell it that we've already dissected all the
1121
                 * the data in the packet, so that we avoid getting it
1122
                 * later and trying to decrypt the records again.
1123
                 * (XXX: An alternative would be checking for already decrypted
1124
                 * records before trying to decrypt on the first pass.)
1125
                 *
1126
                 * XXX - TLS says that parties MUST send a close_notify before
1127
                 * closing its write side of the connection (RFC 5246 7.2.1,
1128
                 * RFC 8446 6.1), so we could do nothing here and assume that
1129
                 * the TCP dissector will call us on the close_notify Alert.
1130
                 * There may be implementations that don't and only close the
1131
                 * connection with a TCP FIN, though. Setting this means that
1132
                 * the TCP dissection won't call the TLS dissector again until
1133
                 * TCP FIN. The TCP dissector doesn't support "continue calling
1134
                 * the payload dissector normally, but also call it at FIN in
1135
                 * case a TLS close_notify wasn't received."
1136
                 *
1137
                 * The effect here is that the desegmentation is done on the
1138
                 * TCP FIN instead of the frame with the close_notify.
1139
                 */
1140
0
                pinfo->desegment_offset = tvb_captured_length(tvb);
1141
0
                pinfo->desegment_len = DESEGMENT_UNTIL_FIN;
1142
0
            } else {
1143
0
                ssl_debug_printf("  desegmenting at end of stream (FIN)\n");
1144
0
                struct tcp_multisegment_pdu *msp;
1145
0
                msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(decoder->flow->multisegment_pdus, decoder->flow->byte_seq);
1146
0
                if (msp) {
1147
0
                    fragment_head *ipfd_head;
1148
0
                    ipfd_head = fragment_add(&ssl_reassembly_table, tvb, offset,
1149
0
                                             pinfo, tls_msp_fragment_id(msp), msp,
1150
0
                                             decoder->flow->byte_seq - msp->seq,
1151
0
                                             0, false);
1152
0
                    if (ipfd_head && ipfd_head->reassembled_in == pinfo->num) {
1153
0
                        tvbuff_t *next_tvb;
1154
1155
                        /* create a new TVB structure for desegmented data */
1156
0
                        next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);
1157
1158
                        /* add desegmented data to the data source list */
1159
0
                        add_new_data_source(pinfo, next_tvb, "Reassembled TLS");
1160
1161
                        /* Show details of the reassembly */
1162
0
                        print_tls_fragment_tree(ipfd_head, tree, ssl_tree, pinfo, next_tvb);
1163
1164
                        /*
1165
                         * Supply the sequence number of the first of the
1166
                         * reassembled bytes.
1167
                         */
1168
0
                        tlsinfo.seq = msp->seq;
1169
1170
                        /* indicate that this is reassembled data */
1171
0
                        tlsinfo.is_reassembled = true;
1172
1173
                        /* call subdissector */
1174
0
                        process_ssl_payload(next_tvb, 0, pinfo, tree, session, session->app_handle, &tlsinfo);
1175
1176
0
                        if (ret == 0) {
1177
                            /* XXX: Workaround for #15159. Ordinarily we
1178
                             * return the number of bytes dissected, but zero
1179
                             * indicates the dissector rejecting the data. If
1180
                             * we are dissecting at FIN, but there were no new
1181
                             * records added, we want to indicate that the
1182
                             * dissector accepted the zero length payload so
1183
                             * that the TLS (and, e.g. HTTP) layers don't get
1184
                             * removed. So artificially return 1 instead.
1185
                             * (The TCP dissector will ignore the number.)
1186
                             */
1187
0
                            ret = 1;
1188
0
                        }
1189
0
                    }
1190
0
                }
1191
0
            }
1192
0
        }
1193
3.82k
    }
1194
1195
1196
3.82k
    col_set_fence(pinfo->cinfo, COL_INFO);
1197
1198
3.82k
    ssl_debug_flush();
1199
1200
    /* Make data available to ssl_follow_tap_listener */
1201
3.82k
    tap_queue_packet(tls_follow_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_ssl));
1202
1203
3.82k
    p_set_proto_depth(pinfo, proto_tls, curr_layer_num_ssl);
1204
3.82k
    return ret;
1205
5.07k
}
1206
1207
1208
/*
1209
 * Dissect ECHConfigList structure, for use by the DNS dissector.
1210
 */
1211
static int
1212
dissect_tls_echconfig(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
1213
3.86k
{
1214
3.86k
    return ssl_dissect_ext_ech_echconfiglist(&dissect_ssl3_hf, tvb, pinfo,
1215
3.86k
                                             tree, 0, tvb_reported_length(tvb));
1216
3.86k
}
1217
1218
/*
1219
 * Dissect TLS 1.3 handshake messages (without the record layer).
1220
 * For use by QUIC (draft -13).
1221
 */
1222
static int
1223
dissect_tls13_handshake(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1224
0
{
1225
1226
0
    conversation_t    *conversation;
1227
0
    SslDecryptSession *ssl_session;
1228
0
    SslSession        *session;
1229
0
    int                is_from_server;
1230
0
    proto_item        *ti;
1231
0
    proto_tree        *ssl_tree;
1232
    /**
1233
     * A value that uniquely identifies this fragment in this frame.
1234
     */
1235
0
    unsigned           record_id = GPOINTER_TO_UINT(data);
1236
1237
0
    uint8_t curr_layer_num_ssl = p_get_proto_depth(pinfo, proto_tls);
1238
1239
0
    ssl_debug_printf("\n%s enter frame #%u (%s)\n", G_STRFUNC, pinfo->num, (pinfo->fd->visited)?"already visited":"first time");
1240
1241
0
    conversation = find_or_create_conversation(pinfo);
1242
0
    ssl_session = ssl_get_session(conversation, tls13_handshake_handle, curr_layer_num_ssl);
1243
0
    session = &ssl_session->session;
1244
0
    is_from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
1245
0
    if (session->version == SSL_VER_UNKNOWN) {
1246
0
        session->version = TLSV1DOT3_VERSION;
1247
0
        ssl_session->state |= SSL_VERSION;
1248
0
        ssl_session->state |= SSL_QUIC_RECORD_LAYER;
1249
0
    }
1250
1251
    /*
1252
     * First pass: collect state (including Client Random for key matching).
1253
     * Second pass: dissection only, no need to collect state.
1254
     */
1255
0
    if (PINFO_FD_VISITED(pinfo)) {
1256
0
         ssl_session = NULL;
1257
0
    }
1258
1259
0
    ssl_debug_printf("  conversation = %p, ssl_session = %p, from_server = %d\n",
1260
0
                     (void *)conversation, (void *)ssl_session, is_from_server);
1261
1262
    /* Add a proto_tls item to allow simple "tls" display filter */
1263
0
    ti = proto_tree_add_item(tree, proto_tls, tvb, 0, -1, ENC_NA);
1264
0
    ssl_tree = proto_item_add_subtree(ti, ett_tls);
1265
1266
0
    dissect_tls_handshake(tvb, pinfo, ssl_tree, 0,
1267
0
                          tvb_reported_length(tvb), false, record_id, pinfo->curr_layer_num, session,
1268
0
                          is_from_server, ssl_session, TLSV1DOT3_VERSION);
1269
1270
0
    ssl_debug_flush();
1271
1272
0
    return tvb_captured_length(tvb);
1273
0
}
1274
1275
static bool
1276
is_sslv3_or_tls(tvbuff_t *tvb)
1277
2.61k
{
1278
2.61k
    uint8_t             content_type;
1279
2.61k
    uint16_t            protocol_version, record_length;
1280
1281
    /*
1282
     * Heuristics should match the TLS record header.
1283
     * ContentType (1), ProtocolVersion (2), Length (2)
1284
     *
1285
     * We do not check for an actual payload, IBM WebSphere is known
1286
     * to separate the record header and payload over two separate packets.
1287
     */
1288
2.61k
    if (tvb_captured_length(tvb) < 5) {
1289
158
        return false;
1290
158
    }
1291
1292
2.45k
    content_type = tvb_get_uint8(tvb, 0);
1293
2.45k
    protocol_version = tvb_get_ntohs(tvb, 1);
1294
2.45k
    record_length = tvb_get_ntohs(tvb, 3);
1295
1296
    /* These are the common types. */
1297
2.45k
    if (content_type != SSL_ID_HANDSHAKE && content_type != SSL_ID_APP_DATA) {
1298
2.42k
        return false;
1299
2.42k
    }
1300
1301
    /*
1302
     * Match SSLv3, TLS 1.0/1.1/1.2 (TLS 1.3 uses same value as TLS 1.0). Most
1303
     * likely you'll see 0x300 (SSLv3) or 0x301 (TLS 1.1) for interoperability
1304
     * reasons. Per RFC 5246 we should accept any 0x3xx value, but this is just
1305
     * a heuristic that catches common/likely cases.
1306
     */
1307
30
    if (protocol_version != SSLV3_VERSION &&
1308
24
        protocol_version != TLSV1_VERSION &&
1309
21
        protocol_version != TLSV1DOT1_VERSION &&
1310
20
        protocol_version != TLSV1DOT2_VERSION &&
1311
16
        protocol_version != TLCPV1_VERSION ) {
1312
14
        return false;
1313
14
    }
1314
1315
    /* Check for sane length, see also ssl_check_record_length in packet-tls-utils.c */
1316
16
    if (record_length == 0 || record_length >= TLS_MAX_RECORD_LENGTH + 2048) {
1317
4
        return false;
1318
4
    }
1319
1320
12
    return true;
1321
16
}
1322
1323
static bool
1324
is_sslv2_clienthello(tvbuff_t *tvb)
1325
2.60k
{
1326
    /*
1327
     * Detect SSL 2.0 compatible Client Hello as used in SSLv3 and TLS.
1328
     *
1329
     * https://tools.ietf.org/html/rfc5246#appendix-E.2
1330
     *  uint8 V2CipherSpec[3];
1331
     *  struct {
1332
     *      uint16 msg_length;          // 0: highest bit must be 1
1333
     *      uint8 msg_type;             // 2: 1 for Client Hello
1334
     *      Version version;            // 3: equal to ClientHello.client_version
1335
     *      uint16 cipher_spec_length;  // 5: cannot be 0, must be multiple of 3
1336
     *      uint16 session_id_length;   // 7: zero or 16 (in TLS 1.0)
1337
     *      uint16 challenge_length;    // 9: must be 32
1338
     *      // length so far: 2 + 1 + 2 + 2 + 2 + 2 = 11
1339
     *      V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];    // len: min 3
1340
     *      opaque session_id[V2ClientHello.session_id_length];             // len: zero or 16
1341
     *      opaque challenge[V2ClientHello.challenge_length;                // len: 32
1342
     *      // min. length: 11 + 3 + (0 or 16) + 32 = 46 or 62
1343
     *  } V2ClientHello;
1344
     */
1345
2.60k
    if (tvb_captured_length(tvb) < 46) {
1346
1.26k
        return false;
1347
1.26k
    }
1348
1349
    /* Assume that message length is less than 256 (at most 64 cipherspecs). */
1350
1.33k
    if (tvb_get_uint8(tvb, 0) != 0x80) {
1351
1.32k
        return false;
1352
1.32k
    }
1353
1354
    /* msg_type must be 1 for Client Hello */
1355
13
    if (tvb_get_uint8(tvb, 2) != 1) {
1356
9
        return false;
1357
9
    }
1358
1359
    /* cipher spec length must be a non-zero multiple of 3 */
1360
4
    uint16_t cipher_spec_length = tvb_get_ntohs(tvb, 5);
1361
4
    if (cipher_spec_length == 0 || cipher_spec_length % 3 != 0) {
1362
2
        return false;
1363
2
    }
1364
1365
    /* session ID length must be 0 or 16 in TLS 1.0 */
1366
2
    uint16_t session_id_length = tvb_get_ntohs(tvb, 7);
1367
2
    if (session_id_length != 0 && session_id_length != 16) {
1368
1
        return false;
1369
1
    }
1370
1371
    /* Challenge Length must be 32 */
1372
1
    if (tvb_get_ntohs(tvb, 9) != 32) {
1373
1
        return false;
1374
1
    }
1375
1376
0
    return true;
1377
1
}
1378
1379
static bool
1380
dissect_ssl_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1381
2.61k
{
1382
2.61k
    conversation_t     *conversation;
1383
1384
2.61k
    if (!is_sslv3_or_tls(tvb) && !is_sslv2_clienthello(tvb)) {
1385
2.60k
        return false;
1386
2.60k
    }
1387
1388
12
    conversation = find_or_create_conversation(pinfo);
1389
12
    conversation_set_dissector_from_frame_number(conversation, pinfo->num, tls_handle);
1390
12
    return dissect_ssl(tvb, pinfo, tree, data) > 0;
1391
2.61k
}
1392
1393
static void
1394
tls_save_decrypted_record(packet_info *pinfo, int record_id, SslDecryptSession *ssl, uint8_t content_type,
1395
                          SslDecoder *decoder, bool allow_fragments, uint8_t curr_layer_num_ssl)
1396
0
{
1397
0
    const unsigned char *data = ssl_decrypted_data.data;
1398
0
    unsigned content_len = ssl_decrypted_data_avail;
1399
1400
0
    if (content_len == 0) {
1401
0
        return;
1402
0
    }
1403
1404
0
    if (ssl->session.version == TLSV1DOT3_VERSION) {
1405
        /*
1406
         * The content is followed by the content type and then zero or
1407
         * more padding. Scan backwards for content type, skipping padding.
1408
         */
1409
0
        while (content_len > 0 && data[content_len - 1] == 0) {
1410
0
            content_len--;
1411
0
        }
1412
0
        ssl_debug_printf("%s found %d padding bytes\n", G_STRFUNC, ssl_decrypted_data_avail - content_len);
1413
0
        if (content_len == 0) {
1414
0
            ssl_debug_printf("%s there is no room for content type!\n", G_STRFUNC);
1415
0
            return;
1416
0
        }
1417
0
        content_type = data[--content_len];
1418
0
        if (content_len == 0) {
1419
            /*
1420
             * XXX zero-length Handshake fragments are forbidden by RFC 8446,
1421
             * Section 5.1. Empty Application Data fragments are allowed though.
1422
             */
1423
0
            return;
1424
0
        }
1425
0
    }
1426
1427
    /* In TLS 1.3 only Handshake and Application Data can be fragmented.
1428
     * Alert messages MUST NOT be fragmented across records, so do not
1429
     * bother maintaining a flow for those. */
1430
0
    ssl_add_record_info(proto_tls, pinfo, data, ssl_decrypted_data_avail, content_len, record_id,
1431
0
            allow_fragments ? decoder->flow : NULL, (ContentType)content_type,
1432
0
            curr_layer_num_ssl, decoder->seq - 1); // decoder->seq has already been incremented
1433
0
}
1434
1435
/**
1436
 * Try to decrypt the record and update the internal cipher state.
1437
 * On success, the decrypted data will be available in "ssl_decrypted_data" of
1438
 * length "ssl_decrypted_data_avail".
1439
 */
1440
static bool
1441
decrypt_ssl3_record(tvbuff_t *tvb, packet_info *pinfo, uint32_t offset, SslDecryptSession *ssl,
1442
        uint8_t content_type, uint16_t record_version, uint16_t record_length,
1443
        bool allow_fragments, uint8_t curr_layer_num_ssl)
1444
3.53k
{
1445
3.53k
    bool        success;
1446
3.53k
    int         direction;
1447
3.53k
    StringInfo *data_for_iv;
1448
3.53k
    int         data_for_iv_len, data_for_iv_offset;
1449
3.53k
    SslDecoder *decoder;
1450
1451
    /* if we can decrypt and decryption was a success
1452
     * add decrypted data to this packet info */
1453
3.53k
    ssl_debug_printf("decrypt_ssl3_record: app_data len %d, ssl state 0x%02X\n",
1454
3.53k
        record_length, ssl->state);
1455
3.53k
    direction = ssl_packet_from_server(&ssl->session, ssl_associations, pinfo);
1456
1457
    /* retrieve decoder for this packet direction */
1458
3.53k
    if (direction != 0) {
1459
0
        ssl_debug_printf("decrypt_ssl3_record: using server decoder\n");
1460
0
        decoder = ssl->server;
1461
0
    }
1462
3.53k
    else {
1463
3.53k
        ssl_debug_printf("decrypt_ssl3_record: using client decoder\n");
1464
3.53k
        decoder = ssl->client;
1465
3.53k
    }
1466
1467
    /* save data to update IV if decoder is available or updated later */
1468
3.53k
    data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
1469
3.53k
    data_for_iv_len = (record_length < 24) ? record_length : 24;
1470
3.53k
    data_for_iv_offset = offset + record_length - data_for_iv_len;
1471
3.53k
    if (!tvb_bytes_exist(tvb, data_for_iv_offset, data_for_iv_len)) {
1472
2.30k
        ssl_debug_printf("decrypt_ssl3_record: record truncated\n");
1473
2.30k
        return false;
1474
2.30k
    }
1475
1.22k
    ssl_data_set(data_for_iv, (const unsigned char*)tvb_get_ptr(tvb, data_for_iv_offset, data_for_iv_len), data_for_iv_len);
1476
1477
1.22k
    if (!decoder) {
1478
898
        ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
1479
898
        return false;
1480
898
    }
1481
1482
    /* run decryption and add decrypted payload to protocol data, if decryption
1483
     * is successful*/
1484
330
    ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1485
330
    success = ssl_decrypt_record(pinfo->pool, ssl, decoder, content_type, record_version, tls_ignore_mac_failed,
1486
330
                           tvb_get_ptr(tvb, offset, record_length), record_length, NULL, 0,
1487
330
                           &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1488
    /*  */
1489
330
    if (!success) {
1490
        /* save data to update IV if valid session key is obtained later */
1491
330
        data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
1492
330
        data_for_iv_len = (record_length < 24) ? record_length : 24;
1493
330
        ssl_data_set(data_for_iv, (const unsigned char*)tvb_get_ptr(tvb, offset + record_length - data_for_iv_len, data_for_iv_len), data_for_iv_len);
1494
330
    }
1495
330
    if (success) {
1496
0
        tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, content_type, decoder, allow_fragments, curr_layer_num_ssl);
1497
0
    }
1498
330
    return success;
1499
1.22k
}
1500
1501
/**
1502
 * Try to guess the early data cipher using trial decryption.
1503
 * Requires Libgcrypt 1.6 or newer for verifying that decryption is successful.
1504
 */
1505
static bool
1506
decrypt_tls13_early_data(tvbuff_t *tvb, packet_info *pinfo, uint32_t offset,
1507
                         uint16_t record_length, SslDecryptSession *ssl,
1508
                         uint8_t curr_layer_num_ssl)
1509
1510
3
{
1511
3
    bool            success = false;
1512
1513
3
    ssl_debug_printf("Trying early data encryption, first record / trial decryption: %s\n",
1514
3
                    !(ssl->state & SSL_SEEN_0RTT_APPDATA) ? "true" : "false");
1515
1516
    /* Only try trial decryption for the first record. */
1517
3
    if (ssl->state & SSL_SEEN_0RTT_APPDATA) {
1518
2
        if (!ssl->client) {
1519
2
            return false;       // sanity check, should not happen in valid captures.
1520
2
        }
1521
1522
0
        ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1523
0
        success = ssl_decrypt_record(pinfo->pool, ssl, ssl->client, SSL_ID_APP_DATA, 0x303, false,
1524
0
                                     tvb_get_ptr(tvb, offset, record_length), record_length, NULL, 0,
1525
0
                                     &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1526
0
        if (success) {
1527
0
            tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, SSL_ID_APP_DATA, ssl->client, true, curr_layer_num_ssl);
1528
0
        } else {
1529
0
            ssl_debug_printf("early data decryption failed, end of early data?\n");
1530
0
        }
1531
0
        return success;
1532
2
    }
1533
1
    ssl->state |= SSL_SEEN_0RTT_APPDATA;
1534
1535
1
    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
1536
    // Early data can only be used with a PSK. (The early secret is computed w/o
1537
    // input from the (EC)DHE even if psk_dhe_ke is used.)
1538
1
    tls_load_psk(ssl, ssl_options.psk);
1539
1
    StringInfo *secret = tls13_load_secret(ssl, &ssl_master_key_map, false, TLS_SECRET_0RTT_APP);
1540
1
    if (!secret) {
1541
1
        ssl_debug_printf("Missing secrets, early data decryption not possible!\n");
1542
1
        return false;
1543
1
    }
1544
1545
0
    static const uint16_t tls13_ciphers[] = {
1546
0
        0x1301, /* TLS_AES_128_GCM_SHA256 */
1547
0
        0x1302, /* TLS_AES_256_GCM_SHA384 */
1548
0
        0x1303, /* TLS_CHACHA20_POLY1305_SHA256 */
1549
0
        0x1304, /* TLS_AES_128_CCM_SHA256 */
1550
0
        0x1305, /* TLS_AES_128_CCM_8_SHA256 */
1551
0
        0x00c6, /* TLS_SM4_GCM_SM3 */
1552
0
    };
1553
0
    const unsigned char   *record = tvb_get_ptr(tvb, offset, record_length);
1554
0
    for (unsigned i = 0; i < G_N_ELEMENTS(tls13_ciphers); i++) {
1555
0
        uint16_t cipher = tls13_ciphers[i];
1556
1557
0
        ssl_debug_printf("Performing early data trial decryption, cipher = %#x\n", cipher);
1558
0
        ssl->session.cipher = cipher;
1559
0
        ssl->cipher_suite = ssl_find_cipher(cipher);
1560
0
        if (!tls13_generate_keys(ssl, secret, false)) {
1561
            /* Unable to create cipher (old Libgcrypt) */
1562
0
            continue;
1563
0
        }
1564
1565
0
        ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1566
0
        success = ssl_decrypt_record(pinfo->pool, ssl, ssl->client, SSL_ID_APP_DATA, 0x303, false, record, record_length, NULL, 0,
1567
0
                                     &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1568
0
        if (success) {
1569
0
            ssl_debug_printf("Early data decryption succeeded, cipher = %#x\n", cipher);
1570
0
            tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, SSL_ID_APP_DATA, ssl->client, true, curr_layer_num_ssl);
1571
0
            break;
1572
0
        }
1573
0
    }
1574
0
    if (!success) {
1575
0
        ssl_debug_printf("Trial decryption of early data failed!\n");
1576
0
    }
1577
0
    return success;
1578
1
}
1579
1580
static void
1581
print_tls_fragment_tree(fragment_head *ipfd_head, proto_tree *tree, proto_tree *tls_tree, packet_info *pinfo, tvbuff_t *next_tvb)
1582
0
{
1583
0
    proto_item *tls_tree_item, *frag_tree_item;
1584
1585
    /*
1586
     * The subdissector thought it was completely
1587
     * desegmented (although the stuff at the
1588
     * end may, in turn, require desegmentation),
1589
     * so we show a tree with all segments.
1590
     */
1591
0
    show_fragment_tree(ipfd_head, &ssl_segment_items,
1592
0
                       tree, pinfo, next_tvb, &frag_tree_item);
1593
    /*
1594
     * The toplevel fragment subtree is now
1595
     * behind all desegmented data; move it
1596
     * right behind the TLS tree.
1597
     */
1598
0
    tls_tree_item = proto_tree_get_parent(tls_tree);
1599
0
    if (frag_tree_item && tls_tree_item) {
1600
0
        proto_tree_move_item(tree, tls_tree_item, frag_tree_item);
1601
0
    }
1602
0
}
1603
1604
static uint32_t
1605
tls_msp_fragment_id(struct tcp_multisegment_pdu *msp)
1606
0
{
1607
    /*
1608
     * If a frame contains multiple appdata PDUs, then "first_frame" is not
1609
     * sufficient to uniquely identify groups of fragments. Therefore we use
1610
     * the tcp reassembly functions that also test msp->seq (the position of
1611
     * the initial fragment in the TLS stream).
1612
     * As a frame most likely does not have multiple PDUs (except maybe for
1613
     * HTTP2), just check 'seq' at the end instead of using it in the hash.
1614
     */
1615
0
    uint32_t id = msp->first_frame;
1616
#if 0
1617
    id ^= (msp->seq & 0xff) << 24;
1618
    id ^= (msp->seq & 0xff00) << 16;
1619
#endif
1620
0
    return id;
1621
0
}
1622
1623
static void
1624
desegment_ssl(tvbuff_t *tvb, packet_info *pinfo, int offset,
1625
              uint32_t seq, uint32_t nxtseq,
1626
              SslSession *session,
1627
              proto_tree *root_tree, proto_tree *tree,
1628
              SslFlow *flow, dissector_handle_t app_handle_port,
1629
              struct tlsinfo *tlsinfo)
1630
0
{
1631
0
    fragment_head *ipfd_head;
1632
0
    bool           must_desegment;
1633
0
    bool           called_dissector;
1634
0
    unsigned       another_pdu_follows;
1635
0
    bool           another_segment_in_frame = false;
1636
0
    int            deseg_offset;
1637
0
    uint32_t       deseg_seq;
1638
0
    int            nbytes;
1639
0
    proto_item    *item;
1640
0
    struct tcp_multisegment_pdu *msp;
1641
1642
0
again:
1643
0
    ipfd_head = NULL;
1644
0
    must_desegment = false;
1645
0
    called_dissector = false;
1646
0
    another_pdu_follows = 0;
1647
0
    msp = NULL;
1648
1649
    /*
1650
     * Initialize these to assume no desegmentation.
1651
     * If that's not the case, these will be set appropriately
1652
     * by the subdissector.
1653
     */
1654
0
    pinfo->desegment_offset = 0;
1655
0
    pinfo->desegment_len = 0;
1656
1657
    /*
1658
     * Initialize this to assume that this segment will just be
1659
     * added to the middle of a desegmented chunk of data, so
1660
     * that we should show it all as data.
1661
     * If that's not the case, it will be set appropriately.
1662
     */
1663
0
    deseg_offset = offset;
1664
1665
    /* If we've seen this segment before (e.g., it's a retransmission),
1666
     * there's nothing for us to do.  Certainly, don't add it to the list
1667
     * of multisegment_pdus (that would cause subsequent lookups to find
1668
     * the retransmission instead of the original transmission, breaking
1669
     * dissection of the desegmented pdu if we'd already seen the end of
1670
     * the pdu).
1671
     */
1672
0
    if ((msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32(flow->multisegment_pdus, seq))) {
1673
0
        const char *prefix;
1674
0
        bool is_retransmission = false;
1675
1676
0
        if (msp->first_frame == pinfo->num) {
1677
            /* This must be after the first pass. */
1678
0
            prefix = "";
1679
0
            if (msp->last_frame == pinfo->num) {
1680
0
                col_clear(pinfo->cinfo, COL_INFO);
1681
0
            } else {
1682
0
                col_set_str(pinfo->cinfo, COL_INFO, "[TLS segment of a reassembled PDU]");
1683
0
            }
1684
0
        } else {
1685
0
            prefix = "Retransmitted ";
1686
0
            is_retransmission = true;
1687
0
        }
1688
1689
0
        if (!is_retransmission) {
1690
0
            ipfd_head = fragment_get(&ssl_reassembly_table, pinfo, msp->first_frame, msp);
1691
0
            if (ipfd_head != NULL && ipfd_head->reassembled_in !=0 &&
1692
0
                ipfd_head->reassembled_in != pinfo->num) {
1693
                /* Show what frame this was reassembled in if not this one. */
1694
0
                item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
1695
0
                                         tvb, 0, 0, ipfd_head->reassembled_in);
1696
0
                proto_item_set_generated(item);
1697
0
            }
1698
0
        }
1699
0
        nbytes = tvb_reported_length_remaining(tvb, offset);
1700
0
        ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, prefix);
1701
0
        return;
1702
0
    }
1703
1704
    /* Else, find the most previous PDU starting before this sequence number */
1705
0
    msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(flow->multisegment_pdus, seq-1);
1706
0
    if (msp && msp->seq <= seq && msp->nxtpdu > seq) {
1707
0
        unsigned len;
1708
1709
0
        if (!PINFO_FD_VISITED(pinfo)) {
1710
0
            msp->last_frame = pinfo->num;
1711
0
            msp->last_frame_time = pinfo->abs_ts;
1712
0
        }
1713
1714
        /* OK, this PDU was found, which means the segment continues
1715
         * a higher-level PDU and that we must desegment it.
1716
         */
1717
0
        if (msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
1718
            /* The dissector asked for the entire segment */
1719
0
            len = tvb_reported_length_remaining(tvb, offset);
1720
0
        } else {
1721
0
            len = MIN(nxtseq, msp->nxtpdu) - seq;
1722
0
        }
1723
1724
0
        ipfd_head = fragment_add(&ssl_reassembly_table, tvb, offset,
1725
0
                                 pinfo, tls_msp_fragment_id(msp), msp,
1726
0
                                 seq - msp->seq,
1727
0
                                 len, (LT_SEQ (nxtseq,msp->nxtpdu)));
1728
1729
0
        if (!PINFO_FD_VISITED(pinfo)
1730
0
        && msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
1731
0
            msp->flags &= (~MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT);
1732
1733
            /* If we consumed the entire segment there is no
1734
             * other pdu starting anywhere inside this segment.
1735
             * So update nxtpdu to point at least to the start
1736
             * of the next segment.
1737
             * (If the subdissector asks for even more data we
1738
             * will advance nxtpdu even further later down in
1739
             * the code.)
1740
             */
1741
0
            msp->nxtpdu = nxtseq;
1742
0
        }
1743
1744
0
        if ( (msp->nxtpdu < nxtseq)
1745
0
        &&  (msp->nxtpdu >= seq)
1746
0
        &&  (len > 0)) {
1747
0
            another_pdu_follows = msp->nxtpdu - seq;
1748
0
        }
1749
0
    } else {
1750
        /* This segment was not found in our table, so it doesn't
1751
         * contain a continuation of a higher-level PDU.
1752
         * Call the normal subdissector.
1753
         */
1754
1755
        /*
1756
         * Supply the sequence number of this segment. We set this here
1757
         * because this segment could be after another in the same packet,
1758
         * in which case seq was incremented at the end of the loop.
1759
         */
1760
0
        tlsinfo->seq = seq;
1761
1762
0
        process_ssl_payload(tvb, offset, pinfo, tree, session, app_handle_port, tlsinfo);
1763
0
        called_dissector = true;
1764
1765
        /* Did the subdissector ask us to desegment some more data
1766
         * before it could handle the packet?
1767
         * If so we'll have to handle that later.
1768
         */
1769
0
        if (pinfo->desegment_len) {
1770
0
            must_desegment = true;
1771
1772
            /*
1773
             * Set "deseg_offset" to the offset in "tvb"
1774
             * of the first byte of data that the
1775
             * subdissector didn't process.
1776
             */
1777
0
            deseg_offset = offset + pinfo->desegment_offset;
1778
0
        }
1779
1780
        /* Either no desegmentation is necessary, or this is
1781
         * segment contains the beginning but not the end of
1782
         * a higher-level PDU and thus isn't completely
1783
         * desegmented.
1784
         */
1785
0
        ipfd_head = NULL;
1786
0
    }
1787
1788
1789
    /* is it completely desegmented? */
1790
0
    if (ipfd_head && ipfd_head->reassembled_in == pinfo->num) {
1791
        /*
1792
         * Yes, we think it is.
1793
         * We only call subdissector for the last segment.
1794
         * Note that the last segment may include more than what
1795
         * we needed.
1796
         */
1797
0
        if (nxtseq < msp->nxtpdu) {
1798
            /*
1799
             * This is *not* the last segment. It is part of a PDU in the same
1800
             * frame, so no another PDU can follow this one.
1801
             * Do not reassemble TLS yet, it will be done in the final segment.
1802
             * (If we are reassembling at FIN, we will do that in dissect_ssl()
1803
             * after iterating through all the records.)
1804
             * Clear the Info column and avoid displaying [TLS segment of a
1805
             * reassembled PDU], the payload dissector will typically set it.
1806
             * (This is needed here for the second pass.)
1807
             */
1808
0
            another_pdu_follows = 0;
1809
0
            col_clear(pinfo->cinfo, COL_INFO);
1810
0
            another_segment_in_frame = true;
1811
0
        } else {
1812
            /*
1813
             * OK, this is the last segment of the PDU and also the
1814
             * last segment in this frame.
1815
             * Let's call the subdissector with the desegmented
1816
             * data.
1817
             */
1818
0
            tvbuff_t *next_tvb;
1819
0
            int old_len;
1820
1821
            /*
1822
             * Reset column in case multiple TLS segments form the
1823
             * PDU and this last TLS segment is not in the first TCP segment of
1824
             * this frame.
1825
             * XXX prevent clearing the column if the last layer is not SSL?
1826
             */
1827
            /* Clear column during the first pass. */
1828
0
            col_clear(pinfo->cinfo, COL_INFO);
1829
1830
            /* create a new TVB structure for desegmented data */
1831
0
            next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);
1832
1833
            /* add desegmented data to the data source list */
1834
0
            add_new_data_source(pinfo, next_tvb, "Reassembled TLS");
1835
1836
            /*
1837
             * Supply the sequence number of the first of the
1838
             * reassembled bytes.
1839
             */
1840
0
            tlsinfo->seq = msp->seq;
1841
1842
            /* indicate that this is reassembled data */
1843
0
            tlsinfo->is_reassembled = true;
1844
1845
            /* call subdissector */
1846
0
            process_ssl_payload(next_tvb, 0, pinfo, tree, session, app_handle_port, tlsinfo);
1847
0
            called_dissector = true;
1848
1849
            /*
1850
             * OK, did the subdissector think it was completely
1851
             * desegmented, or does it think we need even more
1852
             * data?
1853
             */
1854
0
            old_len = (int)(tvb_reported_length(next_tvb) - tvb_reported_length_remaining(tvb, offset));
1855
0
            if (pinfo->desegment_len && pinfo->desegment_offset <= old_len) {
1856
                /*
1857
                 * "desegment_len" isn't 0, so it needs more
1858
                 * data for something - and "desegment_offset"
1859
                 * is before "old_len", so it needs more data
1860
                 * to dissect the stuff we thought was
1861
                 * completely desegmented (as opposed to the
1862
                 * stuff at the beginning being completely
1863
                 * desegmented, but the stuff at the end
1864
                 * being a new higher-level PDU that also
1865
                 * needs desegmentation).
1866
                 */
1867
0
                fragment_set_partial_reassembly(&ssl_reassembly_table,
1868
0
                                                pinfo, tls_msp_fragment_id(msp), msp);
1869
0
                if (pinfo->desegment_offset == 0) {
1870
                    /* It didn't dissect anything in the reassembled TLS segment, so
1871
                     * remove the newly added data source. */
1872
0
                    remove_last_data_source(pinfo);
1873
0
                }
1874
                /* Update msp->nxtpdu to point to the new next
1875
                 * pdu boundary.
1876
                 */
1877
0
                if (pinfo->desegment_len == DESEGMENT_ONE_MORE_SEGMENT) {
1878
                    /* We want reassembly of at least one
1879
                     * more segment so set the nxtpdu
1880
                     * boundary to one byte into the next
1881
                     * segment.
1882
                     * This means that the next segment
1883
                     * will complete reassembly even if it
1884
                     * is only one single byte in length.
1885
                     */
1886
0
                    msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + 1;
1887
0
                    msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
1888
0
                } else if (pinfo->desegment_len == DESEGMENT_UNTIL_FIN) {
1889
                    /* This is not the first segment, and we thought reassembly
1890
                     * would be done now, but now we know we desegment at FIN.
1891
                     * E.g., a HTTP response where the headers were split
1892
                     * across segments (so previous ONE_MORE_SEGMENT) and
1893
                     * also no Content-Length (so now DESEGMENT_UNTIL_FIN).
1894
                     */
1895
0
                    flow->flags |= TCP_FLOW_REASSEMBLE_UNTIL_FIN;
1896
0
                    msp->nxtpdu = nxtseq + 0x40000000;
1897
0
                } else {
1898
0
                    msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + pinfo->desegment_len;
1899
0
                }
1900
                /* Since we need at least some more data
1901
                 * there can be no pdu following in the
1902
                 * tail of this segment.
1903
                 */
1904
0
                another_pdu_follows = 0;
1905
0
            } else {
1906
                /*
1907
                 * Show the stuff in this TLS segment as
1908
                 * just raw TLS segment data.
1909
                 */
1910
0
                nbytes = another_pdu_follows > 0 ?
1911
0
                    another_pdu_follows :
1912
0
                    tvb_reported_length_remaining(tvb, offset);
1913
0
                ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, NULL);
1914
1915
                /* Show details of the reassembly */
1916
0
                print_tls_fragment_tree(ipfd_head, root_tree, tree, pinfo, next_tvb);
1917
1918
                /* Did the subdissector ask us to desegment
1919
                 * some more data?  This means that the data
1920
                 * at the beginning of this segment completed
1921
                 * a higher-level PDU, but the data at the
1922
                 * end of this segment started a higher-level
1923
                 * PDU but didn't complete it.
1924
                 */
1925
0
                if (pinfo->desegment_len) {
1926
0
                    must_desegment = true;
1927
1928
                    /* The stuff we couldn't dissect
1929
                     * must have come from this segment,
1930
                     * so it's all in "tvb".
1931
                     *
1932
                     * "pinfo->desegment_offset" is
1933
                     * relative to the beginning of
1934
                     * "next_tvb"; we want an offset
1935
                     * relative to the beginning of "tvb".
1936
                     *
1937
                     * First, compute the offset relative
1938
                     * to the *end* of "next_tvb" - i.e.,
1939
                     * the number of bytes before the end
1940
                     * of "next_tvb" at which the
1941
                     * subdissector stopped.  That's the
1942
                     * length of "next_tvb" minus the
1943
                     * offset, relative to the beginning
1944
                     * of "next_tvb, at which the
1945
                     * subdissector stopped.
1946
                     */
1947
0
                    deseg_offset = ipfd_head->datalen - pinfo->desegment_offset;
1948
1949
                    /* "tvb" and "next_tvb" end at the
1950
                     * same byte of data, so the offset
1951
                     * relative to the end of "next_tvb"
1952
                     * of the byte at which we stopped
1953
                     * is also the offset relative to
1954
                     * the end of "tvb" of the byte at
1955
                     * which we stopped.
1956
                     *
1957
                     * Convert that back into an offset
1958
                     * relative to the beginning of
1959
                     * "tvb", by taking the length of
1960
                     * "tvb" and subtracting the offset
1961
                     * relative to the end.
1962
                     */
1963
0
                    deseg_offset = tvb_reported_length(tvb) - deseg_offset;
1964
0
                }
1965
0
            }
1966
0
        }
1967
0
    }
1968
1969
0
    if (must_desegment) {
1970
        /*
1971
         * The sequence number at which the stuff to be desegmented
1972
         * starts is the sequence number of the byte at an offset
1973
         * of "deseg_offset" into "tvb".
1974
         *
1975
         * The sequence number of the byte at an offset of "offset"
1976
         * is "seq", i.e. the starting sequence number of this
1977
         * segment, so the sequence number of the byte at
1978
         * "deseg_offset" is "seq + (deseg_offset - offset)".
1979
         */
1980
0
        deseg_seq = seq + (deseg_offset - offset);
1981
1982
        /* We have to create some structures the first time. */
1983
0
        if (!PINFO_FD_VISITED(pinfo)) {
1984
            /* If the dissector requested "reassemble until FIN"
1985
             * just set this flag for the flow and let reassembly
1986
             * proceed at normal.  We will check/pick up these
1987
             * reassembled PDUs later down in dissect_tcp() when checking
1988
             * for the FIN flag.
1989
             */
1990
0
            if (pinfo->desegment_len == DESEGMENT_UNTIL_FIN) {
1991
0
                flow->flags |= TCP_FLOW_REASSEMBLE_UNTIL_FIN;
1992
0
            }
1993
0
            if ((nxtseq - deseg_seq) <= 1024*1024) {
1994
0
                if (pinfo->desegment_len == DESEGMENT_ONE_MORE_SEGMENT) {
1995
                    /* The subdissector asked to reassemble using the
1996
                     * entire next segment.
1997
                     * Just ask reassembly for one more byte
1998
                     * but set this msp flag so we can pick it up
1999
                     * above.
2000
                     */
2001
0
                    msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
2002
0
                        deseg_seq, nxtseq+1, flow->multisegment_pdus);
2003
0
                    msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
2004
0
                } else if (pinfo->desegment_len == DESEGMENT_UNTIL_FIN) {
2005
                    /* Set nxtseq very large so that reassembly won't happen
2006
                     * until we force it at the end of the stream in dissect_ssl()
2007
                     * outside this function.
2008
                     */
2009
0
                    msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
2010
0
                        deseg_seq, nxtseq+0x40000000, flow->multisegment_pdus);
2011
0
                } else {
2012
0
                    msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
2013
0
                        deseg_seq, nxtseq+pinfo->desegment_len, flow->multisegment_pdus);
2014
0
                }
2015
2016
                /* add this segment as the first one for this new pdu */
2017
0
                fragment_add(&ssl_reassembly_table, tvb, deseg_offset,
2018
0
                             pinfo, tls_msp_fragment_id(msp), msp,
2019
0
                             0, nxtseq - deseg_seq,
2020
0
                             LT_SEQ(nxtseq, msp->nxtpdu));
2021
0
            }
2022
0
        } else {
2023
            /* If this is not the first pass, then the MSP should already be
2024
             * created. Retrieve it to see if we know what later frame the
2025
             * last segment was reassembled in. */
2026
0
            if ((msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32(flow->multisegment_pdus, deseg_seq))) {
2027
0
                ipfd_head = fragment_get(&ssl_reassembly_table, pinfo, msp->first_frame, msp);
2028
0
            }
2029
0
        }
2030
0
    }
2031
2032
0
    if (!called_dissector || pinfo->desegment_len != 0) {
2033
0
        if (ipfd_head != NULL && ipfd_head->reassembled_in != 0 &&
2034
0
            ipfd_head->reassembled_in != pinfo->num &&
2035
0
            !(ipfd_head->flags & FD_PARTIAL_REASSEMBLY)) {
2036
            /*
2037
             * We know what other frame this PDU is reassembled in;
2038
             * let the user know.
2039
             */
2040
0
            item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
2041
0
                                     tvb, 0, 0, ipfd_head->reassembled_in);
2042
0
            proto_item_set_generated(item);
2043
0
        }
2044
2045
        /*
2046
         * Either we didn't call the subdissector at all (i.e.,
2047
         * this is a segment that contains the middle of a
2048
         * higher-level PDU, but contains neither the beginning
2049
         * nor the end), or the subdissector couldn't dissect it
2050
         * all, as some data was missing (i.e., it set
2051
         * "pinfo->desegment_len" to the amount of additional
2052
         * data it needs).
2053
         */
2054
0
        if (!another_segment_in_frame && pinfo->desegment_offset == 0) {
2055
            /*
2056
             * It couldn't, in fact, dissect any of it (the
2057
             * first byte it couldn't dissect is at an offset
2058
             * of "pinfo->desegment_offset" from the beginning
2059
             * of the payload, and that's 0).
2060
             * Just mark this as SSL.
2061
             */
2062
0
            col_set_str(pinfo->cinfo, COL_PROTOCOL,
2063
0
                    val_to_str_const(session->version, ssl_version_short_names, "SSL"));
2064
0
            col_set_str(pinfo->cinfo, COL_INFO, "[TLS segment of a reassembled PDU]");
2065
0
        }
2066
2067
        /*
2068
         * Show what's left in the packet as just raw TCP segment
2069
         * data.
2070
         * XXX - remember what protocol the last subdissector
2071
         * was, and report it as a continuation of that, instead?
2072
         */
2073
0
        nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
2074
0
        ssl_proto_tree_add_segment_data(tree, tvb, deseg_offset, nbytes, NULL);
2075
0
    }
2076
0
    pinfo->can_desegment = 0;
2077
0
    pinfo->desegment_offset = 0;
2078
0
    pinfo->desegment_len = 0;
2079
2080
0
    if (another_pdu_follows) {
2081
        /* there was another pdu following this one. */
2082
0
        pinfo->can_desegment=2;
2083
        /* we also have to prevent the dissector from changing the
2084
         * PROTOCOL and INFO columns since what follows may be an
2085
         * incomplete PDU and we don't want it be changed back from
2086
         *  <Protocol>   to <TCP>
2087
         */
2088
0
        col_set_fence(pinfo->cinfo, COL_INFO);
2089
0
        col_set_writable(pinfo->cinfo, COL_PROTOCOL, false);
2090
0
        offset += another_pdu_follows;
2091
0
        seq += another_pdu_follows;
2092
0
        goto again;
2093
0
    }
2094
0
}
2095
2096
static tvbuff_t*
2097
handle_export_pdu_check_desegmentation(packet_info *pinfo, tvbuff_t *tvb)
2098
0
{
2099
    /* Check to see if the tvb we're planning on exporting PDUs from was
2100
     * dissected fully, or whether it requested further desegmentation.
2101
     */
2102
0
    if (pinfo->can_desegment > 0 && pinfo->desegment_len != 0) {
2103
        /* Desegmentation was requested. How much did we desegment here?
2104
         * The rest, presumably, will be handled in another frame.
2105
         */
2106
0
        if (pinfo->desegment_offset == 0) {
2107
            /* We couldn't, in fact, dissect any of it. */
2108
0
            return NULL;
2109
0
        }
2110
0
        tvb = tvb_new_subset_length(tvb, 0, pinfo->desegment_offset);
2111
0
    }
2112
0
    return tvb;
2113
0
}
2114
2115
static void
2116
export_pdu_packet(tvbuff_t *tvb, packet_info *pinfo, uint8_t tag, const char *name)
2117
0
{
2118
0
    tvb = handle_export_pdu_check_desegmentation(pinfo, tvb);
2119
0
    if (tvb == NULL) {
2120
0
        return;
2121
0
    }
2122
2123
0
    exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, name, tag);
2124
2125
0
    exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
2126
0
    exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
2127
0
    exp_pdu_data->pdu_tvb = tvb;
2128
2129
0
    tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
2130
0
}
2131
2132
static void
2133
process_ssl_payload(tvbuff_t *tvb, int offset, packet_info *pinfo,
2134
                    proto_tree *tree, SslSession *session,
2135
                    dissector_handle_t app_handle_port,
2136
                    struct tlsinfo *tlsinfo)
2137
0
{
2138
0
    tvbuff_t *next_tvb;
2139
0
    heur_dtbl_entry_t *hdtbl_entry;
2140
0
    uint16_t saved_match_port, app_port;
2141
0
    const char *saved_match_string;
2142
0
    bool heur_first;
2143
2144
0
    tlsinfo->app_handle = &session->app_handle;
2145
2146
0
    next_tvb = tvb_new_subset_remaining(tvb, offset);
2147
2148
0
    if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
2149
0
        app_port = PINFO_SRCPORT(pinfo);
2150
0
    } else {
2151
0
        app_port = PINFO_DESTPORT(pinfo);
2152
0
    }
2153
    /* If the appdata proto is not yet known (no STARTTLS or ALPN), try
2154
     * heuristics and ports-based dissectors, order depending on preference. */
2155
0
    if (!session->app_handle) {
2156
0
        heur_first = value_is_in_range(tls_try_heuristic_first, app_port);
2157
        /* The heuristics dissector should set the app_handle via tlsinfo
2158
         * if it wants to be called in the future. */
2159
0
        if (heur_first && dissector_try_heuristic(ssl_heur_subdissector_list,
2160
0
                                    next_tvb, pinfo, proto_tree_get_root(tree), &hdtbl_entry,
2161
0
                                    tlsinfo)) {
2162
0
            ssl_debug_printf("%s: found heuristics dissector %s, app_handle is %p (%s)\n",
2163
0
                             G_STRFUNC, hdtbl_entry->short_name,
2164
0
                             (void *)session->app_handle,
2165
0
                             dissector_handle_get_dissector_name(session->app_handle));
2166
0
            if (have_tap_listener(exported_pdu_tap)) {
2167
0
                export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_HEUR_DISSECTOR_NAME, hdtbl_entry->short_name);
2168
0
            }
2169
0
            return;
2170
0
        }
2171
0
        if (app_handle_port) {
2172
            /* Heuristics failed, just try the port-based dissector. */
2173
0
            ssl_debug_printf("%s: no heuristics dissector, falling back to "
2174
0
                             "handle %p (%s)\n", G_STRFUNC,
2175
0
                             (void *)app_handle_port,
2176
0
                             dissector_handle_get_dissector_name(app_handle_port));
2177
0
            session->app_handle = app_handle_port;
2178
0
        } else if (!heur_first && dissector_try_heuristic(ssl_heur_subdissector_list,
2179
0
                                    next_tvb, pinfo, proto_tree_get_root(tree), &hdtbl_entry,
2180
0
                                    tlsinfo)) {
2181
0
            ssl_debug_printf("%s: found heuristics dissector %s, app_handle is %p (%s)\n",
2182
0
                             G_STRFUNC, hdtbl_entry->short_name,
2183
0
                             (void *)session->app_handle,
2184
0
                             dissector_handle_get_dissector_name(session->app_handle));
2185
0
            if (have_tap_listener(exported_pdu_tap)) {
2186
0
                export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_HEUR_DISSECTOR_NAME, hdtbl_entry->short_name);
2187
0
            }
2188
0
            return;
2189
0
        } else {
2190
            /* No heuristics, no port-based proto, unknown protocol. */
2191
0
            ssl_debug_printf("%s: no appdata dissector found\n", G_STRFUNC);
2192
0
            call_data_dissector(next_tvb, pinfo, proto_tree_get_root(tree));
2193
0
            if (have_tap_listener(exported_pdu_tap)) {
2194
0
                export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_DISSECTOR_NAME,
2195
0
                                  "data");
2196
0
            }
2197
0
            return;
2198
0
        }
2199
0
    }
2200
2201
0
    ssl_debug_printf("%s: found handle %p (%s)\n", G_STRFUNC,
2202
0
                     (void *)session->app_handle,
2203
0
                     dissector_handle_get_dissector_name(session->app_handle));
2204
2205
0
    saved_match_port = pinfo->match_uint;
2206
0
    saved_match_string = pinfo->match_string; // probably unneeded
2207
0
    pinfo->match_uint = app_port;
2208
0
    pinfo->match_string = session->alpn_name;
2209
0
    call_dissector_with_data(session->app_handle, next_tvb, pinfo, proto_tree_get_root(tree), tlsinfo);
2210
    /* The app dissector might not fully dissect next_tvb and request
2211
     * desegmentation. This is especially true on the first pass, but
2212
     * can also occur on the second pass if it dissects part of next_tvb
2213
     * but not all of it. So we can't export until after calling the
2214
     * app handle. (XXX - What if it throws an exception? Should we catch
2215
     * it and try to export it anyway? That should be fairly rare with
2216
     * TLS since decryption succeeded.) */
2217
0
    if (have_tap_listener(exported_pdu_tap)) {
2218
0
        export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_DISSECTOR_NAME,
2219
0
                          dissector_handle_get_dissector_name(session->app_handle));
2220
0
    }
2221
0
    pinfo->match_uint = saved_match_port;
2222
0
    pinfo->match_string = saved_match_string;
2223
0
}
2224
2225
static void
2226
dissect_ssl_payload(tvbuff_t *decrypted, packet_info *pinfo,
2227
                    proto_tree *tree, SslSession *session,
2228
                    SslRecordInfo *record,
2229
                    dissector_handle_t app_handle_port,
2230
                    struct tlsinfo *tlsinfo)
2231
0
{
2232
0
    bool         save_fragmented;
2233
0
    uint16_t     save_can_desegment;
2234
2235
0
    tlsinfo->seq = record->seq;
2236
2237
    /* Preserve current desegmentation ability to prevent the subdissector
2238
     * from messing up the ssl desegmentation */
2239
0
    save_can_desegment = pinfo->can_desegment;
2240
2241
    /* try to dissect decrypted data*/
2242
0
    ssl_debug_printf("%s decrypted len %d\n", G_STRFUNC, record->content_len);
2243
0
    ssl_print_data("decrypted app data fragment", record->plain_data, record->content_len);
2244
2245
    /* Can we desegment this segment? */
2246
0
    if (tls_desegment_app_data) {
2247
        /* Yes. */
2248
0
        pinfo->can_desegment = 2;
2249
0
        desegment_ssl(decrypted, pinfo, 0, record->seq, record->seq + record->content_len,
2250
0
                      session, proto_tree_get_root(tree), tree,
2251
0
                      record->flow, app_handle_port, tlsinfo);
2252
0
    } else if (session->app_handle || app_handle_port) {
2253
        /* No - just call the subdissector.
2254
           Mark this as fragmented, so if somebody throws an exception,
2255
           we don't report it as a malformed frame. */
2256
0
        pinfo->can_desegment = 0;
2257
0
        save_fragmented = pinfo->fragmented;
2258
0
        pinfo->fragmented = true;
2259
2260
0
        process_ssl_payload(decrypted, 0, pinfo, tree, session, app_handle_port, tlsinfo);
2261
0
        pinfo->fragmented = save_fragmented;
2262
0
    }
2263
2264
    /* restore desegmentation ability */
2265
0
    pinfo->can_desegment = save_can_desegment;
2266
0
}
2267
2268
2269
/*********************************************************************
2270
 *
2271
 * SSL version 3 and TLS Dissection Routines
2272
 *
2273
 *********************************************************************/
2274
static int
2275
dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
2276
                    proto_tree *tree, uint32_t offset,
2277
                    SslSession *session, int is_from_server,
2278
                    bool *need_desegmentation,
2279
                    SslDecryptSession *ssl,
2280
                    uint8_t curr_layer_num_ssl, struct tlsinfo *tlsinfo)
2281
5.77k
{
2282
2283
    /*
2284
     *    struct {
2285
     *        uint8 major, minor;
2286
     *    } ProtocolVersion;
2287
     *
2288
     *
2289
     *    enum {
2290
     *        change_cipher_spec(20), alert(21), handshake(22),
2291
     *        application_data(23), (255)
2292
     *    } ContentType;
2293
     *
2294
     *    struct {
2295
     *        ContentType type;
2296
     *        ProtocolVersion version;
2297
     *        uint16 length;
2298
     *        opaque fragment[TLSPlaintext.length];
2299
     *    } TLSPlaintext;
2300
     */
2301
5.77k
    uint32_t        record_length;
2302
5.77k
    uint16_t        record_version, version;
2303
5.77k
    uint8_t         content_type;
2304
5.77k
    uint8_t         next_byte;
2305
5.77k
    proto_tree     *ti;
2306
5.77k
    proto_tree     *ssl_record_tree;
2307
5.77k
    proto_item     *length_pi, *ct_pi;
2308
5.77k
    uint32_t        available_bytes;
2309
5.77k
    tvbuff_t       *decrypted;
2310
5.77k
    SslRecordInfo  *record = NULL;
2311
2312
5.77k
    ti = NULL;
2313
5.77k
    ssl_record_tree = NULL;
2314
2315
5.77k
    available_bytes = tvb_reported_length_remaining(tvb, offset);
2316
2317
    /* TLS 1.0/1.1 just ignores unknown records - RFC 2246 chapter 6. The TLS Record Protocol */
2318
5.77k
    if ((session->version==TLSV1_VERSION ||
2319
5.50k
         session->version==TLSV1DOT1_VERSION ||
2320
4.72k
         session->version==TLSV1DOT2_VERSION ||
2321
2.46k
         session->version==TLCPV1_VERSION ) &&
2322
4.13k
        (available_bytes >=1 ) && !ssl_is_valid_content_type(tvb_get_uint8(tvb, offset))) {
2323
498
        proto_tree_add_expert(tree, pinfo, &ei_tls_ignored_unknown_record, tvb, offset, available_bytes);
2324
498
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Ignored Unknown Record");
2325
498
        return offset + available_bytes;
2326
498
    }
2327
2328
    /*
2329
     * Is the record header split across segment boundaries?
2330
     */
2331
5.28k
    if (available_bytes < 5) {
2332
        /*
2333
         * Yes - can we do reassembly?
2334
         */
2335
0
        ssl_proto_tree_add_segment_data(tree, tvb, offset, available_bytes, NULL);
2336
0
        if (tls_desegment && pinfo->can_desegment) {
2337
            /*
2338
             * Yes.  Tell the TCP dissector where the data for this
2339
             * message starts in the data it handed us, and that we need
2340
             * "some more data."  Don't tell it exactly how many bytes we
2341
             * need because if/when we ask for even more (after the header)
2342
             * that will break reassembly.
2343
             */
2344
0
            pinfo->desegment_offset = offset;
2345
0
            pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
2346
0
            *need_desegmentation = true;
2347
0
            return offset;
2348
0
        } else {
2349
            /* Not enough bytes available. Stop here. */
2350
0
            return offset + available_bytes;
2351
0
        }
2352
0
    }
2353
2354
    /*
2355
     * Get the record layer fields of interest
2356
     */
2357
5.28k
    content_type  = tvb_get_uint8(tvb, offset);
2358
5.28k
    version       = tvb_get_ntohs(tvb, offset + 1);
2359
5.28k
    record_version = version;
2360
5.28k
    record_length = tvb_get_ntohs(tvb, offset + 3);
2361
2362
5.28k
    if (ssl_is_valid_content_type(content_type)) {
2363
2364
        /*
2365
         * Is the record split across segment boundaries?
2366
         */
2367
5.16k
        if (available_bytes < record_length + 5) {
2368
            /*
2369
             * Yes - can we do reassembly?
2370
             */
2371
75
            ssl_proto_tree_add_segment_data(tree, tvb, offset, available_bytes, NULL);
2372
75
            if (tls_desegment && pinfo->can_desegment) {
2373
                /*
2374
                 * Yes.  Tell the TCP dissector where the data for this
2375
                 * message starts in the data it handed us, and how many
2376
                 * more bytes we need, and return.
2377
                 */
2378
0
                pinfo->desegment_offset = offset;
2379
2380
                /* Don't use:
2381
                 * pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
2382
                 * it avoids some minor display glitches when a frame contains
2383
                 * the continuation of a previous PDU together with a full new
2384
                 * PDU, but it completely breaks dissection for jumbo TLS frames
2385
                 */
2386
2387
0
                pinfo->desegment_len = (record_length + 5) - available_bytes;
2388
0
                *need_desegmentation = true;
2389
0
                return offset;
2390
75
            } else {
2391
                /* Not enough bytes available. Stop here. */
2392
75
                return offset + available_bytes;
2393
75
            }
2394
75
        }
2395
2396
5.16k
    } else {
2397
        /* if we don't have a valid content_type, there's no sense
2398
         * continuing any further
2399
         */
2400
118
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
2401
2402
118
        return offset + 5 + record_length;
2403
118
    }
2404
2405
    /* add the record layer subtree header */
2406
5.08k
    ti = proto_tree_add_item(tree, hf_tls_record, tvb,
2407
5.08k
                             offset, 5 + record_length, ENC_NA);
2408
5.08k
    ssl_record_tree = proto_item_add_subtree(ti, ett_tls_record);
2409
2410
    /* show the one-byte content type */
2411
5.08k
    if (session->version == TLSV1DOT3_VERSION && content_type == SSL_ID_APP_DATA) {
2412
35
        ct_pi = proto_tree_add_item(ssl_record_tree, hf_tls_record_opaque_type,
2413
35
                            tvb, offset, 1, ENC_BIG_ENDIAN);
2414
5.05k
    } else {
2415
5.05k
        ct_pi = proto_tree_add_item(ssl_record_tree, hf_tls_record_content_type,
2416
5.05k
                            tvb, offset, 1, ENC_BIG_ENDIAN);
2417
5.05k
    }
2418
5.08k
    offset++;
2419
2420
    /* add the version */
2421
5.08k
    proto_tree_add_item(ssl_record_tree, hf_tls_record_version, tvb,
2422
5.08k
                        offset, 2, ENC_BIG_ENDIAN);
2423
5.08k
    offset += 2;
2424
2425
    /* add the length */
2426
5.08k
    length_pi = proto_tree_add_uint(ssl_record_tree, hf_tls_record_length, tvb,
2427
5.08k
                        offset, 2, record_length);
2428
5.08k
    offset += 2;    /* move past length field itself */
2429
2430
    /*
2431
     * if we don't already have a version set for this conversation,
2432
     * but this message's version is authoritative (i.e., it's
2433
     * not client_hello, then save the version to the conversation
2434
     * structure and print the column version. If the message is not authoritative
2435
     * (i.e. it is a Client Hello), then this version will still be used for
2436
     * display purposes only (it will not be stored in the conversation).
2437
     */
2438
5.08k
    next_byte = tvb_get_uint8(tvb, offset);
2439
5.08k
    if (session->version == SSL_VER_UNKNOWN) {
2440
15
        ssl_try_set_version(session, ssl, content_type, next_byte, false, version);
2441
        /* Version has possibly changed, adjust the column accordingly. */
2442
15
        col_set_str(pinfo->cinfo, COL_PROTOCOL,
2443
15
                            val_to_str_const(version, ssl_version_short_names, "SSL"));
2444
5.07k
    } else {
2445
5.07k
        version = session->version;
2446
5.07k
    }
2447
2448
    /*
2449
     * now dissect the next layer
2450
     */
2451
5.08k
    ssl_debug_printf("dissect_ssl3_record: content_type %d %s\n",content_type, val_to_str_const(content_type, ssl_31_content_type, "unknown"));
2452
2453
    /* try to decrypt record on the first pass, if possible. Store decrypted
2454
     * record for later usage (without having to decrypt again). The offset is
2455
     * used as 'key' to identify this record in the packet (we can have multiple
2456
     * handshake records in the same frame).
2457
     * In TLS 1.3, an encrypted record always has (outer) opaque_type of
2458
     * "Application Data". The actual content type of the record is found
2459
     * after decryption.
2460
     */
2461
5.08k
    if (ssl && record_length && (session->version != TLSV1DOT3_VERSION || content_type == SSL_ID_APP_DATA)) {
2462
3.53k
        bool        decrypt_ok = false;
2463
2464
        /* Try to decrypt TLS 1.3 early data first */
2465
3.53k
        if (session->version == TLSV1DOT3_VERSION && content_type == SSL_ID_APP_DATA &&
2466
35
            ssl->has_early_data && !ssl_packet_from_server(session, ssl_associations, pinfo)) {
2467
3
            decrypt_ok = decrypt_tls13_early_data(tvb, pinfo, offset, record_length, ssl, curr_layer_num_ssl);
2468
3
            if (!decrypt_ok) {
2469
                /* Either trial decryption failed (e.g. missing key) or end of
2470
                 * early data is reached. Switch to HS secrets if available. */
2471
3
                if (ssl->state & SSL_SERVER_RANDOM) {
2472
2
                    tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
2473
2
                }
2474
3
                ssl->has_early_data = false;
2475
3
            }
2476
3
        }
2477
2478
3.53k
        if (!decrypt_ok) {
2479
3.53k
            decrypt_ssl3_record(tvb, pinfo, offset, ssl,
2480
3.53k
                content_type, record_version, record_length,
2481
3.53k
                content_type == SSL_ID_APP_DATA ||
2482
3.45k
                content_type == SSL_ID_HANDSHAKE, curr_layer_num_ssl);
2483
3.53k
        }
2484
3.53k
    }
2485
2486
    /* try to retrieve and use decrypted alert/handshake/appdata record, if any. */
2487
5.08k
    decrypted = ssl_get_record_info(tvb, proto_tls, pinfo, tvb_raw_offset(tvb)+offset, curr_layer_num_ssl, &record);
2488
5.08k
    if (decrypted) {
2489
0
        add_new_data_source(pinfo, decrypted, "Decrypted TLS");
2490
0
        if (session->version == TLSV1DOT3_VERSION) {
2491
0
            content_type = record->type;
2492
0
            proto_tree_add_uint(ssl_record_tree, hf_tls_record_content_type,
2493
0
                                decrypted, record->content_len, 1, record->type);
2494
0
            decrypted = tvb_new_subset_length(decrypted, 0, record->content_len);
2495
0
        }
2496
0
        ti = proto_tree_add_uint64(ssl_record_tree, hf_tls_record_sequence_number,
2497
0
                                     tvb, 0, 0, record->record_seq);
2498
0
        proto_item_set_generated(ti);
2499
0
    }
2500
5.08k
    ssl_check_record_length(&dissect_ssl3_hf, pinfo, (ContentType)content_type, record_length, length_pi, version, decrypted);
2501
2502
5.08k
    switch ((ContentType) content_type) {
2503
278
    case SSL_ID_CHG_CIPHER_SPEC:
2504
278
        if (version == TLSV1DOT3_VERSION && session->tls13_draft_version > 0 && session->tls13_draft_version < 22) {
2505
            /* CCS was reintroduced in TLS 1.3 draft -22 */
2506
2
            expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
2507
2
                                   "Record type is not allowed in TLS 1.3");
2508
2
            break;
2509
2
        }
2510
276
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Change Cipher Spec");
2511
276
        ssl_dissect_change_cipher_spec(&dissect_ssl3_hf, tvb, pinfo,
2512
276
                                       ssl_record_tree, offset, session,
2513
276
                                       is_from_server, ssl);
2514
276
        if (version == TLSV1DOT3_VERSION) {
2515
            /* CCS is a dummy message in TLS 1.3, do not try to load keys. */
2516
8
            break;
2517
8
        }
2518
268
        if (ssl) {
2519
268
            ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
2520
268
                             &ssl_master_key_map);
2521
268
            ssl_finalize_decryption(ssl, &ssl_master_key_map);
2522
268
            ssl_change_cipher(ssl, ssl_packet_from_server(session, ssl_associations, pinfo));
2523
268
        }
2524
        /* Heuristic: any later ChangeCipherSpec is not a resumption of this
2525
         * session. Set the flag after ssl_finalize_decryption such that it has
2526
         * a chance to use resume using Session Tickets. */
2527
268
        if (is_from_server)
2528
0
          session->is_session_resumed = false;
2529
268
        break;
2530
82
    case SSL_ID_ALERT:
2531
82
        if (decrypted) {
2532
0
            dissect_ssl3_alert(decrypted, pinfo, ssl_record_tree, 0, 2, session, tlsinfo);
2533
82
        } else {
2534
82
            dissect_ssl3_alert(tvb, pinfo, ssl_record_tree, offset, record_length, session, tlsinfo);
2535
82
        }
2536
82
        break;
2537
4.50k
    case SSL_ID_HANDSHAKE:
2538
4.50k
        if (decrypted) {
2539
0
            unsigned record_id = record->id;
2540
0
            dissect_tls_handshake(decrypted, pinfo, ssl_record_tree, 0,
2541
0
                                  tvb_reported_length(decrypted), false, record_id, curr_layer_num_ssl, session,
2542
0
                                  is_from_server, ssl, version);
2543
4.50k
        } else {
2544
            // Combine both the offset within this TCP segment and the layer
2545
            // number in case a record consists of multiple reassembled TCP
2546
            // segments. The exact value does not matter, but it should be
2547
            // unique per frame.
2548
4.50k
            unsigned record_id = tvb_raw_offset(tvb) + offset + curr_layer_num_ssl;
2549
4.50k
            dissect_tls_handshake(tvb, pinfo, ssl_record_tree, offset,
2550
4.50k
                                  offset + record_length, true, record_id, curr_layer_num_ssl, session,
2551
4.50k
                                  is_from_server, ssl, version);
2552
4.50k
        }
2553
4.50k
        break;
2554
87
    case SSL_ID_APP_DATA:
2555
87
    {
2556
87
        dissector_handle_t app_handle;
2557
2558
        /* show on info column what we are decoding */
2559
87
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Application Data");
2560
2561
        /* app_handle discovery is done here instead of dissect_ssl_payload()
2562
         * because the protocol name needs to be displayed below. */
2563
87
        app_handle = session->app_handle;
2564
87
        if (!app_handle) {
2565
            /* Unknown protocol handle, ssl_starttls_ack was not called before.
2566
             * Try to find a port-based protocol and use it if there is no
2567
             * heuristics dissector (see process_ssl_payload). */
2568
5
            app_handle = dissector_get_uint_handle(ssl_associations, PINFO_SRCPORT(pinfo));
2569
5
            if (!app_handle) app_handle = dissector_get_uint_handle(ssl_associations, PINFO_DESTPORT(pinfo));
2570
5
        }
2571
2572
87
        proto_item_set_text(ssl_record_tree,
2573
87
           "%s Record Layer: %s Protocol: %s",
2574
87
            val_to_str_const(version, ssl_version_short_names, "SSL"),
2575
87
            val_to_str_const(content_type, ssl_31_content_type, "unknown"),
2576
87
            app_handle ? dissector_handle_get_protocol_long_name(app_handle)
2577
87
            : "Application Data");
2578
2579
87
        proto_tree_add_item(ssl_record_tree, hf_tls_record_appdata, tvb,
2580
87
                       offset, record_length, ENC_NA);
2581
2582
87
        if (app_handle) {
2583
76
            ti = proto_tree_add_string(ssl_record_tree, hf_tls_record_appdata_proto, tvb, 0, 0, dissector_handle_get_protocol_long_name(app_handle));
2584
76
            proto_item_set_generated(ti);
2585
76
        }
2586
2587
87
        if (decrypted) {
2588
0
            dissect_ssl_payload(decrypted, pinfo, tree, session, record, app_handle, tlsinfo);
2589
0
        }
2590
2591
        /* Set app proto again in case the heuristics found a different proto. */
2592
87
        if (session->app_handle && session->app_handle != app_handle)
2593
0
            proto_item_set_text(ssl_record_tree,
2594
0
               "%s Record Layer: %s Protocol: %s",
2595
0
                val_to_str_const(version, ssl_version_short_names, "SSL"),
2596
0
                val_to_str_const(content_type, ssl_31_content_type, "unknown"),
2597
0
                dissector_handle_get_protocol_long_name(session->app_handle));
2598
2599
87
        break;
2600
276
    }
2601
110
    case SSL_ID_HEARTBEAT:
2602
110
        if (version == TLSV1DOT3_VERSION) {
2603
27
            expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
2604
27
                                   "Record type is not allowed in TLS 1.3");
2605
27
            break;
2606
27
        }
2607
83
        if (decrypted) {
2608
0
            dissect_ssl3_heartbeat(decrypted, pinfo, ssl_record_tree, 0, session, tvb_reported_length (decrypted), true);
2609
83
        } else {
2610
83
            bool plaintext = true;
2611
            /* heartbeats before ChangeCipherSpec are unencrypted */
2612
83
            if (ssl) {
2613
83
                if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
2614
0
                    plaintext = ssl->server == NULL;
2615
83
                } else {
2616
83
                    plaintext = ssl->client == NULL;
2617
83
                }
2618
83
            }
2619
83
            dissect_ssl3_heartbeat(tvb, pinfo, ssl_record_tree, offset, session, record_length, plaintext);
2620
83
        }
2621
83
        break;
2622
11
    case SSL_ID_TLS12_CID:
2623
23
    case SSL_ID_DTLS13_ACK:
2624
23
        break;
2625
5.08k
    }
2626
3.92k
    offset += record_length; /* skip to end of record */
2627
2628
3.92k
    return offset;
2629
5.08k
}
2630
2631
/* dissects the alert message, filling in the tree */
2632
static void
2633
dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
2634
                   proto_tree *tree, uint32_t offset, uint32_t record_length,
2635
                   const SslSession *session, struct tlsinfo *tlsinfo)
2636
82
{
2637
    /*     struct {
2638
     *         AlertLevel level;
2639
     *         AlertDescription description;
2640
     *     } Alert;
2641
     */
2642
82
    proto_tree  *ti;
2643
82
    proto_tree  *alert_tree = NULL;
2644
82
    const char *level;
2645
82
    const char *desc;
2646
82
    uint8_t      level_byte, desc_byte;
2647
2648
82
    if (tree)
2649
82
    {
2650
82
        ti = proto_tree_add_item(tree, hf_tls_alert_message, tvb,
2651
82
                                 offset, record_length, ENC_NA);
2652
82
        alert_tree = proto_item_add_subtree(ti, ett_tls_alert);
2653
82
    }
2654
2655
    /*
2656
     * Assume that TLS alert records are not fragmented. Any larger message is
2657
     * assumed to be encrypted.
2658
     */
2659
82
    if (record_length != 2) {
2660
57
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Alert");
2661
57
        proto_item_set_text(tree,
2662
57
                            "%s Record Layer: Encrypted Alert",
2663
57
                            val_to_str_const(session->version, ssl_version_short_names, "TLS"));
2664
57
        proto_item_set_text(alert_tree,
2665
57
                            "Alert Message: Encrypted Alert");
2666
57
        return;
2667
57
    }
2668
2669
    /*
2670
     * set the record layer label
2671
     */
2672
2673
    /* first lookup the names for the alert level and description */
2674
25
    level_byte = tvb_get_uint8(tvb, offset); /* grab the level byte */
2675
25
    level = val_to_str_const(level_byte, ssl_31_alert_level, "Unknown");
2676
2677
25
    desc_byte = tvb_get_uint8(tvb, offset+1); /* grab the desc byte */
2678
25
    desc = val_to_str_const(desc_byte, ssl_31_alert_description, "Unknown");
2679
25
    if (desc_byte == 0) {
2680
        /* If this is a close_notify, mark it as the end of the stream.
2681
         * (XXX: Maybe we should do this for other alerts, and maybe
2682
         * reassembling at FIN should also try reassembling at RST as well?)
2683
         */
2684
8
        tlsinfo->end_of_stream = true;
2685
8
    }
2686
2687
    /* now set the text in the record layer line */
2688
25
    col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
2689
25
                        "Alert (Level: %s, Description: %s)",
2690
25
                        level, desc);
2691
2692
25
    if (tree)
2693
25
    {
2694
25
        proto_item_set_text(tree, "%s Record Layer: Alert "
2695
25
                            "(Level: %s, Description: %s)",
2696
25
                            val_to_str_const(session->version, ssl_version_short_names, "TLS"),
2697
25
                            level, desc);
2698
25
        proto_tree_add_item(alert_tree, hf_tls_alert_message_level,
2699
25
                            tvb, offset++, 1, ENC_BIG_ENDIAN);
2700
2701
25
        proto_tree_add_item(alert_tree, hf_tls_alert_message_description,
2702
25
                            tvb, offset++, 1, ENC_BIG_ENDIAN);
2703
25
    }
2704
25
}
2705
2706
2707
/**
2708
 * Checks whether a handshake message seems encrypted and cannot be dissected.
2709
 */
2710
static bool
2711
is_encrypted_handshake_message(tvbuff_t *tvb, packet_info *pinfo, uint32_t offset, uint32_t offset_end,
2712
                               SslSession *session, bool is_from_server)
2713
3.60k
{
2714
3.60k
    unsigned record_length = offset_end - offset;
2715
3.60k
    unsigned msg_length = 0;
2716
3.60k
    uint8_t msg_type = 0;
2717
3.60k
    uint16_t version;
2718
2719
3.60k
    if (record_length < 16) {
2720
        /*
2721
         * Encrypted data has additional overhead. For TLS 1.0/1.1 with stream
2722
         * and block ciphers, there is at least a MAC which is at minimum 16
2723
         * bytes for MD5. In TLS 1.2, AEAD adds an explicit nonce and auth tag.
2724
         * For AES-GCM/CCM the auth tag is 16 bytes. AES_CCM_8 (RFC 6655) uses 8
2725
         * byte auth tags, but the explicit nonce is also 8 (sums up to 16).
2726
         *
2727
         * So anything smaller than 16 bytes is assumed to be plaintext.
2728
         */
2729
148
        return false;
2730
148
    }
2731
2732
    /*
2733
     * If this is not a decrypted buffer, then perhaps it is still in plaintext.
2734
     * Heuristics: if the buffer is too small, it is likely not encrypted.
2735
     * Otherwise assume that the Handshake does not contain two successive
2736
     * HelloRequest messages (type=0x00 length=0x000000, type=0x00). If this
2737
     * occurs, then we have possibly found the explicit nonce preceding the
2738
     * encrypted contents for GCM/CCM cipher suites as used in TLS 1.2.
2739
     */
2740
3.60k
    bool maybe_encrypted = tvb_get_ntoh40(tvb, offset) == 0;
2741
    /*
2742
     * TODO handle Finished message after CCS in the same frame and remove the
2743
     * above nonce-based heuristic.
2744
     */
2745
2746
3.45k
    if (!maybe_encrypted) {
2747
        /*
2748
         * Assume encrypted if the message type makes no sense. If this still
2749
         * leads to false positives (detecting plaintext while it should mark
2750
         * stuff as encrypted), some other ideas include:
2751
         * - Perform additional validation based on the message type.
2752
         * - Disallow handshake fragmentation except for some common cases like
2753
         *   Certificate messages (due to large certificates).
2754
         */
2755
3.44k
        msg_type = tvb_get_uint8(tvb, offset);
2756
3.44k
        maybe_encrypted = try_val_to_str(msg_type, ssl_31_handshake_type) == NULL;
2757
3.44k
        if (!maybe_encrypted) {
2758
3.13k
            msg_length = tvb_get_ntoh24(tvb, offset + 1);
2759
            // Assume handshake messages are below 64K.
2760
3.13k
            maybe_encrypted = msg_length >= 0x010000;
2761
3.13k
        }
2762
3.44k
    }
2763
2764
3.45k
    if (!maybe_encrypted) {
2765
2766
        /*
2767
         * Everything after the ChangeCipherSpec message should be encrypted.
2768
         * At least some buggy clients send a new handshake in the clear
2769
         * when renegotiating, though. (#18867).
2770
         */
2771
3.02k
        uint32_t *ccs_frame = is_from_server ? &session->server_ccs_frame : &session->client_ccs_frame;
2772
3.02k
        if (*ccs_frame != 0 && pinfo->num > *ccs_frame) {
2773
189
            switch (msg_type) {
2774
2775
44
            case SSL_HND_CLIENT_HELLO:
2776
71
            case SSL_HND_SERVER_HELLO:
2777
71
                version = tvb_get_ntohs(tvb, offset + 4);
2778
71
                maybe_encrypted = !ssl_is_valid_ssl_version(version);
2779
2780
71
                if (!maybe_encrypted) {
2781
                    // Assume ClientHello and ServerHello are < 1024.
2782
48
                    maybe_encrypted = msg_length >= 0x400;
2783
48
                }
2784
2785
71
                if (!maybe_encrypted) {
2786
                    /*
2787
                     * This is after the CCS, but looks like an unencrypted
2788
                     * ClientHello or ServerHello. This is a new handshake;
2789
                     * it's a buggy renegotiation or possibly retransmissions.
2790
                     */
2791
45
                    if (!PINFO_FD_VISITED(pinfo))
2792
45
                        *ccs_frame = 0;
2793
                    /* XXX: Resetting the CCS frame state will allow us to
2794
                     * detect the new handshake, but can mean false positives
2795
                     * on earlier frames on later passes (reporting as
2796
                     * cleartext handshake messages that were encrypted and
2797
                     * we failed to decrypt on the first pass.) Maybe we
2798
                     * should store some additional state, either per packet
2799
                     * in SslPacketInfo or more complicated information about
2800
                     * encrypted handshake state changes. (E.g., in a wmem_tree
2801
                     * store the frames where we get a CCS and the frames
2802
                     * where this happens.)
2803
                     */
2804
45
                }
2805
71
                break;
2806
118
            default:
2807
118
                maybe_encrypted = true;
2808
189
            }
2809
189
        }
2810
3.02k
    }
2811
3.45k
    return maybe_encrypted;
2812
3.45k
}
2813
2814
static TlsHsFragment *
2815
save_tls_handshake_fragment(packet_info *pinfo, uint8_t curr_layer_num_tls,
2816
                            unsigned record_id, unsigned reassembly_id,
2817
                            tvbuff_t *tvb, uint32_t offset, unsigned frag_len,
2818
                            unsigned frag_offset, uint8_t msg_type, bool is_last,
2819
                            SslSession *session)
2820
2.90k
{
2821
    // Full handshake messages should not be saved.
2822
2.90k
    DISSECTOR_ASSERT(!(frag_offset == 0 && is_last));
2823
    // 0 is a special value indicating no reassembly in progress.
2824
2.90k
    DISSECTOR_ASSERT(reassembly_id != 0);
2825
2826
2.90k
    if (tvb_reported_length(tvb) > tvb_captured_length(tvb)) {
2827
        // The reassembly API will refuse to add fragments when not all
2828
        // available data has been captured. Since we were given a tvb with at
2829
        // least 'frag_len' data, we must always succeed in obtaining a subset.
2830
2.73k
        tvb = tvb_new_subset_length(tvb, 0, offset + frag_len);
2831
2.73k
    }
2832
2833
2.90k
    SslPacketInfo *pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
2834
2.90k
    TlsHsFragment *frag_info = wmem_new0(wmem_file_scope(), TlsHsFragment);
2835
2.90k
    frag_info->record_id = record_id;
2836
2.90k
    frag_info->reassembly_id = reassembly_id;
2837
2.90k
    frag_info->is_last = is_last;
2838
2.90k
    frag_info->offset = frag_offset;
2839
2.90k
    frag_info->type = msg_type;
2840
2841
2.90k
    TlsHsFragment **p = &pi->hs_fragments;
2842
8.21k
    while (*p) p = &(*p)->next;
2843
2.90k
    *p = frag_info;
2844
2845
    // Add (subset of) record data.
2846
2.90k
    fragment_add_check(&tls_hs_reassembly_table, tvb, offset,
2847
2.90k
                       pinfo, reassembly_id, session, frag_offset, frag_len, !is_last);
2848
2849
2.90k
    return frag_info;
2850
2.90k
}
2851
2852
/**
2853
 * Populate the Info column and record layer tree item based on the message type.
2854
 *
2855
 * @param pinfo Packet info.
2856
 * @param record_tree The Record layer tree item.
2857
 * @param version Record version.
2858
 * @param msg_type The message type (not necessarily the same as the first byte
2859
 * of the buffer in case of HRR in TLS 1.3).
2860
 * @param is_first_msg true if this is the first message in this record.
2861
 * @param complete true if the buffer describes the full (encrypted) message.
2862
 * @param tvb Buffer that covers the start of this handshake fragment.
2863
 * @param offset Position within the record data.
2864
 * @param length Length of the record fragment that is part of the handshake
2865
 * message. May be smaller than the record length if this is a fragment.
2866
 */
2867
static proto_item *
2868
tls_show_handshake_details(packet_info *pinfo, proto_tree *record_tree, unsigned version,
2869
        uint8_t msg_type, bool is_encrypted, bool is_first_msg, bool complete,
2870
        tvbuff_t *tvb, uint32_t offset, uint32_t length)
2871
15.7k
{
2872
15.7k
    const char *msg_type_str = "Encrypted Handshake Message";
2873
15.7k
    if (!is_encrypted) {
2874
15.1k
        msg_type_str = val_to_str_const(msg_type, ssl_31_handshake_type, msg_type_str);
2875
15.1k
    }
2876
2877
    /*
2878
     * Update our info string if this is the first message (possibly a fragment
2879
     * of a handshake message), or if this is a complete (reassembled) message.
2880
     */
2881
15.7k
    if (complete) {
2882
13.5k
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);
2883
13.5k
    } else if (is_first_msg) {
2884
        /*
2885
         * Only mark the first message to avoid an empty Info column. If another
2886
         * message came before this one, do not bother mentioning this fragment.
2887
         */
2888
1.16k
        col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "[%s Fragment]", msg_type_str);
2889
1.16k
    }
2890
2891
    /* set the label text on the record layer expanding node */
2892
15.7k
    if (is_first_msg) {
2893
4.40k
        proto_item_set_text(record_tree, "%s Record Layer: Handshake Protocol: %s",
2894
4.40k
                val_to_str_const(version, ssl_version_short_names, "TLS"),
2895
4.40k
                msg_type_str);
2896
4.40k
        if (!complete && !is_encrypted) {
2897
1.16k
            proto_item_append_text(record_tree, " (fragment)");
2898
1.16k
        }
2899
11.3k
    } else {
2900
11.3k
        proto_item_set_text(record_tree, "%s Record Layer: Handshake Protocol: %s",
2901
11.3k
                val_to_str_const(version, ssl_version_short_names, "TLS"),
2902
11.3k
                "Multiple Handshake Messages");
2903
11.3k
    }
2904
2905
15.7k
    proto_item *ti = proto_tree_add_item(record_tree, hf_tls_handshake_protocol,
2906
15.7k
            tvb, offset, length, ENC_NA);
2907
15.7k
    proto_item_set_text(ti, "Handshake Protocol: %s", msg_type_str);
2908
15.7k
    if (!complete && !is_encrypted) {
2909
2.14k
        proto_item_append_text(ti, " (fragment)");
2910
2.14k
    }
2911
15.7k
    return ti;
2912
15.7k
}
2913
2914
/* dissects the handshake protocol, filling the tree */
2915
static void
2916
dissect_tls_handshake(tvbuff_t *tvb, packet_info *pinfo,
2917
                      proto_tree *tree, uint32_t offset,
2918
                      uint32_t offset_end, bool maybe_encrypted,
2919
                      unsigned record_id, uint8_t curr_layer_num_tls,
2920
                      SslSession *session, int is_from_server,
2921
                      SslDecryptSession *ssl,
2922
                      const uint16_t version)
2923
4.50k
{
2924
    // Handshake fragment processing:
2925
    // 1. (First pass:) If a previous handshake message needed reassembly, add
2926
    //    (a subset of) the new data for reassembly.
2927
    // 2. Did this fragment complete reassembly in the previous step?
2928
    //    - Yes: dissect message and continue.
2929
    //    - No: show details and stop.
2930
    // 3. Not part of a reassembly, so this is a new handshake message. Does it
2931
    //    look like encrypted data?
2932
    //    - Yes: show details and stop.
2933
    // 4. Loop through remaining handshake messages. Is there sufficient data?
2934
    //    - Yes: dissect message and continue with next message.
2935
    //    - No (first pass): Add all data for reassembly, show details and stop.
2936
    //    - No (second pass): Show details and stop.
2937
2938
4.50k
    fragment_head  *fh = NULL;
2939
4.50k
    unsigned        subset_len;
2940
4.50k
    uint32_t        msg_len = 0;
2941
4.50k
    TlsHsFragment  *frag_info = NULL;
2942
4.50k
    bool            is_first_msg = true;
2943
4.50k
    proto_item     *frag_tree_item;
2944
4.50k
    unsigned       *hs_reassembly_id_p = is_from_server ? &session->server_hs_reassembly_id : &session->client_hs_reassembly_id;
2945
2946
4.50k
    if (!PINFO_FD_VISITED(pinfo)) {
2947
        // 1. (First pass:) If a previous handshake message needed reassembly.
2948
4.50k
        if (*hs_reassembly_id_p) {
2949
            // Continuation, so a previous fragment *must* exist.
2950
2.19k
            fh = fragment_get(&tls_hs_reassembly_table, pinfo, *hs_reassembly_id_p, session);
2951
2.19k
            DISSECTOR_ASSERT(fh);
2952
            // We expect that reassembly has not completed yet.
2953
2.19k
            DISSECTOR_ASSERT(fh->tvb_data == NULL);
2954
2955
            // Combine all previous segments plus data from the current record
2956
            // in order to find the length.
2957
2.19k
            tvbuff_t *len_tvb = tvb_new_composite();
2958
2.19k
            unsigned frags_len = 0;
2959
3.91k
            for (fragment_item *fd = fh->next; fd; fd = fd->next) {
2960
1.72k
                if (frags_len < 4) {
2961
1.18k
                    tvb_composite_append(len_tvb, fd->tvb_data);
2962
1.18k
                }
2963
1.72k
                frags_len += tvb_reported_length(fd->tvb_data);
2964
1.72k
            }
2965
2.19k
            if (frags_len < 4) {
2966
1.15k
                tvbuff_t *remaining_tvb = tvb_new_subset_remaining(tvb, offset);
2967
1.15k
                tvb_composite_append(len_tvb, remaining_tvb);
2968
1.15k
            }
2969
2.19k
            tvb_composite_finalize(len_tvb);
2970
2971
            // Extract the actual handshake message length (0 means unknown) and
2972
            // check whether only a subset of the current record is needed.
2973
2.19k
            subset_len = offset_end - offset;
2974
2.19k
            if (tvb_reported_length(len_tvb) >= 4) {
2975
2.18k
                msg_len = 4 + tvb_get_ntoh24(len_tvb, 1);
2976
2.18k
                if (subset_len > msg_len - frags_len) {
2977
275
                    subset_len = msg_len - frags_len;
2978
275
                }
2979
2.18k
            }
2980
2981
2.19k
            if (tvb_captured_length(tvb) < offset + subset_len) {
2982
                // Not all data has been captured. As we are missing data, the
2983
                // reassembly cannot be completed nor do we know the boundary
2984
                // where the next handshake message starts. Stop reassembly.
2985
1.28k
                *hs_reassembly_id_p = 0;
2986
1.28k
            } else {
2987
                // Check if the handshake message is complete.
2988
907
                uint8_t msg_type = tvb_get_uint8(len_tvb, 0);
2989
907
                bool is_last = frags_len + subset_len == msg_len;
2990
907
                frag_info = save_tls_handshake_fragment(pinfo, curr_layer_num_tls, record_id, *hs_reassembly_id_p,
2991
907
                        tvb, offset, subset_len, frags_len, msg_type, is_last, session);
2992
907
                if (is_last) {
2993
                    // Reassembly finished, next message should not continue this message.
2994
67
                    *hs_reassembly_id_p = 0;
2995
67
                }
2996
907
            }
2997
2.19k
        }
2998
4.50k
    } else {
2999
        // Lookup the reassembled handshake matching this frame (if any).
3000
0
        SslPacketInfo *pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
3001
0
        if (pi) {
3002
0
            for (TlsHsFragment *rec = pi->hs_fragments; rec; rec = rec->next) {
3003
0
                if (rec->record_id == record_id) {
3004
0
                    frag_info = rec;
3005
0
                    break;
3006
0
                }
3007
0
            }
3008
0
        }
3009
0
    }
3010
3011
    // 2. Did this fragment complete reassembly in the previous step?
3012
4.50k
    if (frag_info && frag_info->offset != 0) {
3013
212
        fh = fragment_get_reassembled_id(&tls_hs_reassembly_table, pinfo, frag_info->reassembly_id);
3014
212
        if (frag_info->is_last) {
3015
            // This is the last fragment of the handshake message.
3016
            // Skip a subset of the bytes of this buffer.
3017
67
            subset_len = tvb_reported_length_remaining(fh->tvb_data, frag_info->offset);
3018
3019
            // Add a tree item to mark the handshake fragment.
3020
67
            proto_item *ti = proto_tree_add_item(tree,
3021
67
                    hf_tls_handshake_protocol, tvb, offset, subset_len, ENC_NA);
3022
67
            offset += subset_len;
3023
67
            proto_item_set_text(ti, "Handshake Protocol: %s (last fragment)",
3024
67
                    val_to_str_const(frag_info->type, ssl_31_handshake_type,
3025
67
                        "Encrypted Handshake Message"));
3026
3027
            // Now display the full, reassembled handshake message.
3028
67
            tvbuff_t *next_tvb = tvb_new_chain(tvb, fh->tvb_data);
3029
67
            add_new_data_source(pinfo, next_tvb, "Reassembled TLS Handshake");
3030
67
            show_fragment_tree(fh, &tls_hs_fragment_items, tree, pinfo, next_tvb, &frag_tree_item);
3031
67
            dissect_tls_handshake_full(next_tvb, pinfo, tree, 0, session, is_from_server, ssl, version, true, curr_layer_num_tls);
3032
67
            is_first_msg = false;
3033
3034
            // Skip to the next fragment in case this records ends with another
3035
            // fragment for which information is presented below.
3036
67
            frag_info = frag_info->next;
3037
67
            if (frag_info && frag_info->record_id != record_id) {
3038
0
                frag_info = NULL;
3039
0
            }
3040
67
        }
3041
145
        else {
3042
            // The full TVB is in the middle of a handshake message and needs more data.
3043
145
            tls_show_handshake_details(pinfo, tree, version, frag_info->type, false, is_first_msg, false,
3044
145
                    tvb, offset, offset_end - offset);
3045
145
            if (fh) {
3046
0
                proto_tree_add_uint(tree, hf_tls_handshake_reassembled_in, tvb, 0, 0, fh->reassembled_in);
3047
0
            }
3048
145
            return;
3049
145
        }
3050
4.29k
    } else if (!frag_info) {
3051
        // 3. Not part of a reassembly, so this is a new handshake message. Does it
3052
        //    look like encrypted data?
3053
3.60k
        if (maybe_encrypted && is_encrypted_handshake_message(tvb, pinfo, offset, offset_end, session, is_from_server)) {
3054
            // Update Info column and record tree.
3055
576
            tls_show_handshake_details(pinfo, tree, version, 0, true, true, true,
3056
576
                    tvb, offset, offset_end - offset);
3057
576
            return;
3058
576
        }
3059
3.60k
    }
3060
3061
    // 4. Loop through remaining handshake messages.
3062
    // The previous reassembly has been handled, so at this point, offset should
3063
    // start a new, valid handshake message.
3064
18.4k
    while (offset < offset_end) {
3065
16.6k
        msg_len = 0;
3066
16.6k
        subset_len = offset_end - offset;
3067
16.6k
        if (subset_len >= 4) {
3068
16.5k
            msg_len = 4 + tvb_get_ntoh24(tvb, offset + 1);
3069
16.5k
        }
3070
16.6k
        if (msg_len == 0 || subset_len < msg_len) {
3071
            // Need more data to find the message length or complete it.
3072
2.00k
            if (!PINFO_FD_VISITED(pinfo)) {
3073
2.00k
                uint8_t msg_type = tvb_get_uint8(tvb, offset);
3074
2.00k
                *hs_reassembly_id_p = ++hs_reassembly_id_count;
3075
2.00k
                frag_info = save_tls_handshake_fragment(pinfo, curr_layer_num_tls, record_id, *hs_reassembly_id_p,
3076
2.00k
                        tvb, offset, subset_len, 0, msg_type, false, session);
3077
2.00k
            } else {
3078
                // The first pass must have created a new fragment.
3079
0
                if (!frag_info || frag_info->offset != 0) {
3080
                    /* The first pass took another path, just show the data. */
3081
0
                    tls_show_handshake_details(pinfo, tree, version, tvb_get_uint8(tvb, offset),
3082
0
                            false, is_first_msg, false, tvb, offset, subset_len);
3083
0
                    break;
3084
0
                }
3085
0
            }
3086
3087
2.00k
            tls_show_handshake_details(pinfo, tree, version, frag_info->type, false, is_first_msg, false,
3088
2.00k
                    tvb, offset, subset_len);
3089
2.00k
            fh = fragment_get_reassembled_id(&tls_hs_reassembly_table, pinfo, frag_info->reassembly_id);
3090
2.00k
            if (fh) {
3091
0
                proto_tree_add_uint(tree, hf_tls_handshake_reassembled_in, tvb, 0, 0, fh->reassembled_in);
3092
0
            }
3093
2.00k
            break;
3094
2.00k
        }
3095
3096
14.6k
        dissect_tls_handshake_full(tvb, pinfo, tree, offset, session, is_from_server, ssl, version, is_first_msg, curr_layer_num_tls);
3097
14.6k
        offset += msg_len;
3098
14.6k
        is_first_msg = false;
3099
14.6k
    }
3100
3.78k
}
3101
3102
/* Dissects a single (reassembled) Handshake message. */
3103
static void
3104
dissect_tls_handshake_full(tvbuff_t *tvb, packet_info *pinfo,
3105
                           proto_tree *tree, uint32_t offset,
3106
                           SslSession *session, int is_from_server,
3107
                           SslDecryptSession *ssl,
3108
                           const uint16_t version,
3109
                           bool is_first_msg, uint8_t curr_layer_num_tls)
3110
14.3k
{
3111
    /*     struct {
3112
     *         HandshakeType msg_type;
3113
     *         uint24 length;
3114
     *         select (HandshakeType) {
3115
     *             case hello_request:       HelloRequest;
3116
     *             case client_hello:        ClientHello;
3117
     *             case server_hello:        ServerHello;
3118
     *             case certificate:         Certificate;
3119
     *             case server_key_exchange: ServerKeyExchange;
3120
     *             case certificate_request: CertificateRequest;
3121
     *             case server_hello_done:   ServerHelloDone;
3122
     *             case certificate_verify:  CertificateVerify;
3123
     *             case client_key_exchange: ClientKeyExchange;
3124
     *             case finished:            Finished;
3125
     *             case certificate_url:     CertificateURL;
3126
     *             case certificate_status:  CertificateStatus;
3127
     *             case encrypted_extensions:NextProtocolNegotiationEncryptedExtension;
3128
     *         } body;
3129
     *     } Handshake;
3130
     */
3131
14.3k
    proto_tree    *ssl_hand_tree = NULL;
3132
14.3k
    const char    *msg_type_str;
3133
14.3k
    uint8_t        msg_type;
3134
14.3k
    uint32_t       length;
3135
14.3k
    proto_item    *ti;
3136
14.3k
    SslPacketInfo *pi;
3137
3138
14.3k
    {
3139
14.3k
        uint32_t hs_offset = offset;
3140
14.3k
        bool is_hrr = false;
3141
3142
14.3k
        msg_type = tvb_get_uint8(tvb, offset);
3143
14.3k
        length   = tvb_get_ntoh24(tvb, offset + 1);
3144
        // The caller should have given us a fully reassembled record.
3145
14.3k
        DISSECTOR_ASSERT((unsigned)tvb_reported_length_remaining(tvb, offset + 4) >= length);
3146
3147
14.3k
        msg_type_str = try_val_to_str(msg_type, ssl_31_handshake_type);
3148
3149
14.3k
        ssl_debug_printf("dissect_ssl3_handshake iteration %d type %d offset %d length %d "
3150
14.3k
            "bytes\n", is_first_msg, msg_type, offset, length);
3151
14.3k
        if (!msg_type_str && !is_first_msg)
3152
1.30k
        {
3153
            /* only dissect / report messages if they're
3154
             * either the first message in this record
3155
             * or they're a valid message type
3156
             */
3157
1.30k
            return;
3158
1.30k
        }
3159
3160
13.0k
        if (is_first_msg && msg_type == SSL_HND_SERVER_HELLO && length > 2) {
3161
224
            uint16_t server_version;
3162
3163
224
            tls_scan_server_hello(tvb, offset + 4, offset + 4 + length, &server_version, &is_hrr);
3164
224
            ssl_try_set_version(session, ssl, SSL_ID_HANDSHAKE, SSL_HND_SERVER_HELLO, false, server_version);
3165
224
            if (is_hrr) {
3166
9
                msg_type_str = "Hello Retry Request";
3167
9
            }
3168
224
        }
3169
3170
        /* Populate Info column and set record layer text. */
3171
13.0k
        ti = tls_show_handshake_details(pinfo, tree, version,
3172
13.0k
                is_hrr ? SSL_HND_HELLO_RETRY_REQUEST : msg_type, false, is_first_msg, true,
3173
13.0k
                tvb, offset, length + 4);
3174
3175
        /* if we don't have a valid handshake type, just quit dissecting */
3176
13.0k
        if (!msg_type_str)
3177
19
            return;
3178
3179
        /* add a subtree for the handshake protocol */
3180
12.9k
        ssl_hand_tree = proto_item_add_subtree(ti, ett_tls_handshake);
3181
3182
        /* add nodes for the message type and message length */
3183
12.9k
        proto_tree_add_uint(ssl_hand_tree, hf_tls_handshake_type,
3184
12.9k
                tvb, offset, 1, msg_type);
3185
12.9k
        offset += 1;
3186
12.9k
        proto_tree_add_uint(ssl_hand_tree, hf_tls_handshake_length,
3187
12.9k
                tvb, offset, 3, length);
3188
12.9k
        offset += 3;
3189
3190
12.9k
        if ((msg_type == SSL_HND_CLIENT_HELLO || msg_type == SSL_HND_SERVER_HELLO)) {
3191
2.08k
            if (msg_type == SSL_HND_CLIENT_HELLO) {
3192
                /* If this is ClientHello2 after a HelloRetryRequest, the
3193
                 * transcript is kept (RFC 8446 4.4.1); check that it is. */
3194
1.19k
                tls_check_client_hello_random(ssl, tvb, offset);
3195
1.19k
            }
3196
            /* Prepare for renegotiation by resetting the state. */
3197
2.08k
            ssl_reset_session(session, ssl, msg_type == SSL_HND_CLIENT_HELLO);
3198
2.08k
        }
3199
3200
        /*
3201
         * Add handshake message (including type, length, etc.) to hash (for
3202
         * Extended Master Secret or TLS 1.3 secrets when using psk_ke).
3203
         * A HelloRetryRequest is handled in ssl_dissect_hnd_srv_hello.
3204
         */
3205
12.9k
        ssl_calculate_handshake_hash(ssl, tvb, hs_offset, 4 + length, msg_type, is_from_server);
3206
3207
        /* now dissect the handshake message, if necessary */
3208
12.9k
        switch ((HandshakeType) msg_type) {
3209
3.95k
            case SSL_HND_HELLO_REQUEST:
3210
                /* hello_request has no fields, so nothing to do! */
3211
3.95k
                break;
3212
3213
1.19k
            case SSL_HND_CLIENT_HELLO:
3214
1.19k
                if (ssl) {
3215
                    /* ClientHello is first packet so set direction */
3216
1.19k
                    ssl_set_server(session, PINFO_DST(pinfo), pinfo->ptype, PINFO_DESTPORT(pinfo));
3217
1.19k
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3218
1.19k
                }
3219
1.19k
                ssl_dissect_hnd_cli_hello(&dissect_ssl3_hf, tvb, pinfo,
3220
1.19k
                        ssl_hand_tree, offset, offset + length, session, ssl,
3221
1.19k
                        NULL, &ssl_master_key_map);
3222
                /*
3223
                 * Cannot call tls13_change_key here with TLS_SECRET_HANDSHAKE
3224
                 * since the server may not agree on using TLS 1.3. If
3225
                 * early_data is advertised, it must be TLS 1.3 though.
3226
                 *
3227
                 * XXX - If we want to calculate the key from a PSK, it might
3228
                 * be better to do it now. There's a rare possibility that the
3229
                 * Server Hello could be received before the first 0RTT-APPDATA,
3230
                 * which would throw off the handshake transcript hash.
3231
                 */
3232
1.19k
                if (ssl) {
3233
1.07k
                    tls_save_crandom(ssl, &ssl_master_key_map);
3234
1.07k
                    if  (ssl->has_early_data) {
3235
15
                        session->version = TLSV1DOT3_VERSION;
3236
15
                        ssl->state |= SSL_VERSION;
3237
15
                        ssl_debug_printf("%s forcing version 0x%04X -> state 0x%02X\n", G_STRFUNC, version, ssl->state);
3238
15
                    }
3239
1.07k
                }
3240
1.19k
                break;
3241
3242
885
            case SSL_HND_SERVER_HELLO:
3243
885
                ssl_dissect_hnd_srv_hello(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
3244
885
                        offset, offset + length, session, ssl, false, is_hrr);
3245
885
                if (ssl) {
3246
865
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3247
865
                    if (ssl->has_psk && !ssl->has_key_share) {
3248
                        // Server negotiated psk_ke; load the PSK if have one.
3249
6
                        tls_load_psk(ssl, ssl_options.psk);
3250
6
                    }
3251
                    /* Create client and server decoders for TLS 1.3.
3252
                     * Create client decoder based on HS secret only if there is
3253
                     * no early data, or if there is no decryptable early data. */
3254
865
                    if (!ssl->has_early_data ||
3255
865
                        ((ssl->state & SSL_SEEN_0RTT_APPDATA) && !ssl->client)) {
3256
865
                        tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
3257
865
                    }
3258
865
                    tls13_change_key(ssl, &ssl_master_key_map, true, TLS_SECRET_HANDSHAKE);
3259
865
                }
3260
885
                break;
3261
3262
179
            case SSL_HND_HELLO_VERIFY_REQUEST:
3263
                /* only valid for DTLS */
3264
179
                break;
3265
3266
408
            case SSL_HND_NEWSESSION_TICKET:
3267
                /* no need to load keylog file here as it only links a previous
3268
                 * master key with this Session Ticket */
3269
408
                ssl_dissect_hnd_new_ses_ticket(&dissect_ssl3_hf, tvb, pinfo,
3270
408
                        ssl_hand_tree, offset, offset + length, session, ssl, false,
3271
408
                        ssl_master_key_map.tickets);
3272
408
                break;
3273
3274
107
            case SSL_HND_END_OF_EARLY_DATA:
3275
                /* RFC 8446 Section 4.5 */
3276
107
                if (!is_from_server && ssl) {
3277
107
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3278
107
                    tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
3279
107
                    ssl->has_early_data = false;
3280
107
                }
3281
107
                break;
3282
3283
529
            case SSL_HND_HELLO_RETRY_REQUEST: /* TLS 1.3 draft -21 and before */
3284
529
                ssl_dissect_hnd_hello_retry_request(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
3285
529
                                                    offset, offset + length, session, ssl, false);
3286
529
                break;
3287
3288
110
            case SSL_HND_ENCRYPTED_EXTENSIONS:
3289
                /* XXX expert info if used with non-TLS 1.3? */
3290
110
                ssl_dissect_hnd_encrypted_extensions(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
3291
110
                                                     offset, offset + length, session, ssl, false);
3292
3293
110
                break;
3294
3295
135
            case SSL_HND_CERTIFICATE:
3296
135
                ssl_dissect_hnd_cert(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3297
135
                        offset, offset + length, pinfo, session, ssl, is_from_server, false);
3298
135
                break;
3299
3300
699
            case SSL_HND_SERVER_KEY_EXCHG:
3301
699
                if (!PINFO_FD_VISITED(pinfo)) {
3302
699
                    pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
3303
699
                    pi->cipher = session->cipher;
3304
699
                } else {
3305
0
                    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
3306
0
                    if (pi) {
3307
0
                        session->cipher = pi->cipher;
3308
0
                    }
3309
0
                }
3310
699
                ssl_dissect_hnd_srv_keyex(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session);
3311
699
                break;
3312
3313
619
            case SSL_HND_CERT_REQUEST:
3314
619
                ssl_dissect_hnd_cert_req(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session, false);
3315
619
                break;
3316
3317
39
            case SSL_HND_SVR_HELLO_DONE:
3318
                /* This is not an abbreviated handshake, it is certainly not resumed. */
3319
39
                session->is_session_resumed = false;
3320
39
                break;
3321
3322
217
            case SSL_HND_CERT_VERIFY:
3323
217
                ssl_dissect_hnd_cli_cert_verify(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session->version);
3324
217
                break;
3325
3326
3.07k
            case SSL_HND_CLIENT_KEY_EXCHG:
3327
3.07k
                if (!PINFO_FD_VISITED(pinfo)) {
3328
3.07k
                    pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
3329
3.07k
                    pi->cipher = session->cipher;
3330
3.07k
                } else {
3331
0
                    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
3332
0
                    if (pi) {
3333
0
                        session->cipher = pi->cipher;
3334
0
                    }
3335
0
                }
3336
3.07k
                ssl_dissect_hnd_cli_keyex(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset, length, session);
3337
3338
3.07k
                if (!ssl)
3339
0
                    break;
3340
3341
3.07k
                ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
3342
3.07k
                        &ssl_master_key_map);
3343
                /* try to find master key from pre-master key */
3344
3.07k
                if (!ssl_generate_pre_master_secret(ssl, length, tvb, offset,
3345
3.07k
                            ssl_options.psk, pinfo,
3346
#ifdef HAVE_LIBGNUTLS
3347
                            ssl_key_hash,
3348
#endif
3349
3.07k
                            &ssl_master_key_map)) {
3350
2.93k
                    ssl_debug_printf("dissect_ssl3_handshake can't generate pre master secret\n");
3351
2.93k
                }
3352
3.07k
                break;
3353
3354
93
            case SSL_HND_FINISHED:
3355
93
                ssl_dissect_hnd_finished(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3356
93
                        offset, offset + length, session, &ssl_hfs);
3357
93
                if (ssl) {
3358
92
                    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3359
92
                    tls13_change_key(ssl, &ssl_master_key_map, is_from_server, TLS_SECRET_APP);
3360
92
                }
3361
93
                break;
3362
3363
32
            case SSL_HND_CERT_URL:
3364
32
                ssl_dissect_hnd_cert_url(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset);
3365
32
                break;
3366
3367
159
            case SSL_HND_CERT_STATUS:
3368
159
                tls_dissect_hnd_certificate_status(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length);
3369
159
                break;
3370
3371
0
            case SSL_HND_SUPPLEMENTAL_DATA:
3372
                /* TODO: dissect this? */
3373
0
                break;
3374
3375
104
            case SSL_HND_KEY_UPDATE:
3376
104
                tls13_dissect_hnd_key_update(&dissect_ssl3_hf, tvb, tree, offset);
3377
104
                if (ssl) {
3378
104
                    tls13_key_update(ssl, is_from_server);
3379
104
                }
3380
104
                break;
3381
3382
133
            case SSL_HND_COMPRESSED_CERTIFICATE:
3383
133
                ssl_dissect_hnd_compress_certificate(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3384
133
                                                     offset, offset + length, pinfo, session,
3385
133
                                                     ssl, is_from_server, false);
3386
133
                break;
3387
3388
305
            case SSL_HND_ENCRYPTED_EXTS:
3389
305
                dissect_ssl3_hnd_encrypted_exts(tvb, ssl_hand_tree, offset);
3390
305
                break;
3391
0
            case SSL_HND_MESSAGE_HASH:
3392
0
                break;
3393
12.9k
        }
3394
12.9k
    }
3395
12.9k
}
3396
3397
/* dissects the heartbeat message, filling in the tree */
3398
static void
3399
dissect_ssl3_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
3400
                       proto_tree *tree, uint32_t offset,
3401
                       const SslSession *session, uint32_t record_length,
3402
                       bool decrypted)
3403
83
{
3404
    /*     struct {
3405
     *         HeartbeatMessageType type;
3406
     *         uint16 payload_length;
3407
     *         opaque payload;
3408
     *         opaque padding;
3409
     *     } HeartbeatMessage;
3410
     */
3411
3412
83
    proto_item  *ti;
3413
83
    proto_tree  *tls_heartbeat_tree;
3414
83
    const char *type;
3415
83
    uint8_t      byte;
3416
83
    uint16_t     payload_length;
3417
83
    uint16_t     padding_length;
3418
3419
83
    tls_heartbeat_tree = NULL;
3420
3421
83
    if (tree) {
3422
83
        ti = proto_tree_add_item(tree, hf_tls_heartbeat_message, tvb,
3423
83
                                 offset, record_length, ENC_NA);
3424
83
        tls_heartbeat_tree = proto_item_add_subtree(ti, ett_tls_heartbeat);
3425
83
    }
3426
3427
    /*
3428
     * set the record layer label
3429
     */
3430
3431
    /* first lookup the names for the message type and the payload length */
3432
83
    byte = tvb_get_uint8(tvb, offset);
3433
83
    type = try_val_to_str(byte, tls_heartbeat_type);
3434
3435
83
    payload_length = tvb_get_ntohs(tvb, offset + 1);
3436
83
    padding_length = record_length - 3 - payload_length;
3437
3438
    /* assume plaintext if the (expected) record size is smaller than the type
3439
     * (1), length (2)[, payload] and padding (16) fields combined */
3440
83
    if (record_length <= 19u || 3u + payload_length + 16 <= record_length) {
3441
50
        decrypted = true;
3442
50
    }
3443
3444
    /* now set the text in the record layer line */
3445
83
    if (type && decrypted) {
3446
29
        col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "Heartbeat %s", type);
3447
54
    } else {
3448
54
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Heartbeat");
3449
54
    }
3450
3451
83
    if (type && decrypted) {
3452
29
        proto_item_set_text(tree, "%s Record Layer: Heartbeat "
3453
29
                            "%s",
3454
29
                            val_to_str_const(session->version, ssl_version_short_names, "SSL"),
3455
29
                            type);
3456
29
        proto_tree_add_item(tls_heartbeat_tree, hf_tls_heartbeat_message_type,
3457
29
                            tvb, offset, 1, ENC_BIG_ENDIAN);
3458
29
        offset += 1;
3459
29
        ti = proto_tree_add_uint(tls_heartbeat_tree, hf_tls_heartbeat_message_payload_length,
3460
29
                                 tvb, offset, 2, payload_length);
3461
29
        offset += 2;
3462
29
        if (3u + payload_length + 16 > record_length) {
3463
19
            expert_add_info_format(pinfo, ti, &ei_ssl3_heartbeat_payload_length,
3464
19
                                   "Invalid heartbeat payload length (%d)", payload_length);
3465
            /* There is no room for padding... truncate the payload such that
3466
             * the field can be selected (for the interested). */
3467
19
            payload_length = record_length - 3;
3468
19
            padding_length = 0;
3469
19
            proto_item_append_text (ti, " (invalid, using %u to decode payload)", payload_length);
3470
19
        }
3471
29
        proto_tree_add_bytes_format(tls_heartbeat_tree, hf_tls_heartbeat_message_payload,
3472
29
                                    tvb, offset, payload_length,
3473
29
                                    NULL, "Payload (%u byte%s)",
3474
29
                                    payload_length,
3475
29
                                    plurality(payload_length, "", "s"));
3476
29
        offset += payload_length;
3477
29
        if (padding_length)
3478
7
            proto_tree_add_bytes_format(tls_heartbeat_tree, hf_tls_heartbeat_message_padding,
3479
7
                                        tvb, offset, padding_length,
3480
7
                                        NULL, "Padding and HMAC (%u byte%s)",
3481
7
                                        padding_length,
3482
7
                                        plurality(padding_length, "", "s"));
3483
54
    } else {
3484
54
        proto_item_set_text(tree,
3485
54
                            "%s Record Layer: Encrypted Heartbeat",
3486
54
                            val_to_str_const(session->version, ssl_version_short_names, "SSL"));
3487
54
        proto_item_set_text(tls_heartbeat_tree,
3488
54
                            "Encrypted Heartbeat Message");
3489
54
    }
3490
83
}
3491
3492
/* based on https://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04 */
3493
static void
3494
dissect_ssl3_hnd_encrypted_exts(tvbuff_t *tvb, proto_tree *tree,
3495
                                uint32_t offset)
3496
305
{
3497
305
    uint8_t      selected_protocol_len;
3498
305
    uint8_t      padding_len;
3499
3500
305
    selected_protocol_len = tvb_get_uint8(tvb, offset);
3501
305
    proto_tree_add_item(tree, hf_tls_handshake_npn_selected_protocol_len,
3502
305
        tvb, offset, 1, ENC_BIG_ENDIAN);
3503
305
    offset++;
3504
305
    proto_tree_add_item(tree, hf_tls_handshake_npn_selected_protocol,
3505
305
        tvb, offset, selected_protocol_len, ENC_ASCII);
3506
305
    offset += selected_protocol_len;
3507
3508
305
    padding_len = tvb_get_uint8(tvb, offset);
3509
305
    proto_tree_add_item(tree, hf_tls_handshake_npn_padding_len,
3510
305
        tvb, offset, 1, ENC_BIG_ENDIAN);
3511
305
    offset++;
3512
305
    proto_tree_add_item(tree, hf_tls_handshake_npn_padding,
3513
305
        tvb, offset, padding_len, ENC_NA);
3514
305
}
3515
3516
/*********************************************************************
3517
 *
3518
 * SSL version 2 Dissectors
3519
 *
3520
 *********************************************************************/
3521
3522
3523
/* record layer dissector */
3524
static int
3525
dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
3526
                    uint32_t offset, SslSession *session,
3527
                    bool *need_desegmentation,
3528
                    SslDecryptSession *ssl)
3529
358
{
3530
358
    uint32_t     initial_offset;
3531
358
    uint8_t      byte;
3532
358
    uint8_t      record_length_length;
3533
358
    uint32_t     record_length;
3534
358
    int          is_escape;
3535
358
    int16_t      padding_length;
3536
358
    uint8_t      msg_type;
3537
358
    const char *msg_type_str;
3538
358
    uint32_t     available_bytes;
3539
358
    proto_item  *ti;
3540
358
    proto_tree  *ssl_record_tree;
3541
3542
358
    initial_offset  = offset;
3543
358
    record_length   = 0;
3544
358
    is_escape       = -1;
3545
358
    padding_length  = -1;
3546
358
    msg_type_str    = NULL;
3547
358
    ssl_record_tree = NULL;
3548
3549
    /* pull first byte; if high bit is unset, then record
3550
     * length is three bytes due to padding; otherwise
3551
     * record length is two bytes
3552
     */
3553
358
    byte = tvb_get_uint8(tvb, offset);
3554
358
    record_length_length = (byte & 0x80) ? 2 : 3;
3555
3556
358
    available_bytes = tvb_reported_length_remaining(tvb, offset);
3557
3558
    /*
3559
     * Is the record header split across segment boundaries?
3560
     */
3561
358
    if (available_bytes < record_length_length) {
3562
        /*
3563
         * Yes - can we do reassembly?
3564
         */
3565
0
        ssl_proto_tree_add_segment_data(tree, tvb, offset, available_bytes, NULL);
3566
0
        if (tls_desegment && pinfo->can_desegment) {
3567
            /*
3568
             * Yes.  Tell the TCP dissector where the data for this
3569
             * message starts in the data it handed us, and that we need
3570
             * "some more data."  Don't tell it exactly how many bytes we
3571
             * need because if/when we ask for even more (after the header)
3572
             * that will break reassembly.
3573
             */
3574
0
            pinfo->desegment_offset = offset;
3575
0
            pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
3576
0
            *need_desegmentation = true;
3577
0
            return offset;
3578
0
        } else {
3579
            /* Not enough bytes available. Stop here. */
3580
0
            return offset + available_bytes;
3581
0
        }
3582
0
    }
3583
3584
    /* parse out the record length */
3585
358
    switch (record_length_length) {
3586
324
    case 2:                     /* two-byte record length */
3587
324
        record_length = (byte & 0x7f) << 8;
3588
324
        byte = tvb_get_uint8(tvb, offset + 1);
3589
324
        record_length += byte;
3590
324
        break;
3591
34
    case 3:                     /* three-byte record length */
3592
34
        is_escape = (byte & 0x40) ? true : false;
3593
34
        record_length = (byte & 0x3f) << 8;
3594
34
        byte = tvb_get_uint8(tvb, offset + 1);
3595
34
        record_length += byte;
3596
34
        byte = tvb_get_uint8(tvb, offset + 2);
3597
34
        padding_length = byte;
3598
358
    }
3599
3600
    /*
3601
     * Is the record split across segment boundaries?
3602
     */
3603
358
    if (available_bytes < (record_length_length + record_length)) {
3604
        /*
3605
         * Yes - Can we do reassembly?
3606
         */
3607
130
        ssl_proto_tree_add_segment_data(tree, tvb, offset, available_bytes, NULL);
3608
130
        if (tls_desegment && pinfo->can_desegment) {
3609
            /*
3610
             * Yes.  Tell the TCP dissector where the data for this
3611
             * message starts in the data it handed us, and how many
3612
             * more bytes we need, and return.
3613
             */
3614
0
            pinfo->desegment_offset = offset;
3615
0
            pinfo->desegment_len = (record_length_length + record_length)
3616
0
                                   - available_bytes;
3617
0
            *need_desegmentation = true;
3618
0
            return offset;
3619
130
        } else {
3620
            /* Not enough bytes available. Stop here. */
3621
130
            return offset + available_bytes;
3622
130
        }
3623
130
    }
3624
228
    offset += record_length_length;
3625
3626
    /* add the record layer subtree header */
3627
228
    ti = proto_tree_add_item(tree, hf_ssl2_record, tvb, initial_offset,
3628
228
                             record_length_length + record_length, ENC_NA);
3629
228
    ssl_record_tree = proto_item_add_subtree(ti, ett_tls_record);
3630
3631
    /* pull the msg_type so we can bail if it's unknown */
3632
228
    msg_type = tvb_get_uint8(tvb, initial_offset + record_length_length);
3633
3634
    /* if we get a server_hello or later handshake in v2, then set
3635
     * this to sslv2
3636
     */
3637
228
    if (session->version == SSL_VER_UNKNOWN)
3638
1
    {
3639
1
        if (msg_type >= 2 && msg_type <= 8)
3640
1
        {
3641
1
            session->version = SSLV2_VERSION;
3642
1
        }
3643
1
    }
3644
3645
    /* if we get here, but don't have a version set for the
3646
     * conversation, then set a version for just this frame
3647
     * (e.g., on a client hello)
3648
     */
3649
228
    col_set_str(pinfo->cinfo, COL_PROTOCOL, "SSLv2");
3650
3651
    /* see if the msg_type is valid; if not the payload is
3652
     * probably encrypted, so note that fact and bail
3653
     */
3654
228
    msg_type_str = try_val_to_str(msg_type, ssl_20_msg_types);
3655
228
    if (!msg_type_str
3656
224
        || (!ssl_looks_like_valid_v2_handshake(tvb, initial_offset
3657
224
                               + record_length_length,
3658
224
                               record_length)))
3659
106
    {
3660
106
        if (ssl_record_tree)
3661
106
        {
3662
106
            proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
3663
106
                                "SSLv2",
3664
106
                                "Encrypted Data");
3665
3666
            /* Unlike SSLv3, the SSLv2 record layer does not have a
3667
             * version field. To make it possible to filter on record
3668
             * layer version we create a generated field with ssl
3669
             * record layer version 0x0002
3670
             */
3671
106
            ti = proto_tree_add_uint(ssl_record_tree,
3672
106
                    hf_tls_record_version, tvb,
3673
106
                    initial_offset, 0, 0x0002);
3674
106
            proto_item_set_generated(ti);
3675
106
        }
3676
3677
106
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Data");
3678
106
        return initial_offset + record_length_length + record_length;
3679
106
    }
3680
122
    else
3681
122
    {
3682
122
        col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);
3683
3684
122
        if (ssl_record_tree)
3685
122
        {
3686
122
            proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
3687
122
                                "SSLv2",
3688
122
                                msg_type_str);
3689
122
        }
3690
122
    }
3691
3692
    /* We have a valid message type, so move forward, filling in the
3693
     * tree by adding the length, is_escape boolean and padding_length,
3694
     * if present in the original packet
3695
     */
3696
122
    if (ssl_record_tree)
3697
122
    {
3698
        /* Unlike SSLv3, the SSLv2 record layer does not have a
3699
         * version field. To make it possible to filter on record
3700
         * layer version we create a generated field with ssl
3701
         * record layer version 0x0002
3702
         */
3703
122
        ti = proto_tree_add_uint(ssl_record_tree,
3704
122
                                 hf_tls_record_version, tvb,
3705
122
                                 initial_offset, 0, 0x0002);
3706
122
        proto_item_set_generated(ti);
3707
3708
        /* add the record length */
3709
122
        tvb_ensure_bytes_exist(tvb, offset, record_length_length);
3710
122
        proto_tree_add_uint (ssl_record_tree,
3711
122
                             hf_tls_record_length, tvb,
3712
122
                             initial_offset, record_length_length,
3713
122
                             record_length);
3714
122
    }
3715
122
    if (ssl_record_tree && is_escape != -1)
3716
0
    {
3717
0
        proto_tree_add_boolean(ssl_record_tree,
3718
0
                               hf_ssl2_record_is_escape, tvb,
3719
0
                               initial_offset, 1, is_escape);
3720
0
    }
3721
122
    if (ssl_record_tree && padding_length != -1)
3722
0
    {
3723
0
        proto_tree_add_uint(ssl_record_tree,
3724
0
                            hf_ssl2_record_padding_length, tvb,
3725
0
                            initial_offset + 2, 1, padding_length);
3726
0
    }
3727
3728
    /*
3729
     * dissect the record data
3730
     */
3731
3732
    /* jump forward to the start of the record data */
3733
122
    offset = initial_offset + record_length_length;
3734
3735
    /* add the message type */
3736
122
    if (ssl_record_tree)
3737
122
    {
3738
122
        proto_tree_add_item(ssl_record_tree, hf_ssl2_msg_type,
3739
122
                            tvb, offset, 1, ENC_BIG_ENDIAN);
3740
122
    }
3741
122
    offset += 1;                   /* move past msg_type byte */
3742
3743
122
    {
3744
        /* dissect the message (only handle client hello right now) */
3745
122
        switch (msg_type) {
3746
116
        case SSL2_HND_CLIENT_HELLO:
3747
116
            dissect_ssl2_hnd_client_hello(tvb, pinfo, ssl_record_tree, offset, ssl);
3748
116
            break;
3749
3750
6
        case SSL2_HND_CLIENT_MASTER_KEY:
3751
6
            dissect_ssl2_hnd_client_master_key(tvb, ssl_record_tree, offset);
3752
6
            break;
3753
3754
0
        case SSL2_HND_SERVER_HELLO:
3755
0
            dissect_ssl2_hnd_server_hello(tvb, ssl_record_tree, offset, pinfo);
3756
0
            break;
3757
3758
0
        case SSL2_HND_ERROR:
3759
0
        case SSL2_HND_CLIENT_FINISHED:
3760
0
        case SSL2_HND_SERVER_VERIFY:
3761
0
        case SSL2_HND_SERVER_FINISHED:
3762
0
        case SSL2_HND_REQUEST_CERTIFICATE:
3763
0
        case SSL2_HND_CLIENT_CERTIFICATE:
3764
            /* unimplemented */
3765
0
            break;
3766
3767
0
        default:                    /* unknown */
3768
0
            break;
3769
122
        }
3770
122
    }
3771
114
    return (initial_offset + record_length_length + record_length);
3772
122
}
3773
3774
static void
3775
dissect_ssl2_hnd_client_hello(tvbuff_t *tvb, packet_info *pinfo,
3776
                              proto_tree *tree, uint32_t offset,
3777
                              SslDecryptSession *ssl)
3778
116
{
3779
    /* struct {
3780
     *    uint8 msg_type;
3781
     *     Version version;
3782
     *     uint16 cipher_spec_length;
3783
     *     uint16 session_id_length;
3784
     *     uint16 challenge_length;
3785
     *     V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
3786
     *     opaque session_id[V2ClientHello.session_id_length];
3787
     *     Random challenge;
3788
     * } V2ClientHello;
3789
     *
3790
     * Note: when we get here, offset's already pointing at Version
3791
     *
3792
     */
3793
116
    uint16_t version;
3794
116
    uint16_t cipher_spec_length;
3795
116
    uint16_t session_id_length;
3796
116
    uint16_t challenge_length;
3797
3798
116
    proto_item *ti;
3799
116
    proto_tree *cs_tree;
3800
116
    cs_tree=0;
3801
3802
116
    version = tvb_get_ntohs(tvb, offset);
3803
116
    if (!ssl_is_valid_ssl_version(version))
3804
0
    {
3805
        /* invalid version; probably encrypted data */
3806
0
        return;
3807
0
    }
3808
3809
116
    if (ssl) {
3810
116
      ssl_set_server(&ssl->session, PINFO_DST(pinfo), pinfo->ptype, PINFO_DESTPORT(pinfo));
3811
116
    }
3812
3813
    /* show the version */
3814
116
    proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_client_version, tvb,
3815
116
                        offset, 2, ENC_BIG_ENDIAN);
3816
116
    offset += 2;
3817
3818
116
    cipher_spec_length = tvb_get_ntohs(tvb, offset);
3819
116
    proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec_len,
3820
116
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3821
116
    offset += 2;
3822
3823
116
    session_id_length = tvb_get_ntohs(tvb, offset);
3824
116
    ti = proto_tree_add_item(tree, hf_ssl2_handshake_session_id_len,
3825
116
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3826
116
    if (session_id_length > SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES) {
3827
28
        expert_add_info_format(pinfo, ti, &ei_ssl2_handshake_session_id_len_error,
3828
28
                               "Session ID length (%u) must be less than %u.",
3829
28
                               session_id_length, SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES);
3830
28
        return;
3831
28
    }
3832
88
    offset += 2;
3833
3834
88
    challenge_length = tvb_get_ntohs(tvb, offset);
3835
88
    if (tree)
3836
88
        proto_tree_add_item(tree, hf_ssl2_handshake_challenge_len,
3837
88
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3838
88
    offset += 2;
3839
3840
88
    if (tree)
3841
88
    {
3842
        /* tell the user how many cipher specs they've won */
3843
88
        ti = proto_tree_add_none_format(tree, dissect_ssl3_hf.hf.hs_cipher_suites,
3844
88
                                        tvb, offset, cipher_spec_length,
3845
88
                                        "Cipher Specs (%u specs)",
3846
88
                                        cipher_spec_length/3);
3847
3848
        /* make this a subtree and expand the actual specs below */
3849
88
        cs_tree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
3850
88
        if (!cs_tree)
3851
0
        {
3852
0
            cs_tree = tree;     /* failsafe */
3853
0
        }
3854
88
    }
3855
3856
    /* iterate through the cipher specs, showing them */
3857
269
    while (cipher_spec_length > 0)
3858
181
    {
3859
181
        if (cs_tree)
3860
181
            proto_tree_add_item(cs_tree, hf_ssl2_handshake_cipher_spec,
3861
181
                            tvb, offset, 3, ENC_BIG_ENDIAN);
3862
181
        offset += 3;        /* length of one cipher spec */
3863
181
        cipher_spec_length -= 3;
3864
181
    }
3865
3866
    /* if there's a session id, show it */
3867
88
    if (session_id_length > 0)
3868
18
    {
3869
18
        proto_tree_add_bytes_format(tree,
3870
18
                                        dissect_ssl3_hf.hf.hs_session_id,
3871
18
                                        tvb, offset, session_id_length,
3872
18
                                        NULL, "Session ID (%u byte%s)",
3873
18
                                        session_id_length,
3874
18
                                        plurality(session_id_length, "", "s"));
3875
3876
        /* PAOLO: get session id and reset session state for key [re]negotiation */
3877
18
        if (ssl)
3878
18
        {
3879
18
            tvb_memcpy(tvb,ssl->session_id.data, offset, session_id_length);
3880
18
            ssl->session_id.data_len = session_id_length;
3881
18
            ssl->state &= ~(SSL_HAVE_SESSION_KEY|SSL_MASTER_SECRET|SSL_PRE_MASTER_SECRET|
3882
18
                    SSL_CIPHER|SSL_SERVER_RANDOM);
3883
18
        }
3884
18
        offset += session_id_length;
3885
18
    }
3886
3887
    /* if there's a challenge, show it */
3888
88
    if (challenge_length > 0)
3889
36
    {
3890
36
        proto_tree_add_item(tree, hf_ssl2_handshake_challenge,
3891
36
                            tvb, offset, challenge_length, ENC_NA);
3892
36
        if (ssl)
3893
36
        {
3894
            /* PAOLO: get client random data; we get at most 32 bytes from
3895
             challenge */
3896
36
            int max;
3897
36
            max = challenge_length > 32? 32: challenge_length;
3898
3899
36
            ssl_debug_printf("client random len: %d padded to 32\n", challenge_length);
3900
3901
            /* client random is padded with zero and 'right' aligned */
3902
36
            memset(ssl->client_random.data, 0, 32 - max);
3903
36
            tvb_memcpy(tvb, &ssl->client_random.data[32 - max], offset, max);
3904
36
            ssl->client_random.data_len = 32;
3905
36
            ssl->state |= SSL_CLIENT_RANDOM;
3906
36
            ssl_debug_printf("dissect_ssl2_hnd_client_hello found CLIENT RANDOM -> state 0x%02X\n", ssl->state);
3907
36
        }
3908
36
    }
3909
88
}
3910
3911
static void
3912
dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
3913
                                   proto_tree *tree, uint32_t offset)
3914
6
{
3915
    /* struct {
3916
     *    uint8 msg_type;
3917
     *    V2Cipherspec cipher;
3918
     *    uint16 clear_key_length;
3919
     *    uint16 encrypted_key_length;
3920
     *    uint16 key_arg_length;
3921
     *    opaque clear_key_data[V2ClientMasterKey.clear_key_length];
3922
     *    opaque encrypted_key_data[V2ClientMasterKey.encrypted_key_length];
3923
     *    opaque key_arg_data[V2ClientMasterKey.key_arg_length];
3924
     * } V2ClientMasterKey;
3925
     *
3926
     * Note: when we get here, offset's already pointing at cipher
3927
     */
3928
6
    uint16_t clear_key_length;
3929
6
    uint16_t encrypted_key_length;
3930
6
    uint16_t key_arg_length;
3931
3932
    /* at this point, everything we do involves the tree,
3933
     * so quit now if we don't have one ;-)
3934
     */
3935
6
    if (!tree)
3936
0
    {
3937
0
        return;
3938
0
    }
3939
3940
    /* show the selected cipher */
3941
6
    proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec,
3942
6
                        tvb, offset, 3, ENC_BIG_ENDIAN);
3943
6
    offset += 3;
3944
3945
    /* get the fixed fields */
3946
6
    clear_key_length = tvb_get_ntohs(tvb, offset);
3947
6
    proto_tree_add_item(tree, hf_ssl2_handshake_clear_key_len,
3948
6
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3949
6
    offset += 2;
3950
3951
6
    encrypted_key_length = tvb_get_ntohs(tvb, offset);
3952
6
    proto_tree_add_item(tree, hf_ssl2_handshake_enc_key_len,
3953
6
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3954
6
    offset += 2;
3955
3956
6
    key_arg_length = tvb_get_ntohs(tvb, offset);
3957
6
    proto_tree_add_item(tree, hf_ssl2_handshake_key_arg_len,
3958
6
                        tvb, offset, 2, ENC_BIG_ENDIAN);
3959
6
    offset += 2;
3960
3961
    /* show the variable length fields */
3962
6
    if (clear_key_length > 0)
3963
5
    {
3964
5
        proto_tree_add_item(tree, hf_ssl2_handshake_clear_key,
3965
5
                            tvb, offset, clear_key_length, ENC_NA);
3966
5
        offset += clear_key_length;
3967
5
    }
3968
3969
6
    if (encrypted_key_length > 0)
3970
4
    {
3971
4
        proto_tree_add_item(tree, hf_ssl2_handshake_enc_key,
3972
4
                            tvb, offset, encrypted_key_length, ENC_NA);
3973
4
        offset += encrypted_key_length;
3974
4
    }
3975
3976
6
    if (key_arg_length > 0)
3977
3
    {
3978
3
        proto_tree_add_item(tree, hf_ssl2_handshake_key_arg,
3979
3
                            tvb, offset, key_arg_length, ENC_NA);
3980
3
    }
3981
3982
6
}
3983
3984
static void
3985
dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
3986
                              proto_tree *tree, uint32_t offset, packet_info *pinfo)
3987
0
{
3988
    /* struct {
3989
     *    uint8  msg_type;
3990
     *    uint8  session_id_hit;
3991
     *    uint8  certificate_type;
3992
     *    uint16 server_version;
3993
     *    uint16 certificate_length;
3994
     *    uint16 cipher_specs_length;
3995
     *    uint16 connection_id_length;
3996
     *    opaque certificate_data[V2ServerHello.certificate_length];
3997
     *    opaque cipher_specs_data[V2ServerHello.cipher_specs_length];
3998
     *    opaque connection_id_data[V2ServerHello.connection_id_length];
3999
     * } V2ServerHello;
4000
     *
4001
     * Note: when we get here, offset's already pointing at session_id_hit
4002
     */
4003
0
    uint16_t    certificate_length;
4004
0
    uint16_t    cipher_spec_length;
4005
0
    uint16_t    connection_id_length;
4006
0
    uint16_t    version;
4007
0
    proto_item *ti;
4008
0
    proto_tree *subtree;
4009
0
    asn1_ctx_t  asn1_ctx;
4010
4011
0
    asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, true, pinfo);
4012
4013
    /* everything we do only makes sense with a tree, so
4014
     * quit now if we don't have one
4015
     */
4016
0
    if (!tree)
4017
0
    {
4018
0
        return;
4019
0
    }
4020
4021
0
    version = tvb_get_ntohs(tvb, offset + 2);
4022
0
    if (!ssl_is_valid_ssl_version(version))
4023
0
    {
4024
        /* invalid version; probably encrypted data */
4025
0
        return;
4026
0
    }
4027
4028
4029
    /* is there a hit? */
4030
0
    proto_tree_add_item(tree, hf_ssl2_handshake_session_id_hit,
4031
0
                        tvb, offset, 1, ENC_BIG_ENDIAN);
4032
0
    offset += 1;
4033
4034
    /* what type of certificate is this? */
4035
0
    proto_tree_add_item(tree, hf_ssl2_handshake_cert_type,
4036
0
                        tvb, offset, 1, ENC_BIG_ENDIAN);
4037
0
    offset += 1;
4038
4039
    /* now the server version */
4040
0
    proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_server_version,
4041
0
                        tvb, offset, 2, ENC_BIG_ENDIAN);
4042
0
    offset += 2;
4043
4044
    /* get the fixed fields */
4045
0
    certificate_length = tvb_get_ntohs(tvb, offset);
4046
0
    proto_tree_add_uint(tree, dissect_ssl3_hf.hf.hs_certificate_len,
4047
0
                        tvb, offset, 2, certificate_length);
4048
0
    offset += 2;
4049
4050
0
    cipher_spec_length = tvb_get_ntohs(tvb, offset);
4051
0
    proto_tree_add_uint(tree, hf_ssl2_handshake_cipher_spec_len,
4052
0
                        tvb, offset, 2, cipher_spec_length);
4053
0
    offset += 2;
4054
4055
0
    connection_id_length = tvb_get_ntohs(tvb, offset);
4056
0
    proto_tree_add_uint(tree, hf_ssl2_handshake_connection_id_len,
4057
0
                        tvb, offset, 2, connection_id_length);
4058
0
    offset += 2;
4059
4060
    /* now the variable length fields */
4061
0
    if (certificate_length > 0)
4062
0
    {
4063
0
        (void)dissect_x509af_Certificate(false, tvb, offset, &asn1_ctx, tree, dissect_ssl3_hf.hf.hs_certificate);
4064
0
        offset += certificate_length;
4065
0
    }
4066
4067
0
    if (cipher_spec_length > 0)
4068
0
    {
4069
        /* provide a collapsing node for the cipher specs */
4070
0
        ti = proto_tree_add_none_format(tree,
4071
0
                                        dissect_ssl3_hf.hf.hs_cipher_suites,
4072
0
                                        tvb, offset, cipher_spec_length,
4073
0
                                        "Cipher Specs (%u spec%s)",
4074
0
                                        cipher_spec_length/3,
4075
0
                                        plurality(cipher_spec_length/3, "", "s"));
4076
0
        subtree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
4077
0
        if (!subtree)
4078
0
        {
4079
0
            subtree = tree;
4080
0
        }
4081
4082
        /* iterate through the cipher specs */
4083
0
        while (cipher_spec_length > 0)
4084
0
        {
4085
0
            proto_tree_add_item(subtree, hf_ssl2_handshake_cipher_spec,
4086
0
                                tvb, offset, 3, ENC_BIG_ENDIAN);
4087
0
            offset += 3;
4088
0
            cipher_spec_length -= 3;
4089
0
        }
4090
0
    }
4091
4092
0
    if (connection_id_length > 0)
4093
0
    {
4094
0
        proto_tree_add_item(tree, hf_ssl2_handshake_connection_id,
4095
0
                            tvb, offset, connection_id_length, ENC_NA);
4096
0
    }
4097
4098
0
}
4099
4100
4101
void ssl_set_master_secret(uint32_t frame_num, address *addr_srv, address *addr_cli,
4102
                           port_type ptype, uint32_t port_srv, uint32_t port_cli,
4103
                           uint32_t version, int cipher, const unsigned char *_master_secret,
4104
                           const unsigned char *_client_random, const unsigned char *_server_random,
4105
                           uint32_t client_seq, uint32_t server_seq)
4106
0
{
4107
0
    conversation_t    *conversation;
4108
0
    SslDecryptSession *ssl;
4109
0
    unsigned           iv_len;
4110
4111
0
    ssl_debug_printf("\nssl_set_master_secret enter frame #%u\n", frame_num);
4112
4113
0
    conversation = find_conversation(frame_num, addr_srv, addr_cli, conversation_pt_to_conversation_type(ptype), port_srv, port_cli, 0);
4114
4115
0
    if (!conversation) {
4116
        /* create a new conversation */
4117
0
        conversation = conversation_new(frame_num, addr_srv, addr_cli, conversation_pt_to_conversation_type(ptype), port_srv, port_cli, 0);
4118
0
        ssl_debug_printf("  new conversation = %p created\n", (void *)conversation);
4119
0
    }
4120
    /* XXX - This need to be updated to handle tunneling. This API call was
4121
     * only ever used by external dissectors and plugins. For now just support
4122
     * the outer TLS layer. */
4123
0
    ssl = ssl_get_session(conversation, tls_handle, 0);
4124
4125
0
    ssl_debug_printf("  conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl);
4126
4127
0
    ssl_set_server(&ssl->session, addr_srv, ptype, port_srv);
4128
4129
    /* version */
4130
0
    if ((ssl->session.version==SSL_VER_UNKNOWN) && (version!=SSL_VER_UNKNOWN)) {
4131
0
        switch (version) {
4132
0
        case SSLV3_VERSION:
4133
0
        case TLSV1_VERSION:
4134
0
        case TLSV1DOT1_VERSION:
4135
0
        case TLSV1DOT2_VERSION:
4136
0
        case TLCPV1_VERSION:
4137
0
            ssl->session.version = version;
4138
0
            ssl->state |= SSL_VERSION;
4139
0
            ssl_debug_printf("%s set version 0x%04X -> state 0x%02X\n", G_STRFUNC, ssl->session.version, ssl->state);
4140
0
            break;
4141
0
        default:
4142
            /* API change: version number is no longer an internal value
4143
             * (SSL_VER_*) but the ProtocolVersion from wire (*_VERSION) */
4144
0
            ssl_debug_printf("%s WARNING must pass ProtocolVersion, not 0x%04x!\n", G_STRFUNC, version);
4145
0
            break;
4146
0
        }
4147
0
    }
4148
4149
    /* cipher */
4150
0
    if (cipher > 0) {
4151
0
        ssl->session.cipher = cipher;
4152
0
        if (!(ssl->cipher_suite = ssl_find_cipher(ssl->session.cipher))) {
4153
0
            ssl->state &= ~SSL_CIPHER;
4154
0
            ssl_debug_printf("ssl_set_master_secret can't find cipher suite 0x%X\n", ssl->session.cipher);
4155
0
        } else {
4156
0
            ssl->state |= SSL_CIPHER;
4157
0
            ssl_debug_printf("ssl_set_master_secret set CIPHER 0x%04X -> state 0x%02X\n", ssl->session.cipher, ssl->state);
4158
0
        }
4159
0
    }
4160
4161
    /* client random */
4162
0
    if (_client_random) {
4163
0
        ssl_data_set(&ssl->client_random, _client_random, 32);
4164
0
        ssl->state |= SSL_CLIENT_RANDOM;
4165
0
        ssl_debug_printf("ssl_set_master_secret set CLIENT RANDOM -> state 0x%02X\n", ssl->state);
4166
0
    }
4167
4168
    /* server random */
4169
0
    if (_server_random) {
4170
0
        ssl_data_set(&ssl->server_random, _server_random, 32);
4171
0
        ssl->state |= SSL_SERVER_RANDOM;
4172
0
        ssl_debug_printf("ssl_set_master_secret set SERVER RANDOM -> state 0x%02X\n", ssl->state);
4173
0
    }
4174
4175
    /* master secret */
4176
0
    if (_master_secret) {
4177
0
        ssl_data_set(&ssl->master_secret, _master_secret, 48);
4178
0
        ssl->state |= SSL_MASTER_SECRET;
4179
0
        ssl_debug_printf("ssl_set_master_secret set MASTER SECRET -> state 0x%02X\n", ssl->state);
4180
0
    }
4181
4182
0
    ssl_debug_printf("ssl_set_master_secret trying to generate keys\n");
4183
0
    if (ssl_generate_keyring_material(ssl)<0) {
4184
0
        ssl_debug_printf("ssl_set_master_secret can't generate keyring material\n");
4185
0
        return;
4186
0
    }
4187
4188
    /* change ciphers immediately */
4189
0
    ssl_change_cipher(ssl, true);
4190
0
    ssl_change_cipher(ssl, false);
4191
4192
    /* update seq numbers if available */
4193
    /* TODO change API to accept 64-bit sequence numbers. */
4194
0
    if (ssl->client && (client_seq != (uint32_t)-1)) {
4195
0
        ssl->client->seq = client_seq;
4196
0
        ssl_debug_printf("ssl_set_master_secret client->seq updated to %" PRIu64 "\n", ssl->client->seq);
4197
0
    }
4198
0
    if (ssl->server && (server_seq != (uint32_t)-1)) {
4199
0
        ssl->server->seq = server_seq;
4200
0
        ssl_debug_printf("ssl_set_master_secret server->seq updated to %" PRIu64 "\n", ssl->server->seq);
4201
0
    }
4202
4203
    /* update IV from last data */
4204
0
    iv_len = ssl_get_cipher_blocksize(ssl->cipher_suite);
4205
0
    if (ssl->client && ((ssl->client->seq > 0) || (ssl->client_data_for_iv.data_len > iv_len))) {
4206
0
        ssl_cipher_setiv(&ssl->client->evp, ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
4207
0
        ssl_print_data("ssl_set_master_secret client IV updated",ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
4208
0
    }
4209
0
    if (ssl->server && ((ssl->server->seq > 0) || (ssl->server_data_for_iv.data_len > iv_len))) {
4210
0
        ssl_cipher_setiv(&ssl->server->evp, ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
4211
0
        ssl_print_data("ssl_set_master_secret server IV updated",ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
4212
0
    }
4213
0
}
4214
4215
4216
/*********************************************************************
4217
 *
4218
 * Support Functions
4219
 *
4220
 *********************************************************************/
4221
static int
4222
ssl_is_valid_ssl_version(const uint16_t version)
4223
370
{
4224
370
    const char *version_str;
4225
4226
370
    version_str = try_val_to_str(version, ssl_versions);
4227
370
    return version_str != NULL;
4228
370
}
4229
4230
static int
4231
ssl_is_v2_client_hello(tvbuff_t *tvb, const uint32_t offset)
4232
4.61k
{
4233
4.61k
    uint8_t byte;
4234
4235
4.61k
    byte = tvb_get_uint8(tvb, offset);
4236
4.61k
    if (byte != 0x80)           /* v2 client hello should start this way */
4237
4.47k
    {
4238
4.47k
        return 0;
4239
4.47k
    }
4240
4241
143
    byte = tvb_get_uint8(tvb, offset+2);
4242
143
    if (byte != 0x01)           /* v2 client hello msg type */
4243
48
    {
4244
48
        return 0;
4245
48
    }
4246
4247
    /* 1 in 2^16 of being right; improve later if necessary */
4248
95
    return 1;
4249
143
}
4250
4251
/* this applies a heuristic to determine whether
4252
 * or not the data beginning at offset looks like a
4253
 * valid sslv2 record.  this isn't really possible,
4254
 * but we'll try to do a reasonable job anyway.
4255
 */
4256
static int
4257
ssl_looks_like_sslv2(tvbuff_t *tvb, const uint32_t offset)
4258
2.04k
{
4259
    /* here's the current approach:
4260
     *
4261
     * we only try to catch unencrypted handshake messages, so we can
4262
     * assume that there is not padding.  This means that the
4263
     * first byte must be >= 0x80 and there must be a valid sslv2
4264
     * msg_type in the third byte
4265
     */
4266
4267
    /* get the first byte; must have high bit set */
4268
2.04k
    uint8_t byte;
4269
2.04k
    byte = tvb_get_uint8(tvb, offset);
4270
4271
2.04k
    if (byte < 0x80)
4272
1.69k
    {
4273
1.69k
        return 0;
4274
1.69k
    }
4275
4276
    /* get the supposed msg_type byte; since we only care about
4277
     * unencrypted handshake messages (we can't tell the type for
4278
     * encrypted messages), we just check against that list
4279
     */
4280
347
    byte = tvb_get_uint8(tvb, offset + 2);
4281
347
    switch (byte) {
4282
47
    case SSL2_HND_ERROR:
4283
155
    case SSL2_HND_CLIENT_HELLO:
4284
180
    case SSL2_HND_CLIENT_MASTER_KEY:
4285
222
    case SSL2_HND_SERVER_HELLO:
4286
222
        return 1;
4287
347
    }
4288
123
    return 0;
4289
347
}
4290
4291
/* this applies a heuristic to determine whether
4292
 * or not the data beginning at offset looks like a
4293
 * valid sslv3 record.  this is somewhat more reliable
4294
 * than sslv2 due to the structure of the v3 protocol
4295
 */
4296
static int
4297
ssl_looks_like_sslv3(tvbuff_t *tvb, const uint32_t offset)
4298
1.81k
{
4299
    /* have to have a valid content type followed by a valid
4300
     * protocol version
4301
     */
4302
1.81k
    uint8_t byte;
4303
1.81k
    uint16_t version;
4304
4305
    /* see if the first byte is a valid content type */
4306
1.81k
    byte = tvb_get_uint8(tvb, offset);
4307
1.81k
    if (!ssl_is_valid_content_type(byte))
4308
433
    {
4309
433
        return 0;
4310
433
    }
4311
4312
    /* now check to see if the version byte appears valid */
4313
1.38k
    version = tvb_get_ntohs(tvb, offset + 1);
4314
1.38k
    switch (version) {
4315
33
    case SSLV3_VERSION:
4316
59
    case TLSV1_VERSION:
4317
143
    case TLSV1DOT1_VERSION:
4318
982
    case TLSV1DOT2_VERSION:
4319
1.21k
    case TLSV1DOT3_VERSION:
4320
1.25k
    case TLCPV1_VERSION:
4321
1.25k
        return 1;
4322
1.38k
    }
4323
130
    return 0;
4324
1.38k
}
4325
4326
/* applies a heuristic to determine whether
4327
 * or not the data beginning at offset looks
4328
 * like a valid, unencrypted v2 handshake message.
4329
 * since it isn't possible to completely tell random
4330
 * data apart from a valid message without state,
4331
 * we try to help the odds.
4332
 */
4333
static int
4334
ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb, const uint32_t offset,
4335
                                  const uint32_t record_length)
4336
224
{
4337
    /* first byte should be a msg_type.
4338
     *
4339
     *   - we know we only see client_hello, client_master_key,
4340
     *     and server_hello in the clear, so check to see if
4341
     *     msg_type is one of those (this gives us a 3 in 2^8
4342
     *     chance of saying yes with random payload)
4343
     *
4344
     *   - for those three types that we know about, do some
4345
     *     further validation to reduce the chance of an error
4346
     */
4347
224
    uint8_t msg_type;
4348
224
    uint16_t version;
4349
224
    uint32_t sum;
4350
224
    int     ret = 0;
4351
4352
    /* fetch the msg_type */
4353
224
    msg_type = tvb_get_uint8(tvb, offset);
4354
4355
224
    switch (msg_type) {
4356
174
    case SSL2_HND_CLIENT_HELLO:
4357
        /* version follows msg byte, so verify that this is valid */
4358
174
        version = tvb_get_ntohs(tvb, offset+1);
4359
174
        ret = ssl_is_valid_ssl_version(version);
4360
174
        break;
4361
4362
9
    case SSL2_HND_SERVER_HELLO:
4363
        /* version is three bytes after msg_type */
4364
9
        version = tvb_get_ntohs(tvb, offset+3);
4365
9
        ret = ssl_is_valid_ssl_version(version);
4366
9
        break;
4367
4368
15
    case SSL2_HND_CLIENT_MASTER_KEY:
4369
        /* sum of clear_key_length, encrypted_key_length, and key_arg_length
4370
         * must be less than record length
4371
         */
4372
15
        sum  = tvb_get_ntohs(tvb, offset + 4); /* clear_key_length */
4373
15
        sum += tvb_get_ntohs(tvb, offset + 6); /* encrypted_key_length */
4374
15
        sum += tvb_get_ntohs(tvb, offset + 8); /* key_arg_length */
4375
15
        if (sum <= record_length) {
4376
6
            ret = 1;
4377
6
        }
4378
15
        break;
4379
4380
26
    default:
4381
26
        break;
4382
224
    }
4383
4384
224
    return ret;
4385
224
}
4386
4387
SslDecryptSession *
4388
tls_get_current_session(packet_info *pinfo)
4389
0
{
4390
0
    conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4391
0
    if (!conv) {
4392
0
        return NULL;
4393
0
    }
4394
4395
0
    return tls_get_session(conv, proto_tls, p_get_proto_depth(pinfo, proto_tls));
4396
0
}
4397
4398
SslDecryptSession *
4399
tls_get_parent_session(packet_info *pinfo)
4400
0
{
4401
0
    conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4402
0
    if (!conv) {
4403
0
        return NULL;
4404
0
    }
4405
4406
0
    int tls_depth = p_get_proto_depth(pinfo, proto_tls);
4407
0
    if (tls_depth == 0) {
4408
0
        return NULL;
4409
0
    }
4410
4411
0
    return tls_get_session(conv, proto_tls, tls_depth - 1);
4412
0
}
4413
4414
bool
4415
tls_get_cipher_info(SslDecryptSession *ssl_session, uint16_t cipher_suite, int *cipher_algo, int *cipher_mode, int *hash_algo)
4416
0
{
4417
0
    if (cipher_suite == 0) {
4418
0
        if (ssl_session == NULL) {
4419
0
            return false;
4420
0
        }
4421
0
        cipher_suite = ssl_session->session.cipher;
4422
0
    }
4423
0
    const SslCipherSuite *suite = ssl_find_cipher(cipher_suite);
4424
0
    if (!suite) {
4425
0
        return false;
4426
0
    }
4427
4428
    /* adapted from ssl_cipher_init in packet-tls-utils.c */
4429
0
    static const int gcry_modes[] = {
4430
0
        GCRY_CIPHER_MODE_STREAM,
4431
0
        GCRY_CIPHER_MODE_CBC,
4432
0
        GCRY_CIPHER_MODE_GCM,
4433
0
        GCRY_CIPHER_MODE_CCM,
4434
0
        GCRY_CIPHER_MODE_CCM,
4435
0
        GCRY_CIPHER_MODE_POLY1305,
4436
0
    };
4437
0
    static const int gcry_mds[] = {
4438
0
        GCRY_MD_MD5,
4439
0
        GCRY_MD_SHA1,
4440
0
        GCRY_MD_SHA256,
4441
0
        GCRY_MD_SHA384,
4442
0
        -1,
4443
0
    };
4444
0
    int mode = gcry_modes[suite->mode];
4445
0
    int cipher_algo_id = ssl_get_cipher_algo(suite);
4446
0
    int hash_algo_id = gcry_mds[suite->dig-DIG_MD5];
4447
0
    if (mode == -1 || cipher_algo_id == 0 || hash_algo_id == -1) {
4448
        /* Identifiers are unusable, fail. */
4449
0
        return false;
4450
0
    }
4451
0
    if (cipher_algo) {
4452
0
        *cipher_algo = cipher_algo_id;
4453
0
    }
4454
0
    if (cipher_mode) {
4455
0
        *cipher_mode = mode;
4456
0
    }
4457
0
    if (hash_algo) {
4458
0
        *hash_algo = hash_algo_id;
4459
0
    }
4460
4461
0
    return true;
4462
0
}
4463
4464
/**
4465
 * Load the QUIC traffic secret from the keylog file.
4466
 * Returns the secret length (at most 'secret_max_len') and the secret into
4467
 * 'secret' if a secret was found, or zero otherwise.
4468
 */
4469
int
4470
tls13_get_quic_secret(packet_info *pinfo, bool is_from_server, int type, unsigned secret_min_len, unsigned secret_max_len, uint8_t *secret_out)
4471
0
{
4472
0
    GHashTable *key_map;
4473
0
    const char *label;
4474
4475
0
    SslDecryptSession *ssl = tls_get_current_session(pinfo);
4476
0
    if (ssl == NULL) {
4477
0
        return 0;
4478
0
    }
4479
4480
0
    bool is_quic = !!(ssl->state & SSL_QUIC_RECORD_LAYER);
4481
0
    ssl_debug_printf("%s frame %d is_quic=%d\n", G_STRFUNC, pinfo->num, is_quic);
4482
0
    if (!is_quic) {
4483
0
        return 0;
4484
0
    }
4485
4486
0
    if (ssl->client_random.data_len == 0) {
4487
        /* May happen if Hello message is missing and Finished is found. */
4488
0
        ssl_debug_printf("%s missing Client Random\n", G_STRFUNC);
4489
0
        return 0;
4490
0
    }
4491
4492
    // Not strictly necessary as QUIC CRYPTO frames have just been processed
4493
    // which also calls ssl_load_keyfile for key transitions.
4494
0
    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
4495
4496
0
    switch ((TLSRecordType)type) {
4497
0
    case TLS_SECRET_0RTT_APP:
4498
0
        DISSECTOR_ASSERT(!is_from_server);
4499
0
        label = "CLIENT_EARLY_TRAFFIC_SECRET";
4500
0
        key_map = ssl_master_key_map.tls13_client_early;
4501
0
        break;
4502
0
    case TLS_SECRET_HANDSHAKE:
4503
0
        if (is_from_server) {
4504
0
            label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
4505
0
            key_map = ssl_master_key_map.tls13_server_handshake;
4506
0
        } else {
4507
0
            label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
4508
0
            key_map = ssl_master_key_map.tls13_client_handshake;
4509
0
        }
4510
0
        break;
4511
0
    case TLS_SECRET_APP:
4512
0
        if (is_from_server) {
4513
0
            label = "SERVER_TRAFFIC_SECRET_0";
4514
0
            key_map = ssl_master_key_map.tls13_server_appdata;
4515
0
        } else {
4516
0
            label = "CLIENT_TRAFFIC_SECRET_0";
4517
0
            key_map = ssl_master_key_map.tls13_client_appdata;
4518
0
        }
4519
0
        break;
4520
0
    default:
4521
0
        ws_assert_not_reached();
4522
0
    }
4523
4524
0
    StringInfo *secret = (StringInfo *)g_hash_table_lookup(key_map, &ssl->client_random);
4525
0
    if (!secret || secret->data_len < secret_min_len || secret->data_len > secret_max_len) {
4526
0
        ssl_debug_printf("%s Cannot find QUIC %s of size %d..%d, found bad size %d!\n",
4527
0
                         G_STRFUNC, label, secret_min_len, secret_max_len, secret ? secret->data_len : 0);
4528
0
        return 0;
4529
0
    }
4530
4531
0
    ssl_debug_printf("%s Retrieved QUIC traffic secret.\n", G_STRFUNC);
4532
0
    ssl_print_string("Client Random", &ssl->client_random);
4533
0
    ssl_print_string(label, secret);
4534
0
    memcpy(secret_out, secret->data, secret->data_len);
4535
0
    return secret->data_len;
4536
0
}
4537
4538
const char *
4539
tls_get_alpn(SslDecryptSession *session)
4540
0
{
4541
0
    if (session == NULL) {
4542
0
        return NULL;
4543
0
    }
4544
4545
0
    return session->session.alpn_name;
4546
0
}
4547
4548
const char *
4549
tls_get_client_alpn(SslDecryptSession *session)
4550
0
{
4551
0
    if (session == NULL) {
4552
0
        return NULL;
4553
0
    }
4554
4555
0
    return session->session.client_alpn_name;
4556
0
}
4557
4558
/* TLS Exporters {{{ */
4559
/**
4560
 * Computes the TLS 1.3 Exporter value (RFC 8446 Section 7.5).
4561
 *
4562
 * "secret" is the [early_]exporter_master_secret. On success, true is returned
4563
 * and the key is returned via "out" (free with "wmem_free(NULL, out)").
4564
 */
4565
static bool
4566
tls13_exporter_common(int algo, const StringInfo *secret, const char *label, uint8_t *context,
4567
                      unsigned context_length, unsigned key_length, unsigned char **out)
4568
0
{
4569
    /*  TLS-Exporter(label, context_value, key_length) =
4570
     *      HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
4571
     *                        "exporter", Hash(context_value), key_length)
4572
     *
4573
     *  Derive-Secret(Secret, Label, Messages) =
4574
     *      HKDF-Expand-Label(Secret, Label,
4575
     *                        Transcript-Hash(Messages), Hash.length)
4576
     */
4577
0
    gcry_error_t    err;
4578
0
    gcry_md_hd_t    hd;
4579
0
    const uint8_t  *hash_value;
4580
0
    StringInfo      derived_secret = { NULL, 0 };
4581
    // QUIC -09 currently uses draft 23, so no need to support older TLS drafts
4582
0
    const char *label_prefix = "tls13 ";
4583
4584
0
    err = gcry_md_open(&hd, algo, 0);
4585
0
    if (err) {
4586
0
        return false;
4587
0
    }
4588
4589
    /* Calculate Derive-Secret(Secret, label, ""). */
4590
0
    hash_value = gcry_md_read(hd, 0);   /* Empty Messages */
4591
0
    uint8_t hash_len = (uint8_t) gcry_md_get_algo_dlen(algo);
4592
0
    derived_secret.data_len = hash_len;
4593
0
    if (!tls13_hkdf_expand_label_context(algo, secret, label_prefix, label, hash_value, hash_len, derived_secret.data_len, &derived_secret.data)) {
4594
0
        gcry_md_close(hd);
4595
0
        return false;
4596
0
    }
4597
4598
    /* HKDF-Expand-Label(..., "exporter", Hash(context_value), key_length) */
4599
0
    gcry_md_reset(hd);
4600
0
    gcry_md_write(hd, context, context_length);
4601
0
    hash_value = gcry_md_read(hd, 0);
4602
0
    tls13_hkdf_expand_label_context(algo, &derived_secret, label_prefix, "exporter", hash_value, hash_len, key_length, out);
4603
0
    wmem_free(NULL, derived_secret.data);
4604
0
    gcry_md_close(hd);
4605
4606
0
    return true;
4607
0
}
4608
4609
/**
4610
 * Exports keying material using "[early_]exporter_master_secret". See
4611
 * tls13_exporter_common for more details.
4612
 */
4613
bool
4614
tls13_exporter(SslDecryptSession *ssl_session, bool is_early,
4615
               const char *label, uint8_t *context,
4616
               unsigned context_length, unsigned key_length, unsigned char **out)
4617
0
{
4618
0
    int hash_algo = 0;
4619
0
    GHashTable *key_map;
4620
0
    const StringInfo *secret;
4621
4622
0
    if (ssl_session == NULL) {
4623
0
        return false;
4624
0
    }
4625
4626
0
    if (!tls_get_cipher_info(ssl_session, 0, NULL, NULL, &hash_algo)) {
4627
0
        return false;
4628
0
    }
4629
4630
    /* Lookup EXPORTER_SECRET based on client_random from conversation */
4631
0
    ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
4632
0
    key_map = is_early ? ssl_master_key_map.tls13_early_exporter
4633
0
                       : ssl_master_key_map.tls13_exporter;
4634
0
    secret = (StringInfo *)g_hash_table_lookup(key_map, &ssl_session->client_random);
4635
0
    if (!secret) {
4636
0
        return false;
4637
0
    }
4638
4639
0
    return tls13_exporter_common(hash_algo, secret, label, context, context_length, key_length, out);
4640
0
}
4641
/* }}} */
4642
4643
4644
/* UAT */
4645
4646
#ifdef HAVE_LIBGNUTLS
4647
static void
4648
ssldecrypt_free_cb(void *r)
4649
{
4650
    ssldecrypt_assoc_t *h = (ssldecrypt_assoc_t *)r;
4651
4652
    g_free(h->ipaddr);
4653
    g_free(h->port);
4654
    g_free(h->protocol);
4655
    g_free(h->keyfile);
4656
    g_free(h->password);
4657
}
4658
4659
static void*
4660
ssldecrypt_copy_cb(void *dest, const void *orig, size_t len _U_)
4661
{
4662
    const ssldecrypt_assoc_t *o = (const ssldecrypt_assoc_t *)orig;
4663
    ssldecrypt_assoc_t       *d = (ssldecrypt_assoc_t *)dest;
4664
4665
    d->ipaddr    = g_strdup(o->ipaddr);
4666
    d->port      = g_strdup(o->port);
4667
    d->protocol  = g_strdup(o->protocol);
4668
    d->keyfile   = g_strdup(o->keyfile);
4669
    d->password  = g_strdup(o->password);
4670
4671
    return d;
4672
}
4673
4674
UAT_CSTRING_CB_DEF(sslkeylist_uats,ipaddr,ssldecrypt_assoc_t)
4675
UAT_CSTRING_CB_DEF(sslkeylist_uats,port,ssldecrypt_assoc_t)
4676
UAT_CSTRING_CB_DEF(sslkeylist_uats,protocol,ssldecrypt_assoc_t)
4677
UAT_FILENAME_CB_DEF(sslkeylist_uats,keyfile,ssldecrypt_assoc_t)
4678
UAT_CSTRING_CB_DEF(sslkeylist_uats,password,ssldecrypt_assoc_t)
4679
4680
static bool
4681
ssldecrypt_uat_fld_protocol_chk_cb(void* r _U_, const char* p, unsigned len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
4682
{
4683
    if (!p || strlen(p) == 0u) {
4684
        // This should be removed in favor of Decode As. Make it optional.
4685
        *err = NULL;
4686
        return true;
4687
    }
4688
4689
    if (!ssl_find_appdata_dissector(p)) {
4690
        if (find_dissector(p)) {
4691
            // ssl_find_appdata_dissector accepts any valid dissector name so
4692
            // this path cannot happen
4693
            *err = ws_strdup_printf("While '%s' is a valid dissector name, that dissector is not configured"
4694
                                   " to support TLS decryption.\n\n"
4695
                                   "If you need to decrypt '%s' over TLS, please contact the Wireshark development team.", p, p);
4696
        } else {
4697
            // The GUI validates dissector names now so this path shouldn't
4698
            // occur either. (Perhaps if the UAT is hand-edited it might?)
4699
            char* ssl_str = ssl_association_info("tls.port", "TCP");
4700
            *err = ws_strdup_printf("Could not find dissector for: '%s'\nCommonly used TLS dissectors include:\n%s", p, ssl_str);
4701
            g_free(ssl_str);
4702
        }
4703
        return false;
4704
    }
4705
4706
    *err = NULL;
4707
    return true;
4708
}
4709
#endif  /* HAVE_LIBGNUTLS */
4710
4711
static void
4712
ssl_src_prompt(packet_info *pinfo, char *result)
4713
0
{
4714
0
    SslPacketInfo* pi;
4715
0
    uint32_t srcport = PINFO_SRCPORT(pinfo);
4716
4717
0
    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4718
0
    if (pi != NULL)
4719
0
        srcport = pi->srcport;
4720
4721
0
    snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "source (%u%s)", srcport, UTF8_RIGHTWARDS_ARROW);
4722
0
}
4723
4724
static void *
4725
ssl_src_value(packet_info *pinfo)
4726
0
{
4727
0
    SslPacketInfo* pi;
4728
4729
0
    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4730
0
    if (pi == NULL)
4731
0
        return GUINT_TO_POINTER(PINFO_SRCPORT(pinfo));
4732
4733
0
    return GUINT_TO_POINTER(pi->srcport);
4734
0
}
4735
4736
static void
4737
ssl_dst_prompt(packet_info *pinfo, char *result)
4738
0
{
4739
0
    SslPacketInfo* pi;
4740
0
    uint32_t destport = PINFO_DESTPORT(pinfo);
4741
4742
0
    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4743
0
    if (pi != NULL)
4744
0
        destport = pi->destport;
4745
4746
0
    snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "destination (%s%u)", UTF8_RIGHTWARDS_ARROW, destport);
4747
0
}
4748
4749
static void *
4750
ssl_dst_value(packet_info *pinfo)
4751
0
{
4752
0
    SslPacketInfo* pi;
4753
4754
0
    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4755
0
    if (pi == NULL)
4756
0
        return GUINT_TO_POINTER(PINFO_DESTPORT(pinfo));
4757
4758
0
    return GUINT_TO_POINTER(pi->destport);
4759
0
}
4760
4761
static void
4762
ssl_both_prompt(packet_info *pinfo, char *result)
4763
0
{
4764
0
    SslPacketInfo* pi;
4765
0
    uint32_t srcport = PINFO_SRCPORT(pinfo),
4766
0
            destport = PINFO_DESTPORT(pinfo);
4767
4768
0
    pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4769
0
    if (pi != NULL)
4770
0
    {
4771
0
        srcport = pi->srcport;
4772
0
        destport = pi->destport;
4773
0
    }
4774
4775
0
    snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "both (%u%s%u)", srcport, UTF8_LEFT_RIGHT_ARROW, destport);
4776
0
}
4777
4778
static void
4779
tls_secrets_block_callback(const void *secrets, unsigned size)
4780
0
{
4781
0
    tls_keylog_process_lines(&ssl_master_key_map, (const uint8_t *)secrets, size);
4782
0
}
4783
4784
/*********************************************************************
4785
 *
4786
 * Standard Wireshark Protocol Registration and housekeeping
4787
 *
4788
 *********************************************************************/
4789
void
4790
proto_register_tls(void)
4791
16
{
4792
4793
    /* Setup list of header fields See Section 1.6.1 for details*/
4794
16
    static hf_register_info hf[] = {
4795
16
        { &hf_tls_stream,
4796
16
          { "Stream index", "tls.stream",
4797
16
            FT_UINT32, BASE_DEC, NULL, 0x0,
4798
16
            NULL, HFILL }
4799
16
        },
4800
16
        { &hf_tls_record,
4801
16
          { "Record Layer", "tls.record",
4802
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4803
16
            NULL, HFILL }
4804
16
        },
4805
16
        { &hf_tls_record_content_type,
4806
16
          { "Content Type", "tls.record.content_type",
4807
16
            FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
4808
16
            NULL, HFILL}
4809
16
        },
4810
16
        { &hf_tls_record_opaque_type,
4811
16
          { "Opaque Type", "tls.record.opaque_type",
4812
16
            FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
4813
16
            "Always set to value 23, actual content type is known after decryption", HFILL}
4814
16
        },
4815
16
        { &hf_ssl2_msg_type,
4816
16
          { "Handshake Message Type", "tls.ssl2.handshake.type",
4817
16
            FT_UINT8, BASE_DEC, VALS(ssl_20_msg_types), 0x0,
4818
16
            "SSLv2 handshake message type", HFILL}
4819
16
        },
4820
16
        { &hf_tls_record_version,
4821
16
          { "Version", "tls.record.version",
4822
16
            FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
4823
16
            "Record layer version", HFILL }
4824
16
        },
4825
16
        { &hf_tls_record_length,
4826
16
          { "Length", "tls.record.length",
4827
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4828
16
            "Length of TLS record data", HFILL }
4829
16
        },
4830
16
        { &hf_tls_record_sequence_number,
4831
16
          { "Sequence Number", "tls.record.sequence_number",
4832
16
            FT_UINT64, BASE_DEC, NULL, 0x0,
4833
16
            NULL, HFILL}
4834
16
        },
4835
16
        { &hf_tls_record_appdata,
4836
16
          { "Encrypted Application Data", "tls.app_data",
4837
16
            FT_BYTES, BASE_NONE, NULL, 0x0,
4838
16
            "Payload is encrypted application data", HFILL }
4839
16
        },
4840
16
        { &hf_tls_record_appdata_proto,
4841
16
          { "Application Data Protocol", "tls.app_data_proto",
4842
16
            FT_STRING, BASE_NONE, NULL, 0x0,
4843
16
            NULL, HFILL }
4844
16
        },
4845
16
        { &hf_ssl2_record,
4846
16
          { "SSLv2 Record Header", "tls.record",
4847
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4848
16
            "SSLv2 record data", HFILL }
4849
16
        },
4850
16
        { &hf_ssl2_record_is_escape,
4851
16
          { "Is Escape", "tls.record.is_escape",
4852
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4853
16
            "Indicates a security escape", HFILL}
4854
16
        },
4855
16
        { &hf_ssl2_record_padding_length,
4856
16
          { "Padding Length", "tls.record.padding_length",
4857
16
            FT_UINT8, BASE_DEC, NULL, 0x0,
4858
16
            "Length of padding at end of record", HFILL }
4859
16
        },
4860
16
        { &hf_tls_alert_message,
4861
16
          { "Alert Message", "tls.alert_message",
4862
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4863
16
            NULL, HFILL }
4864
16
        },
4865
16
        { &hf_tls_alert_message_level,
4866
16
          { "Level", "tls.alert_message.level",
4867
16
            FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
4868
16
            "Alert message level", HFILL }
4869
16
        },
4870
16
        { &hf_tls_alert_message_description,
4871
16
          { "Description", "tls.alert_message.desc",
4872
16
            FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
4873
16
            "Alert message description", HFILL }
4874
16
        },
4875
16
        { &hf_tls_handshake_protocol,
4876
16
          { "Handshake Protocol", "tls.handshake",
4877
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4878
16
            "Handshake protocol message", HFILL}
4879
16
        },
4880
16
        { &hf_tls_handshake_type,
4881
16
          { "Handshake Type", "tls.handshake.type",
4882
16
            FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
4883
16
            "Type of handshake message", HFILL}
4884
16
        },
4885
16
        { &hf_tls_handshake_length,
4886
16
          { "Length", "tls.handshake.length",
4887
16
            FT_UINT24, BASE_DEC, NULL, 0x0,
4888
16
            "Length of handshake message", HFILL }
4889
16
        },
4890
16
        { &hf_ssl2_handshake_cipher_spec,
4891
16
          { "Cipher Spec", "tls.ssl2.handshake.cipherspec",
4892
16
            FT_UINT24, BASE_HEX|BASE_EXT_STRING, &ssl_20_cipher_suites_ext, 0x0,
4893
16
            "Cipher specification", HFILL }
4894
16
        },
4895
16
        { &hf_tls_handshake_npn_selected_protocol_len,
4896
16
          { "Selected Protocol Length", "tls.handshake.npn_selected_protocol_len",
4897
16
            FT_UINT8, BASE_DEC, NULL, 0x0,
4898
16
            NULL, HFILL }
4899
16
        },
4900
16
        { &hf_tls_handshake_npn_selected_protocol,
4901
16
          { "Selected Protocol", "tls.handshake.npn_selected_protocol",
4902
16
            FT_STRING, BASE_NONE, NULL, 0x0,
4903
16
            "Protocol to be used for connection", HFILL }
4904
16
        },
4905
16
        { &hf_tls_handshake_npn_padding_len,
4906
16
          { "Padding Length", "tls.handshake.npn_padding_len",
4907
16
            FT_UINT8, BASE_DEC, NULL, 0x0,
4908
16
            NULL, HFILL }
4909
16
        },
4910
16
        { &hf_tls_handshake_npn_padding,
4911
16
          { "Padding", "tls.handshake.npn_padding",
4912
16
            FT_BYTES, BASE_NONE, NULL, 0x0,
4913
16
            NULL, HFILL }
4914
16
        },
4915
16
        { &ssl_hfs.hs_md5_hash,
4916
16
          { "MD5 Hash", "tls.handshake.md5_hash",
4917
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4918
16
            "Hash of messages, master_secret, etc.", HFILL }
4919
16
        },
4920
16
        { &ssl_hfs.hs_sha_hash,
4921
16
          { "SHA-1 Hash", "tls.handshake.sha_hash",
4922
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4923
16
            "Hash of messages, master_secret, etc.", HFILL }
4924
16
        },
4925
16
        { &hf_tls_heartbeat_message,
4926
16
          { "Heartbeat Message", "tls.heartbeat_message",
4927
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4928
16
            NULL, HFILL }
4929
16
        },
4930
16
        { &hf_tls_heartbeat_message_type,
4931
16
          { "Type", "tls.heartbeat_message.type",
4932
16
            FT_UINT8, BASE_DEC, VALS(tls_heartbeat_type), 0x0,
4933
16
            "Heartbeat message type", HFILL }
4934
16
        },
4935
16
        { &hf_tls_heartbeat_message_payload_length,
4936
16
          { "Payload Length", "tls.heartbeat_message.payload_length",
4937
16
            FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
4938
16
        },
4939
16
        { &hf_tls_heartbeat_message_payload,
4940
16
          { "Payload Length", "tls.heartbeat_message.payload",
4941
16
            FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
4942
16
        },
4943
16
        { &hf_tls_heartbeat_message_padding,
4944
16
          { "Payload Length", "tls.heartbeat_message.padding",
4945
16
            FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
4946
16
        },
4947
16
        { &hf_ssl2_handshake_challenge,
4948
16
          { "Challenge", "tls.handshake.challenge",
4949
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4950
16
            "Challenge data used to authenticate server", HFILL }
4951
16
        },
4952
16
        { &hf_ssl2_handshake_cipher_spec_len,
4953
16
          { "Cipher Spec Length", "tls.handshake.cipher_spec_len",
4954
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4955
16
            "Length of cipher specs field", HFILL }
4956
16
        },
4957
16
        { &hf_ssl2_handshake_session_id_len,
4958
16
          { "Session ID Length", "tls.handshake.session_id_length",
4959
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4960
16
            "Length of session ID field", HFILL }
4961
16
        },
4962
16
        { &hf_ssl2_handshake_challenge_len,
4963
16
          { "Challenge Length", "tls.handshake.challenge_length",
4964
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4965
16
            "Length of challenge field", HFILL }
4966
16
        },
4967
16
        { &hf_ssl2_handshake_clear_key_len,
4968
16
          { "Clear Key Data Length", "tls.handshake.clear_key_length",
4969
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4970
16
            "Length of clear key data", HFILL }
4971
16
        },
4972
16
        { &hf_ssl2_handshake_enc_key_len,
4973
16
          { "Encrypted Key Data Length", "tls.handshake.encrypted_key_length",
4974
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4975
16
            "Length of encrypted key data", HFILL }
4976
16
        },
4977
16
        { &hf_ssl2_handshake_key_arg_len,
4978
16
          { "Key Argument Length", "tls.handshake.key_arg_length",
4979
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
4980
16
            "Length of key argument", HFILL }
4981
16
        },
4982
16
        { &hf_ssl2_handshake_clear_key,
4983
16
          { "Clear Key Data", "tls.handshake.clear_key_data",
4984
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4985
16
            "Clear portion of MASTER-KEY", HFILL }
4986
16
        },
4987
16
        { &hf_ssl2_handshake_enc_key,
4988
16
          { "Encrypted Key", "tls.handshake.encrypted_key",
4989
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4990
16
            "Secret portion of MASTER-KEY encrypted to server", HFILL }
4991
16
        },
4992
16
        { &hf_ssl2_handshake_key_arg,
4993
16
          { "Key Argument", "tls.handshake.key_arg",
4994
16
            FT_NONE, BASE_NONE, NULL, 0x0,
4995
16
            "Key Argument (e.g., Initialization Vector)", HFILL }
4996
16
        },
4997
16
        { &hf_ssl2_handshake_session_id_hit,
4998
16
          { "Session ID Hit", "tls.handshake.session_id_hit",
4999
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
5000
16
            "Did the server find the client's Session ID?", HFILL }
5001
16
        },
5002
16
        { &hf_ssl2_handshake_cert_type,
5003
16
          { "Certificate Type", "tls.ssl2.handshake.cert_type",
5004
16
            FT_UINT8, BASE_DEC, VALS(ssl_20_certificate_type), 0x0,
5005
16
            NULL, HFILL }
5006
16
        },
5007
16
        { &hf_ssl2_handshake_connection_id_len,
5008
16
          { "Connection ID Length", "tls.handshake.connection_id_length",
5009
16
            FT_UINT16, BASE_DEC, NULL, 0x0,
5010
16
            "Length of connection ID", HFILL }
5011
16
        },
5012
16
        { &hf_ssl2_handshake_connection_id,
5013
16
          { "Connection ID", "tls.handshake.connection_id",
5014
16
            FT_NONE, BASE_NONE, NULL, 0x0,
5015
16
            "Server's challenge to client", HFILL }
5016
16
        },
5017
5018
16
        { &hf_tls_segment_overlap,
5019
16
          { "Segment overlap", "tls.segment.overlap",
5020
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
5021
16
            "Segment overlaps with other segments", HFILL }},
5022
5023
16
        { &hf_tls_segment_overlap_conflict,
5024
16
          { "Conflicting data in segment overlap", "tls.segment.overlap.conflict",
5025
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
5026
16
            "Overlapping segments contained conflicting data", HFILL }},
5027
5028
16
        { &hf_tls_segment_multiple_tails,
5029
16
          { "Multiple tail segments found", "tls.segment.multipletails",
5030
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
5031
16
            "Several tails were found when reassembling the pdu", HFILL }},
5032
5033
16
        { &hf_tls_segment_too_long_fragment,
5034
16
          { "Segment too long", "tls.segment.toolongfragment",
5035
16
            FT_BOOLEAN, BASE_NONE, NULL, 0x0,
5036
16
            "Segment contained data past end of the pdu", HFILL }},
5037
5038
16
        { &hf_tls_segment_error,
5039
16
          { "Reassembling error", "tls.segment.error",
5040
16
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
5041
16
            "Reassembling error due to illegal segments", HFILL }},
5042
5043
16
        { &hf_tls_segment_count,
5044
16
          { "Segment count", "tls.segment.count",
5045
16
            FT_UINT32, BASE_DEC, NULL, 0x0,
5046
16
            NULL, HFILL }},
5047
5048
16
        { &hf_tls_segment,
5049
16
          { "TLS segment", "tls.segment",
5050
16
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
5051
16
            NULL, HFILL }},
5052
5053
16
        { &hf_tls_segments,
5054
16
          { "Reassembled TLS segments", "tls.segments",
5055
16
            FT_NONE, BASE_NONE, NULL, 0x0,
5056
16
            NULL, HFILL }},
5057
5058
16
        { &hf_tls_reassembled_in,
5059
16
          { "Reassembled PDU in frame", "tls.reassembled_in",
5060
16
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
5061
16
            "The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},
5062
5063
16
        { &hf_tls_reassembled_length,
5064
16
          { "Reassembled PDU length", "tls.reassembled.length",
5065
16
            FT_UINT32, BASE_DEC, NULL, 0x0,
5066
16
            "The total length of the reassembled payload", HFILL }},
5067
5068
16
        { &hf_tls_reassembled_data,
5069
16
          { "Reassembled PDU data", "tls.reassembled.data",
5070
16
            FT_BYTES, BASE_NONE, NULL, 0x00,
5071
16
            "The payload of multiple reassembled TLS segments", HFILL }},
5072
5073
16
        { &hf_tls_segment_data,
5074
16
          { "TLS segment data", "tls.segment.data",
5075
16
            FT_BYTES, BASE_NONE, NULL, 0x00,
5076
16
            "The payload of a single TLS segment", HFILL }
5077
16
        },
5078
5079
16
        { &hf_tls_handshake_fragment_count,
5080
16
          { "Handshake Fragment count", "tls.handshake.fragment.count",
5081
16
            FT_UINT32, BASE_DEC, NULL, 0x0,
5082
16
            NULL, HFILL }},
5083
5084
16
        { &hf_tls_handshake_fragment,
5085
16
          { "Handshake Fragment", "tls.handshake.fragment",
5086
16
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
5087
16
            NULL, HFILL }},
5088
5089
16
        { &hf_tls_handshake_fragments,
5090
16
          { "Reassembled Handshake Fragments", "tls.handshake.fragments",
5091
16
            FT_NONE, BASE_NONE, NULL, 0x0,
5092
16
            NULL, HFILL }},
5093
5094
16
        { &hf_tls_handshake_reassembled_in,
5095
16
          { "Reassembled Handshake Message in frame", "tls.handshake.reassembled_in",
5096
16
            FT_FRAMENUM, BASE_NONE, NULL, 0x0,
5097
16
            "The handshake message is fully reassembled in this frame", HFILL }},
5098
5099
16
        SSL_COMMON_HF_LIST(dissect_ssl3_hf, "tls")
5100
16
    };
5101
5102
    /* Setup protocol subtree array */
5103
16
    static int *ett[] = {
5104
16
        &ett_tls,
5105
16
        &ett_tls_record,
5106
16
        &ett_tls_alert,
5107
16
        &ett_tls_handshake,
5108
16
        &ett_tls_heartbeat,
5109
16
        &ett_tls_certs,
5110
16
        &ett_tls_segments,
5111
16
        &ett_tls_segment,
5112
16
        &ett_tls_hs_fragments,
5113
16
        &ett_tls_hs_fragment,
5114
16
        SSL_COMMON_ETT_LIST(dissect_ssl3_hf)
5115
16
    };
5116
5117
16
    static ei_register_info ei[] = {
5118
16
        { &ei_ssl2_handshake_session_id_len_error, { "tls.handshake.session_id_length.error", PI_MALFORMED, PI_ERROR, "Session ID length error", EXPFILL }},
5119
16
        { &ei_ssl3_heartbeat_payload_length, { "tls.heartbeat_message.payload_length.invalid", PI_MALFORMED, PI_ERROR, "Invalid heartbeat payload length", EXPFILL }},
5120
16
        { &ei_tls_unexpected_message, { "tls.unexpected_message", PI_PROTOCOL, PI_ERROR, "Unexpected message", EXPFILL }},
5121
5122
      /* Generated from convert_proto_tree_add_text.pl */
5123
16
      { &ei_tls_ignored_unknown_record, { "tls.ignored_unknown_record", PI_PROTOCOL, PI_WARN, "Ignored Unknown Record", EXPFILL }},
5124
5125
16
        SSL_COMMON_EI_LIST(dissect_ssl3_hf, "tls")
5126
16
    };
5127
5128
16
    static build_valid_func ssl_da_src_values[1] = {ssl_src_value};
5129
16
    static build_valid_func ssl_da_dst_values[1] = {ssl_dst_value};
5130
16
    static build_valid_func ssl_da_both_values[2] = {ssl_src_value, ssl_dst_value};
5131
16
    static decode_as_value_t ssl_da_values[3] = {{ssl_src_prompt, 1, ssl_da_src_values}, {ssl_dst_prompt, 1, ssl_da_dst_values}, {ssl_both_prompt, 2, ssl_da_both_values}};
5132
16
    static decode_as_t ssl_da = {"tls", "tls.port", 3, 2, ssl_da_values, "TCP", "port(s) as",
5133
16
                                 decode_as_default_populate_list, decode_as_default_reset, decode_as_default_change, NULL, NULL, NULL };
5134
5135
16
    expert_module_t* expert_ssl;
5136
5137
    /* Register the protocol name and description */
5138
16
    proto_tls = proto_register_protocol("Transport Layer Security",
5139
16
                                        "TLS", "tls");
5140
5141
16
    ssl_associations = register_dissector_table("tls.port", "TLS Port", proto_tls, FT_UINT16, BASE_DEC);
5142
16
    register_dissector_table_alias(ssl_associations, "ssl.port");
5143
5144
    /* Required function calls to register the header fields and
5145
     * subtrees used */
5146
16
    proto_register_field_array(proto_tls, hf, array_length(hf));
5147
16
    proto_register_alias(proto_tls, "ssl");
5148
16
    proto_register_subtree_array(ett, array_length(ett));
5149
16
    expert_ssl = expert_register_protocol(proto_tls);
5150
16
    expert_register_field_array(expert_ssl, ei, array_length(ei));
5151
5152
16
    {
5153
16
        module_t *ssl_module = prefs_register_protocol(proto_tls, proto_reg_handoff_ssl);
5154
5155
#ifdef HAVE_LIBGNUTLS
5156
        static uat_field_t sslkeylist_uats_flds[] = {
5157
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, ipaddr, "IP address", ssldecrypt_uat_fld_ip_chk_cb, "IPv4 or IPv6 address (unused)"),
5158
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, port, "Port", ssldecrypt_uat_fld_port_chk_cb, "Port Number (optional)"),
5159
            UAT_FLD_DISSECTOR_OTHER(sslkeylist_uats, protocol, "Protocol", ssldecrypt_uat_fld_protocol_chk_cb, "Application Layer Protocol (optional)"),
5160
            UAT_FLD_FILENAME_OTHER(sslkeylist_uats, keyfile, "Key File", ssldecrypt_uat_fld_fileopen_chk_cb, "Private keyfile."),
5161
            UAT_FLD_CSTRING_OTHER(sslkeylist_uats, password,"Password", ssldecrypt_uat_fld_password_chk_cb, "Password (for PCKS#12 keyfile)"),
5162
            UAT_END_FIELDS
5163
        };
5164
5165
        ssldecrypt_uat = uat_new("TLS Decrypt",
5166
            sizeof(ssldecrypt_assoc_t),
5167
            "ssl_keys",                     /* filename */
5168
            true,                           /* from_profile */
5169
            &tlskeylist_uats,               /* data_ptr */
5170
            &ntlsdecrypt,                   /* numitems_ptr */
5171
            UAT_AFFECTS_DISSECTION,         /* affects dissection of packets, but not set of named fields */
5172
            NULL,                           /* Help section (currently a wiki page) */
5173
            ssldecrypt_copy_cb,
5174
            NULL,
5175
            ssldecrypt_free_cb,
5176
            ssl_parse_uat,
5177
            ssl_reset_uat,
5178
            sslkeylist_uats_flds);
5179
5180
        prefs_register_uat_preference(ssl_module, "key_table",
5181
            "RSA keys list",
5182
            "A table of RSA keys for TLS decryption",
5183
            ssldecrypt_uat);
5184
5185
        prefs_register_obsolete_preference(ssl_module, "keys_list");
5186
#endif  /* HAVE_LIBGNUTLS */
5187
5188
16
        prefs_register_filename_preference(ssl_module, "debug_file", "TLS debug file",
5189
16
            "Redirect TLS debug to the file specified. Leave empty to disable debugging "
5190
16
            "or use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr.",
5191
16
            &ssl_debug_file_name, true);
5192
5193
16
        prefs_register_bool_preference(ssl_module,
5194
16
             "desegment_ssl_records",
5195
16
             "Reassemble TLS records spanning multiple TCP segments",
5196
16
             "Whether the TLS dissector should reassemble TLS records spanning multiple TCP segments. "
5197
16
             "To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
5198
16
             &tls_desegment);
5199
16
        prefs_register_bool_preference(ssl_module,
5200
16
             "desegment_ssl_application_data",
5201
16
             "Reassemble TLS Application Data spanning multiple TLS records",
5202
16
             "Whether the TLS dissector should reassemble TLS Application Data spanning multiple TLS records. ",
5203
16
             &tls_desegment_app_data);
5204
16
        prefs_register_bool_preference(ssl_module,
5205
16
             "ignore_ssl_mac_failed",
5206
16
             "Message Authentication Code (MAC), ignore \"mac failed\"",
5207
16
             "For troubleshooting ignore the mac check result and decrypt also if the Message Authentication Code (MAC) fails.",
5208
16
             &tls_ignore_mac_failed);
5209
5210
        /* Port 443 is too overloaded... */
5211
16
        range_convert_str(wmem_epan_scope(), &tls_try_heuristic_first, PORT_HEUR_DEFAULT, 65535);
5212
16
        prefs_register_range_preference(ssl_module,
5213
16
             "try_heuristic_first",
5214
16
             "Try heuristic sub-dissectors first on ports",
5215
16
             "Try to decode a packet using an heuristic sub-dissector before using a sub-dissector registered to a specific port for these ports, e.g. the overloaded port 443. An ALPN for a connection always has precedence.",
5216
16
             &tls_try_heuristic_first, 65535);
5217
16
        ssl_common_register_options(ssl_module, &ssl_options, false);
5218
16
    }
5219
5220
    /* heuristic dissectors for any preamble e.g. CredSSP before RDP */
5221
16
    ssl_heur_subdissector_list = register_heur_dissector_list_with_description("tls", "TLS data", proto_tls);
5222
5223
16
    ssl_common_register_ssl_alpn_dissector_table("tls.alpn",
5224
16
        "SSL/TLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs",
5225
16
        proto_tls);
5226
5227
16
    tls_handle = register_dissector("tls", dissect_ssl, proto_tls);
5228
16
    tls13_handshake_handle = register_dissector("tls13-handshake", dissect_tls13_handshake, proto_tls);
5229
16
    register_dissector("tls-echconfig", dissect_tls_echconfig, proto_tls);
5230
5231
16
    register_init_routine(ssl_init);
5232
16
    register_cleanup_routine(ssl_cleanup);
5233
16
    reassembly_table_register(&ssl_reassembly_table,
5234
16
                          &tcp_reassembly_table_functions);
5235
16
    reassembly_table_register(&tls_hs_reassembly_table,
5236
16
                          &tls_hs_reassembly_table_functions);
5237
16
    register_decode_as(&ssl_da);
5238
5239
    /* XXX: this seems unused due to new "Follow TLS" method, remove? */
5240
16
    tls_follow_tap = register_tap("tls_follow");
5241
16
    ssl_debug_printf("proto_register_ssl: registered tap %s:%d\n",
5242
16
        "tls_follow", tls_follow_tap);
5243
5244
16
    register_follow_stream(proto_tls, "tls_follow", tls_follow_conv_filter, tls_follow_index_filter, tcp_follow_address_filter,
5245
16
                            tcp_port_to_display, ssl_follow_tap_listener, get_tls_stream_count, NULL);
5246
16
    secrets_register_type(SECRETS_TYPE_TLS, tls_secrets_block_callback);
5247
16
    secrets_register_inject_type("TLS", ssl_session_key_count, tls_export_dsb, ssl_export_sessions);
5248
16
}
5249
5250
static int dissect_tls_sct_ber(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
5251
0
{
5252
0
    uint32_t offset = 0;
5253
    /* Skip through tag and length for OCTET STRING encoding. */
5254
0
    offset = dissect_ber_identifier(pinfo, tree, tvb, offset, NULL, NULL, NULL);
5255
0
    offset = dissect_ber_length(pinfo, tree, tvb, offset, NULL, NULL);
5256
    /*
5257
     * RFC 6962 (Certificate Transparency) refers to RFC 5246 (TLS 1.2) for the
5258
     * DigitallySigned format, so assume that version.
5259
     */
5260
0
    return tls_dissect_sct_list(&dissect_ssl3_hf, tvb, pinfo, tree, offset, tvb_captured_length(tvb), TLSV1DOT2_VERSION);
5261
0
}
5262
5263
/* If this dissector uses sub-dissector registration add a registration
5264
 * routine.  This format is required because a script is used to find
5265
 * these routines and create the code that calls these routines.
5266
 */
5267
void
5268
proto_reg_handoff_ssl(void)
5269
16
{
5270
16
    if (files_identical(ssl_debug_file_name, ssl_options.keylog_filename)) {
5271
0
        report_failure("The TLS debug file (\"%s\") cannot point to the same "
5272
0
        "file as the TLS key log file (\"%s\").", ssl_debug_file_name,
5273
0
        ssl_options.keylog_filename);
5274
5275
        /* ssl_parse_uat() sets (and thus overwrites) the debug file, so to
5276
         * be safe, set it the empty string before calling that so we don't
5277
         * overwrite their key log file.
5278
         */
5279
0
        module_t *tls_module = prefs_find_module("tls");
5280
0
        if (tls_module) {
5281
0
            pref_t *pref_tls_debug = prefs_find_preference(tls_module, "debug_file");
5282
0
            if (pref_tls_debug) {
5283
0
                prefs_set_string_value(pref_tls_debug, "", pref_current);
5284
0
            }
5285
0
        }
5286
0
    }
5287
5288
#ifdef HAVE_LIBGNUTLS
5289
    /* parse key list */
5290
    ssl_parse_uat();
5291
#endif
5292
5293
16
    static bool initialized = false;
5294
16
    if (initialized) {
5295
0
        return;
5296
0
    }
5297
16
    initialized = true;
5298
5299
16
    exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_7);
5300
5301
    /* Certificate Transparency extensions: 2 (Certificate), 5 (OCSP Response) */
5302
16
    register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.2", dissect_tls_sct_ber, proto_tls, "SignedCertificateTimestampList");
5303
16
    register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.5", dissect_tls_sct_ber, proto_tls, "SignedCertificateTimestampList");
5304
5305
16
    heur_dissector_add("tcp", dissect_ssl_heur, "SSL/TLS over TCP", "tls_tcp", proto_tls, HEURISTIC_ENABLE);
5306
16
    dissector_add_string("http.upgrade", "tls", tls_handle);
5307
16
    dissector_add_string("http.upgrade", "TLS/1.0", tls_handle);
5308
16
    dissector_add_string("http.upgrade", "TLS/1.1", tls_handle);
5309
16
    dissector_add_string("http.upgrade", "TLS/1.2", tls_handle);
5310
16
    dissector_add_string("http.upgrade", "TLS/1.3", tls_handle);
5311
    /* Ivanti VPNs (unregistered with IANA) */
5312
16
    dissector_add_string("http.upgrade", "IF-T/TLS", tls_handle);
5313
5314
    /* RFC 9934 */
5315
16
    dissector_add_string("rfc7468.preeb_label", "ECHCONFIG", create_dissector_handle(dissect_tls_echconfig, proto_tls));
5316
16
}
5317
5318
void
5319
ssl_dissector_add(unsigned port, dissector_handle_t handle)
5320
592
{
5321
592
    ssl_association_add("tls.port", tls_handle, handle, port, true);
5322
592
}
5323
5324
void
5325
ssl_dissector_delete(unsigned port, dissector_handle_t handle)
5326
0
{
5327
    ssl_association_remove("tls.port", tls_handle, handle, port, true);
5328
0
}
5329
5330
/*
5331
 * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
5332
 *
5333
 * Local variables:
5334
 * c-basic-offset: 4
5335
 * tab-width: 8
5336
 * indent-tabs-mode: nil
5337
 * End:
5338
 *
5339
 * vi: set shiftwidth=4 tabstop=8 expandtab:
5340
 * :indentSize=4:tabSize=8:noTabs=true:
5341
 */