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