HTTPS (almost) everywhere.
[metze/wireshark/wip.git] / epan / dissectors / packet-dtls.c
1 /* packet-dtls.c
2  * Routines for dtls dissection
3  * Copyright (c) 2006, Authesserre Samuel <sauthess@gmail.com>
4  * Copyright (c) 2007, Mikael Magnusson <mikma@users.sourceforge.net>
5  * Copyright (c) 2013, Hauke Mehrtens <hauke@hauke-m.de>
6  *
7  * Wireshark - Network traffic analyzer
8  * By Gerald Combs <gerald@wireshark.org>
9  * Copyright 1998 Gerald Combs
10  *
11  * SPDX-License-Identifier: GPL-2.0-or-later
12  *
13  *
14  * DTLS dissection and decryption.
15  * See RFC 4347 for details about DTLS specs.
16  *
17  * Notes :
18  * This dissector is based on the TLS dissector (packet-tls.c); Because of the similarity
19  *   of DTLS and TLS, decryption works like TLS with RSA key exchange.
20  * This dissector uses the sames things (file, libraries) as the TLS dissector (gnutls, packet-tls-utils.h)
21  *  to make it easily maintainable.
22  *
23  * It was developed to dissect and decrypt the OpenSSL v 0.9.8f DTLS implementation.
24  * It is limited to this implementation; there is no complete implementation.
25  *
26  * Implemented :
27  *  - DTLS dissection
28  *  - DTLS decryption (openssl one)
29  *
30  * Todo :
31  *  - activate correct Mac calculation when openssl will be corrected
32  *    (or if an other implementation works),
33  *    corrected code is ready and commented in packet-tls-utils.h file.
34  *  - add missing things (desegmentation, reordering... that aren't present in actual OpenSSL implementation)
35  */
36
37 #include "config.h"
38
39 #include <epan/packet.h>
40 #include <epan/to_str.h>
41 #include <epan/asn1.h>
42 #include <epan/tap.h>
43 #include <epan/reassemble.h>
44 #include <epan/uat.h>
45 #include <epan/sctpppids.h>
46 #include <epan/exported_pdu.h>
47 #include <epan/decode_as.h>
48 #include <epan/proto_data.h>
49 #include <epan/secrets.h>   /* for privkey_hash_table_new */
50 #include <wsutil/str_util.h>
51 #include <wsutil/strtoi.h>
52 #include <wsutil/utf8_entities.h>
53 #include <wsutil/rsa.h>
54 #include "packet-tls-utils.h"
55 #include "packet-dtls.h"
56
57 void proto_register_dtls(void);
58
59 #ifdef HAVE_LIBGNUTLS
60 /* DTLS User Access Table */
61 static ssldecrypt_assoc_t *dtlskeylist_uats = NULL;
62 static guint ndtlsdecrypt = 0;
63 #endif
64
65 /* we need to remember the top tree so that subdissectors we call are created
66  * at the root and not deep down inside the DTLS decode
67  */
68 static proto_tree *top_tree;
69
70 /*********************************************************************
71  *
72  * Protocol Constants, Variables, Data Structures
73  *
74  *********************************************************************/
75
76 /* https://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml */
77 static const value_string srtp_protection_profile_vals[] = {
78   { 0x0001, "SRTP_AES128_CM_HMAC_SHA1_80" }, /* RFC 5764 */
79   { 0x0002, "SRTP_AES128_CM_HMAC_SHA1_32" },
80   { 0x0005, "SRTP_NULL_HMAC_SHA1_80" },
81   { 0x0006, "SRTP_NULL_HMAC_SHA1_32" },
82   { 0x0007, "SRTP_AEAD_AES_128_GCM" }, /* RFC 7714 */
83   { 0x0008, "SRTP_AEAD_AES_256_GCM" },
84   { 0x00, NULL },
85 };
86
87 /* Initialize the protocol and registered fields */
88 static gint dtls_tap                            = -1;
89 static gint exported_pdu_tap                    = -1;
90 static gint proto_dtls                          = -1;
91 static gint hf_dtls_record                      = -1;
92 static gint hf_dtls_record_content_type         = -1;
93 static gint hf_dtls_record_version              = -1;
94 static gint hf_dtls_record_epoch                = -1;
95 static gint hf_dtls_record_sequence_number      = -1;
96 static gint hf_dtls_record_length               = -1;
97 static gint hf_dtls_record_appdata              = -1;
98 static gint hf_dtls_alert_message               = -1;
99 static gint hf_dtls_alert_message_level         = -1;
100 static gint hf_dtls_alert_message_description   = -1;
101 static gint hf_dtls_handshake_protocol          = -1;
102 static gint hf_dtls_handshake_type              = -1;
103 static gint hf_dtls_handshake_length            = -1;
104 static gint hf_dtls_handshake_message_seq       = -1;
105 static gint hf_dtls_handshake_fragment_offset   = -1;
106 static gint hf_dtls_handshake_fragment_length   = -1;
107
108 static gint hf_dtls_heartbeat_message                 = -1;
109 static gint hf_dtls_heartbeat_message_type            = -1;
110 static gint hf_dtls_heartbeat_message_payload_length  = -1;
111 static gint hf_dtls_heartbeat_message_payload         = -1;
112 static gint hf_dtls_heartbeat_message_padding         = -1;
113
114 static gint hf_dtls_fragments                   = -1;
115 static gint hf_dtls_fragment                    = -1;
116 static gint hf_dtls_fragment_overlap            = -1;
117 static gint hf_dtls_fragment_overlap_conflicts  = -1;
118 static gint hf_dtls_fragment_multiple_tails     = -1;
119 static gint hf_dtls_fragment_too_long_fragment  = -1;
120 static gint hf_dtls_fragment_error              = -1;
121 static gint hf_dtls_fragment_count              = -1;
122 static gint hf_dtls_reassembled_in              = -1;
123 static gint hf_dtls_reassembled_length          = -1;
124
125 static gint hf_dtls_hs_ext_use_srtp_protection_profiles_length  = -1;
126 static gint hf_dtls_hs_ext_use_srtp_protection_profile          = -1;
127 static gint hf_dtls_hs_ext_use_srtp_mki_length                  = -1;
128 static gint hf_dtls_hs_ext_use_srtp_mki                         = -1;
129
130 /* header fields used in ssl-utils, but defined here. */
131 static dtls_hfs_t dtls_hfs = { -1, -1 };
132
133 /* Initialize the subtree pointers */
134 static gint ett_dtls                   = -1;
135 static gint ett_dtls_record            = -1;
136 static gint ett_dtls_alert             = -1;
137 static gint ett_dtls_handshake         = -1;
138 static gint ett_dtls_heartbeat         = -1;
139 static gint ett_dtls_certs             = -1;
140
141 static gint ett_dtls_fragment          = -1;
142 static gint ett_dtls_fragments         = -1;
143
144 static expert_field ei_dtls_handshake_fragment_length_too_long = EI_INIT;
145 static expert_field ei_dtls_handshake_fragment_length_zero = EI_INIT;
146 static expert_field ei_dtls_handshake_fragment_past_end_msg = EI_INIT;
147 static expert_field ei_dtls_msg_len_diff_fragment = EI_INIT;
148 static expert_field ei_dtls_heartbeat_payload_length = EI_INIT;
149
150 #ifdef HAVE_LIBGNUTLS
151 static GHashTable      *dtls_key_hash   = NULL;
152 static wmem_stack_t    *key_list_stack  = NULL;
153 static uat_t           *dtlsdecrypt_uat = NULL;
154 static const gchar     *dtls_keys_list  = NULL;
155 #endif
156 static reassembly_table    dtls_reassembly_table;
157 static dissector_table_t   dtls_associations         = NULL;
158 static dissector_handle_t  dtls_handle               = NULL;
159 static StringInfo          dtls_compressed_data      = {NULL, 0};
160 static StringInfo          dtls_decrypted_data       = {NULL, 0};
161 static gint                dtls_decrypted_data_avail = 0;
162
163 static ssl_common_options_t dtls_options = { NULL, NULL};
164 static const gchar *dtls_debug_file_name = NULL;
165
166 static heur_dissector_list_t heur_subdissector_list;
167
168 static const fragment_items dtls_frag_items = {
169   /* Fragment subtrees */
170   &ett_dtls_fragment,
171   &ett_dtls_fragments,
172   /* Fragment fields */
173   &hf_dtls_fragments,
174   &hf_dtls_fragment,
175   &hf_dtls_fragment_overlap,
176   &hf_dtls_fragment_overlap_conflicts,
177   &hf_dtls_fragment_multiple_tails,
178   &hf_dtls_fragment_too_long_fragment,
179   &hf_dtls_fragment_error,
180   &hf_dtls_fragment_count,
181   /* Reassembled in field */
182   &hf_dtls_reassembled_in,
183   /* Reassembled length field */
184   &hf_dtls_reassembled_length,
185   /* Reassembled data field */
186   NULL,
187   /* Tag */
188   "Message fragments"
189 };
190
191 static SSL_COMMON_LIST_T(dissect_dtls_hf);
192
193 /* initialize/reset per capture state data (dtls sessions cache) */
194 static void
195 dtls_init(void)
196 {
197   module_t *dtls_module = prefs_find_module("dtls");
198   pref_t   *keys_list_pref;
199
200   ssl_data_alloc(&dtls_decrypted_data, 32);
201   ssl_data_alloc(&dtls_compressed_data, 32);
202
203   /* We should have loaded "keys_list" by now. Mark it obsolete */
204   if (dtls_module) {
205     keys_list_pref = prefs_find_preference(dtls_module, "keys_list");
206     if (! prefs_get_preference_obsolete(keys_list_pref)) {
207       prefs_set_preference_obsolete(keys_list_pref);
208     }
209   }
210 }
211
212 static void
213 dtls_cleanup(void)
214 {
215 #ifdef HAVE_LIBGNUTLS
216   if (key_list_stack != NULL) {
217     wmem_destroy_stack(key_list_stack);
218     key_list_stack = NULL;
219   }
220 #endif
221   g_free(dtls_decrypted_data.data);
222   g_free(dtls_compressed_data.data);
223 }
224
225 #ifdef HAVE_LIBGNUTLS
226 /* parse dtls related preferences (private keys and ports association strings) */
227 static void
228 dtls_parse_uat(void)
229 {
230   guint            i, port;
231   dissector_handle_t handle;
232
233   if (dtls_key_hash)
234   {
235       g_hash_table_destroy(dtls_key_hash);
236   }
237
238   /* remove only associations created from key list */
239   if (key_list_stack != NULL) {
240     while (wmem_stack_count(key_list_stack) > 0) {
241       port = GPOINTER_TO_UINT(wmem_stack_pop(key_list_stack));
242       handle = dissector_get_uint_handle(dtls_associations, port);
243       if (handle != NULL)
244         ssl_association_remove("dtls.port", dtls_handle, handle, port, FALSE);
245     }
246   }
247
248   /* parse private keys string, load available keys and put them in key hash*/
249   dtls_key_hash = privkey_hash_table_new();
250
251   ssl_set_debug(dtls_debug_file_name);
252
253   if (ndtlsdecrypt > 0)
254   {
255     if (key_list_stack == NULL)
256       key_list_stack = wmem_stack_new(NULL);
257
258     for (i = 0; i < ndtlsdecrypt; i++)
259     {
260       ssldecrypt_assoc_t *d = &(dtlskeylist_uats[i]);
261       ssl_parse_key_list(d, dtls_key_hash, "dtls.port", dtls_handle, FALSE);
262       if (key_list_stack && ws_strtou32(d->port, NULL, &port))
263         wmem_stack_push(key_list_stack, GUINT_TO_POINTER(port));
264     }
265   }
266
267   dissector_add_for_decode_as("sctp.port", dtls_handle);
268   dissector_add_for_decode_as("udp.port", dtls_handle);
269 }
270
271 static void
272 dtls_reset_uat(void)
273 {
274   g_hash_table_destroy(dtls_key_hash);
275   dtls_key_hash = NULL;
276 }
277
278 static void
279 dtls_parse_old_keys(void)
280 {
281   gchar          **old_keys, **parts, *err;
282   guint            i;
283   gchar          *uat_entry;
284
285   /* Import old-style keys */
286   if (dtlsdecrypt_uat && dtls_keys_list && dtls_keys_list[0]) {
287     old_keys = g_strsplit(dtls_keys_list, ";", 0);
288     for (i = 0; old_keys[i] != NULL; i++) {
289       parts = g_strsplit(old_keys[i], ",", 4);
290       if (parts[0] && parts[1] && parts[2] && parts[3]) {
291         gchar *path = uat_esc(parts[3], (guint)strlen(parts[3]));
292         uat_entry = wmem_strdup_printf(NULL, "\"%s\",\"%s\",\"%s\",\"%s\",\"\"",
293                         parts[0], parts[1], parts[2], path);
294         g_free(path);
295         if (!uat_load_str(dtlsdecrypt_uat, uat_entry, &err)) {
296           ssl_debug_printf("dtls_parse: Can't load UAT string %s: %s\n",
297                            uat_entry, err);
298           g_free(err);
299         }
300         wmem_free(NULL, uat_entry);
301       }
302       g_strfreev(parts);
303     }
304     g_strfreev(old_keys);
305   }
306 }
307 #endif  /* HAVE_LIBGNUTLS */
308
309 /*
310  * DTLS Dissection Routines
311  *
312  */
313
314 /* record layer dissector */
315 static gint dissect_dtls_record(tvbuff_t *tvb, packet_info *pinfo,
316                                 proto_tree *tree, guint32 offset,
317                                 SslSession *session, gint is_from_server,
318                                 SslDecryptSession *conv_data,
319                                 guint8 curr_layer_num_ssl);
320
321 /* alert message dissector */
322 static void dissect_dtls_alert(tvbuff_t *tvb, packet_info *pinfo,
323                                proto_tree *tree, guint32 offset,
324                                const SslSession *session);
325
326 /* handshake protocol dissector */
327 static void dissect_dtls_handshake(tvbuff_t *tvb, packet_info *pinfo,
328                                    proto_tree *tree, guint32 offset,
329                                    guint32 record_length,
330                                    SslSession *session, gint is_from_server,
331                                    SslDecryptSession *conv_data, guint8 content_type);
332
333 /* heartbeat message dissector */
334 static void dissect_dtls_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
335                                    proto_tree *tree, guint32 offset,
336                                    const SslSession *session, guint32 record_length,
337                                    gboolean decrypted);
338
339 static int dissect_dtls_hnd_hello_verify_request(ssl_common_dissect_t *hf, tvbuff_t *tvb,
340                                                  packet_info *pinfo, proto_tree *tree,
341                                                  guint32 offset, guint32 offset_end);
342
343 /*
344  * Support Functions
345  *
346  */
347
348 static gint  looks_like_dtls(tvbuff_t *tvb, guint32 offset);
349
350 /*********************************************************************
351  *
352  * Main dissector
353  *
354  *********************************************************************/
355 /*
356  * Code to actually dissect the packets
357  */
358 static int
359 dissect_dtls(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
360 {
361
362   conversation_t    *conversation;
363   proto_item        *ti;
364   proto_tree        *dtls_tree;
365   guint32            offset;
366   SslDecryptSession *ssl_session;
367   SslSession        *session;
368   gint               is_from_server;
369   guint8             curr_layer_num_ssl = pinfo->curr_layer_num;
370
371   ti                    = NULL;
372   dtls_tree             = NULL;
373   offset                = 0;
374   ssl_session           = NULL;
375   top_tree              = tree;
376
377   /* Track the version using conversations allows
378    * us to more frequently set the protocol column properly
379    * for continuation data frames.
380    *
381    * Also: We use the copy in conv_version as our cached copy,
382    *       so that we don't have to search the conversation
383    *       table every time we want the version; when setting
384    *       the conv_version, must set the copy in the conversation
385    *       in addition to conv_version
386    */
387   conversation = find_or_create_conversation(pinfo);
388   ssl_session = ssl_get_session(conversation, dtls_handle);
389   session = &ssl_session->session;
390   is_from_server = ssl_packet_from_server(session, dtls_associations, pinfo);
391
392   if (session->last_nontls_frame != 0 &&
393       session->last_nontls_frame >= pinfo->num) {
394     /* This conversation started at a different protocol and STARTTLS was
395      * used, but this packet comes too early. */
396     return 0;
397   }
398
399   /* try decryption only the first time we see this packet
400    * (to keep cipher synchronized) */
401   if (pinfo->fd->visited)
402     ssl_session = NULL;
403
404   /* Initialize the protocol column; we'll set it later when we
405    * figure out what flavor of DTLS it is */
406   col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
407
408   /* clear the the info column */
409   col_clear(pinfo->cinfo, COL_INFO);
410
411   /* Create display subtree for SSL as a whole */
412   ti = proto_tree_add_item(tree, proto_dtls, tvb, 0, -1, ENC_NA);
413   dtls_tree = proto_item_add_subtree(ti, ett_dtls);
414
415   /* iterate through the records in this tvbuff */
416   while (tvb_reported_length_remaining(tvb, offset) != 0)
417     {
418       /* first try to dispatch off the cached version
419        * known to be associated with the conversation
420        */
421       switch(session->version) {
422       case DTLSV1DOT0_VERSION:
423       case DTLSV1DOT0_OPENSSL_VERSION:
424       case DTLSV1DOT2_VERSION:
425         offset = dissect_dtls_record(tvb, pinfo, dtls_tree,
426                                      offset, session, is_from_server,
427                                      ssl_session, curr_layer_num_ssl);
428         break;
429
430         /* that failed, so apply some heuristics based
431          * on this individual packet
432          */
433       default:
434         if (looks_like_dtls(tvb, offset))
435           {
436             /* looks like dtls */
437             offset = dissect_dtls_record(tvb, pinfo, dtls_tree,
438                                          offset, session, is_from_server,
439                                          ssl_session, curr_layer_num_ssl);
440           }
441         else
442           {
443             /* looks like something unknown, so lump into
444              * continuation data
445              */
446             offset = tvb_reported_length(tvb);
447             col_append_sep_str(pinfo->cinfo, COL_INFO,
448                                NULL, "Continuation Data");
449
450             /* Set the protocol column */
451             col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
452           }
453         break;
454       }
455     }
456
457   // XXX there is no Follow DTLS Stream, is this tap needed?
458   tap_queue_packet(dtls_tap, pinfo, NULL);
459   return tvb_captured_length(tvb);
460 }
461
462 static gboolean
463 dissect_dtls_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
464
465 {
466   /* Stronger confirmation of DTLS packet is provided by verifying the
467    * captured payload length against the remainder of the UDP packet size. */
468   guint length = tvb_captured_length(tvb);
469   guint offset = 0;
470
471   if (tvb_reported_length(tvb) == length) {
472     /* The entire payload was captured. */
473     while (offset + 13 <= length && looks_like_dtls(tvb, offset)) {
474       /* Advance offset to the end of the current DTLS record */
475       offset += tvb_get_ntohs(tvb, offset + 11) + 13;
476       if (offset == length) {
477         dissect_dtls(tvb, pinfo, tree, data);
478         return TRUE;
479       }
480     }
481
482     if (pinfo->fragmented && offset >= 13) {
483       dissect_dtls(tvb, pinfo, tree, data);
484       return TRUE;
485     }
486     return FALSE;
487   }
488
489   /* This packet was truncated by the capture process due to a snapshot
490    * length - do our best with what we've got. */
491   while (tvb_captured_length_remaining(tvb, offset) >= 3) {
492     if (!looks_like_dtls(tvb, offset))
493       return FALSE;
494
495     offset += 3;
496     if (tvb_captured_length_remaining(tvb, offset) >= 10 ) {
497       offset += tvb_get_ntohs(tvb, offset + 8) + 10;
498     } else {
499       /* Dissect what we've got, which might be as little as 3 bytes. */
500       dissect_dtls(tvb, pinfo, tree, data);
501       return TRUE;
502     }
503     if (offset == length) {
504       /* Can this ever happen?  Well, just in case ... */
505       dissect_dtls(tvb, pinfo, tree, data);
506       return TRUE;
507     }
508   }
509
510   /* One last check to see if the current offset is at least less than the
511    * original number of bytes present before truncation or we're dealing with
512    * a packet fragment that's also been truncated. */
513   if ((length >= 3) && (offset <= tvb_reported_length(tvb) || pinfo->fragmented)) {
514     dissect_dtls(tvb, pinfo, tree, data);
515     return TRUE;
516   }
517   return FALSE;
518 }
519
520 static gboolean
521 dtls_is_null_cipher(guint cipher )
522 {
523   switch(cipher) {
524   case 0x0000:
525   case 0x0001:
526   case 0x0002:
527   case 0x002c:
528   case 0x002d:
529   case 0x002e:
530   case 0x003b:
531   case 0x00b0:
532   case 0x00b1:
533   case 0x00b4:
534   case 0x00b5:
535   case 0x00b8:
536   case 0x00b9:
537   case 0xc001:
538   case 0xc006:
539   case 0xc00b:
540   case 0xc010:
541   case 0xc015:
542   case 0xc039:
543   case 0xc03a:
544   case 0xc03b:
545     return TRUE;
546   default:
547     return FALSE;
548   }
549 }
550
551 static gboolean
552 decrypt_dtls_record(tvbuff_t *tvb, packet_info *pinfo, guint32 offset, SslDecryptSession *ssl,
553                     guint8 content_type, guint16 record_version, guint16 record_length, guint8 curr_layer_num_ssl)
554 {
555   gboolean    success;
556   SslDecoder *decoder;
557
558   /* if we can decrypt and decryption have success
559    * add decrypted data to this packet info */
560   if (!ssl || !(ssl->state & SSL_HAVE_SESSION_KEY)) {
561     ssl_debug_printf("decrypt_dtls_record: no session key\n");
562     return FALSE;
563   }
564   ssl_debug_printf("decrypt_dtls_record: app_data len %d, ssl state %X\n",
565                    record_length, ssl->state);
566
567   /* retrieve decoder for this packet direction */
568   if (ssl_packet_from_server(&ssl->session, dtls_associations, pinfo) != 0) {
569     ssl_debug_printf("decrypt_dtls_record: using server decoder\n");
570     decoder = ssl->server;
571   }
572   else {
573     ssl_debug_printf("decrypt_dtls_record: using client decoder\n");
574     decoder = ssl->client;
575   }
576
577   if (!decoder && !dtls_is_null_cipher(ssl->session.cipher)) {
578     ssl_debug_printf("decrypt_dtls_record: no decoder available\n");
579     return FALSE;
580   }
581
582   /* ensure we have enough storage space for decrypted data */
583   if (record_length > dtls_decrypted_data.data_len)
584     {
585       ssl_debug_printf("decrypt_dtls_record: allocating %d bytes"
586                        " for decrypt data (old len %d)\n",
587                        record_length + 32, dtls_decrypted_data.data_len);
588       dtls_decrypted_data.data = (guchar *)g_realloc(dtls_decrypted_data.data,
589                                            record_length + 32);
590       dtls_decrypted_data.data_len = record_length + 32;
591     }
592
593   /* run decryption and add decrypted payload to protocol data, if decryption
594    * is successful*/
595   dtls_decrypted_data_avail = dtls_decrypted_data.data_len;
596   if (ssl->state & SSL_HAVE_SESSION_KEY) {
597     if (!decoder) {
598       ssl_debug_printf("decrypt_dtls_record: no decoder available\n");
599       return FALSE;
600     }
601     success = ssl_decrypt_record(ssl, decoder, content_type, record_version, FALSE,
602                            tvb_get_ptr(tvb, offset, record_length), record_length,
603                            &dtls_compressed_data, &dtls_decrypted_data, &dtls_decrypted_data_avail) == 0;
604   }
605   else if (dtls_is_null_cipher(ssl->session.cipher)) {
606     /* Non-encrypting cipher NULL-XXX */
607     tvb_memcpy(tvb, dtls_decrypted_data.data, offset, record_length);
608     dtls_decrypted_data_avail = dtls_decrypted_data.data_len = record_length;
609     success = TRUE;
610   } else {
611     success = FALSE;
612   }
613
614   if (success && dtls_decrypted_data_avail > 0) {
615     const guchar *data = dtls_decrypted_data.data;
616     guint datalen = dtls_decrypted_data_avail;
617
618     ssl_add_record_info(proto_dtls, pinfo, data, datalen,
619         tvb_raw_offset(tvb)+offset,
620         NULL, (ContentType)content_type, curr_layer_num_ssl);
621   }
622   return success;
623 }
624
625 static void
626 export_pdu_packet(tvbuff_t *tvb, packet_info *pinfo, guint8 tag, const gchar *name)
627 {
628   exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, name, tag);
629
630   exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb);
631   exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb);
632   exp_pdu_data->pdu_tvb = tvb;
633
634   tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data);
635 }
636
637
638 /*********************************************************************
639  *
640  * DTLS Dissection Routines
641  *
642  *********************************************************************/
643 static gint
644 dissect_dtls_record(tvbuff_t *tvb, packet_info *pinfo,
645                     proto_tree *tree, guint32 offset,
646                     SslSession *session, gint is_from_server,
647                     SslDecryptSession* ssl,
648                     guint8 curr_layer_num_ssl)
649 {
650
651   /*
652    *    struct {
653    *        uint8 major, minor;
654    *    } ProtocolVersion;
655    *
656    *
657    *    enum {
658    *        change_cipher_spec(20), alert(21), handshake(22),
659    *        application_data(23), (255)
660    *    } ContentType;
661    *
662    *    struct {
663    *        ContentType type;
664    *        ProtocolVersion version;
665    *        uint16 epoch;               // New field
666    *        uint48 sequence_number;     // New field
667    *        uint16 length;
668    *        opaque fragment[TLSPlaintext.length];
669    *    } DTLSPlaintext;
670    */
671
672   guint32         record_length;
673   guint16         version;
674   guint16         epoch;
675   guint64         sequence_number;
676   guint8          content_type;
677   guint8          next_byte;
678   proto_tree     *ti;
679   proto_tree     *dtls_record_tree;
680   proto_item     *length_pi;
681   tvbuff_t       *decrypted;
682   SslRecordInfo  *record = NULL;
683   heur_dtbl_entry_t *hdtbl_entry;
684
685   /*
686    * Get the record layer fields of interest
687    */
688   content_type          = tvb_get_guint8(tvb, offset);
689   version               = tvb_get_ntohs(tvb, offset + 1);
690   epoch                 = tvb_get_ntohs(tvb, offset + 3);
691   sequence_number       = tvb_get_ntoh48(tvb, offset + 5);
692   record_length         = tvb_get_ntohs(tvb, offset + 11);
693
694   if(ssl){
695     if(ssl_packet_from_server(session, dtls_associations, pinfo)){
696      if (ssl->server) {
697       ssl->server->seq=sequence_number;
698       ssl->server->epoch=epoch;
699      }
700     }
701     else{
702      if (ssl->client) {
703       ssl->client->seq=sequence_number;
704       ssl->client->epoch=epoch;
705      }
706     }
707   }
708   if (!ssl_is_valid_content_type(content_type)) {
709
710     /* if we don't have a valid content_type, there's no sense
711      * continuing any further
712      */
713     col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Continuation Data");
714
715     /* Set the protocol column */
716     col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
717     return offset + 13 + record_length;
718   }
719
720   /*
721    * If GUI, fill in record layer part of tree
722    */
723
724   /* add the record layer subtree header */
725   ti = proto_tree_add_item(tree, hf_dtls_record, tvb,
726                                offset, 13 + record_length, ENC_NA);
727   dtls_record_tree = proto_item_add_subtree(ti, ett_dtls_record);
728
729   /* show the one-byte content type */
730   proto_tree_add_item(dtls_record_tree, hf_dtls_record_content_type,
731                         tvb, offset, 1, ENC_BIG_ENDIAN);
732   offset++;
733
734   /* add the version */
735   proto_tree_add_item(dtls_record_tree, hf_dtls_record_version, tvb,
736                         offset, 2, ENC_BIG_ENDIAN);
737   offset += 2;
738
739   /* show epoch */
740   proto_tree_add_uint(dtls_record_tree, hf_dtls_record_epoch, tvb, offset, 2, epoch);
741   offset += 2;
742
743   /* add sequence_number */
744   proto_tree_add_uint64(dtls_record_tree, hf_dtls_record_sequence_number, tvb, offset, 6, sequence_number);
745   offset += 6;
746
747   /* add the length */
748   length_pi = proto_tree_add_uint(dtls_record_tree, hf_dtls_record_length, tvb,
749                         offset, 2, record_length);
750   offset += 2;    /* move past length field itself */
751
752   /*
753    * if we don't already have a version set for this conversation,
754    * but this message's version is authoritative (i.e., it's
755    * not client_hello, then save the version to to conversation
756    * structure and print the column version
757    */
758   next_byte = tvb_get_guint8(tvb, offset);
759   if (session->version == SSL_VER_UNKNOWN)
760     ssl_try_set_version(session, ssl, content_type, next_byte, TRUE, version);
761   col_set_str(pinfo->cinfo, COL_PROTOCOL,
762       val_to_str_const(session->version, ssl_version_short_names, "DTLS"));
763
764   /*
765    * now dissect the next layer
766    */
767   ssl_debug_printf("dissect_dtls_record: content_type %d\n",content_type);
768
769   /* try to decrypt record on the first pass, if possible. Store decrypted
770    * record for later usage (without having to decrypt again). */
771   if (ssl) {
772     decrypt_dtls_record(tvb, pinfo, offset, ssl, content_type, version, record_length, curr_layer_num_ssl);
773   }
774   decrypted = ssl_get_record_info(tvb, proto_dtls, pinfo, tvb_raw_offset(tvb)+offset, curr_layer_num_ssl, &record);
775   if (decrypted) {
776     add_new_data_source(pinfo, decrypted, "Decrypted DTLS");
777   }
778   ssl_check_record_length(&dissect_dtls_hf, pinfo, (ContentType)content_type, record_length, length_pi, session->version, decrypted);
779
780
781   switch ((ContentType) content_type) {
782   case SSL_ID_CHG_CIPHER_SPEC:
783     col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Change Cipher Spec");
784     ssl_dissect_change_cipher_spec(&dissect_dtls_hf, tvb, pinfo,
785                                    dtls_record_tree, offset, session,
786                                    is_from_server, ssl);
787     if (ssl) {
788         ssl_finalize_decryption(ssl, tls_get_master_key_map(TRUE));
789         ssl_change_cipher(ssl, ssl_packet_from_server(session, dtls_associations, pinfo));
790     }
791     /* Heuristic: any later ChangeCipherSpec is not a resumption of this
792      * session. Set the flag after ssl_finalize_decryption such that it has
793      * a chance to use resume using Session Tickets. */
794     if (is_from_server)
795       session->is_session_resumed = FALSE;
796     break;
797   case SSL_ID_ALERT:
798     {
799       /* try to retrieve and use decrypted alert record, if any. */
800       if (decrypted) {
801         dissect_dtls_alert(decrypted, pinfo, dtls_record_tree, 0,
802                            session);
803       } else {
804         dissect_dtls_alert(tvb, pinfo, dtls_record_tree, offset,
805                            session);
806       }
807       break;
808     }
809   case SSL_ID_HANDSHAKE:
810     {
811       /* try to retrieve and use decrypted handshake record, if any. */
812       if (decrypted) {
813         dissect_dtls_handshake(decrypted, pinfo, dtls_record_tree, 0,
814                                tvb_reported_length(decrypted), session, is_from_server,
815                                ssl, content_type);
816       } else {
817         dissect_dtls_handshake(tvb, pinfo, dtls_record_tree, offset,
818                                record_length, session, is_from_server, ssl,
819                                content_type);
820       }
821       break;
822     }
823   case SSL_ID_APP_DATA:
824     /* show on info column what we are decoding */
825     col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Application Data");
826
827     /* app_handle discovery is done here instead of dissect_dtls_payload()
828      * because the protocol name needs to be displayed below. */
829     if (!session->app_handle) {
830       /* Unknown protocol handle, ssl_starttls_ack was not called before.
831        * Try to find an appropriate dissection handle and cache it. */
832       dissector_handle_t handle;
833       handle = dissector_get_uint_handle(dtls_associations, pinfo->srcport);
834       handle = handle ? handle : dissector_get_uint_handle(dtls_associations, pinfo->destport);
835       if (handle) session->app_handle = handle;
836     }
837
838     proto_item_set_text(dtls_record_tree,
839                         "%s Record Layer: %s Protocol: %s",
840                         val_to_str_const(session->version, ssl_version_short_names, "DTLS"),
841                         val_to_str_const(content_type, ssl_31_content_type, "unknown"),
842                         session->app_handle
843                         ? dissector_handle_get_dissector_name(session->app_handle)
844                         : "Application Data");
845
846     proto_tree_add_item(dtls_record_tree, hf_dtls_record_appdata, tvb,
847                         offset, record_length, ENC_NA);
848
849     /* show decrypted data info, if available */
850     if (decrypted)
851       {
852         gboolean  dissected;
853         guint16   saved_match_port;
854         /* try to dissect decrypted data*/
855         ssl_debug_printf("%s decrypted len %d\n", G_STRFUNC, record->data_len);
856
857         saved_match_port = pinfo->match_uint;
858         if (ssl_packet_from_server(session, dtls_associations, pinfo)) {
859           pinfo->match_uint = pinfo->srcport;
860         } else {
861           pinfo->match_uint = pinfo->destport;
862         }
863
864         /* find out a dissector using server port*/
865         if (session->app_handle) {
866           ssl_debug_printf("%s: found handle %p (%s)\n", G_STRFUNC,
867                            (void *)session->app_handle,
868                            dissector_handle_get_dissector_name(session->app_handle));
869           ssl_print_data("decrypted app data", record->plain_data, record->data_len);
870
871           if (have_tap_listener(exported_pdu_tap)) {
872             export_pdu_packet(decrypted, pinfo, EXP_PDU_TAG_PROTO_NAME,
873                               dissector_handle_get_dissector_name(session->app_handle));
874           }
875
876           dissected = call_dissector_only(session->app_handle, decrypted, pinfo, top_tree, NULL);
877         }
878         else {
879           /* try heuristic subdissectors */
880           dissected = dissector_try_heuristic(heur_subdissector_list, decrypted, pinfo, top_tree, &hdtbl_entry, NULL);
881           if (dissected && have_tap_listener(exported_pdu_tap)) {
882             export_pdu_packet(decrypted, pinfo, EXP_PDU_TAG_HEUR_PROTO_NAME, hdtbl_entry->short_name);
883           }
884         }
885         pinfo->match_uint = saved_match_port;
886         /* fallback to data dissector */
887         if (!dissected)
888           call_data_dissector(decrypted, pinfo, top_tree);
889       }
890     break;
891   case SSL_ID_HEARTBEAT:
892     /* try to retrieve and use decrypted alert record, if any. */
893     if (decrypted) {
894       dissect_dtls_heartbeat(decrypted, pinfo, dtls_record_tree, 0,
895                              session, tvb_reported_length (decrypted), TRUE);
896     } else {
897       dissect_dtls_heartbeat(tvb, pinfo, dtls_record_tree, offset,
898                              session, record_length, FALSE);
899     }
900     break;
901   }
902   offset += record_length; /* skip to end of record */
903
904   return offset;
905 }
906
907 /* dissects the alert message, filling in the tree */
908 static void
909 dissect_dtls_alert(tvbuff_t *tvb, packet_info *pinfo,
910                    proto_tree *tree, guint32 offset,
911                    const SslSession *session)
912 {
913   /*     struct {
914    *         AlertLevel level;
915    *         AlertDescription description;
916    *     } Alert;
917    */
918
919   proto_tree  *ti;
920   proto_tree  *ssl_alert_tree;
921   const gchar *level;
922   const gchar *desc;
923   guint8       byte;
924
925    ti = proto_tree_add_item(tree, hf_dtls_alert_message, tvb,
926                                offset, 2, ENC_NA);
927    ssl_alert_tree = proto_item_add_subtree(ti, ett_dtls_alert);
928
929   /*
930    * set the record layer label
931    */
932
933   /* first lookup the names for the alert level and description */
934   byte  = tvb_get_guint8(tvb, offset); /* grab the level byte */
935   level = try_val_to_str(byte, ssl_31_alert_level);
936
937   byte  = tvb_get_guint8(tvb, offset+1); /* grab the desc byte */
938   desc  = try_val_to_str(byte, ssl_31_alert_description);
939
940   /* now set the text in the record layer line */
941   if (level && desc)
942     {
943        col_append_sep_fstr(pinfo->cinfo, COL_INFO,
944              NULL, "Alert (Level: %s, Description: %s)",
945              level, desc);
946     }
947   else
948     {
949       col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Alert");
950     }
951
952   if (tree)
953     {
954       if (level && desc)
955         {
956           proto_item_set_text(tree, "%s Record Layer: Alert "
957                               "(Level: %s, Description: %s)",
958                               val_to_str_const(session->version, ssl_version_short_names, "DTLS"),
959                               level, desc);
960           proto_tree_add_item(ssl_alert_tree, hf_dtls_alert_message_level,
961                               tvb, offset++, 1, ENC_BIG_ENDIAN);
962
963           proto_tree_add_item(ssl_alert_tree, hf_dtls_alert_message_description,
964                               tvb, offset, 1, ENC_BIG_ENDIAN);
965         }
966       else
967         {
968           proto_item_set_text(tree,
969                               "%s Record Layer: Encrypted Alert",
970                               val_to_str_const(session->version, ssl_version_short_names, "DTLS"));
971           proto_item_set_text(ssl_alert_tree,
972                               "Alert Message: Encrypted Alert");
973         }
974     }
975 }
976
977
978 /* dissects the handshake protocol, filling the tree */
979 static void
980 dissect_dtls_handshake(tvbuff_t *tvb, packet_info *pinfo,
981                        proto_tree *tree, guint32 offset,
982                        guint32 record_length, SslSession *session,
983                        gint is_from_server,
984                        SslDecryptSession* ssl, guint8 content_type)
985 {
986   /*     struct {
987    *         HandshakeType msg_type;
988    *         uint24 length;
989    *         uint16 message_seq;          //new field
990    *         uint24 fragment_offset;      //new field
991    *         uint24 fragment_length;      //new field
992    *         select (HandshakeType) {
993    *             case hello_request:       HelloRequest;
994    *             case client_hello:        ClientHello;
995    *             case server_hello:        ServerHello;
996    *             case hello_verify_request: HelloVerifyRequest;     //new field
997    *             case certificate:         Certificate;
998    *             case server_key_exchange: ServerKeyExchange;
999    *             case certificate_request: CertificateRequest;
1000    *             case server_hello_done:   ServerHelloDone;
1001    *             case certificate_verify:  CertificateVerify;
1002    *             case client_key_exchange: ClientKeyExchange;
1003    *             case finished:            Finished;
1004    *         } body;
1005    *     } Handshake;
1006    */
1007
1008   proto_tree  *ti, *length_item = NULL, *fragment_length_item = NULL;
1009   proto_tree  *ssl_hand_tree;
1010   const gchar *msg_type_str;
1011   guint8       msg_type;
1012   guint32      length;
1013   guint16      message_seq;
1014   guint32      fragment_offset;
1015   guint32      fragment_length;
1016   gboolean     first_iteration;
1017   guint32      reassembled_length;
1018   tvbuff_t     *sub_tvb;
1019
1020   msg_type_str    = NULL;
1021   first_iteration = TRUE;
1022
1023   /* just as there can be multiple records per packet, there
1024    * can be multiple messages per record as long as they have
1025    * the same content type
1026    *
1027    * we really only care about this for handshake messages
1028    */
1029
1030   /* set record_length to the max offset */
1031   record_length += offset;
1032   for (; offset < record_length; offset += fragment_length,
1033          first_iteration = FALSE) /* set up for next pass, if any */
1034     {
1035       fragment_head *frag_msg = NULL;
1036       tvbuff_t      *new_tvb  = NULL;
1037       const gchar   *frag_str = NULL;
1038       gboolean       fragmented;
1039       guint32        hs_offset = offset;
1040
1041       /* add a subtree for the handshake protocol */
1042       ti = proto_tree_add_item(tree, hf_dtls_handshake_protocol, tvb, offset, -1, ENC_NA);
1043       ssl_hand_tree = proto_item_add_subtree(ti, ett_dtls_handshake);
1044
1045       msg_type = tvb_get_guint8(tvb, offset);
1046       fragment_length = tvb_get_ntoh24(tvb, offset + 9);
1047
1048       /* Check the fragment length in the handshake message. Assume it's an
1049        * encrypted handshake message if the message would pass
1050        * the record_length boundary. This is a workaround for the
1051        * situation where the first octet of the encrypted handshake
1052        * message is actually a known handshake message type.
1053        */
1054       if (offset + fragment_length <= record_length)
1055           msg_type_str = try_val_to_str(msg_type, ssl_31_handshake_type);
1056
1057       if (!msg_type_str && !first_iteration)
1058         {
1059           /* only dissect / report messages if they're
1060            * either the first message in this record
1061            * or they're a valid message type
1062            */
1063           return;
1064         }
1065
1066       /*
1067        * Update our info string
1068        */
1069       if (msg_type_str)
1070         {
1071           col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, msg_type_str);
1072         }
1073       else
1074         {
1075           /* if we don't have a valid handshake type, just quit dissecting */
1076           col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Handshake Message");
1077           return;
1078         }
1079
1080       proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_type,
1081                             tvb, offset, 1, msg_type);
1082       offset++;
1083
1084       length = tvb_get_ntoh24(tvb, offset);
1085       length_item = proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_length,
1086                                           tvb, offset, 3, length);
1087       offset += 3;
1088
1089       message_seq = tvb_get_ntohs(tvb,offset);
1090       proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_message_seq,
1091                             tvb, offset, 2, message_seq);
1092       offset += 2;
1093
1094       fragment_offset = tvb_get_ntoh24(tvb, offset);
1095       proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_fragment_offset,
1096                             tvb, offset, 3, fragment_offset);
1097       offset += 3;
1098
1099       fragment_length_item = proto_tree_add_uint(ssl_hand_tree,
1100                                                    hf_dtls_handshake_fragment_length,
1101                                                    tvb, offset, 3,
1102                                                    fragment_length);
1103       offset += 3;
1104       proto_item_set_len(ti, fragment_length + 12);
1105
1106       fragmented = FALSE;
1107       if (fragment_length + fragment_offset > length)
1108         {
1109           if (fragment_offset == 0)
1110             {
1111               expert_add_info(pinfo, fragment_length_item, &ei_dtls_handshake_fragment_length_too_long);
1112             }
1113           else
1114             {
1115               fragmented = TRUE;
1116               expert_add_info(pinfo, fragment_length_item, &ei_dtls_handshake_fragment_past_end_msg);
1117             }
1118         }
1119       else if (fragment_offset > 0 && fragment_length == 0)
1120         {
1121           /* Fragmented message, but no actual fragment... Note that if a
1122            * fragment was previously completed (reassembled_length == length),
1123            * it is already dissected. */
1124           expert_add_info(pinfo, fragment_length_item, &ei_dtls_handshake_fragment_length_zero);
1125           continue;
1126         }
1127       else if (fragment_length < length)
1128         {
1129           fragmented = TRUE;
1130
1131           /* Handle fragments of known message type, ignore others */
1132           if (ssl_is_valid_handshake_type(msg_type, TRUE))
1133             {
1134               /* Fragmented handshake message */
1135               pinfo->fragmented = TRUE;
1136
1137               /* Don't pass the reassembly code data that doesn't exist */
1138               tvb_ensure_bytes_exist(tvb, offset, fragment_length);
1139
1140               frag_msg = fragment_add(&dtls_reassembly_table,
1141                                       tvb, offset, pinfo, message_seq, NULL,
1142                                       fragment_offset, fragment_length, TRUE);
1143               /*
1144                * Do we already have a length for this reassembly?
1145                */
1146               reassembled_length = fragment_get_tot_len(&dtls_reassembly_table,
1147                                                         pinfo, message_seq, NULL);
1148               if (reassembled_length == 0)
1149                 {
1150                   /* No - set it to the length specified by this packet. */
1151                   fragment_set_tot_len(&dtls_reassembly_table,
1152                                        pinfo, message_seq, NULL, length);
1153                 }
1154               else
1155                 {
1156                   /* Yes - if this packet specifies a different length,
1157                      report an error. */
1158                   if (reassembled_length != length)
1159                     {
1160                       expert_add_info(pinfo, length_item, &ei_dtls_msg_len_diff_fragment);
1161                     }
1162                 }
1163
1164               if (frag_msg && (fragment_length + fragment_offset) == reassembled_length)
1165                 {
1166                   /* Reassembled */
1167                   new_tvb = process_reassembled_data(tvb, offset, pinfo,
1168                                                      "Reassembled DTLS",
1169                                                      frag_msg,
1170                                                      &dtls_frag_items,
1171                                                      NULL, tree);
1172                   frag_str = " (Reassembled)";
1173                 }
1174               else
1175                 {
1176                   frag_str = " (Fragment)";
1177                 }
1178
1179               col_append_str(pinfo->cinfo, COL_INFO, frag_str);
1180             }
1181         }
1182
1183       if (tree)
1184         {
1185           /* set the label text on the record layer expanding node */
1186           if (first_iteration)
1187             {
1188               proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s%s",
1189                                   val_to_str_const(session->version, ssl_version_short_names, "DTLS"),
1190                                   val_to_str_const(content_type, ssl_31_content_type, "unknown"),
1191                                   msg_type_str, (frag_str!=NULL) ? frag_str : "");
1192             }
1193           else
1194             {
1195               proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s%s",
1196                                   val_to_str_const(session->version, ssl_version_short_names, "DTLS"),
1197                                   val_to_str_const(content_type, ssl_31_content_type, "unknown"),
1198                                   "Multiple Handshake Messages",
1199                                   (frag_str!=NULL) ? frag_str : "");
1200             }
1201
1202           if (ssl_hand_tree)
1203             {
1204               /* set the text label on the subtree node */
1205               proto_item_set_text(ssl_hand_tree, "Handshake Protocol: %s%s",
1206                                   msg_type_str, (frag_str!=NULL) ? frag_str : "");
1207             }
1208         }
1209
1210         if (fragmented && !new_tvb)
1211         {
1212           /* Skip fragmented messages not reassembled yet */
1213           continue;
1214         }
1215
1216         if (new_tvb)
1217         {
1218           sub_tvb = new_tvb;
1219         }
1220         else
1221         {
1222           sub_tvb = tvb_new_subset_length(tvb, offset, fragment_length);
1223         }
1224
1225         /*
1226          * Add handshake message (including type, length, etc.) to hash (for
1227          * Extended Master Secret). The computation must however happen as if
1228          * the message was sent in a single fragment (RFC 6347, section 4.2.6).
1229          *
1230          * Skip CertificateVerify since the handshake hash covers just
1231          * ClientHello up to and including ClientKeyExchange, but the keys are
1232          * actually retrieved in ChangeCipherSpec (which comes after that).
1233          */
1234         if (msg_type != SSL_HND_CERT_VERIFY) {
1235           if (fragment_offset == 0) {
1236             /* Unfragmented packet. */
1237             ssl_calculate_handshake_hash(ssl, tvb, hs_offset, 12 + fragment_length);
1238           } else {
1239             /*
1240              * Handshake message was fragmented over multiple messages, fake a
1241              * single fragment and add reassembled data.
1242              */
1243             /* msg_type (1), length (3), message_seq (2) */
1244             ssl_calculate_handshake_hash(ssl, tvb, hs_offset, 6);
1245             /* fragment_offset (3) equals to zero. */
1246             ssl_calculate_handshake_hash(ssl, NULL, 0, 3);
1247             /* fragment_length (3) equals to length. */
1248             ssl_calculate_handshake_hash(ssl, tvb, hs_offset + 1, 3);
1249             /* actual handshake data */
1250             ssl_calculate_handshake_hash(ssl, sub_tvb, 0, length);
1251           }
1252         }
1253
1254         /* now dissect the handshake message, if necessary */
1255         switch ((HandshakeType) msg_type) {
1256           case SSL_HND_HELLO_REQUEST:
1257             /* hello_request has no fields, so nothing to do! */
1258             break;
1259
1260           case SSL_HND_CLIENT_HELLO:
1261             if (ssl) {
1262               /* ClientHello is first packet so set direction */
1263               ssl_set_server(session, &pinfo->dst, pinfo->ptype, pinfo->destport);
1264             }
1265             ssl_dissect_hnd_cli_hello(&dissect_dtls_hf, sub_tvb, pinfo,
1266                                       ssl_hand_tree, 0, length, session, ssl,
1267                                       &dtls_hfs);
1268             break;
1269
1270           case SSL_HND_SERVER_HELLO:
1271             ssl_try_set_version(session, ssl, SSL_ID_HANDSHAKE, SSL_HND_SERVER_HELLO, TRUE,
1272                                 tvb_get_ntohs(sub_tvb, 0));
1273
1274             ssl_dissect_hnd_srv_hello(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree,
1275                                       0, length, session, ssl, TRUE, FALSE);
1276             break;
1277
1278           case SSL_HND_HELLO_VERIFY_REQUEST:
1279             /*
1280              * The initial ClientHello and HelloVerifyRequest are not included
1281              * in the calculation of the handshake_messages
1282              * (https://tools.ietf.org/html/rfc6347#page-18). This is also
1283              * important for correct calculation of Extended Master Secret.
1284              */
1285             if (ssl && ssl->handshake_data.data_len) {
1286               ssl_debug_printf("%s erasing previous handshake_messages: %d\n", G_STRFUNC, ssl->handshake_data.data_len);
1287               wmem_free(wmem_file_scope(), ssl->handshake_data.data);
1288               ssl->handshake_data.data = NULL;
1289               ssl->handshake_data.data_len = 0;
1290             }
1291             dissect_dtls_hnd_hello_verify_request(&dissect_dtls_hf, sub_tvb, pinfo,
1292                                                   ssl_hand_tree, 0, length);
1293             break;
1294
1295           case SSL_HND_NEWSESSION_TICKET:
1296             /* no need to load keylog file here as it only links a previous
1297              * master key with this Session Ticket */
1298             ssl_dissect_hnd_new_ses_ticket(&dissect_dtls_hf, sub_tvb, pinfo,
1299                                            ssl_hand_tree, 0, length, session, ssl, TRUE,
1300                                            tls_get_master_key_map(FALSE)->tickets);
1301             break;
1302
1303           case SSL_HND_HELLO_RETRY_REQUEST:
1304             ssl_dissect_hnd_hello_retry_request(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree,
1305                                                 0, length, session, ssl, TRUE);
1306             break;
1307
1308           case SSL_HND_CERTIFICATE:
1309             ssl_dissect_hnd_cert(&dissect_dtls_hf, sub_tvb, ssl_hand_tree, 0, length,
1310                 pinfo, session, ssl, is_from_server, TRUE);
1311             break;
1312
1313           case SSL_HND_SERVER_KEY_EXCHG:
1314             ssl_dissect_hnd_srv_keyex(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree, 0, length, session);
1315             break;
1316
1317           case SSL_HND_CERT_REQUEST:
1318             ssl_dissect_hnd_cert_req(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree, 0, length, session, TRUE);
1319             break;
1320
1321           case SSL_HND_SVR_HELLO_DONE:
1322             /* This is not an abbreviated handshake, it is certainly not resumed. */
1323             session->is_session_resumed = FALSE;
1324             break;
1325
1326           case SSL_HND_CERT_VERIFY:
1327             ssl_dissect_hnd_cli_cert_verify(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree, 0, length, session->version);
1328             break;
1329
1330           case SSL_HND_CLIENT_KEY_EXCHG:
1331             ssl_dissect_hnd_cli_keyex(&dissect_dtls_hf, sub_tvb, ssl_hand_tree, 0, length, session);
1332             if (!ssl)
1333                 break;
1334
1335             /* try to find master key from pre-master key */
1336             if (!ssl_generate_pre_master_secret(ssl, length, sub_tvb, 0,
1337                                                 dtls_options.psk,
1338 #ifdef HAVE_LIBGNUTLS
1339                                                 dtls_key_hash,
1340 #endif
1341                                                 tls_get_master_key_map(TRUE))) {
1342                 ssl_debug_printf("dissect_dtls_handshake can't generate pre master secret\n");
1343             }
1344             break;
1345
1346           case SSL_HND_FINISHED:
1347             ssl_dissect_hnd_finished(&dissect_dtls_hf, sub_tvb, ssl_hand_tree,
1348                                      0, length, session, NULL);
1349             break;
1350
1351           case SSL_HND_CERT_STATUS:
1352             tls_dissect_hnd_certificate_status(&dissect_dtls_hf, sub_tvb, pinfo, ssl_hand_tree, 0, length);
1353             break;
1354
1355           case SSL_HND_CERT_URL:
1356           case SSL_HND_SUPPLEMENTAL_DATA:
1357           case SSL_HND_KEY_UPDATE:
1358           case SSL_HND_ENCRYPTED_EXTS:
1359           case SSL_HND_END_OF_EARLY_DATA: /* TLS 1.3 */
1360           case SSL_HND_COMPRESSED_CERTIFICATE:
1361           case SSL_HND_ENCRYPTED_EXTENSIONS: /* TLS 1.3 */
1362             /* TODO: does this need further dissection? */
1363             break;
1364         }
1365     }
1366 }
1367
1368 /* dissects the heartbeat message, filling in the tree */
1369 static void
1370 dissect_dtls_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
1371                        proto_tree *tree, guint32 offset,
1372                        const SslSession *session, guint32 record_length,
1373                        gboolean decrypted)
1374 {
1375   /*     struct {
1376    *         HeartbeatMessageType type;
1377    *         uint16 payload_length;
1378    *         opaque payload;
1379    *         opaque padding;
1380    *     } HeartbeatMessage;
1381    */
1382
1383   proto_tree  *ti;
1384   proto_tree  *dtls_heartbeat_tree;
1385   const gchar *type;
1386   guint8       byte;
1387   guint16      payload_length;
1388   guint16      padding_length;
1389
1390   ti = proto_tree_add_item(tree, hf_dtls_heartbeat_message, tvb,
1391                              offset, record_length - 32, ENC_NA);
1392   dtls_heartbeat_tree = proto_item_add_subtree(ti, ett_dtls_heartbeat);
1393
1394   /*
1395    * set the record layer label
1396    */
1397
1398   /* first lookup the names for the message type and the payload length */
1399   byte = tvb_get_guint8(tvb, offset);
1400   type = try_val_to_str(byte, tls_heartbeat_type);
1401
1402   payload_length = tvb_get_ntohs(tvb, offset + 1);
1403   padding_length = record_length - 3 - payload_length;
1404
1405   /* now set the text in the record layer line */
1406   if (type && (payload_length <= record_length - 16 - 3)) {
1407     col_append_sep_fstr(pinfo->cinfo, COL_INFO, NULL, "Heartbeat %s", type);
1408   } else {
1409     col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "Encrypted Heartbeat");
1410   }
1411
1412   if (tree) {
1413     if (type && ((payload_length <= record_length - 16 - 3) || decrypted)) {
1414       proto_item_set_text(tree, "%s Record Layer: Heartbeat "
1415                                 "%s",
1416                                 val_to_str_const(session->version, ssl_version_short_names, "DTLS"),
1417                                 type);
1418       proto_tree_add_item(dtls_heartbeat_tree, hf_dtls_heartbeat_message_type,
1419                           tvb, offset, 1, ENC_BIG_ENDIAN);
1420       offset += 1;
1421       ti = proto_tree_add_uint(dtls_heartbeat_tree, hf_dtls_heartbeat_message_payload_length,
1422                                tvb, offset, 2, payload_length);
1423       offset += 2;
1424       if (payload_length > record_length - 16 - 3) {
1425         expert_add_info_format(pinfo, ti, &ei_dtls_heartbeat_payload_length,
1426                                "Invalid heartbeat payload length (%d)", payload_length);
1427         /* Invalid heartbeat payload length, adjust to try decoding */
1428         payload_length = record_length - 16 - 3;
1429         padding_length = 16;
1430         proto_item_append_text (ti, " (invalid, using %u to decode payload)", payload_length);
1431
1432       }
1433       proto_tree_add_bytes_format(dtls_heartbeat_tree, hf_dtls_heartbeat_message_payload,
1434                                   tvb, offset, payload_length,
1435                                   NULL, "Payload (%u byte%s)",
1436                                   payload_length,
1437                                   plurality(payload_length, "", "s"));
1438       offset += payload_length;
1439       proto_tree_add_bytes_format(dtls_heartbeat_tree, hf_dtls_heartbeat_message_padding,
1440                                   tvb, offset, padding_length,
1441                                   NULL, "Padding and HMAC (%u byte%s)",
1442                                   padding_length,
1443                                   plurality(padding_length, "", "s"));
1444     } else {
1445       proto_item_set_text(tree,
1446                          "%s Record Layer: Encrypted Heartbeat",
1447                          val_to_str_const(session->version, ssl_version_short_names, "DTLS"));
1448       proto_item_set_text(dtls_heartbeat_tree,
1449                           "Encrypted Heartbeat Message");
1450     }
1451   }
1452 }
1453
1454 static int
1455 dissect_dtls_hnd_hello_verify_request(ssl_common_dissect_t *hf, tvbuff_t *tvb,
1456                                       packet_info *pinfo, proto_tree *tree,
1457                                       guint32 offset, guint32 offset_end)
1458 {
1459   /*
1460    * struct {
1461    *    ProtocolVersion server_version;
1462    *    opaque cookie<0..32>;
1463    * } HelloVerifyRequest;
1464    */
1465
1466   guint32 cookie_length;
1467
1468   /* show the client version */
1469   proto_tree_add_item(tree, dissect_dtls_hf.hf.hs_server_version, tvb,
1470                         offset, 2, ENC_BIG_ENDIAN);
1471   offset += 2;
1472
1473   if (!ssl_add_vector(hf, tvb, pinfo, tree, offset, offset_end, &cookie_length,
1474                       dtls_hfs.hf_dtls_handshake_cookie_len, 0, 32)) {
1475       return offset;
1476   }
1477   offset++;
1478
1479   if (cookie_length > 0)
1480   {
1481     proto_tree_add_item(tree, dtls_hfs.hf_dtls_handshake_cookie,
1482                         tvb, offset, cookie_length, ENC_NA);
1483     offset += cookie_length;
1484   }
1485
1486   return offset;
1487 }
1488
1489 gint
1490 dtls_dissect_hnd_hello_ext_use_srtp(tvbuff_t *tvb, proto_tree *tree,
1491                                     guint32 offset, guint32 ext_len)
1492 {
1493   /* From https://tools.ietf.org/html/rfc5764#section-4.1.1
1494    *
1495    * uint8 SRTPProtectionProfile[2];
1496    *
1497    * struct {
1498    *    SRTPProtectionProfiles SRTPProtectionProfiles;
1499    *    opaque srtp_mki<0..255>;
1500    * } UseSRTPData;
1501    *
1502    * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
1503    */
1504
1505   guint32 profiles_length, profiles_end, mki_length;
1506
1507   if (ext_len < 2) {
1508     /* XXX expert info, record too small */
1509     return offset + ext_len;
1510   }
1511
1512   /* SRTPProtectionProfiles list length */
1513   proto_tree_add_item_ret_uint(tree, hf_dtls_hs_ext_use_srtp_protection_profiles_length,
1514       tvb, offset, 2, ENC_BIG_ENDIAN, &profiles_length);
1515   if (profiles_length > ext_len - 2) {
1516     /* XXX expert info because length exceeds extension_data field */
1517     profiles_length = ext_len - 2;
1518   }
1519   offset += 2;
1520
1521   /* SRTPProtectionProfiles list items */
1522   profiles_end = offset + profiles_length;
1523   while (offset < profiles_end) {
1524     proto_tree_add_item(tree, hf_dtls_hs_ext_use_srtp_protection_profile,
1525         tvb, offset, 2, ENC_BIG_ENDIAN);
1526     offset += 2;
1527   }
1528
1529   /* MKI */
1530   proto_tree_add_item_ret_uint(tree, hf_dtls_hs_ext_use_srtp_mki_length,
1531       tvb, offset, 1, ENC_NA, &mki_length);
1532   offset++;
1533   if (mki_length > 0) {
1534     proto_tree_add_item(tree, hf_dtls_hs_ext_use_srtp_mki,
1535         tvb, offset, mki_length, ENC_NA);
1536     offset += mki_length;
1537   }
1538
1539   return offset;
1540 }
1541
1542 /*********************************************************************
1543  *
1544  * Support Functions
1545  *
1546  *********************************************************************/
1547
1548 /* this applies a heuristic to determine whether
1549  * or not the data beginning at offset looks like a
1550  * valid dtls record.
1551  */
1552 static gint
1553 looks_like_dtls(tvbuff_t *tvb, guint32 offset)
1554 {
1555   /* have to have a valid content type followed by a valid
1556    * protocol version
1557    */
1558   guint8  byte;
1559   guint16 version;
1560
1561   /* see if the first byte is a valid content type */
1562   byte = tvb_get_guint8(tvb, offset);
1563   if (!ssl_is_valid_content_type(byte))
1564     {
1565       return 0;
1566     }
1567
1568   /* now check to see if the version byte appears valid */
1569   version = tvb_get_ntohs(tvb, offset + 1);
1570   if (version != DTLSV1DOT0_VERSION && version != DTLSV1DOT2_VERSION &&
1571       version != DTLSV1DOT0_OPENSSL_VERSION)
1572     {
1573       return 0;
1574     }
1575
1576   return 1;
1577 }
1578
1579 /* UAT */
1580
1581 #if defined(HAVE_LIBGNUTLS)
1582 static void
1583 dtlsdecrypt_free_cb(void* r)
1584 {
1585   ssldecrypt_assoc_t* h = (ssldecrypt_assoc_t*)r;
1586
1587   g_free(h->ipaddr);
1588   g_free(h->port);
1589   g_free(h->protocol);
1590   g_free(h->keyfile);
1591   g_free(h->password);
1592 }
1593 #endif
1594
1595 #if 0
1596 static void
1597 dtlsdecrypt_update_cb(void* r _U_, const char** err _U_)
1598 {
1599   return;
1600 }
1601 #endif
1602
1603 #if defined(HAVE_LIBGNUTLS)
1604 static void *
1605 dtlsdecrypt_copy_cb(void* dest, const void* orig, size_t len _U_)
1606 {
1607   const ssldecrypt_assoc_t* o = (const ssldecrypt_assoc_t*)orig;
1608   ssldecrypt_assoc_t*       d = (ssldecrypt_assoc_t*)dest;
1609
1610   d->ipaddr    = g_strdup(o->ipaddr);
1611   d->port      = g_strdup(o->port);
1612   d->protocol  = g_strdup(o->protocol);
1613   d->keyfile   = g_strdup(o->keyfile);
1614   d->password  = g_strdup(o->password);
1615
1616   return d;
1617 }
1618
1619 UAT_CSTRING_CB_DEF(sslkeylist_uats,ipaddr,ssldecrypt_assoc_t)
1620 UAT_CSTRING_CB_DEF(sslkeylist_uats,port,ssldecrypt_assoc_t)
1621 UAT_CSTRING_CB_DEF(sslkeylist_uats,protocol,ssldecrypt_assoc_t)
1622 UAT_FILENAME_CB_DEF(sslkeylist_uats,keyfile,ssldecrypt_assoc_t)
1623 UAT_CSTRING_CB_DEF(sslkeylist_uats,password,ssldecrypt_assoc_t)
1624
1625 static gboolean
1626 dtlsdecrypt_uat_fld_protocol_chk_cb(void* r _U_, const char* p, guint len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
1627 {
1628     if (!p || strlen(p) == 0u) {
1629         // This should be removed in favor of Decode As. Make it optional.
1630         *err = NULL;
1631         return TRUE;
1632     }
1633
1634     if (!find_dissector(p)) {
1635         if (proto_get_id_by_filter_name(p) != -1) {
1636             *err = g_strdup_printf("While '%s' is a valid dissector filter name, that dissector is not configured"
1637                                    " to support DTLS decryption.\n\n"
1638                                    "If you need to decrypt '%s' over DTLS, please contact the Wireshark development team.", p, p);
1639         } else {
1640             char* ssl_str = ssl_association_info("dtls.port", "UDP");
1641             *err = g_strdup_printf("Could not find dissector for: '%s'\nCommonly used DTLS dissectors include:\n%s", p, ssl_str);
1642             g_free(ssl_str);
1643         }
1644         return FALSE;
1645     }
1646
1647     *err = NULL;
1648     return TRUE;
1649 }
1650 #endif
1651
1652 static void
1653 dtls_src_prompt(packet_info *pinfo, gchar *result)
1654 {
1655     SslPacketInfo* pi;
1656     guint32 srcport = pinfo->srcport;
1657
1658     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_dtls, pinfo->curr_layer_num);
1659     if (pi != NULL)
1660         srcport = pi->srcport;
1661
1662     g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "source (%u%s)", srcport, UTF8_RIGHTWARDS_ARROW);
1663 }
1664
1665 static gpointer
1666 dtls_src_value(packet_info *pinfo)
1667 {
1668     SslPacketInfo* pi;
1669
1670     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_dtls, pinfo->curr_layer_num);
1671     if (pi == NULL)
1672         return GUINT_TO_POINTER(pinfo->srcport);
1673
1674     return GUINT_TO_POINTER(pi->srcport);
1675 }
1676
1677 static void
1678 dtls_dst_prompt(packet_info *pinfo, gchar *result)
1679 {
1680     SslPacketInfo* pi;
1681     guint32 destport = pinfo->destport;
1682
1683     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_dtls, pinfo->curr_layer_num);
1684     if (pi != NULL)
1685         destport = pi->destport;
1686
1687     g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "destination (%s%u)", UTF8_RIGHTWARDS_ARROW, destport);
1688 }
1689
1690 static gpointer
1691 dtls_dst_value(packet_info *pinfo)
1692 {
1693     SslPacketInfo* pi;
1694
1695     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_dtls, pinfo->curr_layer_num);
1696     if (pi == NULL)
1697         return GUINT_TO_POINTER(pinfo->destport);
1698
1699     return GUINT_TO_POINTER(pi->destport);
1700 }
1701
1702 static void
1703 dtls_both_prompt(packet_info *pinfo, gchar *result)
1704 {
1705     SslPacketInfo* pi;
1706     guint32 srcport = pinfo->srcport,
1707             destport = pinfo->destport;
1708
1709     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto_dtls, pinfo->curr_layer_num);
1710     if (pi != NULL)
1711     {
1712         srcport = pi->srcport;
1713         destport = pi->destport;
1714     }
1715
1716     g_snprintf(result, MAX_DECODE_AS_PROMPT_LEN, "both (%u%s%u)", srcport, UTF8_LEFT_RIGHT_ARROW, destport);
1717 }
1718
1719 void proto_reg_handoff_dtls(void);
1720
1721 /*********************************************************************
1722  *
1723  * Standard Wireshark Protocol Registration and housekeeping
1724  *
1725  *********************************************************************/
1726 void
1727 proto_register_dtls(void)
1728 {
1729
1730   /* Setup list of header fields See Section 1.6.1 for details*/
1731   static hf_register_info hf[] = {
1732     { &hf_dtls_record,
1733       { "Record Layer", "dtls.record",
1734         FT_NONE, BASE_NONE, NULL, 0x0,
1735         NULL, HFILL }
1736     },
1737     { &hf_dtls_record_content_type,
1738       { "Content Type", "dtls.record.content_type",
1739         FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
1740         NULL, HFILL}
1741     },
1742     { &hf_dtls_record_version,
1743       { "Version", "dtls.record.version",
1744         FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
1745         "Record layer version", HFILL }
1746     },
1747     { &hf_dtls_record_epoch,
1748       { "Epoch", "dtls.record.epoch",
1749         FT_UINT16, BASE_DEC, NULL, 0x0,
1750         NULL, HFILL }
1751     },
1752     { &hf_dtls_record_sequence_number,
1753       { "Sequence Number", "dtls.record.sequence_number",
1754         FT_UINT64, BASE_DEC, NULL, 0x0,
1755         NULL, HFILL }
1756     },
1757     { &hf_dtls_record_length,
1758       { "Length", "dtls.record.length",
1759         FT_UINT16, BASE_DEC, NULL, 0x0,
1760         "Length of DTLS record data", HFILL }
1761     },
1762     { &hf_dtls_record_appdata,
1763       { "Encrypted Application Data", "dtls.app_data",
1764         FT_BYTES, BASE_NONE, NULL, 0x0,
1765         "Payload is encrypted application data", HFILL }
1766     },
1767     { & hf_dtls_alert_message,
1768       { "Alert Message", "dtls.alert_message",
1769         FT_NONE, BASE_NONE, NULL, 0x0,
1770         NULL, HFILL }
1771     },
1772     { & hf_dtls_alert_message_level,
1773       { "Level", "dtls.alert_message.level",
1774         FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
1775         "Alert message level", HFILL }
1776     },
1777     { &hf_dtls_alert_message_description,
1778       { "Description", "dtls.alert_message.desc",
1779         FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
1780         "Alert message description", HFILL }
1781     },
1782     { &hf_dtls_handshake_protocol,
1783       { "Handshake Protocol", "dtls.handshake",
1784         FT_NONE, BASE_NONE, NULL, 0x0,
1785         "Handshake protocol message", HFILL}
1786     },
1787     { &hf_dtls_handshake_type,
1788       { "Handshake Type", "dtls.handshake.type",
1789         FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
1790         "Type of handshake message", HFILL}
1791     },
1792     { &hf_dtls_handshake_length,
1793       { "Length", "dtls.handshake.length",
1794         FT_UINT24, BASE_DEC, NULL, 0x0,
1795         "Length of handshake message", HFILL }
1796     },
1797     { &hf_dtls_handshake_message_seq,
1798       { "Message Sequence", "dtls.handshake.message_seq",
1799         FT_UINT16, BASE_DEC, NULL, 0x0,
1800         "Message sequence of handshake message", HFILL }
1801     },
1802     { &hf_dtls_handshake_fragment_offset,
1803       { "Fragment Offset", "dtls.handshake.fragment_offset",
1804         FT_UINT24, BASE_DEC, NULL, 0x0,
1805         "Fragment offset of handshake message", HFILL }
1806     },
1807     { &hf_dtls_handshake_fragment_length,
1808       { "Fragment Length", "dtls.handshake.fragment_length",
1809         FT_UINT24, BASE_DEC, NULL, 0x0,
1810         "Fragment length of handshake message", HFILL }
1811     },
1812     { &dtls_hfs.hf_dtls_handshake_cookie_len,
1813       { "Cookie Length", "dtls.handshake.cookie_length",
1814         FT_UINT8, BASE_DEC, NULL, 0x0,
1815         "Length of the cookie field", HFILL }
1816     },
1817     { &dtls_hfs.hf_dtls_handshake_cookie,
1818       { "Cookie", "dtls.handshake.cookie",
1819         FT_BYTES, BASE_NONE, NULL, 0x0,
1820         NULL, HFILL }
1821     },
1822     { &hf_dtls_heartbeat_message,
1823       { "Heartbeat Message", "dtls.heartbeat_message",
1824         FT_NONE, BASE_NONE, NULL, 0x0,
1825         NULL, HFILL }
1826     },
1827     { &hf_dtls_heartbeat_message_type,
1828       { "Type", "dtls.heartbeat_message.type",
1829         FT_UINT8, BASE_DEC, VALS(tls_heartbeat_type), 0x0,
1830         "Heartbeat message type", HFILL }
1831     },
1832     { &hf_dtls_heartbeat_message_payload_length,
1833       { "Payload Length", "dtls.heartbeat_message.payload_length",
1834         FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
1835     },
1836     { &hf_dtls_heartbeat_message_payload,
1837       { "Payload Length", "dtls.heartbeat_message.payload",
1838         FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
1839     },
1840     { &hf_dtls_heartbeat_message_padding,
1841       { "Payload Length", "dtls.heartbeat_message.padding",
1842         FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
1843     },
1844     { &hf_dtls_fragments,
1845       { "Message fragments", "dtls.fragments",
1846         FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL }
1847     },
1848     { &hf_dtls_fragment,
1849       { "Message fragment", "dtls.fragment",
1850         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
1851     },
1852     { &hf_dtls_fragment_overlap,
1853       { "Message fragment overlap", "dtls.fragment.overlap",
1854         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
1855     },
1856     { &hf_dtls_fragment_overlap_conflicts,
1857       { "Message fragment overlapping with conflicting data",
1858         "dtls.fragment.overlap.conflicts",
1859        FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
1860     },
1861     { &hf_dtls_fragment_multiple_tails,
1862       { "Message has multiple tail fragments",
1863         "dtls.fragment.multiple_tails",
1864         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
1865     },
1866     { &hf_dtls_fragment_too_long_fragment,
1867       { "Message fragment too long", "dtls.fragment.too_long_fragment",
1868         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
1869     },
1870     { &hf_dtls_fragment_error,
1871       { "Message defragmentation error", "dtls.fragment.error",
1872         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
1873     },
1874     { &hf_dtls_fragment_count,
1875       { "Message fragment count", "dtls.fragment.count",
1876         FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
1877     },
1878     { &hf_dtls_reassembled_in,
1879       { "Reassembled in", "dtls.reassembled.in",
1880         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
1881     },
1882     { &hf_dtls_reassembled_length,
1883       { "Reassembled DTLS length", "dtls.reassembled.length",
1884         FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
1885     },
1886     { &hf_dtls_hs_ext_use_srtp_protection_profiles_length,
1887       { "SRTP Protection Profiles Length", "dtls.use_srtp.protection_profiles_length",
1888         FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
1889     },
1890     { &hf_dtls_hs_ext_use_srtp_protection_profile,
1891       { "SRTP Protection Profile", "dtls.use_srtp.protection_profile",
1892         FT_UINT16, BASE_HEX, VALS(srtp_protection_profile_vals), 0x00, NULL, HFILL }
1893     },
1894     { &hf_dtls_hs_ext_use_srtp_mki_length,
1895       { "MKI Length", "dtls.use_srtp.mki_length",
1896         FT_UINT8, BASE_DEC, NULL, 0x00, NULL, HFILL }
1897     },
1898     { &hf_dtls_hs_ext_use_srtp_mki,
1899       { "MKI", "dtls.use_srtp.mki",
1900         FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
1901     },
1902     SSL_COMMON_HF_LIST(dissect_dtls_hf, "dtls")
1903   };
1904
1905   /* Setup protocol subtree array */
1906   static gint *ett[] = {
1907     &ett_dtls,
1908     &ett_dtls_record,
1909     &ett_dtls_alert,
1910     &ett_dtls_handshake,
1911     &ett_dtls_heartbeat,
1912     &ett_dtls_certs,
1913     &ett_dtls_fragment,
1914     &ett_dtls_fragments,
1915     SSL_COMMON_ETT_LIST(dissect_dtls_hf)
1916   };
1917
1918   static ei_register_info ei[] = {
1919      { &ei_dtls_handshake_fragment_length_zero, { "dtls.handshake.fragment_length.zero", PI_PROTOCOL, PI_WARN, "Zero-length fragment length for fragmented message", EXPFILL }},
1920      { &ei_dtls_handshake_fragment_length_too_long, { "dtls.handshake.fragment_length.too_long", PI_PROTOCOL, PI_ERROR, "Fragment length is larger than message length", EXPFILL }},
1921      { &ei_dtls_handshake_fragment_past_end_msg, { "dtls.handshake.fragment_past_end_msg", PI_PROTOCOL, PI_ERROR, "Fragment runs past the end of the message", EXPFILL }},
1922      { &ei_dtls_msg_len_diff_fragment, { "dtls.msg_len_diff_fragment", PI_PROTOCOL, PI_ERROR, "Message length differs from value in earlier fragment", EXPFILL }},
1923      { &ei_dtls_heartbeat_payload_length, { "dtls.heartbeat_message.payload_length.invalid", PI_MALFORMED, PI_ERROR, "Invalid heartbeat payload length", EXPFILL }},
1924
1925      SSL_COMMON_EI_LIST(dissect_dtls_hf, "dtls")
1926   };
1927
1928   static build_valid_func dtls_da_src_values[1] = {dtls_src_value};
1929   static build_valid_func dtls_da_dst_values[1] = {dtls_dst_value};
1930   static build_valid_func dtls_da_both_values[2] = {dtls_src_value, dtls_dst_value};
1931   static decode_as_value_t dtls_da_values[3] = {{dtls_src_prompt, 1, dtls_da_src_values}, {dtls_dst_prompt, 1, dtls_da_dst_values}, {dtls_both_prompt, 2, dtls_da_both_values}};
1932   static decode_as_t dtls_da = {"dtls", "dtls.port", 3, 2, dtls_da_values, "UDP", "port(s) as",
1933                                decode_as_default_populate_list, decode_as_default_reset, decode_as_default_change, NULL};
1934
1935   expert_module_t* expert_dtls;
1936
1937   /* Register the protocol name and description */
1938   proto_dtls = proto_register_protocol("Datagram Transport Layer Security",
1939                                        "DTLS", "dtls");
1940
1941   dtls_associations = register_dissector_table("dtls.port", "DTLS Port", proto_dtls, FT_UINT16, BASE_DEC);
1942
1943   ssl_common_register_dtls_alpn_dissector_table("dtls.alpn",
1944         "DTLS Application-Layer Protocol Negotiation (ALPN) Protocol IDs",
1945         proto_dtls);
1946
1947   /* Required function calls to register the header fields and
1948    * subtrees used */
1949   proto_register_field_array(proto_dtls, hf, array_length(hf));
1950   proto_register_subtree_array(ett, array_length(ett));
1951   expert_dtls = expert_register_protocol(proto_dtls);
1952   expert_register_field_array(expert_dtls, ei, array_length(ei));
1953
1954   {
1955     module_t *dtls_module = prefs_register_protocol(proto_dtls, proto_reg_handoff_dtls);
1956
1957 #ifdef HAVE_LIBGNUTLS
1958     static uat_field_t dtlskeylist_uats_flds[] = {
1959       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, ipaddr, "IP address", ssldecrypt_uat_fld_ip_chk_cb, "IPv4 or IPv6 address (unused)"),
1960       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, port, "Port", ssldecrypt_uat_fld_port_chk_cb, "Port Number (optional)"),
1961       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, protocol, "Protocol", dtlsdecrypt_uat_fld_protocol_chk_cb, "Application Layer Protocol (optional)"),
1962       UAT_FLD_FILENAME_OTHER(sslkeylist_uats, keyfile, "Key File", ssldecrypt_uat_fld_fileopen_chk_cb, "Path to the keyfile."),
1963       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, password," Password (p12 file)", ssldecrypt_uat_fld_password_chk_cb, "Password"),
1964       UAT_END_FIELDS
1965     };
1966
1967     dtlsdecrypt_uat = uat_new("DTLS RSA Keylist",
1968                               sizeof(ssldecrypt_assoc_t),
1969                               "dtlsdecrypttablefile",         /* filename */
1970                               TRUE,                           /* from_profile */
1971                               &dtlskeylist_uats,              /* data_ptr */
1972                               &ndtlsdecrypt,                  /* numitems_ptr */
1973                               UAT_AFFECTS_DISSECTION,         /* affects dissection of packets, but not set of named fields */
1974                               "ChK12ProtocolsSection",        /* TODO, need revision - help */
1975                               dtlsdecrypt_copy_cb,
1976                               NULL, /* dtlsdecrypt_update_cb? */
1977                               dtlsdecrypt_free_cb,
1978                               dtls_parse_uat,
1979                               dtls_reset_uat,
1980                               dtlskeylist_uats_flds);
1981
1982     prefs_register_uat_preference(dtls_module, "cfg",
1983                                   "RSA keys list",
1984                                   "A table of RSA keys for DTLS decryption",
1985                                   dtlsdecrypt_uat);
1986
1987     prefs_register_string_preference(dtls_module, "keys_list", "RSA keys list (deprecated)",
1988                                      "Semicolon-separated list of private RSA keys used for DTLS decryption. "
1989                                      "Used by versions of Wireshark prior to 1.6",
1990                                      &dtls_keys_list);
1991 #endif  /* HAVE_LIBGNUTLS */
1992
1993     prefs_register_filename_preference(dtls_module, "debug_file", "DTLS debug file",
1994                                        "redirect dtls debug to file name; leave empty to disable debug, "
1995                                        "use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr\n",
1996                                        &dtls_debug_file_name, TRUE);
1997     ssl_common_register_options(dtls_module, &dtls_options, TRUE);
1998   }
1999
2000   dtls_handle = register_dissector("dtls", dissect_dtls, proto_dtls);
2001
2002   register_init_routine(dtls_init);
2003   register_cleanup_routine(dtls_cleanup);
2004   reassembly_table_register (&dtls_reassembly_table, &addresses_ports_reassembly_table_functions);
2005   register_decode_as(&dtls_da);
2006
2007   dtls_tap = register_tap("dtls");
2008   ssl_debug_printf("proto_register_dtls: registered tap %s:%d\n",
2009                    "dtls", dtls_tap);
2010
2011   heur_subdissector_list = register_heur_dissector_list("dtls", proto_dtls);
2012 }
2013
2014
2015 /* If this dissector uses sub-dissector registration add a registration
2016  * routine.  This format is required because a script is used to find
2017  * these routines and create the code that calls these routines.
2018  */
2019 void
2020 proto_reg_handoff_dtls(void)
2021 {
2022   static gboolean initialized = FALSE;
2023
2024 #ifdef HAVE_LIBGNUTLS
2025   dtls_parse_uat();
2026   dtls_parse_old_keys();
2027 #endif
2028   exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_7);
2029
2030   if (initialized == FALSE) {
2031     heur_dissector_add("udp", dissect_dtls_heur, "DTLS over UDP", "dtls_udp", proto_dtls, HEURISTIC_ENABLE);
2032     dissector_add_uint("sctp.ppi", DIAMETER_DTLS_PROTOCOL_ID, dtls_handle);
2033   }
2034
2035   initialized = TRUE;
2036 }
2037
2038 void
2039 dtls_dissector_add(guint port, dissector_handle_t handle)
2040 {
2041   ssl_association_add("dtls.port", dtls_handle, handle, port, FALSE);
2042 }
2043
2044 void
2045 dtls_dissector_delete(guint port, dissector_handle_t handle)
2046 {
2047   ssl_association_remove("dtls.port", dtls_handle, handle, port, FALSE);
2048 }
2049
2050 /*
2051  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
2052  *
2053  * Local Variables:
2054  * c-basic-offset: 2
2055  * tab-width: 8
2056  * indent-tabs-mode: nil
2057  * End:
2058  *
2059  * ex: set shiftwidth=2 tabstop=8 expandtab:
2060  * :indentSize=2:tabSize=8:noTabs=true:
2061  */