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