Coverage Report

Created: 2025-02-15 06:25

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