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