Revert "TODO epan/dissectors/asn1/kerberos/packet-kerberos-template.c new GSS flags"
[wireshark-sm.git] / epan / dissectors / packet-tls.c
blobccffb503c496f491365c36b4b545dfad82f1070d
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>
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * SPDX-License-Identifier: GPL-2.0-or-later
14 * Supported protocol versions:
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.
19 * Primary protocol specifications:
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
28 * Important IANA registries:
30 * https://www.iana.org/assignments/tls-parameters/
31 * https://www.iana.org/assignments/tls-extensiontype-values/
33 * Notes:
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
41 * We are at Packet reception if time pinfo->fd->visited == 0
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).
50 #include "config.h"
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>
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"
79 void proto_register_tls(void);
81 #ifdef HAVE_LIBGNUTLS
82 static ssldecrypt_assoc_t *tlskeylist_uats;
83 static unsigned ntlsdecrypt;
84 #endif
86 static bool tls_desegment = true;
87 static bool tls_desegment_app_data = true;
88 static bool tls_ignore_mac_failed;
90 #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;
95 /*********************************************************************
97 * Protocol Constants, Variables, Data Structures
99 *********************************************************************/
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;
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;
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;
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;
166 static ssl_hfs_t ssl_hfs;
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;
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;
184 /* Generated from convert_proto_tree_add_text.pl */
185 static expert_field ei_tls_ignored_unknown_record;
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"
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"
225 static SSL_COMMON_LIST_T(dissect_ssl3_hf);
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)
235 proto_tree_add_bytes_format(
236 tree,
237 hf_tls_segment_data,
238 tvb,
239 offset,
240 length,
241 NULL,
242 "%sTLS segment data (%u %s)",
243 prefix != NULL ? prefix : "",
244 length == -1 ? tvb_reported_length_remaining(tvb, offset) : length,
245 plurality(length, "byte", "bytes"));
249 static ssl_master_key_map_t ssl_master_key_map;
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;
265 /* List of dissectors to call for TLS data */
266 static heur_dissector_list_t ssl_heur_subdissector_list;
268 static const char *ssl_debug_file_name;
271 /* Forward declaration we need below */
272 void proto_reg_handoff_ssl(void);
274 /* Desegmentation of TLS streams */
275 /* table to hold defragmented TLS streams */
276 static reassembly_table ssl_reassembly_table;
278 /* Table to hold fragmented TLS handshake records. */
279 static reassembly_table tls_hs_reassembly_table;
280 static uint32_t hs_reassembly_id_count;
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.
286 typedef struct _tls_hs_fragment_key {
287 const SslSession *session;
288 uint32_t id;
289 bool from_server;
290 } tls_hs_fragment_key;
292 static unsigned
293 tls_hs_fragment_hash(const void *k)
295 const tls_hs_fragment_key* key = (const tls_hs_fragment_key*) k;
296 return key->id;
299 static int
300 tls_hs_fragment_equal(const void *k1, const void *k2)
302 const tls_hs_fragment_key* key1 = (const tls_hs_fragment_key*) k1;
303 const tls_hs_fragment_key* key2 = (const tls_hs_fragment_key*) k2;
305 return (key1->id == key2->id &&
306 key1->session == key2->session &&
307 key1->from_server == key2->from_server);
310 static void *
311 tls_hs_fragment_temporary_key(const packet_info *pinfo, const uint32_t id,
312 const void *data)
314 tls_hs_fragment_key *key = g_slice_new0(tls_hs_fragment_key);
315 SslSession *session = (SslSession *)data;
316 key->id = id;
317 key->session = session;
318 key->from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
319 return key;
322 static void
323 tls_hs_fragment_free_temporary_key(void *ptr)
325 tls_hs_fragment_key *key = (tls_hs_fragment_key *)ptr;
326 g_slice_free(tls_hs_fragment_key, key);
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,
339 /* initialize/reset per capture state data (ssl sessions cache) */
340 static void
341 ssl_init(void)
343 module_t *ssl_module = prefs_find_module("tls");
344 pref_t *keys_list_pref;
346 ssl_common_init(&ssl_master_key_map,
347 &ssl_decrypted_data, &ssl_compressed_data);
348 ssl_debug_flush();
350 /* We should have loaded "keys_list" by now. Mark it obsolete */
351 if (ssl_module) {
352 keys_list_pref = prefs_find_preference(ssl_module, "keys_list");
353 if (! prefs_get_preference_obsolete(keys_list_pref)) {
354 prefs_set_preference_obsolete(keys_list_pref);
358 /* Reset the identifier for a group of handshake fragments. */
359 hs_reassembly_id_count = 0;
362 static void
363 ssl_cleanup(void)
365 #ifdef HAVE_LIBGNUTLS
366 if (key_list_stack != NULL) {
367 wmem_destroy_stack(key_list_stack);
368 key_list_stack = NULL;
370 #endif
371 ssl_common_cleanup(&ssl_master_key_map, &ssl_keylog_file,
372 &ssl_decrypted_data, &ssl_compressed_data);
375 ssl_master_key_map_t *
376 tls_get_master_key_map(bool load_secrets)
378 // Try to load new keys.
379 if (load_secrets) {
380 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
382 return &ssl_master_key_map;
385 #ifdef HAVE_LIBGNUTLS
386 /* parse ssl related preferences (private keys and ports association strings) */
387 static void
388 ssl_parse_uat(void)
390 unsigned i;
391 uint16_t port;
392 dissector_handle_t handle;
394 ssl_set_debug(ssl_debug_file_name);
396 if (ssl_key_hash)
398 g_hash_table_destroy(ssl_key_hash);
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);
410 /* parse private keys string, load available keys and put them in key hash*/
411 ssl_key_hash = privkey_hash_table_new();
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));
425 ssl_debug_flush();
428 static void
429 ssl_reset_uat(void)
431 g_hash_table_destroy(ssl_key_hash);
432 ssl_key_hash = NULL;
435 static void
436 ssl_parse_old_keys(void)
438 char **old_keys, **parts, *err;
439 char *uat_entry;
440 unsigned i;
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);
458 wmem_free(NULL, uat_entry);
460 g_strfreev(parts);
462 g_strfreev(old_keys);
465 #endif /* HAVE_LIBGNUTLS */
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_)
471 follow_info_t * follow_info = (follow_info_t*) tapdata;
472 follow_record_t * follow_record = NULL;
473 const SslRecordInfo *appl_data = NULL;
474 const SslPacketInfo *pi = (const SslPacketInfo*)ssl;
475 show_stream_t from = FROM_CLIENT;
477 /* Skip packets without decrypted payload data. */
478 if (!pi || !pi->records) return TAP_PACKET_DONT_REDRAW;
480 /* Compute the packet's sender. */
481 if (follow_info->client_port == 0) {
482 follow_info->client_port = pinfo->srcport;
483 copy_address(&follow_info->client_ip, &pinfo->src);
484 follow_info->server_port = pinfo->destport;
485 copy_address(&follow_info->server_ip, &pinfo->dst);
487 if (addresses_equal(&follow_info->client_ip, &pinfo->src) &&
488 follow_info->client_port == pinfo->srcport) {
489 from = FROM_CLIENT;
490 } else {
491 from = FROM_SERVER;
494 for (appl_data = pi->records; appl_data != NULL; appl_data = appl_data->next) {
496 /* Include only application data in the record, skipping things like
497 * Handshake messages and alerts. */
498 if (appl_data->type != SSL_ID_APP_DATA) continue;
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 if (appl_data->seq < follow_info->bytes_written[from]) continue;
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 follow_record = g_new(follow_record_t,1);
519 follow_record->is_server = (from == FROM_SERVER);
520 follow_record->packet_num = pinfo->num;
521 follow_record->abs_ts = pinfo->abs_ts;
523 follow_record->data = g_byte_array_sized_new(appl_data->data_len);
524 follow_record->data = g_byte_array_append(follow_record->data,
525 appl_data->plain_data,
526 appl_data->data_len);
528 /* Add the record to the follow_info structure. */
529 follow_info->payload = g_list_prepend(follow_info->payload, follow_record);
530 follow_info->bytes_written[from] += appl_data->data_len;
533 return TAP_PACKET_DONT_REDRAW;
536 /*********************************************************************
538 * Forward Declarations
540 *********************************************************************/
543 * SSL version 3 and TLS dissectors
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);
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);
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);
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);
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);
583 static void dissect_ssl3_hnd_encrypted_exts(tvbuff_t *tvb,
584 proto_tree *tree,
585 uint32_t offset);
588 * SSL version 2 dissectors
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);
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);
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);
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);
617 * Support Functions
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);
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);
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);
639 /*********************************************************************
641 * Main dissector
643 *********************************************************************/
645 * Code to actually dissect the packets
647 static int
648 dissect_ssl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
651 conversation_t *conversation;
652 proto_item *ti;
653 proto_tree *ssl_tree;
654 uint32_t offset;
655 bool need_desegmentation;
656 SslDecryptSession *ssl_session, *ssl_session_save;
657 SslSession *session;
658 int is_from_server;
659 struct tcpinfo *tcpinfo;
660 struct tlsinfo tlsinfo;
662 * A single packet may contain multiple TLS records. Two possible scenarios:
664 * - Multiple TLS records belonging to the same TLS session.
665 * - TLS within a different encrypted TLS tunnel.
667 * To support the second case, 'curr_layer_num_ssl' is used as identifier
668 * for the current TLS layer.
670 uint8_t curr_layer_num_ssl = pinfo->curr_proto_layer_num;
672 ti = NULL;
673 ssl_tree = NULL;
674 offset = 0;
675 ssl_session = NULL;
677 memset(&tlsinfo, 0, sizeof(tlsinfo));
678 tcpinfo = (struct tcpinfo*)data;
680 if (tvb_captured_length(tvb) > 4) {
681 const uint8_t *tmp = tvb_get_ptr(tvb, 0, 4);
682 if (g_ascii_isprint(tmp[0]) &&
683 g_ascii_isprint(tmp[1]) &&
684 g_ascii_isprint(tmp[2]) &&
685 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 return 0;
697 ssl_debug_printf("\ndissect_ssl enter frame #%u (%s)\n", pinfo->num, (pinfo->fd->visited)?"already visited":"first time");
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.
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
711 /* Get the conversation with the deinterlacing strategy,
712 * assuming it does exist, as created by an underlying proto.
714 conversation = find_conversation_strat(pinfo, conversation_pt_to_conversation_type(pinfo->ptype), 0);
715 if(conversation == NULL) {
716 conversation = conversation_new(pinfo->num, &pinfo->src,
717 &pinfo->dst, conversation_pt_to_conversation_type(pinfo->ptype),
718 pinfo->srcport, pinfo->destport, 0);
722 ssl_session_save = ssl_session = ssl_get_session(conversation, tls_handle);
723 session = &ssl_session->session;
724 is_from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
726 if (session->last_nontls_frame != 0 &&
727 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 return 0;
733 /* try decryption only the first time we see this packet
734 * (to keep cipher synchronized) */
735 if (pinfo->fd->visited)
736 ssl_session = NULL;
738 ssl_debug_printf(" conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl_session);
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 col_set_str(pinfo->cinfo, COL_PROTOCOL,
744 val_to_str_const(session->version, ssl_version_short_names, "SSL"));
745 /* clear the info column */
746 col_clear(pinfo->cinfo, COL_INFO);
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.
752 * This loop accounts for multiple ssl records in a single
753 * frame, but not a single ssl record across multiple tcp
754 * packets.
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.
762 /* Create display subtree for TLS as a whole */
763 if (tree)
765 ti = proto_tree_add_item(tree, proto_tls, tvb, 0, -1, ENC_NA);
766 ssl_tree = proto_item_add_subtree(ti, ett_tls);
768 /* iterate through the records in this tvbuff */
769 while (tvb_reported_length_remaining(tvb, offset) > 0)
771 ssl_debug_printf(" record: offset = %d, reported_length_remaining = %d\n", offset, tvb_reported_length_remaining(tvb, offset));
774 * Assume, for now, that this doesn't need desegmentation.
776 need_desegmentation = false;
778 /* first try to dispatch off the cached version
779 * known to be associated with the conversation
781 switch (session->version) {
782 case SSLV2_VERSION:
783 offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
784 offset, session,
785 &need_desegmentation,
786 ssl_session);
787 break;
789 case SSLV3_VERSION:
790 case TLSV1_VERSION:
791 case TLSV1DOT1_VERSION:
792 case TLSV1DOT2_VERSION:
793 case TLCPV1_VERSION:
794 /* SSLv3/TLS record headers need at least 1+2+2 = 5 bytes. */
795 if (tvb_reported_length_remaining(tvb, offset) < 5) {
796 if (tls_desegment && pinfo->can_desegment) {
797 pinfo->desegment_offset = offset;
798 pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
799 need_desegmentation = true;
800 } else {
801 /* Not enough bytes available. Stop here. */
802 offset = tvb_reported_length(tvb);
804 break;
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
813 if (ssl_is_v2_client_hello(tvb, offset))
815 offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
816 offset, session,
817 &need_desegmentation,
818 ssl_session);
820 else
822 offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
823 offset, session, is_from_server,
824 &need_desegmentation,
825 ssl_session,
826 curr_layer_num_ssl, &tlsinfo);
828 break;
830 /* that failed, so apply some heuristics based
831 * on this individual packet
833 default:
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).
839 if (tvb_reported_length_remaining(tvb, offset) < 5) {
840 if (tls_desegment && pinfo->can_desegment) {
841 pinfo->desegment_offset = offset;
842 pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
843 need_desegmentation = true;
844 } else {
845 /* Not enough bytes available. Stop here. */
846 offset = tvb_reported_length(tvb);
848 break;
851 if (ssl_looks_like_sslv2(tvb, offset))
853 /* looks like sslv2 client hello */
854 offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
855 offset, session,
856 &need_desegmentation,
857 ssl_session);
859 else if (ssl_looks_like_sslv3(tvb, offset))
861 /* looks like sslv3 or tls */
862 offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
863 offset, session, is_from_server,
864 &need_desegmentation,
865 ssl_session,
866 curr_layer_num_ssl, &tlsinfo);
868 else
870 /* looks like something unknown, so lump into
871 * continuation data
873 offset = tvb_reported_length(tvb);
874 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
876 break;
879 /* Desegmentation return check */
880 if (need_desegmentation) {
881 ssl_debug_printf(" need_desegmentation: offset = %d, reported_length_remaining = %d\n",
882 offset, tvb_reported_length_remaining(tvb, offset));
883 /* Make data available to ssl_follow_tap_listener */
884 tap_queue_packet(tls_follow_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_ssl));
885 return tvb_captured_length(tvb);
889 unsigned ret = tvb_captured_length(tvb);
891 /* Check for needing to reassemble at end of stream */
892 ssl_session = ssl_session_save;
893 if (ssl_session) {
894 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 if (is_from_server != 0) {
900 decoder = ssl_session->server;
902 else {
903 decoder = ssl_session->client;
906 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.)
917 if (tcpinfo) {
918 tlsinfo.end_of_stream |= (tcpinfo->flags & TH_FIN);
920 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.
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.)
931 pinfo->desegment_offset = tvb_captured_length(tvb);
932 pinfo->desegment_len = DESEGMENT_UNTIL_FIN;
933 } else {
934 ssl_debug_printf(" desegmenting at end of stream (FIN)\n");
935 struct tcp_multisegment_pdu *msp;
936 msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(decoder->flow->multisegment_pdus, decoder->flow->byte_seq);
937 if (msp) {
938 fragment_head *ipfd_head;
939 ipfd_head = fragment_add(&ssl_reassembly_table, tvb, offset,
940 pinfo, tls_msp_fragment_id(msp), msp,
941 decoder->flow->byte_seq - msp->seq,
942 0, false);
943 if (ipfd_head && ipfd_head->reassembled_in == pinfo->num) {
944 tvbuff_t *next_tvb;
946 /* create a new TVB structure for desegmented data */
947 next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);
949 /* add desegmented data to the data source list */
950 add_new_data_source(pinfo, next_tvb, "Reassembled TLS");
952 /* Show details of the reassembly */
953 print_tls_fragment_tree(ipfd_head, tree, ssl_tree, pinfo, next_tvb);
956 * Supply the sequence number of the first of the
957 * reassembled bytes.
959 tlsinfo.seq = msp->seq;
961 /* indicate that this is reassembled data */
962 tlsinfo.is_reassembled = true;
964 /* call subdissector */
965 process_ssl_payload(next_tvb, 0, pinfo, tree, session, session->app_handle, &tlsinfo);
967 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.)
978 ret = 1;
987 col_set_fence(pinfo->cinfo, COL_INFO);
989 ssl_debug_flush();
991 /* Make data available to ssl_follow_tap_listener */
992 tap_queue_packet(tls_follow_tap, pinfo, p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_ssl));
994 return ret;
999 * Dissect ECHConfigList structure, for use by the DNS dissector.
1001 static int
1002 dissect_tls_echconfig(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
1004 return ssl_dissect_ext_ech_echconfiglist(&dissect_ssl3_hf, tvb, pinfo,
1005 tree, 0, tvb_reported_length(tvb));
1009 * Dissect TLS 1.3 handshake messages (without the record layer).
1010 * For use by QUIC (draft -13).
1012 static int
1013 dissect_tls13_handshake(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1016 conversation_t *conversation;
1017 SslDecryptSession *ssl_session;
1018 SslSession *session;
1019 int is_from_server;
1020 proto_item *ti;
1021 proto_tree *ssl_tree;
1023 * A value that uniquely identifies this fragment in this frame.
1025 unsigned record_id = GPOINTER_TO_UINT(data);
1027 ssl_debug_printf("\n%s enter frame #%u (%s)\n", G_STRFUNC, pinfo->num, (pinfo->fd->visited)?"already visited":"first time");
1029 conversation = find_or_create_conversation(pinfo);
1030 ssl_session = ssl_get_session(conversation, tls_handle);
1031 session = &ssl_session->session;
1032 is_from_server = ssl_packet_from_server(session, ssl_associations, pinfo);
1033 if (session->version == SSL_VER_UNKNOWN) {
1034 session->version = TLSV1DOT3_VERSION;
1035 ssl_session->state |= SSL_VERSION;
1036 ssl_session->state |= SSL_QUIC_RECORD_LAYER;
1040 * First pass: collect state (including Client Random for key matching).
1041 * Second pass: dissection only, no need to collect state.
1043 if (PINFO_FD_VISITED(pinfo)) {
1044 ssl_session = NULL;
1047 ssl_debug_printf(" conversation = %p, ssl_session = %p, from_server = %d\n",
1048 (void *)conversation, (void *)ssl_session, is_from_server);
1050 /* Add a proto_tls item to allow simple "tls" display filter */
1051 ti = proto_tree_add_item(tree, proto_tls, tvb, 0, -1, ENC_NA);
1052 ssl_tree = proto_item_add_subtree(ti, ett_tls);
1054 dissect_tls_handshake(tvb, pinfo, ssl_tree, 0,
1055 tvb_reported_length(tvb), false, record_id, pinfo->curr_layer_num, session,
1056 is_from_server, ssl_session, TLSV1DOT3_VERSION);
1058 ssl_debug_flush();
1060 return tvb_captured_length(tvb);
1063 static bool
1064 is_sslv3_or_tls(tvbuff_t *tvb)
1066 uint8_t content_type;
1067 uint16_t protocol_version, record_length;
1070 * Heuristics should match the TLS record header.
1071 * ContentType (1), ProtocolVersion (2), Length (2)
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.
1076 if (tvb_captured_length(tvb) < 5) {
1077 return false;
1080 content_type = tvb_get_uint8(tvb, 0);
1081 protocol_version = tvb_get_ntohs(tvb, 1);
1082 record_length = tvb_get_ntohs(tvb, 3);
1084 /* These are the common types. */
1085 if (content_type != SSL_ID_HANDSHAKE && content_type != SSL_ID_APP_DATA) {
1086 return false;
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.
1095 if (protocol_version != SSLV3_VERSION &&
1096 protocol_version != TLSV1_VERSION &&
1097 protocol_version != TLSV1DOT1_VERSION &&
1098 protocol_version != TLSV1DOT2_VERSION &&
1099 protocol_version != TLCPV1_VERSION ) {
1100 return false;
1103 /* Check for sane length, see also ssl_check_record_length in packet-tls-utils.c */
1104 if (record_length == 0 || record_length >= TLS_MAX_RECORD_LENGTH + 2048) {
1105 return false;
1108 return true;
1111 static bool
1112 is_sslv2_clienthello(tvbuff_t *tvb)
1115 * Detect SSL 2.0 compatible Client Hello as used in SSLv3 and TLS.
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;
1133 if (tvb_captured_length(tvb) < 46) {
1134 return false;
1137 /* Assume that message length is less than 256 (at most 64 cipherspecs). */
1138 if (tvb_get_uint8(tvb, 0) != 0x80) {
1139 return false;
1142 /* msg_type must be 1 for Client Hello */
1143 if (tvb_get_uint8(tvb, 2) != 1) {
1144 return false;
1147 /* cipher spec length must be a non-zero multiple of 3 */
1148 uint16_t cipher_spec_length = tvb_get_ntohs(tvb, 5);
1149 if (cipher_spec_length == 0 || cipher_spec_length % 3 != 0) {
1150 return false;
1153 /* session ID length must be 0 or 16 in TLS 1.0 */
1154 uint16_t session_id_length = tvb_get_ntohs(tvb, 7);
1155 if (session_id_length != 0 && session_id_length != 16) {
1156 return false;
1159 /* Challenge Length must be 32 */
1160 if (tvb_get_ntohs(tvb, 9) != 32) {
1161 return false;
1164 return true;
1167 static bool
1168 dissect_ssl_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
1170 conversation_t *conversation;
1172 if (!is_sslv3_or_tls(tvb) && !is_sslv2_clienthello(tvb)) {
1173 return false;
1176 conversation = find_or_create_conversation(pinfo);
1177 conversation_set_dissector_from_frame_number(conversation, pinfo->num, tls_handle);
1178 return dissect_ssl(tvb, pinfo, tree, data) > 0;
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)
1185 const unsigned char *data = ssl_decrypted_data.data;
1186 unsigned datalen = ssl_decrypted_data_avail;
1188 if (datalen == 0) {
1189 return;
1192 if (ssl->session.version == TLSV1DOT3_VERSION) {
1194 * The actual data is followed by the content type and then zero or
1195 * more padding. Scan backwards for content type, skipping padding.
1197 while (datalen > 0 && data[datalen - 1] == 0) {
1198 datalen--;
1200 ssl_debug_printf("%s found %d padding bytes\n", G_STRFUNC, ssl_decrypted_data_avail - datalen);
1201 if (datalen == 0) {
1202 ssl_debug_printf("%s there is no room for content type!\n", G_STRFUNC);
1203 return;
1205 content_type = data[--datalen];
1206 if (datalen == 0) {
1208 * XXX zero-length Handshake fragments are forbidden by RFC 8446,
1209 * Section 5.1. Empty Application Data fragments are allowed though.
1211 return;
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 ssl_add_record_info(proto_tls, pinfo, data, datalen, record_id,
1219 allow_fragments ? decoder->flow : NULL, (ContentType)content_type, curr_layer_num_ssl);
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".
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)
1232 bool success;
1233 int direction;
1234 StringInfo *data_for_iv;
1235 int data_for_iv_len, data_for_iv_offset;
1236 SslDecoder *decoder;
1238 /* if we can decrypt and decryption was a success
1239 * add decrypted data to this packet info */
1240 ssl_debug_printf("decrypt_ssl3_record: app_data len %d, ssl state 0x%02X\n",
1241 record_length, ssl->state);
1242 direction = ssl_packet_from_server(&ssl->session, ssl_associations, pinfo);
1244 /* retrieve decoder for this packet direction */
1245 if (direction != 0) {
1246 ssl_debug_printf("decrypt_ssl3_record: using server decoder\n");
1247 decoder = ssl->server;
1249 else {
1250 ssl_debug_printf("decrypt_ssl3_record: using client decoder\n");
1251 decoder = ssl->client;
1254 /* save data to update IV if decoder is available or updated later */
1255 data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
1256 data_for_iv_len = (record_length < 24) ? record_length : 24;
1257 data_for_iv_offset = offset + record_length - data_for_iv_len;
1258 if (!tvb_bytes_exist(tvb, data_for_iv_offset, data_for_iv_len)) {
1259 ssl_debug_printf("decrypt_ssl3_record: record truncated\n");
1260 return false;
1262 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);
1264 if (!decoder) {
1265 ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
1266 return false;
1269 /* run decryption and add decrypted payload to protocol data, if decryption
1270 * is successful*/
1271 ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1272 success = ssl_decrypt_record(ssl, decoder, content_type, record_version, tls_ignore_mac_failed,
1273 tvb_get_ptr(tvb, offset, record_length), record_length, NULL, 0,
1274 &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1275 /* */
1276 if (!success) {
1277 /* save data to update IV if valid session key is obtained later */
1278 data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
1279 data_for_iv_len = (record_length < 24) ? record_length : 24;
1280 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);
1282 if (success) {
1283 tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, content_type, decoder, allow_fragments, curr_layer_num_ssl);
1285 return success;
1289 * Try to guess the early data cipher using trial decryption.
1290 * Requires Libgcrypt 1.6 or newer for verifying that decryption is successful.
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)
1298 bool success = false;
1300 ssl_debug_printf("Trying early data encryption, first record / trial decryption: %s\n",
1301 !(ssl->state & SSL_SEEN_0RTT_APPDATA) ? "true" : "false");
1303 /* Only try trial decryption for the first record. */
1304 if (ssl->state & SSL_SEEN_0RTT_APPDATA) {
1305 if (!ssl->client) {
1306 return false; // sanity check, should not happen in valid captures.
1309 ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1310 success = ssl_decrypt_record(ssl, ssl->client, SSL_ID_APP_DATA, 0x303, false,
1311 tvb_get_ptr(tvb, offset, record_length), record_length, NULL, 0,
1312 &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1313 if (success) {
1314 tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, SSL_ID_APP_DATA, ssl->client, true, curr_layer_num_ssl);
1315 } else {
1316 ssl_debug_printf("early data decryption failed, end of early data?\n");
1318 return success;
1320 ssl->state |= SSL_SEEN_0RTT_APPDATA;
1322 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
1323 StringInfo *secret = tls13_load_secret(ssl, &ssl_master_key_map, false, TLS_SECRET_0RTT_APP);
1324 if (!secret) {
1325 ssl_debug_printf("Missing secrets, early data decryption not possible!\n");
1326 return false;
1329 static const uint16_t tls13_ciphers[] = {
1330 0x1301, /* TLS_AES_128_GCM_SHA256 */
1331 0x1302, /* TLS_AES_256_GCM_SHA384 */
1332 0x1303, /* TLS_CHACHA20_POLY1305_SHA256 */
1333 0x1304, /* TLS_AES_128_CCM_SHA256 */
1334 0x1305, /* TLS_AES_128_CCM_8_SHA256 */
1335 0x00c6, /* TLS_SM4_GCM_SM3 */
1337 const unsigned char *record = tvb_get_ptr(tvb, offset, record_length);
1338 for (unsigned i = 0; i < G_N_ELEMENTS(tls13_ciphers); i++) {
1339 uint16_t cipher = tls13_ciphers[i];
1341 ssl_debug_printf("Performing early data trial decryption, cipher = %#x\n", cipher);
1342 ssl->session.cipher = cipher;
1343 ssl->cipher_suite = ssl_find_cipher(cipher);
1344 if (!tls13_generate_keys(ssl, secret, false)) {
1345 /* Unable to create cipher (old Libgcrypt) */
1346 continue;
1349 ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
1350 success = ssl_decrypt_record(ssl, ssl->client, SSL_ID_APP_DATA, 0x303, false, record, record_length, NULL, 0,
1351 &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0;
1352 if (success) {
1353 ssl_debug_printf("Early data decryption succeeded, cipher = %#x\n", cipher);
1354 tls_save_decrypted_record(pinfo, tvb_raw_offset(tvb)+offset, ssl, SSL_ID_APP_DATA, ssl->client, true, curr_layer_num_ssl);
1355 break;
1358 if (!success) {
1359 ssl_debug_printf("Trial decryption of early data failed!\n");
1361 return success;
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)
1367 proto_item *tls_tree_item, *frag_tree_item;
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.
1375 show_fragment_tree(ipfd_head, &ssl_segment_items,
1376 tree, pinfo, next_tvb, &frag_tree_item);
1378 * The toplevel fragment subtree is now
1379 * behind all desegmented data; move it
1380 * right behind the TLS tree.
1382 tls_tree_item = proto_tree_get_parent(tls_tree);
1383 if (frag_tree_item && tls_tree_item) {
1384 proto_tree_move_item(tree, tls_tree_item, frag_tree_item);
1388 static uint32_t
1389 tls_msp_fragment_id(struct tcp_multisegment_pdu *msp)
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.
1399 uint32_t id = msp->first_frame;
1400 #if 0
1401 id ^= (msp->seq & 0xff) << 24;
1402 id ^= (msp->seq & 0xff00) << 16;
1403 #endif
1404 return id;
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)
1415 fragment_head *ipfd_head;
1416 bool must_desegment;
1417 bool called_dissector;
1418 int another_pdu_follows;
1419 bool another_segment_in_frame = false;
1420 int deseg_offset;
1421 uint32_t deseg_seq;
1422 int nbytes;
1423 proto_item *item;
1424 struct tcp_multisegment_pdu *msp;
1426 again:
1427 ipfd_head = NULL;
1428 must_desegment = false;
1429 called_dissector = false;
1430 another_pdu_follows = 0;
1431 msp = NULL;
1434 * Initialize these to assume no desegmentation.
1435 * If that's not the case, these will be set appropriately
1436 * by the subdissector.
1438 pinfo->desegment_offset = 0;
1439 pinfo->desegment_len = 0;
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.
1447 deseg_offset = offset;
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).
1456 if ((msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32(flow->multisegment_pdus, seq))) {
1457 const char *prefix;
1458 bool is_retransmission = false;
1460 if (msp->first_frame == pinfo->num) {
1461 /* This must be after the first pass. */
1462 prefix = "";
1463 if (msp->last_frame == pinfo->num) {
1464 col_clear(pinfo->cinfo, COL_INFO);
1465 } else {
1466 col_set_str(pinfo->cinfo, COL_INFO, "[TLS segment of a reassembled PDU]");
1468 } else {
1469 prefix = "Retransmitted ";
1470 is_retransmission = true;
1473 if (!is_retransmission) {
1474 ipfd_head = fragment_get(&ssl_reassembly_table, pinfo, msp->first_frame, msp);
1475 if (ipfd_head != NULL && ipfd_head->reassembled_in !=0 &&
1476 ipfd_head->reassembled_in != pinfo->num) {
1477 /* Show what frame this was reassembled in if not this one. */
1478 item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
1479 tvb, 0, 0, ipfd_head->reassembled_in);
1480 proto_item_set_generated(item);
1483 nbytes = tvb_reported_length_remaining(tvb, offset);
1484 ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, prefix);
1485 return;
1488 /* Else, find the most previous PDU starting before this sequence number */
1489 msp = (struct tcp_multisegment_pdu *)wmem_tree_lookup32_le(flow->multisegment_pdus, seq-1);
1490 if (msp && msp->seq <= seq && msp->nxtpdu > seq) {
1491 int len;
1493 if (!PINFO_FD_VISITED(pinfo)) {
1494 msp->last_frame = pinfo->num;
1495 msp->last_frame_time = pinfo->abs_ts;
1498 /* OK, this PDU was found, which means the segment continues
1499 * a higher-level PDU and that we must desegment it.
1501 if (msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
1502 /* The dissector asked for the entire segment */
1503 len = MAX(0, tvb_reported_length_remaining(tvb, offset));
1504 } else {
1505 len = MIN(nxtseq, msp->nxtpdu) - seq;
1508 ipfd_head = fragment_add(&ssl_reassembly_table, tvb, offset,
1509 pinfo, tls_msp_fragment_id(msp), msp,
1510 seq - msp->seq,
1511 len, (LT_SEQ (nxtseq,msp->nxtpdu)));
1513 if (!PINFO_FD_VISITED(pinfo)
1514 && msp->flags & MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT) {
1515 msp->flags &= (~MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT);
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.)
1525 msp->nxtpdu = nxtseq;
1528 if ( (msp->nxtpdu < nxtseq)
1529 && (msp->nxtpdu >= seq)
1530 && (len > 0)) {
1531 another_pdu_follows = msp->nxtpdu - seq;
1533 } 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.
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.
1544 tlsinfo->seq = seq;
1546 process_ssl_payload(tvb, offset, pinfo, tree, session, app_handle_port, tlsinfo);
1547 called_dissector = true;
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.
1555 if (pinfo->desegment_len) {
1556 if (!PINFO_FD_VISITED(pinfo))
1557 must_desegment = true;
1560 * Set "deseg_offset" to the offset in "tvb"
1561 * of the first byte of data that the
1562 * subdissector didn't process.
1564 deseg_offset = offset + pinfo->desegment_offset;
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.
1572 ipfd_head = NULL;
1576 /* is it completely desegmented? */
1577 if (ipfd_head && ipfd_head->reassembled_in == pinfo->num) {
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.
1584 if (nxtseq < msp->nxtpdu) {
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.)
1595 another_pdu_follows = 0;
1596 col_clear(pinfo->cinfo, COL_INFO);
1597 another_segment_in_frame = true;
1598 } else {
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.
1605 tvbuff_t *next_tvb;
1606 int old_len;
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?
1614 /* Clear column during the first pass. */
1615 col_clear(pinfo->cinfo, COL_INFO);
1617 /* create a new TVB structure for desegmented data */
1618 next_tvb = tvb_new_chain(tvb, ipfd_head->tvb_data);
1620 /* add desegmented data to the data source list */
1621 add_new_data_source(pinfo, next_tvb, "Reassembled TLS");
1624 * Supply the sequence number of the first of the
1625 * reassembled bytes.
1627 tlsinfo->seq = msp->seq;
1629 /* indicate that this is reassembled data */
1630 tlsinfo->is_reassembled = true;
1632 /* call subdissector */
1633 process_ssl_payload(next_tvb, 0, pinfo, tree, session, app_handle_port, tlsinfo);
1634 called_dissector = true;
1637 * OK, did the subdissector think it was completely
1638 * desegmented, or does it think we need even more
1639 * data?
1641 old_len = (int)(tvb_reported_length(next_tvb) - tvb_reported_length_remaining(tvb, offset));
1642 if (pinfo->desegment_len && pinfo->desegment_offset <= old_len) {
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).
1654 fragment_set_partial_reassembly(&ssl_reassembly_table,
1655 pinfo, tls_msp_fragment_id(msp), msp);
1656 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 remove_last_data_source(pinfo);
1661 /* Update msp->nxtpdu to point to the new next
1662 * pdu boundary.
1664 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.
1673 msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + 1;
1674 msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
1675 } 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).
1682 flow->flags |= TCP_FLOW_REASSEMBLE_UNTIL_FIN;
1683 msp->nxtpdu = nxtseq + 0x40000000;
1684 } else {
1685 msp->nxtpdu = seq + tvb_reported_length_remaining(tvb, offset) + pinfo->desegment_len;
1687 /* Since we need at least some more data
1688 * there can be no pdu following in the
1689 * tail of this segment.
1691 another_pdu_follows = 0;
1692 } else {
1694 * Show the stuff in this TCP segment as
1695 * just raw TCP segment data.
1697 nbytes = tvb_reported_length_remaining(tvb, offset);
1698 ssl_proto_tree_add_segment_data(tree, tvb, offset, nbytes, NULL);
1700 /* Show details of the reassembly */
1701 print_tls_fragment_tree(ipfd_head, root_tree, tree, pinfo, next_tvb);
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.
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.
1714 if (pinfo->desegment_len) {
1715 if (!PINFO_FD_VISITED(pinfo))
1716 must_desegment = true;
1718 /* The stuff we couldn't dissect
1719 * must have come from this segment,
1720 * so it's all in "tvb".
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".
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.
1737 deseg_offset = ipfd_head->datalen - pinfo->desegment_offset;
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.
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.
1753 deseg_offset = tvb_reported_length(tvb) - deseg_offset;
1759 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.
1766 if (pinfo->desegment_len == DESEGMENT_UNTIL_FIN) {
1767 flow->flags |= TCP_FLOW_REASSEMBLE_UNTIL_FIN;
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".
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)".
1779 deseg_seq = seq + (deseg_offset - offset);
1781 if (((nxtseq - deseg_seq) <= 1024*1024)
1782 && (!PINFO_FD_VISITED(pinfo))) {
1783 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.
1790 msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
1791 deseg_seq, nxtseq+1, flow->multisegment_pdus);
1792 msp->flags |= MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
1793 } 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.
1798 msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
1799 deseg_seq, nxtseq+0x40000000, flow->multisegment_pdus);
1800 } else {
1801 msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
1802 deseg_seq, nxtseq+pinfo->desegment_len, flow->multisegment_pdus);
1805 /* add this segment as the first one for this new pdu */
1806 fragment_add(&ssl_reassembly_table, tvb, deseg_offset,
1807 pinfo, tls_msp_fragment_id(msp), msp,
1808 0, nxtseq - deseg_seq,
1809 LT_SEQ(nxtseq, msp->nxtpdu));
1813 if (!called_dissector || pinfo->desegment_len != 0) {
1814 if (ipfd_head != NULL && ipfd_head->reassembled_in != 0 &&
1815 ipfd_head->reassembled_in != pinfo->num &&
1816 !(ipfd_head->flags & FD_PARTIAL_REASSEMBLY)) {
1818 * We know what other frame this PDU is reassembled in;
1819 * let the user know.
1821 item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
1822 tvb, 0, 0, ipfd_head->reassembled_in);
1823 proto_item_set_generated(item);
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).
1835 if (!another_segment_in_frame && pinfo->desegment_offset == 0) {
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.
1843 col_set_str(pinfo->cinfo, COL_PROTOCOL,
1844 val_to_str_const(session->version, ssl_version_short_names, "SSL"));
1845 col_set_str(pinfo->cinfo, COL_INFO, "[TLS segment of a reassembled PDU]");
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?
1854 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
1855 ssl_proto_tree_add_segment_data(tree, tvb, deseg_offset, nbytes, NULL);
1857 pinfo->can_desegment = 0;
1858 pinfo->desegment_offset = 0;
1859 pinfo->desegment_len = 0;
1861 if (another_pdu_follows) {
1862 /* there was another pdu following this one. */
1863 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>
1869 col_set_fence(pinfo->cinfo, COL_INFO);
1870 col_set_writable(pinfo->cinfo, COL_PROTOCOL, false);
1871 offset += another_pdu_follows;
1872 seq += another_pdu_follows;
1873 goto again;
1877 static void
1878 export_pdu_packet(tvbuff_t *tvb, packet_info *pinfo, uint8_t tag, const char *name)
1880 exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, name, tag);
1882 exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
1883 exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
1884 exp_pdu_data->pdu_tvb = tvb;
1886 tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
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)
1895 tvbuff_t *next_tvb;
1896 heur_dtbl_entry_t *hdtbl_entry;
1897 uint16_t saved_match_port, app_port;
1898 bool heur_first;
1900 tlsinfo->app_handle = &session->app_handle;
1902 next_tvb = tvb_new_subset_remaining(tvb, offset);
1904 if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
1905 app_port = pinfo->srcport;
1906 } else {
1907 app_port = pinfo->destport;
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 if (!session->app_handle) {
1912 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 if (heur_first && dissector_try_heuristic(ssl_heur_subdissector_list,
1916 next_tvb, pinfo, proto_tree_get_root(tree), &hdtbl_entry,
1917 tlsinfo)) {
1918 ssl_debug_printf("%s: found heuristics dissector %s, app_handle is %p (%s)\n",
1919 G_STRFUNC, hdtbl_entry->short_name,
1920 (void *)session->app_handle,
1921 dissector_handle_get_dissector_name(session->app_handle));
1922 if (have_tap_listener(exported_pdu_tap)) {
1923 export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_HEUR_DISSECTOR_NAME, hdtbl_entry->short_name);
1925 return;
1927 if (app_handle_port) {
1928 /* Heuristics failed, just try the port-based dissector. */
1929 ssl_debug_printf("%s: no heuristics dissector, falling back to "
1930 "handle %p (%s)\n", G_STRFUNC,
1931 (void *)app_handle_port,
1932 dissector_handle_get_dissector_name(app_handle_port));
1933 session->app_handle = app_handle_port;
1934 } else if (!heur_first && dissector_try_heuristic(ssl_heur_subdissector_list,
1935 next_tvb, pinfo, proto_tree_get_root(tree), &hdtbl_entry,
1936 tlsinfo)) {
1937 ssl_debug_printf("%s: found heuristics dissector %s, app_handle is %p (%s)\n",
1938 G_STRFUNC, hdtbl_entry->short_name,
1939 (void *)session->app_handle,
1940 dissector_handle_get_dissector_name(session->app_handle));
1941 if (have_tap_listener(exported_pdu_tap)) {
1942 export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_HEUR_DISSECTOR_NAME, hdtbl_entry->short_name);
1944 return;
1945 } else {
1946 /* No heuristics, no port-based proto, unknown protocol. */
1947 ssl_debug_printf("%s: no appdata dissector found\n", G_STRFUNC);
1948 call_data_dissector(next_tvb, pinfo, proto_tree_get_root(tree));
1949 return;
1953 ssl_debug_printf("%s: found handle %p (%s)\n", G_STRFUNC,
1954 (void *)session->app_handle,
1955 dissector_handle_get_dissector_name(session->app_handle));
1957 if (have_tap_listener(exported_pdu_tap)) {
1958 export_pdu_packet(next_tvb, pinfo, EXP_PDU_TAG_DISSECTOR_NAME,
1959 dissector_handle_get_dissector_name(session->app_handle));
1961 saved_match_port = pinfo->match_uint;
1962 pinfo->match_uint = app_port;
1963 call_dissector_with_data(session->app_handle, next_tvb, pinfo, proto_tree_get_root(tree), tlsinfo);
1964 pinfo->match_uint = saved_match_port;
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)
1974 bool save_fragmented;
1975 uint16_t save_can_desegment;
1977 tlsinfo->seq = record->seq;
1979 /* Preserve current desegmentation ability to prevent the subdissector
1980 * from messing up the ssl desegmentation */
1981 save_can_desegment = pinfo->can_desegment;
1983 /* try to dissect decrypted data*/
1984 ssl_debug_printf("%s decrypted len %d\n", G_STRFUNC, record->data_len);
1985 ssl_print_data("decrypted app data fragment", record->plain_data, record->data_len);
1987 /* Can we desegment this segment? */
1988 if (tls_desegment_app_data) {
1989 /* Yes. */
1990 pinfo->can_desegment = 2;
1991 desegment_ssl(decrypted, pinfo, 0, record->seq, record->seq + record->data_len,
1992 session, proto_tree_get_root(tree), tree,
1993 record->flow, app_handle_port, tlsinfo);
1994 } 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 pinfo->can_desegment = 0;
1999 save_fragmented = pinfo->fragmented;
2000 pinfo->fragmented = true;
2002 process_ssl_payload(decrypted, 0, pinfo, tree, session, app_handle_port, tlsinfo);
2003 pinfo->fragmented = save_fragmented;
2006 /* restore desegmentation ability */
2007 pinfo->can_desegment = save_can_desegment;
2011 /*********************************************************************
2013 * SSL version 3 and TLS Dissection Routines
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)
2026 * struct {
2027 * uint8 major, minor;
2028 * } ProtocolVersion;
2031 * enum {
2032 * change_cipher_spec(20), alert(21), handshake(22),
2033 * application_data(23), (255)
2034 * } ContentType;
2036 * struct {
2037 * ContentType type;
2038 * ProtocolVersion version;
2039 * uint16 length;
2040 * opaque fragment[TLSPlaintext.length];
2041 * } TLSPlaintext;
2043 uint32_t record_length;
2044 uint16_t record_version, version;
2045 uint8_t content_type;
2046 uint8_t next_byte;
2047 proto_tree *ti;
2048 proto_tree *ssl_record_tree;
2049 proto_item *length_pi, *ct_pi;
2050 unsigned content_type_offset;
2051 uint32_t available_bytes;
2052 tvbuff_t *decrypted;
2053 SslRecordInfo *record = NULL;
2055 ti = NULL;
2056 ssl_record_tree = NULL;
2058 available_bytes = tvb_reported_length_remaining(tvb, offset);
2060 /* TLS 1.0/1.1 just ignores unknown records - RFC 2246 chapter 6. The TLS Record Protocol */
2061 if ((session->version==TLSV1_VERSION ||
2062 session->version==TLSV1DOT1_VERSION ||
2063 session->version==TLSV1DOT2_VERSION ||
2064 session->version==TLCPV1_VERSION ) &&
2065 (available_bytes >=1 ) && !ssl_is_valid_content_type(tvb_get_uint8(tvb, offset))) {
2066 proto_tree_add_expert(tree, pinfo, &ei_tls_ignored_unknown_record, tvb, offset, available_bytes);
2067 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Ignored Unknown Record");
2068 return offset + available_bytes;
2072 * Is the record header split across segment boundaries?
2074 if (available_bytes < 5) {
2076 * Yes - can we do reassembly?
2078 ssl_proto_tree_add_segment_data(tree, tvb, offset, -1, NULL);
2079 if (tls_desegment && pinfo->can_desegment) {
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.
2087 pinfo->desegment_offset = offset;
2088 pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
2089 *need_desegmentation = true;
2090 return offset;
2091 } else {
2092 /* Not enough bytes available. Stop here. */
2093 return offset + available_bytes;
2098 * Get the record layer fields of interest
2100 content_type = tvb_get_uint8(tvb, offset);
2101 version = tvb_get_ntohs(tvb, offset + 1);
2102 record_version = version;
2103 record_length = tvb_get_ntohs(tvb, offset + 3);
2105 if (ssl_is_valid_content_type(content_type)) {
2108 * Is the record split across segment boundaries?
2110 if (available_bytes < record_length + 5) {
2112 * Yes - can we do reassembly?
2114 ssl_proto_tree_add_segment_data(tree, tvb, offset, -1, NULL);
2115 if (tls_desegment && pinfo->can_desegment) {
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.
2121 pinfo->desegment_offset = offset;
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
2130 pinfo->desegment_len = (record_length + 5) - available_bytes;
2131 *need_desegmentation = true;
2132 return offset;
2133 } else {
2134 /* Not enough bytes available. Stop here. */
2135 return offset + available_bytes;
2139 } else {
2140 /* if we don't have a valid content_type, there's no sense
2141 * continuing any further
2143 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
2145 return offset + 5 + record_length;
2148 /* add the record layer subtree header */
2149 ti = proto_tree_add_item(tree, hf_tls_record, tvb,
2150 offset, 5 + record_length, ENC_NA);
2151 ssl_record_tree = proto_item_add_subtree(ti, ett_tls_record);
2153 /* show the one-byte content type */
2154 if (session->version == TLSV1DOT3_VERSION && content_type == SSL_ID_APP_DATA) {
2155 ct_pi = proto_tree_add_item(ssl_record_tree, hf_tls_record_opaque_type,
2156 tvb, offset, 1, ENC_BIG_ENDIAN);
2157 } else {
2158 ct_pi = proto_tree_add_item(ssl_record_tree, hf_tls_record_content_type,
2159 tvb, offset, 1, ENC_BIG_ENDIAN);
2161 content_type_offset = offset;
2162 offset++;
2164 /* add the version */
2165 proto_tree_add_item(ssl_record_tree, hf_tls_record_version, tvb,
2166 offset, 2, ENC_BIG_ENDIAN);
2167 offset += 2;
2169 /* add the length */
2170 length_pi = proto_tree_add_uint(ssl_record_tree, hf_tls_record_length, tvb,
2171 offset, 2, record_length);
2172 offset += 2; /* move past length field itself */
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).
2182 next_byte = tvb_get_uint8(tvb, offset);
2183 if (session->version == SSL_VER_UNKNOWN) {
2184 ssl_try_set_version(session, ssl, content_type, next_byte, false, version);
2185 /* Version has possibly changed, adjust the column accordingly. */
2186 col_set_str(pinfo->cinfo, COL_PROTOCOL,
2187 val_to_str_const(version, ssl_version_short_names, "SSL"));
2188 } else {
2189 version = session->version;
2193 * now dissect the next layer
2195 ssl_debug_printf("dissect_ssl3_record: content_type %d %s\n",content_type, val_to_str_const(content_type, ssl_31_content_type, "unknown"));
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.
2205 if (ssl && record_length && (session->version != TLSV1DOT3_VERSION || content_type == SSL_ID_APP_DATA)) {
2206 bool decrypt_ok = false;
2208 /* Try to decrypt TLS 1.3 early data first */
2209 if (session->version == TLSV1DOT3_VERSION && content_type == SSL_ID_APP_DATA &&
2210 ssl->has_early_data && !ssl_packet_from_server(session, ssl_associations, pinfo)) {
2211 decrypt_ok = decrypt_tls13_early_data(tvb, pinfo, offset, record_length, ssl, curr_layer_num_ssl);
2212 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 if (ssl->state & SSL_SERVER_RANDOM) {
2216 tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
2218 ssl->has_early_data = false;
2222 if (!decrypt_ok) {
2223 decrypt_ssl3_record(tvb, pinfo, offset, ssl,
2224 content_type, record_version, record_length,
2225 content_type == SSL_ID_APP_DATA ||
2226 content_type == SSL_ID_HANDSHAKE, curr_layer_num_ssl);
2230 /* try to retrieve and use decrypted alert/handshake/appdata record, if any. */
2231 decrypted = ssl_get_record_info(tvb, proto_tls, pinfo, tvb_raw_offset(tvb)+offset, curr_layer_num_ssl, &record);
2232 if (decrypted) {
2233 add_new_data_source(pinfo, decrypted, "Decrypted TLS");
2234 if (session->version == TLSV1DOT3_VERSION) {
2235 content_type = record->type;
2236 ti = proto_tree_add_uint(ssl_record_tree, hf_tls_record_content_type,
2237 tvb, content_type_offset, 1, record->type);
2238 proto_item_set_generated(ti);
2241 ssl_check_record_length(&dissect_ssl3_hf, pinfo, (ContentType)content_type, record_length, length_pi, version, decrypted);
2243 switch ((ContentType) content_type) {
2244 case SSL_ID_CHG_CIPHER_SPEC:
2245 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 expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
2248 "Record type is not allowed in TLS 1.3");
2249 break;
2251 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Change Cipher Spec");
2252 ssl_dissect_change_cipher_spec(&dissect_ssl3_hf, tvb, pinfo,
2253 ssl_record_tree, offset, session,
2254 is_from_server, ssl);
2255 if (version == TLSV1DOT3_VERSION) {
2256 /* CCS is a dummy message in TLS 1.3, do not try to load keys. */
2257 break;
2259 if (ssl) {
2260 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
2261 &ssl_master_key_map);
2262 ssl_finalize_decryption(ssl, &ssl_master_key_map);
2263 ssl_change_cipher(ssl, ssl_packet_from_server(session, ssl_associations, pinfo));
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 if (is_from_server)
2269 session->is_session_resumed = false;
2270 break;
2271 case SSL_ID_ALERT:
2272 if (decrypted) {
2273 dissect_ssl3_alert(decrypted, pinfo, ssl_record_tree, 0, 2, session, tlsinfo);
2274 } else {
2275 dissect_ssl3_alert(tvb, pinfo, ssl_record_tree, offset, record_length, session, tlsinfo);
2277 break;
2278 case SSL_ID_HANDSHAKE:
2279 if (decrypted) {
2280 unsigned record_id = record->id;
2281 dissect_tls_handshake(decrypted, pinfo, ssl_record_tree, 0,
2282 tvb_reported_length(decrypted), false, record_id, curr_layer_num_ssl, session,
2283 is_from_server, ssl, version);
2284 } 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 unsigned record_id = tvb_raw_offset(tvb) + offset + curr_layer_num_ssl;
2290 dissect_tls_handshake(tvb, pinfo, ssl_record_tree, offset,
2291 offset + record_length, true, record_id, curr_layer_num_ssl, session,
2292 is_from_server, ssl, version);
2294 break;
2295 case SSL_ID_APP_DATA:
2297 dissector_handle_t app_handle;
2299 /* show on info column what we are decoding */
2300 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Application Data");
2302 /* app_handle discovery is done here instead of dissect_ssl_payload()
2303 * because the protocol name needs to be displayed below. */
2304 app_handle = session->app_handle;
2305 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 app_handle = dissector_get_uint_handle(ssl_associations, pinfo->srcport);
2310 if (!app_handle) app_handle = dissector_get_uint_handle(ssl_associations, pinfo->destport);
2313 proto_item_set_text(ssl_record_tree,
2314 "%s Record Layer: %s Protocol: %s",
2315 val_to_str_const(version, ssl_version_short_names, "SSL"),
2316 val_to_str_const(content_type, ssl_31_content_type, "unknown"),
2317 app_handle ? dissector_handle_get_protocol_long_name(app_handle)
2318 : "Application Data");
2320 proto_tree_add_item(ssl_record_tree, hf_tls_record_appdata, tvb,
2321 offset, record_length, ENC_NA);
2323 if (app_handle) {
2324 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 proto_item_set_generated(ti);
2328 if (decrypted) {
2329 dissect_ssl_payload(decrypted, pinfo, tree, session, record, app_handle, tlsinfo);
2332 /* Set app proto again in case the heuristics found a different proto. */
2333 if (session->app_handle && session->app_handle != app_handle)
2334 proto_item_set_text(ssl_record_tree,
2335 "%s Record Layer: %s Protocol: %s",
2336 val_to_str_const(version, ssl_version_short_names, "SSL"),
2337 val_to_str_const(content_type, ssl_31_content_type, "unknown"),
2338 dissector_handle_get_protocol_long_name(session->app_handle));
2340 break;
2342 case SSL_ID_HEARTBEAT:
2343 if (version == TLSV1DOT3_VERSION) {
2344 expert_add_info_format(pinfo, ct_pi, &ei_tls_unexpected_message,
2345 "Record type is not allowed in TLS 1.3");
2346 break;
2348 if (decrypted) {
2349 dissect_ssl3_heartbeat(decrypted, pinfo, ssl_record_tree, 0, session, tvb_reported_length (decrypted), true);
2350 } else {
2351 bool plaintext = true;
2352 /* heartbeats before ChangeCipherSpec are unencrypted */
2353 if (ssl) {
2354 if (ssl_packet_from_server(session, ssl_associations, pinfo)) {
2355 plaintext = ssl->server == NULL;
2356 } else {
2357 plaintext = ssl->client == NULL;
2360 dissect_ssl3_heartbeat(tvb, pinfo, ssl_record_tree, offset, session, record_length, plaintext);
2362 break;
2363 case SSL_ID_TLS12_CID:
2364 case SSL_ID_DTLS13_ACK:
2365 break;
2367 offset += record_length; /* skip to end of record */
2369 return offset;
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)
2378 /* struct {
2379 * AlertLevel level;
2380 * AlertDescription description;
2381 * } Alert;
2383 proto_tree *ti;
2384 proto_tree *alert_tree = NULL;
2385 const char *level;
2386 const char *desc;
2387 uint8_t level_byte, desc_byte;
2389 if (tree)
2391 ti = proto_tree_add_item(tree, hf_tls_alert_message, tvb,
2392 offset, record_length, ENC_NA);
2393 alert_tree = proto_item_add_subtree(ti, ett_tls_alert);
2397 * Assume that TLS alert records are not fragmented. Any larger message is
2398 * assumed to be encrypted.
2400 if (record_length != 2) {
2401 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Alert");
2402 proto_item_set_text(tree,
2403 "%s Record Layer: Encrypted Alert",
2404 val_to_str_const(session->version, ssl_version_short_names, "TLS"));
2405 proto_item_set_text(alert_tree,
2406 "Alert Message: Encrypted Alert");
2407 return;
2411 * set the record layer label
2414 /* first lookup the names for the alert level and description */
2415 level_byte = tvb_get_uint8(tvb, offset); /* grab the level byte */
2416 level = val_to_str_const(level_byte, ssl_31_alert_level, "Unknown");
2418 desc_byte = tvb_get_uint8(tvb, offset+1); /* grab the desc byte */
2419 desc = val_to_str_const(desc_byte, ssl_31_alert_description, "Unknown");
2420 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?)
2425 tlsinfo->end_of_stream = true;
2428 /* now set the text in the record layer line */
2429 col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL,
2430 "Alert (Level: %s, Description: %s)",
2431 level, desc);
2433 if (tree)
2435 proto_item_set_text(tree, "%s Record Layer: Alert "
2436 "(Level: %s, Description: %s)",
2437 val_to_str_const(session->version, ssl_version_short_names, "TLS"),
2438 level, desc);
2439 proto_tree_add_item(alert_tree, hf_tls_alert_message_level,
2440 tvb, offset++, 1, ENC_BIG_ENDIAN);
2442 proto_tree_add_item(alert_tree, hf_tls_alert_message_description,
2443 tvb, offset++, 1, ENC_BIG_ENDIAN);
2449 * Checks whether a handshake message seems encrypted and cannot be dissected.
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)
2455 unsigned record_length = offset_end - offset;
2456 unsigned msg_length;
2457 uint8_t msg_type;
2458 uint16_t version;
2460 if (record_length < 16) {
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).
2468 * So anything smaller than 16 bytes is assumed to be plaintext.
2470 return false;
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.
2481 if (maybe_encrypted) {
2482 maybe_encrypted = tvb_get_ntoh40(tvb, offset) == 0;
2484 * TODO handle Finished message after CCS in the same frame and remove the
2485 * above nonce-based heuristic.
2489 if (!maybe_encrypted) {
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).
2498 msg_type = tvb_get_uint8(tvb, offset);
2499 maybe_encrypted = try_val_to_str(msg_type, ssl_31_handshake_type) == NULL;
2500 if (!maybe_encrypted) {
2501 msg_length = tvb_get_ntoh24(tvb, offset + 1);
2502 // Assume handshake messages are below 64K.
2503 maybe_encrypted = msg_length >= 0x010000;
2507 if (!maybe_encrypted) {
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).
2514 uint32_t *ccs_frame = is_from_server ? &session->server_ccs_frame : &session->client_ccs_frame;
2515 if (*ccs_frame != 0 && pinfo->num > *ccs_frame) {
2516 switch (msg_type) {
2518 case SSL_HND_CLIENT_HELLO:
2519 case SSL_HND_SERVER_HELLO:
2520 version = tvb_get_ntohs(tvb, offset + 4);
2521 maybe_encrypted = !ssl_is_valid_ssl_version(version);
2523 if (!maybe_encrypted) {
2524 // Assume ClientHello and ServerHello are < 1024.
2525 maybe_encrypted = msg_length >= 0x400;
2528 if (!maybe_encrypted) {
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.
2534 *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.)
2547 break;
2548 default:
2549 maybe_encrypted = true;
2553 return maybe_encrypted;
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)
2563 // Full handshake messages should not be saved.
2564 DISSECTOR_ASSERT(!(frag_offset == 0 && is_last));
2565 // 0 is a special value indicating no reassembly in progress.
2566 DISSECTOR_ASSERT(reassembly_id != 0);
2568 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 tvb = tvb_new_subset_length(tvb, 0, offset + frag_len);
2575 SslPacketInfo *pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
2576 TlsHsFragment *frag_info = wmem_new0(wmem_file_scope(), TlsHsFragment);
2577 frag_info->record_id = record_id;
2578 frag_info->reassembly_id = reassembly_id;
2579 frag_info->is_last = is_last;
2580 frag_info->offset = frag_offset;
2581 frag_info->type = msg_type;
2583 TlsHsFragment **p = &pi->hs_fragments;
2584 while (*p) p = &(*p)->next;
2585 *p = frag_info;
2587 // Add (subset of) record data.
2588 fragment_add_check(&tls_hs_reassembly_table, tvb, offset,
2589 pinfo, reassembly_id, session, frag_offset, frag_len, !is_last);
2591 return frag_info;
2595 * Populate the Info column and record layer tree item based on the message type.
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.
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)
2614 const char *msg_type_str = "Encrypted Handshake Message";
2615 if (!is_encrypted) {
2616 msg_type_str = val_to_str_const(msg_type, ssl_31_handshake_type, msg_type_str);
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.
2623 if (complete) {
2624 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);
2625 } else if (is_first_msg) {
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.
2630 col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "[%s Fragment]", msg_type_str);
2633 /* set the label text on the record layer expanding node */
2634 if (is_first_msg) {
2635 proto_item_set_text(record_tree, "%s Record Layer: Handshake Protocol: %s",
2636 val_to_str_const(version, ssl_version_short_names, "TLS"),
2637 msg_type_str);
2638 if (!complete && !is_encrypted) {
2639 proto_item_append_text(record_tree, " (fragment)");
2641 } else {
2642 proto_item_set_text(record_tree, "%s Record Layer: Handshake Protocol: %s",
2643 val_to_str_const(version, ssl_version_short_names, "TLS"),
2644 "Multiple Handshake Messages");
2647 proto_item *ti = proto_tree_add_item(record_tree, hf_tls_handshake_protocol,
2648 tvb, offset, length, ENC_NA);
2649 proto_item_set_text(ti, "Handshake Protocol: %s", msg_type_str);
2650 if (!complete && !is_encrypted) {
2651 proto_item_append_text(ti, " (fragment)");
2653 return ti;
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)
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.
2680 fragment_head *fh = NULL;
2681 unsigned subset_len;
2682 uint32_t msg_len = 0;
2683 TlsHsFragment *frag_info = NULL;
2684 bool is_first_msg = true;
2685 proto_item *frag_tree_item;
2686 unsigned *hs_reassembly_id_p = is_from_server ? &session->server_hs_reassembly_id : &session->client_hs_reassembly_id;
2688 if (!PINFO_FD_VISITED(pinfo)) {
2689 // 1. (First pass:) If a previous handshake message needed reassembly.
2690 if (*hs_reassembly_id_p) {
2691 // Continuation, so a previous fragment *must* exist.
2692 fh = fragment_get(&tls_hs_reassembly_table, pinfo, *hs_reassembly_id_p, session);
2693 DISSECTOR_ASSERT(fh);
2694 // We expect that reassembly has not completed yet.
2695 DISSECTOR_ASSERT(fh->tvb_data == NULL);
2697 // Combine all previous segments plus data from the current record
2698 // in order to find the length.
2699 tvbuff_t *len_tvb = tvb_new_composite();
2700 unsigned frags_len = 0;
2701 for (fragment_item *fd = fh->next; fd; fd = fd->next) {
2702 if (frags_len < 4) {
2703 tvb_composite_append(len_tvb, fd->tvb_data);
2705 frags_len += tvb_reported_length(fd->tvb_data);
2707 if (frags_len < 4) {
2708 tvbuff_t *remaining_tvb = tvb_new_subset_remaining(tvb, offset);
2709 tvb_composite_append(len_tvb, remaining_tvb);
2711 tvb_composite_finalize(len_tvb);
2713 // Extract the actual handshake message length (0 means unknown) and
2714 // check whether only a subset of the current record is needed.
2715 subset_len = offset_end - offset;
2716 if (tvb_reported_length(len_tvb) >= 4) {
2717 msg_len = 4 + tvb_get_ntoh24(len_tvb, 1);
2718 if (subset_len > msg_len - frags_len) {
2719 subset_len = msg_len - frags_len;
2723 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 *hs_reassembly_id_p = 0;
2728 } else {
2729 // Check if the handshake message is complete.
2730 uint8_t msg_type = tvb_get_uint8(len_tvb, 0);
2731 bool is_last = frags_len + subset_len == msg_len;
2732 frag_info = save_tls_handshake_fragment(pinfo, curr_layer_num_tls, record_id, *hs_reassembly_id_p,
2733 tvb, offset, subset_len, frags_len, msg_type, is_last, session);
2734 if (is_last) {
2735 // Reassembly finished, next message should not continue this message.
2736 *hs_reassembly_id_p = 0;
2740 } else {
2741 // Lookup the reassembled handshake matching this frame (if any).
2742 SslPacketInfo *pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
2743 if (pi) {
2744 for (TlsHsFragment *rec = pi->hs_fragments; rec; rec = rec->next) {
2745 if (rec->record_id == record_id) {
2746 frag_info = rec;
2747 break;
2753 // 2. Did this fragment complete reassembly in the previous step?
2754 if (frag_info && frag_info->offset != 0) {
2755 fh = fragment_get_reassembled_id(&tls_hs_reassembly_table, pinfo, frag_info->reassembly_id);
2756 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 subset_len = tvb_reported_length_remaining(fh->tvb_data, frag_info->offset);
2761 // Add a tree item to mark the handshake fragment.
2762 proto_item *ti = proto_tree_add_item(tree,
2763 hf_tls_handshake_protocol, tvb, offset, subset_len, ENC_NA);
2764 offset += subset_len;
2765 proto_item_set_text(ti, "Handshake Protocol: %s (last fragment)",
2766 val_to_str_const(frag_info->type, ssl_31_handshake_type,
2767 "Encrypted Handshake Message"));
2769 // Now display the full, reassembled handshake message.
2770 tvbuff_t *next_tvb = tvb_new_chain(tvb, fh->tvb_data);
2771 add_new_data_source(pinfo, next_tvb, "Reassembled TLS Handshake");
2772 show_fragment_tree(fh, &tls_hs_fragment_items, tree, pinfo, next_tvb, &frag_tree_item);
2773 dissect_tls_handshake_full(next_tvb, pinfo, tree, 0, session, is_from_server, ssl, version, true, curr_layer_num_tls);
2774 is_first_msg = false;
2776 // Skip to the next fragment in case this records ends with another
2777 // fragment for which information is presented below.
2778 frag_info = frag_info->next;
2779 if (frag_info && frag_info->record_id != record_id) {
2780 frag_info = NULL;
2782 } else if (frag_info->offset != 0) {
2783 // The full TVB is in the middle of a handshake message and needs more data.
2784 tls_show_handshake_details(pinfo, tree, version, frag_info->type, false, false, false,
2785 tvb, offset, offset_end - offset);
2786 if (fh) {
2787 proto_tree_add_uint(tree, hf_tls_handshake_reassembled_in, tvb, 0, 0, fh->reassembled_in);
2789 return;
2791 } 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 if (is_encrypted_handshake_message(tvb, pinfo, offset, offset_end, maybe_encrypted, session, is_from_server)) {
2795 // Update Info column and record tree.
2796 tls_show_handshake_details(pinfo, tree, version, 0, true, true, true,
2797 tvb, offset, offset_end - offset);
2798 return;
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 while (offset < offset_end) {
2806 msg_len = 0;
2807 subset_len = offset_end - offset;
2808 if (subset_len >= 4) {
2809 msg_len = 4 + tvb_get_ntoh24(tvb, offset + 1);
2811 if (msg_len == 0 || subset_len < msg_len) {
2812 // Need more data to find the message length or complete it.
2813 if (!PINFO_FD_VISITED(pinfo)) {
2814 uint8_t msg_type = tvb_get_uint8(tvb, offset);
2815 *hs_reassembly_id_p = ++hs_reassembly_id_count;
2816 frag_info = save_tls_handshake_fragment(pinfo, curr_layer_num_tls, record_id, *hs_reassembly_id_p,
2817 tvb, offset, subset_len, 0, msg_type, false, session);
2818 } else {
2819 // The first pass must have created a new fragment.
2820 DISSECTOR_ASSERT(frag_info && frag_info->offset == 0);
2823 tls_show_handshake_details(pinfo, tree, version, frag_info->type, false, is_first_msg, false,
2824 tvb, offset, subset_len);
2825 fh = fragment_get_reassembled_id(&tls_hs_reassembly_table, pinfo, frag_info->reassembly_id);
2826 if (fh) {
2827 proto_tree_add_uint(tree, hf_tls_handshake_reassembled_in, tvb, 0, 0, fh->reassembled_in);
2829 break;
2832 dissect_tls_handshake_full(tvb, pinfo, tree, offset, session, is_from_server, ssl, version, is_first_msg, curr_layer_num_tls);
2833 offset += msg_len;
2834 is_first_msg = false;
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)
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;
2867 proto_tree *ssl_hand_tree = NULL;
2868 const char *msg_type_str;
2869 uint8_t msg_type;
2870 uint32_t length;
2871 proto_item *ti;
2872 SslPacketInfo *pi;
2875 uint32_t hs_offset = offset;
2876 bool is_hrr = false;
2878 msg_type = tvb_get_uint8(tvb, offset);
2879 length = tvb_get_ntoh24(tvb, offset + 1);
2880 // The caller should have given us a fully reassembled record.
2881 DISSECTOR_ASSERT((unsigned)tvb_reported_length_remaining(tvb, offset + 4) >= length);
2883 msg_type_str = try_val_to_str(msg_type, ssl_31_handshake_type);
2885 ssl_debug_printf("dissect_ssl3_handshake iteration %d type %d offset %d length %d "
2886 "bytes\n", is_first_msg, msg_type, offset, length);
2887 if (!msg_type_str && !is_first_msg)
2889 /* only dissect / report messages if they're
2890 * either the first message in this record
2891 * or they're a valid message type
2893 return;
2896 if (is_first_msg && msg_type == SSL_HND_SERVER_HELLO && length > 2) {
2897 uint16_t server_version;
2899 tls_scan_server_hello(tvb, offset + 4, offset + 4 + length, &server_version, &is_hrr);
2900 ssl_try_set_version(session, ssl, SSL_ID_HANDSHAKE, SSL_HND_SERVER_HELLO, false, server_version);
2901 if (is_hrr) {
2902 msg_type_str = "Hello Retry Request";
2906 /* Populate Info column and set record layer text. */
2907 ti = tls_show_handshake_details(pinfo, tree, version,
2908 is_hrr ? SSL_HND_HELLO_RETRY_REQUEST : msg_type, false, is_first_msg, true,
2909 tvb, offset, length + 4);
2911 /* if we don't have a valid handshake type, just quit dissecting */
2912 if (!msg_type_str)
2913 return;
2915 /* add a subtree for the handshake protocol */
2916 ssl_hand_tree = proto_item_add_subtree(ti, ett_tls_handshake);
2918 /* add nodes for the message type and message length */
2919 proto_tree_add_uint(ssl_hand_tree, hf_tls_handshake_type,
2920 tvb, offset, 1, msg_type);
2921 offset += 1;
2922 proto_tree_add_uint(ssl_hand_tree, hf_tls_handshake_length,
2923 tvb, offset, 3, length);
2924 offset += 3;
2926 if ((msg_type == SSL_HND_CLIENT_HELLO || msg_type == SSL_HND_SERVER_HELLO)) {
2927 /* Prepare for renegotiation by resetting the state. */
2928 ssl_reset_session(session, ssl, msg_type == SSL_HND_CLIENT_HELLO);
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.
2939 if (msg_type != SSL_HND_CERT_VERIFY) {
2940 ssl_calculate_handshake_hash(ssl, tvb, hs_offset, 4 + length);
2943 /* now dissect the handshake message, if necessary */
2944 switch ((HandshakeType) msg_type) {
2945 case SSL_HND_HELLO_REQUEST:
2946 /* hello_request has no fields, so nothing to do! */
2947 break;
2949 case SSL_HND_CLIENT_HELLO:
2950 if (ssl) {
2951 /* ClientHello is first packet so set direction */
2952 ssl_set_server(session, &pinfo->dst, pinfo->ptype, pinfo->destport);
2953 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
2955 ssl_dissect_hnd_cli_hello(&dissect_ssl3_hf, tvb, pinfo,
2956 ssl_hand_tree, offset, offset + length, session, ssl,
2957 NULL, &ssl_master_key_map);
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.
2963 if (ssl) {
2964 tls_save_crandom(ssl, &ssl_master_key_map);
2965 if (ssl->has_early_data) {
2966 session->version = TLSV1DOT3_VERSION;
2967 ssl->state |= SSL_VERSION;
2968 ssl_debug_printf("%s forcing version 0x%04X -> state 0x%02X\n", G_STRFUNC, version, ssl->state);
2971 break;
2973 case SSL_HND_SERVER_HELLO:
2974 ssl_dissect_hnd_srv_hello(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
2975 offset, offset + length, session, ssl, false, is_hrr);
2976 if (ssl) {
2977 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 if (!ssl->has_early_data ||
2982 ((ssl->state & SSL_SEEN_0RTT_APPDATA) && !ssl->client)) {
2983 tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
2985 tls13_change_key(ssl, &ssl_master_key_map, true, TLS_SECRET_HANDSHAKE);
2987 break;
2989 case SSL_HND_HELLO_VERIFY_REQUEST:
2990 /* only valid for DTLS */
2991 break;
2993 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 ssl_dissect_hnd_new_ses_ticket(&dissect_ssl3_hf, tvb, pinfo,
2997 ssl_hand_tree, offset, offset + length, session, ssl, false,
2998 ssl_master_key_map.tickets);
2999 break;
3001 case SSL_HND_END_OF_EARLY_DATA:
3002 /* RFC 8446 Section 4.5 */
3003 if (!is_from_server && ssl) {
3004 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3005 tls13_change_key(ssl, &ssl_master_key_map, false, TLS_SECRET_HANDSHAKE);
3006 ssl->has_early_data = false;
3008 break;
3010 case SSL_HND_HELLO_RETRY_REQUEST: /* TLS 1.3 draft -21 and before */
3011 ssl_dissect_hnd_hello_retry_request(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
3012 offset, offset + length, session, ssl, false);
3013 break;
3015 case SSL_HND_ENCRYPTED_EXTENSIONS:
3016 /* XXX expert info if used with non-TLS 1.3? */
3017 ssl_dissect_hnd_encrypted_extensions(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree,
3018 offset, offset + length, session, ssl, false);
3020 break;
3022 case SSL_HND_CERTIFICATE:
3023 ssl_dissect_hnd_cert(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3024 offset, offset + length, pinfo, session, ssl, is_from_server, false);
3025 break;
3027 case SSL_HND_SERVER_KEY_EXCHG:
3028 if (!PINFO_FD_VISITED(pinfo)) {
3029 pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
3030 pi->cipher = session->cipher;
3031 } else {
3032 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
3033 if (pi) {
3034 session->cipher = pi->cipher;
3037 ssl_dissect_hnd_srv_keyex(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session);
3038 break;
3040 case SSL_HND_CERT_REQUEST:
3041 ssl_dissect_hnd_cert_req(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session, false);
3042 break;
3044 case SSL_HND_SVR_HELLO_DONE:
3045 /* This is not an abbreviated handshake, it is certainly not resumed. */
3046 session->is_session_resumed = false;
3047 break;
3049 case SSL_HND_CERT_VERIFY:
3050 ssl_dissect_hnd_cli_cert_verify(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length, session->version);
3051 break;
3053 case SSL_HND_CLIENT_KEY_EXCHG:
3054 if (!PINFO_FD_VISITED(pinfo)) {
3055 pi = tls_add_packet_info(proto_tls, pinfo, curr_layer_num_tls);
3056 pi->cipher = session->cipher;
3057 } else {
3058 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, curr_layer_num_tls);
3059 if (pi) {
3060 session->cipher = pi->cipher;
3063 ssl_dissect_hnd_cli_keyex(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset, length, session);
3065 if (!ssl)
3066 break;
3068 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file,
3069 &ssl_master_key_map);
3070 /* try to find master key from pre-master key */
3071 if (!ssl_generate_pre_master_secret(ssl, length, tvb, offset,
3072 ssl_options.psk, pinfo,
3073 #ifdef HAVE_LIBGNUTLS
3074 ssl_key_hash,
3075 #endif
3076 &ssl_master_key_map)) {
3077 ssl_debug_printf("dissect_ssl3_handshake can't generate pre master secret\n");
3079 break;
3081 case SSL_HND_FINISHED:
3082 ssl_dissect_hnd_finished(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3083 offset, offset + length, session, &ssl_hfs);
3084 if (ssl) {
3085 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
3086 tls13_change_key(ssl, &ssl_master_key_map, is_from_server, TLS_SECRET_APP);
3088 break;
3090 case SSL_HND_CERT_URL:
3091 ssl_dissect_hnd_cert_url(&dissect_ssl3_hf, tvb, ssl_hand_tree, offset);
3092 break;
3094 case SSL_HND_CERT_STATUS:
3095 tls_dissect_hnd_certificate_status(&dissect_ssl3_hf, tvb, pinfo, ssl_hand_tree, offset, offset + length);
3096 break;
3098 case SSL_HND_SUPPLEMENTAL_DATA:
3099 /* TODO: dissect this? */
3100 break;
3102 case SSL_HND_KEY_UPDATE:
3103 tls13_dissect_hnd_key_update(&dissect_ssl3_hf, tvb, tree, offset);
3104 if (ssl) {
3105 tls13_key_update(ssl, is_from_server);
3107 break;
3109 case SSL_HND_COMPRESSED_CERTIFICATE:
3110 ssl_dissect_hnd_compress_certificate(&dissect_ssl3_hf, tvb, ssl_hand_tree,
3111 offset, offset + length, pinfo, session,
3112 ssl, is_from_server, false);
3113 break;
3115 case SSL_HND_ENCRYPTED_EXTS:
3116 dissect_ssl3_hnd_encrypted_exts(tvb, ssl_hand_tree, offset);
3117 break;
3118 case SSL_HND_MESSAGE_HASH:
3119 break;
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)
3131 /* struct {
3132 * HeartbeatMessageType type;
3133 * uint16 payload_length;
3134 * opaque payload;
3135 * opaque padding;
3136 * } HeartbeatMessage;
3139 proto_item *ti;
3140 proto_tree *tls_heartbeat_tree;
3141 const char *type;
3142 uint8_t byte;
3143 uint16_t payload_length;
3144 uint16_t padding_length;
3146 tls_heartbeat_tree = NULL;
3148 if (tree) {
3149 ti = proto_tree_add_item(tree, hf_tls_heartbeat_message, tvb,
3150 offset, record_length, ENC_NA);
3151 tls_heartbeat_tree = proto_item_add_subtree(ti, ett_tls_heartbeat);
3155 * set the record layer label
3158 /* first lookup the names for the message type and the payload length */
3159 byte = tvb_get_uint8(tvb, offset);
3160 type = try_val_to_str(byte, tls_heartbeat_type);
3162 payload_length = tvb_get_ntohs(tvb, offset + 1);
3163 padding_length = record_length - 3 - payload_length;
3165 /* assume plaintext if the (expected) record size is smaller than the type
3166 * (1), length (2)[, payload] and padding (16) fields combined */
3167 if (record_length <= 19u || 3u + payload_length + 16 <= record_length) {
3168 decrypted = true;
3171 /* now set the text in the record layer line */
3172 if (type && decrypted) {
3173 col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "Heartbeat %s", type);
3174 } else {
3175 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Heartbeat");
3178 if (type && decrypted) {
3179 proto_item_set_text(tree, "%s Record Layer: Heartbeat "
3180 "%s",
3181 val_to_str_const(session->version, ssl_version_short_names, "SSL"),
3182 type);
3183 proto_tree_add_item(tls_heartbeat_tree, hf_tls_heartbeat_message_type,
3184 tvb, offset, 1, ENC_BIG_ENDIAN);
3185 offset += 1;
3186 ti = proto_tree_add_uint(tls_heartbeat_tree, hf_tls_heartbeat_message_payload_length,
3187 tvb, offset, 2, payload_length);
3188 offset += 2;
3189 if (3u + payload_length + 16 > record_length) {
3190 expert_add_info_format(pinfo, ti, &ei_ssl3_heartbeat_payload_length,
3191 "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 payload_length = record_length - 3;
3195 padding_length = 0;
3196 proto_item_append_text (ti, " (invalid, using %u to decode payload)", payload_length);
3198 proto_tree_add_bytes_format(tls_heartbeat_tree, hf_tls_heartbeat_message_payload,
3199 tvb, offset, payload_length,
3200 NULL, "Payload (%u byte%s)",
3201 payload_length,
3202 plurality(payload_length, "", "s"));
3203 offset += payload_length;
3204 if (padding_length)
3205 proto_tree_add_bytes_format(tls_heartbeat_tree, hf_tls_heartbeat_message_padding,
3206 tvb, offset, padding_length,
3207 NULL, "Padding and HMAC (%u byte%s)",
3208 padding_length,
3209 plurality(padding_length, "", "s"));
3210 } else {
3211 proto_item_set_text(tree,
3212 "%s Record Layer: Encrypted Heartbeat",
3213 val_to_str_const(session->version, ssl_version_short_names, "SSL"));
3214 proto_item_set_text(tls_heartbeat_tree,
3215 "Encrypted Heartbeat Message");
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)
3224 uint8_t selected_protocol_len;
3225 uint8_t padding_len;
3227 selected_protocol_len = tvb_get_uint8(tvb, offset);
3228 proto_tree_add_item(tree, hf_tls_handshake_npn_selected_protocol_len,
3229 tvb, offset, 1, ENC_BIG_ENDIAN);
3230 offset++;
3231 proto_tree_add_item(tree, hf_tls_handshake_npn_selected_protocol,
3232 tvb, offset, selected_protocol_len, ENC_ASCII);
3233 offset += selected_protocol_len;
3235 padding_len = tvb_get_uint8(tvb, offset);
3236 proto_tree_add_item(tree, hf_tls_handshake_npn_padding_len,
3237 tvb, offset, 1, ENC_BIG_ENDIAN);
3238 offset++;
3239 proto_tree_add_item(tree, hf_tls_handshake_npn_padding,
3240 tvb, offset, padding_len, ENC_NA);
3243 /*********************************************************************
3245 * SSL version 2 Dissectors
3247 *********************************************************************/
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)
3257 uint32_t initial_offset;
3258 uint8_t byte;
3259 uint8_t record_length_length;
3260 uint32_t record_length;
3261 int is_escape;
3262 int16_t padding_length;
3263 uint8_t msg_type;
3264 const char *msg_type_str;
3265 uint32_t available_bytes;
3266 proto_item *ti;
3267 proto_tree *ssl_record_tree;
3269 initial_offset = offset;
3270 record_length = 0;
3271 is_escape = -1;
3272 padding_length = -1;
3273 msg_type_str = NULL;
3274 ssl_record_tree = NULL;
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
3280 byte = tvb_get_uint8(tvb, offset);
3281 record_length_length = (byte & 0x80) ? 2 : 3;
3283 available_bytes = tvb_reported_length_remaining(tvb, offset);
3286 * Is the record header split across segment boundaries?
3288 if (available_bytes < record_length_length) {
3290 * Yes - can we do reassembly?
3292 ssl_proto_tree_add_segment_data(tree, tvb, offset, -1, NULL);
3293 if (tls_desegment && pinfo->can_desegment) {
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.
3301 pinfo->desegment_offset = offset;
3302 pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT;
3303 *need_desegmentation = true;
3304 return offset;
3305 } else {
3306 /* Not enough bytes available. Stop here. */
3307 return offset + available_bytes;
3311 /* parse out the record length */
3312 switch (record_length_length) {
3313 case 2: /* two-byte record length */
3314 record_length = (byte & 0x7f) << 8;
3315 byte = tvb_get_uint8(tvb, offset + 1);
3316 record_length += byte;
3317 break;
3318 case 3: /* three-byte record length */
3319 is_escape = (byte & 0x40) ? true : false;
3320 record_length = (byte & 0x3f) << 8;
3321 byte = tvb_get_uint8(tvb, offset + 1);
3322 record_length += byte;
3323 byte = tvb_get_uint8(tvb, offset + 2);
3324 padding_length = byte;
3328 * Is the record split across segment boundaries?
3330 if (available_bytes < (record_length_length + record_length)) {
3332 * Yes - Can we do reassembly?
3334 ssl_proto_tree_add_segment_data(tree, tvb, offset, -1, NULL);
3335 if (tls_desegment && pinfo->can_desegment) {
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.
3341 pinfo->desegment_offset = offset;
3342 pinfo->desegment_len = (record_length_length + record_length)
3343 - available_bytes;
3344 *need_desegmentation = true;
3345 return offset;
3346 } else {
3347 /* Not enough bytes available. Stop here. */
3348 return offset + available_bytes;
3351 offset += record_length_length;
3353 /* add the record layer subtree header */
3354 ti = proto_tree_add_item(tree, hf_ssl2_record, tvb, initial_offset,
3355 record_length_length + record_length, ENC_NA);
3356 ssl_record_tree = proto_item_add_subtree(ti, ett_tls_record);
3358 /* pull the msg_type so we can bail if it's unknown */
3359 msg_type = tvb_get_uint8(tvb, initial_offset + record_length_length);
3361 /* if we get a server_hello or later handshake in v2, then set
3362 * this to sslv2
3364 if (session->version == SSL_VER_UNKNOWN)
3366 if (msg_type >= 2 && msg_type <= 8)
3368 session->version = SSLV2_VERSION;
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)
3376 col_set_str(pinfo->cinfo, COL_PROTOCOL, "SSLv2");
3378 /* see if the msg_type is valid; if not the payload is
3379 * probably encrypted, so note that fact and bail
3381 msg_type_str = try_val_to_str(msg_type, ssl_20_msg_types);
3382 if (!msg_type_str
3383 || (!ssl_looks_like_valid_v2_handshake(tvb, initial_offset
3384 + record_length_length,
3385 record_length)))
3387 if (ssl_record_tree)
3389 proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
3390 "SSLv2",
3391 "Encrypted Data");
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
3398 ti = proto_tree_add_uint(ssl_record_tree,
3399 hf_tls_record_version, tvb,
3400 initial_offset, 0, 0x0002);
3401 proto_item_set_generated(ti);
3404 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Data");
3405 return initial_offset + record_length_length + record_length;
3407 else
3409 col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);
3411 if (ssl_record_tree)
3413 proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
3414 "SSLv2",
3415 msg_type_str);
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
3423 if (ssl_record_tree)
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
3430 ti = proto_tree_add_uint(ssl_record_tree,
3431 hf_tls_record_version, tvb,
3432 initial_offset, 0, 0x0002);
3433 proto_item_set_generated(ti);
3435 /* add the record length */
3436 tvb_ensure_bytes_exist(tvb, offset, record_length_length);
3437 proto_tree_add_uint (ssl_record_tree,
3438 hf_tls_record_length, tvb,
3439 initial_offset, record_length_length,
3440 record_length);
3442 if (ssl_record_tree && is_escape != -1)
3444 proto_tree_add_boolean(ssl_record_tree,
3445 hf_ssl2_record_is_escape, tvb,
3446 initial_offset, 1, is_escape);
3448 if (ssl_record_tree && padding_length != -1)
3450 proto_tree_add_uint(ssl_record_tree,
3451 hf_ssl2_record_padding_length, tvb,
3452 initial_offset + 2, 1, padding_length);
3456 * dissect the record data
3459 /* jump forward to the start of the record data */
3460 offset = initial_offset + record_length_length;
3462 /* add the message type */
3463 if (ssl_record_tree)
3465 proto_tree_add_item(ssl_record_tree, hf_ssl2_msg_type,
3466 tvb, offset, 1, ENC_BIG_ENDIAN);
3468 offset += 1; /* move past msg_type byte */
3471 /* dissect the message (only handle client hello right now) */
3472 switch (msg_type) {
3473 case SSL2_HND_CLIENT_HELLO:
3474 dissect_ssl2_hnd_client_hello(tvb, pinfo, ssl_record_tree, offset, ssl);
3475 break;
3477 case SSL2_HND_CLIENT_MASTER_KEY:
3478 dissect_ssl2_hnd_client_master_key(tvb, ssl_record_tree, offset);
3479 break;
3481 case SSL2_HND_SERVER_HELLO:
3482 dissect_ssl2_hnd_server_hello(tvb, ssl_record_tree, offset, pinfo);
3483 break;
3485 case SSL2_HND_ERROR:
3486 case SSL2_HND_CLIENT_FINISHED:
3487 case SSL2_HND_SERVER_VERIFY:
3488 case SSL2_HND_SERVER_FINISHED:
3489 case SSL2_HND_REQUEST_CERTIFICATE:
3490 case SSL2_HND_CLIENT_CERTIFICATE:
3491 /* unimplemented */
3492 break;
3494 default: /* unknown */
3495 break;
3498 return (initial_offset + record_length_length + record_length);
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)
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;
3517 * Note: when we get here, offset's already pointing at Version
3520 uint16_t version;
3521 uint16_t cipher_spec_length;
3522 uint16_t session_id_length;
3523 uint16_t challenge_length;
3525 proto_item *ti;
3526 proto_tree *cs_tree;
3527 cs_tree=0;
3529 version = tvb_get_ntohs(tvb, offset);
3530 if (!ssl_is_valid_ssl_version(version))
3532 /* invalid version; probably encrypted data */
3533 return;
3536 if (ssl) {
3537 ssl_set_server(&ssl->session, &pinfo->dst, pinfo->ptype, pinfo->destport);
3540 /* show the version */
3541 proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_client_version, tvb,
3542 offset, 2, ENC_BIG_ENDIAN);
3543 offset += 2;
3545 cipher_spec_length = tvb_get_ntohs(tvb, offset);
3546 proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec_len,
3547 tvb, offset, 2, ENC_BIG_ENDIAN);
3548 offset += 2;
3550 session_id_length = tvb_get_ntohs(tvb, offset);
3551 ti = proto_tree_add_item(tree, hf_ssl2_handshake_session_id_len,
3552 tvb, offset, 2, ENC_BIG_ENDIAN);
3553 if (session_id_length > SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES) {
3554 expert_add_info_format(pinfo, ti, &ei_ssl2_handshake_session_id_len_error,
3555 "Session ID length (%u) must be less than %u.",
3556 session_id_length, SSLV2_MAX_SESSION_ID_LENGTH_IN_BYTES);
3557 return;
3559 offset += 2;
3561 challenge_length = tvb_get_ntohs(tvb, offset);
3562 if (tree)
3563 proto_tree_add_item(tree, hf_ssl2_handshake_challenge_len,
3564 tvb, offset, 2, ENC_BIG_ENDIAN);
3565 offset += 2;
3567 if (tree)
3569 /* tell the user how many cipher specs they've won */
3570 ti = proto_tree_add_none_format(tree, dissect_ssl3_hf.hf.hs_cipher_suites,
3571 tvb, offset, cipher_spec_length,
3572 "Cipher Specs (%u specs)",
3573 cipher_spec_length/3);
3575 /* make this a subtree and expand the actual specs below */
3576 cs_tree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
3577 if (!cs_tree)
3579 cs_tree = tree; /* failsafe */
3583 /* iterate through the cipher specs, showing them */
3584 while (cipher_spec_length > 0)
3586 if (cs_tree)
3587 proto_tree_add_item(cs_tree, hf_ssl2_handshake_cipher_spec,
3588 tvb, offset, 3, ENC_BIG_ENDIAN);
3589 offset += 3; /* length of one cipher spec */
3590 cipher_spec_length -= 3;
3593 /* if there's a session id, show it */
3594 if (session_id_length > 0)
3596 proto_tree_add_bytes_format(tree,
3597 dissect_ssl3_hf.hf.hs_session_id,
3598 tvb, offset, session_id_length,
3599 NULL, "Session ID (%u byte%s)",
3600 session_id_length,
3601 plurality(session_id_length, "", "s"));
3603 /* PAOLO: get session id and reset session state for key [re]negotiation */
3604 if (ssl)
3606 tvb_memcpy(tvb,ssl->session_id.data, offset, session_id_length);
3607 ssl->session_id.data_len = session_id_length;
3608 ssl->state &= ~(SSL_HAVE_SESSION_KEY|SSL_MASTER_SECRET|SSL_PRE_MASTER_SECRET|
3609 SSL_CIPHER|SSL_SERVER_RANDOM);
3611 offset += session_id_length;
3614 /* if there's a challenge, show it */
3615 if (challenge_length > 0)
3617 proto_tree_add_item(tree, hf_ssl2_handshake_challenge,
3618 tvb, offset, challenge_length, ENC_NA);
3619 if (ssl)
3621 /* PAOLO: get client random data; we get at most 32 bytes from
3622 challenge */
3623 int max;
3624 max = challenge_length > 32? 32: challenge_length;
3626 ssl_debug_printf("client random len: %d padded to 32\n", challenge_length);
3628 /* client random is padded with zero and 'right' aligned */
3629 memset(ssl->client_random.data, 0, 32 - max);
3630 tvb_memcpy(tvb, &ssl->client_random.data[32 - max], offset, max);
3631 ssl->client_random.data_len = 32;
3632 ssl->state |= SSL_CLIENT_RANDOM;
3633 ssl_debug_printf("dissect_ssl2_hnd_client_hello found CLIENT RANDOM -> state 0x%02X\n", ssl->state);
3638 static void
3639 dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
3640 proto_tree *tree, uint32_t offset)
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;
3653 * Note: when we get here, offset's already pointing at cipher
3655 uint16_t clear_key_length;
3656 uint16_t encrypted_key_length;
3657 uint16_t key_arg_length;
3659 /* at this point, everything we do involves the tree,
3660 * so quit now if we don't have one ;-)
3662 if (!tree)
3664 return;
3667 /* show the selected cipher */
3668 proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec,
3669 tvb, offset, 3, ENC_BIG_ENDIAN);
3670 offset += 3;
3672 /* get the fixed fields */
3673 clear_key_length = tvb_get_ntohs(tvb, offset);
3674 proto_tree_add_item(tree, hf_ssl2_handshake_clear_key_len,
3675 tvb, offset, 2, ENC_BIG_ENDIAN);
3676 offset += 2;
3678 encrypted_key_length = tvb_get_ntohs(tvb, offset);
3679 proto_tree_add_item(tree, hf_ssl2_handshake_enc_key_len,
3680 tvb, offset, 2, ENC_BIG_ENDIAN);
3681 offset += 2;
3683 key_arg_length = tvb_get_ntohs(tvb, offset);
3684 proto_tree_add_item(tree, hf_ssl2_handshake_key_arg_len,
3685 tvb, offset, 2, ENC_BIG_ENDIAN);
3686 offset += 2;
3688 /* show the variable length fields */
3689 if (clear_key_length > 0)
3691 proto_tree_add_item(tree, hf_ssl2_handshake_clear_key,
3692 tvb, offset, clear_key_length, ENC_NA);
3693 offset += clear_key_length;
3696 if (encrypted_key_length > 0)
3698 proto_tree_add_item(tree, hf_ssl2_handshake_enc_key,
3699 tvb, offset, encrypted_key_length, ENC_NA);
3700 offset += encrypted_key_length;
3703 if (key_arg_length > 0)
3705 proto_tree_add_item(tree, hf_ssl2_handshake_key_arg,
3706 tvb, offset, key_arg_length, ENC_NA);
3711 static void
3712 dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
3713 proto_tree *tree, uint32_t offset, packet_info *pinfo)
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;
3728 * Note: when we get here, offset's already pointing at session_id_hit
3730 uint16_t certificate_length;
3731 uint16_t cipher_spec_length;
3732 uint16_t connection_id_length;
3733 uint16_t version;
3734 proto_item *ti;
3735 proto_tree *subtree;
3736 asn1_ctx_t asn1_ctx;
3738 asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, true, pinfo);
3740 /* everything we do only makes sense with a tree, so
3741 * quit now if we don't have one
3743 if (!tree)
3745 return;
3748 version = tvb_get_ntohs(tvb, offset + 2);
3749 if (!ssl_is_valid_ssl_version(version))
3751 /* invalid version; probably encrypted data */
3752 return;
3756 /* is there a hit? */
3757 proto_tree_add_item(tree, hf_ssl2_handshake_session_id_hit,
3758 tvb, offset, 1, ENC_BIG_ENDIAN);
3759 offset += 1;
3761 /* what type of certificate is this? */
3762 proto_tree_add_item(tree, hf_ssl2_handshake_cert_type,
3763 tvb, offset, 1, ENC_BIG_ENDIAN);
3764 offset += 1;
3766 /* now the server version */
3767 proto_tree_add_item(tree, dissect_ssl3_hf.hf.hs_server_version,
3768 tvb, offset, 2, ENC_BIG_ENDIAN);
3769 offset += 2;
3771 /* get the fixed fields */
3772 certificate_length = tvb_get_ntohs(tvb, offset);
3773 proto_tree_add_uint(tree, dissect_ssl3_hf.hf.hs_certificate_len,
3774 tvb, offset, 2, certificate_length);
3775 offset += 2;
3777 cipher_spec_length = tvb_get_ntohs(tvb, offset);
3778 proto_tree_add_uint(tree, hf_ssl2_handshake_cipher_spec_len,
3779 tvb, offset, 2, cipher_spec_length);
3780 offset += 2;
3782 connection_id_length = tvb_get_ntohs(tvb, offset);
3783 proto_tree_add_uint(tree, hf_ssl2_handshake_connection_id_len,
3784 tvb, offset, 2, connection_id_length);
3785 offset += 2;
3787 /* now the variable length fields */
3788 if (certificate_length > 0)
3790 (void)dissect_x509af_Certificate(false, tvb, offset, &asn1_ctx, tree, dissect_ssl3_hf.hf.hs_certificate);
3791 offset += certificate_length;
3794 if (cipher_spec_length > 0)
3796 /* provide a collapsing node for the cipher specs */
3797 ti = proto_tree_add_none_format(tree,
3798 dissect_ssl3_hf.hf.hs_cipher_suites,
3799 tvb, offset, cipher_spec_length,
3800 "Cipher Specs (%u spec%s)",
3801 cipher_spec_length/3,
3802 plurality(cipher_spec_length/3, "", "s"));
3803 subtree = proto_item_add_subtree(ti, dissect_ssl3_hf.ett.cipher_suites);
3804 if (!subtree)
3806 subtree = tree;
3809 /* iterate through the cipher specs */
3810 while (cipher_spec_length > 0)
3812 proto_tree_add_item(subtree, hf_ssl2_handshake_cipher_spec,
3813 tvb, offset, 3, ENC_BIG_ENDIAN);
3814 offset += 3;
3815 cipher_spec_length -= 3;
3819 if (connection_id_length > 0)
3821 proto_tree_add_item(tree, hf_ssl2_handshake_connection_id,
3822 tvb, offset, connection_id_length, ENC_NA);
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)
3834 conversation_t *conversation;
3835 SslDecryptSession *ssl;
3836 unsigned iv_len;
3838 ssl_debug_printf("\nssl_set_master_secret enter frame #%u\n", frame_num);
3840 conversation = find_conversation(frame_num, addr_srv, addr_cli, conversation_pt_to_conversation_type(ptype), port_srv, port_cli, 0);
3842 if (!conversation) {
3843 /* create a new conversation */
3844 conversation = conversation_new(frame_num, addr_srv, addr_cli, conversation_pt_to_conversation_type(ptype), port_srv, port_cli, 0);
3845 ssl_debug_printf(" new conversation = %p created\n", (void *)conversation);
3847 ssl = ssl_get_session(conversation, tls_handle);
3849 ssl_debug_printf(" conversation = %p, ssl_session = %p\n", (void *)conversation, (void *)ssl);
3851 ssl_set_server(&ssl->session, addr_srv, ptype, port_srv);
3853 /* version */
3854 if ((ssl->session.version==SSL_VER_UNKNOWN) && (version!=SSL_VER_UNKNOWN)) {
3855 switch (version) {
3856 case SSLV3_VERSION:
3857 case TLSV1_VERSION:
3858 case TLSV1DOT1_VERSION:
3859 case TLSV1DOT2_VERSION:
3860 case TLCPV1_VERSION:
3861 ssl->session.version = version;
3862 ssl->state |= SSL_VERSION;
3863 ssl_debug_printf("%s set version 0x%04X -> state 0x%02X\n", G_STRFUNC, ssl->session.version, ssl->state);
3864 break;
3865 default:
3866 /* API change: version number is no longer an internal value
3867 * (SSL_VER_*) but the ProtocolVersion from wire (*_VERSION) */
3868 ssl_debug_printf("%s WARNING must pass ProtocolVersion, not 0x%04x!\n", G_STRFUNC, version);
3869 break;
3873 /* cipher */
3874 if (cipher > 0) {
3875 ssl->session.cipher = cipher;
3876 if (!(ssl->cipher_suite = ssl_find_cipher(ssl->session.cipher))) {
3877 ssl->state &= ~SSL_CIPHER;
3878 ssl_debug_printf("ssl_set_master_secret can't find cipher suite 0x%X\n", ssl->session.cipher);
3879 } else {
3880 ssl->state |= SSL_CIPHER;
3881 ssl_debug_printf("ssl_set_master_secret set CIPHER 0x%04X -> state 0x%02X\n", ssl->session.cipher, ssl->state);
3885 /* client random */
3886 if (_client_random) {
3887 ssl_data_set(&ssl->client_random, _client_random, 32);
3888 ssl->state |= SSL_CLIENT_RANDOM;
3889 ssl_debug_printf("ssl_set_master_secret set CLIENT RANDOM -> state 0x%02X\n", ssl->state);
3892 /* server random */
3893 if (_server_random) {
3894 ssl_data_set(&ssl->server_random, _server_random, 32);
3895 ssl->state |= SSL_SERVER_RANDOM;
3896 ssl_debug_printf("ssl_set_master_secret set SERVER RANDOM -> state 0x%02X\n", ssl->state);
3899 /* master secret */
3900 if (_master_secret) {
3901 ssl_data_set(&ssl->master_secret, _master_secret, 48);
3902 ssl->state |= SSL_MASTER_SECRET;
3903 ssl_debug_printf("ssl_set_master_secret set MASTER SECRET -> state 0x%02X\n", ssl->state);
3906 ssl_debug_printf("ssl_set_master_secret trying to generate keys\n");
3907 if (ssl_generate_keyring_material(ssl)<0) {
3908 ssl_debug_printf("ssl_set_master_secret can't generate keyring material\n");
3909 return;
3912 /* change ciphers immediately */
3913 ssl_change_cipher(ssl, true);
3914 ssl_change_cipher(ssl, false);
3916 /* update seq numbers if available */
3917 /* TODO change API to accept 64-bit sequence numbers. */
3918 if (ssl->client && (client_seq != (uint32_t)-1)) {
3919 ssl->client->seq = client_seq;
3920 ssl_debug_printf("ssl_set_master_secret client->seq updated to %" PRIu64 "\n", ssl->client->seq);
3922 if (ssl->server && (server_seq != (uint32_t)-1)) {
3923 ssl->server->seq = server_seq;
3924 ssl_debug_printf("ssl_set_master_secret server->seq updated to %" PRIu64 "\n", ssl->server->seq);
3927 /* update IV from last data */
3928 iv_len = ssl_get_cipher_blocksize(ssl->cipher_suite);
3929 if (ssl->client && ((ssl->client->seq > 0) || (ssl->client_data_for_iv.data_len > iv_len))) {
3930 ssl_cipher_setiv(&ssl->client->evp, ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
3931 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);
3933 if (ssl->server && ((ssl->server->seq > 0) || (ssl->server_data_for_iv.data_len > iv_len))) {
3934 ssl_cipher_setiv(&ssl->server->evp, ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
3935 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);
3940 /*********************************************************************
3942 * Support Functions
3944 *********************************************************************/
3945 static int
3946 ssl_is_valid_ssl_version(const uint16_t version)
3948 const char *version_str;
3950 version_str = try_val_to_str(version, ssl_versions);
3951 return version_str != NULL;
3954 static int
3955 ssl_is_v2_client_hello(tvbuff_t *tvb, const uint32_t offset)
3957 uint8_t byte;
3959 byte = tvb_get_uint8(tvb, offset);
3960 if (byte != 0x80) /* v2 client hello should start this way */
3962 return 0;
3965 byte = tvb_get_uint8(tvb, offset+2);
3966 if (byte != 0x01) /* v2 client hello msg type */
3968 return 0;
3971 /* 1 in 2^16 of being right; improve later if necessary */
3972 return 1;
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.
3980 static int
3981 ssl_looks_like_sslv2(tvbuff_t *tvb, const uint32_t offset)
3983 /* here's the current approach:
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
3991 /* get the first byte; must have high bit set */
3992 uint8_t byte;
3993 byte = tvb_get_uint8(tvb, offset);
3995 if (byte < 0x80)
3997 return 0;
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
4004 byte = tvb_get_uint8(tvb, offset + 2);
4005 switch (byte) {
4006 case SSL2_HND_ERROR:
4007 case SSL2_HND_CLIENT_HELLO:
4008 case SSL2_HND_CLIENT_MASTER_KEY:
4009 case SSL2_HND_SERVER_HELLO:
4010 return 1;
4012 return 0;
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
4020 static int
4021 ssl_looks_like_sslv3(tvbuff_t *tvb, const uint32_t offset)
4023 /* have to have a valid content type followed by a valid
4024 * protocol version
4026 uint8_t byte;
4027 uint16_t version;
4029 /* see if the first byte is a valid content type */
4030 byte = tvb_get_uint8(tvb, offset);
4031 if (!ssl_is_valid_content_type(byte))
4033 return 0;
4036 /* now check to see if the version byte appears valid */
4037 version = tvb_get_ntohs(tvb, offset + 1);
4038 switch (version) {
4039 case SSLV3_VERSION:
4040 case TLSV1_VERSION:
4041 case TLSV1DOT1_VERSION:
4042 case TLSV1DOT2_VERSION:
4043 case TLSV1DOT3_VERSION:
4044 case TLCPV1_VERSION:
4045 return 1;
4047 return 0;
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.
4057 static int
4058 ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb, const uint32_t offset,
4059 const uint32_t record_length)
4061 /* first byte should be a msg_type.
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)
4068 * - for those three types that we know about, do some
4069 * further validation to reduce the chance of an error
4071 uint8_t msg_type;
4072 uint16_t version;
4073 uint32_t sum;
4074 int ret = 0;
4076 /* fetch the msg_type */
4077 msg_type = tvb_get_uint8(tvb, offset);
4079 switch (msg_type) {
4080 case SSL2_HND_CLIENT_HELLO:
4081 /* version follows msg byte, so verify that this is valid */
4082 version = tvb_get_ntohs(tvb, offset+1);
4083 ret = ssl_is_valid_ssl_version(version);
4084 break;
4086 case SSL2_HND_SERVER_HELLO:
4087 /* version is three bytes after msg_type */
4088 version = tvb_get_ntohs(tvb, offset+3);
4089 ret = ssl_is_valid_ssl_version(version);
4090 break;
4092 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
4096 sum = tvb_get_ntohs(tvb, offset + 4); /* clear_key_length */
4097 sum += tvb_get_ntohs(tvb, offset + 6); /* encrypted_key_length */
4098 sum += tvb_get_ntohs(tvb, offset + 8); /* key_arg_length */
4099 if (sum <= record_length) {
4100 ret = 1;
4102 break;
4104 default:
4105 break;
4108 return ret;
4111 bool
4112 tls_get_cipher_info(packet_info *pinfo, uint16_t cipher_suite, int *cipher_algo, int *cipher_mode, int *hash_algo)
4114 if (cipher_suite == 0) {
4115 conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4116 if (!conv) {
4117 return false;
4120 void *conv_data = conversation_get_proto_data(conv, proto_tls);
4121 if (conv_data == NULL) {
4122 return false;
4125 SslDecryptSession *ssl_session = (SslDecryptSession *)conv_data;
4126 cipher_suite = ssl_session->session.cipher;
4128 const SslCipherSuite *suite = ssl_find_cipher(cipher_suite);
4129 if (!suite) {
4130 return false;
4133 /* adapted from ssl_cipher_init in packet-tls-utils.c */
4134 static const int gcry_modes[] = {
4135 GCRY_CIPHER_MODE_STREAM,
4136 GCRY_CIPHER_MODE_CBC,
4137 GCRY_CIPHER_MODE_GCM,
4138 GCRY_CIPHER_MODE_CCM,
4139 GCRY_CIPHER_MODE_CCM,
4140 GCRY_CIPHER_MODE_POLY1305,
4142 static const int gcry_mds[] = {
4143 GCRY_MD_MD5,
4144 GCRY_MD_SHA1,
4145 GCRY_MD_SHA256,
4146 GCRY_MD_SHA384,
4149 int mode = gcry_modes[suite->mode];
4150 int cipher_algo_id = ssl_get_cipher_algo(suite);
4151 int hash_algo_id = gcry_mds[suite->dig-DIG_MD5];
4152 if (mode == -1 || cipher_algo_id == 0 || hash_algo_id == -1) {
4153 /* Identifiers are unusable, fail. */
4154 return false;
4156 if (cipher_algo) {
4157 *cipher_algo = cipher_algo_id;
4159 if (cipher_mode) {
4160 *cipher_mode = mode;
4162 if (hash_algo) {
4163 *hash_algo = hash_algo_id;
4166 return true;
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.
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)
4177 GHashTable *key_map;
4178 const char *label;
4179 conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4180 if (!conv) {
4181 return 0;
4184 SslDecryptSession *ssl = (SslDecryptSession *)conversation_get_proto_data(conv, proto_tls);
4185 if (ssl == NULL) {
4186 return 0;
4189 bool is_quic = !!(ssl->state & SSL_QUIC_RECORD_LAYER);
4190 ssl_debug_printf("%s frame %d is_quic=%d\n", G_STRFUNC, pinfo->num, is_quic);
4191 if (!is_quic) {
4192 return 0;
4195 if (ssl->client_random.data_len == 0) {
4196 /* May happen if Hello message is missing and Finished is found. */
4197 ssl_debug_printf("%s missing Client Random\n", G_STRFUNC);
4198 return 0;
4201 // Not strictly necessary as QUIC CRYPTO frames have just been processed
4202 // which also calls ssl_load_keyfile for key transitions.
4203 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
4205 switch ((TLSRecordType)type) {
4206 case TLS_SECRET_0RTT_APP:
4207 DISSECTOR_ASSERT(!is_from_server);
4208 label = "CLIENT_EARLY_TRAFFIC_SECRET";
4209 key_map = ssl_master_key_map.tls13_client_early;
4210 break;
4211 case TLS_SECRET_HANDSHAKE:
4212 if (is_from_server) {
4213 label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
4214 key_map = ssl_master_key_map.tls13_server_handshake;
4215 } else {
4216 label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
4217 key_map = ssl_master_key_map.tls13_client_handshake;
4219 break;
4220 case TLS_SECRET_APP:
4221 if (is_from_server) {
4222 label = "SERVER_TRAFFIC_SECRET_0";
4223 key_map = ssl_master_key_map.tls13_server_appdata;
4224 } else {
4225 label = "CLIENT_TRAFFIC_SECRET_0";
4226 key_map = ssl_master_key_map.tls13_client_appdata;
4228 break;
4229 default:
4230 ws_assert_not_reached();
4233 StringInfo *secret = (StringInfo *)g_hash_table_lookup(key_map, &ssl->client_random);
4234 if (!secret || secret->data_len < secret_min_len || secret->data_len > secret_max_len) {
4235 ssl_debug_printf("%s Cannot find QUIC %s of size %d..%d, found bad size %d!\n",
4236 G_STRFUNC, label, secret_min_len, secret_max_len, secret ? secret->data_len : 0);
4237 return 0;
4240 ssl_debug_printf("%s Retrieved QUIC traffic secret.\n", G_STRFUNC);
4241 ssl_print_string("Client Random", &ssl->client_random);
4242 ssl_print_string(label, secret);
4243 memcpy(secret_out, secret->data, secret->data_len);
4244 return secret->data_len;
4247 const char *
4248 tls_get_alpn(packet_info *pinfo)
4250 conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4251 if (!conv) {
4252 return NULL;
4255 SslDecryptSession *session = (SslDecryptSession *)conversation_get_proto_data(conv, proto_tls);
4256 if (session == NULL) {
4257 return NULL;
4260 return session->session.alpn_name;
4263 const char *
4264 tls_get_client_alpn(packet_info *pinfo)
4266 conversation_t *conv = find_conversation_pinfo(pinfo, 0);
4267 if (!conv) {
4268 return NULL;
4271 SslDecryptSession *session = (SslDecryptSession *)conversation_get_proto_data(conv, proto_tls);
4272 if (session == NULL) {
4273 return NULL;
4276 return session->session.client_alpn_name;
4279 /* TLS Exporters {{{ */
4281 * Computes the TLS 1.3 Exporter value (RFC 8446 Section 7.5).
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)").
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)
4290 /* TLS-Exporter(label, context_value, key_length) =
4291 * HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
4292 * "exporter", Hash(context_value), key_length)
4294 * Derive-Secret(Secret, Label, Messages) =
4295 * HKDF-Expand-Label(Secret, Label,
4296 * Transcript-Hash(Messages), Hash.length)
4298 gcry_error_t err;
4299 gcry_md_hd_t hd;
4300 const char *hash_value;
4301 StringInfo derived_secret = { NULL, 0 };
4302 // QUIC -09 currently uses draft 23, so no need to support older TLS drafts
4303 const char *label_prefix = "tls13 ";
4305 err = gcry_md_open(&hd, algo, 0);
4306 if (err) {
4307 return false;
4310 /* Calculate Derive-Secret(Secret, label, ""). */
4311 hash_value = gcry_md_read(hd, 0); /* Empty Messages */
4312 uint8_t hash_len = (uint8_t) gcry_md_get_algo_dlen(algo);
4313 derived_secret.data_len = hash_len;
4314 if (!tls13_hkdf_expand_label_context(algo, secret, label_prefix, label, hash_value, hash_len, derived_secret.data_len, &derived_secret.data)) {
4315 gcry_md_close(hd);
4316 return false;
4319 /* HKDF-Expand-Label(..., "exporter", Hash(context_value), key_length) */
4320 gcry_md_reset(hd);
4321 gcry_md_write(hd, context, context_length);
4322 hash_value = gcry_md_read(hd, 0);
4323 tls13_hkdf_expand_label_context(algo, &derived_secret, label_prefix, "exporter", hash_value, hash_len, key_length, out);
4324 wmem_free(NULL, derived_secret.data);
4325 gcry_md_close(hd);
4327 return true;
4331 * Exports keying material using "[early_]exporter_master_secret". See
4332 * tls13_exporter_common for more details.
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)
4339 int hash_algo = 0;
4340 GHashTable *key_map;
4341 const StringInfo *secret;
4343 if (!tls_get_cipher_info(pinfo, 0, NULL, NULL, &hash_algo)) {
4344 return false;
4347 /* Lookup EXPORTER_SECRET based on client_random from conversation */
4348 conversation_t *conv = find_conversation_strat(pinfo, conversation_pt_to_conversation_type(pinfo->ptype), 0);
4349 if (!conv) {
4350 return false;
4353 void *conv_data = conversation_get_proto_data(conv, proto_tls);
4354 if (conv_data == NULL) {
4355 return false;
4358 SslDecryptSession *ssl_session = (SslDecryptSession *)conv_data;
4359 ssl_load_keyfile(ssl_options.keylog_filename, &ssl_keylog_file, &ssl_master_key_map);
4360 key_map = is_early ? ssl_master_key_map.tls13_early_exporter
4361 : ssl_master_key_map.tls13_exporter;
4362 secret = (StringInfo *)g_hash_table_lookup(key_map, &ssl_session->client_random);
4363 if (!secret) {
4364 return false;
4367 return tls13_exporter_common(hash_algo, secret, label, context, context_length, key_length, out);
4369 /* }}} */
4372 /* UAT */
4374 #ifdef HAVE_LIBGNUTLS
4375 static void
4376 ssldecrypt_free_cb(void *r)
4378 ssldecrypt_assoc_t *h = (ssldecrypt_assoc_t *)r;
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);
4387 static void*
4388 ssldecrypt_copy_cb(void *dest, const void *orig, size_t len _U_)
4390 const ssldecrypt_assoc_t *o = (const ssldecrypt_assoc_t *)orig;
4391 ssldecrypt_assoc_t *d = (ssldecrypt_assoc_t *)dest;
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);
4399 return d;
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)
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)
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;
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);
4431 return false;
4434 *err = NULL;
4435 return true;
4437 #endif /* HAVE_LIBGNUTLS */
4439 static void
4440 ssl_src_prompt(packet_info *pinfo, char *result)
4442 SslPacketInfo* pi;
4443 uint32_t srcport = pinfo->srcport;
4445 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4446 if (pi != NULL)
4447 srcport = pi->srcport;
4449 snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "source (%u%s)", srcport, UTF8_RIGHTWARDS_ARROW);
4452 static void *
4453 ssl_src_value(packet_info *pinfo)
4455 SslPacketInfo* pi;
4457 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4458 if (pi == NULL)
4459 return GUINT_TO_POINTER(pinfo->srcport);
4461 return GUINT_TO_POINTER(pi->srcport);
4464 static void
4465 ssl_dst_prompt(packet_info *pinfo, char *result)
4467 SslPacketInfo* pi;
4468 uint32_t destport = pinfo->destport;
4470 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4471 if (pi != NULL)
4472 destport = pi->destport;
4474 snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "destination (%s%u)", UTF8_RIGHTWARDS_ARROW, destport);
4477 static void *
4478 ssl_dst_value(packet_info *pinfo)
4480 SslPacketInfo* pi;
4482 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4483 if (pi == NULL)
4484 return GUINT_TO_POINTER(pinfo->destport);
4486 return GUINT_TO_POINTER(pi->destport);
4489 static void
4490 ssl_both_prompt(packet_info *pinfo, char *result)
4492 SslPacketInfo* pi;
4493 uint32_t srcport = pinfo->srcport,
4494 destport = pinfo->destport;
4496 pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_tls, pinfo->curr_layer_num);
4497 if (pi != NULL)
4499 srcport = pi->srcport;
4500 destport = pi->destport;
4503 snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "both (%u%s%u)", srcport, UTF8_LEFT_RIGHT_ARROW, destport);
4506 static void
4507 tls_secrets_block_callback(const void *secrets, unsigned size)
4509 tls_keylog_process_lines(&ssl_master_key_map, (const uint8_t *)secrets, size);
4512 /*********************************************************************
4514 * Standard Wireshark Protocol Registration and housekeeping
4516 *********************************************************************/
4517 void
4518 proto_register_tls(void)
4521 /* Setup list of header fields See Section 1.6.1 for details*/
4522 static hf_register_info hf[] = {
4523 { &hf_tls_record,
4524 { "Record Layer", "tls.record",
4525 FT_NONE, BASE_NONE, NULL, 0x0,
4526 NULL, HFILL }
4528 { &hf_tls_record_content_type,
4529 { "Content Type", "tls.record.content_type",
4530 FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
4531 NULL, HFILL}
4533 { &hf_tls_record_opaque_type,
4534 { "Opaque Type", "tls.record.opaque_type",
4535 FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
4536 "Always set to value 23, actual content type is known after decryption", HFILL}
4538 { &hf_ssl2_msg_type,
4539 { "Handshake Message Type", "tls.ssl2.handshake.type",
4540 FT_UINT8, BASE_DEC, VALS(ssl_20_msg_types), 0x0,
4541 "SSLv2 handshake message type", HFILL}
4543 { &hf_tls_record_version,
4544 { "Version", "tls.record.version",
4545 FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
4546 "Record layer version", HFILL }
4548 { &hf_tls_record_length,
4549 { "Length", "tls.record.length",
4550 FT_UINT16, BASE_DEC, NULL, 0x0,
4551 "Length of TLS record data", HFILL }
4553 { &hf_tls_record_appdata,
4554 { "Encrypted Application Data", "tls.app_data",
4555 FT_BYTES, BASE_NONE, NULL, 0x0,
4556 "Payload is encrypted application data", HFILL }
4558 { &hf_tls_record_appdata_proto,
4559 { "Application Data Protocol", "tls.app_data_proto",
4560 FT_STRING, BASE_NONE, NULL, 0x0,
4561 NULL, HFILL }
4563 { &hf_ssl2_record,
4564 { "SSLv2 Record Header", "tls.record",
4565 FT_NONE, BASE_NONE, NULL, 0x0,
4566 "SSLv2 record data", HFILL }
4568 { &hf_ssl2_record_is_escape,
4569 { "Is Escape", "tls.record.is_escape",
4570 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4571 "Indicates a security escape", HFILL}
4573 { &hf_ssl2_record_padding_length,
4574 { "Padding Length", "tls.record.padding_length",
4575 FT_UINT8, BASE_DEC, NULL, 0x0,
4576 "Length of padding at end of record", HFILL }
4578 { &hf_tls_alert_message,
4579 { "Alert Message", "tls.alert_message",
4580 FT_NONE, BASE_NONE, NULL, 0x0,
4581 NULL, HFILL }
4583 { &hf_tls_alert_message_level,
4584 { "Level", "tls.alert_message.level",
4585 FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
4586 "Alert message level", HFILL }
4588 { &hf_tls_alert_message_description,
4589 { "Description", "tls.alert_message.desc",
4590 FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
4591 "Alert message description", HFILL }
4593 { &hf_tls_handshake_protocol,
4594 { "Handshake Protocol", "tls.handshake",
4595 FT_NONE, BASE_NONE, NULL, 0x0,
4596 "Handshake protocol message", HFILL}
4598 { &hf_tls_handshake_type,
4599 { "Handshake Type", "tls.handshake.type",
4600 FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
4601 "Type of handshake message", HFILL}
4603 { &hf_tls_handshake_length,
4604 { "Length", "tls.handshake.length",
4605 FT_UINT24, BASE_DEC, NULL, 0x0,
4606 "Length of handshake message", HFILL }
4608 { &hf_ssl2_handshake_cipher_spec,
4609 { "Cipher Spec", "tls.ssl2.handshake.cipherspec",
4610 FT_UINT24, BASE_HEX|BASE_EXT_STRING, &ssl_20_cipher_suites_ext, 0x0,
4611 "Cipher specification", HFILL }
4613 { &hf_tls_handshake_npn_selected_protocol_len,
4614 { "Selected Protocol Length", "tls.handshake.npn_selected_protocol_len",
4615 FT_UINT8, BASE_DEC, NULL, 0x0,
4616 NULL, HFILL }
4618 { &hf_tls_handshake_npn_selected_protocol,
4619 { "Selected Protocol", "tls.handshake.npn_selected_protocol",
4620 FT_STRING, BASE_NONE, NULL, 0x0,
4621 "Protocol to be used for connection", HFILL }
4623 { &hf_tls_handshake_npn_padding_len,
4624 { "Padding Length", "tls.handshake.npn_padding_len",
4625 FT_UINT8, BASE_DEC, NULL, 0x0,
4626 NULL, HFILL }
4628 { &hf_tls_handshake_npn_padding,
4629 { "Padding", "tls.handshake.npn_padding",
4630 FT_BYTES, BASE_NONE, NULL, 0x0,
4631 NULL, HFILL }
4633 { &ssl_hfs.hs_md5_hash,
4634 { "MD5 Hash", "tls.handshake.md5_hash",
4635 FT_NONE, BASE_NONE, NULL, 0x0,
4636 "Hash of messages, master_secret, etc.", HFILL }
4638 { &ssl_hfs.hs_sha_hash,
4639 { "SHA-1 Hash", "tls.handshake.sha_hash",
4640 FT_NONE, BASE_NONE, NULL, 0x0,
4641 "Hash of messages, master_secret, etc.", HFILL }
4643 { &hf_tls_heartbeat_message,
4644 { "Heartbeat Message", "tls.heartbeat_message",
4645 FT_NONE, BASE_NONE, NULL, 0x0,
4646 NULL, HFILL }
4648 { &hf_tls_heartbeat_message_type,
4649 { "Type", "tls.heartbeat_message.type",
4650 FT_UINT8, BASE_DEC, VALS(tls_heartbeat_type), 0x0,
4651 "Heartbeat message type", HFILL }
4653 { &hf_tls_heartbeat_message_payload_length,
4654 { "Payload Length", "tls.heartbeat_message.payload_length",
4655 FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
4657 { &hf_tls_heartbeat_message_payload,
4658 { "Payload Length", "tls.heartbeat_message.payload",
4659 FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
4661 { &hf_tls_heartbeat_message_padding,
4662 { "Payload Length", "tls.heartbeat_message.padding",
4663 FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
4665 { &hf_ssl2_handshake_challenge,
4666 { "Challenge", "tls.handshake.challenge",
4667 FT_NONE, BASE_NONE, NULL, 0x0,
4668 "Challenge data used to authenticate server", HFILL }
4670 { &hf_ssl2_handshake_cipher_spec_len,
4671 { "Cipher Spec Length", "tls.handshake.cipher_spec_len",
4672 FT_UINT16, BASE_DEC, NULL, 0x0,
4673 "Length of cipher specs field", HFILL }
4675 { &hf_ssl2_handshake_session_id_len,
4676 { "Session ID Length", "tls.handshake.session_id_length",
4677 FT_UINT16, BASE_DEC, NULL, 0x0,
4678 "Length of session ID field", HFILL }
4680 { &hf_ssl2_handshake_challenge_len,
4681 { "Challenge Length", "tls.handshake.challenge_length",
4682 FT_UINT16, BASE_DEC, NULL, 0x0,
4683 "Length of challenge field", HFILL }
4685 { &hf_ssl2_handshake_clear_key_len,
4686 { "Clear Key Data Length", "tls.handshake.clear_key_length",
4687 FT_UINT16, BASE_DEC, NULL, 0x0,
4688 "Length of clear key data", HFILL }
4690 { &hf_ssl2_handshake_enc_key_len,
4691 { "Encrypted Key Data Length", "tls.handshake.encrypted_key_length",
4692 FT_UINT16, BASE_DEC, NULL, 0x0,
4693 "Length of encrypted key data", HFILL }
4695 { &hf_ssl2_handshake_key_arg_len,
4696 { "Key Argument Length", "tls.handshake.key_arg_length",
4697 FT_UINT16, BASE_DEC, NULL, 0x0,
4698 "Length of key argument", HFILL }
4700 { &hf_ssl2_handshake_clear_key,
4701 { "Clear Key Data", "tls.handshake.clear_key_data",
4702 FT_NONE, BASE_NONE, NULL, 0x0,
4703 "Clear portion of MASTER-KEY", HFILL }
4705 { &hf_ssl2_handshake_enc_key,
4706 { "Encrypted Key", "tls.handshake.encrypted_key",
4707 FT_NONE, BASE_NONE, NULL, 0x0,
4708 "Secret portion of MASTER-KEY encrypted to server", HFILL }
4710 { &hf_ssl2_handshake_key_arg,
4711 { "Key Argument", "tls.handshake.key_arg",
4712 FT_NONE, BASE_NONE, NULL, 0x0,
4713 "Key Argument (e.g., Initialization Vector)", HFILL }
4715 { &hf_ssl2_handshake_session_id_hit,
4716 { "Session ID Hit", "tls.handshake.session_id_hit",
4717 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4718 "Did the server find the client's Session ID?", HFILL }
4720 { &hf_ssl2_handshake_cert_type,
4721 { "Certificate Type", "tls.ssl2.handshake.cert_type",
4722 FT_UINT8, BASE_DEC, VALS(ssl_20_certificate_type), 0x0,
4723 NULL, HFILL }
4725 { &hf_ssl2_handshake_connection_id_len,
4726 { "Connection ID Length", "tls.handshake.connection_id_length",
4727 FT_UINT16, BASE_DEC, NULL, 0x0,
4728 "Length of connection ID", HFILL }
4730 { &hf_ssl2_handshake_connection_id,
4731 { "Connection ID", "tls.handshake.connection_id",
4732 FT_NONE, BASE_NONE, NULL, 0x0,
4733 "Server's challenge to client", HFILL }
4736 { &hf_tls_segment_overlap,
4737 { "Segment overlap", "tls.segment.overlap",
4738 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4739 "Segment overlaps with other segments", HFILL }},
4741 { &hf_tls_segment_overlap_conflict,
4742 { "Conflicting data in segment overlap", "tls.segment.overlap.conflict",
4743 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4744 "Overlapping segments contained conflicting data", HFILL }},
4746 { &hf_tls_segment_multiple_tails,
4747 { "Multiple tail segments found", "tls.segment.multipletails",
4748 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4749 "Several tails were found when reassembling the pdu", HFILL }},
4751 { &hf_tls_segment_too_long_fragment,
4752 { "Segment too long", "tls.segment.toolongfragment",
4753 FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4754 "Segment contained data past end of the pdu", HFILL }},
4756 { &hf_tls_segment_error,
4757 { "Reassembling error", "tls.segment.error",
4758 FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4759 "Reassembling error due to illegal segments", HFILL }},
4761 { &hf_tls_segment_count,
4762 { "Segment count", "tls.segment.count",
4763 FT_UINT32, BASE_DEC, NULL, 0x0,
4764 NULL, HFILL }},
4766 { &hf_tls_segment,
4767 { "TLS segment", "tls.segment",
4768 FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4769 NULL, HFILL }},
4771 { &hf_tls_segments,
4772 { "Reassembled TLS segments", "tls.segments",
4773 FT_NONE, BASE_NONE, NULL, 0x0,
4774 NULL, HFILL }},
4776 { &hf_tls_reassembled_in,
4777 { "Reassembled PDU in frame", "tls.reassembled_in",
4778 FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4779 "The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},
4781 { &hf_tls_reassembled_length,
4782 { "Reassembled PDU length", "tls.reassembled.length",
4783 FT_UINT32, BASE_DEC, NULL, 0x0,
4784 "The total length of the reassembled payload", HFILL }},
4786 { &hf_tls_reassembled_data,
4787 { "Reassembled PDU data", "tls.reassembled.data",
4788 FT_BYTES, BASE_NONE, NULL, 0x00,
4789 "The payload of multiple reassembled TLS segments", HFILL }},
4791 { &hf_tls_segment_data,
4792 { "TLS segment data", "tls.segment.data",
4793 FT_BYTES, BASE_NONE, NULL, 0x00,
4794 "The payload of a single TLS segment", HFILL }
4797 { &hf_tls_handshake_fragment_count,
4798 { "Handshake Fragment count", "tls.handshake.fragment.count",
4799 FT_UINT32, BASE_DEC, NULL, 0x0,
4800 NULL, HFILL }},
4802 { &hf_tls_handshake_fragment,
4803 { "Handshake Fragment", "tls.handshake.fragment",
4804 FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4805 NULL, HFILL }},
4807 { &hf_tls_handshake_fragments,
4808 { "Reassembled Handshake Fragments", "tls.handshake.fragments",
4809 FT_NONE, BASE_NONE, NULL, 0x0,
4810 NULL, HFILL }},
4812 { &hf_tls_handshake_reassembled_in,
4813 { "Reassembled Handshake Message in frame", "tls.handshake.reassembled_in",
4814 FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4815 "The handshake message is fully reassembled in this frame", HFILL }},
4817 SSL_COMMON_HF_LIST(dissect_ssl3_hf, "tls")
4820 /* Setup protocol subtree array */
4821 static int *ett[] = {
4822 &ett_tls,
4823 &ett_tls_record,
4824 &ett_tls_alert,
4825 &ett_tls_handshake,
4826 &ett_tls_heartbeat,
4827 &ett_tls_certs,
4828 &ett_tls_segments,
4829 &ett_tls_segment,
4830 &ett_tls_hs_fragments,
4831 &ett_tls_hs_fragment,
4832 SSL_COMMON_ETT_LIST(dissect_ssl3_hf)
4835 static ei_register_info ei[] = {
4836 { &ei_ssl2_handshake_session_id_len_error, { "tls.handshake.session_id_length.error", PI_MALFORMED, PI_ERROR, "Session ID length error", EXPFILL }},
4837 { &ei_ssl3_heartbeat_payload_length, { "tls.heartbeat_message.payload_length.invalid", PI_MALFORMED, PI_ERROR, "Invalid heartbeat payload length", EXPFILL }},
4838 { &ei_tls_unexpected_message, { "tls.unexpected_message", PI_PROTOCOL, PI_ERROR, "Unexpected message", EXPFILL }},
4840 /* Generated from convert_proto_tree_add_text.pl */
4841 { &ei_tls_ignored_unknown_record, { "tls.ignored_unknown_record", PI_PROTOCOL, PI_WARN, "Ignored Unknown Record", EXPFILL }},
4843 SSL_COMMON_EI_LIST(dissect_ssl3_hf, "tls")
4846 static build_valid_func ssl_da_src_values[1] = {ssl_src_value};
4847 static build_valid_func ssl_da_dst_values[1] = {ssl_dst_value};
4848 static build_valid_func ssl_da_both_values[2] = {ssl_src_value, ssl_dst_value};
4849 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 static decode_as_t ssl_da = {"tls", "tls.port", 3, 2, ssl_da_values, "TCP", "port(s) as",
4851 decode_as_default_populate_list, decode_as_default_reset, decode_as_default_change, NULL};
4853 expert_module_t* expert_ssl;
4855 /* Register the protocol name and description */
4856 proto_tls = proto_register_protocol("Transport Layer Security",
4857 "TLS", "tls");
4859 ssl_associations = register_dissector_table("tls.port", "TLS Port", proto_tls, FT_UINT16, BASE_DEC);
4860 register_dissector_table_alias(ssl_associations, "ssl.port");
4862 /* Required function calls to register the header fields and
4863 * subtrees used */
4864 proto_register_field_array(proto_tls, hf, array_length(hf));
4865 proto_register_alias(proto_tls, "ssl");
4866 proto_register_subtree_array(ett, array_length(ett));
4867 expert_ssl = expert_register_protocol(proto_tls);
4868 expert_register_field_array(expert_ssl, ei, array_length(ei));
4871 module_t *ssl_module = prefs_register_protocol(proto_tls, proto_reg_handoff_ssl);
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
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);
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);
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 */
4909 prefs_register_filename_preference(ssl_module, "debug_file", "TLS debug file",
4910 "Redirect TLS debug to the file specified. Leave empty to disable debugging "
4911 "or use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr.",
4912 &ssl_debug_file_name, true);
4914 prefs_register_bool_preference(ssl_module,
4915 "desegment_ssl_records",
4916 "Reassemble TLS records spanning multiple TCP segments",
4917 "Whether the TLS dissector should reassemble TLS records spanning multiple TCP segments. "
4918 "To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
4919 &tls_desegment);
4920 prefs_register_bool_preference(ssl_module,
4921 "desegment_ssl_application_data",
4922 "Reassemble TLS Application Data spanning multiple TLS records",
4923 "Whether the TLS dissector should reassemble TLS Application Data spanning multiple TLS records. ",
4924 &tls_desegment_app_data);
4925 prefs_register_bool_preference(ssl_module,
4926 "ignore_ssl_mac_failed",
4927 "Message Authentication Code (MAC), ignore \"mac failed\"",
4928 "For troubleshooting ignore the mac check result and decrypt also if the Message Authentication Code (MAC) fails.",
4929 &tls_ignore_mac_failed);
4931 /* Port 443 is too overloaded... */
4932 range_convert_str(wmem_epan_scope(), &tls_try_heuristic_first, PORT_HEUR_DEFAULT, 65535);
4933 prefs_register_range_preference(ssl_module,
4934 "try_heuristic_first",
4935 "Try heuristic sub-dissectors first on ports",
4936 "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 &tls_try_heuristic_first, 65535);
4938 ssl_common_register_options(ssl_module, &ssl_options, false);
4941 /* heuristic dissectors for any preamble e.g. CredSSP before RDP */
4942 ssl_heur_subdissector_list = register_heur_dissector_list_with_description("tls", "TLS data", proto_tls);
4944 ssl_common_register_ssl_alpn_dissector_table("tls.alpn",
4945 "SSL/TLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs",
4946 proto_tls);
4948 tls_handle = register_dissector("tls", dissect_ssl, proto_tls);
4949 register_dissector("tls13-handshake", dissect_tls13_handshake, proto_tls);
4950 register_dissector("tls-echconfig", dissect_tls_echconfig, proto_tls);
4952 register_init_routine(ssl_init);
4953 register_cleanup_routine(ssl_cleanup);
4954 reassembly_table_register(&ssl_reassembly_table,
4955 &tcp_reassembly_table_functions);
4956 reassembly_table_register(&tls_hs_reassembly_table,
4957 &tls_hs_reassembly_table_functions);
4958 register_decode_as(&ssl_da);
4960 /* XXX: this seems unused due to new "Follow TLS" method, remove? */
4961 tls_follow_tap = register_tap("tls_follow");
4962 ssl_debug_printf("proto_register_ssl: registered tap %s:%d\n",
4963 "tls_follow", tls_follow_tap);
4965 register_follow_stream(proto_tls, "tls_follow", tcp_follow_conv_filter, tcp_follow_index_filter, tcp_follow_address_filter,
4966 tcp_port_to_display, ssl_follow_tap_listener, get_tcp_stream_count, NULL);
4967 secrets_register_type(SECRETS_TYPE_TLS, tls_secrets_block_callback);
4970 static int dissect_tls_sct_ber(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
4972 uint32_t offset = 0;
4973 /* Skip through tag and length for OCTET STRING encoding. */
4974 offset = dissect_ber_identifier(pinfo, tree, tvb, offset, NULL, NULL, NULL);
4975 offset = dissect_ber_length(pinfo, tree, tvb, offset, NULL, NULL);
4977 * RFC 6962 (Certificate Transparency) refers to RFC 5246 (TLS 1.2) for the
4978 * DigitallySigned format, so asssume that version.
4980 return tls_dissect_sct_list(&dissect_ssl3_hf, tvb, pinfo, tree, offset, tvb_captured_length(tvb), TLSV1DOT2_VERSION);
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.
4987 void
4988 proto_reg_handoff_ssl(void)
4990 if (files_identical(ssl_debug_file_name, ssl_options.keylog_filename)) {
4991 report_failure("The TLS debug file (\"%s\") cannot point to the same "
4992 "file as the TLS key log file (\"%s\").", ssl_debug_file_name,
4993 ssl_options.keylog_filename);
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.
4999 module_t *tls_module = prefs_find_module("tls");
5000 if (tls_module) {
5001 pref_t *pref_tls_debug = prefs_find_preference(tls_module, "debug_file");
5002 if (pref_tls_debug) {
5003 prefs_set_string_value(pref_tls_debug, "", pref_current);
5008 #ifdef HAVE_LIBGNUTLS
5009 /* parse key list */
5010 ssl_parse_uat();
5011 ssl_parse_old_keys();
5012 #endif
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.
5019 static bool initialized = false;
5020 if (initialized) {
5021 return;
5023 initialized = true;
5025 exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_7);
5027 /* Certificate Transparency extensions: 2 (Certificate), 5 (OCSP Response) */
5028 register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.2", dissect_tls_sct_ber, proto_tls, "SignedCertificateTimestampList");
5029 register_ber_oid_dissector("1.3.6.1.4.1.11129.2.4.5", dissect_tls_sct_ber, proto_tls, "SignedCertificateTimestampList");
5031 heur_dissector_add("tcp", dissect_ssl_heur, "SSL/TLS over TCP", "tls_tcp", proto_tls, HEURISTIC_ENABLE);
5032 dissector_add_string("http.upgrade", "tls", tls_handle);
5035 void
5036 ssl_dissector_add(unsigned port, dissector_handle_t handle)
5038 ssl_association_add("tls.port", tls_handle, handle, port, true);
5041 void
5042 ssl_dissector_delete(unsigned port, dissector_handle_t handle)
5044 ssl_association_remove("tls.port", tls_handle, handle, port, true);
5048 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5050 * Local variables:
5051 * c-basic-offset: 4
5052 * tab-width: 8
5053 * indent-tabs-mode: nil
5054 * End:
5056 * vi: set shiftwidth=4 tabstop=8 expandtab:
5057 * :indentSize=4:tabSize=8:noTabs=true: