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