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