Pass NULL (instead of proto_) in the last parameter of tap_queue_packet()
[obnox/wireshark/wip.git] / epan / dissectors / packet-ssl.c
1 /* packet-ssl.c
2  * Routines for ssl dissection
3  * Copyright (c) 2000-2001, Scott Renfro <scott@renfro.org>
4  *
5  * $Id$
6  *
7  * Wireshark - Network traffic analyzer
8  * By Gerald Combs <gerald@wireshark.org>
9  * Copyright 1998 Gerald Combs
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24  *
25  * See
26  *
27  *      http://www.netscape.com/eng/security/SSL_2.html
28  *
29  * for SSL 2.0 specs.
30  *
31  * See
32  *
33  *      http://www.netscape.com/eng/ssl3/
34  *
35  * for SSL 3.0 specs.
36  *
37  * See RFC 2246 for SSL 3.1/TLS 1.0 specs.
38  *
39  * See (among other places)
40  *
41  *      http://www.graphcomp.com/info/specs/ms/pct.htm
42  *
43  * for PCT 1 draft specs.
44  *
45  * See
46  *
47  *      http://research.sun.com/projects/crypto/draft-ietf-tls-ecc-05.txt
48  *
49  * for Elliptic Curve Cryptography cipher suites.
50  *
51  * See
52  *
53  *      http://www.ietf.org/internet-drafts/draft-ietf-tls-camellia-04.txt
54  *
55  * for Camellia-based cipher suites.
56  *
57  * Notes:
58  *
59  *   - Does not support dissection
60  *     of frames that would require state maintained between frames
61  *     (e.g., single ssl records spread across multiple tcp frames)
62  *
63  *   - Identifies, but does not fully dissect the following messages:
64  *
65  *     - SSLv3/TLS (These need more state from previous handshake msgs)
66  *       - Server Key Exchange
67  *       - Client Key Exchange
68  *       - Certificate Verify
69  *
70  *     - SSLv2 (These don't appear in the clear)
71  *       - Error
72  *       - Client Finished
73  *       - Server Verify
74  *       - Server Finished
75  *       - Request Certificate
76  *       - Client Certificate
77  *
78  *    - Decryption is supported only for session that use RSA key exchange,
79  *      if the host private key is provided via preference.
80  *
81  *    - Decryption need to be performed 'sequentially', so it's done
82  *      at packet reception time. This may cause a significative packet capture
83  *      slow down. This also cause do dissect some ssl info that in previous
84  *      dissector version were dissected only when a proto_tree context was
85  *      available
86  *
87  *     We are at Packet reception if time pinfo->fd->flags.visited == 0
88  *
89  */
90
91 #ifdef HAVE_CONFIG_H
92 # include "config.h"
93 #endif
94
95 #include <stdio.h>
96 #include <stdlib.h>
97 #include <string.h>
98 #include <sys/stat.h>
99 #include <errno.h>
100
101 #include <sys/types.h>
102 #ifdef HAVE_SYS_SOCKET_H
103 #include <sys/socket.h>
104 #endif
105
106 #include <glib.h>
107
108 #include <epan/conversation.h>
109 #include <epan/reassemble.h>
110 #include <epan/prefs.h>
111 #include <epan/emem.h>
112 #include <epan/inet_v6defs.h>
113 #include <epan/dissectors/packet-tcp.h>
114 #include <epan/dissectors/packet-x509af.h>
115 #include <epan/tap.h>
116 #include <epan/filesystem.h>
117 #include <epan/report_err.h>
118 #include "packet-ssl.h"
119 #include "packet-ssl-utils.h"
120
121
122 static gboolean ssl_desegment = TRUE;
123 static gboolean ssl_desegment_app_data = TRUE;
124
125
126 /*********************************************************************
127  *
128  * Protocol Constants, Variables, Data Structures
129  *
130  *********************************************************************/
131
132 /* Initialize the protocol and registered fields */
133 static gint ssl_tap                           = -1;
134 static gint proto_ssl                         = -1;
135 static gint hf_ssl_record                     = -1;
136 static gint hf_ssl_record_content_type        = -1;
137 static gint hf_ssl_record_version             = -1;
138 static gint hf_ssl_record_length              = -1;
139 static gint hf_ssl_record_appdata             = -1;
140 static gint hf_ssl2_record                    = -1;
141 static gint hf_ssl2_record_is_escape          = -1;
142 static gint hf_ssl2_record_padding_length     = -1;
143 static gint hf_ssl2_msg_type                  = -1;
144 static gint hf_pct_msg_type                   = -1;
145 static gint hf_ssl_change_cipher_spec         = -1;
146 static gint hf_ssl_alert_message              = -1;
147 static gint hf_ssl_alert_message_level        = -1;
148 static gint hf_ssl_alert_message_description  = -1;
149 static gint hf_ssl_handshake_protocol         = -1;
150 static gint hf_ssl_handshake_type             = -1;
151 static gint hf_ssl_handshake_length           = -1;
152 static gint hf_ssl_handshake_client_version   = -1;
153 static gint hf_ssl_handshake_server_version   = -1;
154 static gint hf_ssl_handshake_random_time      = -1;
155 static gint hf_ssl_handshake_random_bytes     = -1;
156 static gint hf_ssl_handshake_cipher_suites_len = -1;
157 static gint hf_ssl_handshake_cipher_suites    = -1;
158 static gint hf_ssl_handshake_cipher_suite     = -1;
159 static gint hf_ssl_handshake_session_id       = -1;
160 static gint hf_ssl_handshake_comp_methods_len = -1;
161 static gint hf_ssl_handshake_comp_methods     = -1;
162 static gint hf_ssl_handshake_comp_method      = -1;
163 static gint hf_ssl_handshake_extensions_len   = -1;
164 static gint hf_ssl_handshake_extension_type   = -1;
165 static gint hf_ssl_handshake_extension_len    = -1;
166 static gint hf_ssl_handshake_extension_data   = -1;
167 static gint hf_ssl_handshake_certificates_len = -1;
168 static gint hf_ssl_handshake_certificates     = -1;
169 static gint hf_ssl_handshake_certificate      = -1;
170 static gint hf_ssl_handshake_certificate_len  = -1;
171 static gint hf_ssl_handshake_cert_types_count = -1;
172 static gint hf_ssl_handshake_cert_types       = -1;
173 static gint hf_ssl_handshake_cert_type        = -1;
174 static gint hf_ssl_handshake_finished         = -1;
175 static gint hf_ssl_handshake_md5_hash         = -1;
176 static gint hf_ssl_handshake_sha_hash         = -1;
177 static gint hf_ssl_handshake_session_id_len   = -1;
178 static gint hf_ssl_handshake_dnames_len       = -1;
179 static gint hf_ssl_handshake_dnames           = -1;
180 static gint hf_ssl_handshake_dname_len        = -1;
181 static gint hf_ssl_handshake_dname            = -1;
182 static gint hf_ssl2_handshake_cipher_spec_len = -1;
183 static gint hf_ssl2_handshake_session_id_len  = -1;
184 static gint hf_ssl2_handshake_challenge_len   = -1;
185 static gint hf_ssl2_handshake_cipher_spec     = -1;
186 static gint hf_ssl2_handshake_challenge       = -1;
187 static gint hf_ssl2_handshake_clear_key_len   = -1;
188 static gint hf_ssl2_handshake_enc_key_len     = -1;
189 static gint hf_ssl2_handshake_key_arg_len     = -1;
190 static gint hf_ssl2_handshake_clear_key       = -1;
191 static gint hf_ssl2_handshake_enc_key         = -1;
192 static gint hf_ssl2_handshake_key_arg         = -1;
193 static gint hf_ssl2_handshake_session_id_hit  = -1;
194 static gint hf_ssl2_handshake_cert_type       = -1;
195 static gint hf_ssl2_handshake_connection_id_len = -1;
196 static gint hf_ssl2_handshake_connection_id   = -1;
197 static gint hf_pct_handshake_cipher_spec        = -1;
198 static gint hf_pct_handshake_hash_spec  = -1;
199 static gint hf_pct_handshake_cert_spec  = -1;
200 static gint hf_pct_handshake_cert       = -1;
201 static gint hf_pct_handshake_server_cert        = -1;
202 static gint hf_pct_handshake_exch_spec  = -1;
203 static gint hf_pct_handshake_hash       = -1;
204 static gint hf_pct_handshake_cipher     = -1;
205 static gint hf_pct_handshake_exch       = -1;
206 static gint hf_pct_handshake_sig                = -1;
207 static gint hf_pct_msg_error_type       = -1;
208 static int hf_ssl_reassembled_in = -1;
209 static int hf_ssl_segments = -1;
210 static int hf_ssl_segment = -1;
211 static int hf_ssl_segment_overlap = -1;
212 static int hf_ssl_segment_overlap_conflict = -1;
213 static int hf_ssl_segment_multiple_tails = -1;
214 static int hf_ssl_segment_too_long_fragment = -1;
215 static int hf_ssl_segment_error = -1;
216
217 /* Initialize the subtree pointers */
218 static gint ett_ssl                   = -1;
219 static gint ett_ssl_record            = -1;
220 static gint ett_ssl_alert             = -1;
221 static gint ett_ssl_handshake         = -1;
222 static gint ett_ssl_cipher_suites     = -1;
223 static gint ett_ssl_comp_methods      = -1;
224 static gint ett_ssl_extension         = -1;
225 static gint ett_ssl_certs             = -1;
226 static gint ett_ssl_cert_types        = -1;
227 static gint ett_ssl_dnames            = -1;
228 static gint ett_ssl_random            = -1;
229 static gint ett_pct_cipher_suites         = -1;
230 static gint ett_pct_hash_suites           = -1;
231 static gint ett_pct_cert_suites           = -1;
232 static gint ett_pct_exch_suites           = -1;
233 static gint ett_ssl_segments = -1;
234 static gint ett_ssl_segment  = -1;
235
236
237 /* not all of the hf_fields below make sense for SSL but we have to provide
238    them anyways to comply with the api (which was aimed for ip fragment
239    reassembly) */
240 static const fragment_items ssl_segment_items = {
241         &ett_ssl_segment,
242         &ett_ssl_segments,
243         &hf_ssl_segments,
244         &hf_ssl_segment,
245         &hf_ssl_segment_overlap,
246         &hf_ssl_segment_overlap_conflict,
247         &hf_ssl_segment_multiple_tails,
248         &hf_ssl_segment_too_long_fragment,
249         &hf_ssl_segment_error,
250         &hf_ssl_reassembled_in,
251         "Segments"
252 };
253
254 static GHashTable *ssl_session_hash = NULL;
255 static GHashTable *ssl_key_hash = NULL;
256 static GTree* ssl_associations = NULL;
257 static dissector_handle_t ssl_handle = NULL;
258 static StringInfo ssl_compressed_data = {NULL, 0};
259 static StringInfo ssl_decrypted_data = {NULL, 0};
260 static gint ssl_decrypted_data_avail = 0;
261
262 static gchar* ssl_keys_list = NULL;
263
264 #if defined(SSL_DECRYPT_DEBUG) || defined(HAVE_LIBGNUTLS)
265 static gchar* ssl_debug_file_name = NULL;
266 #endif
267
268 const gchar* ssl_version_short_names[] = {
269     "SSL",
270     "SSLv2",
271     "SSLv3",
272     "TLSv1",
273     "TLSv1.1",
274     "DTLSv1.0",
275     "PCT"
276 };
277
278 /* Forward declaration we need below */
279 void proto_reg_handoff_ssl(void);
280
281 /* Desegmentation of SSL streams */
282 /* table to hold defragmented SSL streams */
283 static GHashTable *ssl_fragment_table = NULL;
284 static void
285 ssl_fragment_init(void)
286 {
287         fragment_table_init(&ssl_fragment_table);
288 }
289
290 /* initialize/reset per capture state data (ssl sessions cache) */
291 static void
292 ssl_init(void)
293 {
294   ssl_common_init(&ssl_session_hash, &ssl_decrypted_data, &ssl_compressed_data);
295   ssl_fragment_init();
296 }
297
298 /* parse ssl related preferences (private keys and ports association strings) */
299 static void
300 ssl_parse(void)
301 {
302     ep_stack_t tmp_stack;
303     SslAssociation *tmp_assoc;
304     FILE *ssl_keys_file;
305         struct stat statb;
306         size_t size;
307         gchar *tmp_buf;
308
309     ssl_set_debug(ssl_debug_file_name);
310
311     if (ssl_key_hash)
312     {
313         g_hash_table_foreach(ssl_key_hash, ssl_private_key_free, NULL);
314         g_hash_table_destroy(ssl_key_hash);
315     }
316
317     /* remove only associations created from key list */
318     tmp_stack = ep_stack_new();
319     g_tree_traverse(ssl_associations, ssl_assoc_from_key_list, G_IN_ORDER, tmp_stack);
320     while ((tmp_assoc = ep_stack_pop(tmp_stack)) != NULL) {
321         ssl_association_remove(ssl_associations, tmp_assoc);
322     }
323
324     /* parse private keys string, load available keys and put them in key hash*/
325     ssl_key_hash = g_hash_table_new(ssl_private_key_hash,ssl_private_key_equal);
326
327     if (ssl_keys_list && (ssl_keys_list[0] != 0))
328     {
329                 if (file_exists(ssl_keys_list)) {
330                     if ((ssl_keys_file = fopen(ssl_keys_list, "r"))) {
331                                 fstat(fileno(ssl_keys_file), &statb);
332                                 size = statb.st_size;
333                                 tmp_buf = ep_alloc0(size + 1);
334                                 fread(tmp_buf, size, 1, ssl_keys_file);
335                                 tmp_buf[size] = '\0';
336                                 fclose(ssl_keys_file);
337                         ssl_parse_key_list(tmp_buf,ssl_key_hash,ssl_associations,ssl_handle,TRUE);
338                         } else {
339                         report_open_failure(ssl_keys_list, errno, FALSE);
340                     }
341
342                 } else {
343                 ssl_parse_key_list(ssl_keys_list,ssl_key_hash,ssl_associations,ssl_handle,TRUE);
344                 }
345     }
346
347 }
348
349 /*********************************************************************
350  *
351  * Forward Declarations
352  *
353  *********************************************************************/
354
355 /*
356  * SSL version 3 and TLS dissectors
357  *
358  */
359 /* record layer dissector */
360 static gint dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
361                                proto_tree *tree, guint32 offset,
362                                guint *conv_version,
363                                gboolean *need_desegmentation,
364                                SslDecryptSession *conv_data,
365                                gboolean first_record_in_frame);
366
367 /* change cipher spec dissector */
368 static void dissect_ssl3_change_cipher_spec(tvbuff_t *tvb,
369                                             proto_tree *tree,
370                                             guint32 offset,
371                                             guint *conv_version, guint8 content_type);
372
373 /* alert message dissector */
374 static void dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
375                                proto_tree *tree, guint32 offset,
376                                guint *conv_version);
377
378 /* handshake protocol dissector */
379 static void dissect_ssl3_handshake(tvbuff_t *tvb, packet_info *pinfo,
380                                    proto_tree *tree, guint32 offset,
381                                    guint32 record_length,
382                                    guint *conv_version,
383                                    SslDecryptSession *conv_data, guint8 content_type);
384
385
386 static void dissect_ssl3_hnd_cli_hello(tvbuff_t *tvb,
387                                        proto_tree *tree,
388                                        guint32 offset, guint32 length,
389                                        SslDecryptSession* ssl);
390
391 static void dissect_ssl3_hnd_srv_hello(tvbuff_t *tvb,
392                                        proto_tree *tree,
393                                        guint32 offset, guint32 length,
394                                        SslDecryptSession* ssl);
395
396 static void dissect_ssl3_hnd_cert(tvbuff_t *tvb,
397                                   proto_tree *tree, guint32 offset, packet_info *pinfo);
398
399 static void dissect_ssl3_hnd_cert_req(tvbuff_t *tvb,
400                                       proto_tree *tree,
401                                       guint32 offset);
402
403 static void dissect_ssl3_hnd_finished(tvbuff_t *tvb,
404                                       proto_tree *tree,
405                                       guint32 offset,
406                                       guint* conv_version);
407
408
409 /*
410  * SSL version 2 dissectors
411  *
412  */
413
414 /* record layer dissector */
415 static gint dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo,
416                                proto_tree *tree, guint32 offset,
417                                guint *conv_version,
418                                gboolean *need_desegmentation,
419                                SslDecryptSession* ssl);
420
421 /* client hello dissector */
422 static void dissect_ssl2_hnd_client_hello(tvbuff_t *tvb,
423                                           proto_tree *tree,
424                                           guint32 offset,
425                                           SslDecryptSession* ssl);
426
427 static void dissect_pct_msg_client_hello(tvbuff_t *tvb,
428                                           proto_tree *tree,
429                                           guint32 offset);
430
431 /* client master key dissector */
432 static void dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
433                                                proto_tree *tree,
434                                                guint32 offset);
435 static void dissect_pct_msg_client_master_key(tvbuff_t *tvb,
436                                               proto_tree *tree,
437                                               guint32 offset);
438
439 /* server hello dissector */
440 static void dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
441                                           proto_tree *tree,
442                                           guint32 offset, packet_info *pinfo);
443 static void dissect_pct_msg_server_hello(tvbuff_t *tvb,
444                                          proto_tree *tree,
445                                          guint32 offset, packet_info *pinfo);
446
447
448 static void dissect_pct_msg_server_verify(tvbuff_t *tvb,
449                                               proto_tree *tree,
450                                               guint32 offset);
451
452 static void dissect_pct_msg_error(tvbuff_t *tvb,
453                                               proto_tree *tree,
454                                               guint32 offset);
455
456 /*
457  * Support Functions
458  *
459  */
460 /*static void ssl_set_conv_version(packet_info *pinfo, guint version);*/
461 static gint  ssl_is_valid_handshake_type(guint8 type);
462 static gint  ssl_is_valid_ssl_version(guint16 version);
463 static gint  ssl_is_authoritative_version_message(guint8 content_type,
464                                                 guint8 next_byte);
465 static gint  ssl_is_v2_client_hello(tvbuff_t *tvb, guint32 offset);
466 static gint  ssl_looks_like_sslv2(tvbuff_t *tvb, guint32 offset);
467 static gint  ssl_looks_like_sslv3(tvbuff_t *tvb, guint32 offset);
468 static gint  ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb,
469                                               guint32 offset,
470                                               guint32 record_length);
471 static gint  ssl_looks_like_valid_pct_handshake(tvbuff_t *tvb,
472                                                guint32 offset,
473                                                guint32 record_length);
474 /*********************************************************************
475  *
476  * Main dissector
477  *
478  *********************************************************************/
479 /*
480  * Code to actually dissect the packets
481  */
482 static void
483 dissect_ssl(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
484 {
485
486     conversation_t *conversation;
487     void *conv_data;
488     proto_item *ti;
489     proto_tree *ssl_tree;
490     guint32 offset;
491     gboolean first_record_in_frame;
492     gboolean need_desegmentation;
493     SslDecryptSession* ssl_session;
494     guint* conv_version;
495     ti = NULL;
496     ssl_tree   = NULL;
497     offset = 0;
498     first_record_in_frame = TRUE;
499     ssl_session = NULL;
500
501     ssl_debug_printf("\ndissect_ssl enter frame #%u (%s)\n", pinfo->fd->num, (pinfo->fd->flags.visited)?"already visited":"first time");
502
503     /* Track the version using conversations to reduce the
504      * chance that a packet that simply *looks* like a v2 or
505      * v3 packet is dissected improperly.  This also allows
506      * us to more frequently set the protocol column properly
507      * for continuation data frames.
508      *
509      * Also: We use the copy in conv_version as our cached copy,
510      *       so that we don't have to search the conversation
511      *       table every time we want the version; when setting
512      *       the conv_version, must set the copy in the conversation
513      *       in addition to conv_version
514      */
515     conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype,
516                                      pinfo->srcport, pinfo->destport, 0);
517
518     if (!conversation)
519     {
520         /* create a new conversation */
521         conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype,
522                                         pinfo->srcport, pinfo->destport, 0);
523     }
524     conv_data = conversation_get_proto_data(conversation, proto_ssl);
525
526     /* PAOLO: manage ssl decryption data */
527     /*get a valid ssl session pointer*/
528     if (conv_data != NULL)
529         ssl_session = conv_data;
530     else {
531         SslService dummy;
532
533         ssl_session = se_alloc0(sizeof(SslDecryptSession));
534         ssl_session_init(ssl_session);
535         ssl_session->version = SSL_VER_UNKNOWN;
536         conversation_add_proto_data(conversation, proto_ssl, ssl_session);
537
538         /* we need to know witch side of conversation is speaking*/
539         if (ssl_packet_from_server(ssl_associations, pinfo->srcport, pinfo->ptype == PT_TCP)) {
540             dummy.addr = pinfo->src;
541             dummy.port = pinfo->srcport;
542         }
543         else {
544             dummy.addr = pinfo->dst;
545             dummy.port = pinfo->destport;
546         }
547         ssl_debug_printf("dissect_ssl server %hhu.%hhu.%hhu.%hhu:%u\n",
548             dummy.addr.data[0],
549             dummy.addr.data[1],dummy.addr.data[2],
550             dummy.addr.data[3],dummy.port);
551
552         /* try to retrive private key for this service. Do it now 'cause pinfo
553          * is not always available
554          * Note that with HAVE_LIBGNUTLS undefined private_key is allways 0
555          * and thus decryption never engaged*/
556         ssl_session->private_key = g_hash_table_lookup(ssl_key_hash, &dummy);
557         if (!ssl_session->private_key)
558             ssl_debug_printf("dissect_ssl can't find private key for this server!\n");
559     }
560     conv_version= & ssl_session->version;
561
562     /* try decryption only the first time we see this packet
563      * (to keep cipher syncronized)and only if we have
564      * the server private key*/
565     if (pinfo->fd->flags.visited)
566          ssl_session = NULL;
567
568     /* Initialize the protocol column; we'll set it later when we
569      * figure out what flavor of SSL it is (assuming we don't
570      * throw an exception before we get the chance to do so). */
571     if (check_col(pinfo->cinfo, COL_PROTOCOL))
572     {
573         col_set_str(pinfo->cinfo, COL_PROTOCOL, "SSL");
574     }
575     /* clear the the info column */
576     if (check_col(pinfo->cinfo, COL_INFO))
577         col_clear(pinfo->cinfo, COL_INFO);
578
579     /* TCP packets and SSL records are orthogonal.
580      * A tcp packet may contain multiple ssl records and an ssl
581      * record may be spread across multiple tcp packets.
582      *
583      * This loop accounts for multiple ssl records in a single
584      * frame, but not a single ssl record across multiple tcp
585      * packets.
586      *
587      * Handling the single ssl record across multiple packets
588      * may be possible using wireshark conversations, but
589      * probably not cleanly.  May have to wait for tcp stream
590      * reassembly.
591      */
592
593     /* Create display subtree for SSL as a whole */
594     if (tree)
595     {
596         ti = proto_tree_add_item(tree, proto_ssl, tvb, 0, -1, FALSE);
597         ssl_tree = proto_item_add_subtree(ti, ett_ssl);
598     }
599     /* iterate through the records in this tvbuff */
600     while (tvb_reported_length_remaining(tvb, offset) != 0)
601     {
602         /* on second and subsequent records per frame
603          * add a delimiter on info column
604          */
605         if (!first_record_in_frame
606             && check_col(pinfo->cinfo, COL_INFO))
607         {
608             col_append_str(pinfo->cinfo, COL_INFO, ", ");
609         }
610
611         /*
612          * Assume, for now, that this doesn't need desegmentation.
613          */
614         need_desegmentation = FALSE;
615
616         /* first try to dispatch off the cached version
617          * known to be associated with the conversation
618          */
619         switch(*conv_version) {
620         case SSL_VER_SSLv2:
621         case SSL_VER_PCT:
622             offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
623                                          offset, conv_version,
624                                          &need_desegmentation,
625                                          ssl_session);
626             break;
627
628         case SSL_VER_SSLv3:
629         case SSL_VER_TLS:
630             /* the version tracking code works too well ;-)
631              * at times, we may visit a v2 client hello after
632              * we already know the version of the connection;
633              * work around that here by detecting and calling
634              * the v2 dissector instead
635              */
636             if (ssl_is_v2_client_hello(tvb, offset))
637             {
638                 offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
639                                              offset, conv_version,
640                                              &need_desegmentation,
641                                              ssl_session);
642             }
643             else
644             {
645                 offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
646                                              offset, conv_version,
647                                              &need_desegmentation,
648                                              ssl_session,
649                                              first_record_in_frame);
650             }
651             break;
652
653             /* that failed, so apply some heuristics based
654              * on this individual packet
655              */
656         default:
657             if (ssl_looks_like_sslv2(tvb, offset))
658             {
659                 /* looks like sslv2 or pct client hello */
660                 offset = dissect_ssl2_record(tvb, pinfo, ssl_tree,
661                                              offset, conv_version,
662                                              &need_desegmentation,
663                                              ssl_session);
664             }
665             else if (ssl_looks_like_sslv3(tvb, offset))
666             {
667                 /* looks like sslv3 or tls */
668                 offset = dissect_ssl3_record(tvb, pinfo, ssl_tree,
669                                              offset, conv_version,
670                                              &need_desegmentation,
671                                              ssl_session,
672                                              first_record_in_frame);
673             }
674             else
675             {
676                 /* looks like something unknown, so lump into
677                  * continuation data
678                  */
679                 offset = tvb_length(tvb);
680                 if (check_col(pinfo->cinfo, COL_INFO))
681                     col_append_str(pinfo->cinfo, COL_INFO,
682                                    "Continuation Data");
683
684                 /* Set the protocol column */
685                 if (check_col(pinfo->cinfo, COL_PROTOCOL))
686                 {
687                     col_set_str(pinfo->cinfo, COL_PROTOCOL,
688                          ssl_version_short_names[*conv_version]);
689                 }
690             }
691             break;
692         }
693
694         /* Desegmentation return check */
695         if (need_desegmentation)
696           return;
697         /* set up for next record in frame, if any */
698         first_record_in_frame = FALSE;
699     }
700     if (check_col(pinfo->cinfo, COL_INFO))
701         col_set_fence(pinfo->cinfo, COL_INFO);
702
703     tap_queue_packet(ssl_tap, pinfo, NULL);
704 }
705
706 static gint
707 decrypt_ssl3_record(tvbuff_t *tvb, packet_info *pinfo, guint32 offset,
708         guint32 record_length, guint8 content_type, SslDecryptSession* ssl,
709         gboolean save_plaintext)
710 {
711     gint ret;
712     gint direction;
713     StringInfo* data_for_iv;
714     gint data_for_iv_len;
715     SslDecoder* decoder;
716     ret = 0;
717     /* if we can decrypt and decryption have success
718     * add decrypted data to this packet info*/
719     ssl_debug_printf("decrypt_ssl3_record: app_data len %d ssl, state 0x%02X\n",
720         record_length, ssl->state);
721     direction = ssl_packet_from_server(ssl_associations, pinfo->srcport, pinfo->ptype == PT_TCP);
722
723     /* retrive decoder for this packet direction*/
724     if (direction != 0) {
725         ssl_debug_printf("decrypt_ssl3_record: using server decoder\n");
726         decoder = ssl->server;
727     }
728     else {
729         ssl_debug_printf("decrypt_ssl3_record: using client decoder\n");
730         decoder = ssl->client;
731     }
732
733     if (!decoder) {
734         ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
735         /* save data to update IV if decoder is available later */
736         data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
737         data_for_iv_len = (record_length < 24) ? record_length : 24;
738         ssl_data_set(data_for_iv, (guchar*)tvb_get_ptr(tvb, offset + record_length - data_for_iv_len, data_for_iv_len), data_for_iv_len);
739         return ret;
740     }
741
742     /* run decryption and add decrypted payload to protocol data, if decryption
743     * is successful*/
744     ssl_decrypted_data_avail = ssl_decrypted_data.data_len;
745     if (ssl_decrypt_record(ssl, decoder,
746           content_type, tvb_get_ptr(tvb, offset, record_length),
747           record_length, &ssl_compressed_data, &ssl_decrypted_data, &ssl_decrypted_data_avail) == 0)
748         ret = 1;
749     /*  */
750     if (!ret) {
751         /* save data to update IV if valid session key is obtained later */
752         data_for_iv = (direction != 0) ? &ssl->server_data_for_iv : &ssl->client_data_for_iv;
753         data_for_iv_len = (record_length < 24) ? record_length : 24;
754         ssl_data_set(data_for_iv, (guchar*)tvb_get_ptr(tvb, offset + record_length - data_for_iv_len, data_for_iv_len), data_for_iv_len);
755     }
756     if (ret && save_plaintext) {
757       ssl_add_data_info(proto_ssl, pinfo, ssl_decrypted_data.data, ssl_decrypted_data_avail,  TVB_RAW_OFFSET(tvb)+offset, decoder->flow);
758     }
759     return ret;
760 }
761
762 static void
763 process_ssl_payload(tvbuff_t *tvb, volatile int offset, packet_info *pinfo,
764         proto_tree *root_tree, proto_tree *tree, SslAssociation* association,
765         guint32 seq, guint32 nxtseq, gboolean is_ssl_segment,
766         SslFlow *flow);
767
768 static void
769 desegment_ssl(tvbuff_t *tvb, packet_info *pinfo, int offset,
770                 guint32 seq, guint32 nxtseq,
771                 SslAssociation* association,
772                 proto_tree *root_tree, proto_tree *tree,
773                 SslFlow *flow)
774 {
775         fragment_data *ipfd_head;
776         gboolean must_desegment;
777         gboolean called_dissector;
778         int another_pdu_follows;
779         int deseg_offset;
780         guint32 deseg_seq;
781         gint nbytes;
782         proto_item *item;
783         proto_item *frag_tree_item;
784         proto_item *ssl_tree_item;
785     struct tcp_multisegment_pdu *msp;
786
787 again:
788         ipfd_head=NULL;
789         must_desegment = FALSE;
790         called_dissector = FALSE;
791         another_pdu_follows = 0;
792         msp=NULL;
793
794         /*
795          * Initialize these to assume no desegmentation.
796          * If that's not the case, these will be set appropriately
797          * by the subdissector.
798          */
799         pinfo->desegment_offset = 0;
800         pinfo->desegment_len = 0;
801
802         /*
803          * Initialize this to assume that this segment will just be
804          * added to the middle of a desegmented chunk of data, so
805          * that we should show it all as data.
806          * If that's not the case, it will be set appropriately.
807          */
808         deseg_offset = offset;
809
810         /* find the most previous PDU starting before this sequence number */
811         msp=se_tree_lookup32_le(flow->multisegment_pdus, seq-1);
812         if(msp && msp->seq<=seq && msp->nxtpdu>seq){
813                 int len;
814
815                 if(!pinfo->fd->flags.visited){
816                         msp->last_frame=pinfo->fd->num;
817                         msp->last_frame_time=pinfo->fd->abs_ts;
818                 }
819
820                 /* OK, this PDU was found, which means the segment continues
821                    a higher-level PDU and that we must desegment it.
822                 */
823                 if(msp->flags&MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT){
824                         /* The dissector asked for the entire segment */
825                         len=tvb_length_remaining(tvb, offset);
826                 } else {
827                         len=MIN(nxtseq, msp->nxtpdu) - seq;
828                 }
829
830                 ipfd_head = fragment_add(tvb, offset, pinfo, msp->first_frame,
831                         ssl_fragment_table,
832                         seq - msp->seq,
833                         len,
834                         (LT_SEQ (nxtseq,msp->nxtpdu)) );
835
836                 if(msp->flags&MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT){
837                         msp->flags&=(~MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT);
838
839                         /* If we consumed the entire segment there is no
840                          * other pdu starting anywhere inside this segment.
841                          * So update nxtpdu to point at least to the start
842                          * of the next segment.
843                          * (If the subdissector asks for even more data we
844                          * will advance nxtpdu even furhter later down in
845                          * the code.)
846                          */
847                         msp->nxtpdu=nxtseq;
848                 }
849
850                 if( (msp->nxtpdu<nxtseq)
851                 &&  (msp->nxtpdu>=seq)
852                 &&  (len>0) ){
853                         another_pdu_follows=msp->nxtpdu-seq;
854                 }
855         } else {
856                 /* This segment was not found in our table, so it doesn't
857                    contain a continuation of a higher-level PDU.
858                    Call the normal subdissector.
859                 */
860                 process_ssl_payload(tvb, offset, pinfo, root_tree, tree,
861                                 association, 0, 0, FALSE, flow);
862                 called_dissector = TRUE;
863
864                 /* Did the subdissector ask us to desegment some more data
865                    before it could handle the packet?
866                    If so we have to create some structures in our table but
867                    this is something we only do the first time we see this
868                    packet.
869                 */
870                 if(pinfo->desegment_len) {
871                         if (!pinfo->fd->flags.visited)
872                                 must_desegment = TRUE;
873
874                         /*
875                          * Set "deseg_offset" to the offset in "tvb"
876                          * of the first byte of data that the
877                          * subdissector didn't process.
878                          */
879                         deseg_offset = offset + pinfo->desegment_offset;
880                 }
881
882                 /* Either no desegmentation is necessary, or this is
883                    segment contains the beginning but not the end of
884                    a higher-level PDU and thus isn't completely
885                    desegmented.
886                 */
887                 ipfd_head = NULL;
888         }
889
890
891         /* is it completely desegmented? */
892         if(ipfd_head){
893                 /*
894                  * Yes, we think it is.
895                  * We only call subdissector for the last segment.
896                  * Note that the last segment may include more than what
897                  * we needed.
898                  */
899                 if(ipfd_head->reassembled_in==pinfo->fd->num){
900                         /*
901                          * OK, this is the last segment.
902                          * Let's call the subdissector with the desegmented
903                          * data.
904                          */
905                         tvbuff_t *next_tvb;
906                         int old_len;
907
908                         /* create a new TVB structure for desegmented data */
909                         next_tvb = tvb_new_real_data(ipfd_head->data,
910                                         ipfd_head->datalen, ipfd_head->datalen);
911
912                         /* add this tvb as a child to the original one */
913                         tvb_set_child_real_data_tvbuff(tvb, next_tvb);
914
915                         /* add desegmented data to the data source list */
916                         add_new_data_source(pinfo, next_tvb, "Reassembled SSL");
917
918                         /* call subdissector */
919                         process_ssl_payload(next_tvb, 0, pinfo, root_tree,
920                             tree, association, 0, 0, FALSE, flow);
921                         called_dissector = TRUE;
922
923                         /*
924                          * OK, did the subdissector think it was completely
925                          * desegmented, or does it think we need even more
926                          * data?
927                          */
928                         old_len=(int)(tvb_reported_length(next_tvb)-tvb_reported_length_remaining(tvb, offset));
929                         if(pinfo->desegment_len &&
930                             pinfo->desegment_offset<=old_len){
931                                 /*
932                                  * "desegment_len" isn't 0, so it needs more
933                                  * data for something - and "desegment_offset"
934                                  * is before "old_len", so it needs more data
935                                  * to dissect the stuff we thought was
936                                  * completely desegmented (as opposed to the
937                                  * stuff at the beginning being completely
938                                  * desegmented, but the stuff at the end
939                                  * being a new higher-level PDU that also
940                                  * needs desegmentation).
941                                  */
942                                 fragment_set_partial_reassembly(pinfo,msp->first_frame,ssl_fragment_table);
943                                 /* Update msp->nxtpdu to point to the new next
944                                  * pdu boundary.
945                                  */
946                                 if(pinfo->desegment_len==DESEGMENT_ONE_MORE_SEGMENT){
947                                         /* We want reassembly of at least one
948                                          * more segment so set the nxtpdu
949                                          * boundary to one byte into the next
950                                          * segment.
951                                          * This means that the next segment
952                                          * will complete reassembly even if it
953                                          * is only one single byte in length.
954                                          */
955                                         msp->nxtpdu=seq+tvb_reported_length_remaining(tvb, offset) + 1;
956                                         msp->flags|=MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
957                                 } else {
958                                         msp->nxtpdu=seq+tvb_reported_length_remaining(tvb, offset) + pinfo->desegment_len;
959                                 }
960                                 /* Since we need at least some more data
961                                  * there can be no pdu following in the
962                                  * tail of this segment.
963                                  */
964                                 another_pdu_follows=0;
965                         } else {
966                                 /*
967                                  * Show the stuff in this TCP segment as
968                                  * just raw TCP segment data.
969                                  */
970                                 nbytes =
971                                     tvb_reported_length_remaining(tvb, offset);
972                                 proto_tree_add_text(tree, tvb, offset, -1,
973                                     "SSL segment data (%u byte%s)", nbytes,
974                                     plurality(nbytes, "", "s"));
975
976                                 /*
977                                  * The subdissector thought it was completely
978                                  * desegmented (although the stuff at the
979                                  * end may, in turn, require desegmentation),
980                                  * so we show a tree with all segments.
981                                  */
982                                 show_fragment_tree(ipfd_head, &ssl_segment_items,
983                                         root_tree, pinfo, next_tvb, &frag_tree_item);
984                                 /*
985                                  * The toplevel fragment subtree is now
986                                  * behind all desegmented data; move it
987                                  * right behind the TCP tree.
988                                  */
989                                 ssl_tree_item = proto_tree_get_parent(tree);
990                                 if(frag_tree_item && ssl_tree_item) {
991                                         proto_tree_move_item(root_tree, ssl_tree_item, frag_tree_item);
992                                 }
993
994                                 /* Did the subdissector ask us to desegment
995                                    some more data?  This means that the data
996                                    at the beginning of this segment completed
997                                    a higher-level PDU, but the data at the
998                                    end of this segment started a higher-level
999                                    PDU but didn't complete it.
1000
1001                                    If so, we have to create some structures
1002                                    in our table, but this is something we
1003                                    only do the first time we see this packet.
1004                                 */
1005                                 if(pinfo->desegment_len) {
1006                                         if (!pinfo->fd->flags.visited)
1007                                                 must_desegment = TRUE;
1008
1009                                         /* The stuff we couldn't dissect
1010                                            must have come from this segment,
1011                                            so it's all in "tvb".
1012
1013                                            "pinfo->desegment_offset" is
1014                                            relative to the beginning of
1015                                            "next_tvb"; we want an offset
1016                                            relative to the beginning of "tvb".
1017
1018                                            First, compute the offset relative
1019                                            to the *end* of "next_tvb" - i.e.,
1020                                            the number of bytes before the end
1021                                            of "next_tvb" at which the
1022                                            subdissector stopped.  That's the
1023                                            length of "next_tvb" minus the
1024                                            offset, relative to the beginning
1025                                            of "next_tvb, at which the
1026                                            subdissector stopped.
1027                                         */
1028                                         deseg_offset =
1029                                             ipfd_head->datalen - pinfo->desegment_offset;
1030
1031                                         /* "tvb" and "next_tvb" end at the
1032                                            same byte of data, so the offset
1033                                            relative to the end of "next_tvb"
1034                                            of the byte at which we stopped
1035                                            is also the offset relative to
1036                                            the end of "tvb" of the byte at
1037                                            which we stopped.
1038
1039                                            Convert that back into an offset
1040                                            relative to the beginninng of
1041                                            "tvb", by taking the length of
1042                                            "tvb" and subtracting the offset
1043                                            relative to the end.
1044                                         */
1045                                         deseg_offset=tvb_reported_length(tvb) - deseg_offset;
1046                                 }
1047                         }
1048                 }
1049         }
1050
1051         if (must_desegment) {
1052             /* If the dissector requested "reassemble until FIN"
1053              * just set this flag for the flow and let reassembly
1054              * proceed at normal.  We will check/pick up these
1055              * reassembled PDUs later down in dissect_tcp() when checking
1056              * for the FIN flag.
1057              */
1058             if(pinfo->desegment_len==DESEGMENT_UNTIL_FIN){
1059                   flow->flags|=TCP_FLOW_REASSEMBLE_UNTIL_FIN;
1060             }
1061             /*
1062              * The sequence number at which the stuff to be desegmented
1063              * starts is the sequence number of the byte at an offset
1064              * of "deseg_offset" into "tvb".
1065              *
1066              * The sequence number of the byte at an offset of "offset"
1067              * is "seq", i.e. the starting sequence number of this
1068              * segment, so the sequence number of the byte at
1069              * "deseg_offset" is "seq + (deseg_offset - offset)".
1070              */
1071             deseg_seq = seq + (deseg_offset - offset);
1072
1073             if( ((nxtseq - deseg_seq) <= 1024*1024)
1074             &&  (!pinfo->fd->flags.visited) ){
1075                 if(pinfo->desegment_len==DESEGMENT_ONE_MORE_SEGMENT){
1076                         /* The subdissector asked to reassemble using the
1077                          * entire next segment.
1078                          * Just ask reassembly for one more byte
1079                          * but set this msp flag so we can pick it up
1080                          * above.
1081                          */
1082                         msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
1083                                 deseg_seq, nxtseq+1, flow->multisegment_pdus);
1084                         msp->flags|=MSP_FLAGS_REASSEMBLE_ENTIRE_SEGMENT;
1085                 } else {
1086                         msp = pdu_store_sequencenumber_of_next_pdu(pinfo,
1087                                 deseg_seq, nxtseq+pinfo->desegment_len, flow->multisegment_pdus);
1088                 }
1089
1090                 /* add this segment as the first one for this new pdu */
1091                 fragment_add(tvb, deseg_offset, pinfo, msp->first_frame,
1092                         ssl_fragment_table,
1093                         0,
1094                         nxtseq - deseg_seq,
1095                         LT_SEQ(nxtseq, msp->nxtpdu));
1096                 }
1097         }
1098
1099         if (!called_dissector || pinfo->desegment_len != 0) {
1100                 if (ipfd_head != NULL && ipfd_head->reassembled_in != 0 &&
1101                     !(ipfd_head->flags & FD_PARTIAL_REASSEMBLY)) {
1102                         /*
1103                          * We know what frame this PDU is reassembled in;
1104                          * let the user know.
1105                          */
1106                         item=proto_tree_add_uint(tree, *ssl_segment_items.hf_reassembled_in,
1107                             tvb, 0, 0, ipfd_head->reassembled_in);
1108                         PROTO_ITEM_SET_GENERATED(item);
1109                 }
1110
1111                 /*
1112                  * Either we didn't call the subdissector at all (i.e.,
1113                  * this is a segment that contains the middle of a
1114                  * higher-level PDU, but contains neither the beginning
1115                  * nor the end), or the subdissector couldn't dissect it
1116                  * all, as some data was missing (i.e., it set
1117                  * "pinfo->desegment_len" to the amount of additional
1118                  * data it needs).
1119                  */
1120                 if (pinfo->desegment_offset == 0) {
1121                         /*
1122                          * It couldn't, in fact, dissect any of it (the
1123                          * first byte it couldn't dissect is at an offset
1124                          * of "pinfo->desegment_offset" from the beginning
1125                          * of the payload, and that's 0).
1126                          * Just mark this as SSL.
1127                          */
1128                         if (check_col(pinfo->cinfo, COL_PROTOCOL)){
1129                                 col_set_str(pinfo->cinfo, COL_PROTOCOL, "SSL");
1130                         }
1131                         if (check_col(pinfo->cinfo, COL_INFO)){
1132                                 col_set_str(pinfo->cinfo, COL_INFO, "[SSL segment of a reassembled PDU]");
1133                         }
1134                 }
1135
1136                 /*
1137                  * Show what's left in the packet as just raw TCP segment
1138                  * data.
1139                  * XXX - remember what protocol the last subdissector
1140                  * was, and report it as a continuation of that, instead?
1141                  */
1142                 nbytes = tvb_reported_length_remaining(tvb, deseg_offset);
1143                 proto_tree_add_text(tree, tvb, deseg_offset, -1,
1144                     "SSL segment data (%u byte%s)", nbytes,
1145                     plurality(nbytes, "", "s"));
1146         }
1147         pinfo->can_desegment=0;
1148         pinfo->desegment_offset = 0;
1149         pinfo->desegment_len = 0;
1150
1151         if(another_pdu_follows){
1152                 /* there was another pdu following this one. */
1153                 pinfo->can_desegment=2;
1154                 /* we also have to prevent the dissector from changing the
1155                  * PROTOCOL and INFO colums since what follows may be an
1156                  * incomplete PDU and we dont want it be changed back from
1157                  *  <Protocol>   to <TCP>
1158                  * XXX There is no good way to block the PROTOCOL column
1159                  * from being changed yet so we set the entire row unwritable.
1160                  */
1161                 col_set_fence(pinfo->cinfo, COL_INFO);
1162                 col_set_writable(pinfo->cinfo, FALSE);
1163                 offset += another_pdu_follows;
1164                 seq += another_pdu_follows;
1165                 goto again;
1166         }
1167 }
1168
1169 static void
1170 process_ssl_payload(tvbuff_t *tvb, volatile int offset, packet_info *pinfo,
1171         proto_tree *root_tree _U_ , proto_tree *tree, SslAssociation* association,
1172         guint32 seq _U_, guint32 nxtseq _U_, gboolean is_ssl_segment _U_,
1173         SslFlow *flow _U_)
1174 {
1175   tvbuff_t *next_tvb;
1176
1177   next_tvb = tvb_new_subset(tvb, offset, -1, -1);
1178
1179   if (association && association->handle) {
1180     ssl_debug_printf("dissect_ssl3_record found association %p\n", association);
1181     call_dissector(association->handle, next_tvb, pinfo, proto_tree_get_root(tree));
1182   }
1183 }
1184
1185 void
1186 dissect_ssl_payload(tvbuff_t *tvb, packet_info *pinfo, int offset, proto_tree *tree, SslAssociation* association)
1187 {
1188   gboolean save_fragmented;
1189   SslDataInfo *appl_data;
1190   tvbuff_t *next_tvb;
1191
1192   /* show decrypted data info, if available */
1193   appl_data = ssl_get_data_info(proto_ssl, pinfo, TVB_RAW_OFFSET(tvb)+offset);
1194   if (!appl_data || !appl_data->plain_data.data_len) return;
1195
1196   /* try to dissect decrypted data*/
1197   ssl_debug_printf("dissect_ssl3_record decrypted len %d\n", appl_data->plain_data.data_len);
1198   ssl_print_text_data("decrypted app data fragment", appl_data->plain_data.data, appl_data->plain_data.data_len);
1199
1200   /* create a new TVB structure for desegmented data */
1201   next_tvb = tvb_new_real_data(appl_data->plain_data.data, appl_data->plain_data.data_len, appl_data->plain_data.data_len);
1202
1203   /* add this tvb as a child to the original one */
1204   tvb_set_child_real_data_tvbuff(tvb, next_tvb);
1205
1206   /* add desegmented data to the data source list */
1207   add_new_data_source(pinfo, next_tvb, "Decrypted SSL data");
1208
1209   /* Can we desegment this segment? */
1210   if (ssl_desegment_app_data) {
1211     /* Yes. */
1212     pinfo->can_desegment = 2;
1213     desegment_ssl(next_tvb, pinfo, 0, appl_data->seq, appl_data->nxtseq, association, proto_tree_get_root(tree), tree, appl_data->flow);
1214   } else if (association && association->handle) {
1215     /* No - just call the subdissector.
1216        Mark this as fragmented, so if somebody throws an exception,
1217        we don't report it as a malformed frame. */
1218     pinfo->can_desegment = 0;
1219     save_fragmented = pinfo->fragmented;
1220     pinfo->fragmented = TRUE;
1221     process_ssl_payload(next_tvb, 0, pinfo,     proto_tree_get_root(tree), tree, association, appl_data->seq, appl_data->nxtseq, TRUE, appl_data->flow);
1222     pinfo->fragmented = save_fragmented;
1223   }
1224 }
1225
1226
1227 /*********************************************************************
1228  *
1229  * SSL version 3 and TLS Dissection Routines
1230  *
1231  *********************************************************************/
1232 static gint
1233 dissect_ssl3_record(tvbuff_t *tvb, packet_info *pinfo,
1234                     proto_tree *tree, guint32 offset,
1235                     guint *conv_version, gboolean *need_desegmentation,
1236                     SslDecryptSession* ssl, gboolean first_record_in_frame _U_)
1237 {
1238
1239     /*
1240      *    struct {
1241      *        uint8 major, minor;
1242      *    } ProtocolVersion;
1243      *
1244      *
1245      *    enum {
1246      *        change_cipher_spec(20), alert(21), handshake(22),
1247      *        application_data(23), (255)
1248      *    } ContentType;
1249      *
1250      *    struct {
1251      *        ContentType type;
1252      *        ProtocolVersion version;
1253      *        uint16 length;
1254      *        opaque fragment[TLSPlaintext.length];
1255      *    } TLSPlaintext;
1256      */
1257     guint32 record_length;
1258     guint16 version;
1259     guint8 content_type;
1260     guint8 next_byte;
1261     proto_tree *ti;
1262     proto_tree *ssl_record_tree;
1263     SslAssociation* association;
1264     guint32 available_bytes;
1265     ti = NULL;
1266     ssl_record_tree = NULL;
1267     available_bytes = 0;
1268
1269     available_bytes = tvb_length_remaining(tvb, offset);
1270
1271     /* TLS 1.0/1.1 just ignores unknown records - RFC 2246 chapter 6. The TLS Record Protocol */
1272     if ((*conv_version==SSL_VER_TLS || *conv_version==SSL_VER_TLSv1DOT1) &&
1273         (available_bytes >=1 ) && !ssl_is_valid_content_type(tvb_get_guint8(tvb, offset))) {
1274       proto_tree_add_text(tree, tvb, offset, available_bytes, "Ignored Unknown Record");
1275       if (check_col(pinfo->cinfo, COL_INFO))
1276           col_append_str(pinfo->cinfo, COL_INFO, "Ignored Unknown Record");
1277       if (check_col(pinfo->cinfo, COL_PROTOCOL))
1278         col_set_str(pinfo->cinfo, COL_PROTOCOL, ssl_version_short_names[*conv_version]);
1279       return offset + available_bytes;
1280     }
1281
1282    /*
1283      * Can we do reassembly?
1284      */
1285     if (ssl_desegment && pinfo->can_desegment) {
1286         /*
1287          * Yes - is the record header split across segment boundaries?
1288          */
1289         if (available_bytes < 5) {
1290             /*
1291              * Yes.  Tell the TCP dissector where the data for this
1292              * message starts in the data it handed us, and how many
1293              * more bytes we need, and return.
1294              */
1295             pinfo->desegment_offset = offset;
1296             pinfo->desegment_len = 5 - available_bytes;
1297             *need_desegmentation = TRUE;
1298             return offset;
1299         }
1300     }
1301
1302     /*
1303      * Get the record layer fields of interest
1304      */
1305     content_type  = tvb_get_guint8(tvb, offset);
1306     version       = tvb_get_ntohs(tvb, offset + 1);
1307     record_length = tvb_get_ntohs(tvb, offset + 3);
1308
1309     if (ssl_is_valid_content_type(content_type)) {
1310
1311         /*
1312          * Can we do reassembly?
1313          */
1314         if (ssl_desegment && pinfo->can_desegment) {
1315             /*
1316              * Yes - is the record split across segment boundaries?
1317              */
1318             if (available_bytes < record_length + 5) {
1319                 /*
1320                  * Yes.  Tell the TCP dissector where the data for this
1321                  * message starts in the data it handed us, and how many
1322                  * more bytes we need, and return.
1323                  */
1324                 pinfo->desegment_offset = offset;
1325                 pinfo->desegment_len = (record_length + 5) - available_bytes;
1326                 *need_desegmentation = TRUE;
1327                 return offset;
1328             }
1329         }
1330
1331     } else {
1332
1333     /* if we don't have a valid content_type, there's no sense
1334      * continuing any further
1335      */
1336         if (check_col(pinfo->cinfo, COL_INFO))
1337             col_append_str(pinfo->cinfo, COL_INFO, "Continuation Data");
1338
1339         /* Set the protocol column */
1340         if (check_col(pinfo->cinfo, COL_PROTOCOL))
1341         {
1342             col_set_str(pinfo->cinfo, COL_PROTOCOL,
1343                         ssl_version_short_names[*conv_version]);
1344         }
1345         return offset + 5 + record_length;
1346     }
1347
1348     /*
1349      * If GUI, fill in record layer part of tree
1350      */
1351     if (tree)
1352     {
1353
1354         /* add the record layer subtree header */
1355         tvb_ensure_bytes_exist(tvb, offset, 5 + record_length);
1356         ti = proto_tree_add_item(tree, hf_ssl_record, tvb,
1357                                  offset, 5 + record_length, 0);
1358         ssl_record_tree = proto_item_add_subtree(ti, ett_ssl_record);
1359     }
1360     if (ssl_record_tree)
1361     {
1362
1363         /* show the one-byte content type */
1364         proto_tree_add_item(ssl_record_tree, hf_ssl_record_content_type,
1365                             tvb, offset, 1, 0);
1366         offset++;
1367
1368         /* add the version */
1369         proto_tree_add_item(ssl_record_tree, hf_ssl_record_version, tvb,
1370                             offset, 2, FALSE);
1371         offset += 2;
1372
1373         /* add the length */
1374         proto_tree_add_uint(ssl_record_tree, hf_ssl_record_length, tvb,
1375                             offset, 2, record_length);
1376         offset += 2;    /* move past length field itself */
1377     }
1378     else
1379     {
1380         /* if no GUI tree, then just skip over those fields */
1381         offset += 5;
1382     }
1383
1384
1385     /*
1386      * if we don't already have a version set for this conversation,
1387      * but this message's version is authoritative (i.e., it's
1388      * not client_hello, then save the version to to conversation
1389      * structure and print the column version
1390      */
1391     next_byte = tvb_get_guint8(tvb, offset);
1392     if (*conv_version == SSL_VER_UNKNOWN
1393         && ssl_is_authoritative_version_message(content_type, next_byte))
1394     {
1395         if (version == SSLV3_VERSION)
1396         {
1397             *conv_version = SSL_VER_SSLv3;
1398             if (ssl) {
1399                 ssl->version_netorder = version;
1400                 ssl->state |= SSL_VERSION;
1401                 ssl_debug_printf("dissect_ssl3_record found version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
1402             }
1403             /*ssl_set_conv_version(pinfo, ssl->version);*/
1404         }
1405         else if (version == TLSV1_VERSION)
1406         {
1407
1408             *conv_version = SSL_VER_TLS;
1409             if (ssl) {
1410                 ssl->version_netorder = version;
1411                 ssl->state |= SSL_VERSION;
1412                 ssl_debug_printf("dissect_ssl3_record found version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
1413             }
1414             /*ssl_set_conv_version(pinfo, ssl->version);*/
1415         }
1416         else if (version == TLSV1DOT1_VERSION)
1417         {
1418
1419             *conv_version = SSL_VER_TLSv1DOT1;
1420             if (ssl) {
1421                 ssl->version_netorder = version;
1422                 ssl->state |= SSL_VERSION;
1423                 ssl_debug_printf("dissect_ssl3_record found version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
1424             }
1425             /*ssl_set_conv_version(pinfo, ssl->version);*/
1426         }
1427     }
1428     if (check_col(pinfo->cinfo, COL_PROTOCOL))
1429     {
1430             col_set_str(pinfo->cinfo, COL_PROTOCOL,
1431                         ssl_version_short_names[*conv_version]);
1432     }
1433
1434     /*
1435      * now dissect the next layer
1436      */
1437     ssl_debug_printf("dissect_ssl3_record: content_type %d\n",content_type);
1438
1439     /* PAOLO try to decrypt each record (we must keep ciphers "in sync")
1440      * store plain text only for app data */
1441
1442     switch (content_type) {
1443     case SSL_ID_CHG_CIPHER_SPEC:
1444         ssl_debug_printf("dissect_ssl3_change_cipher_spec\n");
1445         if (check_col(pinfo->cinfo, COL_INFO))
1446             col_append_str(pinfo->cinfo, COL_INFO, "Change Cipher Spec");
1447         dissect_ssl3_change_cipher_spec(tvb, ssl_record_tree,
1448                                         offset, conv_version, content_type);
1449         if (ssl) ssl_change_cipher(ssl, ssl_packet_from_server(ssl_associations, pinfo->srcport, pinfo->ptype == PT_TCP));
1450         break;
1451     case SSL_ID_ALERT:
1452       {
1453         tvbuff_t* decrypted;
1454         decrypted=0;
1455         if (ssl&&decrypt_ssl3_record(tvb, pinfo, offset,
1456                 record_length, content_type, ssl, FALSE))
1457           ssl_add_record_info(proto_ssl, pinfo, ssl_decrypted_data.data,
1458                               ssl_decrypted_data_avail, offset);
1459
1460         /* try to retrive and use decrypted alert record, if any. */
1461         decrypted = ssl_get_record_info(proto_ssl, pinfo, offset);
1462         if (decrypted)
1463           dissect_ssl3_alert(decrypted, pinfo, ssl_record_tree, 0,
1464                              conv_version);
1465         else
1466           dissect_ssl3_alert(tvb, pinfo, ssl_record_tree, offset,
1467                              conv_version);
1468         break;
1469       }
1470     case SSL_ID_HANDSHAKE:
1471     {
1472         tvbuff_t* decrypted;
1473         decrypted=0;
1474         /* try to decrypt handshake record, if possible. Store decrypted
1475          * record for later usage. The offset is used as 'key' to itentify
1476          * this record into the packet (we can have multiple handshake records
1477          * in the same frame) */
1478         if (ssl && decrypt_ssl3_record(tvb, pinfo, offset,
1479                 record_length, content_type, ssl, FALSE))
1480             ssl_add_record_info(proto_ssl, pinfo, ssl_decrypted_data.data,
1481                 ssl_decrypted_data_avail, offset);
1482
1483         /* try to retrive and use decrypted handshake record, if any. */
1484         decrypted = ssl_get_record_info(proto_ssl, pinfo, offset);
1485         if (decrypted) {
1486                     /* add desegmented data to the data source list */
1487                     add_new_data_source(pinfo, decrypted, "Decrypted SSL record");
1488             dissect_ssl3_handshake(decrypted, pinfo, ssl_record_tree, 0,
1489                  decrypted->length, conv_version, ssl, content_type);
1490                 } else {
1491             dissect_ssl3_handshake(tvb, pinfo, ssl_record_tree, offset,
1492                                record_length, conv_version, ssl, content_type);
1493                 }
1494         break;
1495     }
1496     case SSL_ID_APP_DATA:
1497         if (ssl){
1498             decrypt_ssl3_record(tvb, pinfo, offset,
1499                             record_length, content_type, ssl, TRUE);
1500             /* if application data desegmentation is allowed and needed */
1501             /*if(ssl_desegment_app_data && *need_desegmentation)
1502                 ssl_desegment_ssl_app_data(ssl,pinfo);
1503         */
1504         }
1505
1506         /* show on info colum what we are decoding */
1507         if (check_col(pinfo->cinfo, COL_INFO))
1508             col_append_str(pinfo->cinfo, COL_INFO, "Application Data");
1509
1510         /* we need dissector information when the selected packet is shown.
1511          * ssl session pointer is NULL at that time, so we can't access
1512          * info cached there*/
1513         association = ssl_association_find(ssl_associations, pinfo->srcport, pinfo->ptype == PT_TCP);
1514         association = association ? association: ssl_association_find(ssl_associations, pinfo->destport, pinfo->ptype == PT_TCP);
1515
1516         proto_item_set_text(ssl_record_tree,
1517            "%s Record Layer: %s Protocol: %s",
1518             ssl_version_short_names[*conv_version],
1519             val_to_str(content_type, ssl_31_content_type, "unknown"),
1520             association?association->info:"Application Data");
1521
1522         proto_tree_add_item(ssl_record_tree, hf_ssl_record_appdata, tvb,
1523                        offset, record_length, 0);
1524
1525                 dissect_ssl_payload(tvb, pinfo, offset, tree, association);
1526
1527         break;
1528
1529     default:
1530         /* shouldn't get here since we check above for valid types */
1531         if (check_col(pinfo->cinfo, COL_INFO))
1532             col_append_str(pinfo->cinfo, COL_INFO, "Bad SSLv3 Content Type");
1533         break;
1534     }
1535     offset += record_length; /* skip to end of record */
1536
1537     return offset;
1538 }
1539
1540 /* dissects the change cipher spec procotol, filling in the tree */
1541 static void
1542 dissect_ssl3_change_cipher_spec(tvbuff_t *tvb,
1543                                 proto_tree *tree, guint32 offset,
1544                                 guint* conv_version, guint8 content_type)
1545 {
1546     /*
1547      * struct {
1548      *     enum { change_cipher_spec(1), (255) } type;
1549      * } ChangeCipherSpec;
1550      *
1551      */
1552     if (tree)
1553     {
1554         proto_item_set_text(tree,
1555                             "%s Record Layer: %s Protocol: Change Cipher Spec",
1556                             ssl_version_short_names[*conv_version],
1557                             val_to_str(content_type, ssl_31_content_type, "unknown"));
1558         proto_tree_add_item(tree, hf_ssl_change_cipher_spec, tvb,
1559                             offset++, 1, FALSE);
1560     }
1561 }
1562
1563 /* dissects the alert message, filling in the tree */
1564 static void
1565 dissect_ssl3_alert(tvbuff_t *tvb, packet_info *pinfo,
1566                    proto_tree *tree, guint32 offset,
1567                    guint* conv_version)
1568 {
1569     /*     struct {
1570      *         AlertLevel level;
1571      *         AlertDescription description;
1572      *     } Alert;
1573      */
1574     proto_tree *ti;
1575     proto_tree *ssl_alert_tree;
1576     const gchar *level;
1577     const gchar *desc;
1578     guint8 byte;
1579     ssl_alert_tree = NULL;
1580     if (tree)
1581     {
1582         ti = proto_tree_add_item(tree, hf_ssl_alert_message, tvb,
1583                                  offset, 2, 0);
1584         ssl_alert_tree = proto_item_add_subtree(ti, ett_ssl_alert);
1585     }
1586
1587     /*
1588      * set the record layer label
1589      */
1590
1591     /* first lookup the names for the alert level and description */
1592     byte = tvb_get_guint8(tvb, offset); /* grab the level byte */
1593     level = match_strval(byte, ssl_31_alert_level);
1594
1595     byte = tvb_get_guint8(tvb, offset+1); /* grab the desc byte */
1596     desc = match_strval(byte, ssl_31_alert_description);
1597
1598     /* now set the text in the record layer line */
1599     if (level && desc)
1600     {
1601         if (check_col(pinfo->cinfo, COL_INFO))
1602             col_append_fstr(pinfo->cinfo, COL_INFO,
1603                             "Alert (Level: %s, Description: %s)",
1604                             level, desc);
1605     }
1606     else
1607     {
1608         if (check_col(pinfo->cinfo, COL_INFO))
1609             col_append_str(pinfo->cinfo, COL_INFO, "Encrypted Alert");
1610     }
1611
1612     if (tree)
1613     {
1614         if (level && desc)
1615         {
1616             proto_item_set_text(tree, "%s Record Layer: Alert "
1617                                 "(Level: %s, Description: %s)",
1618                                 ssl_version_short_names[*conv_version],
1619                                 level, desc);
1620             proto_tree_add_item(ssl_alert_tree, hf_ssl_alert_message_level,
1621                                 tvb, offset++, 1, FALSE);
1622
1623             proto_tree_add_item(ssl_alert_tree, hf_ssl_alert_message_description,
1624                                 tvb, offset++, 1, FALSE);
1625         }
1626         else
1627         {
1628             proto_item_set_text(tree,
1629                                 "%s Record Layer: Encrypted Alert",
1630                                 ssl_version_short_names[*conv_version]);
1631             proto_item_set_text(ssl_alert_tree,
1632                                 "Alert Message: Encrypted Alert");
1633         }
1634     }
1635 }
1636
1637
1638 /* dissects the handshake protocol, filling the tree */
1639 static void
1640 dissect_ssl3_handshake(tvbuff_t *tvb, packet_info *pinfo,
1641                        proto_tree *tree, guint32 offset,
1642                        guint32 record_length, guint *conv_version,
1643                        SslDecryptSession* ssl, guint8 content_type)
1644 {
1645     /*     struct {
1646      *         HandshakeType msg_type;
1647      *         uint24 length;
1648      *         select (HandshakeType) {
1649      *             case hello_request:       HelloRequest;
1650      *             case client_hello:        ClientHello;
1651      *             case server_hello:        ServerHello;
1652      *             case certificate:         Certificate;
1653      *             case server_key_exchange: ServerKeyExchange;
1654      *             case certificate_request: CertificateRequest;
1655      *             case server_hello_done:   ServerHelloDone;
1656      *             case certificate_verify:  CertificateVerify;
1657      *             case client_key_exchange: ClientKeyExchange;
1658      *             case finished:            Finished;
1659      *         } body;
1660      *     } Handshake;
1661      */
1662     proto_tree *ti;
1663     proto_tree *ssl_hand_tree;
1664     const gchar *msg_type_str;
1665     guint8 msg_type;
1666     guint32 length;
1667     gboolean first_iteration;
1668     ti = NULL;
1669     ssl_hand_tree = NULL;
1670     msg_type_str = NULL;
1671     first_iteration = TRUE;
1672
1673     /* just as there can be multiple records per packet, there
1674      * can be multiple messages per record as long as they have
1675      * the same content type
1676      *
1677      * we really only care about this for handshake messages
1678      */
1679
1680     /* set record_length to the max offset */
1681     record_length += offset;
1682     while (offset < record_length)
1683     {
1684         msg_type = tvb_get_guint8(tvb, offset);
1685         length   = tvb_get_ntoh24(tvb, offset + 1);
1686
1687         /* Check the length in the handshake message. Assume it's an
1688          * encrypted handshake message if the message would pass
1689          * the record_length boundary. This is a workaround for the
1690          * situation where the first octet of the encrypted handshake
1691          * message is actually a known handshake message type.
1692          */
1693         if ( offset + length <= record_length )
1694            msg_type_str = match_strval(msg_type, ssl_31_handshake_type);
1695         else
1696            msg_type_str = NULL;
1697
1698         ssl_debug_printf("dissect_ssl3_handshake iteration %d type %d offset %d length %d "
1699             "bytes, remaining %d \n", first_iteration, msg_type, offset, length, record_length);
1700         if (!msg_type_str && !first_iteration)
1701         {
1702             /* only dissect / report messages if they're
1703              * either the first message in this record
1704              * or they're a valid message type
1705              */
1706             return;
1707         }
1708
1709         /* on second and later iterations, add comma to info col */
1710         if (!first_iteration)
1711         {
1712             if (check_col(pinfo->cinfo, COL_INFO))
1713                 col_append_fstr(pinfo->cinfo, COL_INFO, ", ");
1714         }
1715
1716         /*
1717          * Update our info string
1718          */
1719         if (check_col(pinfo->cinfo, COL_INFO))
1720             col_append_fstr(pinfo->cinfo, COL_INFO, "%s", (msg_type_str != NULL)
1721                             ? msg_type_str : "Encrypted Handshake Message");
1722
1723         if (tree)
1724         {
1725             /* set the label text on the record layer expanding node */
1726             if (first_iteration)
1727             {
1728                 proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s",
1729                                     ssl_version_short_names[*conv_version],
1730                                     val_to_str(content_type, ssl_31_content_type, "unknown"),
1731                                     (msg_type_str!=NULL) ? msg_type_str :
1732                                         "Encrypted Handshake Message");
1733             }
1734             else
1735             {
1736                 proto_item_set_text(tree, "%s Record Layer: %s Protocol: %s",
1737                                     ssl_version_short_names[*conv_version],
1738                                     val_to_str(content_type, ssl_31_content_type, "unknown"),
1739                                     "Multiple Handshake Messages");
1740             }
1741
1742             /* add a subtree for the handshake protocol */
1743             ti = proto_tree_add_item(tree, hf_ssl_handshake_protocol, tvb,
1744                                      offset, length + 4, 0);
1745             ssl_hand_tree = proto_item_add_subtree(ti, ett_ssl_handshake);
1746
1747             if (ssl_hand_tree)
1748             {
1749                 /* set the text label on the subtree node */
1750                 proto_item_set_text(ssl_hand_tree, "Handshake Protocol: %s",
1751                                     (msg_type_str != NULL) ? msg_type_str :
1752                                     "Encrypted Handshake Message");
1753             }
1754         }
1755
1756         /* if we don't have a valid handshake type, just quit dissecting */
1757         if (!msg_type_str)
1758             return;
1759
1760         /* PAOLO: if we are doing ssl decryption we must dissect some requests type */
1761         if (ssl_hand_tree || ssl)
1762         {
1763             /* add nodes for the message type and message length */
1764             if (ssl_hand_tree)
1765                 proto_tree_add_item(ssl_hand_tree, hf_ssl_handshake_type,
1766                                     tvb, offset, 1, msg_type);
1767             offset++;
1768             if (ssl_hand_tree)
1769                 proto_tree_add_uint(ssl_hand_tree, hf_ssl_handshake_length,
1770                                 tvb, offset, 3, length);
1771             offset += 3;
1772
1773             /* now dissect the handshake message, if necessary */
1774             switch (msg_type) {
1775             case SSL_HND_HELLO_REQUEST:
1776                 /* hello_request has no fields, so nothing to do! */
1777                 break;
1778
1779             case SSL_HND_CLIENT_HELLO:
1780                 dissect_ssl3_hnd_cli_hello(tvb, ssl_hand_tree, offset, length, ssl);
1781             break;
1782
1783             case SSL_HND_SERVER_HELLO:
1784                 dissect_ssl3_hnd_srv_hello(tvb, ssl_hand_tree, offset, length, ssl);
1785                 break;
1786
1787             case SSL_HND_CERTIFICATE:
1788                 dissect_ssl3_hnd_cert(tvb, ssl_hand_tree, offset, pinfo);
1789                 break;
1790
1791             case SSL_HND_SERVER_KEY_EXCHG:
1792                 /* unimplemented */
1793                 break;
1794
1795             case SSL_HND_CERT_REQUEST:
1796                 dissect_ssl3_hnd_cert_req(tvb, ssl_hand_tree, offset);
1797                 break;
1798
1799             case SSL_HND_SVR_HELLO_DONE:
1800                 /* server_hello_done has no fields, so nothing to do! */
1801                 break;
1802
1803             case SSL_HND_CERT_VERIFY:
1804                 /* unimplemented */
1805                 break;
1806
1807             case SSL_HND_CLIENT_KEY_EXCHG:
1808                 {
1809                     /* PAOLO: here we can have all the data to build session key*/
1810                     StringInfo encrypted_pre_master;
1811                     gint ret;
1812                     guint encrlen, skip;
1813                     encrlen = length;
1814                     skip = 0;
1815
1816                     if (!ssl)
1817                         break;
1818
1819                     /* check for required session data */
1820                     ssl_debug_printf("dissect_ssl3_handshake found SSL_HND_CLIENT_KEY_EXCHG state 0x%X\n",
1821                         ssl->state);
1822                     if ((ssl->state & (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) !=
1823                             (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) {
1824                         ssl_debug_printf("dissect_ssl3_handshake not enough data to generate key (required 0x%02X)\n",
1825                             (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION));
1826                         break;
1827                     }
1828
1829                     /* get encrypted data, on tls1 we have to skip two bytes
1830                      * (it's the encrypted len and should be equal to record len - 2)
1831                      */
1832                     if (ssl->version == SSL_VER_TLS||ssl->version == SSL_VER_TLSv1DOT1)
1833                     {
1834                         encrlen  = tvb_get_ntohs(tvb, offset);
1835                         skip = 2;
1836                         if (encrlen > length - 2)
1837                         {
1838                             ssl_debug_printf("dissect_ssl3_handshake wrong encrypted length (%d max %d)\n",
1839                                 encrlen, length);
1840                             break;
1841                         }
1842                     }
1843                     encrypted_pre_master.data = se_alloc(encrlen);
1844                     encrypted_pre_master.data_len = encrlen;
1845                     tvb_memcpy(tvb, encrypted_pre_master.data, offset+skip, encrlen);
1846
1847                     if (!ssl->private_key) {
1848                         ssl_debug_printf("dissect_ssl3_handshake can't find private key\n");
1849                         break;
1850                     }
1851
1852                     /* go with ssl key processessing; encrypted_pre_master
1853                      * will be used for master secret store*/
1854                     ret = ssl_decrypt_pre_master_secret(ssl, &encrypted_pre_master, ssl->private_key);
1855                     if (ret < 0) {
1856                         ssl_debug_printf("dissect_ssl3_handshake can't decrypt pre master secret\n");
1857                         break;
1858                     }
1859                     if (ssl_generate_keyring_material(ssl)<0) {
1860                         ssl_debug_printf("dissect_ssl3_handshake can't generate keyring material\n");
1861                         break;
1862                     }
1863                     ssl->state |= SSL_HAVE_SESSION_KEY;
1864                     ssl_save_session(ssl, ssl_session_hash);
1865                     ssl_debug_printf("dissect_ssl3_handshake session keys succesfully generated\n");
1866                 }
1867                 break;
1868
1869             case SSL_HND_FINISHED:
1870                 dissect_ssl3_hnd_finished(tvb, ssl_hand_tree,
1871                                           offset, conv_version);
1872                 break;
1873             }
1874
1875         }
1876         else
1877             offset += 4;        /* skip the handshake header when handshake is not processed*/
1878
1879         offset += length;
1880         first_iteration = FALSE; /* set up for next pass, if any */
1881     }
1882 }
1883
1884 static gint
1885 dissect_ssl3_hnd_hello_common(tvbuff_t *tvb, proto_tree *tree,
1886                               guint32 offset, SslDecryptSession* ssl, gint from_server)
1887 {
1888     /* show the client's random challenge */
1889     nstime_t gmt_unix_time;
1890     guint8  session_id_length;
1891         proto_item *ti_rnd;
1892         proto_tree *ssl_rnd_tree;
1893
1894     session_id_length = 0;
1895
1896     if (ssl)
1897     {
1898         /* PAOLO: get proper peer information*/
1899         StringInfo* rnd;
1900         if (from_server)
1901             rnd = &ssl->server_random;
1902         else
1903             rnd = &ssl->client_random;
1904
1905         /* get provided random for keyring generation*/
1906         tvb_memcpy(tvb, rnd->data, offset, 32);
1907         rnd->data_len = 32;
1908         if (from_server)
1909             ssl->state |= SSL_SERVER_RANDOM;
1910         else
1911             ssl->state |= SSL_CLIENT_RANDOM;
1912         ssl_debug_printf("dissect_ssl3_hnd_hello_common found %s RANDOM -> state 0x%02X\n",
1913             (from_server)?"SERVER":"CLIENT", ssl->state);
1914
1915         session_id_length = tvb_get_guint8(tvb, offset + 32);
1916         /* check stored session id info */
1917         if (from_server && (session_id_length == ssl->session_id.data_len) &&
1918                  (tvb_memeql(tvb, offset+33, ssl->session_id.data, session_id_length) == 0))
1919         {
1920             /* clinet/server id match: try to restore a previous cached session*/
1921             ssl_restore_session(ssl, ssl_session_hash);
1922         }
1923         else {
1924             tvb_memcpy(tvb,ssl->session_id.data, offset+33, session_id_length);
1925             ssl->session_id.data_len = session_id_length;
1926         }
1927     }
1928
1929     if (tree)
1930     {
1931                 ti_rnd = proto_tree_add_text(tree, tvb, offset, 32, "Random");
1932                 ssl_rnd_tree = proto_item_add_subtree(ti_rnd, ett_ssl_random);
1933
1934         /* show the time */
1935         gmt_unix_time.secs = tvb_get_ntohl(tvb, offset);
1936         gmt_unix_time.nsecs = 0;
1937         proto_tree_add_time(ssl_rnd_tree, hf_ssl_handshake_random_time,
1938                                      tvb, offset, 4, &gmt_unix_time);
1939         offset += 4;
1940
1941         /* show the random bytes */
1942         proto_tree_add_item(ssl_rnd_tree, hf_ssl_handshake_random_bytes,
1943                             tvb, offset, 28, FALSE);
1944         offset += 28;
1945
1946         /* show the session id */
1947         session_id_length = tvb_get_guint8(tvb, offset);
1948         proto_tree_add_item(tree, hf_ssl_handshake_session_id_len,
1949                             tvb, offset++, 1, 0);
1950         if (session_id_length > 0)
1951         {
1952             tvb_ensure_bytes_exist(tvb, offset, session_id_length);
1953             proto_tree_add_bytes(tree, hf_ssl_handshake_session_id,
1954                                          tvb, offset, session_id_length,
1955                                          tvb_get_ptr(tvb, offset, session_id_length));
1956             offset += session_id_length;
1957         }
1958
1959     }
1960
1961     /* XXXX */
1962     return session_id_length+33;
1963 }
1964
1965 static gint
1966 dissect_ssl3_hnd_hello_ext(tvbuff_t *tvb,
1967                            proto_tree *tree, guint32 offset, guint32 left)
1968 {
1969     guint16 extension_length;
1970     guint16 ext_type;
1971     guint16 ext_len;
1972     proto_item *pi;
1973     proto_tree *ext_tree;
1974
1975     if (left < 2)
1976         return offset;
1977
1978     extension_length = tvb_get_ntohs(tvb, offset);
1979     proto_tree_add_uint(tree, hf_ssl_handshake_extensions_len,
1980                         tvb, offset, 2, extension_length);
1981     offset += 2;
1982     left -= 2;
1983
1984     while (left >= 4)
1985     {
1986         ext_type = tvb_get_ntohs(tvb, offset);
1987         ext_len = tvb_get_ntohs(tvb, offset + 2);
1988
1989         pi = proto_tree_add_text(tree, tvb, offset, 4 + ext_len,
1990                                  "Extension: %s",
1991                                  val_to_str(ext_type,
1992                                             tls_hello_extension_types,
1993                                             "Unknown %u"));
1994         ext_tree = proto_item_add_subtree(pi, ett_ssl_extension);
1995         if (!ext_tree)
1996             ext_tree = tree;
1997
1998         proto_tree_add_uint(ext_tree, hf_ssl_handshake_extension_type,
1999                             tvb, offset, 2, ext_type);
2000         offset += 2;
2001
2002         proto_tree_add_uint(ext_tree, hf_ssl_handshake_extension_len,
2003                             tvb, offset, 2, ext_len);
2004         offset += 2;
2005
2006         proto_tree_add_bytes_format(ext_tree, hf_ssl_handshake_extension_data,
2007                                     tvb, offset, ext_len,
2008                                     tvb_get_ptr(tvb, offset, ext_len),
2009                                     "Data (%u byte%s)",
2010                                     ext_len, plurality(ext_len, "", "s"));
2011         offset += ext_len;
2012         left -= 2 + 2 + ext_len;
2013     }
2014
2015     return offset;
2016 }
2017
2018 static void
2019 dissect_ssl3_hnd_cli_hello(tvbuff_t *tvb,
2020        proto_tree *tree, guint32 offset, guint32 length,
2021        SslDecryptSession*ssl)
2022 {
2023     /* struct {
2024      *     ProtocolVersion client_version;
2025      *     Random random;
2026      *     SessionID session_id;
2027      *     CipherSuite cipher_suites<2..2^16-1>;
2028      *     CompressionMethod compression_methods<1..2^8-1>;
2029      *     Extension client_hello_extension_list<0..2^16-1>;
2030      * } ClientHello;
2031      *
2032      */
2033     proto_tree *ti;
2034     proto_tree *cs_tree;
2035     guint16 cipher_suite_length;
2036     guint8  compression_methods_length;
2037     guint8  compression_method;
2038     guint16 start_offset;
2039     cipher_suite_length = 0;
2040     compression_methods_length = 0;
2041     start_offset = offset;
2042
2043     if (tree || ssl)
2044     {
2045         /* show the client version */
2046         if (tree)
2047             proto_tree_add_item(tree, hf_ssl_handshake_client_version, tvb,
2048                             offset, 2, FALSE);
2049         offset += 2;
2050
2051         /* show the fields in common with server hello */
2052         offset += dissect_ssl3_hnd_hello_common(tvb, tree, offset, ssl, 0);
2053
2054         /* tell the user how many cipher suites there are */
2055         cipher_suite_length = tvb_get_ntohs(tvb, offset);
2056         if (!tree)
2057             return;
2058         proto_tree_add_uint(tree, hf_ssl_handshake_cipher_suites_len,
2059                         tvb, offset, 2, cipher_suite_length);
2060         offset += 2;            /* skip opaque length */
2061
2062         if (cipher_suite_length > 0)
2063         {
2064             tvb_ensure_bytes_exist(tvb, offset, cipher_suite_length);
2065             ti = proto_tree_add_none_format(tree,
2066                                             hf_ssl_handshake_cipher_suites,
2067                                             tvb, offset, cipher_suite_length,
2068                                             "Cipher Suites (%u suite%s)",
2069                                             cipher_suite_length / 2,
2070                                             plurality(cipher_suite_length/2, "", "s"));
2071
2072             /* make this a subtree */
2073             cs_tree = proto_item_add_subtree(ti, ett_ssl_cipher_suites);
2074             if (!cs_tree)
2075             {
2076                 cs_tree = tree; /* failsafe */
2077             }
2078
2079             while (cipher_suite_length > 0)
2080             {
2081                 proto_tree_add_item(cs_tree, hf_ssl_handshake_cipher_suite,
2082                                     tvb, offset, 2, FALSE);
2083                 offset += 2;
2084                 cipher_suite_length -= 2;
2085             }
2086         }
2087
2088         /* tell the user how man compression methods there are */
2089         compression_methods_length = tvb_get_guint8(tvb, offset);
2090         proto_tree_add_uint(tree, hf_ssl_handshake_comp_methods_len,
2091                             tvb, offset, 1, compression_methods_length);
2092         offset++;
2093
2094         if (compression_methods_length > 0)
2095         {
2096             tvb_ensure_bytes_exist(tvb, offset, compression_methods_length);
2097             ti = proto_tree_add_none_format(tree,
2098                                             hf_ssl_handshake_comp_methods,
2099                                             tvb, offset, compression_methods_length,
2100                                             "Compression Methods (%u method%s)",
2101                                             compression_methods_length,
2102                                             plurality(compression_methods_length,
2103                                               "", "s"));
2104
2105             /* make this a subtree */
2106             cs_tree = proto_item_add_subtree(ti, ett_ssl_comp_methods);
2107             if (!cs_tree)
2108             {
2109                 cs_tree = tree; /* failsafe */
2110             }
2111
2112             while (compression_methods_length > 0)
2113             {
2114                 compression_method = tvb_get_guint8(tvb, offset);
2115                 if (compression_method < 64)
2116                     proto_tree_add_uint(cs_tree, hf_ssl_handshake_comp_method,
2117                                     tvb, offset, 1, compression_method);
2118                 else if (compression_method > 63 && compression_method < 193)
2119                     proto_tree_add_text(cs_tree, tvb, offset, 1,
2120                       "Compression Method: Reserved - to be assigned by IANA (%u)",
2121                       compression_method);
2122                 else
2123                     proto_tree_add_text(cs_tree, tvb, offset, 1,
2124                        "Compression Method: Private use range (%u)",
2125                        compression_method);
2126                 offset++;
2127                 compression_methods_length--;
2128             }
2129         }
2130
2131         if (length > offset - start_offset)
2132         {
2133             offset = dissect_ssl3_hnd_hello_ext(tvb, tree, offset,
2134                                                 length -
2135                                                 (offset - start_offset));
2136         }
2137     }
2138 }
2139
2140 static void
2141 dissect_ssl3_hnd_srv_hello(tvbuff_t *tvb,
2142                            proto_tree *tree, guint32 offset, guint32 length, SslDecryptSession* ssl)
2143 {
2144     /* struct {
2145      *     ProtocolVersion server_version;
2146      *     Random random;
2147      *     SessionID session_id;
2148      *     CipherSuite cipher_suite;
2149      *     CompressionMethod compression_method;
2150      *     Extension server_hello_extension_list<0..2^16-1>;
2151      * } ServerHello;
2152      */
2153     guint16 start_offset;
2154     start_offset = offset;
2155
2156     if (tree || ssl)
2157     {
2158         /* show the server version */
2159         if (tree)
2160                 proto_tree_add_item(tree, hf_ssl_handshake_server_version, tvb,
2161                             offset, 2, FALSE);
2162         offset += 2;
2163
2164         /* first display the elements conveniently in
2165          * common with client hello
2166          */
2167         offset += dissect_ssl3_hnd_hello_common(tvb, tree, offset, ssl, 1);
2168
2169         /* PAOLO: handle session cipher suite  */
2170         if (ssl) {
2171             /* store selected cipher suite for decryption */
2172             ssl->cipher = tvb_get_ntohs(tvb, offset);
2173             if (ssl_find_cipher(ssl->cipher,&ssl->cipher_suite) < 0) {
2174                 ssl_debug_printf("dissect_ssl3_hnd_srv_hello can't find cipher suite 0x%X\n", ssl->cipher);
2175                 goto no_cipher;
2176             }
2177
2178             ssl->state |= SSL_CIPHER;
2179             ssl_debug_printf("dissect_ssl3_hnd_srv_hello found CIPHER 0x%04X -> state 0x%02X\n",
2180                 ssl->cipher, ssl->state);
2181
2182             /* if we have restored a session now we can have enought material
2183              * to build session key, check it out*/
2184             if ((ssl->state &
2185                     (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) !=
2186                     (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) {
2187                 ssl_debug_printf("dissect_ssl3_hnd_srv_hello not enough data to generate key (required 0x%02X)\n",
2188                     (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET));
2189                 goto no_cipher;
2190             }
2191
2192             ssl_debug_printf("dissect_ssl3_hnd_srv_hello trying to generate keys\n");
2193             if (ssl_generate_keyring_material(ssl)<0) {
2194                 ssl_debug_printf("dissect_ssl3_hnd_srv_hello can't generate keyring material\n");
2195                 goto no_cipher;
2196             }
2197             ssl->state |= SSL_HAVE_SESSION_KEY;
2198         }
2199 no_cipher:
2200
2201         /* now the server-selected cipher suite */
2202         proto_tree_add_item(tree, hf_ssl_handshake_cipher_suite,
2203                     tvb, offset, 2, FALSE);
2204         offset += 2;
2205
2206       if (ssl) {
2207           /* store selected compression method for decryption */
2208           ssl->compression = tvb_get_guint8(tvb, offset);
2209       }
2210         /* and the server-selected compression method */
2211         proto_tree_add_item(tree, hf_ssl_handshake_comp_method,
2212                             tvb, offset, 1, FALSE);
2213         offset++;
2214
2215         if (length > offset - start_offset)
2216         {
2217             offset = dissect_ssl3_hnd_hello_ext(tvb, tree, offset,
2218                                                 length -
2219                                                 (offset - start_offset));
2220         }
2221     }
2222 }
2223
2224 static void
2225 dissect_ssl3_hnd_cert(tvbuff_t *tvb,
2226                       proto_tree *tree, guint32 offset, packet_info *pinfo)
2227 {
2228
2229     /* opaque ASN.1Cert<2^24-1>;
2230      *
2231      * struct {
2232      *     ASN.1Cert certificate_list<1..2^24-1>;
2233      * } Certificate;
2234      */
2235     guint32 certificate_list_length;
2236     proto_tree *ti;
2237     proto_tree *subtree;
2238
2239     if (tree)
2240     {
2241         certificate_list_length = tvb_get_ntoh24(tvb, offset);
2242         proto_tree_add_uint(tree, hf_ssl_handshake_certificates_len,
2243                             tvb, offset, 3, certificate_list_length);
2244         offset += 3;            /* 24-bit length value */
2245
2246         if (certificate_list_length > 0)
2247         {
2248             tvb_ensure_bytes_exist(tvb, offset, certificate_list_length);
2249             ti = proto_tree_add_none_format(tree,
2250                                             hf_ssl_handshake_certificates,
2251                                             tvb, offset, certificate_list_length,
2252                                             "Certificates (%u byte%s)",
2253                                             certificate_list_length,
2254                                             plurality(certificate_list_length,
2255                                               "", "s"));
2256
2257             /* make it a subtree */
2258             subtree = proto_item_add_subtree(ti, ett_ssl_certs);
2259             if (!subtree)
2260             {
2261                 subtree = tree; /* failsafe */
2262             }
2263
2264             /* iterate through each certificate */
2265             while (certificate_list_length > 0)
2266             {
2267                 /* get the length of the current certificate */
2268                 guint32 cert_length;
2269                 cert_length = tvb_get_ntoh24(tvb, offset);
2270                 certificate_list_length -= 3 + cert_length;
2271
2272                 proto_tree_add_item(subtree, hf_ssl_handshake_certificate_len,
2273                                     tvb, offset, 3, FALSE);
2274                 offset += 3;
2275
2276                 dissect_x509af_Certificate(FALSE, tvb, offset, pinfo, subtree, hf_ssl_handshake_certificate);
2277                 offset += cert_length;
2278             }
2279         }
2280
2281     }
2282 }
2283
2284 static void
2285 dissect_ssl3_hnd_cert_req(tvbuff_t *tvb,
2286                           proto_tree *tree, guint32 offset)
2287 {
2288     /*
2289      *    enum {
2290      *        rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
2291      *        (255)
2292      *    } ClientCertificateType;
2293      *
2294      *    opaque DistinguishedName<1..2^16-1>;
2295      *
2296      *    struct {
2297      *        ClientCertificateType certificate_types<1..2^8-1>;
2298      *        DistinguishedName certificate_authorities<3..2^16-1>;
2299      *    } CertificateRequest;
2300      *
2301      */
2302     proto_tree *ti;
2303     proto_tree *subtree;
2304     guint8      cert_types_count;
2305     gint         dnames_length;
2306     cert_types_count = 0;
2307     dnames_length = 0;
2308
2309     if (tree)
2310     {
2311         cert_types_count = tvb_get_guint8(tvb, offset);
2312         proto_tree_add_uint(tree, hf_ssl_handshake_cert_types_count,
2313                             tvb, offset, 1, cert_types_count);
2314         offset++;
2315
2316         if (cert_types_count > 0)
2317         {
2318             ti = proto_tree_add_none_format(tree,
2319                                             hf_ssl_handshake_cert_types,
2320                                             tvb, offset, cert_types_count,
2321                                             "Certificate types (%u type%s)",
2322                                             cert_types_count,
2323                                             plurality(cert_types_count, "", "s"));
2324             subtree = proto_item_add_subtree(ti, ett_ssl_cert_types);
2325             if (!subtree)
2326             {
2327                 subtree = tree;
2328             }
2329
2330             while (cert_types_count > 0)
2331             {
2332                 proto_tree_add_item(subtree, hf_ssl_handshake_cert_type,
2333                                     tvb, offset, 1, FALSE);
2334                 offset++;
2335                 cert_types_count--;
2336             }
2337         }
2338
2339         dnames_length = tvb_get_ntohs(tvb, offset);
2340         proto_tree_add_uint(tree, hf_ssl_handshake_dnames_len,
2341                             tvb, offset, 2, dnames_length);
2342         offset += 2;
2343
2344         if (dnames_length > 0)
2345         {
2346             tvb_ensure_bytes_exist(tvb, offset, dnames_length);
2347             ti = proto_tree_add_none_format(tree,
2348                                             hf_ssl_handshake_dnames,
2349                                             tvb, offset, dnames_length,
2350                                             "Distinguished Names (%d byte%s)",
2351                                             dnames_length,
2352                                             plurality(dnames_length, "", "s"));
2353             subtree = proto_item_add_subtree(ti, ett_ssl_dnames);
2354             if (!subtree)
2355             {
2356                 subtree = tree;
2357             }
2358
2359             while (dnames_length > 0)
2360             {
2361                 /* get the length of the current certificate */
2362                 guint16 name_length;
2363                 name_length = tvb_get_ntohs(tvb, offset);
2364                 dnames_length -= 2 + name_length;
2365
2366                 proto_tree_add_item(subtree, hf_ssl_handshake_dname_len,
2367                                     tvb, offset, 2, FALSE);
2368                 offset += 2;
2369
2370                 tvb_ensure_bytes_exist(tvb, offset, name_length);
2371                 proto_tree_add_bytes_format(subtree,
2372                                             hf_ssl_handshake_dname,
2373                                             tvb, offset, name_length,
2374                                             tvb_get_ptr(tvb, offset, name_length),
2375                                             "Distinguished Name (%u byte%s)",
2376                                             name_length,
2377                                             plurality(name_length, "", "s"));
2378                 offset += name_length;
2379             }
2380         }
2381     }
2382
2383 }
2384
2385 static void
2386 dissect_ssl3_hnd_finished(tvbuff_t *tvb,
2387                           proto_tree *tree, guint32 offset,
2388                           guint* conv_version)
2389 {
2390     /* For TLS:
2391      *     struct {
2392      *         opaque verify_data[12];
2393      *     } Finished;
2394      *
2395      * For SSLv3:
2396      *     struct {
2397      *         opaque md5_hash[16];
2398      *         opaque sha_hash[20];
2399      *     } Finished;
2400      */
2401
2402     /* this all needs a tree, so bail if we don't have one */
2403     if (!tree)
2404     {
2405         return;
2406     }
2407
2408     switch(*conv_version) {
2409     case SSL_VER_TLS:
2410     case SSL_VER_TLSv1DOT1:
2411         proto_tree_add_item(tree, hf_ssl_handshake_finished,
2412                             tvb, offset, 12, FALSE);
2413         break;
2414
2415     case SSL_VER_SSLv3:
2416         proto_tree_add_item(tree, hf_ssl_handshake_md5_hash,
2417                             tvb, offset, 16, FALSE);
2418         offset += 16;
2419         proto_tree_add_item(tree, hf_ssl_handshake_sha_hash,
2420                             tvb, offset, 20, FALSE);
2421         offset += 20;
2422         break;
2423     }
2424 }
2425
2426 /*********************************************************************
2427  *
2428  * SSL version 2 Dissectors
2429  *
2430  *********************************************************************/
2431
2432
2433 /* record layer dissector */
2434 static gint
2435 dissect_ssl2_record(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
2436                     guint32 offset, guint* conv_version,
2437                     gboolean *need_desegmentation,
2438                     SslDecryptSession* ssl)
2439 {
2440     guint32 initial_offset;
2441     guint8  byte;
2442     guint8  record_length_length;
2443     guint32 record_length;
2444     gint    is_escape;
2445     gint16  padding_length;
2446     guint8  msg_type;
2447     const gchar *msg_type_str;
2448     guint32 available_bytes;
2449     proto_tree *ti;
2450     proto_tree *ssl_record_tree;
2451
2452     initial_offset       = offset;
2453     byte                 = 0;
2454     record_length_length = 0;
2455     record_length        = 0;
2456     is_escape            = -1;
2457     padding_length       = -1;
2458     msg_type             = 0;
2459     msg_type_str         = NULL;
2460     available_bytes      = 0;
2461     ssl_record_tree      = NULL;
2462
2463     /* pull first byte; if high bit is unset, then record
2464      * length is three bytes due to padding; otherwise
2465      * record length is two bytes
2466      */
2467     byte = tvb_get_guint8(tvb, offset);
2468     record_length_length = (byte & 0x80) ? 2 : 3;
2469
2470     /*
2471      * Can we do reassembly?
2472      */
2473     available_bytes = tvb_length_remaining(tvb, offset);
2474
2475     if (ssl_desegment && pinfo->can_desegment) {
2476         /*
2477          * Yes - is the record header split across segment boundaries?
2478          */
2479         if (available_bytes < record_length_length) {
2480             /*
2481              * Yes.  Tell the TCP dissector where the data for this
2482              * message starts in the data it handed us, and how many
2483              * more bytes we need, and return.
2484              */
2485             pinfo->desegment_offset = offset;
2486             pinfo->desegment_len = record_length_length - available_bytes;
2487             *need_desegmentation = TRUE;
2488             return offset;
2489         }
2490     }
2491
2492     /* parse out the record length */
2493     switch(record_length_length) {
2494     case 2:                     /* two-byte record length */
2495         record_length = (byte & 0x7f) << 8;
2496         byte = tvb_get_guint8(tvb, offset + 1);
2497         record_length += byte;
2498         break;
2499     case 3:                     /* three-byte record length */
2500         is_escape = (byte & 0x40) ? TRUE : FALSE;
2501         record_length = (byte & 0x3f) << 8;
2502         byte = tvb_get_guint8(tvb, offset + 1);
2503         record_length += byte;
2504         byte = tvb_get_guint8(tvb, offset + 2);
2505         padding_length = byte;
2506     }
2507
2508     /*
2509      * Can we do reassembly?
2510      */
2511     if (ssl_desegment && pinfo->can_desegment) {
2512         /*
2513          * Yes - is the record split across segment boundaries?
2514          */
2515         if (available_bytes < (record_length_length + record_length)) {
2516             /*
2517              * Yes.  Tell the TCP dissector where the data for this
2518              * message starts in the data it handed us, and how many
2519              * more bytes we need, and return.
2520              */
2521             pinfo->desegment_offset = offset;
2522             pinfo->desegment_len = (record_length_length + record_length)
2523                                    - available_bytes;
2524             *need_desegmentation = TRUE;
2525             return offset;
2526         }
2527     }
2528     offset += record_length_length;
2529
2530     /* add the record layer subtree header */
2531     ti = proto_tree_add_item(tree, hf_ssl2_record, tvb, initial_offset,
2532                              record_length_length + record_length, 0);
2533     ssl_record_tree = proto_item_add_subtree(ti, ett_ssl_record);
2534
2535     /* pull the msg_type so we can bail if it's unknown */
2536     msg_type = tvb_get_guint8(tvb, initial_offset + record_length_length);
2537
2538     /* if we get a server_hello or later handshake in v2, then set
2539      * this to sslv2
2540      */
2541     if (*conv_version == SSL_VER_UNKNOWN)
2542     {
2543         if (ssl_looks_like_valid_pct_handshake(tvb,
2544                                                (initial_offset +
2545                                                 record_length_length),
2546                                                record_length)) {
2547             *conv_version = SSL_VER_PCT;
2548             /*ssl_set_conv_version(pinfo, ssl->version);*/
2549         }
2550         else if (msg_type >= 2 && msg_type <= 8)
2551         {
2552             *conv_version = SSL_VER_SSLv2;
2553             /*ssl_set_conv_version(pinfo, ssl->version);*/
2554         }
2555     }
2556
2557     /* if we get here, but don't have a version set for the
2558      * conversation, then set a version for just this frame
2559      * (e.g., on a client hello)
2560      */
2561     if (check_col(pinfo->cinfo, COL_PROTOCOL))
2562     {
2563         col_set_str(pinfo->cinfo, COL_PROTOCOL,
2564                     (*conv_version == SSL_VER_PCT) ? "PCT" : "SSLv2");
2565     }
2566
2567     /* see if the msg_type is valid; if not the payload is
2568      * probably encrypted, so note that fact and bail
2569      */
2570     msg_type_str = match_strval(msg_type,
2571                                 (*conv_version == SSL_VER_PCT)
2572                                 ? pct_msg_types : ssl_20_msg_types);
2573     if (!msg_type_str
2574         || ((*conv_version != SSL_VER_PCT) &&
2575             !ssl_looks_like_valid_v2_handshake(tvb, initial_offset
2576                                                + record_length_length,
2577                                                record_length))
2578         || ((*conv_version == SSL_VER_PCT) &&
2579             !ssl_looks_like_valid_pct_handshake(tvb, initial_offset
2580                                                 + record_length_length,
2581                                                 record_length)))
2582     {
2583         if (ssl_record_tree)
2584         {
2585             proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
2586                                 (*conv_version == SSL_VER_PCT)
2587                                 ? "PCT" : "SSLv2",
2588                                 "Encrypted Data");
2589
2590             /* Unlike SSLv3, the SSLv2 record layer does not have a
2591              * version field. To make it possible to filter on record
2592              * layer version we create a generated field with ssl
2593              * record layer version 0x0002
2594              */
2595             ti = proto_tree_add_uint(ssl_record_tree,
2596                                      hf_ssl_record_version, tvb,
2597                                      initial_offset, 0, 0x0002);
2598             PROTO_ITEM_SET_GENERATED(ti);
2599         }
2600
2601         if (check_col(pinfo->cinfo, COL_INFO))
2602             col_append_str(pinfo->cinfo, COL_INFO, "Encrypted Data");
2603         return initial_offset + record_length_length + record_length;
2604     }
2605     else
2606     {
2607         if (check_col(pinfo->cinfo, COL_INFO))
2608             col_append_str(pinfo->cinfo, COL_INFO, msg_type_str);
2609
2610         if (ssl_record_tree)
2611         {
2612             proto_item_set_text(ssl_record_tree, "%s Record Layer: %s",
2613                                 (*conv_version == SSL_VER_PCT)
2614                                 ? "PCT" : "SSLv2",
2615                                 msg_type_str);
2616         }
2617     }
2618
2619     /* We have a valid message type, so move foward, filling in the
2620      * tree by adding the length, is_escape boolean and padding_length,
2621      * if present in the original packet
2622      */
2623     if (ssl_record_tree)
2624     {
2625         /* Unlike SSLv3, the SSLv2 record layer does not have a
2626          * version field. To make it possible to filter on record
2627          * layer version we create a generated field with ssl
2628          * record layer version 0x0002
2629          */
2630         ti = proto_tree_add_uint(ssl_record_tree,
2631                                  hf_ssl_record_version, tvb,
2632                                  initial_offset, 0, 0x0002);
2633         PROTO_ITEM_SET_GENERATED(ti);
2634
2635         /* add the record length */
2636         tvb_ensure_bytes_exist(tvb, offset, record_length_length);
2637         ti = proto_tree_add_uint (ssl_record_tree,
2638                                   hf_ssl_record_length, tvb,
2639                                   initial_offset, record_length_length,
2640                                   record_length);
2641     }
2642     if (ssl_record_tree && is_escape != -1)
2643     {
2644         proto_tree_add_boolean(ssl_record_tree,
2645                                hf_ssl2_record_is_escape, tvb,
2646                                initial_offset, 1, is_escape);
2647         }
2648     if (ssl_record_tree && padding_length != -1)
2649     {
2650         proto_tree_add_uint(ssl_record_tree,
2651                             hf_ssl2_record_padding_length, tvb,
2652                             initial_offset + 2, 1, padding_length);
2653     }
2654
2655     /*
2656      * dissect the record data
2657      */
2658
2659     /* jump forward to the start of the record data */
2660     offset = initial_offset + record_length_length;
2661
2662     /* add the message type */
2663     if (ssl_record_tree)
2664     {
2665         proto_tree_add_item(ssl_record_tree,
2666                             (*conv_version == SSL_VER_PCT)
2667                             ? hf_pct_msg_type : hf_ssl2_msg_type,
2668                             tvb, offset, 1, 0);
2669     }
2670     offset++;                   /* move past msg_type byte */
2671
2672     if (*conv_version != SSL_VER_PCT)
2673     {
2674         /* dissect the message (only handle client hello right now) */
2675         switch (msg_type) {
2676         case SSL2_HND_CLIENT_HELLO:
2677             dissect_ssl2_hnd_client_hello(tvb, ssl_record_tree, offset, ssl);
2678             break;
2679
2680         case SSL2_HND_CLIENT_MASTER_KEY:
2681             dissect_ssl2_hnd_client_master_key(tvb, ssl_record_tree, offset);
2682             break;
2683
2684         case SSL2_HND_SERVER_HELLO:
2685             dissect_ssl2_hnd_server_hello(tvb, ssl_record_tree, offset, pinfo);
2686             break;
2687
2688         case SSL2_HND_ERROR:
2689         case SSL2_HND_CLIENT_FINISHED:
2690         case SSL2_HND_SERVER_VERIFY:
2691         case SSL2_HND_SERVER_FINISHED:
2692         case SSL2_HND_REQUEST_CERTIFICATE:
2693         case SSL2_HND_CLIENT_CERTIFICATE:
2694             /* unimplemented */
2695             break;
2696
2697         default:                    /* unknown */
2698             break;
2699         }
2700     }
2701     else
2702     {
2703         /* dissect the message */
2704         switch (msg_type) {
2705         case PCT_MSG_CLIENT_HELLO:
2706                         dissect_pct_msg_client_hello(tvb, ssl_record_tree, offset);
2707                         break;
2708         case PCT_MSG_SERVER_HELLO:
2709                         dissect_pct_msg_server_hello(tvb, ssl_record_tree, offset, pinfo);
2710                         break;
2711         case PCT_MSG_CLIENT_MASTER_KEY:
2712                         dissect_pct_msg_client_master_key(tvb, ssl_record_tree, offset);
2713                         break;
2714         case PCT_MSG_SERVER_VERIFY:
2715                         dissect_pct_msg_server_verify(tvb, ssl_record_tree, offset);
2716                         break;
2717                 case PCT_MSG_ERROR:
2718                         dissect_pct_msg_error(tvb, ssl_record_tree, offset);
2719             break;
2720
2721         default:                    /* unknown */
2722             break;
2723         }
2724     }
2725     return (initial_offset + record_length_length + record_length);
2726 }
2727
2728 static void
2729 dissect_ssl2_hnd_client_hello(tvbuff_t *tvb,
2730                               proto_tree *tree, guint32 offset,
2731                               SslDecryptSession* ssl)
2732 {
2733     /* struct {
2734      *    uint8 msg_type;
2735      *     Version version;
2736      *     uint16 cipher_spec_length;
2737      *     uint16 session_id_length;
2738      *     uint16 challenge_length;
2739      *     V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
2740      *     opaque session_id[V2ClientHello.session_id_length];
2741      *     Random challenge;
2742      * } V2ClientHello;
2743      *
2744      * Note: when we get here, offset's already pointing at Version
2745      *
2746      */
2747     guint16 version;
2748     guint16 cipher_spec_length;
2749     guint16 session_id_length;
2750     guint16 challenge_length;
2751
2752     proto_tree *ti;
2753     proto_tree *cs_tree;
2754     cs_tree=0;
2755
2756     version = tvb_get_ntohs(tvb, offset);
2757     if (!ssl_is_valid_ssl_version(version))
2758     {
2759         /* invalid version; probably encrypted data */
2760         return;
2761     }
2762
2763     if (tree || ssl)
2764     {
2765         /* show the version */
2766         if (tree)
2767             proto_tree_add_item(tree, hf_ssl_handshake_client_version, tvb,
2768                             offset, 2, FALSE);
2769         offset += 2;
2770
2771         cipher_spec_length = tvb_get_ntohs(tvb, offset);
2772         if (tree)
2773             proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec_len,
2774                             tvb, offset, 2, FALSE);
2775         offset += 2;
2776
2777         session_id_length = tvb_get_ntohs(tvb, offset);
2778         if (tree)
2779             proto_tree_add_item(tree, hf_ssl2_handshake_session_id_len,
2780                             tvb, offset, 2, FALSE);
2781         offset += 2;
2782
2783         challenge_length = tvb_get_ntohs(tvb, offset);
2784         if (tree)
2785             proto_tree_add_item(tree, hf_ssl2_handshake_challenge_len,
2786                             tvb, offset, 2, FALSE);
2787         offset += 2;
2788
2789         if (tree)
2790         {
2791             /* tell the user how many cipher specs they've won */
2792             tvb_ensure_bytes_exist(tvb, offset, cipher_spec_length);
2793             ti = proto_tree_add_none_format(tree, hf_ssl_handshake_cipher_suites,
2794                                         tvb, offset, cipher_spec_length,
2795                                         "Cipher Specs (%u specs)",
2796                                         cipher_spec_length/3);
2797
2798             /* make this a subtree and expand the actual specs below */
2799             cs_tree = proto_item_add_subtree(ti, ett_ssl_cipher_suites);
2800             if (!cs_tree)
2801             {
2802                 cs_tree = tree;     /* failsafe */
2803             }
2804         }
2805
2806         /* iterate through the cipher specs, showing them */
2807         while (cipher_spec_length > 0)
2808         {
2809             if (cs_tree)
2810                 proto_tree_add_item(cs_tree, hf_ssl2_handshake_cipher_spec,
2811                                 tvb, offset, 3, FALSE);
2812             offset += 3;        /* length of one cipher spec */
2813             cipher_spec_length -= 3;
2814         }
2815
2816         /* if there's a session id, show it */
2817         if (session_id_length > 0)
2818         {
2819             if (tree)
2820             {
2821                 tvb_ensure_bytes_exist(tvb, offset, session_id_length);
2822                 proto_tree_add_bytes_format(tree,
2823                                              hf_ssl_handshake_session_id,
2824                                              tvb, offset, session_id_length,
2825                                              tvb_get_ptr(tvb, offset, session_id_length),
2826                                              "Session ID (%u byte%s)",
2827                                              session_id_length,
2828                                              plurality(session_id_length, "", "s"));
2829             }
2830
2831             /* PAOLO: get session id and reset session state for key [re]negotiation */
2832             if (ssl)
2833             {
2834                 tvb_memcpy(tvb,ssl->session_id.data, offset, session_id_length);
2835                 ssl->session_id.data_len = session_id_length;
2836                 ssl->state &= ~(SSL_HAVE_SESSION_KEY|SSL_MASTER_SECRET|
2837                         SSL_CIPHER|SSL_SERVER_RANDOM);
2838             }
2839             offset += session_id_length;
2840         }
2841
2842         /* if there's a challenge, show it */
2843         if (challenge_length > 0)
2844         {
2845             tvb_ensure_bytes_exist(tvb, offset, challenge_length);
2846
2847             if (tree)
2848                 proto_tree_add_item(tree, hf_ssl2_handshake_challenge,
2849                                 tvb, offset, challenge_length, 0);
2850             if (ssl)
2851             {
2852                 /* PAOLO: get client random data; we get at most 32 bytes from
2853                  challenge */
2854                 gint max;
2855                 max = challenge_length > 32? 32: challenge_length;
2856
2857                 ssl_debug_printf("client random len: %d padded to 32\n",
2858                     challenge_length);
2859
2860                 /* client random is padded with zero and 'right' aligned */
2861                 memset(ssl->client_random.data, 0, 32 - max);
2862                 tvb_memcpy(tvb, &ssl->client_random.data[32 - max], offset, max);
2863                 ssl->client_random.data_len = 32;
2864                 ssl->state |= SSL_CLIENT_RANDOM;
2865
2866             }
2867             offset += challenge_length;
2868         }
2869     }
2870 }
2871
2872 static void
2873 dissect_pct_msg_client_hello(tvbuff_t *tvb,
2874                                                         proto_tree *tree, guint32 offset)
2875 {
2876         guint16 CH_CLIENT_VERSION, CH_OFFSET, CH_CIPHER_SPECS_LENGTH, CH_HASH_SPECS_LENGTH, CH_CERT_SPECS_LENGTH, CH_EXCH_SPECS_LENGTH, CH_KEY_ARG_LENGTH;
2877         proto_item *CH_CIPHER_SPECS_ti, *CH_HASH_SPECS_ti, *CH_CERT_SPECS_ti, *CH_EXCH_SPECS_ti;
2878         proto_tree *CH_CIPHER_SPECS_tree, *CH_HASH_SPECS_tree, *CH_CERT_SPECS_tree, *CH_EXCH_SPECS_tree;
2879         gint i;
2880
2881         CH_CLIENT_VERSION = tvb_get_ntohs(tvb, offset);
2882         if(CH_CLIENT_VERSION != PCT_VERSION_1)
2883                 proto_tree_add_text(tree, tvb, offset, 2, "Client Version, should be %x in PCT version 1", PCT_VERSION_1);
2884         else
2885                 proto_tree_add_text(tree, tvb, offset, 2, "Client Version (%x)", PCT_VERSION_1);
2886         offset += 2;
2887
2888         proto_tree_add_text(tree, tvb, offset, 1, "PAD");
2889         offset += 1;
2890
2891         proto_tree_add_text(tree, tvb, offset, 32, "Client Session ID Data (32 bytes)");
2892         offset += 32;
2893
2894         proto_tree_add_text(tree, tvb, offset, 32, "Challange Data(32 bytes)");
2895         offset += 32;
2896
2897         CH_OFFSET = tvb_get_ntohs(tvb, offset);
2898         if(CH_OFFSET != PCT_CH_OFFSET_V1)
2899                 proto_tree_add_text(tree, tvb, offset, 2, "CH_OFFSET: %d, should be %d in PCT version 1", CH_OFFSET, PCT_CH_OFFSET_V1);
2900         else
2901                 proto_tree_add_text(tree, tvb, offset, 2, "CH_OFFSET: %d", CH_OFFSET);
2902         offset += 2;
2903
2904         CH_CIPHER_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
2905         proto_tree_add_text(tree, tvb, offset, 2, "CIPHER_SPECS Length: %d", CH_CIPHER_SPECS_LENGTH);
2906         offset += 2;
2907
2908         CH_HASH_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
2909         proto_tree_add_text(tree, tvb, offset, 2, "HASH_SPECS Length: %d", CH_HASH_SPECS_LENGTH);
2910         offset += 2;
2911
2912         CH_CERT_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
2913         proto_tree_add_text(tree, tvb, offset, 2, "CERT_SPECS Length: %d", CH_CERT_SPECS_LENGTH);
2914         offset += 2;
2915
2916         CH_EXCH_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
2917         proto_tree_add_text(tree, tvb, offset, 2, "EXCH_SPECS Length: %d", CH_EXCH_SPECS_LENGTH);
2918         offset += 2;
2919
2920         CH_KEY_ARG_LENGTH = tvb_get_ntohs(tvb, offset);
2921         proto_tree_add_text(tree, tvb, offset, 2, "IV Length: %d", CH_KEY_ARG_LENGTH);
2922         offset += 2;
2923
2924         if(CH_CIPHER_SPECS_LENGTH) {
2925                 tvb_ensure_bytes_exist(tvb, offset, CH_CIPHER_SPECS_LENGTH);
2926                 CH_CIPHER_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_cipher_spec, tvb, offset, CH_CIPHER_SPECS_LENGTH, FALSE);
2927                 CH_CIPHER_SPECS_tree = proto_item_add_subtree(CH_CIPHER_SPECS_ti, ett_pct_cipher_suites);
2928
2929                 for(i=0; i<(CH_CIPHER_SPECS_LENGTH/4); i++) {
2930                         proto_tree_add_item(CH_CIPHER_SPECS_tree, hf_pct_handshake_cipher, tvb, offset, 2, FALSE);
2931                         offset += 2;
2932                         proto_tree_add_text(CH_CIPHER_SPECS_tree, tvb, offset, 1, "Encryption key length: %d", tvb_get_guint8(tvb, offset));
2933                         offset += 1;
2934                         proto_tree_add_text(CH_CIPHER_SPECS_tree, tvb, offset, 1, "MAC key length in bits: %d", tvb_get_guint8(tvb, offset) + 64);
2935                         offset += 1;
2936                 }
2937         }
2938
2939         if(CH_HASH_SPECS_LENGTH) {
2940                 tvb_ensure_bytes_exist(tvb, offset, CH_HASH_SPECS_LENGTH);
2941                 CH_HASH_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_hash_spec, tvb, offset, CH_HASH_SPECS_LENGTH, FALSE);
2942                 CH_HASH_SPECS_tree = proto_item_add_subtree(CH_HASH_SPECS_ti, ett_pct_hash_suites);
2943
2944                 for(i=0; i<(CH_HASH_SPECS_LENGTH/2); i++) {
2945                         proto_tree_add_item(CH_HASH_SPECS_tree, hf_pct_handshake_hash, tvb, offset, 2, FALSE);
2946                         offset += 2;
2947                 }
2948         }
2949
2950         if(CH_CERT_SPECS_LENGTH) {
2951                 tvb_ensure_bytes_exist(tvb, offset, CH_CERT_SPECS_LENGTH);
2952                 CH_CERT_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_cert_spec, tvb, offset, CH_CERT_SPECS_LENGTH, FALSE);
2953                 CH_CERT_SPECS_tree = proto_item_add_subtree(CH_CERT_SPECS_ti, ett_pct_cert_suites);
2954
2955                 for(i=0; i< (CH_CERT_SPECS_LENGTH/2); i++) {
2956                         proto_tree_add_item(CH_CERT_SPECS_tree, hf_pct_handshake_cert, tvb, offset, 2, FALSE);
2957                         offset += 2;
2958                 }
2959         }
2960
2961         if(CH_EXCH_SPECS_LENGTH) {
2962                 tvb_ensure_bytes_exist(tvb, offset, CH_EXCH_SPECS_LENGTH);
2963                 CH_EXCH_SPECS_ti = proto_tree_add_item(tree, hf_pct_handshake_exch_spec, tvb, offset, CH_EXCH_SPECS_LENGTH, FALSE);
2964                 CH_EXCH_SPECS_tree = proto_item_add_subtree(CH_EXCH_SPECS_ti, ett_pct_exch_suites);
2965
2966                 for(i=0; i<(CH_EXCH_SPECS_LENGTH/2); i++) {
2967                         proto_tree_add_item(CH_EXCH_SPECS_tree, hf_pct_handshake_exch, tvb, offset, 2, FALSE);
2968                         offset += 2;
2969                 }
2970         }
2971
2972         if(CH_KEY_ARG_LENGTH) {
2973                 tvb_ensure_bytes_exist(tvb, offset, CH_KEY_ARG_LENGTH);
2974                 proto_tree_add_text(tree, tvb, offset, CH_KEY_ARG_LENGTH, "IV data (%d bytes)", CH_KEY_ARG_LENGTH);
2975                 offset += CH_KEY_ARG_LENGTH;
2976         }
2977 }
2978
2979 static void
2980 dissect_pct_msg_server_hello(tvbuff_t *tvb, proto_tree *tree, guint32 offset, packet_info *pinfo)
2981 {
2982 /* structure:
2983 char SH_MSG_SERVER_HELLO
2984 char SH_PAD
2985 char SH_SERVER_VERSION_MSB
2986 char SH_SERVER_VERSION_LSB
2987 char SH_RESTART_SESSION_OK
2988 char SH_CLIENT_AUTH_REQ
2989 char SH_CIPHER_SPECS_DATA[4]
2990 char SH_HASH_SPECS_DATA[2]
2991 char SH_CERT_SPECS_DATA[2]
2992 char SH_EXCH_SPECS_DATA[2]
2993 char SH_CONNECTION_ID_DATA[32]
2994 char SH_CERTIFICATE_LENGTH_MSB
2995 char SH_CERTIFICATE_LENGTH_LSB
2996 char SH_CLIENT_CERT_SPECS_LENGTH_MSB
2997 char SH_CLIENT_CERT_SPECS_LENGTH_LSB
2998 char SH_CLIENT_SIG_SPECS_LENGTH_MSB
2999 char SH_CLIENT_SIG_SPECS_LENGTH_LSB
3000 char SH_RESPONSE_LENGTH_MSB
3001 char SH_RESPONSE_LENGTH_LSB
3002 char SH_CERTIFICATE_DATA[MSB<<8|LSB]
3003 char SH_CLIENT_CERT_SPECS_DATA[MSB<<8|LSB]
3004 char SH_CLIENT_SIG_SPECS_DATA[MSB<<8|LSB]
3005 char SH_RESPONSE_DATA[MSB<<8|LSB]
3006
3007 */
3008
3009         guint16 SH_SERVER_VERSION, SH_CERT_LENGTH, SH_CERT_SPECS_LENGTH, SH_CLIENT_SIG_LENGTH, SH_RESPONSE_LENGTH;
3010
3011         proto_tree_add_text(tree, tvb, offset, 1, "PAD");
3012         offset += 1;
3013
3014         SH_SERVER_VERSION = tvb_get_ntohs(tvb, offset);
3015         if(SH_SERVER_VERSION != PCT_VERSION_1)
3016                 proto_tree_add_text(tree, tvb, offset, 2, "Server Version, should be %x in PCT version 1", PCT_VERSION_1);
3017         else
3018                 proto_tree_add_text(tree, tvb, offset, 2, "Server Version (%x)", PCT_VERSION_1);
3019         offset += 2;
3020
3021         proto_tree_add_text(tree, tvb, offset, 1, "SH_RESTART_SESSION_OK flag");
3022         offset += 1;
3023
3024         proto_tree_add_text(tree, tvb, offset, 1, "SH_CLIENT_AUTH_REQ flag");
3025         offset += 1;
3026
3027         proto_tree_add_item(tree, hf_pct_handshake_cipher, tvb, offset, 2, FALSE);
3028         offset += 2;
3029         proto_tree_add_text(tree, tvb, offset, 1, "Encryption key length: %d", tvb_get_guint8(tvb, offset));
3030         offset += 1;
3031         proto_tree_add_text(tree, tvb, offset, 1, "MAC key length in bits: %d", tvb_get_guint8(tvb, offset) + 64);
3032         offset += 1;
3033
3034         proto_tree_add_item(tree, hf_pct_handshake_hash, tvb, offset, 2, FALSE);
3035         offset += 2;
3036
3037         proto_tree_add_item(tree, hf_pct_handshake_cert, tvb, offset, 2, FALSE);
3038         offset += 2;
3039
3040         proto_tree_add_item(tree, hf_pct_handshake_exch, tvb, offset, 2, FALSE);
3041         offset += 2;
3042
3043         proto_tree_add_text(tree, tvb, offset, 32, "Connection ID Data (32 bytes)");
3044         offset += 32;
3045
3046         SH_CERT_LENGTH = tvb_get_ntohs(tvb, offset);
3047         proto_tree_add_text(tree, tvb, offset, 2, "Server Certificate Length: %d", SH_CERT_LENGTH);
3048         offset += 2;
3049
3050         SH_CERT_SPECS_LENGTH = tvb_get_ntohs(tvb, offset);
3051         proto_tree_add_text(tree, tvb, offset, 2, "Client CERT_SPECS Length: %d", SH_CERT_SPECS_LENGTH);
3052         offset += 2;
3053
3054         SH_CLIENT_SIG_LENGTH = tvb_get_ntohs(tvb, offset);
3055         proto_tree_add_text(tree, tvb, offset, 2, "Client SIG_SPECS Length: %d", SH_CLIENT_SIG_LENGTH);
3056         offset += 2;
3057
3058         SH_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
3059         proto_tree_add_text(tree, tvb, offset, 2, "Response Length: %d", SH_RESPONSE_LENGTH);
3060         offset += 2;
3061
3062         if(SH_CERT_LENGTH) {
3063                 dissect_x509af_Certificate(FALSE, tvb, offset, pinfo, tree, hf_pct_handshake_server_cert);
3064                 offset += SH_CERT_LENGTH;
3065         }
3066
3067         if(SH_CERT_SPECS_LENGTH) {
3068                 tvb_ensure_bytes_exist(tvb, offset, SH_CERT_SPECS_LENGTH);
3069                 proto_tree_add_text(tree, tvb, offset, SH_CERT_SPECS_LENGTH, "Client CERT_SPECS (%d bytes)", SH_CERT_SPECS_LENGTH);
3070                 offset += SH_CERT_SPECS_LENGTH;
3071         }
3072
3073         if(SH_CLIENT_SIG_LENGTH) {
3074                 tvb_ensure_bytes_exist(tvb, offset, SH_CLIENT_SIG_LENGTH);
3075                 proto_tree_add_text(tree, tvb, offset, SH_CLIENT_SIG_LENGTH, "Client Signature (%d bytes)", SH_CLIENT_SIG_LENGTH);
3076                 offset += SH_CLIENT_SIG_LENGTH;
3077         }
3078
3079         if(SH_RESPONSE_LENGTH) {
3080                 tvb_ensure_bytes_exist(tvb, offset, SH_RESPONSE_LENGTH);
3081                 proto_tree_add_text(tree, tvb, offset, SH_RESPONSE_LENGTH, "Server Response (%d bytes)", SH_RESPONSE_LENGTH);
3082                 offset += SH_RESPONSE_LENGTH;
3083         }
3084
3085 }
3086
3087 static void
3088 dissect_pct_msg_client_master_key(tvbuff_t *tvb, proto_tree *tree, guint32 offset)
3089 {
3090         guint16 CMK_CLEAR_KEY_LENGTH, CMK_ENCRYPTED_KEY_LENGTH, CMK_KEY_ARG_LENGTH, CMK_VERIFY_PRELUDE, CMK_CLIENT_CERT_LENGTH, CMK_RESPONSE_LENGTH;
3091
3092         proto_tree_add_text(tree, tvb, offset, 1, "PAD");
3093         offset += 1;
3094
3095         proto_tree_add_item(tree, hf_pct_handshake_cert, tvb, offset, 2, FALSE);
3096         offset += 2;
3097
3098         proto_tree_add_item(tree, hf_pct_handshake_sig, tvb, offset, 2, FALSE);
3099         offset += 2;
3100
3101         CMK_CLEAR_KEY_LENGTH = tvb_get_ntohs(tvb, offset);
3102         proto_tree_add_text(tree, tvb, offset, 2, "Clear Key Length: %d",CMK_CLEAR_KEY_LENGTH);
3103         offset += 2;
3104
3105         CMK_ENCRYPTED_KEY_LENGTH = tvb_get_ntohs(tvb, offset);
3106         proto_tree_add_text(tree, tvb, offset, 2, "Encrypted Key Length: %d",CMK_ENCRYPTED_KEY_LENGTH);
3107         offset += 2;
3108
3109         CMK_KEY_ARG_LENGTH= tvb_get_ntohs(tvb, offset);
3110         proto_tree_add_text(tree, tvb, offset, 2, "IV Length: %d",CMK_KEY_ARG_LENGTH);
3111         offset += 2;
3112
3113         CMK_VERIFY_PRELUDE = tvb_get_ntohs(tvb, offset);
3114         proto_tree_add_text(tree, tvb, offset, 2, "Verify Prelude Length: %d",CMK_VERIFY_PRELUDE);
3115         offset += 2;
3116
3117         CMK_CLIENT_CERT_LENGTH = tvb_get_ntohs(tvb, offset);
3118         proto_tree_add_text(tree, tvb, offset, 2, "Client Cert Length: %d",CMK_CLIENT_CERT_LENGTH);
3119         offset += 2;
3120
3121         CMK_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
3122         proto_tree_add_text(tree, tvb, offset, 2, "Response Length: %d",CMK_RESPONSE_LENGTH);
3123         offset += 2;
3124
3125         if(CMK_CLEAR_KEY_LENGTH) {
3126                 tvb_ensure_bytes_exist(tvb, offset, CMK_CLEAR_KEY_LENGTH);
3127                 proto_tree_add_text(tree, tvb, offset, CMK_CLEAR_KEY_LENGTH, "Clear Key data (%d bytes)", CMK_CLEAR_KEY_LENGTH);
3128                 offset += CMK_CLEAR_KEY_LENGTH;
3129         }
3130         if(CMK_ENCRYPTED_KEY_LENGTH) {
3131                 tvb_ensure_bytes_exist(tvb, offset, CMK_ENCRYPTED_KEY_LENGTH);
3132                 proto_tree_add_text(tree, tvb, offset, CMK_ENCRYPTED_KEY_LENGTH, "Encrypted Key data (%d bytes)", CMK_ENCRYPTED_KEY_LENGTH);
3133                 offset += CMK_ENCRYPTED_KEY_LENGTH;
3134         }
3135         if(CMK_KEY_ARG_LENGTH) {
3136                 tvb_ensure_bytes_exist(tvb, offset, CMK_KEY_ARG_LENGTH);
3137                 proto_tree_add_text(tree, tvb, offset, CMK_KEY_ARG_LENGTH, "IV data (%d bytes)", CMK_KEY_ARG_LENGTH);
3138                 offset += CMK_KEY_ARG_LENGTH;
3139         }
3140         if(CMK_VERIFY_PRELUDE) {
3141                 tvb_ensure_bytes_exist(tvb, offset, CMK_VERIFY_PRELUDE);
3142                 proto_tree_add_text(tree, tvb, offset, CMK_VERIFY_PRELUDE, "Verify Prelude data (%d bytes)", CMK_VERIFY_PRELUDE);
3143                 offset += CMK_VERIFY_PRELUDE;
3144         }
3145         if(CMK_CLIENT_CERT_LENGTH) {
3146                 tvb_ensure_bytes_exist(tvb, offset, CMK_CLIENT_CERT_LENGTH);
3147                 proto_tree_add_text(tree, tvb, offset, CMK_CLIENT_CERT_LENGTH, "Client Certificate data (%d bytes)", CMK_CLIENT_CERT_LENGTH);
3148                 offset += CMK_CLIENT_CERT_LENGTH;
3149         }
3150         if(CMK_RESPONSE_LENGTH) {
3151                 tvb_ensure_bytes_exist(tvb, offset, CMK_RESPONSE_LENGTH);
3152                 proto_tree_add_text(tree, tvb, offset, CMK_RESPONSE_LENGTH, "Response data (%d bytes)", CMK_RESPONSE_LENGTH);
3153                 offset += CMK_RESPONSE_LENGTH;
3154         }
3155 }
3156
3157 static void
3158 dissect_pct_msg_server_verify(tvbuff_t *tvb,
3159                                                         proto_tree *tree, guint32 offset)
3160 {
3161         guint16 SV_RESPONSE_LENGTH;
3162
3163         proto_tree_add_text(tree, tvb, offset, 1, "PAD");
3164         offset += 1;
3165
3166         proto_tree_add_text(tree, tvb, offset, 32, "Server Session ID data (32 bytes)");
3167         offset += 32;
3168
3169         SV_RESPONSE_LENGTH = tvb_get_ntohs(tvb, offset);
3170         proto_tree_add_text(tree, tvb, offset, 2, "Server Response Length: %d", SV_RESPONSE_LENGTH);
3171         offset += 2;
3172
3173         if(SV_RESPONSE_LENGTH) {
3174                 tvb_ensure_bytes_exist(tvb, offset, SV_RESPONSE_LENGTH);
3175                 proto_tree_add_text(tree, tvb, offset, SV_RESPONSE_LENGTH, "Server Response (%d bytes)", SV_RESPONSE_LENGTH);
3176                 offset += SV_RESPONSE_LENGTH;
3177         }
3178 }
3179
3180 static void
3181 dissect_pct_msg_error(tvbuff_t *tvb,
3182                                                         proto_tree *tree, guint32 offset)
3183 {
3184         guint16 ERROR_CODE, INFO_LEN;
3185
3186         ERROR_CODE = tvb_get_ntohs(tvb, offset);
3187         proto_tree_add_item(tree, hf_pct_msg_error_type, tvb, offset, 2, FALSE);
3188         offset += 2;
3189
3190         INFO_LEN = tvb_get_ntohs(tvb, offset);
3191         proto_tree_add_text(tree, tvb, offset, 2, "Eror Information Length: %d", INFO_LEN);
3192         offset += 2;
3193         if (ERROR_CODE == PCT_ERR_SPECS_MISMATCH && INFO_LEN == 6)
3194         {
3195                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_CIPHER");
3196                 offset += 1;
3197                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_HASH");
3198                 offset += 1;
3199                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_CERT");
3200                 offset += 1;
3201                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_EXCH");
3202                 offset += 1;
3203                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_CLIENT_CERT");
3204                 offset += 1;
3205                 proto_tree_add_text(tree, tvb, offset, 1, "SPECS_MISMATCH_CLIENT_SIG");
3206                 offset += 1;
3207         }
3208         else if(INFO_LEN) {
3209                 proto_tree_add_text(tree, tvb, offset, INFO_LEN, "Error Information dta (%d bytes)", INFO_LEN);
3210                 offset += INFO_LEN;
3211         }
3212 }
3213
3214 static void
3215 dissect_ssl2_hnd_client_master_key(tvbuff_t *tvb,
3216                                    proto_tree *tree, guint32 offset)
3217 {
3218     /* struct {
3219      *    uint8 msg_type;
3220      *    V2Cipherspec cipher;
3221      *    uint16 clear_key_length;
3222      *    uint16 encrypted_key_length;
3223      *    uint16 key_arg_length;
3224      *    opaque clear_key_data[V2ClientMasterKey.clear_key_length];
3225      *    opaque encrypted_key_data[V2ClientMasterKey.encrypted_key_length];
3226      *    opaque key_arg_data[V2ClientMasterKey.key_arg_length];
3227      * } V2ClientMasterKey;
3228      *
3229      * Note: when we get here, offset's already pointing at cipher
3230      */
3231     guint16 clear_key_length;
3232     guint16 encrypted_key_length;
3233     guint16 key_arg_length;
3234
3235     /* at this point, everything we do involves the tree,
3236      * so quit now if we don't have one ;-)
3237      */
3238     if (!tree)
3239     {
3240         return;
3241     }
3242
3243     /* show the selected cipher */
3244     proto_tree_add_item(tree, hf_ssl2_handshake_cipher_spec,
3245                         tvb, offset, 3, FALSE);
3246     offset += 3;
3247
3248     /* get the fixed fields */
3249     clear_key_length = tvb_get_ntohs(tvb, offset);
3250     proto_tree_add_item(tree, hf_ssl2_handshake_clear_key_len,
3251                         tvb, offset, 2, FALSE);
3252     offset += 2;
3253
3254     encrypted_key_length = tvb_get_ntohs(tvb, offset);
3255     proto_tree_add_item(tree, hf_ssl2_handshake_enc_key_len,
3256                         tvb, offset, 2, FALSE);
3257     offset += 2;
3258
3259     key_arg_length = tvb_get_ntohs(tvb, offset);
3260     proto_tree_add_item(tree, hf_ssl2_handshake_key_arg_len,
3261                         tvb, offset, 2, FALSE);
3262     offset += 2;
3263
3264     /* show the variable length fields */
3265     if (clear_key_length > 0)
3266     {
3267         tvb_ensure_bytes_exist(tvb, offset, clear_key_length);
3268         proto_tree_add_item(tree, hf_ssl2_handshake_clear_key,
3269                             tvb, offset, clear_key_length, FALSE);
3270         offset += clear_key_length;
3271     }
3272
3273     if (encrypted_key_length > 0)
3274     {
3275         tvb_ensure_bytes_exist(tvb, offset, encrypted_key_length);
3276         proto_tree_add_item(tree, hf_ssl2_handshake_enc_key,
3277                             tvb, offset, encrypted_key_length, FALSE);
3278         offset += encrypted_key_length;
3279     }
3280
3281     if (key_arg_length > 0)
3282     {
3283         tvb_ensure_bytes_exist(tvb, offset, key_arg_length);
3284         proto_tree_add_item(tree, hf_ssl2_handshake_key_arg,
3285                             tvb, offset, key_arg_length, FALSE);
3286         offset += key_arg_length;
3287     }
3288
3289 }
3290
3291 static void
3292 dissect_ssl2_hnd_server_hello(tvbuff_t *tvb,
3293                               proto_tree *tree, guint32 offset, packet_info *pinfo)
3294 {
3295     /* struct {
3296      *    uint8  msg_type;
3297      *    uint8  session_id_hit;
3298      *    uint8  certificate_type;
3299      *    uint16 server_version;
3300      *    uint16 certificate_length;
3301      *    uint16 cipher_specs_length;
3302      *    uint16 connection_id_length;
3303      *    opaque certificate_data[V2ServerHello.certificate_length];
3304      *    opaque cipher_specs_data[V2ServerHello.cipher_specs_length];
3305      *    opaque connection_id_data[V2ServerHello.connection_id_length];
3306      * } V2ServerHello;
3307      *
3308      * Note: when we get here, offset's already pointing at session_id_hit
3309      */
3310     guint16 certificate_length;
3311     guint16 cipher_spec_length;
3312     guint16 connection_id_length;
3313     guint16 version;
3314     proto_tree *ti;
3315     proto_tree *subtree;
3316
3317     /* everything we do only makes sense with a tree, so
3318      * quit now if we don't have one
3319      */
3320     if (!tree)
3321     {
3322         return;
3323     }
3324
3325     version = tvb_get_ntohs(tvb, offset + 2);
3326     if (!ssl_is_valid_ssl_version(version))
3327     {
3328         /* invalid version; probably encrypted data */
3329         return;
3330     }
3331
3332
3333     /* is there a hit? */
3334     proto_tree_add_item(tree, hf_ssl2_handshake_session_id_hit,
3335                         tvb, offset, 1, FALSE);
3336     offset++;
3337
3338     /* what type of certificate is this? */
3339     proto_tree_add_item(tree, hf_ssl2_handshake_cert_type,
3340                         tvb, offset, 1, FALSE);
3341     offset++;
3342
3343     /* now the server version */
3344     proto_tree_add_item(tree, hf_ssl_handshake_server_version,
3345                         tvb, offset, 2, FALSE);
3346     offset += 2;
3347
3348     /* get the fixed fields */
3349     certificate_length = tvb_get_ntohs(tvb, offset);
3350     proto_tree_add_uint(tree, hf_ssl_handshake_certificate_len,
3351                         tvb, offset, 2, certificate_length);
3352     offset += 2;
3353
3354     cipher_spec_length = tvb_get_ntohs(tvb, offset);
3355     proto_tree_add_uint(tree, hf_ssl2_handshake_cipher_spec_len,
3356                         tvb, offset, 2, cipher_spec_length);
3357     offset += 2;
3358
3359     connection_id_length = tvb_get_ntohs(tvb, offset);
3360     proto_tree_add_uint(tree, hf_ssl2_handshake_connection_id_len,
3361                         tvb, offset, 2, connection_id_length);
3362     offset += 2;
3363
3364     /* now the variable length fields */
3365     if (certificate_length > 0)
3366     {
3367         dissect_x509af_Certificate(FALSE, tvb, offset, pinfo, tree, hf_ssl_handshake_certificate);
3368         offset += certificate_length;
3369     }
3370
3371     if (cipher_spec_length > 0)
3372     {
3373         /* provide a collapsing node for the cipher specs */
3374         tvb_ensure_bytes_exist(tvb, offset, cipher_spec_length);
3375         ti = proto_tree_add_none_format(tree,
3376                                         hf_ssl_handshake_cipher_suites,
3377                                         tvb, offset, cipher_spec_length,
3378                                         "Cipher Specs (%u spec%s)",
3379                                         cipher_spec_length/3,
3380                                         plurality(cipher_spec_length/3, "", "s"));
3381         subtree = proto_item_add_subtree(ti, ett_ssl_cipher_suites);
3382         if (!subtree)
3383         {
3384             subtree = tree;
3385         }
3386
3387         /* iterate through the cipher specs */
3388         while (cipher_spec_length > 0)
3389         {
3390             proto_tree_add_item(subtree, hf_ssl2_handshake_cipher_spec,
3391                                 tvb, offset, 3, FALSE);
3392             offset += 3;
3393             cipher_spec_length -= 3;
3394         }
3395     }
3396
3397     if (connection_id_length > 0)
3398     {
3399         tvb_ensure_bytes_exist(tvb, offset, connection_id_length);
3400         proto_tree_add_item(tree, hf_ssl2_handshake_connection_id,
3401                             tvb, offset, connection_id_length, FALSE);
3402         offset += connection_id_length;
3403     }
3404
3405 }
3406
3407
3408 void ssl_set_master_secret(guint32 frame_num, address *addr_srv, address *addr_cli,
3409                            port_type ptype, guint32 port_srv, guint32 port_cli,
3410                            guint32 version, gint cipher, const guchar *_master_secret,
3411                            const guchar *_client_random, const guchar *_server_random,
3412                            guint32 client_seq, guint32 server_seq)
3413 {
3414   conversation_t *conversation = NULL;
3415   void *conv_data = NULL;
3416   SslDecryptSession *ssl = NULL;
3417   guint iv_len;
3418
3419   ssl_debug_printf("\nssl_set_master_secret enter frame #%u\n", frame_num);
3420
3421   conversation = find_conversation(frame_num, addr_srv, addr_cli, ptype, port_srv, port_cli, 0);
3422
3423   if (!conversation) {
3424     /* create a new conversation */
3425     conversation = conversation_new(frame_num, addr_srv, addr_cli, ptype, port_srv, port_cli, 0);
3426   }
3427   conv_data = conversation_get_proto_data(conversation, proto_ssl);
3428
3429   if (conv_data) {
3430     ssl = conv_data;
3431   } else {
3432     ssl = se_alloc0(sizeof(SslDecryptSession));
3433     ssl_session_init(ssl);
3434     ssl->version = SSL_VER_UNKNOWN;
3435     conversation_add_proto_data(conversation, proto_ssl, ssl);
3436   }
3437
3438   /* version */
3439   if ((ssl->version==SSL_VER_UNKNOWN) && (version!=SSL_VER_UNKNOWN)) {
3440     switch (version) {
3441       case SSL_VER_SSLv3:
3442         ssl->version = SSL_VER_SSLv3;
3443         ssl->version_netorder = SSLV3_VERSION;
3444         ssl->state |= SSL_VERSION;
3445         ssl_debug_printf("ssl_set_master_secret set version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
3446         break;
3447
3448       case SSL_VER_TLS:
3449         ssl->version = SSL_VER_TLS;
3450         ssl->version_netorder = TLSV1_VERSION;
3451         ssl->state |= SSL_VERSION;
3452         ssl_debug_printf("ssl_set_master_secret set version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
3453         break;
3454
3455       case SSL_VER_TLSv1DOT1:
3456         ssl->version = SSL_VER_TLSv1DOT1;
3457         ssl->version_netorder = TLSV1DOT1_VERSION;
3458         ssl->state |= SSL_VERSION;
3459         ssl_debug_printf("ssl_set_master_secret set version 0x%04X -> state 0x%02X\n", ssl->version_netorder, ssl->state);
3460         break;
3461     }
3462   }
3463
3464   /* cipher */
3465   if (cipher > 0) {
3466     ssl->cipher = cipher;
3467     if (ssl_find_cipher(ssl->cipher,&ssl->cipher_suite) < 0) {
3468         ssl_debug_printf("ssl_set_master_secret can't find cipher suite 0x%X\n", ssl->cipher);
3469     } else {
3470         ssl->state |= SSL_CIPHER;
3471         ssl_debug_printf("ssl_set_master_secret set CIPHER 0x%04X -> state 0x%02X\n", ssl->cipher, ssl->state);
3472     }
3473   }
3474
3475   /* client random */
3476   if (_client_random) {
3477     ssl_data_set(&ssl->client_random, _client_random, 32);
3478     ssl->state |= SSL_CLIENT_RANDOM;
3479     ssl_debug_printf("ssl_set_master_secret set CLIENT RANDOM -> state 0x%02X\n", ssl->state);
3480   }
3481
3482   /* server random */
3483   if (_server_random) {
3484     ssl_data_set(&ssl->server_random, _server_random, 32);
3485     ssl->state |= SSL_SERVER_RANDOM;
3486     ssl_debug_printf("ssl_set_master_secret set SERVER RANDOM -> state 0x%02X\n", ssl->state);
3487   }
3488
3489   /* master secret */
3490   if (_master_secret) {
3491     ssl_data_set(&ssl->master_secret, _master_secret, 48);
3492     ssl->state |= SSL_MASTER_SECRET;
3493     ssl_debug_printf("ssl_set_master_secret set MASTER SECRET -> state 0x%02X\n", ssl->state);
3494   }
3495
3496   if ((ssl->state &
3497           (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) !=
3498           (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET)) {
3499       ssl_debug_printf("ssl_set_master_secret not enough data to generate key (has 0x%02X but required 0x%02X)\n",
3500           ssl->state, (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION|SSL_MASTER_SECRET));
3501       return;
3502   }
3503
3504   ssl_debug_printf("ssl_set_master_secret trying to generate keys\n");
3505   if (ssl_generate_keyring_material(ssl)<0) {
3506       ssl_debug_printf("ssl_set_master_secret can't generate keyring material\n");
3507       return;
3508   }
3509   ssl->state |= SSL_HAVE_SESSION_KEY;
3510
3511   /* chenge ciphers immediately */
3512   ssl_change_cipher(ssl, TRUE);
3513   ssl_change_cipher(ssl, FALSE);
3514
3515   /* update seq numbers is available */
3516   if (ssl->client && (client_seq != (guint32)-1)) {
3517     ssl->client->seq = client_seq;
3518     ssl_debug_printf("ssl_set_master_secret client->seq updated to %u\n", ssl->client->seq);
3519   }
3520   if (ssl->server && (server_seq != (guint32)-1)) {
3521     ssl->server->seq = server_seq;
3522     ssl_debug_printf("ssl_set_master_secret server->seq updated to %u\n", ssl->server->seq);
3523   }
3524
3525   /* update IV from last data */
3526   iv_len = (ssl->cipher_suite.block>1) ? ssl->cipher_suite.block : 8;
3527   if (ssl->client && ((ssl->client->seq > 0) || (ssl->client_data_for_iv.data_len > iv_len))) {
3528     ssl_cipher_setiv(&ssl->client->evp, ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
3529     ssl_print_data("ssl_set_master_secret client IV updated",ssl->client_data_for_iv.data + ssl->client_data_for_iv.data_len - iv_len, iv_len);
3530   }
3531   if (ssl->server && ((ssl->server->seq > 0) || (ssl->server_data_for_iv.data_len > iv_len))) {
3532     ssl_cipher_setiv(&ssl->server->evp, ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
3533     ssl_print_data("ssl_set_master_secret server IV updated",ssl->server_data_for_iv.data + ssl->server_data_for_iv.data_len - iv_len, iv_len);
3534   }
3535 }
3536
3537
3538 /*********************************************************************
3539  *
3540  * Support Functions
3541  *
3542  *********************************************************************/
3543 #if 0
3544 static void
3545 ssl_set_conv_version(packet_info *pinfo, guint version)
3546 {
3547     conversation_t *conversation;
3548
3549     if (pinfo->fd->flags.visited)
3550     {
3551         /* We've already processed this frame; no need to do any more
3552          * work on it.
3553          */
3554         return;
3555     }
3556
3557     conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype,
3558                                      pinfo->srcport, pinfo->destport, 0);
3559
3560     if (conversation == NULL)
3561     {
3562         /* create a new conversation */
3563         conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, pinfo->ptype,
3564                                         pinfo->srcport, pinfo->destport, 0);
3565     }
3566
3567     if (conversation_get_proto_data(conversation, proto_ssl) != NULL)
3568     {
3569         /* get rid of the current data */
3570         conversation_delete_proto_data(conversation, proto_ssl);
3571     }
3572     conversation_add_proto_data(conversation, proto_ssl, GINT_TO_POINTER(version));
3573 }
3574 #endif
3575
3576 static gint
3577 ssl_is_valid_handshake_type(guint8 type)
3578 {
3579
3580     switch (type) {
3581     case SSL_HND_HELLO_REQUEST:
3582     case SSL_HND_CLIENT_HELLO:
3583     case SSL_HND_SERVER_HELLO:
3584     case SSL_HND_CERTIFICATE:
3585     case SSL_HND_SERVER_KEY_EXCHG:
3586     case SSL_HND_CERT_REQUEST:
3587     case SSL_HND_SVR_HELLO_DONE:
3588     case SSL_HND_CERT_VERIFY:
3589     case SSL_HND_CLIENT_KEY_EXCHG:
3590     case SSL_HND_FINISHED:
3591         return 1;
3592     }
3593     return 0;
3594 }
3595
3596 static gint
3597 ssl_is_valid_ssl_version(guint16 version)
3598 {
3599     const gchar *version_str;
3600     version_str = match_strval(version, ssl_versions);
3601     return version_str != NULL;
3602 }
3603
3604 static gint
3605 ssl_is_authoritative_version_message(guint8 content_type,
3606                                      guint8 next_byte)
3607 {
3608     if (content_type == SSL_ID_HANDSHAKE
3609         && ssl_is_valid_handshake_type(next_byte))
3610     {
3611         return (next_byte != SSL_HND_CLIENT_HELLO);
3612     }
3613     else if (ssl_is_valid_content_type(content_type)
3614              && content_type != SSL_ID_HANDSHAKE)
3615     {
3616         return 1;
3617     }
3618     return 0;
3619 }
3620
3621 static gint
3622 ssl_is_v2_client_hello(tvbuff_t *tvb, guint32 offset)
3623 {
3624     guint8 byte;
3625
3626     byte = tvb_get_guint8(tvb, offset);
3627     if (byte != 0x80)           /* v2 client hello should start this way */
3628     {
3629         return 0;
3630     }
3631
3632     byte = tvb_get_guint8(tvb, offset+2);
3633     if (byte != 0x01)           /* v2 client hello msg type */
3634     {
3635         return 0;
3636     }
3637
3638     /* 1 in 2^16 of being right; improve later if necessary */
3639     return 1;
3640 }
3641
3642 /* this applies a heuristic to determine whether
3643  * or not the data beginning at offset looks like a
3644  * valid sslv2 record.  this isn't really possible,
3645  * but we'll try to do a reasonable job anyway.
3646  */
3647 static gint
3648 ssl_looks_like_sslv2(tvbuff_t *tvb, guint32 offset)
3649 {
3650     /* here's the current approach:
3651      *
3652      * we only try to catch unencrypted handshake messages, so we can
3653      * assume that there is not padding.  This means that the
3654      * first byte must be >= 0x80 and there must be a valid sslv2
3655      * msg_type in the third byte
3656      */
3657
3658     /* get the first byte; must have high bit set */
3659     guint8 byte;
3660     byte = tvb_get_guint8(tvb, offset);
3661
3662     if (byte < 0x80)
3663     {
3664         return 0;
3665     }
3666
3667     /* get the supposed msg_type byte; since we only care about
3668      * unencrypted handshake messages (we can't tell the type for
3669      * encrypted messages), we just check against that list
3670      */
3671     byte = tvb_get_guint8(tvb, offset + 2);
3672     switch(byte) {
3673     case SSL2_HND_ERROR:
3674     case SSL2_HND_CLIENT_HELLO:
3675     case SSL2_HND_CLIENT_MASTER_KEY:
3676     case SSL2_HND_SERVER_HELLO:
3677     case PCT_MSG_CLIENT_MASTER_KEY:
3678     case PCT_MSG_ERROR:
3679         return 1;
3680     }
3681     return 0;
3682 }
3683
3684 /* this applies a heuristic to determine whether
3685  * or not the data beginning at offset looks like a
3686  * valid sslv3 record.  this is somewhat more reliable
3687  * than sslv2 due to the structure of the v3 protocol
3688  */
3689 static gint
3690 ssl_looks_like_sslv3(tvbuff_t *tvb, guint32 offset)
3691 {
3692     /* have to have a valid content type followed by a valid
3693      * protocol version
3694      */
3695     guint8 byte;
3696     guint16 version;
3697
3698     /* see if the first byte is a valid content type */
3699     byte = tvb_get_guint8(tvb, offset);
3700     if (!ssl_is_valid_content_type(byte))
3701     {
3702         return 0;
3703     }
3704
3705     /* now check to see if the version byte appears valid */
3706     version = tvb_get_ntohs(tvb, offset + 1);
3707     if (version != SSLV3_VERSION && version != TLSV1_VERSION && version != TLSV1DOT1_VERSION)
3708     {
3709         return 0;
3710     }
3711
3712     return 1;
3713 }
3714
3715 /* applies a heuristic to determine whether
3716  * or not the data beginning at offset looks
3717  * like a valid, unencrypted v2 handshake message.
3718  * since it isn't possible to completely tell random
3719  * data apart from a valid message without state,
3720  * we try to help the odds.
3721  */
3722 static gint
3723 ssl_looks_like_valid_v2_handshake(tvbuff_t *tvb, guint32 offset,
3724                                   guint32 record_length)
3725 {
3726     /* first byte should be a msg_type.
3727      *
3728      *   - we know we only see client_hello, client_master_key,
3729      *     and server_hello in the clear, so check to see if
3730      *     msg_type is one of those (this gives us a 3 in 2^8
3731      *     chance of saying yes with random payload)
3732      *
3733      *   - for those three types that we know about, do some
3734      *     further validation to reduce the chance of an error
3735      */
3736     guint8 msg_type;
3737     guint16 version;
3738     guint32 sum;
3739
3740     /* fetch the msg_type */
3741     msg_type = tvb_get_guint8(tvb, offset);
3742
3743     switch (msg_type) {
3744     case SSL2_HND_CLIENT_HELLO:
3745         /* version follows msg byte, so verify that this is valid */
3746         version = tvb_get_ntohs(tvb, offset+1);
3747         return ssl_is_valid_ssl_version(version);
3748         break;
3749
3750     case SSL2_HND_SERVER_HELLO:
3751         /* version is three bytes after msg_type */
3752         version = tvb_get_ntohs(tvb, offset+3);
3753         return ssl_is_valid_ssl_version(version);
3754         break;
3755
3756     case SSL2_HND_CLIENT_MASTER_KEY:
3757         /* sum of clear_key_length, encrypted_key_length, and key_arg_length
3758          * must be less than record length
3759          */
3760         sum  = tvb_get_ntohs(tvb, offset + 4); /* clear_key_length */
3761         sum += tvb_get_ntohs(tvb, offset + 6); /* encrypted_key_length */
3762         sum += tvb_get_ntohs(tvb, offset + 8); /* key_arg_length */
3763         if (sum > record_length)
3764         {
3765             return 0;
3766         }
3767         return 1;
3768         break;
3769
3770     default:
3771         return 0;
3772     }
3773     return 0;
3774 }
3775
3776 /* applies a heuristic to determine whether
3777  * or not the data beginning at offset looks
3778  * like a valid, unencrypted v2 handshake message.
3779  * since it isn't possible to completely tell random
3780  * data apart from a valid message without state,
3781  * we try to help the odds.
3782  */
3783 static gint
3784 ssl_looks_like_valid_pct_handshake(tvbuff_t *tvb, guint32 offset,
3785                                    guint32 record_length)
3786 {
3787     /* first byte should be a msg_type.
3788      *
3789      *   - we know we only see client_hello, client_master_key,
3790      *     and server_hello in the clear, so check to see if
3791      *     msg_type is one of those (this gives us a 3 in 2^8
3792      *     chance of saying yes with random payload)
3793      *
3794      *   - for those three types that we know about, do some
3795      *     further validation to reduce the chance of an error
3796      */
3797     guint8 msg_type;
3798     guint16 version;
3799     guint32 sum;
3800
3801     /* fetch the msg_type */
3802     msg_type = tvb_get_guint8(tvb, offset);
3803
3804     switch (msg_type) {
3805     case PCT_MSG_CLIENT_HELLO:
3806         /* version follows msg byte, so verify that this is valid */
3807         version = tvb_get_ntohs(tvb, offset+1);
3808         return version == PCT_VERSION_1;
3809         break;
3810
3811     case PCT_MSG_SERVER_HELLO:
3812         /* version is one byte after msg_type */
3813         version = tvb_get_ntohs(tvb, offset+2);
3814         return version == PCT_VERSION_1;
3815         break;
3816
3817     case PCT_MSG_CLIENT_MASTER_KEY:
3818         /* sum of various length fields must be less than record length */
3819         sum  = tvb_get_ntohs(tvb, offset + 6); /* clear_key_length */
3820         sum += tvb_get_ntohs(tvb, offset + 8); /* encrypted_key_length */
3821         sum += tvb_get_ntohs(tvb, offset + 10); /* key_arg_length */
3822         sum += tvb_get_ntohs(tvb, offset + 12); /* verify_prelude_length */
3823         sum += tvb_get_ntohs(tvb, offset + 14); /* client_cert_length */
3824         sum += tvb_get_ntohs(tvb, offset + 16); /* response_length */
3825         if (sum > record_length)
3826         {
3827             return 0;
3828         }
3829         return 1;
3830         break;
3831
3832     case PCT_MSG_SERVER_VERIFY:
3833         /* record is 36 bytes longer than response_length */
3834         sum = tvb_get_ntohs(tvb, offset + 34); /* response_length */
3835         if ((sum + 36) == record_length)
3836             return 1;
3837         else
3838             return 0;
3839         break;
3840
3841     default:
3842         return 0;
3843     }
3844     return 0;
3845 }
3846
3847
3848 /*********************************************************************
3849  *
3850  * Standard Wireshark Protocol Registration and housekeeping
3851  *
3852  *********************************************************************/
3853 void
3854 proto_register_ssl(void)
3855 {
3856
3857     /* Setup list of header fields See Section 1.6.1 for details*/
3858     static hf_register_info hf[] = {
3859         { &hf_ssl_record,
3860           { "Record Layer", "ssl.record",
3861             FT_NONE, BASE_NONE, NULL, 0x0,
3862             "Record layer", HFILL }
3863         },
3864         { &hf_ssl_record_content_type,
3865           { "Content Type", "ssl.record.content_type",
3866             FT_UINT8, BASE_DEC, VALS(ssl_31_content_type), 0x0,
3867             "Content type", HFILL}
3868         },
3869         { &hf_ssl2_msg_type,
3870           { "Handshake Message Type", "ssl.handshake.type",
3871             FT_UINT8, BASE_DEC, VALS(ssl_20_msg_types), 0x0,
3872             "SSLv2 handshake message type", HFILL}
3873         },
3874         { &hf_pct_msg_type,
3875           { "Handshake Message Type", "ssl.pct_handshake.type",
3876             FT_UINT8, BASE_DEC, VALS(pct_msg_types), 0x0,
3877             "PCT handshake message type", HFILL}
3878         },
3879         { &hf_ssl_record_version,
3880           { "Version", "ssl.record.version",
3881             FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
3882             "Record layer version.", HFILL }
3883         },
3884         { &hf_ssl_record_length,
3885           { "Length", "ssl.record.length",
3886             FT_UINT16, BASE_DEC, NULL, 0x0,
3887             "Length of SSL record data", HFILL }
3888         },
3889         { &hf_ssl_record_appdata,
3890           { "Encrypted Application Data", "ssl.app_data",
3891             FT_BYTES, BASE_HEX, NULL, 0x0,
3892             "Payload is encrypted application data", HFILL }
3893         },
3894
3895         { & hf_ssl2_record,
3896           { "SSLv2/PCT Record Header", "ssl.record",
3897             FT_NONE, BASE_DEC, NULL, 0x0,
3898             "SSLv2/PCT record data", HFILL }
3899         },
3900         { &hf_ssl2_record_is_escape,
3901           { "Is Escape", "ssl.record.is_escape",
3902             FT_BOOLEAN, BASE_NONE, NULL, 0x0,
3903             "Indicates a security escape", HFILL}
3904         },
3905         { &hf_ssl2_record_padding_length,
3906           { "Padding Length", "ssl.record.padding_length",
3907             FT_UINT8, BASE_DEC, NULL, 0x0,
3908             "Length of padding at end of record", HFILL }
3909         },
3910         { &hf_ssl_change_cipher_spec,
3911           { "Change Cipher Spec Message", "ssl.change_cipher_spec",
3912             FT_NONE, BASE_NONE, NULL, 0x0,
3913             "Signals a change in cipher specifications", HFILL }
3914         },
3915         { & hf_ssl_alert_message,
3916           { "Alert Message", "ssl.alert_message",
3917             FT_NONE, BASE_NONE, NULL, 0x0,
3918             "Alert message", HFILL }
3919         },
3920         { & hf_ssl_alert_message_level,
3921           { "Level", "ssl.alert_message.level",
3922             FT_UINT8, BASE_DEC, VALS(ssl_31_alert_level), 0x0,
3923             "Alert message level", HFILL }
3924         },
3925         { &hf_ssl_alert_message_description,
3926           { "Description", "ssl.alert_message.desc",
3927             FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
3928             "Alert message description", HFILL }
3929         },
3930         { &hf_ssl_handshake_protocol,
3931           { "Handshake Protocol", "ssl.handshake",
3932             FT_NONE, BASE_NONE, NULL, 0x0,
3933             "Handshake protocol message", HFILL}
3934         },
3935         { &hf_ssl_handshake_type,
3936           { "Handshake Type", "ssl.handshake.type",
3937             FT_UINT8, BASE_DEC, VALS(ssl_31_handshake_type), 0x0,
3938             "Type of handshake message", HFILL}
3939         },
3940         { &hf_ssl_handshake_length,
3941           { "Length", "ssl.handshake.length",
3942             FT_UINT24, BASE_DEC, NULL, 0x0,
3943             "Length of handshake message", HFILL }
3944         },
3945         { &hf_ssl_handshake_client_version,
3946           { "Version", "ssl.handshake.version",
3947             FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
3948             "Maximum version supported by client", HFILL }
3949         },
3950         { &hf_ssl_handshake_server_version,
3951           { "Version", "ssl.handshake.version",
3952             FT_UINT16, BASE_HEX, VALS(ssl_versions), 0x0,
3953             "Version selected by server", HFILL }
3954         },
3955         { &hf_ssl_handshake_random_time,
3956           { "gmt_unix_time", "ssl.handshake.random_time",
3957             FT_ABSOLUTE_TIME, 0, NULL, 0x0,
3958             "Unix time field of random structure", HFILL }
3959         },
3960         { &hf_ssl_handshake_random_bytes,
3961           { "random_bytes", "ssl.handshake.random_bytes",
3962             FT_BYTES, 0, NULL, 0x0,
3963             "Random challenge used to authenticate server", HFILL }
3964         },
3965         { &hf_ssl_handshake_cipher_suites_len,
3966           { "Cipher Suites Length", "ssl.handshake.cipher_suites_length",
3967             FT_UINT16, BASE_DEC, NULL, 0x0,
3968             "Length of cipher suites field", HFILL }
3969         },
3970         { &hf_ssl_handshake_cipher_suites,
3971           { "Cipher Suites", "ssl.handshake.ciphersuites",
3972             FT_NONE, BASE_NONE, NULL, 0x0,
3973             "List of cipher suites supported by client", HFILL }
3974         },
3975         { &hf_ssl_handshake_cipher_suite,
3976           { "Cipher Suite", "ssl.handshake.ciphersuite",
3977             FT_UINT16, BASE_HEX, VALS(ssl_31_ciphersuite), 0x0,
3978             "Cipher suite", HFILL }
3979         },
3980         { &hf_ssl2_handshake_cipher_spec,
3981           { "Cipher Spec", "ssl.handshake.cipherspec",
3982             FT_UINT24, BASE_HEX, VALS(ssl_20_cipher_suites), 0x0,
3983             "Cipher specification", HFILL }
3984         },
3985         { &hf_ssl_handshake_session_id,
3986           { "Session ID", "ssl.handshake.session_id",
3987             FT_BYTES, BASE_NONE, NULL, 0x0,
3988             "Identifies the SSL session, allowing later resumption", HFILL }
3989         },
3990         { &hf_ssl_handshake_comp_methods_len,
3991           { "Compression Methods Length", "ssl.handshake.comp_methods_length",
3992             FT_UINT8, BASE_DEC, NULL, 0x0,
3993             "Length of compression methods field", HFILL }
3994         },
3995         { &hf_ssl_handshake_comp_methods,
3996           { "Compression Methods", "ssl.handshake.comp_methods",
3997             FT_NONE, BASE_NONE, NULL, 0x0,
3998             "List of compression methods supported by client", HFILL }
3999         },
4000         { &hf_ssl_handshake_comp_method,
4001           { "Compression Method", "ssl.handshake.comp_method",
4002             FT_UINT8, BASE_DEC, VALS(ssl_31_compression_method), 0x0,
4003             "Compression Method", HFILL }
4004         },
4005         { &hf_ssl_handshake_extensions_len,
4006           { "Extensions Length", "ssl.handshake.extensions_length",
4007             FT_UINT16, BASE_DEC, NULL, 0x0,
4008             "Length of hello extensions", HFILL }
4009         },
4010         { &hf_ssl_handshake_extension_type,
4011           { "Type", "ssl.handshake.extension.type",
4012             FT_UINT16, BASE_HEX, VALS(tls_hello_extension_types), 0x0,
4013             "Hello extension type", HFILL }
4014         },
4015         { &hf_ssl_handshake_extension_len,
4016           { "Length", "ssl.handshake.extension.len",
4017             FT_UINT16, BASE_DEC, NULL, 0x0,
4018             "Length of a hello extension", HFILL }
4019         },
4020         { &hf_ssl_handshake_extension_data,
4021           { "Data", "ssl.handshake.extension.data",
4022             FT_BYTES, BASE_NONE, NULL, 0x0,
4023             "Hello Extension data", HFILL }
4024         },
4025         { &hf_ssl_handshake_certificates_len,
4026           { "Certificates Length", "ssl.handshake.certificates_length",
4027             FT_UINT24, BASE_DEC, NULL, 0x0,
4028             "Length of certificates field", HFILL }
4029         },
4030         { &hf_ssl_handshake_certificates,
4031           { "Certificates", "ssl.handshake.certificates",
4032             FT_NONE, BASE_NONE, NULL, 0x0,
4033             "List of certificates", HFILL }
4034         },
4035         { &hf_ssl_handshake_certificate,
4036           { "Certificate", "ssl.handshake.certificate",
4037             FT_BYTES, BASE_NONE, NULL, 0x0,
4038             "Certificate", HFILL }
4039         },
4040         { &hf_ssl_handshake_certificate_len,
4041           { "Certificate Length", "ssl.handshake.certificate_length",
4042             FT_UINT24, BASE_DEC, NULL, 0x0,
4043             "Length of certificate", HFILL }
4044         },
4045         { &hf_ssl_handshake_cert_types_count,
4046           { "Certificate types count", "ssl.handshake.cert_types_count",
4047             FT_UINT8, BASE_DEC, NULL, 0x0,
4048             "Count of certificate types", HFILL }
4049         },
4050         { &hf_ssl_handshake_cert_types,
4051           { "Certificate types", "ssl.handshake.cert_types",
4052             FT_NONE, BASE_NONE, NULL, 0x0,
4053             "List of certificate types", HFILL }
4054         },
4055         { &hf_ssl_handshake_cert_type,
4056           { "Certificate type", "ssl.handshake.cert_type",
4057             FT_UINT8, BASE_DEC, VALS(ssl_31_client_certificate_type), 0x0,
4058             "Certificate type", HFILL }
4059         },
4060         { &hf_ssl_handshake_finished,
4061           { "Verify Data", "ssl.handshake.verify_data",
4062             FT_NONE, BASE_NONE, NULL, 0x0,
4063             "Opaque verification data", HFILL }
4064         },
4065         { &hf_ssl_handshake_md5_hash,
4066           { "MD5 Hash", "ssl.handshake.md5_hash",
4067             FT_NONE, BASE_NONE, NULL, 0x0,
4068             "Hash of messages, master_secret, etc.", HFILL }
4069         },
4070         { &hf_ssl_handshake_sha_hash,
4071           { "SHA-1 Hash", "ssl.handshake.sha_hash",
4072             FT_NONE, BASE_NONE, NULL, 0x0,
4073             "Hash of messages, master_secret, etc.", HFILL }
4074         },
4075         { &hf_ssl_handshake_session_id_len,
4076           { "Session ID Length", "ssl.handshake.session_id_length",
4077             FT_UINT8, BASE_DEC, NULL, 0x0,
4078             "Length of session ID field", HFILL }
4079         },
4080         { &hf_ssl_handshake_dnames_len,
4081           { "Distinguished Names Length", "ssl.handshake.dnames_len",
4082             FT_UINT16, BASE_DEC, NULL, 0x0,
4083             "Length of list of CAs that server trusts", HFILL }
4084         },
4085         { &hf_ssl_handshake_dnames,
4086           { "Distinguished Names", "ssl.handshake.dnames",
4087             FT_NONE, BASE_NONE, NULL, 0x0,
4088             "List of CAs that server trusts", HFILL }
4089         },
4090         { &hf_ssl_handshake_dname_len,
4091           { "Distinguished Name Length", "ssl.handshake.dname_len",
4092             FT_UINT16, BASE_DEC, NULL, 0x0,
4093             "Length of distinguished name", HFILL }
4094         },
4095         { &hf_ssl_handshake_dname,
4096           { "Distinguished Name", "ssl.handshake.dname",
4097             FT_BYTES, BASE_NONE, NULL, 0x0,
4098             "Distinguished name of a CA that server trusts", HFILL }
4099         },
4100         { &hf_ssl2_handshake_challenge,
4101           { "Challenge", "ssl.handshake.challenge",
4102             FT_NONE, BASE_NONE, NULL, 0x0,
4103             "Challenge data used to authenticate server", HFILL }
4104         },
4105         { &hf_ssl2_handshake_cipher_spec_len,
4106           { "Cipher Spec Length", "ssl.handshake.cipher_spec_len",
4107             FT_UINT16, BASE_DEC, NULL, 0x0,
4108             "Length of cipher specs field", HFILL }
4109         },
4110         { &hf_ssl2_handshake_session_id_len,
4111           { "Session ID Length", "ssl.handshake.session_id_length",
4112             FT_UINT16, BASE_DEC, NULL, 0x0,
4113             "Length of session ID field", HFILL }
4114         },
4115         { &hf_ssl2_handshake_challenge_len,
4116           { "Challenge Length", "ssl.handshake.challenge_length",
4117             FT_UINT16, BASE_DEC, NULL, 0x0,
4118             "Length of challenge field", HFILL }
4119         },
4120         { &hf_ssl2_handshake_clear_key_len,
4121           { "Clear Key Data Length", "ssl.handshake.clear_key_length",
4122             FT_UINT16, BASE_DEC, NULL, 0x0,
4123             "Length of clear key data", HFILL }
4124         },
4125         { &hf_ssl2_handshake_enc_key_len,
4126           { "Encrypted Key Data Length", "ssl.handshake.encrypted_key_length",
4127             FT_UINT16, BASE_DEC, NULL, 0x0,
4128             "Length of encrypted key data", HFILL }
4129         },
4130         { &hf_ssl2_handshake_key_arg_len,
4131           { "Key Argument Length", "ssl.handshake.key_arg_length",
4132             FT_UINT16, BASE_DEC, NULL, 0x0,
4133             "Length of key argument", HFILL }
4134         },
4135         { &hf_ssl2_handshake_clear_key,
4136           { "Clear Key Data", "ssl.handshake.clear_key_data",
4137             FT_NONE, BASE_NONE, NULL, 0x0,
4138             "Clear portion of MASTER-KEY", HFILL }
4139         },
4140         { &hf_ssl2_handshake_enc_key,
4141           { "Encrypted Key", "ssl.handshake.encrypted_key",
4142             FT_NONE, BASE_NONE, NULL, 0x0,
4143             "Secret portion of MASTER-KEY encrypted to server", HFILL }
4144         },
4145         { &hf_ssl2_handshake_key_arg,
4146           { "Key Argument", "ssl.handshake.key_arg",
4147             FT_NONE, BASE_NONE, NULL, 0x0,
4148             "Key Argument (e.g., Initialization Vector)", HFILL }
4149         },
4150         { &hf_ssl2_handshake_session_id_hit,
4151           { "Session ID Hit", "ssl.handshake.session_id_hit",
4152             FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4153             "Did the server find the client's Session ID?", HFILL }
4154         },
4155         { &hf_ssl2_handshake_cert_type,
4156           { "Certificate Type", "ssl.handshake.cert_type",
4157             FT_UINT8, BASE_DEC, VALS(ssl_20_certificate_type), 0x0,
4158             "Certificate Type", HFILL }
4159         },
4160         { &hf_ssl2_handshake_connection_id_len,
4161           { "Connection ID Length", "ssl.handshake.connection_id_length",
4162             FT_UINT16, BASE_DEC, NULL, 0x0,
4163             "Length of connection ID", HFILL }
4164         },
4165         { &hf_ssl2_handshake_connection_id,
4166           { "Connection ID", "ssl.handshake.connection_id",
4167             FT_NONE, BASE_NONE, NULL, 0x0,
4168             "Server's challenge to client", HFILL }
4169         },
4170         { &hf_pct_handshake_cipher_spec,
4171           { "Cipher Spec", "pct.handshake.cipherspec",
4172                 FT_NONE, BASE_NONE, NULL, 0x0,
4173                 "PCT Cipher specification", HFILL }
4174         },
4175         { &hf_pct_handshake_cipher,
4176           { "Cipher", "pct.handshake.cipher",
4177                 FT_UINT16, BASE_HEX, VALS(pct_cipher_type), 0x0,
4178                 "PCT Ciper", HFILL }
4179         },
4180         { &hf_pct_handshake_hash_spec,
4181           { "Hash Spec", "pct.handshake.hashspec",
4182                 FT_NONE, BASE_NONE, NULL, 0x0,
4183                 "PCT Hash specification", HFILL }
4184         },
4185         { &hf_pct_handshake_hash,
4186           { "Hash", "pct.handshake.hash",
4187                 FT_UINT16, BASE_HEX, VALS(pct_hash_type), 0x0,
4188                 "PCT Hash", HFILL }
4189         },
4190         { &hf_pct_handshake_cert_spec,
4191           { "Cert Spec", "pct.handshake.certspec",
4192                 FT_NONE, BASE_NONE, NULL, 0x0,
4193                 "PCT Certificate specification", HFILL }
4194         },
4195         { &hf_pct_handshake_cert,
4196           { "Cert", "pct.handshake.cert",
4197                 FT_UINT16, BASE_HEX, VALS(pct_cert_type), 0x0,
4198                 "PCT Certificate", HFILL }
4199         },
4200         { &hf_pct_handshake_exch_spec,
4201           { "Exchange Spec", "pct.handshake.exchspec",
4202                 FT_NONE, BASE_NONE, NULL, 0x0,
4203                 "PCT Exchange specification", HFILL }
4204         },
4205         { &hf_pct_handshake_exch,
4206           { "Exchange", "pct.handshake.exch",
4207                 FT_UINT16, BASE_HEX, VALS(pct_exch_type), 0x0,
4208                 "PCT Exchange", HFILL }
4209         },
4210         { &hf_pct_handshake_sig,
4211           { "Sig Spec", "pct.handshake.sig",
4212                 FT_UINT16, BASE_HEX, VALS(pct_sig_type), 0x0,
4213                 "PCT Signature", HFILL }
4214         },
4215         { &hf_pct_msg_error_type,
4216           { "PCT Error Code", "pct.msg_error_code",
4217                 FT_UINT16, BASE_HEX, VALS(pct_error_code), 0x0,
4218                 "PCT Error Code", HFILL }
4219         },
4220         { &hf_pct_handshake_server_cert,
4221           { "Server Cert", "pct.handshake.server_cert",
4222                 FT_NONE, BASE_NONE, NULL , 0x0,
4223                 "PCT Server Certificate", HFILL }
4224         },
4225                 { &hf_ssl_segment_overlap,
4226                 { "Segment overlap",    "ssl.segment.overlap", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4227                         "Segment overlaps with other segments", HFILL }},
4228
4229                 { &hf_ssl_segment_overlap_conflict,
4230                 { "Conflicting data in segment overlap",        "ssl.segment.overlap.conflict", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4231                         "Overlapping segments contained conflicting data", HFILL }},
4232
4233                 { &hf_ssl_segment_multiple_tails,
4234                 { "Multiple tail segments found",       "ssl.segment.multipletails", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4235                         "Several tails were found when reassembling the pdu", HFILL }},
4236
4237                 { &hf_ssl_segment_too_long_fragment,
4238                 { "Segment too long",   "ssl.segment.toolongfragment", FT_BOOLEAN, BASE_NONE, NULL, 0x0,
4239                         "Segment contained data past end of the pdu", HFILL }},
4240
4241                 { &hf_ssl_segment_error,
4242                 { "Reassembling error", "ssl.segment.error", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4243                         "Reassembling error due to illegal segments", HFILL }},
4244
4245                 { &hf_ssl_segment,
4246                 { "SSL Segment", "ssl.segment", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4247                         "SSL Segment", HFILL }},
4248
4249                 { &hf_ssl_segments,
4250                 { "Reassembled SSL Segments", "ssl.segments", FT_NONE, BASE_NONE, NULL, 0x0,
4251                         "SSL Segments", HFILL }},
4252
4253                 { &hf_ssl_reassembled_in,
4254                 { "Reassembled PDU in frame", "ssl.reassembled_in", FT_FRAMENUM, BASE_NONE, NULL, 0x0,
4255                         "The PDU that doesn't end in this segment is reassembled in this frame", HFILL }},
4256     };
4257
4258     /* Setup protocol subtree array */
4259     static gint *ett[] = {
4260         &ett_ssl,
4261         &ett_ssl_record,
4262         &ett_ssl_alert,
4263         &ett_ssl_handshake,
4264         &ett_ssl_cipher_suites,
4265         &ett_ssl_comp_methods,
4266         &ett_ssl_extension,
4267         &ett_ssl_certs,
4268         &ett_ssl_cert_types,
4269         &ett_ssl_dnames,
4270         &ett_ssl_random,
4271         &ett_pct_cipher_suites,
4272         &ett_pct_hash_suites,
4273         &ett_pct_cert_suites,
4274         &ett_pct_exch_suites,
4275                 &ett_ssl_segments,
4276                 &ett_ssl_segment,
4277     };
4278
4279     /* Register the protocol name and description */
4280     proto_ssl = proto_register_protocol("Secure Socket Layer",
4281                                         "SSL", "ssl");
4282
4283     /* Required function calls to register the header fields and
4284      * subtrees used */
4285     proto_register_field_array(proto_ssl, hf, array_length(hf));
4286     proto_register_subtree_array(ett, array_length(ett));
4287
4288     {
4289       module_t *ssl_module = prefs_register_protocol(proto_ssl, proto_reg_handoff_ssl);
4290       prefs_register_bool_preference(ssl_module,
4291              "desegment_ssl_records",
4292              "Reassemble SSL records spanning multiple TCP segments",
4293              "Whether the SSL dissector should reassemble SSL records spanning multiple TCP segments. "
4294              "To use this option, you must also enable \"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.",
4295              &ssl_desegment);
4296       prefs_register_bool_preference(ssl_module,
4297              "desegment_ssl_application_data",
4298              "Reassemble SSL Application Data spanning multiple SSL records",
4299              "Whether the SSL dissector should reassemble SSL Application Data spanning multiple SSL records. ",
4300              &ssl_desegment_app_data);
4301 #ifdef HAVE_LIBGNUTLS
4302        prefs_register_string_preference(ssl_module, "keys_list", "RSA keys list",
4303              "Semicolon-separated list of private RSA keys used for SSL decryption; "
4304              "each list entry must be in the form of <ip>,<port>,<protocol>,<key_file_name>. "
4305              "<key_file_name> is the local file name of the RSA private key used by the specified server "
4306              "(or name of the file containing such a list)",
4307              (const gchar **)&ssl_keys_list);
4308         prefs_register_string_preference(ssl_module, "debug_file", "SSL debug file",
4309              "redirect ssl debug to file name; leave empty to disable debug, "
4310              "use \"" SSL_DEBUG_USE_STDERR "\" to redirect output to stderr\n",
4311              (const gchar **)&ssl_debug_file_name);
4312 #endif
4313     }
4314
4315     register_dissector("ssl", dissect_ssl, proto_ssl);
4316     ssl_handle = find_dissector("ssl");
4317
4318     ssl_associations = g_tree_new(ssl_association_cmp);
4319
4320     register_init_routine(ssl_init);
4321     ssl_lib_init();
4322     ssl_tap = register_tap("ssl");
4323     ssl_debug_printf("proto_register_ssl: registered tap %s:%d\n",
4324         "ssl", ssl_tap);
4325 }
4326
4327 /* If this dissector uses sub-dissector registration add a registration
4328  * routine.  This format is required because a script is used to find
4329  * these routines and create the code that calls these routines.
4330  */
4331 void
4332 proto_reg_handoff_ssl(void)
4333 {
4334
4335     /* parse key list */
4336     ssl_parse();
4337
4338     /* add ssl dissection to defaults ports */
4339     ssl_dissector_add(443, "http", TRUE);
4340     ssl_dissector_add(636, "ldap", TRUE);
4341     ssl_dissector_add(993, "imap", TRUE);
4342     ssl_dissector_add(995, "pop", TRUE);
4343 }
4344
4345 void
4346 ssl_dissector_add(guint port, const gchar *protocol, gboolean tcp)
4347 {
4348         SslAssociation *assoc;
4349
4350         assoc = ssl_association_find(ssl_associations, port, tcp);
4351         if (assoc) {
4352                 ssl_association_remove(ssl_associations, assoc);
4353         }
4354
4355     ssl_association_add(ssl_associations, ssl_handle, port, protocol, tcp, FALSE);
4356 }
4357
4358 void
4359 ssl_dissector_delete(guint port, const gchar *protocol, gboolean tcp)
4360 {
4361         SslAssociation *assoc;
4362
4363         assoc = ssl_association_find(ssl_associations, port, tcp);
4364         if (assoc && (assoc->handle == find_dissector(protocol))) {
4365                 ssl_association_remove(ssl_associations, assoc);
4366         }
4367 }