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