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