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