From Hauke Mehrtens via https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=8567
[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  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  *
26  *
27  * DTLS dissection and decryption.
28  * See RFC 4347 for details about DTLS specs.
29  *
30  * Notes :
31  * This dissector is based on the TLS dissector (packet-ssl.c); Because of the similarity
32  *   of DTLS and TLS, decryption works like TLS with RSA key exchange.
33  * This dissector uses the sames things (file, libraries) as the SSL dissector (gnutls, packet-ssl-utils.h)
34  *  to make it easily maintainable.
35  *
36  * It was developed to dissect and decrypt the OpenSSL v 0.9.8f DTLS implementation.
37  * It is limited to this implementation; there is no complete implementation.
38  *
39  * Implemented :
40  *  - DTLS dissection
41  *  - DTLS decryption (openssl one)
42  *
43  * Todo :
44  *  - activate correct Mac calculation when openssl will be corrected
45  *    (or if an other implementation works),
46  *    corrected code is ready and commented in packet-ssl-utils.h file.
47  *  - add missing things (desegmentation, reordering... that aren't present in actual OpenSSL implementation)
48  */
49
50 #include "config.h"
51
52 #include <glib.h>
53
54 #include <epan/packet.h>
55 #include <epan/conversation.h>
56 #include <epan/expert.h>
57 #include <epan/prefs.h>
58 #include <epan/asn1.h>
59 #include <epan/dissectors/packet-x509af.h>
60 #include <epan/emem.h>
61 #include <epan/tap.h>
62 #include <epan/reassemble.h>
63 #include "packet-ssl-utils.h"
64 #include <wsutil/file_util.h>
65 #include <epan/uat.h>
66 #include <epan/sctpppids.h>
67
68 void proto_register_dtls(void);
69
70 /* DTLS User Access Table */
71 static ssldecrypt_assoc_t *dtlskeylist_uats = NULL;
72 static guint ndtlsdecrypt = 0;
73
74 /* we need to remember the top tree so that subdissectors we call are created
75  * at the root and not deep down inside the DTLS decode
76  */
77 static proto_tree *top_tree;
78
79 /*********************************************************************
80  *
81  * Protocol Constants, Variables, Data Structures
82  *
83  *********************************************************************/
84
85 /* Initialize the protocol and registered fields */
86 static gint dtls_tap                            = -1;
87 static gint proto_dtls                          = -1;
88 static gint hf_dtls_record                      = -1;
89 static gint hf_dtls_record_content_type         = -1;
90 static gint hf_dtls_record_version              = -1;
91 static gint hf_dtls_record_epoch                = -1;
92 static gint hf_dtls_record_sequence_number      = -1;
93 static gint hf_dtls_record_length               = -1;
94 static gint hf_dtls_record_appdata              = -1;
95 static gint hf_dtls_change_cipher_spec          = -1;
96 static gint hf_dtls_alert_message               = -1;
97 static gint hf_dtls_alert_message_level         = -1;
98 static gint hf_dtls_alert_message_description   = -1;
99 static gint hf_dtls_handshake_protocol          = -1;
100 static gint hf_dtls_handshake_type              = -1;
101 static gint hf_dtls_handshake_length            = -1;
102 static gint hf_dtls_handshake_message_seq       = -1;
103 static gint hf_dtls_handshake_fragment_offset   = -1;
104 static gint hf_dtls_handshake_fragment_length   = -1;
105 static gint hf_dtls_handshake_client_version    = -1;
106 static gint hf_dtls_handshake_server_version    = -1;
107 static gint hf_dtls_handshake_random_time       = -1;
108 static gint hf_dtls_handshake_random_bytes      = -1;
109 static gint hf_dtls_handshake_cookie_len        = -1;
110 static gint hf_dtls_handshake_cookie            = -1;
111 static gint hf_dtls_handshake_cipher_suites_len = -1;
112 static gint hf_dtls_handshake_cipher_suites     = -1;
113 static gint hf_dtls_handshake_cipher_suite      = -1;
114 static gint hf_dtls_handshake_session_id        = -1;
115 static gint hf_dtls_handshake_comp_methods_len  = -1;
116 static gint hf_dtls_handshake_comp_methods      = -1;
117 static gint hf_dtls_handshake_comp_method       = -1;
118 static gint hf_dtls_handshake_extensions_len    = -1;
119 static gint hf_dtls_handshake_extension_type    = -1;
120 static gint hf_dtls_handshake_extension_len     = -1;
121 static gint hf_dtls_handshake_extension_data    = -1;
122 static gint hf_dtls_handshake_session_ticket_lifetime_hint = -1;
123 static gint hf_dtls_handshake_session_ticket_len = -1;
124 static gint hf_dtls_handshake_session_ticket    = -1;
125 static gint hf_dtls_handshake_certificates_len  = -1;
126 static gint hf_dtls_handshake_certificates      = -1;
127 static gint hf_dtls_handshake_certificate       = -1;
128 static gint hf_dtls_handshake_certificate_len   = -1;
129 static gint hf_dtls_handshake_cert_types_count  = -1;
130 static gint hf_dtls_handshake_cert_types        = -1;
131 static gint hf_dtls_handshake_cert_type         = -1;
132 static gint hf_dtls_handshake_finished          = -1;
133 /* static gint hf_dtls_handshake_md5_hash          = -1; */
134 /* static gint hf_dtls_handshake_sha_hash          = -1; */
135 static gint hf_dtls_handshake_session_id_len    = -1;
136 static gint hf_dtls_handshake_dnames_len        = -1;
137 static gint hf_dtls_handshake_dnames            = -1;
138 static gint hf_dtls_handshake_dname_len         = -1;
139 static gint hf_dtls_handshake_dname             = -1;
140
141 static gint hf_dtls_heartbeat_extension_mode          = -1;
142 static gint hf_dtls_heartbeat_message                 = -1;
143 static gint hf_dtls_heartbeat_message_type            = -1;
144 static gint hf_dtls_heartbeat_message_payload_length  = -1;
145 static gint hf_dtls_heartbeat_message_payload         = -1;
146 static gint hf_dtls_heartbeat_message_padding         = -1;
147
148 static gint hf_dtls_fragments                   = -1;
149 static gint hf_dtls_fragment                    = -1;
150 static gint hf_dtls_fragment_overlap            = -1;
151 static gint hf_dtls_fragment_overlap_conflicts  = -1;
152 static gint hf_dtls_fragment_multiple_tails     = -1;
153 static gint hf_dtls_fragment_too_long_fragment  = -1;
154 static gint hf_dtls_fragment_error              = -1;
155 static gint hf_dtls_fragment_count              = -1;
156 static gint hf_dtls_reassembled_in              = -1;
157 static gint hf_dtls_reassembled_length          = -1;
158
159 /* Initialize the subtree pointers */
160 static gint ett_dtls                   = -1;
161 static gint ett_dtls_record            = -1;
162 static gint ett_dtls_alert             = -1;
163 static gint ett_dtls_handshake         = -1;
164 static gint ett_dtls_heartbeat         = -1;
165 static gint ett_dtls_cipher_suites     = -1;
166 static gint ett_dtls_comp_methods      = -1;
167 static gint ett_dtls_extension         = -1;
168 static gint ett_dtls_random            = -1;
169 static gint ett_dtls_new_ses_ticket    = -1;
170 static gint ett_dtls_certs             = -1;
171 static gint ett_dtls_cert_types        = -1;
172 static gint ett_dtls_dnames            = -1;
173
174 static gint ett_dtls_fragment          = -1;
175 static gint ett_dtls_fragments         = -1;
176
177 static GHashTable         *dtls_session_hash         = NULL;
178 static GHashTable         *dtls_key_hash             = NULL;
179 static reassembly_table    dtls_reassembly_table;
180 static GTree*              dtls_associations         = NULL;
181 static dissector_handle_t  dtls_handle               = NULL;
182 static StringInfo          dtls_compressed_data      = {NULL, 0};
183 static StringInfo          dtls_decrypted_data       = {NULL, 0};
184 static gint                dtls_decrypted_data_avail = 0;
185
186 static uat_t *dtlsdecrypt_uat      = NULL;
187 static const gchar *dtls_keys_list = NULL;
188 #ifdef HAVE_LIBGNUTLS
189 static const gchar *dtls_debug_file_name = NULL;
190 #endif
191
192 static heur_dissector_list_t heur_subdissector_list;
193
194 static const fragment_items dtls_frag_items = {
195   /* Fragment subtrees */
196   &ett_dtls_fragment,
197   &ett_dtls_fragments,
198   /* Fragment fields */
199   &hf_dtls_fragments,
200   &hf_dtls_fragment,
201   &hf_dtls_fragment_overlap,
202   &hf_dtls_fragment_overlap_conflicts,
203   &hf_dtls_fragment_multiple_tails,
204   &hf_dtls_fragment_too_long_fragment,
205   &hf_dtls_fragment_error,
206   &hf_dtls_fragment_count,
207   /* Reassembled in field */
208   &hf_dtls_reassembled_in,
209   /* Reassembled length field */
210   &hf_dtls_reassembled_length,
211   /* Reassembled data field */
212   NULL,
213   /* Tag */
214   "Message fragments"
215 };
216
217 /* initialize/reset per capture state data (dtls sessions cache) */
218 static void
219 dtls_init(void)
220 {
221   module_t *dtls_module = prefs_find_module("dtls");
222   pref_t   *keys_list_pref;
223
224   ssl_common_init(&dtls_session_hash, &dtls_decrypted_data, &dtls_compressed_data);
225   reassembly_table_init (&dtls_reassembly_table, &addresses_reassembly_table_functions);
226
227   /* We should have loaded "keys_list" by now. Mark it obsolete */
228   if (dtls_module) {
229     keys_list_pref = prefs_find_preference(dtls_module, "keys_list");
230     if (! prefs_get_preference_obsolete(keys_list_pref)) {
231       prefs_set_preference_obsolete(keys_list_pref);
232     }
233   }
234 }
235
236 /* parse dtls related preferences (private keys and ports association strings) */
237 static void
238 dtls_parse_uat(void)
239 {
240   ep_stack_t       tmp_stack;
241   SslAssociation  *tmp_assoc;
242   guint            i;
243
244   if (dtls_key_hash)
245   {
246       g_hash_table_foreach(dtls_key_hash, ssl_private_key_free, NULL);
247       g_hash_table_destroy(dtls_key_hash);
248   }
249
250   /* remove only associations created from key list */
251   tmp_stack = ep_stack_new();
252   g_tree_foreach(dtls_associations, ssl_assoc_from_key_list, tmp_stack);
253   while ((tmp_assoc = (SslAssociation *)ep_stack_pop(tmp_stack)) != NULL) {
254     ssl_association_remove(dtls_associations, tmp_assoc);
255   }
256
257   /* parse private keys string, load available keys and put them in key hash*/
258   dtls_key_hash = g_hash_table_new(ssl_private_key_hash, ssl_private_key_equal);
259
260   ssl_set_debug(dtls_debug_file_name);
261
262   if (ndtlsdecrypt > 0)
263   {
264     for (i = 0; i < ndtlsdecrypt; i++)
265     {
266       ssldecrypt_assoc_t *d = &(dtlskeylist_uats[i]);
267       ssl_parse_key_list(d, dtls_key_hash, dtls_associations, dtls_handle, FALSE);
268     }
269   }
270
271   dissector_add_handle("sctp.port", dtls_handle);
272   dissector_add_handle("udp.port", dtls_handle);
273 }
274
275 static void
276 dtls_parse_old_keys(void)
277 {
278   gchar          **old_keys, **parts, *err;
279   guint            i;
280   gchar          *uat_entry;
281
282   /* Import old-style keys */
283   if (dtlsdecrypt_uat && dtls_keys_list && dtls_keys_list[0]) {
284     old_keys = ep_strsplit(dtls_keys_list, ";", 0);
285     for (i = 0; old_keys[i] != NULL; i++) {
286       parts = ep_strsplit(old_keys[i], ",", 4);
287       if (parts[0] && parts[1] && parts[2] && parts[3]) {
288         uat_entry = ep_strdup_printf("\"%s\",\"%s\",\"%s\",\"%s\",\"\"",
289                         parts[0], parts[1], parts[2], parts[3]);
290         if (!uat_load_str(dtlsdecrypt_uat, uat_entry, &err)) {
291           ssl_debug_printf("dtls_parse: Can't load UAT string %s: %s\n",
292                            uat_entry, err);
293         }
294       }
295     }
296   }
297 }
298
299 /*
300  * DTLS Dissection Routines
301  *
302  */
303
304 /* record layer dissector */
305 static gint dissect_dtls_record(tvbuff_t *tvb, packet_info *pinfo,
306                                 proto_tree *tree, guint32 offset,
307                                 guint *conv_version,
308                                 SslDecryptSession *conv_data);
309
310 /* change cipher spec dissector */
311 static void dissect_dtls_change_cipher_spec(tvbuff_t *tvb,
312                                             proto_tree *tree,
313                                             guint32 offset,
314                                             guint *conv_version, guint8 content_type);
315
316 /* alert message dissector */
317 static void dissect_dtls_alert(tvbuff_t *tvb, packet_info *pinfo,
318                                proto_tree *tree, guint32 offset,
319                                guint *conv_version);
320
321 /* handshake protocol dissector */
322 static void dissect_dtls_handshake(tvbuff_t *tvb, packet_info *pinfo,
323                                    proto_tree *tree, guint32 offset,
324                                    guint32 record_length,
325                                    guint *conv_version,
326                                    SslDecryptSession *conv_data, guint8 content_type);
327
328 /* heartbeat message dissector */
329 static void dissect_dtls_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
330                                    proto_tree *tree, guint32 offset,
331                                    guint *conv_version, guint32 record_length);
332
333
334 static void dissect_dtls_hnd_cli_hello(tvbuff_t *tvb,
335                                        proto_tree *tree,
336                                        guint32 offset, guint32 length,
337                                        SslDecryptSession* ssl);
338
339 static int dissect_dtls_hnd_srv_hello(tvbuff_t *tvb,
340                                        proto_tree *tree,
341                                        guint32 offset, guint32 length,
342                                        SslDecryptSession* ssl);
343
344 static int dissect_dtls_hnd_hello_verify_request(tvbuff_t *tvb,
345                                                   proto_tree *tree,
346                                                   guint32 offset,
347                                                   SslDecryptSession* ssl);
348
349 static void dissect_dtls_hnd_new_ses_ticket(tvbuff_t *tvb,
350                                        proto_tree *tree,
351                                        guint32 offset, guint32 length);
352
353 static void dissect_dtls_hnd_cert(tvbuff_t *tvb,
354                                   proto_tree *tree, guint32 offset, packet_info *pinfo);
355
356 static void dissect_dtls_hnd_cert_req(tvbuff_t *tvb,
357                                       proto_tree *tree,
358                                       guint32 offset);
359
360 static void dissect_dtls_hnd_finished(tvbuff_t *tvb,
361                                       proto_tree *tree,
362                                       guint32 offset,
363                                       guint* conv_version);
364
365 /*
366  * Support Functions
367  *
368  */
369 /*static void ssl_set_conv_version(packet_info *pinfo, guint version);*/
370 static gint  dtls_is_valid_handshake_type(guint8 type);
371
372 static gint  dtls_is_authoritative_version_message(guint8 content_type,
373                                                    guint8 next_byte);
374 static gint  looks_like_dtls(tvbuff_t *tvb, guint32 offset);
375
376 /*********************************************************************
377  *
378  * Main dissector
379  *
380  *********************************************************************/
381 /*
382  * Code to actually dissect the packets
383  */
384 static void
385 dissect_dtls(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
386 {
387
388   conversation_t    *conversation;
389   void              *conv_data;
390   proto_item        *ti;
391   proto_tree        *dtls_tree;
392   guint32            offset;
393   gboolean           first_record_in_frame;
394   SslDecryptSession *ssl_session;
395   guint*             conv_version;
396   Ssl_private_key_t *private_key;
397
398   ti                    = NULL;
399   dtls_tree             = NULL;
400   offset                = 0;
401   first_record_in_frame = TRUE;
402   ssl_session           = NULL;
403   top_tree              = tree;
404
405   /* Track the version using conversations allows
406    * us to more frequently set the protocol column properly
407    * for continuation data frames.
408    *
409    * Also: We use the copy in conv_version as our cached copy,
410    *       so that we don't have to search the conversation
411    *       table every time we want the version; when setting
412    *       the conv_version, must set the copy in the conversation
413    *       in addition to conv_version
414    */
415   conversation = find_or_create_conversation(pinfo);
416   conv_data    = conversation_get_proto_data(conversation, proto_dtls);
417
418   /* manage dtls decryption data */
419   /*get a valid ssl session pointer*/
420   if (conv_data != NULL)
421     ssl_session = (SslDecryptSession *)conv_data;
422   else {
423     SslService dummy;
424
425     ssl_session = se_new0(SslDecryptSession);
426     ssl_session_init(ssl_session);
427     ssl_session->version = SSL_VER_UNKNOWN;
428     conversation_add_proto_data(conversation, proto_dtls, ssl_session);
429
430     /* we need to know witch side of conversation is speaking */
431     if (ssl_packet_from_server(ssl_session, dtls_associations, pinfo)) {
432       dummy.addr = pinfo->src;
433       dummy.port = pinfo->srcport;
434     }
435     else {
436       dummy.addr = pinfo->dst;
437       dummy.port = pinfo->destport;
438     }
439     ssl_debug_printf("dissect_dtls server %s:%d\n",
440                      ep_address_to_str(&dummy.addr),dummy.port);
441
442     /* try to retrieve private key for this service. Do it now 'cause pinfo
443      * is not always available
444      * Note that with HAVE_LIBGNUTLS undefined private_key is always 0
445      * and thus decryption never engaged*/
446     private_key = (Ssl_private_key_t *)g_hash_table_lookup(dtls_key_hash, &dummy);
447     if (!private_key) {
448       ssl_debug_printf("dissect_dtls can't find private key for this server!\n");
449     }
450     else {
451       ssl_session->private_key = private_key->sexp_pkey;
452     }
453   }
454   conv_version= & ssl_session->version;
455
456   /* try decryption only the first time we see this packet
457    * (to keep cipher synchronized) */
458   if (pinfo->fd->flags.visited)
459     ssl_session = NULL;
460
461   /* Initialize the protocol column; we'll set it later when we
462    * figure out what flavor of DTLS it is (actually only one
463    version exists). */
464   col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
465
466   /* clear the the info column */
467   col_clear(pinfo->cinfo, COL_INFO);
468
469   /* Create display subtree for SSL as a whole */
470   if (tree)
471     {
472       ti = proto_tree_add_item(tree, proto_dtls, tvb, 0, -1, ENC_NA);
473       dtls_tree = proto_item_add_subtree(ti, ett_dtls);
474     }
475
476   /* iterate through the records in this tvbuff */
477   while (tvb_reported_length_remaining(tvb, offset) != 0)
478     {
479       /* on second and subsequent records per frame
480        * add a delimiter on info column
481        */
482       if (!first_record_in_frame)
483         {
484           col_append_str(pinfo->cinfo, COL_INFO, ", ");
485         }
486
487       /* first try to dispatch off the cached version
488        * known to be associated with the conversation
489        */
490       switch(*conv_version) {
491       case SSL_VER_DTLS:
492         offset = dissect_dtls_record(tvb, pinfo, dtls_tree,
493                                      offset, conv_version,
494                                      ssl_session);
495         break;
496       case SSL_VER_DTLS1DOT2:
497         offset = dissect_dtls_record(tvb, pinfo, dtls_tree,
498                                      offset, conv_version,
499                                      ssl_session);
500         break;
501
502         /* that failed, so apply some heuristics based
503          * on this individual packet
504          */
505       default:
506         if (looks_like_dtls(tvb, offset))
507           {
508             /* looks like dtls */
509             offset = dissect_dtls_record(tvb, pinfo, dtls_tree,
510                                          offset, conv_version,
511                                          ssl_session);
512           }
513         else
514           {
515             /* looks like something unknown, so lump into
516              * continuation data
517              */
518             offset = tvb_length(tvb);
519             col_append_str(pinfo->cinfo, COL_INFO,
520                              "Continuation Data");
521
522             /* Set the protocol column */
523             col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
524           }
525         break;
526       }
527
528       /* set up for next record in frame, if any */
529       first_record_in_frame = FALSE;
530     }
531
532   tap_queue_packet(dtls_tap, pinfo, NULL);
533 }
534
535 static gboolean
536 dissect_dtls_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_)
537
538 {
539   /* Stronger confirmation of DTLS packet is provided by verifying the
540    * captured payload length against the remainder of the UDP packet size. */
541   guint length = tvb_length(tvb);
542   guint offset = 0;
543
544   if (tvb_reported_length(tvb) == length) {
545     /* The entire payload was captured. */
546     while (offset + 13 <= length && looks_like_dtls(tvb, offset)) {
547       /* Advance offset to the end of the current DTLS record */
548       offset += tvb_get_ntohs(tvb, offset + 11) + 13;
549       if (offset == length) {
550         dissect_dtls(tvb, pinfo, tree);
551         return TRUE;
552       }
553     }
554
555     if (pinfo->fragmented && offset >= 13) {
556       dissect_dtls(tvb, pinfo, tree);
557       return TRUE;
558     }
559     return FALSE;
560   }
561
562   /* This packet was truncated by the capture process due to a snapshot
563    * length - do our best with what we've got. */
564   while (tvb_length_remaining(tvb, offset) >= 3) {
565     if (!looks_like_dtls(tvb, offset))
566       return FALSE;
567
568     offset += 3;
569     if (tvb_length_remaining(tvb, offset) >= 10 ) {
570       offset += tvb_get_ntohs(tvb, offset + 8) + 10;
571     } else {
572       /* Dissect what we've got, which might be as little as 3 bytes. */
573       dissect_dtls(tvb, pinfo, tree);
574       return TRUE;
575     }
576     if (offset == length) {
577       /* Can this ever happen?  Well, just in case ... */
578       dissect_dtls(tvb, pinfo, tree);
579       return TRUE;
580     }
581   }
582
583   /* One last check to see if the current offset is at least less than the
584    * original number of bytes present before truncation or we're dealing with
585    * a packet fragment that's also been truncated. */
586   if ((length >= 3) && (offset <= tvb_reported_length(tvb) || pinfo->fragmented)) {
587     dissect_dtls(tvb, pinfo, tree);
588     return TRUE;
589   }
590   return FALSE;
591 }
592
593 static gint
594 decrypt_dtls_record(tvbuff_t *tvb, packet_info *pinfo, guint32 offset,
595                     guint32 record_length, guint8 content_type, SslDecryptSession* ssl,
596                     gboolean save_plaintext)
597 {
598   gint        ret;
599   SslDecoder *decoder;
600
601   ret = 0;
602
603   /* if we can decrypt and decryption have success
604    * add decrypted data to this packet info */
605   if (!ssl || (!save_plaintext && !(ssl->state & SSL_HAVE_SESSION_KEY))) {
606     ssl_debug_printf("decrypt_dtls_record: no session key\n");
607     return ret;
608   }
609   ssl_debug_printf("decrypt_dtls_record: app_data len %d, ssl state %X\n",
610                    record_length, ssl->state);
611
612   /* retrieve decoder for this packet direction */
613   if (ssl_packet_from_server(ssl, dtls_associations, pinfo) != 0) {
614     ssl_debug_printf("decrypt_dtls_record: using server decoder\n");
615     decoder = ssl->server;
616   }
617   else {
618     ssl_debug_printf("decrypt_dtls_record: using client decoder\n");
619     decoder = ssl->client;
620   }
621
622   if (!decoder && ssl->cipher != 0x0001 && ssl->cipher != 0x0002) {
623     ssl_debug_printf("decrypt_dtls_record: no decoder available\n");
624     return ret;
625   }
626
627   /* ensure we have enough storage space for decrypted data */
628   if (record_length > dtls_decrypted_data.data_len)
629     {
630       ssl_debug_printf("decrypt_dtls_record: allocating %d bytes"
631                        " for decrypt data (old len %d)\n",
632                        record_length + 32, dtls_decrypted_data.data_len);
633       dtls_decrypted_data.data = (guchar *)g_realloc(dtls_decrypted_data.data,
634                                            record_length + 32);
635       dtls_decrypted_data.data_len = record_length + 32;
636     }
637
638   /* run decryption and add decrypted payload to protocol data, if decryption
639    * is successful*/
640   dtls_decrypted_data_avail = dtls_decrypted_data.data_len;
641   if (ssl->state & SSL_HAVE_SESSION_KEY) {
642     if (!decoder) {
643       ssl_debug_printf("decrypt_dtls_record: no decoder available\n");
644       return ret;
645     }
646     if (ssl_decrypt_record(ssl, decoder, content_type, tvb_get_ptr(tvb, offset, record_length), record_length,
647                            &dtls_compressed_data, &dtls_decrypted_data, &dtls_decrypted_data_avail) == 0)
648       ret = 1;
649   }
650   else if (ssl->cipher == 0x0001 || ssl->cipher == 0x0002) {
651     /* Non-encrypting cipher RSA-NULL-MD5 or RSA-NULL-SHA */
652     memcpy(dtls_decrypted_data.data, tvb_get_ptr(tvb, offset, record_length), record_length);
653     dtls_decrypted_data_avail = dtls_decrypted_data.data_len = record_length;
654     ret = 1;
655   }
656
657   if (ret && save_plaintext) {
658     ssl_add_data_info(proto_dtls, pinfo, dtls_decrypted_data.data, dtls_decrypted_data_avail,
659                       tvb_raw_offset(tvb)+offset, 0);
660   }
661
662   return ret;
663 }
664
665
666
667
668
669 /*********************************************************************
670  *
671  * DTLS Dissection Routines
672  *
673  *********************************************************************/
674 static gint
675 dissect_dtls_record(tvbuff_t *tvb, packet_info *pinfo,
676                     proto_tree *tree, guint32 offset,
677                     guint *conv_version,
678                     SslDecryptSession* ssl)
679 {
680
681   /*
682    *    struct {
683    *        uint8 major, minor;
684    *    } ProtocolVersion;
685    *
686    *
687    *    enum {
688    *        change_cipher_spec(20), alert(21), handshake(22),
689    *        application_data(23), (255)
690    *    } ContentType;
691    *
692    *    struct {
693    *        ContentType type;
694    *        ProtocolVersion version;
695    *        uint16 epoch;               // New field
696    *        uint48 sequence_number;     // New field
697    *        uint16 length;
698    *        opaque fragment[TLSPlaintext.length];
699    *    } DTLSPlaintext;
700    */
701
702   guint32         record_length;
703   guint16         version;
704   guint16         epoch;
705   gdouble         sequence_number;
706   gint64          sequence_number_temp;
707   guint8          content_type;
708   guint8          next_byte;
709   proto_tree     *ti;
710   proto_tree     *dtls_record_tree;
711   SslAssociation *association;
712   SslDataInfo    *appl_data;
713
714   ti               = NULL;
715   dtls_record_tree = NULL;
716
717   /*
718    * Get the record layer fields of interest
719    */
720   content_type          = tvb_get_guint8(tvb, offset);
721   version               = tvb_get_ntohs(tvb, offset + 1);
722   epoch                 = tvb_get_ntohs(tvb, offset + 3);
723   sequence_number       = tvb_get_ntohl(tvb, offset + 7);
724   sequence_number_temp  = tvb_get_ntohs(tvb, offset + 5);
725   sequence_number_temp  = sequence_number_temp<<32;
726   sequence_number      += sequence_number_temp;
727   record_length         = tvb_get_ntohs(tvb, offset + 11);
728
729   if(ssl){
730     if(ssl_packet_from_server(ssl, dtls_associations, pinfo)){
731      if (ssl->server) {
732       ssl->server->seq=(guint32)sequence_number;
733       ssl->server->epoch=epoch;
734      }
735     }
736     else{
737      if (ssl->client) {
738       ssl->client->seq=(guint32)sequence_number;
739       ssl->client->epoch=epoch;
740      }
741     }
742   }
743   if (!ssl_is_valid_content_type(content_type)) {
744
745     /* if we don't have a valid content_type, there's no sense
746      * continuing any further
747      */
748     col_append_str(pinfo->cinfo, COL_INFO, "Continuation Data");
749
750     /* Set the protocol column */
751     col_set_str(pinfo->cinfo, COL_PROTOCOL, "DTLS");
752     return offset + 13 + record_length;
753   }
754
755   /*
756    * If GUI, fill in record layer part of tree
757    */
758
759   if (tree)
760     {
761       /* add the record layer subtree header */
762       tvb_ensure_bytes_exist(tvb, offset, 13 + record_length);
763       ti = proto_tree_add_item(tree, hf_dtls_record, tvb,
764                                offset, 13 + record_length, ENC_NA);
765       dtls_record_tree = proto_item_add_subtree(ti, ett_dtls_record);
766     }
767
768   if (dtls_record_tree)
769     {
770
771       /* show the one-byte content type */
772       proto_tree_add_item(dtls_record_tree, hf_dtls_record_content_type,
773                           tvb, offset, 1, ENC_BIG_ENDIAN);
774       offset++;
775
776       /* add the version */
777       proto_tree_add_item(dtls_record_tree, hf_dtls_record_version, tvb,
778                           offset, 2, ENC_BIG_ENDIAN);
779       offset += 2;
780
781       /* show epoch */
782       proto_tree_add_uint(dtls_record_tree, hf_dtls_record_epoch, tvb, offset, 2, epoch);
783
784       offset += 2;
785
786       /* add sequence_number */
787
788       proto_tree_add_double(dtls_record_tree, hf_dtls_record_sequence_number, tvb, offset, 6, sequence_number);
789
790       offset += 6;
791
792       /* add the length */
793       proto_tree_add_uint(dtls_record_tree, hf_dtls_record_length, tvb,
794                           offset, 2, record_length);
795       offset += 2;    /* move past length field itself */
796
797     }
798   else
799     {
800       /* if no GUI tree, then just skip over those fields */
801       offset += 13;
802     }
803
804
805   /*
806    * if we don't already have a version set for this conversation,
807    * but this message's version is authoritative (i.e., it's
808    * not client_hello, then save the version to to conversation
809    * structure and print the column version
810    */
811   next_byte = tvb_get_guint8(tvb, offset);
812   if (*conv_version == SSL_VER_UNKNOWN
813       && dtls_is_authoritative_version_message(content_type, next_byte))
814     {
815       if (version == DTLSV1DOT0_VERSION ||
816           version == DTLSV1DOT0_VERSION_NOT)
817         {
818
819           *conv_version = SSL_VER_DTLS;
820           if (ssl) {
821             ssl->version_netorder = version;
822             ssl->state |= SSL_VERSION;
823           }
824           /*ssl_set_conv_version(pinfo, ssl->version);*/
825         }
826       if (version == DTLSV1DOT2_VERSION)
827         {
828
829           *conv_version = SSL_VER_DTLS1DOT2;
830           if (ssl) {
831             ssl->version_netorder = version;
832             ssl->state |= SSL_VERSION;
833           }
834           /*ssl_set_conv_version(pinfo, ssl->version);*/
835         }
836     }
837   if (check_col(pinfo->cinfo, COL_PROTOCOL))
838     {
839       if (version == DTLSV1DOT0_VERSION)
840         {
841           col_set_str(pinfo->cinfo, COL_PROTOCOL,
842                       val_to_str_const(SSL_VER_DTLS, ssl_version_short_names, "SSL"));
843         }
844       else if (version == DTLSV1DOT2_VERSION)
845         {
846           col_set_str(pinfo->cinfo, COL_PROTOCOL,
847                       val_to_str_const(SSL_VER_DTLS1DOT2, ssl_version_short_names, "SSL"));
848         }
849       else
850         {
851           col_set_str(pinfo->cinfo, COL_PROTOCOL,"DTLS");
852         }
853     }
854
855   /*
856    * now dissect the next layer
857    */
858   ssl_debug_printf("dissect_dtls_record: content_type %d\n",content_type);
859
860   /* PAOLO try to decrypt each record (we must keep ciphers "in sync")
861    * store plain text only for app data */
862
863   switch (content_type) {
864   case SSL_ID_CHG_CIPHER_SPEC:
865     col_append_str(pinfo->cinfo, COL_INFO, "Change Cipher Spec");
866     dissect_dtls_change_cipher_spec(tvb, dtls_record_tree,
867                                     offset, conv_version, content_type);
868     if (ssl) ssl_change_cipher(ssl, ssl_packet_from_server(ssl, dtls_associations, pinfo));
869     break;
870   case SSL_ID_ALERT:
871     {
872       tvbuff_t* decrypted;
873       decrypted = 0;
874       if (ssl&&decrypt_dtls_record(tvb, pinfo, offset,
875                                    record_length, content_type, ssl, FALSE))
876         ssl_add_record_info(proto_dtls, pinfo, dtls_decrypted_data.data,
877                             dtls_decrypted_data_avail, offset);
878
879       /* try to retrieve and use decrypted alert record, if any. */
880       decrypted = ssl_get_record_info(tvb, proto_dtls, pinfo, offset);
881       if (decrypted) {
882         dissect_dtls_alert(decrypted, pinfo, dtls_record_tree, 0,
883                            conv_version);
884         add_new_data_source(pinfo, decrypted, "Decrypted SSL record");
885       } else {
886         dissect_dtls_alert(tvb, pinfo, dtls_record_tree, offset,
887                            conv_version);
888       }
889       break;
890     }
891   case SSL_ID_HANDSHAKE:
892     {
893       tvbuff_t* decrypted;
894       decrypted = 0;
895       /* try to decrypt handshake record, if possible. Store decrypted
896        * record for later usage. The offset is used as 'key' to identify
897        * this record into the packet (we can have multiple handshake records
898        * in the same frame) */
899       if (ssl && decrypt_dtls_record(tvb, pinfo, offset,
900                                      record_length, content_type, ssl, FALSE))
901         ssl_add_record_info(proto_dtls, pinfo, dtls_decrypted_data.data,
902                             dtls_decrypted_data_avail, offset);
903
904       /* try to retrieve and use decrypted handshake record, if any. */
905       decrypted = ssl_get_record_info(tvb, proto_dtls, pinfo, offset);
906       if (decrypted) {
907         dissect_dtls_handshake(decrypted, pinfo, dtls_record_tree, 0,
908                                tvb_length(decrypted), conv_version, ssl, content_type);
909         add_new_data_source(pinfo, decrypted, "Decrypted SSL record");
910       } else {
911         dissect_dtls_handshake(tvb, pinfo, dtls_record_tree, offset,
912                                record_length, conv_version, ssl, content_type);
913       }
914       break;
915     }
916   case SSL_ID_APP_DATA:
917     if (ssl)
918       decrypt_dtls_record(tvb, pinfo, offset,
919                           record_length, content_type, ssl, TRUE);
920
921     /* show on info column what we are decoding */
922     col_append_str(pinfo->cinfo, COL_INFO, "Application Data");
923
924     if (!dtls_record_tree)
925       break;
926
927     /* we need dissector information when the selected packet is shown.
928      * ssl session pointer is NULL at that time, so we can't access
929      * info cached there*/
930     association = ssl_association_find(dtls_associations, pinfo->srcport, pinfo->ptype == PT_TCP);
931     association = association ? association : ssl_association_find(dtls_associations, pinfo->destport, pinfo->ptype == PT_TCP);
932
933     proto_item_set_text(dtls_record_tree,
934                         "%s Record Layer: %s Protocol: %s",
935                         val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
936                         val_to_str_const(content_type, ssl_31_content_type, "unknown"),
937                         association?association->info:"Application Data");
938
939     /* show decrypted data info, if available */
940     appl_data = ssl_get_data_info(proto_dtls, pinfo, tvb_raw_offset(tvb)+offset);
941     if (appl_data && (appl_data->plain_data.data_len > 0))
942       {
943         tvbuff_t *next_tvb;
944         gboolean  dissected;
945         /* try to dissect decrypted data*/
946         ssl_debug_printf("dissect_dtls_record decrypted len %d\n",
947                          appl_data->plain_data.data_len);
948
949         /* create a new TVB structure for desegmented data */
950         next_tvb = tvb_new_child_real_data(tvb,
951                                            appl_data->plain_data.data,
952                                            appl_data->plain_data.data_len,
953                                            appl_data->plain_data.data_len);
954
955         add_new_data_source(pinfo, next_tvb, "Decrypted DTLS data");
956
957         /* find out a dissector using server port*/
958         if (association && association->handle) {
959           ssl_debug_printf("dissect_dtls_record found association %p\n", (void *)association);
960           ssl_print_data("decrypted app data",appl_data->plain_data.data, appl_data->plain_data.data_len);
961
962           dissected = call_dissector_only(association->handle, next_tvb, pinfo, top_tree, NULL);
963         }
964         else {
965           /* try heuristic subdissectors */
966           dissected = dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, top_tree, NULL);
967         }
968         if (dissected)
969           break;
970       }
971
972     proto_tree_add_item(dtls_record_tree, hf_dtls_record_appdata, tvb,
973                         offset, record_length, ENC_NA);
974     break;
975   case SSL_ID_HEARTBEAT:
976   {
977     tvbuff_t* decrypted;
978
979     if (ssl && decrypt_dtls_record(tvb, pinfo, offset,
980                                    record_length, content_type, ssl, FALSE))
981       ssl_add_record_info(proto_dtls, pinfo, dtls_decrypted_data.data,
982                           dtls_decrypted_data_avail, offset);
983
984     /* try to retrieve and use decrypted alert record, if any. */
985     decrypted = ssl_get_record_info(tvb, proto_dtls, pinfo, offset);
986     if (decrypted) {
987       dissect_dtls_heartbeat(decrypted, pinfo, dtls_record_tree, 0,
988                              conv_version, record_length);
989       add_new_data_source(pinfo, decrypted, "Decrypted SSL record");
990     } else {
991       dissect_dtls_heartbeat(tvb, pinfo, dtls_record_tree, offset,
992                              conv_version, record_length);
993     }
994     break;
995   }
996
997   default:
998     /* shouldn't get here since we check above for valid types */
999     col_append_str(pinfo->cinfo, COL_INFO, "Bad DTLS Content Type");
1000     break;
1001   }
1002   offset += record_length; /* skip to end of record */
1003
1004   return offset;
1005 }
1006
1007 /* dissects the change cipher spec protocol, filling in the tree */
1008 static void
1009 dissect_dtls_change_cipher_spec(tvbuff_t *tvb,
1010                                 proto_tree *tree, guint32 offset,
1011                                 guint* conv_version, guint8 content_type)
1012 {
1013   /*
1014    * struct {
1015    *     enum { change_cipher_spec(1), (255) } type;
1016    * } ChangeCipherSpec;
1017    *
1018    */
1019   if (tree)
1020     {
1021       proto_item_set_text(tree,
1022                           "%s Record Layer: %s Protocol: Change Cipher Spec",
1023                           val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
1024                           val_to_str_const(content_type, ssl_31_content_type, "unknown"));
1025       proto_tree_add_item(tree, hf_dtls_change_cipher_spec, tvb,
1026                           offset, 1, ENC_NA);
1027     }
1028 }
1029
1030 /* dissects the alert message, filling in the tree */
1031 static void
1032 dissect_dtls_alert(tvbuff_t *tvb, packet_info *pinfo,
1033                    proto_tree *tree, guint32 offset,
1034                    guint* conv_version)
1035 {
1036   /*     struct {
1037    *         AlertLevel level;
1038    *         AlertDescription description;
1039    *     } Alert;
1040    */
1041
1042   proto_tree  *ti;
1043   proto_tree  *ssl_alert_tree;
1044   const gchar *level;
1045   const gchar *desc;
1046   guint8       byte;
1047
1048   ssl_alert_tree = NULL;
1049
1050   if (tree)
1051     {
1052       ti = proto_tree_add_item(tree, hf_dtls_alert_message, tvb,
1053                                offset, 2, ENC_NA);
1054       ssl_alert_tree = proto_item_add_subtree(ti, ett_dtls_alert);
1055     }
1056
1057   /*
1058    * set the record layer label
1059    */
1060
1061   /* first lookup the names for the alert level and description */
1062   byte  = tvb_get_guint8(tvb, offset); /* grab the level byte */
1063   level = try_val_to_str(byte, ssl_31_alert_level);
1064
1065   byte  = tvb_get_guint8(tvb, offset+1); /* grab the desc byte */
1066   desc  = try_val_to_str(byte, ssl_31_alert_description);
1067
1068   /* now set the text in the record layer line */
1069   if (level && desc)
1070     {
1071       if (check_col(pinfo->cinfo, COL_INFO))
1072         col_append_fstr(pinfo->cinfo, COL_INFO,
1073                         "Alert (Level: %s, Description: %s)",
1074                         level, desc);
1075     }
1076   else
1077     {
1078       col_append_str(pinfo->cinfo, COL_INFO, "Encrypted Alert");
1079     }
1080
1081   if (tree)
1082     {
1083       if (level && desc)
1084         {
1085           proto_item_set_text(tree, "%s Record Layer: Alert "
1086                               "(Level: %s, Description: %s)",
1087                               val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
1088                               level, desc);
1089           proto_tree_add_item(ssl_alert_tree, hf_dtls_alert_message_level,
1090                               tvb, offset++, 1, ENC_BIG_ENDIAN);
1091
1092           proto_tree_add_item(ssl_alert_tree, hf_dtls_alert_message_description,
1093                               tvb, offset, 1, ENC_BIG_ENDIAN);
1094         }
1095       else
1096         {
1097           proto_item_set_text(tree,
1098                               "%s Record Layer: Encrypted Alert",
1099                               val_to_str_const(*conv_version, ssl_version_short_names, "SSL"));
1100           proto_item_set_text(ssl_alert_tree,
1101                               "Alert Message: Encrypted Alert");
1102         }
1103     }
1104 }
1105
1106
1107 /* dissects the handshake protocol, filling the tree */
1108 static void
1109 dissect_dtls_handshake(tvbuff_t *tvb, packet_info *pinfo,
1110                        proto_tree *tree, guint32 offset,
1111                        guint32 record_length, guint *conv_version,
1112                        SslDecryptSession* ssl, guint8 content_type)
1113 {
1114   /*     struct {
1115    *         HandshakeType msg_type;
1116    *         uint24 length;
1117    *         uint16 message_seq;          //new field
1118    *         uint24 fragment_offset;      //new field
1119    *         uint24 fragment_length;      //new field
1120    *         select (HandshakeType) {
1121    *             case hello_request:       HelloRequest;
1122    *             case client_hello:        ClientHello;
1123    *             case server_hello:        ServerHello;
1124    *             case hello_verify_request: HelloVerifyRequest;     //new field
1125    *             case certificate:         Certificate;
1126    *             case server_key_exchange: ServerKeyExchange;
1127    *             case certificate_request: CertificateRequest;
1128    *             case server_hello_done:   ServerHelloDone;
1129    *             case certificate_verify:  CertificateVerify;
1130    *             case client_key_exchange: ClientKeyExchange;
1131    *             case finished:            Finished;
1132    *         } body;
1133    *     } Handshake;
1134    */
1135
1136   proto_tree  *ti, *length_item = NULL, *fragment_length_item = NULL;
1137   proto_tree  *ssl_hand_tree;
1138   const gchar *msg_type_str;
1139   guint8       msg_type;
1140   guint32      length;
1141   guint16      message_seq;
1142   guint32      fragment_offset;
1143   guint32      fragment_length;
1144   gboolean     first_iteration;
1145   gboolean     frag_hand;
1146   guint32      reassembled_length;
1147
1148   ti              = NULL;
1149   ssl_hand_tree   = NULL;
1150   msg_type_str    = NULL;
1151   first_iteration = TRUE;
1152
1153   /* just as there can be multiple records per packet, there
1154    * can be multiple messages per record as long as they have
1155    * the same content type
1156    *
1157    * we really only care about this for handshake messages
1158    */
1159
1160   /* set record_length to the max offset */
1161   record_length += offset;
1162   for (; offset < record_length; offset += fragment_length,
1163          first_iteration = FALSE) /* set up for next pass, if any */
1164     {
1165       fragment_data *frag_msg = NULL;
1166       tvbuff_t      *new_tvb  = NULL;
1167       const gchar   *frag_str = NULL;
1168       gboolean       fragmented;
1169
1170       if (tree)
1171         {
1172           /* add a subtree for the handshake protocol */
1173           ti = proto_tree_add_item(tree, hf_dtls_handshake_protocol, tvb,
1174                                    offset, -1, ENC_NA);
1175           ssl_hand_tree = proto_item_add_subtree(ti, ett_dtls_handshake);
1176         }
1177
1178       msg_type = tvb_get_guint8(tvb, offset);
1179       msg_type_str = try_val_to_str(msg_type, ssl_31_handshake_type);
1180
1181       if (!msg_type_str && !first_iteration)
1182         {
1183           /* only dissect / report messages if they're
1184            * either the first message in this record
1185            * or they're a valid message type
1186            */
1187           return;
1188         }
1189
1190       /* on second and later iterations, add comma to info col */
1191       if (!first_iteration)
1192         {
1193           col_append_str(pinfo->cinfo, COL_INFO, ", ");
1194         }
1195
1196       /*
1197        * Update our info string
1198        */
1199       if (check_col(pinfo->cinfo, COL_INFO))
1200         col_append_str(pinfo->cinfo, COL_INFO, (msg_type_str != NULL)
1201                         ? msg_type_str : "Encrypted Handshake Message");
1202
1203       if (ssl_hand_tree)
1204         proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_type,
1205                             tvb, offset, 1, msg_type);
1206       offset++;
1207
1208       length = tvb_get_ntoh24(tvb, offset);
1209       if (ssl_hand_tree)
1210         length_item = proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_length,
1211                                           tvb, offset, 3, length);
1212       offset += 3;
1213
1214       message_seq = tvb_get_ntohs(tvb,offset);
1215       if (ssl_hand_tree)
1216         proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_message_seq,
1217                             tvb, offset, 2, message_seq);
1218       offset += 2;
1219
1220       fragment_offset = tvb_get_ntoh24(tvb, offset);
1221       if (ssl_hand_tree)
1222         proto_tree_add_uint(ssl_hand_tree, hf_dtls_handshake_fragment_offset,
1223                             tvb, offset, 3, fragment_offset);
1224       offset += 3;
1225
1226       fragment_length = tvb_get_ntoh24(tvb, offset);
1227       if (ssl_hand_tree)
1228         fragment_length_item = proto_tree_add_uint(ssl_hand_tree,
1229                                                    hf_dtls_handshake_fragment_length,
1230                                                    tvb, offset, 3,
1231                                                    fragment_length);
1232       offset += 3;
1233       proto_item_set_len(ti, fragment_length + 12);
1234
1235       fragmented = FALSE;
1236       if (fragment_length + fragment_offset > length)
1237         {
1238           if (fragment_offset == 0)
1239             {
1240               expert_add_info_format(pinfo, fragment_length_item, PI_PROTOCOL,
1241                                      PI_ERROR,
1242                                      "Fragment length is larger than message length");
1243             }
1244           else
1245             {
1246               fragmented = TRUE;
1247               expert_add_info_format(pinfo, fragment_length_item, PI_PROTOCOL,
1248                                      PI_ERROR,
1249                                      "Fragment runs past the end of the message");
1250             }
1251         }
1252       else if (fragment_length < length)
1253         {
1254           fragmented = TRUE;
1255
1256           /* Handle fragments of known message type */
1257           switch (msg_type) {
1258           case SSL_HND_HELLO_REQUEST:
1259           case SSL_HND_CLIENT_HELLO:
1260           case SSL_HND_HELLO_VERIFY_REQUEST:
1261           case SSL_HND_NEWSESSION_TICKET:
1262           case SSL_HND_SERVER_HELLO:
1263           case SSL_HND_CERTIFICATE:
1264           case SSL_HND_SERVER_KEY_EXCHG:
1265           case SSL_HND_CERT_REQUEST:
1266           case SSL_HND_SVR_HELLO_DONE:
1267           case SSL_HND_CERT_VERIFY:
1268           case SSL_HND_CLIENT_KEY_EXCHG:
1269           case SSL_HND_FINISHED:
1270             frag_hand = TRUE;
1271             break;
1272           default:
1273             /* Ignore encrypted handshake messages */
1274             frag_hand = FALSE;
1275             break;
1276           }
1277
1278           if (frag_hand)
1279             {
1280               /* Fragmented handshake message */
1281               pinfo->fragmented = TRUE;
1282
1283               /* Don't pass the reassembly code data that doesn't exist */
1284               tvb_ensure_bytes_exist(tvb, offset, fragment_length);
1285
1286               frag_msg = fragment_add(&dtls_reassembly_table,
1287                                       tvb, offset, pinfo, message_seq, NULL,
1288                                       fragment_offset, fragment_length, TRUE);
1289               /*
1290                * Do we already have a length for this reassembly?
1291                */
1292               reassembled_length = fragment_get_tot_len(&dtls_reassembly_table,
1293                                                         pinfo, message_seq, NULL);
1294               if (reassembled_length == 0)
1295                 {
1296                   /* No - set it to the length specified by this packet. */
1297                   fragment_set_tot_len(&dtls_reassembly_table,
1298                                        pinfo, message_seq, NULL, length);
1299                 }
1300               else
1301                 {
1302                   /* Yes - if this packet specifies a different length,
1303                      report an error. */
1304                   if (reassembled_length != length)
1305                     {
1306                       expert_add_info_format(pinfo, length_item, PI_PROTOCOL,
1307                                              PI_ERROR,
1308                                              "Message length differs from value in earlier fragment");
1309                     }
1310                 }
1311
1312               if (frag_msg && (fragment_length + fragment_offset) == reassembled_length)
1313                 {
1314                   /* Reassembled */
1315                   new_tvb = process_reassembled_data(tvb, offset, pinfo,
1316                                                      "Reassembled DTLS",
1317                                                      frag_msg,
1318                                                      &dtls_frag_items,
1319                                                      NULL, tree);
1320                   frag_str = " (Reassembled)";
1321                 }
1322               else
1323                 {
1324                   frag_str = " (Fragment)";
1325                 }
1326
1327               if (check_col(pinfo->cinfo, COL_INFO))
1328                 col_append_str(pinfo->cinfo, COL_INFO, frag_str);
1329             }
1330         }
1331
1332       if (tree)
1333         {
1334           /* set the label text on the record layer expanding node */
1335           if (first_iteration)
1336             {
1337               proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s%s",
1338                                   val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
1339                                   val_to_str_const(content_type, ssl_31_content_type, "unknown"),
1340                                   (msg_type_str!=NULL) ? msg_type_str :
1341                                   "Encrypted Handshake Message",
1342                                   (frag_str!=NULL) ? frag_str : "");
1343             }
1344           else
1345             {
1346               proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s%s",
1347                                   val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
1348                                   val_to_str_const(content_type, ssl_31_content_type, "unknown"),
1349                                   "Multiple Handshake Messages",
1350                                   (frag_str!=NULL) ? frag_str : "");
1351             }
1352
1353           if (ssl_hand_tree)
1354             {
1355               /* set the text label on the subtree node */
1356               proto_item_set_text(ssl_hand_tree, "Handshake Protocol: %s%s",
1357                                   (msg_type_str != NULL) ? msg_type_str :
1358                                   "Encrypted Handshake Message",
1359                                   (frag_str!=NULL) ? frag_str : "");
1360             }
1361         }
1362
1363       /* if we don't have a valid handshake type, just quit dissecting */
1364       if (!msg_type_str)
1365         return;
1366
1367       if (ssl_hand_tree || ssl)
1368         {
1369           tvbuff_t *sub_tvb = NULL;
1370
1371           if (fragmented && !new_tvb)
1372             {
1373               /* Skip fragmented messages not reassembled yet */
1374               continue;
1375             }
1376
1377           if (new_tvb)
1378             {
1379               sub_tvb = new_tvb;
1380             }
1381           else
1382             {
1383               sub_tvb = tvb_new_subset(tvb, offset, fragment_length,
1384                                        fragment_length);
1385             }
1386
1387           /* now dissect the handshake message, if necessary */
1388           switch (msg_type) {
1389           case SSL_HND_HELLO_REQUEST:
1390             /* hello_request has no fields, so nothing to do! */
1391             break;
1392
1393           case SSL_HND_CLIENT_HELLO:
1394             dissect_dtls_hnd_cli_hello(sub_tvb, ssl_hand_tree, 0, length, ssl);
1395             break;
1396
1397           case SSL_HND_SERVER_HELLO:
1398             dissect_dtls_hnd_srv_hello(sub_tvb, ssl_hand_tree, 0, length, ssl);
1399             break;
1400
1401           case SSL_HND_HELLO_VERIFY_REQUEST:
1402             dissect_dtls_hnd_hello_verify_request(sub_tvb, ssl_hand_tree, 0,  ssl);
1403             break;
1404
1405           case SSL_HND_NEWSESSION_TICKET:
1406             dissect_dtls_hnd_new_ses_ticket(sub_tvb, ssl_hand_tree, 0, length);
1407             break;
1408
1409           case SSL_HND_CERTIFICATE:
1410             dissect_dtls_hnd_cert(sub_tvb, ssl_hand_tree, 0, pinfo);
1411             break;
1412
1413           case SSL_HND_SERVER_KEY_EXCHG:
1414             /* unimplemented */
1415             break;
1416
1417           case SSL_HND_CERT_REQUEST:
1418             dissect_dtls_hnd_cert_req(sub_tvb, ssl_hand_tree, 0);
1419             break;
1420
1421           case SSL_HND_SVR_HELLO_DONE:
1422             /* server_hello_done has no fields, so nothing to do! */
1423             break;
1424
1425           case SSL_HND_CERT_VERIFY:
1426             /* unimplemented */
1427             break;
1428
1429           case SSL_HND_CLIENT_KEY_EXCHG:
1430             {
1431               /* here we can have all the data to build session key */
1432               StringInfo encrypted_pre_master;
1433               gint ret;
1434               guint encrlen = length, skip;
1435               skip = 0;
1436
1437               if (!ssl)
1438                 break;
1439
1440               /* check for required session data */
1441               ssl_debug_printf("dissect_dtls_handshake found SSL_HND_CLIENT_KEY_EXCHG, state %X\n",
1442                                ssl->state);
1443               if ((ssl->state & (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) !=
1444                   (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) {
1445                 ssl_debug_printf("dissect_dtls_handshake not enough data to generate key (required state %X)\n",
1446                                  (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION));
1447                 break;
1448               }
1449
1450               /* Skip leading two bytes length field. Older openssl's DTLS implementation seems not to have this field.
1451                * See implementation note in RFC 4346 section 7.4.7.1
1452                */
1453               if (ssl->cipher_suite.kex==KEX_RSA && ssl->version_netorder != DTLSV1DOT0_VERSION_NOT) {
1454                 encrlen = tvb_get_ntohs(tvb, offset);
1455                 skip = 2;
1456                 if (encrlen > length - 2) {
1457                   ssl_debug_printf("dissect_dtls_handshake wrong encrypted length (%d max %d)\n", encrlen, length);
1458                   break;
1459                 }
1460               }
1461
1462               encrypted_pre_master.data = (guchar *)se_alloc(encrlen);
1463               encrypted_pre_master.data_len = encrlen;
1464               tvb_memcpy(tvb, encrypted_pre_master.data, offset+skip, encrlen);
1465
1466               if (!ssl->private_key) {
1467                 ssl_debug_printf("dissect_dtls_handshake can't find private key\n");
1468                 break;
1469               }
1470
1471               /* go with ssl key processing; encrypted_pre_master
1472                * will be used for master secret store*/
1473               ret = ssl_decrypt_pre_master_secret(ssl, &encrypted_pre_master, ssl->private_key);
1474               if (ret < 0) {
1475                 ssl_debug_printf("dissect_dtls_handshake can't decrypt pre master secret\n");
1476                 break;
1477               }
1478               if (ssl_generate_keyring_material(ssl)<0) {
1479                 ssl_debug_printf("dissect_dtls_handshake can't generate keyring material\n");
1480                 break;
1481               }
1482               ssl->state |= SSL_HAVE_SESSION_KEY;
1483               ssl_save_session(ssl, dtls_session_hash);
1484               ssl_debug_printf("dissect_dtls_handshake session keys successfully generated\n");
1485             }
1486             break;
1487
1488           case SSL_HND_FINISHED:
1489             dissect_dtls_hnd_finished(sub_tvb, ssl_hand_tree,
1490                                       0, conv_version);
1491             break;
1492           }
1493
1494         }
1495     }
1496 }
1497
1498 /* dissects the heartbeat message, filling in the tree */
1499 static void
1500 dissect_dtls_heartbeat(tvbuff_t *tvb, packet_info *pinfo,
1501                        proto_tree *tree, guint32 offset,
1502                        guint* conv_version, guint32 record_length)
1503 {
1504   /*     struct {
1505    *         HeartbeatMessageType type;
1506    *         uint16 payload_length;
1507    *         opaque payload;
1508    *         opaque padding;
1509    *     } HeartbeatMessage;
1510    */
1511
1512   proto_tree  *ti;
1513   proto_tree  *dtls_heartbeat_tree;
1514   const gchar *type;
1515   guint8       byte;
1516   guint16      payload_length;
1517   guint16      padding_length;
1518
1519   dtls_heartbeat_tree = NULL;
1520
1521   if (tree) {
1522     ti = proto_tree_add_item(tree, hf_dtls_heartbeat_message, tvb,
1523                              offset, record_length - 32, ENC_NA);
1524     dtls_heartbeat_tree = proto_item_add_subtree(ti, ett_dtls_heartbeat);
1525   }
1526
1527   /*
1528    * set the record layer label
1529    */
1530
1531   /* first lookup the names for the message type and the payload length */
1532   byte = tvb_get_guint8(tvb, offset);
1533   type = try_val_to_str(byte, tls_heartbeat_type);
1534
1535   payload_length = tvb_get_ntohs(tvb, offset + 1);
1536   padding_length = record_length - 3 - payload_length;
1537
1538   /* now set the text in the record layer line */
1539   if (type && (payload_length <= record_length - 16 - 3)) {
1540     col_append_fstr(pinfo->cinfo, COL_INFO, "Heartbeat %s", type);
1541   } else {
1542     col_append_str(pinfo->cinfo, COL_INFO, "Encrypted Heartbeat");
1543   }
1544
1545   if (tree) {
1546     if (type && (payload_length <= record_length - 16 - 3)) {
1547       proto_item_set_text(tree, "%s Record Layer: Heartbeat "
1548                                 "%s",
1549                                 val_to_str_const(*conv_version, ssl_version_short_names, "SSL"),
1550                                 type);
1551       proto_tree_add_item(dtls_heartbeat_tree, hf_dtls_heartbeat_message_type,
1552                           tvb, offset, 1, ENC_BIG_ENDIAN);
1553       offset += 1;
1554       proto_tree_add_uint(dtls_heartbeat_tree, hf_dtls_heartbeat_message_payload_length,
1555                           tvb, offset, 2, payload_length);
1556       offset += 2;
1557       proto_tree_add_bytes_format(dtls_heartbeat_tree, hf_dtls_heartbeat_message_payload,
1558                                   tvb, offset, payload_length,
1559                                   NULL, "Payload (%u byte%s)",
1560                                   payload_length,
1561                                   plurality(payload_length, "", "s"));
1562       offset += payload_length;
1563       proto_tree_add_bytes_format(dtls_heartbeat_tree, hf_dtls_heartbeat_message_padding,
1564                                   tvb, offset, padding_length,
1565                                   NULL, "Padding and HMAC (%u byte%s)",
1566                                   padding_length,
1567                                   plurality(padding_length, "", "s"));
1568     } else {
1569       proto_item_set_text(tree,
1570                          "%s Record Layer: Encrypted Heartbeat",
1571                          val_to_str_const(*conv_version, ssl_version_short_names, "SSL"));
1572       proto_item_set_text(dtls_heartbeat_tree,
1573                           "Encrypted Heartbeat Message");
1574     }
1575   }
1576 }
1577
1578 static gint
1579 dissect_dtls_hnd_hello_common(tvbuff_t *tvb, proto_tree *tree,
1580                               guint32 offset, SslDecryptSession* ssl, gint from_server)
1581 {
1582   /* show the client's random challenge */
1583   nstime_t gmt_unix_time;
1584   guint8   session_id_length;
1585   proto_item *ti_rnd;
1586   proto_tree *dtls_rnd_tree = NULL;
1587
1588   if (tree || ssl)
1589   {
1590     if (ssl)
1591     {
1592       /* get proper peer information*/
1593       StringInfo* rnd;
1594       if (from_server)
1595         rnd = &ssl->server_random;
1596       else
1597         rnd = &ssl->client_random;
1598
1599       /* get provided random for keyring generation*/
1600       tvb_memcpy(tvb, rnd->data, offset, 32);
1601       rnd->data_len = 32;
1602       if (from_server)
1603         ssl->state |= SSL_SERVER_RANDOM;
1604       else
1605         ssl->state |= SSL_CLIENT_RANDOM;
1606       ssl_debug_printf("dissect_dtls_hnd_hello_common found random state %X\n",
1607                        ssl->state);
1608     }
1609
1610     if (tree)
1611     {
1612         ti_rnd = proto_tree_add_text(tree, tvb, offset, 32, "Random");
1613         dtls_rnd_tree = proto_item_add_subtree(ti_rnd, ett_dtls_random);
1614     }
1615
1616     /* show the time */
1617     if (dtls_rnd_tree)
1618     {
1619       gmt_unix_time.secs  = tvb_get_ntohl(tvb, offset);
1620       gmt_unix_time.nsecs = 0;
1621       proto_tree_add_time(dtls_rnd_tree, hf_dtls_handshake_random_time,
1622                           tvb, offset, 4, &gmt_unix_time);
1623     }
1624     offset += 4;
1625
1626     /* show the random bytes */
1627     if (dtls_rnd_tree)
1628       proto_tree_add_item(dtls_rnd_tree, hf_dtls_handshake_random_bytes,
1629                           tvb, offset, 28, ENC_NA);
1630     offset += 28;
1631
1632     /* show the session id */
1633     session_id_length = tvb_get_guint8(tvb, offset);
1634     if (tree)
1635       proto_tree_add_item(tree, hf_dtls_handshake_session_id_len,
1636                           tvb, offset, 1, ENC_BIG_ENDIAN);
1637     offset++;
1638     if (ssl)
1639     {
1640       /* check stored session id info */
1641       if (from_server && (session_id_length == ssl->session_id.data_len) &&
1642           (tvb_memeql(tvb, offset, ssl->session_id.data, session_id_length) == 0))
1643       {
1644         /* client/server id match: try to restore a previous cached session*/
1645         ssl_restore_session(ssl, dtls_session_hash);
1646       }
1647       else {
1648         tvb_memcpy(tvb,ssl->session_id.data, offset, session_id_length);
1649         ssl->session_id.data_len = session_id_length;
1650       }
1651     }
1652     if (tree && session_id_length > 0)
1653       proto_tree_add_bytes_format(tree, hf_dtls_handshake_session_id,
1654                                   tvb, offset, session_id_length,
1655                                   NULL, "Session ID (%u byte%s)",
1656                                   session_id_length,
1657                                   plurality(session_id_length, "", "s"));
1658     offset += session_id_length;
1659   }
1660
1661   /* XXXX */
1662   return offset;
1663 }
1664
1665 static gint
1666 dissect_dtls_hnd_hello_ext(tvbuff_t *tvb,
1667                            proto_tree *tree, guint32 offset, guint32 left)
1668 {
1669   guint16     extension_length;
1670   guint16     ext_type;
1671   guint16     ext_len;
1672   proto_item *pi;
1673   proto_tree *ext_tree;
1674
1675   if (left < 2)
1676     return offset;
1677
1678   extension_length = tvb_get_ntohs(tvb, offset);
1679   proto_tree_add_uint(tree, hf_dtls_handshake_extensions_len,
1680                       tvb, offset, 2, extension_length);
1681   offset += 2;
1682   left   -= 2;
1683
1684   while (left >= 4)
1685     {
1686       ext_type = tvb_get_ntohs(tvb, offset);
1687       ext_len  = tvb_get_ntohs(tvb, offset + 2);
1688
1689       pi = proto_tree_add_text(tree, tvb, offset, 4 + ext_len,
1690                                "Extension: %s",
1691                                val_to_str(ext_type,
1692                                           tls_hello_extension_types,
1693                                           "Unknown %u"));
1694       ext_tree = proto_item_add_subtree(pi, ett_dtls_extension);
1695       if (!ext_tree)
1696         ext_tree = tree;
1697
1698       proto_tree_add_uint(ext_tree, hf_dtls_handshake_extension_type,
1699                           tvb, offset, 2, ext_type);
1700       offset += 2;
1701
1702       proto_tree_add_uint(ext_tree, hf_dtls_handshake_extension_len,
1703                           tvb, offset, 2, ext_len);
1704       offset += 2;
1705
1706       switch (ext_type) {
1707       case SSL_HND_HELLO_EXT_HEARTBEAT:
1708           proto_tree_add_item(ext_tree, hf_dtls_heartbeat_extension_mode,
1709                               tvb, offset, 1, ENC_BIG_ENDIAN);
1710           offset += ext_len;
1711           break;
1712       default:
1713           proto_tree_add_bytes_format(ext_tree, hf_dtls_handshake_extension_data,
1714                                       tvb, offset, ext_len, NULL,
1715                                       "Data (%u byte%s)",
1716                                       ext_len, plurality(ext_len, "", "s"));
1717           offset += ext_len;
1718           break;
1719       }
1720
1721       left   -= 2 + 2 + ext_len;
1722     }
1723
1724   return offset;
1725 }
1726
1727 static void
1728 dissect_dtls_hnd_cli_hello(tvbuff_t *tvb,
1729                            proto_tree *tree, guint32 offset, guint32 length,
1730                            SslDecryptSession*ssl)
1731 {
1732   /* struct {
1733    *     ProtocolVersion client_version;
1734    *     Random random;
1735    *     SessionID session_id;
1736    *     opaque cookie<0..32>;                   //new field
1737    *     CipherSuite cipher_suites<2..2^16-1>;
1738    *     CompressionMethod compression_methods<1..2^8-1>;
1739    *     Extension client_hello_extension_list<0..2^16-1>;
1740    * } ClientHello;
1741    *
1742    */
1743
1744   proto_tree *ti;
1745   proto_tree *cs_tree;
1746   guint16     cipher_suite_length;
1747   guint8      compression_methods_length;
1748   guint8      compression_method;
1749   guint16     start_offset   = offset;
1750   guint8      cookie_length;
1751
1752   if (tree || ssl)
1753     {
1754       /* show the client version */
1755       if (tree)
1756         proto_tree_add_item(tree, hf_dtls_handshake_client_version, tvb,
1757                             offset, 2, ENC_BIG_ENDIAN);
1758       offset += 2;
1759
1760       /* show the fields in common with server hello */
1761       offset = dissect_dtls_hnd_hello_common(tvb, tree, offset, ssl, 0);
1762
1763       /* look for a cookie */
1764       cookie_length = tvb_get_guint8(tvb, offset);
1765       if (!tree)
1766         return;
1767
1768       proto_tree_add_uint(tree, hf_dtls_handshake_cookie_len,
1769                           tvb, offset, 1, cookie_length);
1770       offset ++;            /* skip opaque length */
1771
1772       if (cookie_length > 0)
1773         {
1774           proto_tree_add_item(tree, hf_dtls_handshake_cookie, tvb, offset,
1775                               cookie_length, ENC_NA);
1776           offset += cookie_length;
1777         }
1778
1779       /* tell the user how many cipher suites there are */
1780       cipher_suite_length = tvb_get_ntohs(tvb, offset);
1781
1782       proto_tree_add_uint(tree, hf_dtls_handshake_cipher_suites_len,
1783                           tvb, offset, 2, cipher_suite_length);
1784       offset += 2;            /* skip opaque length */
1785
1786       if (cipher_suite_length > 0)
1787         {
1788           tvb_ensure_bytes_exist(tvb, offset, cipher_suite_length);
1789           ti = proto_tree_add_none_format(tree,
1790                                           hf_dtls_handshake_cipher_suites,
1791                                           tvb, offset, cipher_suite_length,
1792                                           "Cipher Suites (%u suite%s)",
1793                                           cipher_suite_length / 2,
1794                                           plurality(cipher_suite_length/2, "", "s"));
1795
1796           /* make this a subtree */
1797           cs_tree = proto_item_add_subtree(ti, ett_dtls_cipher_suites);
1798           if (!cs_tree)
1799             {
1800               cs_tree = tree; /* failsafe */
1801             }
1802
1803           while (cipher_suite_length > 0)
1804             {
1805               proto_tree_add_item(cs_tree, hf_dtls_handshake_cipher_suite,
1806                                   tvb, offset, 2, ENC_BIG_ENDIAN);
1807               offset += 2;
1808               cipher_suite_length -= 2;
1809             }
1810         }
1811
1812       /* tell the user how man compression methods there are */
1813       compression_methods_length = tvb_get_guint8(tvb, offset);
1814       proto_tree_add_uint(tree, hf_dtls_handshake_comp_methods_len,
1815                           tvb, offset, 1, compression_methods_length);
1816       offset++;
1817
1818       if (compression_methods_length > 0)
1819         {
1820           tvb_ensure_bytes_exist(tvb, offset, compression_methods_length);
1821           ti = proto_tree_add_none_format(tree,
1822                                           hf_dtls_handshake_comp_methods,
1823                                           tvb, offset, compression_methods_length,
1824                                           "Compression Methods (%u method%s)",
1825                                           compression_methods_length,
1826                                           plurality(compression_methods_length,
1827                                                     "", "s"));
1828
1829           /* make this a subtree */
1830           cs_tree = proto_item_add_subtree(ti, ett_dtls_comp_methods);
1831           if (!cs_tree)
1832             {
1833               cs_tree = tree; /* failsafe */
1834             }
1835
1836           while (compression_methods_length > 0)
1837             {
1838               compression_method = tvb_get_guint8(tvb, offset);
1839               if (compression_method < 64)
1840                 proto_tree_add_uint(cs_tree, hf_dtls_handshake_comp_method,
1841                                     tvb, offset, 1, compression_method);
1842               else if (compression_method > 63 && compression_method < 193)
1843                 proto_tree_add_text(cs_tree, tvb, offset, 1,
1844                                     "Compression Method: Reserved - to be assigned by IANA (%u)",
1845                                     compression_method);
1846               else
1847                 proto_tree_add_text(cs_tree, tvb, offset, 1,
1848                                     "Compression Method: Private use range (%u)",
1849                                     compression_method);
1850               offset++;
1851               compression_methods_length--;
1852             }
1853         }
1854
1855       if (length > offset - start_offset)
1856         {
1857           dissect_dtls_hnd_hello_ext(tvb, tree, offset,
1858                                               length -
1859                                               (offset - start_offset));
1860         }
1861     }
1862 }
1863
1864 static int
1865 dissect_dtls_hnd_srv_hello(tvbuff_t *tvb,
1866                            proto_tree *tree, guint32 offset, guint32 length, SslDecryptSession* ssl)
1867 {
1868   /* struct {
1869    *     ProtocolVersion server_version;
1870    *     Random random;
1871    *     SessionID session_id;
1872    *     CipherSuite cipher_suite;
1873    *     CompressionMethod compression_method;
1874    *     Extension server_hello_extension_list<0..2^16-1>;
1875    * } ServerHello;
1876    */
1877
1878   guint16 start_offset;
1879
1880   start_offset = offset;
1881
1882   if (tree || ssl)
1883     {
1884       /* show the server version */
1885       if (tree)
1886         proto_tree_add_item(tree, hf_dtls_handshake_server_version, tvb,
1887                             offset, 2, ENC_BIG_ENDIAN);
1888       offset += 2;
1889
1890       /* first display the elements conveniently in
1891        * common with client hello
1892        */
1893       offset = dissect_dtls_hnd_hello_common(tvb, tree, offset, ssl, 1);
1894
1895       /* PAOLO: handle session cipher suite  */
1896       if (ssl) {
1897         /* store selected cipher suite for decryption */
1898         ssl->cipher = tvb_get_ntohs(tvb, offset);
1899         if (ssl_find_cipher(ssl->cipher,&ssl->cipher_suite) < 0) {
1900           ssl_debug_printf("dissect_dtls_hnd_srv_hello can't find cipher suite %X\n", ssl->cipher);
1901           goto no_cipher;
1902         }
1903
1904         ssl->state |= SSL_CIPHER;
1905         ssl_debug_printf("dissect_dtls_hnd_srv_hello found cipher %X, state %X\n",
1906                          ssl->cipher, ssl->state);
1907
1908         /* if we have restored a session now we can have enough material
1909          * to build session key, check it out*/
1910         if ((ssl->state &
1911              (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) !=
1912             (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) {
1913           ssl_debug_printf("dissect_dtls_hnd_srv_hello not enough data to generate key (required state %X)\n",
1914                            (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET));
1915           goto no_cipher;
1916         }
1917
1918         ssl_debug_printf("dissect_dtls_hnd_srv_hello trying to generate keys\n");
1919         if (ssl_generate_keyring_material(ssl)<0) {
1920           ssl_debug_printf("dissect_dtls_hnd_srv_hello can't generate keyring material\n");
1921           goto no_cipher;
1922         }
1923         ssl->state |= SSL_HAVE_SESSION_KEY;
1924       }
1925     no_cipher:
1926       if (ssl) {
1927         /* store selected compression method for decompression */
1928         ssl->compression = tvb_get_guint8(tvb, offset+2);
1929       }
1930       if (!tree)
1931         return offset;
1932
1933       /* now the server-selected cipher suite */
1934       proto_tree_add_item(tree, hf_dtls_handshake_cipher_suite,
1935                           tvb, offset, 2, ENC_BIG_ENDIAN);
1936       offset += 2;
1937
1938       /* and the server-selected compression method */
1939       proto_tree_add_item(tree, hf_dtls_handshake_comp_method,
1940                           tvb, offset, 1, ENC_BIG_ENDIAN);
1941       offset++;
1942
1943       if (length > offset - start_offset)
1944         {
1945           offset = dissect_dtls_hnd_hello_ext(tvb, tree, offset,
1946                                               length -
1947                                               (offset - start_offset));
1948         }
1949     }
1950     return offset;
1951 }
1952
1953 static int
1954 dissect_dtls_hnd_hello_verify_request(tvbuff_t *tvb, proto_tree *tree,
1955                                       guint32 offset, SslDecryptSession* ssl)
1956 {
1957   /*
1958    * struct {
1959    *    ProtocolVersion server_version;
1960    *    opaque cookie<0..32>;
1961    * } HelloVerifyRequest;
1962    */
1963
1964   guint8 cookie_length;
1965
1966
1967   if (tree || ssl)
1968     {
1969       /* show the client version */
1970       if (tree)
1971         proto_tree_add_item(tree, hf_dtls_handshake_server_version, tvb,
1972                             offset, 2, ENC_BIG_ENDIAN);
1973       offset += 2;
1974
1975
1976       /* look for a cookie */
1977       cookie_length = tvb_get_guint8(tvb, offset);
1978       if (!tree)
1979         return offset;
1980
1981       proto_tree_add_uint(tree, hf_dtls_handshake_cookie_len,
1982                           tvb, offset, 1, cookie_length);
1983       offset ++;            /* skip opaque length */
1984
1985       if (cookie_length > 0)
1986         {
1987           proto_tree_add_bytes_format(tree, hf_dtls_handshake_cookie,
1988                                       tvb, offset, cookie_length,
1989                                       NULL, "Cookie (%u byte%s)",
1990                                       cookie_length,
1991                                       plurality(cookie_length, "", "s"));
1992           offset += cookie_length;
1993         }
1994     }
1995     return offset;
1996 }
1997
1998 static void
1999 dissect_dtls_hnd_new_ses_ticket(tvbuff_t *tvb,
2000                            proto_tree *tree, guint32 offset, guint32 length)
2001 {
2002     guint nst_len;
2003     proto_item *ti;
2004     proto_tree *subtree;
2005
2006
2007     nst_len = tvb_get_ntohs(tvb, offset+4);
2008     if (6 + nst_len != length) {
2009         return;
2010     }
2011
2012     ti = proto_tree_add_text(tree, tvb, offset, 6+nst_len, "TLS Session Ticket");
2013     subtree = proto_item_add_subtree(ti, ett_dtls_new_ses_ticket);
2014
2015     proto_tree_add_item(subtree, hf_dtls_handshake_session_ticket_lifetime_hint,
2016                         tvb, offset, 4, ENC_BIG_ENDIAN);
2017     offset += 4;
2018
2019     proto_tree_add_uint(subtree, hf_dtls_handshake_session_ticket_len,
2020         tvb, offset, 2, nst_len);
2021     /* Content depends on implementation, so just show data! */
2022     proto_tree_add_item(subtree, hf_dtls_handshake_session_ticket,
2023             tvb, offset + 2, nst_len, ENC_NA);
2024 }
2025
2026 static void
2027 dissect_dtls_hnd_cert(tvbuff_t *tvb,
2028                       proto_tree *tree, guint32 offset, packet_info *pinfo)
2029 {
2030
2031   /* opaque ASN.1Cert<2^24-1>;
2032    *
2033    * struct {
2034    *     ASN.1Cert certificate_list<1..2^24-1>;
2035    * } Certificate;
2036    */
2037
2038   guint32     certificate_list_length;
2039   proto_tree *ti;
2040   proto_tree *subtree;
2041   asn1_ctx_t  asn1_ctx;
2042
2043   asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
2044
2045   if (tree)
2046     {
2047       certificate_list_length = tvb_get_ntoh24(tvb, offset);
2048       proto_tree_add_uint(tree, hf_dtls_handshake_certificates_len,
2049                           tvb, offset, 3, certificate_list_length);
2050       offset += 3;            /* 24-bit length value */
2051
2052       if (certificate_list_length > 0)
2053         {
2054           tvb_ensure_bytes_exist(tvb, offset, certificate_list_length);
2055           ti = proto_tree_add_none_format(tree,
2056                                           hf_dtls_handshake_certificates,
2057                                           tvb, offset, certificate_list_length,
2058                                           "Certificates (%u byte%s)",
2059                                           certificate_list_length,
2060                                           plurality(certificate_list_length,
2061                                                     "", "s"));
2062
2063           /* make it a subtree */
2064           subtree = proto_item_add_subtree(ti, ett_dtls_certs);
2065           if (!subtree)
2066             {
2067               subtree = tree; /* failsafe */
2068             }
2069
2070           /* iterate through each certificate */
2071           while (certificate_list_length > 0)
2072             {
2073               /* get the length of the current certificate */
2074               guint32 cert_length = tvb_get_ntoh24(tvb, offset);
2075               certificate_list_length -= 3 + cert_length;
2076
2077               proto_tree_add_item(subtree, hf_dtls_handshake_certificate_len,
2078                                   tvb, offset, 3, ENC_BIG_ENDIAN);
2079               offset += 3;
2080
2081               dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, subtree, hf_dtls_handshake_certificate);
2082               offset += cert_length;
2083             }
2084         }
2085
2086     }
2087 }
2088
2089 static void
2090 dissect_dtls_hnd_cert_req(tvbuff_t *tvb,
2091                           proto_tree *tree, guint32 offset)
2092 {
2093   /*
2094    *    enum {
2095    *        rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
2096    *        (255)
2097    *    } ClientCertificateType;
2098    *
2099    *    opaque DistinguishedName<1..2^16-1>;
2100    *
2101    *    struct {
2102    *        ClientCertificateType certificate_types<1..2^8-1>;
2103    *        DistinguishedName certificate_authorities<3..2^16-1>;
2104    *    } CertificateRequest;
2105    *
2106    */
2107
2108   proto_tree *ti;
2109   proto_tree *subtree;
2110   guint8      cert_types_count;
2111   gint        dnames_length;
2112
2113   if (tree)
2114     {
2115       cert_types_count = tvb_get_guint8(tvb, offset);
2116       proto_tree_add_uint(tree, hf_dtls_handshake_cert_types_count,
2117                           tvb, offset, 1, cert_types_count);
2118       offset++;
2119
2120       if (cert_types_count > 0)
2121         {
2122           ti = proto_tree_add_none_format(tree,
2123                                           hf_dtls_handshake_cert_types,
2124                                           tvb, offset, cert_types_count,
2125                                           "Certificate types (%u type%s)",
2126                                           cert_types_count,
2127                                           plurality(cert_types_count, "", "s"));
2128           subtree = proto_item_add_subtree(ti, ett_dtls_cert_types);
2129           if (!subtree)
2130             {
2131               subtree = tree;
2132             }
2133
2134           while (cert_types_count > 0)
2135             {
2136               proto_tree_add_item(subtree, hf_dtls_handshake_cert_type,
2137                                   tvb, offset, 1, ENC_BIG_ENDIAN);
2138               offset++;
2139               cert_types_count--;
2140             }
2141         }
2142
2143       dnames_length = tvb_get_ntohs(tvb, offset);
2144       proto_tree_add_uint(tree, hf_dtls_handshake_dnames_len,
2145                           tvb, offset, 2, dnames_length);
2146       offset += 2;
2147
2148       if (dnames_length > 0)
2149         {
2150           tvb_ensure_bytes_exist(tvb, offset, dnames_length);
2151           ti = proto_tree_add_none_format(tree,
2152                                           hf_dtls_handshake_dnames,
2153                                           tvb, offset, dnames_length,
2154                                           "Distinguished Names (%d byte%s)",
2155                                           dnames_length,
2156                                           plurality(dnames_length, "", "s"));
2157           subtree = proto_item_add_subtree(ti, ett_dtls_dnames);
2158           if (!subtree)
2159             {
2160               subtree = tree;
2161             }
2162
2163           while (dnames_length > 0)
2164             {
2165               /* get the length of the current certificate */
2166               guint16 name_length = tvb_get_ntohs(tvb, offset);
2167               dnames_length -= 2 + name_length;
2168
2169               proto_tree_add_item(subtree, hf_dtls_handshake_dname_len,
2170                                   tvb, offset, 2, ENC_BIG_ENDIAN);
2171               offset += 2;
2172
2173               proto_tree_add_bytes_format(subtree,
2174                                           hf_dtls_handshake_dname,
2175                                           tvb, offset, name_length, NULL,
2176                                           "Distinguished Name (%u byte%s)",
2177                                           name_length,
2178                                           plurality(name_length, "", "s"));
2179               offset += name_length;
2180             }
2181         }
2182     }
2183
2184 }
2185
2186 static void
2187 dissect_dtls_hnd_finished(tvbuff_t *tvb, proto_tree *tree, guint32 offset,
2188                           guint* conv_version)
2189 {
2190   /*
2191    *     struct {
2192    *         opaque verify_data[12];
2193    *     } Finished;
2194    */
2195
2196   /* this all needs a tree, so bail if we don't have one */
2197   if (!tree)
2198     {
2199       return;
2200     }
2201
2202   switch(*conv_version) {
2203   case SSL_VER_DTLS:
2204     proto_tree_add_item(tree, hf_dtls_handshake_finished,
2205                         tvb, offset, 12, ENC_NA);
2206     break;
2207   case SSL_VER_DTLS1DOT2:
2208     proto_tree_add_item(tree, hf_dtls_handshake_finished,
2209                         tvb, offset, 12, ENC_NA);
2210     break;
2211   }
2212 }
2213
2214 /*********************************************************************
2215  *
2216  * Support Functions
2217  *
2218  *********************************************************************/
2219 #if 0
2220 static void
2221 ssl_set_conv_version(packet_info *pinfo, guint version)
2222 {
2223   conversation_t *conversation;
2224
2225   if (pinfo->fd->flags.visited)
2226     {
2227       /* We've already processed this frame; no need to do any more
2228        * work on it.
2229        */
2230       return;
2231     }
2232
2233   conversation = find_or_create_conversation(pinfo);
2234
2235   if (conversation_get_proto_data(conversation, proto_dtls) != NULL)
2236     {
2237       /* get rid of the current data */
2238       conversation_delete_proto_data(conversation, proto_dtls);
2239     }
2240   conversation_add_proto_data(conversation, proto_dtls, GINT_TO_POINTER(version));
2241 }
2242 #endif
2243
2244 static gint
2245 dtls_is_valid_handshake_type(guint8 type)
2246 {
2247
2248   switch (type) {
2249   case SSL_HND_HELLO_REQUEST:
2250   case SSL_HND_CLIENT_HELLO:
2251   case SSL_HND_SERVER_HELLO:
2252   case SSL_HND_HELLO_VERIFY_REQUEST:
2253   case SSL_HND_NEWSESSION_TICKET:
2254   case SSL_HND_CERTIFICATE:
2255   case SSL_HND_SERVER_KEY_EXCHG:
2256   case SSL_HND_CERT_REQUEST:
2257   case SSL_HND_SVR_HELLO_DONE:
2258   case SSL_HND_CERT_VERIFY:
2259   case SSL_HND_CLIENT_KEY_EXCHG:
2260   case SSL_HND_FINISHED:
2261     return 1;
2262   }
2263   return 0;
2264 }
2265
2266 static gint
2267 dtls_is_authoritative_version_message(guint8 content_type, guint8 next_byte)
2268 {
2269   if (content_type == SSL_ID_HANDSHAKE
2270       && dtls_is_valid_handshake_type(next_byte))
2271     {
2272       return (next_byte != SSL_HND_CLIENT_HELLO);
2273     }
2274   else if (ssl_is_valid_content_type(content_type)
2275            && content_type != SSL_ID_HANDSHAKE)
2276     {
2277       return 1;
2278     }
2279   return 0;
2280 }
2281
2282 /* this applies a heuristic to determine whether
2283  * or not the data beginning at offset looks like a
2284  * valid dtls record.
2285  */
2286 static gint
2287 looks_like_dtls(tvbuff_t *tvb, guint32 offset)
2288 {
2289   /* have to have a valid content type followed by a valid
2290    * protocol version
2291    */
2292   guint8  byte;
2293   guint16 version;
2294
2295   /* see if the first byte is a valid content type */
2296   byte = tvb_get_guint8(tvb, offset);
2297   if (!ssl_is_valid_content_type(byte))
2298     {
2299       return 0;
2300     }
2301
2302   /* now check to see if the version byte appears valid */
2303   version = tvb_get_ntohs(tvb, offset + 1);
2304   if (version != DTLSV1DOT0_VERSION && version != DTLSV1DOT2_VERSION &&
2305       version != DTLSV1DOT0_VERSION_NOT)
2306     {
2307       return 0;
2308     }
2309
2310   return 1;
2311 }
2312
2313 /* UAT */
2314
2315 #ifdef HAVE_LIBGNUTLS
2316 static void
2317 dtlsdecrypt_free_cb(void* r)
2318 {
2319   ssldecrypt_assoc_t* h = (ssldecrypt_assoc_t*)r;
2320
2321   g_free(h->ipaddr);
2322   g_free(h->port);
2323   g_free(h->protocol);
2324   g_free(h->keyfile);
2325   g_free(h->password);
2326 }
2327 #endif
2328
2329 #if 0
2330 static void
2331 dtlsdecrypt_update_cb(void* r _U_, const char** err _U_)
2332 {
2333   return;
2334 }
2335 #endif
2336
2337 #ifdef HAVE_LIBGNUTLS
2338 static void *
2339 dtlsdecrypt_copy_cb(void* dest, const void* orig, size_t len _U_)
2340 {
2341   const ssldecrypt_assoc_t* o = (const ssldecrypt_assoc_t*)orig;
2342   ssldecrypt_assoc_t*       d = (ssldecrypt_assoc_t*)dest;
2343
2344   d->ipaddr    = g_strdup(o->ipaddr);
2345   d->port      = g_strdup(o->port);
2346   d->protocol  = g_strdup(o->protocol);
2347   d->keyfile   = g_strdup(o->keyfile);
2348   d->password  = g_strdup(o->password);
2349
2350   return d;
2351 }
2352
2353 UAT_CSTRING_CB_DEF(sslkeylist_uats,ipaddr,ssldecrypt_assoc_t)
2354 UAT_CSTRING_CB_DEF(sslkeylist_uats,port,ssldecrypt_assoc_t)
2355 UAT_CSTRING_CB_DEF(sslkeylist_uats,protocol,ssldecrypt_assoc_t)
2356 UAT_FILENAME_CB_DEF(sslkeylist_uats,keyfile,ssldecrypt_assoc_t)
2357 UAT_CSTRING_CB_DEF(sslkeylist_uats,password,ssldecrypt_assoc_t)
2358 #endif
2359
2360 void proto_reg_handoff_dtls(void);
2361
2362 /*********************************************************************
2363  *
2364  * Standard Wireshark Protocol Registration and housekeeping
2365  *
2366  *********************************************************************/
2367 void
2368 proto_register_dtls(void)
2369 {
2370
2371   /* Setup list of header fields See Section 1.6.1 for details*/
2372   static hf_register_info hf[] = {
2373     { &hf_dtls_record,
2374       { "Record Layer", "dtls.record",
2375         FT_NONE, BASE_NONE, NULL, 0x0,
2376         NULL, HFILL }
2377     },
2378     { &hf_dtls_record_content_type,
2379       { "Content Type", "dtls.record.content_type",
2380         FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
2381         NULL, HFILL}
2382     },
2383     { &hf_dtls_record_version,
2384       { "Version", "dtls.record.version",
2385         FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
2386         "Record layer version.", HFILL }
2387     },
2388     { &hf_dtls_record_epoch,
2389       { "Epoch", "dtls.record.epoch",
2390         FT_UINT16, BASE_DEC, NULL, 0x0,
2391         NULL, HFILL }
2392     },
2393     { &hf_dtls_record_sequence_number,
2394       { "Sequence Number", "dtls.record.sequence_number",
2395         FT_DOUBLE, BASE_NONE, NULL, 0x0,
2396         NULL, HFILL }
2397     },
2398     { &hf_dtls_record_length,
2399       { "Length", "dtls.record.length",
2400         FT_UINT16, BASE_DEC, NULL, 0x0,
2401         "Length of DTLS record data", HFILL }
2402     },
2403     { &hf_dtls_record_appdata,
2404       { "Encrypted Application Data", "dtls.app_data",
2405         FT_BYTES, BASE_NONE, NULL, 0x0,
2406         "Payload is encrypted application data", HFILL }
2407     },
2408     { &hf_dtls_change_cipher_spec,
2409       { "Change Cipher Spec Message", "dtls.change_cipher_spec",
2410         FT_NONE, BASE_NONE, NULL, 0x0,
2411         "Signals a change in cipher specifications", HFILL }
2412     },
2413     { & hf_dtls_alert_message,
2414       { "Alert Message", "dtls.alert_message",
2415         FT_NONE, BASE_NONE, NULL, 0x0,
2416         NULL, HFILL }
2417     },
2418     { & hf_dtls_alert_message_level,
2419       { "Level", "dtls.alert_message.level",
2420         FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
2421         "Alert message level", HFILL }
2422     },
2423     { &hf_dtls_alert_message_description,
2424       { "Description", "dtls.alert_message.desc",
2425         FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
2426         "Alert message description", HFILL }
2427     },
2428     { &hf_dtls_handshake_protocol,
2429       { "Handshake Protocol", "dtls.handshake",
2430         FT_NONE, BASE_NONE, NULL, 0x0,
2431         "Handshake protocol message", HFILL}
2432     },
2433     { &hf_dtls_handshake_type,
2434       { "Handshake Type", "dtls.handshake.type",
2435         FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
2436         "Type of handshake message", HFILL}
2437     },
2438     { &hf_dtls_handshake_length,
2439       { "Length", "dtls.handshake.length",
2440         FT_UINT24, BASE_DEC, NULL, 0x0,
2441         "Length of handshake message", HFILL }
2442     },
2443     { &hf_dtls_handshake_message_seq,
2444       { "Message Sequence", "dtls.handshake.message_seq",
2445         FT_UINT16, BASE_DEC, NULL, 0x0,
2446         "Message sequence of handshake message", HFILL }
2447     },
2448     { &hf_dtls_handshake_fragment_offset,
2449       { "Fragment Offset", "dtls.handshake.fragment_offset",
2450         FT_UINT24, BASE_DEC, NULL, 0x0,
2451         "Fragment offset of handshake message", HFILL }
2452     },
2453     { &hf_dtls_handshake_fragment_length,
2454       { "Fragment Length", "dtls.handshake.fragment_length",
2455         FT_UINT24, BASE_DEC, NULL, 0x0,
2456         "Fragment length of handshake message", HFILL }
2457     },
2458     { &hf_dtls_handshake_client_version,
2459       { "Version", "dtls.handshake.client_version",
2460         FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
2461         "Maximum version supported by client", HFILL }
2462     },
2463     { &hf_dtls_handshake_server_version,
2464       { "Version", "dtls.handshake.server_version",
2465         FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
2466         "Version selected by server", HFILL }
2467     },
2468     { &hf_dtls_handshake_random_time,
2469       { "GMT Unix Time", "dtls.handshake.random_time",
2470         FT_ABSOLUTE_TIME, ABSOLUTE_TIME_LOCAL, NULL, 0x0,
2471         "Unix time field of random structure", HFILL }
2472     },
2473     { &hf_dtls_handshake_random_bytes,
2474       { "Random Bytes", "dtls.handshake.random",
2475         FT_BYTES, BASE_NONE, NULL, 0x0,
2476         "Random challenge used to authenticate server", HFILL }
2477     },
2478     { &hf_dtls_handshake_cipher_suites_len,
2479       { "Cipher Suites Length", "dtls.handshake.cipher_suites_length",
2480         FT_UINT16, BASE_DEC, NULL, 0x0,
2481         "Length of cipher suites field", HFILL }
2482     },
2483     { &hf_dtls_handshake_cipher_suites,
2484       { "Cipher Suites", "dtls.handshake.ciphersuites",
2485         FT_NONE, BASE_NONE, NULL, 0x0,
2486         "List of cipher suites supported by client", HFILL }
2487     },
2488     { &hf_dtls_handshake_cipher_suite,
2489       { "Cipher Suite", "dtls.handshake.ciphersuite",
2490         FT_UINT16, BASE_HEX|BASE_EXT_STRING, &ssl_31_ciphersuite_ext, 0x0,
2491         NULL, HFILL }
2492     },
2493     { &hf_dtls_handshake_cookie_len,
2494       { "Cookie Length", "dtls.handshake.cookie_length",
2495         FT_UINT8, BASE_DEC, NULL, 0x0,
2496         "Length of the cookie field", HFILL }
2497     },
2498     { &hf_dtls_handshake_cookie,
2499       { "Cookie", "dtls.handshake.cookie",
2500         FT_BYTES, BASE_NONE, NULL, 0x0,
2501         NULL, HFILL }
2502     },
2503     { &hf_dtls_handshake_session_id,
2504       { "Session ID", "dtls.handshake.session_id",
2505         FT_BYTES, BASE_NONE, NULL, 0x0,
2506         "Identifies the DTLS session, allowing later resumption", HFILL }
2507     },
2508     { &hf_dtls_handshake_comp_methods_len,
2509       { "Compression Methods Length", "dtls.handshake.comp_methods_length",
2510         FT_UINT8, BASE_DEC, NULL, 0x0,
2511         "Length of compression methods field", HFILL }
2512     },
2513     { &hf_dtls_handshake_comp_methods,
2514       { "Compression Methods", "dtls.handshake.comp_methods",
2515         FT_NONE, BASE_NONE, NULL, 0x0,
2516         "List of compression methods supported by client", HFILL }
2517     },
2518     { &hf_dtls_handshake_comp_method,
2519       { "Compression Method", "dtls.handshake.comp_method",
2520         FT_UINT8, BASE_DEC, VALS(ssl_31_compression_method), 0x0,
2521         NULL, HFILL }
2522     },
2523     { &hf_dtls_handshake_extensions_len,
2524       { "Extensions Length", "dtls.handshake.extensions_length",
2525         FT_UINT16, BASE_DEC, NULL, 0x0,
2526         "Length of hello extensions", HFILL }
2527     },
2528     { &hf_dtls_handshake_extension_type,
2529       { "Type", "dtls.handshake.extension.type",
2530         FT_UINT16, BASE_HEX, VALS(tls_hello_extension_types), 0x0,
2531         "Hello extension type", HFILL }
2532     },
2533     { &hf_dtls_handshake_extension_len,
2534       { "Length", "dtls.handshake.extension.len",
2535         FT_UINT16, BASE_DEC, NULL, 0x0,
2536         "Length of a hello extension", HFILL }
2537     },
2538     { &hf_dtls_handshake_extension_data,
2539       { "Data", "dtls.handshake.extension.data",
2540         FT_BYTES, BASE_NONE, NULL, 0x0,
2541         "Hello Extension data", HFILL }
2542     },
2543     { &hf_dtls_handshake_session_ticket_lifetime_hint,
2544       { "Session Ticket Lifetime Hint", "dtls.handshake.session_ticket_lifetime_hint",
2545         FT_UINT32, BASE_DEC, NULL, 0x0,
2546         "New DTLS Session Ticket Lifetime Hint", HFILL }
2547     },
2548     { &hf_dtls_handshake_session_ticket_len,
2549       { "Session Ticket Length", "dtls.handshake.session_ticket_length",
2550         FT_UINT16, BASE_DEC, NULL, 0x0,
2551         "New DTLS Session Ticket Length", HFILL }
2552     },
2553     { &hf_dtls_handshake_session_ticket,
2554       { "Session Ticket", "dtls.handshake.session_ticket",
2555         FT_BYTES, BASE_NONE, NULL, 0x0,
2556         "New DTLS Session Ticket", HFILL }
2557     },
2558     { &hf_dtls_handshake_certificates_len,
2559       { "Certificates Length", "dtls.handshake.certificates_length",
2560         FT_UINT24, BASE_DEC, NULL, 0x0,
2561         "Length of certificates field", HFILL }
2562     },
2563     { &hf_dtls_handshake_certificates,
2564       { "Certificates", "dtls.handshake.certificates",
2565         FT_NONE, BASE_NONE, NULL, 0x0,
2566         "List of certificates", HFILL }
2567     },
2568     { &hf_dtls_handshake_certificate,
2569       { "Certificate", "dtls.handshake.certificate",
2570         FT_BYTES, BASE_NONE, NULL, 0x0,
2571         NULL, HFILL }
2572     },
2573     { &hf_dtls_handshake_certificate_len,
2574       { "Certificate Length", "dtls.handshake.certificate_length",
2575         FT_UINT24, BASE_DEC, NULL, 0x0,
2576         "Length of certificate", HFILL }
2577     },
2578     { &hf_dtls_handshake_cert_types_count,
2579       { "Certificate types count", "dtls.handshake.cert_types_count",
2580         FT_UINT8, BASE_DEC, NULL, 0x0,
2581         "Count of certificate types", HFILL }
2582     },
2583     { &hf_dtls_handshake_cert_types,
2584       { "Certificate types", "dtls.handshake.cert_types",
2585         FT_NONE, BASE_NONE, NULL, 0x0,
2586         "List of certificate types", HFILL }
2587     },
2588     { &hf_dtls_handshake_cert_type,
2589       { "Certificate type", "dtls.handshake.cert_type",
2590         FT_UINT8, BASE_DEC, VALS(ssl_31_client_certificate_type), 0x0,
2591         NULL, HFILL }
2592     },
2593     { &hf_dtls_handshake_finished,
2594       { "Verify Data", "dtls.handshake.verify_data",
2595         FT_NONE, BASE_NONE, NULL, 0x0,
2596         "Opaque verification data", HFILL }
2597     },
2598 #if 0
2599     { &hf_dtls_handshake_md5_hash,
2600       { "MD5 Hash", "dtls.handshake.md5_hash",
2601         FT_NONE, BASE_NONE, NULL, 0x0,
2602         "Hash of messages, master_secret, etc.", HFILL }
2603     },
2604     { &hf_dtls_handshake_sha_hash,
2605       { "SHA-1 Hash", "dtls.handshake.sha_hash",
2606         FT_NONE, BASE_NONE, NULL, 0x0,
2607         "Hash of messages, master_secret, etc.", HFILL }
2608     },
2609 #endif
2610     { &hf_dtls_handshake_session_id_len,
2611       { "Session ID Length", "dtls.handshake.session_id_length",
2612         FT_UINT8, BASE_DEC, NULL, 0x0,
2613         "Length of session ID field", HFILL }
2614     },
2615     { &hf_dtls_handshake_dnames_len,
2616       { "Distinguished Names Length", "dtls.handshake.dnames_len",
2617         FT_UINT16, BASE_DEC, NULL, 0x0,
2618         "Length of list of CAs that server trusts", HFILL }
2619     },
2620     { &hf_dtls_handshake_dnames,
2621       { "Distinguished Names", "dtls.handshake.dnames",
2622         FT_NONE, BASE_NONE, NULL, 0x0,
2623         "List of CAs that server trusts", HFILL }
2624     },
2625     { &hf_dtls_handshake_dname_len,
2626       { "Distinguished Name Length", "dtls.handshake.dname_len",
2627         FT_UINT16, BASE_DEC, NULL, 0x0,
2628         "Length of distinguished name", HFILL }
2629     },
2630     { &hf_dtls_handshake_dname,
2631       { "Distinguished Name", "dtls.handshake.dname",
2632         FT_BYTES, BASE_NONE, NULL, 0x0,
2633         "Distinguished name of a CA that server trusts", HFILL }
2634     },
2635     { &hf_dtls_heartbeat_extension_mode,
2636       { "Mode", "dtls.handshake.extension.heartbeat.mode",
2637         FT_UINT8, BASE_DEC, VALS(tls_heartbeat_mode), 0x0,
2638         "Heartbeat extension mode", HFILL }
2639     },
2640     { &hf_dtls_heartbeat_message,
2641       { "Heartbeat Message", "dtls.heartbeat_message",
2642         FT_NONE, BASE_NONE, NULL, 0x0,
2643         NULL, HFILL }
2644     },
2645     { &hf_dtls_heartbeat_message_type,
2646       { "Type", "dtls.heartbeat_message.type",
2647         FT_UINT8, BASE_DEC, VALS(tls_heartbeat_type), 0x0,
2648         "Heartbeat message type", HFILL }
2649     },
2650     { &hf_dtls_heartbeat_message_payload_length,
2651       { "Payload Length", "dtls.heartbeat_message.payload_length",
2652         FT_UINT16, BASE_DEC, NULL, 0x00, NULL, HFILL }
2653     },
2654     { &hf_dtls_heartbeat_message_payload,
2655       { "Payload Length", "dtls.heartbeat_message.payload",
2656         FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
2657     },
2658     { &hf_dtls_heartbeat_message_padding,
2659       { "Payload Length", "dtls.heartbeat_message.padding",
2660         FT_BYTES, BASE_NONE, NULL, 0x00, NULL, HFILL }
2661     },
2662     { &hf_dtls_fragments,
2663       { "Message fragments", "dtls.fragments",
2664         FT_NONE, BASE_NONE, NULL, 0x00, NULL, HFILL }
2665     },
2666     { &hf_dtls_fragment,
2667       { "Message fragment", "dtls.fragment",
2668         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
2669     },
2670     { &hf_dtls_fragment_overlap,
2671       { "Message fragment overlap", "dtls.fragment.overlap",
2672         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
2673     },
2674     { &hf_dtls_fragment_overlap_conflicts,
2675       { "Message fragment overlapping with conflicting data",
2676         "dtls.fragment.overlap.conflicts",
2677        FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
2678     },
2679     { &hf_dtls_fragment_multiple_tails,
2680       { "Message has multiple tail fragments",
2681         "dtls.fragment.multiple_tails",
2682         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
2683     },
2684     { &hf_dtls_fragment_too_long_fragment,
2685       { "Message fragment too long", "dtls.fragment.too_long_fragment",
2686         FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }
2687     },
2688     { &hf_dtls_fragment_error,
2689       { "Message defragmentation error", "dtls.fragment.error",
2690         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
2691     },
2692     { &hf_dtls_fragment_count,
2693       { "Message fragment count", "dtls.fragment.count",
2694         FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
2695     },
2696     { &hf_dtls_reassembled_in,
2697       { "Reassembled in", "dtls.reassembled.in",
2698         FT_FRAMENUM, BASE_NONE, NULL, 0x00, NULL, HFILL }
2699     },
2700     { &hf_dtls_reassembled_length,
2701       { "Reassembled DTLS length", "dtls.reassembled.length",
2702         FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL }
2703     },
2704   };
2705
2706   /* Setup protocol subtree array */
2707   static gint *ett[] = {
2708     &ett_dtls,
2709     &ett_dtls_record,
2710     &ett_dtls_alert,
2711     &ett_dtls_handshake,
2712     &ett_dtls_heartbeat,
2713     &ett_dtls_cipher_suites,
2714     &ett_dtls_comp_methods,
2715     &ett_dtls_extension,
2716     &ett_dtls_random,
2717     &ett_dtls_new_ses_ticket,
2718     &ett_dtls_certs,
2719     &ett_dtls_cert_types,
2720     &ett_dtls_dnames,
2721     &ett_dtls_fragment,
2722     &ett_dtls_fragments,
2723   };
2724
2725   /* Register the protocol name and description */
2726   proto_dtls = proto_register_protocol("Datagram Transport Layer Security",
2727                                        "DTLS", "dtls");
2728
2729   /* Required function calls to register the header fields and
2730    * subtrees used */
2731   proto_register_field_array(proto_dtls, hf, array_length(hf));
2732   proto_register_subtree_array(ett, array_length(ett));
2733
2734 #ifdef HAVE_LIBGNUTLS
2735   {
2736     module_t *dtls_module = prefs_register_protocol(proto_dtls, proto_reg_handoff_dtls);
2737
2738     static uat_field_t dtlskeylist_uats_flds[] = {
2739       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, ipaddr, "IP address", ssldecrypt_uat_fld_ip_chk_cb, "IPv4 or IPv6 address"),
2740       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, port, "Port", ssldecrypt_uat_fld_port_chk_cb, "Port Number"),
2741       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, protocol, "Protocol", ssldecrypt_uat_fld_protocol_chk_cb, "Protocol"),
2742       UAT_FLD_FILENAME_OTHER(sslkeylist_uats, keyfile, "Key File", ssldecrypt_uat_fld_fileopen_chk_cb, "Path to the keyfile."),
2743       UAT_FLD_CSTRING_OTHER(sslkeylist_uats, password," Password (p12 file)", ssldecrypt_uat_fld_password_chk_cb, "Password"),
2744       UAT_END_FIELDS
2745     };
2746
2747     dtlsdecrypt_uat = uat_new("DTLS RSA Keylist",
2748                               sizeof(ssldecrypt_assoc_t),
2749                               "dtlsdecrypttablefile",         /* filename */
2750                               TRUE,                           /* from_profile */
2751                               (void**) &dtlskeylist_uats,     /* data_ptr */
2752                               &ndtlsdecrypt,                  /* numitems_ptr */
2753                               UAT_AFFECTS_DISSECTION,         /* affects dissection of packets, but not set of named fields */
2754                               "ChK12ProtocolsSection",        /* TODO, need revision - help */
2755                               dtlsdecrypt_copy_cb,
2756                               NULL, /* dtlsdecrypt_update_cb? */
2757                               dtlsdecrypt_free_cb,
2758                               dtls_parse_uat,
2759                               dtlskeylist_uats_flds);
2760
2761     prefs_register_uat_preference(dtls_module, "cfg",
2762                                   "RSA keys list",
2763                                   "A table of RSA keys for DTLS decryption",
2764                                   dtlsdecrypt_uat);
2765
2766     prefs_register_filename_preference(dtls_module, "debug_file", "DTLS debug file",
2767                                        "redirect dtls debug to file name; leave empty to disable debug, "
2768                                        "use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr\n",
2769                                        &dtls_debug_file_name);
2770
2771     prefs_register_string_preference(dtls_module, "keys_list", "RSA keys list (deprecated)",
2772                                      "Semicolon-separated list of private RSA keys used for DTLS decryption. "
2773                                      "Used by versions of Wireshark prior to 1.6",
2774                                      &dtls_keys_list);
2775
2776   }
2777 #endif
2778
2779   register_dissector("dtls", dissect_dtls, proto_dtls);
2780   dtls_handle = find_dissector("dtls");
2781
2782   dtls_associations = g_tree_new(ssl_association_cmp);
2783
2784   register_init_routine(dtls_init);
2785   ssl_lib_init();
2786   dtls_tap = register_tap("dtls");
2787   ssl_debug_printf("proto_register_dtls: registered tap %s:%d\n",
2788                    "dtls", dtls_tap);
2789
2790   register_heur_dissector_list("dtls", &heur_subdissector_list);
2791 }
2792
2793
2794 /* If this dissector uses sub-dissector registration add a registration
2795  * routine.  This format is required because a script is used to find
2796  * these routines and create the code that calls these routines.
2797  */
2798 void
2799 proto_reg_handoff_dtls(void)
2800 {
2801   static gboolean initialized = FALSE;
2802
2803   /* add now dissector to default ports.*/
2804   dtls_parse_uat();
2805   dtls_parse_old_keys();
2806
2807   if (initialized == FALSE) {
2808     heur_dissector_add("udp", dissect_dtls_heur, proto_dtls);
2809     dissector_add_uint("sctp.ppi", DIAMETER_DTLS_PROTOCOL_ID, find_dissector("dtls"));
2810   }
2811
2812   initialized = TRUE;
2813 }