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