From Ales Kocourek
[metze/wireshark/wip.git] / epan / dissectors / packet-ssl-utils.c
1 /* packet-ssl-utils.c
2  * ssl manipulation functions
3  * By Paolo Abeni <paolo.abeni@email.com>
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
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #ifdef HAVE_LIBZ
34 #include <zlib.h>
35 #endif
36 #include "packet-ssl-utils.h"
37
38 #include <epan/emem.h>
39 #include <epan/strutil.h>
40 #include <wiretap/file_util.h>
41
42 /*
43  * Lookup tables
44  *
45  */
46 const value_string ssl_20_msg_types[] = {
47     { SSL2_HND_ERROR,               "Error" },
48     { SSL2_HND_CLIENT_HELLO,        "Client Hello" },
49     { SSL2_HND_CLIENT_MASTER_KEY,   "Client Master Key" },
50     { SSL2_HND_CLIENT_FINISHED,     "Client Finished" },
51     { SSL2_HND_SERVER_HELLO,        "Server Hello" },
52     { SSL2_HND_SERVER_VERIFY,       "Server Verify" },
53     { SSL2_HND_SERVER_FINISHED,     "Server Finished" },
54     { SSL2_HND_REQUEST_CERTIFICATE, "Request Certificate" },
55     { SSL2_HND_CLIENT_CERTIFICATE,  "Client Certificate" },
56     { 0x00, NULL }
57 };
58
59 const value_string ssl_20_cipher_suites[] = {
60     { 0x010080, "SSL2_RC4_128_WITH_MD5" },
61     { 0x020080, "SSL2_RC4_128_EXPORT40_WITH_MD5" },
62     { 0x030080, "SSL2_RC2_CBC_128_CBC_WITH_MD5" },
63     { 0x040080, "SSL2_RC2_CBC_128_CBC_WITH_MD5" },
64     { 0x050080, "SSL2_IDEA_128_CBC_WITH_MD5" },
65     { 0x060040, "SSL2_DES_64_CBC_WITH_MD5" },
66     { 0x0700c0, "SSL2_DES_192_EDE3_CBC_WITH_MD5" },
67     { 0x080080, "SSL2_RC4_64_WITH_MD5" },
68     { 0x000000, "TLS_NULL_WITH_NULL_NULL" },
69     { 0x000001, "TLS_RSA_WITH_NULL_MD5" },
70     { 0x000002, "TLS_RSA_WITH_NULL_SHA" },
71     { 0x000003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
72     { 0x000004, "TLS_RSA_WITH_RC4_128_MD5" },
73     { 0x000005, "TLS_RSA_WITH_RC4_128_SHA" },
74     { 0x000006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
75     { 0x000007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
76     { 0x000008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
77     { 0x000009, "TLS_RSA_WITH_DES_CBC_SHA" },
78     { 0x00000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
79     { 0x00000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
80     { 0x00000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
81     { 0x00000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
82     { 0x00000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
83     { 0x00000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
84     { 0x000010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
85     { 0x000011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
86     { 0x000012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
87     { 0x000013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
88     { 0x000014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
89     { 0x000015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
90     { 0x000016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
91     { 0x000017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
92     { 0x000018, "TLS_DH_anon_WITH_RC4_128_MD5" },
93     { 0x000019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
94     { 0x00001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
95     { 0x00001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
96     { 0x00001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
97     { 0x00001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
98     { 0x00001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
99     { 0x00002f, "TLS_RSA_WITH_AES_128_CBC_SHA" },
100     { 0x000030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
101     { 0x000031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
102     { 0x000032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
103     { 0x000033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
104     { 0x000034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
105     { 0x000035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
106     { 0x000036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
107     { 0x000037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
108     { 0x000038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" }, 
109     { 0x000039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
110     { 0x00003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
111     { 0x000041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
112     { 0x000042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
113     { 0x000043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
114     { 0x000044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
115     { 0x000045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
116     { 0x000046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
117     { 0x000047, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
118     { 0x000048, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
119     { 0x000049, "TLS_ECDH_ECDSA_WITH_DES_CBC_SHA" },
120     { 0x00004A, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
121     { 0x00004B, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
122     { 0x00004C, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
123     { 0x000060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
124     { 0x000061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
125     { 0x000062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
126     { 0x000063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
127     { 0x000064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
128     { 0x000065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
129     { 0x000066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
130     { 0x000084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
131     { 0x000085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
132     { 0x000086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
133     { 0x000087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
134     { 0x000088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
135     { 0x000089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
136     /* these from http://www.mozilla.org/projects/
137          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
138     { 0x00fefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
139     { 0x00feff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
140     { 0x00ffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
141     { 0x00ffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
142     /* Microsoft's old PCT protocol. These are from Eric Rescorla's
143        book "SSL and TLS" */
144     { 0x8f8001, "PCT_SSL_COMPAT | PCT_VERSION_1" },
145     { 0x800003, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509_CHAIN" },
146     { 0x800001, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509" },
147     { 0x810001, "PCT_SSL_HASH_TYPE | PCT1_HASH_MD5" },
148     { 0x810003, "PCT_SSL_HASH_TYPE | PCT1_HASH_SHA" },
149     { 0x820001, "PCT_SSL_EXCH_TYPE | PCT1_EXCH_RSA_PKCS1" },
150     { 0x830004, "PCT_SSL_CIPHER_TYPE_1ST_HALF | PCT1_CIPHER_RC4" },
151     { 0x848040, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_128 | PCT1_MAC_BITS_128" },
152     { 0x842840, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_40 | PCT1_MAC_BITS_128" },
153     /* note that ciphersuites of {0x00????} are TLS cipher suites in
154      * a sslv2 client hello message; the ???? above is the two-byte
155      * tls cipher suite id
156      */
157     { 0x00, NULL }
158 };
159
160 const value_string ssl_20_certificate_type[] = {
161     { 0x00, "N/A" },
162     { 0x01, "X.509 Certificate" },
163     { 0x00, NULL }
164 };
165
166 const value_string ssl_31_content_type[] = {
167     { 20, "Change Cipher Spec" },
168     { 21, "Alert" },
169     { 22, "Handshake" },
170     { 23, "Application Data" },
171     { 0x00, NULL }
172 };
173
174 const value_string ssl_versions[] = {
175     { 0xfeff, "DTLS 1.0" },
176     { 0x0100, "DTLS 1.0 (OpenSSL pre 0.9.8f)" },
177     { 0x0302, "TLS 1.1" },
178     { 0x0301, "TLS 1.0" },
179     { 0x0300, "SSL 3.0" },
180     { 0x0002, "SSL 2.0" },
181     { 0x00, NULL }
182 };
183
184 #if 0
185 /* XXX - would be used if we dissected the body of a Change Cipher Spec
186    message. */
187 const value_string ssl_31_change_cipher_spec[] = {
188     { 1, "Change Cipher Spec" },
189     { 0x00, NULL }
190 };
191 #endif
192
193 const value_string ssl_31_alert_level[] = {
194     { 1, "Warning" },
195     { 2, "Fatal" },
196     { 0x00, NULL }
197 };
198
199 const value_string ssl_31_alert_description[] = {
200     {  0,  "Close Notify" },
201     { 10,  "Unexpected Message" },
202     { 20,  "Bad Record MAC" },
203     { 21,  "Decryption Failed" },
204     { 22,  "Record Overflow" },
205     { 30,  "Decompression Failure" },
206     { 40,  "Handshake Failure" },
207     { 42,  "Bad Certificate" },
208     { 43,  "Unsupported Certificate" },
209     { 44,  "Certificate Revoked" },
210     { 45,  "Certificate Expired" },
211     { 46,  "Certificate Unknown" },
212     { 47,  "Illegal Parameter" },
213     { 48,  "Unknown CA" },
214     { 49,  "Access Denied" },
215     { 50,  "Decode Error" },
216     { 51,  "Decrypt Error" },
217     { 60,  "Export Restriction" },
218     { 70,  "Protocol Version" },
219     { 71,  "Insufficient Security" },
220     { 80,  "Internal Error" },
221     { 90,  "User Canceled" },
222     { 100, "No Renegotiation" },
223     { 0x00, NULL }
224 };
225
226 const value_string ssl_31_handshake_type[] = {
227     { SSL_HND_HELLO_REQUEST,     "Hello Request" },
228     { SSL_HND_CLIENT_HELLO,      "Client Hello" },
229     { SSL_HND_SERVER_HELLO,      "Server Hello" },
230     { SSL_HND_HELLO_VERIFY_REQUEST, "Hello Verify Request"},
231     { SSL_HND_CERTIFICATE,       "Certificate" },
232     { SSL_HND_SERVER_KEY_EXCHG,  "Server Key Exchange" },
233     { SSL_HND_CERT_REQUEST,      "Certificate Request" },
234     { SSL_HND_SVR_HELLO_DONE,    "Server Hello Done" },
235     { SSL_HND_CERT_VERIFY,       "Certificate Verify" },
236     { SSL_HND_CLIENT_KEY_EXCHG,  "Client Key Exchange" },
237     { SSL_HND_FINISHED,          "Finished" },
238     { 0x00, NULL }
239 };
240
241 const value_string ssl_31_compression_method[] = {
242     { 0, "null" },
243     { 1, "DEFLATE" },
244     { 64, "LZS" },
245     { 0x00, NULL }
246 };
247
248 #if 0
249 /* XXX - would be used if we dissected a Signature, as would be
250    seen in a server key exchange or certificate verify message. */
251 const value_string ssl_31_key_exchange_algorithm[] = {
252     { 0, "RSA" },
253     { 1, "Diffie Hellman" },
254     { 0x00, NULL }
255 };
256
257 const value_string ssl_31_signature_algorithm[] = {
258     { 0, "Anonymous" },
259     { 1, "RSA" },
260     { 2, "DSA" },
261     { 0x00, NULL }
262 };
263 #endif
264
265 const value_string ssl_31_client_certificate_type[] = {
266     { 1, "RSA Sign" },
267     { 2, "DSS Sign" },
268     { 3, "RSA Fixed DH" },
269     { 4, "DSS Fixed DH" },
270     { 0x00, NULL }
271 };
272
273 #if 0
274 /* XXX - would be used if we dissected exchange keys, as would be
275    seen in a client key exchange message. */
276 const value_string ssl_31_public_value_encoding[] = {
277     { 0, "Implicit" },
278     { 1, "Explicit" },
279     { 0x00, NULL }
280 };
281 #endif
282
283 const value_string ssl_31_ciphersuite[] = {
284     /* RFC 2246, RFC 4346 */
285     { 0x0000, "TLS_NULL_WITH_NULL_NULL" },
286     { 0x0001, "TLS_RSA_WITH_NULL_MD5" },
287     { 0x0002, "TLS_RSA_WITH_NULL_SHA" },
288     { 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
289     { 0x0004, "TLS_RSA_WITH_RC4_128_MD5" },
290     { 0x0005, "TLS_RSA_WITH_RC4_128_SHA" },
291     { 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
292     { 0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
293     { 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
294     { 0x0009, "TLS_RSA_WITH_DES_CBC_SHA" },
295     { 0x000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
296     { 0x000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
297     { 0x000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
298     { 0x000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
299     { 0x000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
300     { 0x000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
301     { 0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
302     { 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
303     { 0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
304     { 0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
305     { 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
306     { 0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
307     { 0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
308     { 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
309     { 0x0018, "TLS_DH_anon_WITH_RC4_128_MD5" },
310     { 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
311     { 0x001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
312     { 0x001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
313
314     { 0x001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
315     { 0x001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
316 #if 0 /* Because it clashes with KRB5, is never used any more, and is safe
317          to remove according to David Hopwood <david.hopwood@zetnet.co.uk>
318          of the ietf-tls list */
319     { 0x001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
320 #endif
321
322     /* RFC 2712 */
323     { 0x001E, "TLS_KRB5_WITH_DES_CBC_SHA" },
324     { 0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
325     { 0x0020, "TLS_KRB5_WITH_RC4_128_SHA" },
326     { 0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
327     { 0x0022, "TLS_KRB5_WITH_DES_CBC_MD5" },
328     { 0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
329     { 0x0024, "TLS_KRB5_WITH_RC4_128_MD5" },
330     { 0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
331     { 0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
332     { 0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
333     { 0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
334     { 0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
335     { 0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
336     { 0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
337
338     /* RFC 4785 */
339     { 0x002C, "TLS_PSK_WITH_NULL_SHA" },
340     { 0x002D, "TLS_DHE_PSK_WITH_NULL_SHA" },
341     { 0x002E, "TLS_RSA_PSK_WITH_NULL_SHA" },
342
343     /* RFC 3268 */
344     { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA" },
345     { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
346     { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
347     { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
348     { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
349     { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
350     { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
351     { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
352     { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
353     { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
354     { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
355     { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
356
357     /* ??? */
358     { 0x0060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
359     { 0x0061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
360
361     /* draft-ietf-tls-56-bit-ciphersuites-01.txt */
362     { 0x0062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
363     { 0x0063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
364     { 0x0064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
365     { 0x0065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
366     { 0x0066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
367
368     /* RFC 4132 */
369     { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
370     { 0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
371     { 0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
372     { 0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
373     { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
374     { 0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
375     { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
376     { 0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
377     { 0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
378     { 0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
379     { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
380     { 0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
381
382     /* RFC 4279 */
383     { 0x008A, "TLS_PSK_WITH_RC4_128_SHA" },
384     { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
385     { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
386     { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
387     { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
388     { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
389     { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
390     { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
391     { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
392     { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
393     { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
394     { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
395
396     /* RFC 4162 */
397     { 0x0096, "TLS_RSA_WITH_SEED_CBC_SHA" },
398     { 0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
399     { 0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
400     { 0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
401     { 0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
402     { 0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
403
404     /* From RFC 4492 */
405     { 0xc001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
406     { 0xc002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
407     { 0xc003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
408     { 0xc004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
409     { 0xc005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
410     { 0xc006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
411     { 0xc007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
412     { 0xc008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
413     { 0xc009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
414     { 0xc00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
415     { 0xc00b, "TLS_ECDH_RSA_WITH_NULL_SHA" },
416     { 0xc00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
417     { 0xc00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
418     { 0xc00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
419     { 0xc00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
420     { 0xc010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
421     { 0xc011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
422     { 0xc012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
423     { 0xc013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
424     { 0xc014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
425     { 0xc015, "TLS_ECDH_anon_WITH_NULL_SHA" },
426     { 0xc016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
427     { 0xc017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
428     { 0xc018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
429     { 0xc019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
430
431     /* draft-ietf-tls-srp-14.txt */
432     { 0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
433     { 0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
434     { 0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
435     { 0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
436     { 0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
437     { 0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
438     { 0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
439     { 0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
440     { 0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
441
442     /* these from http://www.mozilla.org/projects/
443          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
444     { 0xfefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
445     { 0xfeff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
446     { 0xffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
447     { 0xffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
448     /* note that ciphersuites 0xff00 - 0xffff are private */
449     { 0x00, NULL }
450 };
451
452 const value_string pct_msg_types[] = {
453     { PCT_MSG_CLIENT_HELLO,         "Client Hello" },
454     { PCT_MSG_SERVER_HELLO,         "Server Hello" },
455     { PCT_MSG_CLIENT_MASTER_KEY,    "Client Master Key" },
456     { PCT_MSG_SERVER_VERIFY,        "Server Verify" },
457     { PCT_MSG_ERROR,                "Error" },
458     { 0x00, NULL }
459 };
460
461 const value_string pct_cipher_type[] = {
462         { PCT_CIPHER_DES, "DES" },
463         { PCT_CIPHER_IDEA, "IDEA" },
464         { PCT_CIPHER_RC2, "RC2" },
465         { PCT_CIPHER_RC4, "RC4" },
466         { PCT_CIPHER_DES_112, "DES 112 bit" },
467         { PCT_CIPHER_DES_168, "DES 168 bit" },
468         { 0x00, NULL }
469 };
470
471 const value_string pct_hash_type[] = {
472         { PCT_HASH_MD5, "MD5" },
473         { PCT_HASH_MD5_TRUNC_64, "MD5_TRUNC_64"},
474         { PCT_HASH_SHA, "SHA"},
475         { PCT_HASH_SHA_TRUNC_80, "SHA_TRUNC_80"},
476         { PCT_HASH_DES_DM, "DES_DM"},
477         { 0x00, NULL }
478 };
479
480 const value_string pct_cert_type[] = {
481         { PCT_CERT_NONE, "None" },
482         { PCT_CERT_X509, "X.509" },
483         { PCT_CERT_PKCS7, "PKCS #7" },
484         { 0x00, NULL }
485 };
486 const value_string pct_sig_type[] = {
487         { PCT_SIG_NONE, "None" },
488         { PCT_SIG_RSA_MD5, "MD5" },
489         { PCT_SIG_RSA_SHA, "RSA SHA" },
490         { PCT_SIG_DSA_SHA, "DSA SHA" },
491         { 0x00, NULL }
492 };
493
494 const value_string pct_exch_type[] = {
495         { PCT_EXCH_RSA_PKCS1, "RSA PKCS#1" },
496         { PCT_EXCH_RSA_PKCS1_TOKEN_DES, "RSA PKCS#1 Token DES" },
497         { PCT_EXCH_RSA_PKCS1_TOKEN_DES3, "RSA PKCS#1 Token 3DES" },
498         { PCT_EXCH_RSA_PKCS1_TOKEN_RC2, "RSA PKCS#1 Token RC-2" },
499         { PCT_EXCH_RSA_PKCS1_TOKEN_RC4, "RSA PKCS#1 Token RC-4" },
500         { PCT_EXCH_DH_PKCS3, "DH PKCS#3" },
501         { PCT_EXCH_DH_PKCS3_TOKEN_DES, "DH PKCS#3 Token DES" },
502         { PCT_EXCH_DH_PKCS3_TOKEN_DES3, "DH PKCS#3 Token 3DES" },
503         { PCT_EXCH_FORTEZZA_TOKEN, "Fortezza" },
504         { 0x00, NULL }
505 };
506
507 const value_string pct_error_code[] = {
508         { PCT_ERR_BAD_CERTIFICATE, "PCT_ERR_BAD_CERTIFICATE" },
509         { PCT_ERR_CLIENT_AUTH_FAILED, "PCT_ERR_CLIENT_AUTH_FAILE" },
510         { PCT_ERR_ILLEGAL_MESSAGE, "PCT_ERR_ILLEGAL_MESSAGE" },
511         { PCT_ERR_INTEGRITY_CHECK_FAILED, "PCT_ERR_INTEGRITY_CHECK_FAILED" },
512         { PCT_ERR_SERVER_AUTH_FAILED, "PCT_ERR_SERVER_AUTH_FAILED" },
513         { PCT_ERR_SPECS_MISMATCH, "PCT_ERR_SPECS_MISMATCH" },
514         { 0x00, NULL }
515 };
516
517 /* RFC 4366 */
518 const value_string tls_hello_extension_types[] = {
519         { 0, "server_name" },
520         { 1, "max_fragment_length" },
521         { 2, "client_certificate_url" },
522         { 3, "trusted_ca_keys" },
523         { 4, "truncated_hmac" },
524         { 5, "status_request" },
525         { 6, "user_mapping" },
526         { 7, "Reserved" },
527         { 8, "Reserved" },
528         { 9, "cert_type" },
529         { 10, "elliptic_curves" },
530         { 11, "ec_point_formats" },
531         { 35, "SessionTicket TLS" },
532         { 0, NULL }
533 };
534
535
536 /* we keep this internal to packet-ssl-utils, as there should be
537    no need to access it any other way.
538
539    This also allows us to hide the dependency on zlib.
540 */
541 struct _SslDecompress {
542     gint compression;
543 #ifdef HAVE_LIBZ
544     z_stream istream;
545 #endif
546 };
547
548 static gint
549 ssl_data_alloc(StringInfo* str, guint len)
550 {
551     str->data = g_malloc(len);
552     if (!str->data)
553         return -1;
554     str->data_len = len;
555     return 0;
556 }
557
558 void
559 ssl_data_set(StringInfo* str, const guchar* data, guint len)
560 {
561     memcpy(str->data, data, len);
562     str->data_len = len;
563 }
564
565 #ifdef HAVE_LIBGNUTLS
566
567 static gint ver_major, ver_minor, ver_patch;
568
569 /* hmac abstraction layer */
570 #define SSL_HMAC gcry_md_hd_t
571
572 static inline void
573 ssl_hmac_init(SSL_HMAC* md, const void * key, gint len, gint algo)
574 {
575     gcry_md_open(md,algo, GCRY_MD_FLAG_HMAC);
576     gcry_md_setkey (*(md), key, len);
577 }
578 static inline void
579 ssl_hmac_update(SSL_HMAC* md, const void* data, gint len)
580 {
581     gcry_md_write(*(md), data, len);
582 }
583 static inline void
584 ssl_hmac_final(SSL_HMAC* md, guchar* data, guint* datalen)
585 {
586     gint algo;
587     guint len;
588     algo = gcry_md_get_algo (*(md));
589     len = gcry_md_get_algo_dlen(algo);
590     memcpy(data, gcry_md_read(*(md), algo), len);
591     *datalen =len;
592 }
593 static inline void
594 ssl_hmac_cleanup(SSL_HMAC* md)
595 {
596     gcry_md_close(*(md));
597 }
598
599 /* memory digest abstraction layer*/
600 #define SSL_MD gcry_md_hd_t
601
602 static inline void
603 ssl_md_init(SSL_MD* md, gint algo)
604 {
605     gcry_md_open(md,algo, 0);
606 }
607 static inline void
608 ssl_md_update(SSL_MD* md, guchar* data, gint len)
609 {
610     gcry_md_write(*(md), data, len);
611 }
612 static inline void
613 ssl_md_final(SSL_MD* md, guchar* data, guint* datalen)
614 {
615     gint algo;
616     gint len;
617     algo = gcry_md_get_algo (*(md));
618     len = gcry_md_get_algo_dlen (algo);
619     memcpy(data, gcry_md_read(*(md),  algo), len);
620     *datalen = len;
621 }
622 static inline void
623 ssl_md_cleanup(SSL_MD* md)
624 {
625     gcry_md_close(*(md));
626 }
627
628 /* md5 /sha abstraction layer */
629 #define SSL_SHA_CTX gcry_md_hd_t
630 #define SSL_MD5_CTX gcry_md_hd_t
631
632 static inline void
633 ssl_sha_init(SSL_SHA_CTX* md)
634 {
635     gcry_md_open(md,GCRY_MD_SHA1, 0);
636 }
637 static inline void
638 ssl_sha_update(SSL_SHA_CTX* md, guchar* data, gint len)
639 {
640     gcry_md_write(*(md), data, len);
641 }
642 static inline void
643 ssl_sha_final(guchar* buf, SSL_SHA_CTX* md)
644 {
645     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_SHA1),
646         gcry_md_get_algo_dlen(GCRY_MD_SHA1));
647 }
648 static inline void
649 ssl_sha_cleanup(SSL_SHA_CTX* md)
650 {
651     gcry_md_close(*(md));
652 }
653
654 static inline gint
655 ssl_md5_init(SSL_MD5_CTX* md)
656 {
657     return gcry_md_open(md,GCRY_MD_MD5, 0);
658 }
659 static inline void
660 ssl_md5_update(SSL_MD5_CTX* md, guchar* data, gint len)
661 {
662     gcry_md_write(*(md), data, len);
663 }
664 static inline void
665 ssl_md5_final(guchar* buf, SSL_MD5_CTX* md)
666 {
667     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_MD5),
668         gcry_md_get_algo_dlen(GCRY_MD_MD5));
669 }
670 static inline void
671 ssl_md5_cleanup(SSL_MD5_CTX* md)
672 {
673     gcry_md_close(*(md));
674 }
675
676 gint
677 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher, guchar* iv, gint iv_len)
678 {
679   /* guchar * ivp; */
680   gint ret;
681   /* gint i; */
682   gcry_cipher_hd_t c;
683   ret=0;
684   c=(gcry_cipher_hd_t)*cipher;
685
686   ssl_debug_printf("--------------------------------------------------------------------");
687   /*for(ivp=c->iv,i=0; i < iv_len; i++ )
688     {
689       ssl_debug_printf("%d ",ivp[i]);
690       i++;
691     }
692   */
693   ssl_debug_printf("--------------------------------------------------------------------");
694   ret = gcry_cipher_setiv(*(cipher), iv, iv_len);
695   /*for(ivp=c->iv,i=0; i < iv_len; i++ )
696     {
697       ssl_debug_printf("%d ",ivp[i]);
698       i++;
699     }
700   */
701   ssl_debug_printf("--------------------------------------------------------------------");
702   return ret;
703 }
704 /* stream cipher abstraction layer*/
705 static gint
706 ssl_cipher_init(gcry_cipher_hd_t *cipher, gint algo, guchar* sk,
707         guchar* iv, gint mode)
708 {
709     gint gcry_modes[]={GCRY_CIPHER_MODE_STREAM,GCRY_CIPHER_MODE_CBC};
710     gint err;
711     err = gcry_cipher_open(cipher, algo, gcry_modes[mode], 0);
712     if (err !=0)
713         return  -1;
714     err = gcry_cipher_setkey(*(cipher), sk, gcry_cipher_get_algo_keylen (algo));
715     if (err != 0)
716         return -1;
717     err = gcry_cipher_setiv(*(cipher), iv, gcry_cipher_get_algo_blklen (algo));
718     if (err != 0)
719         return -1;
720     return 0;
721 }
722 static inline gint
723 ssl_cipher_decrypt(gcry_cipher_hd_t *cipher, guchar * out, gint outl,
724                    const guchar * in, gint inl)
725 {
726     return gcry_cipher_decrypt ( *(cipher), out, outl, in, inl);
727 }
728 static inline gint
729 ssl_get_digest_by_name(const gchar*name)
730 {
731     return gcry_md_map_name(name);
732 }
733 static inline gint
734 ssl_get_cipher_by_name(const gchar* name)
735 {
736     return gcry_cipher_map_name(name);
737 }
738
739 static inline void
740 ssl_cipher_cleanup(gcry_cipher_hd_t *cipher)
741 {
742     gcry_cipher_close(*cipher);
743     *cipher = NULL;
744 }
745
746 /* private key abstraction layer */
747 static inline gint
748 ssl_get_key_len(SSL_PRIVATE_KEY* pk) {return gcry_pk_get_nbits (pk); }
749
750 gcry_err_code_t
751 _gcry_rsa_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
752                    gcry_mpi_t *skey, gint flags);
753
754 #define PUBKEY_FLAG_NO_BLINDING (1 << 0)
755
756 /* decrypt data with private key. Store decrypted data directly into input
757  * buffer */
758 int
759 ssl_private_decrypt(guint len, guchar* encr_data, SSL_PRIVATE_KEY* pk)
760 {
761     gint rc;
762     size_t decr_len;
763     gcry_sexp_t  s_data, s_plain;
764     gcry_mpi_t encr_mpi;
765     size_t i, encr_len;
766     guchar* decr_data_ptr;
767     gcry_mpi_t text;
768     decr_len = 0;
769     encr_len = len;
770     text=NULL;
771     /* build up a mpi rappresentation for encrypted data */
772     rc = gcry_mpi_scan(&encr_mpi, GCRYMPI_FMT_USG,encr_data, encr_len, &encr_len);
773     if (rc != 0 ) {
774         ssl_debug_printf("pcry_private_decrypt: can't convert encr_data to mpi (size %d):%s\n",
775             len, gcry_strerror(rc));
776         return 0;
777     }
778
779 #ifndef SSL_FAST
780     /* put the data into a simple list */
781     rc = gcry_sexp_build(&s_data, NULL, "(enc-val(rsa(a%m)))", encr_mpi);
782     if (rc != 0) {
783         ssl_debug_printf("pcry_private_decrypt: can't build encr_sexp:%s \n",
784              gcry_strerror(rc));
785         return 0;
786     }
787
788     /* pass it to libgcrypt */
789     rc = gcry_pk_decrypt(&s_plain, s_data, pk);
790     gcry_sexp_release(s_data);
791     if (rc != 0)
792     {
793         ssl_debug_printf("pcry_private_decrypt: can't decrypt key:%s\n",
794             gcry_strerror(rc));
795         goto out;
796     }
797
798     /* convert plain text sexp to mpi format */
799     text = gcry_sexp_nth_mpi(s_plain, 0, 0);
800
801     /* compute size requested for plaintext buffer */
802     decr_len = len;
803     if (gcry_mpi_print(GCRYMPI_FMT_USG, NULL, decr_len, &decr_len, text) != 0) {
804         ssl_debug_printf("pcry_private_decrypt: can't compute decr size:%s\n",
805             gcry_strerror(rc));
806         decr_len = 0;
807         goto out;
808     }
809
810     /* sanity check on out buffer */
811     if (decr_len > len) {
812         ssl_debug_printf("pcry_private_decrypt: decrypted data is too long ?!? (%zd max %d)\n",
813             decr_len, len);
814         return 0;
815     }
816
817     /* write plain text to encrypted data buffer */
818     decr_data_ptr = encr_data;
819     if (gcry_mpi_print( GCRYMPI_FMT_USG, decr_data_ptr, decr_len, &decr_len,
820             text) != 0) {
821         ssl_debug_printf("pcry_private_decrypt: can't print decr data to mpi (size %zd):%s\n",
822             decr_len, gcry_strerror(rc));
823         g_free(decr_data_ptr);
824         decr_len = 0;
825         goto out;
826     }
827
828     /* strip the padding*/
829     rc = 0;
830     for (i = 1; i < decr_len; i++) {
831         if (decr_data_ptr[i] == 0) {
832             rc = i+1;
833             break;
834         }
835     }
836
837     ssl_debug_printf("pcry_private_decrypt: stripping %d bytes, decr_len %zd\n",
838         rc, decr_len);
839     ssl_print_data("decrypted_unstrip_pre_master", decr_data_ptr, decr_len);
840     g_memmove(decr_data_ptr, &decr_data_ptr[rc], decr_len - rc);
841     decr_len -= rc;
842
843 out:
844     gcry_sexp_release(s_plain);
845 #else /* SSL_FAST */
846     rc = _gcry_rsa_decrypt(0, &text,  &encr_mpi, pk,0);
847     gcry_mpi_print( GCRYMPI_FMT_USG, 0, 0, &decr_len, text);
848
849     /* sanity check on out buffer */
850     if (decr_len > len) {
851         ssl_debug_printf("pcry_private_decrypt: decrypted data is too long ?!? (%d max %d)\n",
852             decr_len, len);
853         return 0;
854     }
855
856     /* write plain text to newly allocated buffer */
857     decr_data_ptr = encr_data;
858     if (gcry_mpi_print( GCRYMPI_FMT_USG, decr_data_ptr, decr_len, &decr_len,
859             text) != 0) {
860         ssl_debug_printf("pcry_private_decrypt: can't print decr data to mpi (size %d):%s\n",
861             decr_len, gcry_strerror(rc));
862         return 0;
863     }
864
865     /* strip the padding*/
866     rc = 0;
867     for (i = 1; i < decr_len; i++) {
868         if (decr_data_ptr[i] == 0) {
869             rc = i+1;
870             break;
871         }
872     }
873
874     ssl_debug_printf("pcry_private_decrypt: stripping %d bytes, decr_len %d\n",
875         rc, decr_len);
876     ssl_print_data("decrypted_unstrip_pre_master", decr_data_ptr, decr_len);
877     g_memmove(decr_data_ptr, &decr_data_ptr[rc], decr_len - rc);
878     decr_len -= rc;
879 #endif /* SSL_FAST */
880     gcry_mpi_release(text);
881     return decr_len;
882 }
883
884 /* stringinfo interface */
885 static gint
886 ssl_data_realloc(StringInfo* str, guint len)
887 {
888     str->data = g_realloc(str->data, len);
889     if (!str->data)
890         return -1;
891     str->data_len = len;
892     return 0;
893 }
894
895 static gint
896 ssl_data_copy(StringInfo* dst, StringInfo* src)
897 {
898     if (dst->data_len < src->data_len) {
899       if (ssl_data_realloc(dst, src->data_len))
900         return -1;
901     }
902     memcpy(dst->data, src->data, src->data_len);
903     dst->data_len = src->data_len;
904     return 0;
905 }
906
907 #define PRF(ssl,secret,usage,rnd1,rnd2,out) ((ssl->version_netorder==SSLV3_VERSION)? \
908         ssl3_prf(secret,usage,rnd1,rnd2,out): \
909         tls_prf(secret,usage,rnd1,rnd2,out))
910
911 static const gchar *digests[]={
912      "MD5",
913      "SHA1"
914 };
915
916 static const gchar *ciphers[]={
917      "DES",
918      "3DES",
919      "ARCFOUR", /* gnutls does not support rc4, but this should be 100% compatible*/
920      "RC2",
921      "IDEA",
922      "AES",
923      "AES256",
924      "*UNKNOWN*"
925 };
926
927 /* look in openssl/ssl/ssl_lib.c for a complete list of available cipersuite*/
928 static SslCipherSuite cipher_suites[]={
929     {1,KEX_RSA,SIG_RSA,ENC_NULL,0,0,0,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
930     {2,KEX_RSA,SIG_RSA,ENC_NULL,0,0,0,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
931     {3,KEX_RSA,SIG_RSA,ENC_RC4,1,128,40,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
932     {4,KEX_RSA,SIG_RSA,ENC_RC4,1,128,128,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
933     {5,KEX_RSA,SIG_RSA,ENC_RC4,1,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
934     {6,KEX_RSA,SIG_RSA,ENC_RC2,8,128,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
935     {7,KEX_RSA,SIG_RSA,ENC_IDEA,8,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
936     {8,KEX_RSA,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
937     {9,KEX_RSA,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
938     {10,KEX_RSA,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
939     {11,KEX_DH,SIG_DSS,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
940     {12,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
941     {13,KEX_DH,SIG_DSS,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
942     {14,KEX_DH,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
943     {15,KEX_DH,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
944     {16,KEX_DH,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
945     {17,KEX_DH,SIG_DSS,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
946     {18,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
947     {19,KEX_DH,SIG_DSS,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
948     {20,KEX_DH,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
949     {21,KEX_DH,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
950     {22,KEX_DH,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
951     {23,KEX_DH,SIG_NONE,ENC_RC4,1,128,40,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
952     {24,KEX_DH,SIG_NONE,ENC_RC4,1,128,128,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
953     {25,KEX_DH,SIG_NONE,ENC_DES,8,64,40,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
954     {26,KEX_DH,SIG_NONE,ENC_DES,8,64,64,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
955     {27,KEX_DH,SIG_NONE,ENC_3DES,8,192,192,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
956     {47,KEX_RSA,SIG_RSA,ENC_AES,16,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
957     {53,KEX_RSA,SIG_RSA,ENC_AES256,16,256,256,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
958     {96,KEX_RSA,SIG_RSA,ENC_RC4,1,128,56,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
959     {97,KEX_RSA,SIG_RSA,ENC_RC2,1,128,56,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
960     {98,KEX_RSA,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
961     {99,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,16,1, SSL_CIPHER_MODE_STREAM},
962     {100,KEX_RSA,SIG_RSA,ENC_RC4,1,128,56,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
963     {101,KEX_DH,SIG_DSS,ENC_RC4,1,128,56,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
964     {102,KEX_DH,SIG_DSS,ENC_RC4,1,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
965     {-1, 0,0,0,0,0,0,0,0,0, 0}
966 };
967
968 #define MAX_BLOCK_SIZE 16
969 #define MAX_KEY_SIZE 32
970
971 int
972 ssl_find_cipher(int num,SslCipherSuite* cs)
973 {
974     SslCipherSuite *c;
975
976     for(c=cipher_suites;c->number!=-1;c++){
977         if(c->number==num){
978             *cs=*c;
979             return 0;
980         }
981     }
982
983     return -1;
984 }
985
986 static gint
987 tls_hash(StringInfo* secret,
988         StringInfo* seed, gint md, StringInfo* out)
989 {
990     guint8 *ptr;
991     guint left;
992     gint tocpy;
993     guint8 *A;
994     guint8 _A[20],tmp[20];
995     guint A_l,tmp_l;
996     SSL_HMAC hm;
997     ptr=out->data;
998     left=out->data_len;
999
1000
1001     ssl_print_string("tls_hash: hash secret", secret);
1002     ssl_print_string("tls_hash: hash seed", seed);
1003     A=seed->data;
1004     A_l=seed->data_len;
1005
1006     while(left){
1007         ssl_hmac_init(&hm,secret->data,secret->data_len,md);
1008         ssl_hmac_update(&hm,A,A_l);
1009         ssl_hmac_final(&hm,_A,&A_l);
1010         ssl_hmac_cleanup(&hm);
1011         A=_A;
1012
1013         ssl_hmac_init(&hm,secret->data,secret->data_len,md);
1014         ssl_hmac_update(&hm,A,A_l);
1015         ssl_hmac_update(&hm,seed->data,seed->data_len);
1016         ssl_hmac_final(&hm,tmp,&tmp_l);
1017         ssl_hmac_cleanup(&hm);
1018
1019         tocpy=MIN(left,tmp_l);
1020         memcpy(ptr,tmp,tocpy);
1021         ptr+=tocpy;
1022         left-=tocpy;
1023     }
1024
1025     ssl_print_string("hash out", out);
1026     return (0);
1027 }
1028
1029 static gint
1030 tls_prf(StringInfo* secret, const gchar *usage,
1031         StringInfo* rnd1, StringInfo* rnd2, StringInfo* out)
1032 {
1033     StringInfo seed, sha_out, md5_out;
1034     guint8 *ptr;
1035     StringInfo s1, s2;
1036     guint i,s_l, r;
1037     gint usage_len;
1038     r=-1;
1039     usage_len = strlen(usage);
1040
1041     /* initalize buffer for sha, md5 random seed*/
1042     if (ssl_data_alloc(&sha_out, MAX(out->data_len,20)) < 0)
1043         return -1;
1044     if (ssl_data_alloc(&md5_out, MAX(out->data_len,16)) < 0)
1045         goto free_sha;
1046     if (ssl_data_alloc(&seed, usage_len+rnd1->data_len+rnd2->data_len) < 0)
1047         goto free_md5;
1048
1049     ptr=seed.data;
1050     memcpy(ptr,usage,usage_len); ptr+=usage_len;
1051     memcpy(ptr,rnd1->data,rnd1->data_len); ptr+=rnd1->data_len;
1052     memcpy(ptr,rnd2->data,rnd2->data_len); ptr+=rnd2->data_len;
1053
1054     /* initalize buffer for client/server seeds*/
1055     s_l=secret->data_len/2 + secret->data_len%2;
1056     if (ssl_data_alloc(&s1, s_l) < 0)
1057         goto free_seed;
1058     if (ssl_data_alloc(&s2, s_l) < 0)
1059         goto free_s1;
1060
1061     memcpy(s1.data,secret->data,s_l);
1062     memcpy(s2.data,secret->data + (secret->data_len - s_l),s_l);
1063
1064     ssl_debug_printf("tls_prf: tls_hash(md5 secret_len %d seed_len %d )\n", s1.data_len, seed.data_len);
1065     if(tls_hash(&s1,&seed,ssl_get_digest_by_name("MD5"),&md5_out) != 0)
1066         goto free_all;
1067     ssl_debug_printf("tls_prf: tls_hash(sha)\n");
1068     if(tls_hash(&s2,&seed,ssl_get_digest_by_name("SHA1"),&sha_out) != 0)
1069         goto free_all;
1070
1071     for(i=0;i<out->data_len;i++)
1072       out->data[i]=md5_out.data[i] ^ sha_out.data[i];
1073     r =0;
1074
1075     ssl_print_string("PRF out",out);
1076 free_all:
1077     g_free(s2.data);
1078 free_s1:
1079     g_free(s1.data);
1080 free_seed:
1081     g_free(seed.data);
1082 free_md5:
1083     g_free(md5_out.data);
1084 free_sha:
1085     g_free(sha_out.data);
1086     return r;
1087 }
1088
1089 static gint
1090 ssl3_generate_export_iv(StringInfo* r1,
1091         StringInfo* r2, StringInfo* out)
1092 {
1093     SSL_MD5_CTX md5;
1094     guint8 tmp[16];
1095
1096     ssl_md5_init(&md5);
1097     ssl_md5_update(&md5,r1->data,r1->data_len);
1098     ssl_md5_update(&md5,r2->data,r2->data_len);
1099     ssl_md5_final(tmp,&md5);
1100     ssl_md5_cleanup(&md5);
1101
1102     memcpy(out->data,tmp,out->data_len);
1103     ssl_print_string("export iv", out);
1104
1105     return(0);
1106 }
1107
1108 static gint
1109 ssl3_prf(StringInfo* secret, const gchar* usage,
1110         StringInfo* r1,
1111         StringInfo* r2,StringInfo* out)
1112 {
1113     SSL_MD5_CTX md5;
1114     SSL_SHA_CTX sha;
1115     StringInfo *rnd1,*rnd2;
1116     guint off;
1117     gint i=0,j;
1118     guint8 buf[20];
1119
1120     rnd1=r1; rnd2=r2;
1121
1122     for(off=0;off<out->data_len;off+=16){
1123         guchar outbuf[16];
1124         gint tocpy;
1125         i++;
1126
1127         ssl_debug_printf("ssl3_prf: sha1_hash(%d)\n",i);
1128         /* A, BB, CCC,  ... */
1129         for(j=0;j<i;j++){
1130             buf[j]=64+i;
1131         }
1132
1133         ssl_sha_init(&sha);
1134         ssl_sha_update(&sha,buf,i);
1135         ssl_sha_update(&sha,secret->data,secret->data_len);
1136
1137         if(!strcmp(usage,"client write key") || !strcmp(usage,"server write key")){
1138             ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
1139             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
1140         }
1141         else{
1142             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
1143             ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
1144         }
1145
1146         ssl_sha_final(buf,&sha);
1147         ssl_sha_cleanup(&sha);
1148
1149         ssl_debug_printf("ssl3_prf: md5_hash(%d) datalen %d\n",i,
1150             secret->data_len);
1151         ssl_md5_init(&md5);
1152         ssl_md5_update(&md5,secret->data,secret->data_len);
1153         ssl_md5_update(&md5,buf,20);
1154         ssl_md5_final(outbuf,&md5);
1155         ssl_md5_cleanup(&md5);
1156
1157         tocpy=MIN(out->data_len-off,16);
1158         memcpy(out->data+off,outbuf,tocpy);
1159     }
1160
1161     return(0);
1162 }
1163
1164 static SslFlow*
1165 ssl_create_flow(void)
1166 {
1167   SslFlow *flow;
1168
1169   flow = se_alloc(sizeof(SslFlow));
1170   flow->byte_seq = 0;
1171   flow->flags = 0;
1172   flow->multisegment_pdus = se_tree_create_non_persistent(EMEM_TREE_TYPE_RED_BLACK, "ssl_multisegment_pdus");
1173   return flow;
1174 }
1175
1176 /* memory allocations functions for zlib intialization */
1177 static void* ssl_zalloc(void* opaque _U_, unsigned int no, unsigned int size)
1178 {
1179         return g_malloc0(no*size);
1180 }
1181 static void ssl_zfree(void* opaque _U_, void* address)
1182 {
1183         g_free(address);
1184 }
1185
1186 static SslDecompress*
1187 ssl_create_decompressor(gint compression)
1188 {
1189   SslDecompress *decomp;
1190 #ifdef HAVE_LIBZ
1191   int err;
1192 #endif
1193
1194   if (compression == 0) return NULL;
1195   ssl_debug_printf("ssl_create_decompressor: compression method %d\n", compression);
1196   decomp = se_alloc(sizeof(SslDecompress));
1197   decomp->compression = compression;
1198   switch (decomp->compression) {
1199 #ifdef HAVE_LIBZ
1200     case 1:  /* DEFLATE */
1201       decomp->istream.zalloc = ssl_zalloc;
1202       decomp->istream.zfree = ssl_zfree;
1203       decomp->istream.opaque = Z_NULL;
1204       decomp->istream.next_in = Z_NULL;
1205       decomp->istream.next_out = Z_NULL;
1206       decomp->istream.avail_in = 0;
1207       decomp->istream.avail_out = 0;
1208       err = inflateInit_(&decomp->istream, ZLIB_VERSION, sizeof(z_stream));
1209       if (err != Z_OK) {
1210         ssl_debug_printf("ssl_create_decompressor: inflateInit_() failed - %d\n", err);
1211         return NULL;
1212       }
1213       break;
1214 #endif
1215     default:
1216       ssl_debug_printf("ssl_create_decompressor: unsupported compression method %d\n", decomp->compression);
1217       return NULL;
1218   }
1219   return decomp;
1220 }
1221
1222 static SslDecoder*
1223 ssl_create_decoder(SslCipherSuite *cipher_suite, gint compression,
1224         guint8 *mk, guint8 *sk, guint8 *iv)
1225 {
1226     SslDecoder *dec;
1227     gint ciph;
1228     ciph=0;
1229
1230     dec = se_alloc0(sizeof(SslDecoder));
1231     /* Find the SSLeay cipher */
1232     if(cipher_suite->enc!=ENC_NULL) {
1233         ssl_debug_printf("ssl_create_decoder CIPHER: %s\n", ciphers[cipher_suite->enc-0x30]);
1234         ciph=ssl_get_cipher_by_name(ciphers[cipher_suite->enc-0x30]);
1235     }
1236     if (ciph == 0) {
1237         ssl_debug_printf("ssl_create_decoder can't find cipher %s\n",
1238             ciphers[(cipher_suite->enc-0x30) > 7 ? 7 : (cipher_suite->enc-0x30)]);
1239         return NULL;
1240     }
1241
1242     /* init mac buffer: mac storage is embedded into decoder struct to save a
1243      memory allocation and waste samo more memory*/
1244     dec->cipher_suite=cipher_suite;
1245     dec->compression = compression;
1246     dec->mac_key.data = dec->_mac_key;
1247     ssl_data_set(&dec->mac_key, mk, cipher_suite->dig_len);
1248     dec->seq = 0;
1249     dec->decomp = ssl_create_decompressor(compression);
1250     dec->flow = ssl_create_flow();
1251
1252     if (dec->evp)
1253         ssl_cipher_cleanup(&dec->evp);
1254
1255     if (ssl_cipher_init(&dec->evp,ciph,sk,iv,cipher_suite->mode) < 0) {
1256         ssl_debug_printf("ssl_create_decoder: can't create cipher id:%d mode:%d\n",
1257             ciph, cipher_suite->mode);
1258         return NULL;
1259     }
1260
1261     ssl_debug_printf("decoder initialized (digest len %d)\n", cipher_suite->dig_len);
1262     return dec;
1263 }
1264
1265 int
1266 ssl_generate_keyring_material(SslDecryptSession*ssl_session)
1267 {
1268     StringInfo key_block;
1269     guint8 _iv_c[MAX_BLOCK_SIZE],_iv_s[MAX_BLOCK_SIZE];
1270     guint8 _key_c[MAX_KEY_SIZE],_key_s[MAX_KEY_SIZE];
1271     gint needed;
1272     guint8 *ptr,*c_wk,*s_wk,*c_mk,*s_mk,*c_iv = _iv_c,*s_iv = _iv_s;
1273
1274     /* if master_key is not yet generate, create it now*/
1275     if (!(ssl_session->state & SSL_MASTER_SECRET)) {
1276         ssl_debug_printf("ssl_generate_keyring_material:PRF(pre_master_secret)\n");
1277         if (PRF(ssl_session,&ssl_session->pre_master_secret,"master secret",
1278                 &ssl_session->client_random,
1279                 &ssl_session->server_random, &ssl_session->master_secret)) {
1280             ssl_debug_printf("ssl_generate_keyring_material can't generate master_secret\n");
1281             return -1;
1282         }
1283         ssl_print_string("master secret",&ssl_session->master_secret);
1284     }
1285
1286     /* Compute the key block. First figure out how much data we need*/
1287     needed=ssl_session->cipher_suite.dig_len*2;
1288     needed+=ssl_session->cipher_suite.bits / 4;
1289     if(ssl_session->cipher_suite.block>1)
1290         needed+=ssl_session->cipher_suite.block*2;
1291
1292     key_block.data_len = needed;
1293     key_block.data = g_malloc(needed);
1294     if (!key_block.data) {
1295         ssl_debug_printf("ssl_generate_keyring_material can't allacate key_block\n");
1296         return -1;
1297     }
1298     ssl_debug_printf("ssl_generate_keyring_material sess key generation\n");
1299     if (PRF(ssl_session,&ssl_session->master_secret,"key expansion",
1300             &ssl_session->server_random,&ssl_session->client_random,
1301             &key_block)) {
1302         ssl_debug_printf("ssl_generate_keyring_material can't generate key_block\n");
1303         goto fail;
1304     }
1305     ssl_print_string("key expansion", &key_block);
1306
1307     ptr=key_block.data;
1308     c_mk=ptr; ptr+=ssl_session->cipher_suite.dig_len;
1309     s_mk=ptr; ptr+=ssl_session->cipher_suite.dig_len;
1310
1311     c_wk=ptr; ptr+=ssl_session->cipher_suite.eff_bits/8;
1312     s_wk=ptr; ptr+=ssl_session->cipher_suite.eff_bits/8;
1313
1314     if(ssl_session->cipher_suite.block>1){
1315         c_iv=ptr; ptr+=ssl_session->cipher_suite.block;
1316         s_iv=ptr; ptr+=ssl_session->cipher_suite.block;
1317     }
1318
1319     if(ssl_session->cipher_suite.export){
1320         StringInfo iv_c,iv_s;
1321         StringInfo key_c,key_s;
1322         StringInfo k;
1323
1324         if(ssl_session->cipher_suite.block>1){
1325
1326             /* We only have room for MAX_BLOCK_SIZE bytes IVs, but that's
1327              all we should need. This is a sanity check */
1328             if(ssl_session->cipher_suite.block>MAX_BLOCK_SIZE) {
1329                 ssl_debug_printf("ssl_generate_keyring_material cipher suite block must be at most %d nut is %d\n",
1330                     MAX_BLOCK_SIZE, ssl_session->cipher_suite.block);
1331                 goto fail;
1332             }
1333
1334             iv_c.data = _iv_c;
1335             iv_c.data_len = ssl_session->cipher_suite.block;
1336             iv_s.data = _iv_s;
1337             iv_s.data_len = ssl_session->cipher_suite.block;
1338
1339             if(ssl_session->version_netorder==SSLV3_VERSION){
1340                 ssl_debug_printf("ssl_generate_keyring_material ssl3_generate_export_iv\n");
1341                 if (ssl3_generate_export_iv(&ssl_session->client_random,
1342                         &ssl_session->server_random,&iv_c)) {
1343                     ssl_debug_printf("ssl_generate_keyring_material can't generate sslv3 client iv\n");
1344                     goto fail;
1345                 }
1346                 ssl_debug_printf("ssl_generate_keyring_material ssl3_generate_export_iv(2)\n");
1347                 if (ssl3_generate_export_iv(&ssl_session->server_random,
1348                         &ssl_session->client_random,&iv_s)) {
1349                     ssl_debug_printf("ssl_generate_keyring_material can't generate sslv3 server iv\n");
1350                     goto fail;
1351                 }
1352             }
1353             else{
1354                 guint8 _iv_block[MAX_BLOCK_SIZE * 2];
1355                 StringInfo iv_block;
1356                 StringInfo key_null;
1357                 guint8 _key_null;
1358
1359                 key_null.data = &_key_null;
1360                 key_null.data_len = 0;
1361
1362                 iv_block.data = _iv_block;
1363                 iv_block.data_len = ssl_session->cipher_suite.block*2;
1364
1365                 ssl_debug_printf("ssl_generate_keyring_material prf(iv_block)\n");
1366                 if(PRF(ssl_session,&key_null, "IV block",
1367                         &ssl_session->client_random,
1368                         &ssl_session->server_random,&iv_block)) {
1369                     ssl_debug_printf("ssl_generate_keyring_material can't generate tls31 iv block\n");
1370                     goto fail;
1371                 }
1372
1373                 memcpy(_iv_c,iv_block.data,ssl_session->cipher_suite.block);
1374                 memcpy(_iv_s,iv_block.data+ssl_session->cipher_suite.block,
1375                     ssl_session->cipher_suite.block);
1376             }
1377
1378             c_iv=_iv_c;
1379             s_iv=_iv_s;
1380         }
1381
1382         if (ssl_session->version_netorder==SSLV3_VERSION){
1383
1384             SSL_MD5_CTX md5;
1385             ssl_debug_printf("ssl_generate_keyring_material MD5(client_random)\n");
1386
1387             ssl_md5_init(&md5);
1388             ssl_md5_update(&md5,c_wk,ssl_session->cipher_suite.eff_bits/8);
1389             ssl_md5_update(&md5,ssl_session->client_random.data,
1390                 ssl_session->client_random.data_len);
1391             ssl_md5_update(&md5,ssl_session->server_random.data,
1392                 ssl_session->server_random.data_len);
1393             ssl_md5_final(_key_c,&md5);
1394             ssl_md5_cleanup(&md5);
1395             c_wk=_key_c;
1396
1397             ssl_md5_init(&md5);
1398             ssl_debug_printf("ssl_generate_keyring_material MD5(server_random)\n");
1399             ssl_md5_update(&md5,s_wk,ssl_session->cipher_suite.eff_bits/8);
1400             ssl_md5_update(&md5,ssl_session->server_random.data,
1401                 ssl_session->server_random.data_len);
1402             ssl_md5_update(&md5,ssl_session->client_random.data,
1403                 ssl_session->client_random.data_len);
1404             ssl_md5_final(_key_s,&md5);
1405             ssl_md5_cleanup(&md5);
1406             s_wk=_key_s;
1407         }
1408         else{
1409             key_c.data = _key_c;
1410             key_c.data_len = sizeof(_key_c);
1411             key_s.data = _key_s;
1412             key_s.data_len = sizeof(_key_s);
1413
1414             k.data = c_wk;
1415             k.data_len = ssl_session->cipher_suite.eff_bits/8;
1416             ssl_debug_printf("ssl_generate_keyring_material PRF(key_c)\n");
1417             if (PRF(ssl_session,&k,"client write key",
1418                     &ssl_session->client_random,
1419                     &ssl_session->server_random, &key_c)) {
1420                 ssl_debug_printf("ssl_generate_keyring_material can't generate tll31 server key \n");
1421                 goto fail;
1422             }
1423             c_wk=_key_c;
1424
1425             k.data = s_wk;
1426             k.data_len = ssl_session->cipher_suite.eff_bits/8;
1427             ssl_debug_printf("ssl_generate_keyring_material PRF(key_s)\n");
1428             if(PRF(ssl_session,&k,"server write key",
1429                     &ssl_session->client_random,
1430                     &ssl_session->server_random, &key_s)) {
1431                 ssl_debug_printf("ssl_generate_keyring_material can't generate tll31 client key \n");
1432                 goto fail;
1433             }
1434             s_wk=_key_s;
1435         }
1436     }
1437
1438     /* show key material info */
1439     ssl_print_data("Client MAC key",c_mk,ssl_session->cipher_suite.dig_len);
1440     ssl_print_data("Server MAC key",s_mk,ssl_session->cipher_suite.dig_len);
1441     ssl_print_data("Client Write key",c_wk,ssl_session->cipher_suite.bits/8);
1442     ssl_print_data("Server Write key",s_wk,ssl_session->cipher_suite.bits/8);
1443
1444     if(ssl_session->cipher_suite.block>1) {
1445         ssl_print_data("Client Write IV",c_iv,ssl_session->cipher_suite.block);
1446         ssl_print_data("Server Write IV",s_iv,ssl_session->cipher_suite.block);
1447     }
1448     else {
1449         ssl_print_data("Client Write IV",c_iv,8);
1450         ssl_print_data("Server Write IV",s_iv,8);
1451     }
1452
1453     /* create both client and server ciphers*/
1454     ssl_debug_printf("ssl_generate_keyring_material ssl_create_decoder(client)\n");
1455     ssl_session->client_new = ssl_create_decoder(&ssl_session->cipher_suite, ssl_session->compression, c_mk, c_wk, c_iv);
1456     if (!ssl_session->client_new) {
1457         ssl_debug_printf("ssl_generate_keyring_material can't init client decoder\n");
1458         goto fail;
1459     }
1460     ssl_debug_printf("ssl_generate_keyring_material ssl_create_decoder(server)\n");
1461     ssl_session->server_new = ssl_create_decoder(&ssl_session->cipher_suite, ssl_session->compression, s_mk, s_wk, s_iv);
1462     if (!ssl_session->server_new) {
1463         ssl_debug_printf("ssl_generate_keyring_material can't init client decoder\n");
1464         goto fail;
1465     }
1466
1467     ssl_debug_printf("ssl_generate_keyring_material: client seq %d, server seq %d\n",
1468         ssl_session->client_new->seq, ssl_session->server_new->seq);
1469     g_free(key_block.data);
1470     return 0;
1471
1472 fail:
1473     g_free(key_block.data);
1474     return -1;
1475 }
1476
1477 void
1478 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
1479 {
1480   ssl_debug_printf("ssl_change_cipher %s\n", (server)?"SERVER":"CLIENT");
1481   if (server) {
1482     ssl_session->server = ssl_session->server_new;
1483     ssl_session->server_new = NULL;
1484   } else {
1485     ssl_session->client = ssl_session->client_new;
1486     ssl_session->client_new = NULL;
1487   }
1488 }
1489
1490 int
1491 ssl_decrypt_pre_master_secret(SslDecryptSession*ssl_session,
1492     StringInfo* entrypted_pre_master, SSL_PRIVATE_KEY *pk)
1493 {
1494     gint i;
1495
1496     if(ssl_session->cipher_suite.kex!=KEX_RSA) {
1497         ssl_debug_printf("ssl_decrypt_pre_master_secret key %d diferent from KEX_RSA(%d)\n",
1498             ssl_session->cipher_suite.kex, KEX_RSA);
1499         return(-1);
1500     }
1501
1502     /* with tls key loading will fail if not rsa type, so no need to check*/
1503     ssl_print_string("pre master encrypted",entrypted_pre_master);
1504     ssl_debug_printf("ssl_decrypt_pre_master_secret:RSA_private_decrypt\n");
1505     i=ssl_private_decrypt(entrypted_pre_master->data_len,
1506         entrypted_pre_master->data, pk);
1507
1508     if (i!=48) {
1509         ssl_debug_printf("ssl_decrypt_pre_master_secret wrong "
1510             "pre_master_secret length (%d, expected %d)\n", i, 48);
1511         return -1;
1512     }
1513
1514     /* the decrypted data has been written into the pre_master key buffer */
1515     ssl_session->pre_master_secret.data = entrypted_pre_master->data;
1516     ssl_session->pre_master_secret.data_len=48;
1517     ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
1518
1519     /* Remove the master secret if it was there.
1520        This force keying material regeneration in
1521        case we're renegotiating */
1522     ssl_session->state &= ~(SSL_MASTER_SECRET|SSL_HAVE_SESSION_KEY);
1523     return 0;
1524 }
1525
1526 /* convert network byte order 32 byte number to right-aligned host byte order *
1527  * 8 bytes buffer */
1528 static gint fmt_seq(guint32 num, guint8* buf)
1529 {
1530     guint32 netnum;
1531
1532     memset(buf,0,8);
1533     netnum=g_htonl(num);
1534     memcpy(buf+4,&netnum,4);
1535
1536     return(0);
1537 }
1538
1539 static gint
1540 tls_check_mac(SslDecoder*decoder, gint ct, gint ver, guint8* data,
1541         guint32 datalen, guint8* mac)
1542 {
1543     SSL_HMAC hm;
1544     gint md;
1545     guint32 len;
1546     guint8 buf[20];
1547
1548     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
1549     ssl_debug_printf("tls_check_mac mac type:%s md %d\n",
1550         digests[decoder->cipher_suite->dig-0x40], md);
1551
1552     ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md);
1553
1554     /* hash sequence number */
1555     fmt_seq(decoder->seq,buf);
1556
1557     decoder->seq++;
1558
1559     ssl_hmac_update(&hm,buf,8);
1560
1561     /* hash content type */
1562     buf[0]=ct;
1563     ssl_hmac_update(&hm,buf,1);
1564
1565     /* hash version,data length and data*/
1566     *((gint16*)buf) = g_htons(ver);
1567     ssl_hmac_update(&hm,buf,2);
1568
1569     *((gint16*)buf) = g_htons(datalen);
1570     ssl_hmac_update(&hm,buf,2);
1571     ssl_hmac_update(&hm,data,datalen);
1572
1573     /* get digest and digest len*/
1574     ssl_hmac_final(&hm,buf,&len);
1575     ssl_print_data("Mac", buf, len);
1576     if(memcmp(mac,buf,len))
1577         return -1;
1578
1579     ssl_hmac_cleanup(&hm);
1580     return(0);
1581 }
1582
1583 int
1584 ssl3_check_mac(SslDecoder*decoder,int ct,guint8* data,
1585         guint32 datalen, guint8* mac)
1586 {
1587     SSL_MD mc;
1588     gint md;
1589     guint32 len;
1590     guint8 buf[64],dgst[20];
1591     gint pad_ct;
1592
1593     pad_ct=(decoder->cipher_suite->dig==DIG_SHA)?40:48;
1594
1595     /* get cipher used for digest comptuation */
1596     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
1597     ssl_md_init(&mc,md);
1598
1599     /* do hash computation on data && padding */
1600     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
1601
1602     /* hash padding*/
1603     memset(buf,0x36,pad_ct);
1604     ssl_md_update(&mc,buf,pad_ct);
1605
1606     /* hash sequence number */
1607     fmt_seq(decoder->seq,buf);
1608     decoder->seq++;
1609     ssl_md_update(&mc,buf,8);
1610
1611     /* hash content type */
1612     buf[0]=ct;
1613     ssl_md_update(&mc,buf,1);
1614
1615     /* hash data length in network byte order and data*/
1616     *((gint16* )buf) = g_htons(datalen);
1617     ssl_md_update(&mc,buf,2);
1618     ssl_md_update(&mc,data,datalen);
1619
1620     /* get partial digest */
1621     ssl_md_final(&mc,dgst,&len);
1622     ssl_md_cleanup(&mc);
1623
1624     ssl_md_init(&mc,md);
1625
1626     /* hash mac key */
1627     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
1628
1629     /* hash padding and partial digest*/
1630     memset(buf,0x5c,pad_ct);
1631     ssl_md_update(&mc,buf,pad_ct);
1632     ssl_md_update(&mc,dgst,len);
1633
1634     ssl_md_final(&mc,dgst,&len);
1635     ssl_md_cleanup(&mc);
1636
1637     if(memcmp(mac,dgst,len))
1638         return -1;
1639
1640     return(0);
1641 }
1642
1643 #if 0
1644 static gint
1645 dtls_check_mac(SslDecoder*decoder, gint ct,int ver, guint8* data,
1646         guint32 datalen, guint8* mac)
1647 {
1648     SSL_HMAC hm;
1649     gint md;
1650     guint32 len;
1651     guint8 buf[20];
1652     guint32 netnum;
1653     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
1654     ssl_debug_printf("dtls_check_mac mac type:%s md %d\n",
1655         digests[decoder->cipher_suite->dig-0x40], md);
1656
1657     ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md);
1658     ssl_debug_printf("dtls_check_mac seq: %d epoch: %d\n",decoder->seq,decoder->epoch);
1659     /* hash sequence number */
1660     fmt_seq(decoder->seq,buf);
1661     buf[0]=decoder->epoch>>8;
1662     buf[1]=decoder->epoch;
1663
1664     ssl_hmac_update(&hm,buf,8);
1665
1666     /* hash content type */
1667     buf[0]=ct;
1668     ssl_hmac_update(&hm,buf,1);
1669
1670     /* hash version,data length and data */
1671     *((gint16*)buf) = g_htons(ver);
1672     ssl_hmac_update(&hm,buf,2);
1673
1674     *((gint16*)buf) = g_htons(datalen);
1675     ssl_hmac_update(&hm,buf,2);
1676     ssl_hmac_update(&hm,data,datalen);
1677     /* get digest and digest len */
1678     ssl_hmac_final(&hm,buf,&len);
1679     ssl_print_data("Mac", buf, len);
1680     if(memcmp(mac,buf,len))
1681         return -1;
1682
1683     ssl_hmac_cleanup(&hm);
1684     return(0);
1685 }
1686 #endif
1687
1688
1689 int
1690 ssl_decompress_record(SslDecompress* decomp, const guchar* in, guint inl, StringInfo* out_str, guint* outl)
1691 {
1692 #ifdef HAVE_LIBZ
1693   gint err;
1694 #endif
1695
1696   switch (decomp->compression) {
1697 #ifdef HAVE_LIBZ
1698     case 1:  /* DEFLATE */
1699       err = Z_OK;
1700       if (out_str->data_len < 16384) {  /* maximal plain length */
1701         ssl_data_realloc(out_str, 16384);
1702       }
1703       decomp->istream.next_in = (guchar*)in;
1704       decomp->istream.avail_in = inl;
1705       decomp->istream.next_out = out_str->data;
1706       decomp->istream.avail_out = out_str->data_len;
1707       if (inl > 0)
1708         err = inflate(&decomp->istream, Z_SYNC_FLUSH);
1709       if (err != Z_OK) {
1710         ssl_debug_printf("ssl_decompress_record: inflate() failed - %d\n", err);
1711         return -1;
1712       }
1713       *outl = out_str->data_len - decomp->istream.avail_out;
1714       break;
1715 #endif  /* HAVE_LIBZ */
1716     default:
1717       ssl_debug_printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
1718       return -1;
1719   }
1720   return 0;
1721 }
1722
1723 int
1724 ssl_decrypt_record(SslDecryptSession*ssl,SslDecoder* decoder, gint ct,
1725         const guchar* in, guint inl, StringInfo* comp_str, StringInfo* out_str, guint* outl)
1726 {
1727     guint pad, worklen, uncomplen;
1728     guint8 *mac;
1729
1730     ssl_debug_printf("ssl_decrypt_record ciphertext len %d\n", inl);
1731     ssl_print_data("Ciphertext",in, inl);
1732
1733     /* ensure we have enough storage space for decrypted data */
1734     if (inl > out_str->data_len)
1735     {
1736         ssl_debug_printf("ssl_decrypt_record: allocating %d bytes for decrypt data (old len %d)\n",
1737                 inl + 32, out_str->data_len);
1738         ssl_data_realloc(out_str, inl + 32);
1739     }
1740
1741     /* First decrypt*/
1742     if ((pad = ssl_cipher_decrypt(&decoder->evp, out_str->data, out_str->data_len, in, inl))!= 0) {
1743         ssl_debug_printf("ssl_decrypt_record failed: ssl_cipher_decrypt: %s %s\n", gcry_strsource (pad),
1744                     gcry_strerror (pad));
1745         return -1;
1746     }
1747
1748     ssl_print_data("Plaintext", out_str->data, inl);
1749     worklen=inl;
1750
1751     /* Now strip off the padding*/
1752     if(decoder->cipher_suite->block!=1) {
1753         pad=out_str->data[inl-1];
1754         worklen-=(pad+1);
1755         ssl_debug_printf("ssl_decrypt_record found padding %d final len %d\n",
1756             pad, worklen);
1757     }
1758
1759     /* And the MAC */
1760     if (decoder->cipher_suite->dig_len > (gint)worklen)
1761     {
1762         ssl_debug_printf("ssl_decrypt_record wrong record len/padding outlen %d\n work %d\n",*outl, worklen);
1763         return -1;
1764     }
1765     worklen-=decoder->cipher_suite->dig_len;
1766     mac = out_str->data + worklen;
1767
1768     /* if TLS 1.1 we use the transmitted IV and remove it after (to not modify dissector in others parts)*/
1769     if(ssl->version_netorder==TLSV1DOT1_VERSION){
1770         worklen=worklen-decoder->cipher_suite->block;
1771         memcpy(out_str->data,out_str->data+decoder->cipher_suite->block,worklen);
1772    }
1773   if(ssl->version_netorder==DTLSV1DOT0_VERSION ||
1774      ssl->version_netorder==DTLSV1DOT0_VERSION_NOT){
1775         worklen=worklen-decoder->cipher_suite->block;
1776         memcpy(out_str->data,out_str->data+decoder->cipher_suite->block,worklen);
1777    }
1778     /* Now check the MAC */
1779     ssl_debug_printf("checking mac (len %d, version %X, ct %d seq %d)\n",
1780         worklen, ssl->version_netorder, ct, decoder->seq);
1781     if(ssl->version_netorder==SSLV3_VERSION){
1782         if(ssl3_check_mac(decoder,ct,out_str->data,worklen,mac) < 0) {
1783             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
1784             return -1;
1785         }
1786     }
1787     else if(ssl->version_netorder==TLSV1_VERSION || ssl->version_netorder==TLSV1DOT1_VERSION){
1788         if(tls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)< 0) {
1789             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
1790             return -1;
1791         }
1792     }
1793     else if(ssl->version_netorder==DTLSV1DOT0_VERSION ||
1794             ssl->version_netorder==DTLSV1DOT0_VERSION_NOT){
1795       /* follow the openssl dtls errors the rigth test is : dtls_check_mac(decoder,ct,ssl->version_netorder,out,worklen,mac)< 0 */
1796 /*      if(dtls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)< 0) { */
1797         if(tls_check_mac(decoder,ct,TLSV1_VERSION,out_str->data,worklen,mac)< 0) {
1798             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
1799             return -1;
1800         }
1801     }
1802     ssl_debug_printf("ssl_decrypt_record: mac ok\n");
1803     *outl = worklen;
1804
1805     if (decoder->compression > 0) {
1806       ssl_debug_printf("ssl_decrypt_record: compression method %d\n", decoder->compression);
1807       ssl_data_copy(comp_str, out_str);
1808       ssl_print_data("Plaintext compressed", comp_str->data, worklen);
1809       if (!decoder->decomp) {
1810         ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
1811         return -1;
1812       }
1813       if (ssl_decompress_record(decoder->decomp, comp_str->data, worklen, out_str, &uncomplen) < 0) return -1;
1814       ssl_print_data("Plaintext uncompressed", out_str->data, uncomplen);
1815       *outl = uncomplen;
1816     }
1817
1818     return 0;
1819 }
1820
1821 static void
1822 ssl_get_version(gint* major, gint* minor, gint* patch)
1823 {
1824   *major = ver_major;
1825   *minor = ver_minor;
1826   *patch = ver_patch;
1827 }
1828
1829 #define RSA_PARS 6
1830 SSL_PRIVATE_KEY*
1831 ssl_privkey_to_sexp(struct gnutls_x509_privkey_int* priv_key)
1832 {
1833     gnutls_datum_t rsa_datum[RSA_PARS]; /* m, e, d, p, q, u */
1834     size_t tmp_size;
1835     gcry_sexp_t rsa_priv_key;
1836     gint major, minor, patch;
1837     gint i;
1838     
1839 #ifdef SSL_FAST
1840     gcry_mpi_t* rsa_params = g_malloc(sizeof(gcry_mpi_t)*RSA_PARS);
1841 #else
1842     gcry_mpi_t rsa_params[RSA_PARS];
1843 #endif
1844
1845     /*
1846      * note: openssl and gnutls use 'p' and 'q' with opposite meaning:
1847      * our 'p' must be equal to 'q' as provided from openssl and viceversa
1848      */    
1849
1850     /* RSA get parameter */
1851     if (gnutls_x509_privkey_export_rsa_raw(priv_key,
1852           &rsa_datum[0], &rsa_datum[1], &rsa_datum[2], &rsa_datum[4], &rsa_datum[3], &rsa_datum[5]) != 0) {
1853         ssl_debug_printf("ssl_load_key: can't export rsa param (is a rsa private key file ?!?)\n");
1854 #ifdef SSL_FAST
1855         g_free(rsa_params);
1856 #endif
1857         return NULL;
1858     }
1859     
1860     /* convert each rsa parameter to mpi format*/
1861     for(i=0; i<RSA_PARS; i++) {
1862       if (gcry_mpi_scan(&rsa_params[i], GCRYMPI_FMT_USG, rsa_datum[i].data, rsa_datum[i].size,&tmp_size) != 0) {
1863         ssl_debug_printf("ssl_load_key: can't convert m rsa param to int (size %d)\n", rsa_datum[i].size);
1864 #ifdef SSL_FAST
1865         g_free(rsa_params);
1866 #endif
1867         return NULL;
1868       } 
1869     }
1870
1871     ssl_get_version(&major, &minor, &patch);
1872
1873     /* certain versions of gnutls require swap of rsa params 'p' and 'q' */
1874     if ((major <= 1) && (minor <= 0) && (patch <=13))
1875     {
1876         gcry_mpi_t tmp;
1877         ssl_debug_printf("ssl_load_key: swapping p and q parametes\n");
1878         tmp = rsa_params[4];
1879         rsa_params[4] = rsa_params[3];
1880         rsa_params[3] = tmp;
1881     }
1882
1883     if  (gcry_sexp_build( &rsa_priv_key, NULL,
1884             "(private-key(rsa((n%m)(e%m)(d%m)(p%m)(q%m)(u%m))))", rsa_params[0],
1885             rsa_params[1], rsa_params[2], rsa_params[3], rsa_params[4],
1886             rsa_params[5]) != 0) {
1887         ssl_debug_printf("ssl_load_key: can't built rsa private key s-exp\n");
1888 #ifdef SSL_FAST
1889         g_free(rsa_params);
1890 #endif        
1891         return NULL;
1892     }
1893
1894 #if SSL_FAST
1895     return rsa_params;
1896 #else
1897     {
1898         gint i;
1899         for (i=0; i< 6; i++)
1900             gcry_mpi_release(rsa_params[i]);
1901     }
1902     return rsa_priv_key;
1903 #endif
1904     
1905 }
1906
1907 Ssl_private_key_t *
1908 ssl_load_key(FILE* fp)
1909 {
1910     /* gnutls make our work much harded, since we have to work internally with
1911      * s-exp formatted data, but PEM loader export only in "gnutls_datum"
1912      * format, and a datum -> s-exp convertion function does not exist.
1913      */
1914     gnutls_x509_privkey_t priv_key;
1915     gnutls_datum key;
1916     gint size;
1917     guint bytes;
1918
1919     Ssl_private_key_t *private_key = g_malloc(sizeof(Ssl_private_key_t));
1920     private_key->x509_cert = 0;
1921     private_key->x509_pkey = 0;
1922     private_key->sexp_pkey = 0;
1923     
1924     /* init private key data*/
1925     gnutls_x509_privkey_init(&priv_key);
1926
1927     /* compute file size and load all file contents into a datum buffer*/
1928     if (fseek(fp, 0, SEEK_END) < 0) {
1929         ssl_debug_printf("ssl_load_key: can't fseek file\n");
1930         g_free(private_key);
1931         return NULL;
1932     }
1933     if ((size = ftell(fp)) < 0) {
1934         ssl_debug_printf("ssl_load_key: can't ftell file\n");
1935         g_free(private_key);
1936         return NULL;
1937     }
1938     if (fseek(fp, 0, SEEK_SET) < 0) {
1939         ssl_debug_printf("ssl_load_key: can't refseek file\n");
1940         g_free(private_key);
1941         return NULL;
1942     }
1943     key.data = g_malloc(size);
1944     key.size = size;
1945     bytes = fread(key.data, 1, key.size, fp);
1946     if (bytes < key.size) {
1947         ssl_debug_printf("ssl_load_key: can't read from file %d bytes, got %d\n",
1948             key.size, bytes);
1949         g_free(private_key);
1950         g_free(key.data);    
1951         return NULL;
1952     }
1953
1954     /* import PEM data*/
1955     if (gnutls_x509_privkey_import(priv_key, &key, GNUTLS_X509_FMT_PEM)!=0) {
1956         ssl_debug_printf("ssl_load_key: can't import pem data\n");
1957         g_free(private_key);
1958         g_free(key.data);
1959         return NULL;
1960     }
1961     g_free(key.data);
1962
1963     private_key->x509_pkey = priv_key;
1964     private_key->sexp_pkey = ssl_privkey_to_sexp(priv_key);
1965     if ( !private_key->sexp_pkey ) {
1966         g_free(private_key);
1967         return NULL;
1968     } 
1969     return private_key;
1970 }
1971
1972 const char *BAGTYPE(gnutls_pkcs12_bag_type_t x) {
1973   switch (x) {
1974     case GNUTLS_BAG_EMPTY:               return "Empty";
1975     case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: return "PKCS#8 Encrypted key";
1976     case GNUTLS_BAG_PKCS8_KEY:           return "PKCS#8 Key";
1977     case GNUTLS_BAG_CERTIFICATE:         return "Certificate";
1978     case GNUTLS_BAG_CRL:                 return "CRL";
1979     case GNUTLS_BAG_ENCRYPTED:           return "Encrypted";
1980     case GNUTLS_BAG_UNKNOWN:             return "Unknown";
1981     default:                             return "<undefined>";
1982     }
1983 }
1984
1985 Ssl_private_key_t *
1986 ssl_load_pkcs12(FILE* fp, const gchar *cert_passwd) {
1987
1988   int i, j, ret, len;
1989   size_t rest;
1990   unsigned char *p;
1991   gnutls_datum_t data;
1992   gnutls_pkcs12_bag_t bag = NULL;
1993   gnutls_pkcs12_bag_type_t bag_type;
1994   size_t buf_len;
1995   static char buf_name[256];
1996   static char buf_email[128];
1997   unsigned char buf_keyid[32];
1998
1999   gnutls_pkcs12_t       ssl_p12  = NULL;
2000   gnutls_x509_crt_t     ssl_cert = NULL;
2001   gnutls_x509_privkey_t ssl_pkey = NULL;
2002
2003   Ssl_private_key_t *private_key = g_malloc(sizeof(Ssl_private_key_t));
2004   private_key->x509_cert = 0;
2005   private_key->x509_pkey = 0;
2006   private_key->sexp_pkey = 0;
2007     
2008   rest = 4096;
2009   data.data = malloc(rest);
2010   data.size = rest;
2011   p = data.data;
2012   while ((len = fread(p, 1, rest, fp)) > 0) {
2013     p += len;
2014     rest -= len;
2015     if (!rest) {
2016       rest = 1024;
2017       data.data = realloc(data.data, data.size + rest);
2018       p = data.data + data.size;
2019       data.size += rest;
2020     }
2021   }
2022   data.size -= rest;
2023   ssl_debug_printf("%d bytes read\n", data.size);
2024   if (!feof(fp)) {
2025     ssl_debug_printf( "Error during certificate reading.\n");
2026     g_free(private_key);
2027     return 0;
2028   }
2029
2030   ret = gnutls_pkcs12_init(&ssl_p12);
2031   if (ret < 0) {
2032     ssl_debug_printf("gnutls_pkcs12_init(&st_p12) - %s", gnutls_strerror(ret));
2033     g_free(private_key);
2034     return 0;
2035   }
2036   ret = gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_DER, 0);
2037   free(data.data);
2038   if (ret < 0) {
2039     ssl_debug_printf("gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_DER, 0) - %s\n", gnutls_strerror(ret));
2040     g_free(private_key);
2041     return 0;
2042   }
2043
2044   ssl_debug_printf( "PKCS#12 imported\n");
2045
2046   for (i=0; ret==0; i++) {
2047
2048     if (bag) { gnutls_pkcs12_bag_deinit(bag); bag = NULL; }
2049
2050     ret = gnutls_pkcs12_bag_init(&bag);
2051     if (ret < 0) continue;
2052
2053     ret = gnutls_pkcs12_get_bag(ssl_p12, i, bag);
2054     if (ret < 0) continue;
2055
2056     for (j=0; ret==0 && j<gnutls_pkcs12_bag_get_count(bag); j++) {
2057
2058       bag_type = gnutls_pkcs12_bag_get_type(bag, j);
2059       if (bag_type < 0) continue;
2060       ssl_debug_printf( "Bag %d/%d: %s\n", i, j, BAGTYPE(bag_type));
2061       if (bag_type == GNUTLS_BAG_ENCRYPTED) {
2062         ret = gnutls_pkcs12_bag_decrypt(bag, cert_passwd);
2063         if (ret == 0) {
2064           bag_type = gnutls_pkcs12_bag_get_type(bag, j);
2065           if (bag_type < 0) continue;
2066           ssl_debug_printf( "Bag %d/%d decrypted: %s\n", i, j, BAGTYPE(bag_type));
2067         }
2068         ret = 0;
2069       }
2070
2071       ret = gnutls_pkcs12_bag_get_data(bag, j, &data);
2072       if (ret < 0) continue;
2073
2074       switch (bag_type) {
2075
2076         case GNUTLS_BAG_CERTIFICATE:
2077
2078           ret = gnutls_x509_crt_init(&ssl_cert);
2079           if (ret < 0) {
2080             ssl_debug_printf( "gnutls_x509_crt_init(&ssl_cert) - %s\n", gnutls_strerror(ret));
2081             g_free(private_key);
2082             return 0;
2083           }
2084
2085           ret = gnutls_x509_crt_import(ssl_cert, &data, GNUTLS_X509_FMT_DER);
2086           if (ret < 0) {
2087             ssl_debug_printf( "gnutls_x509_crt_import(ssl_cert, &data, GNUTLS_X509_FMT_DER) - %s\n", gnutls_strerror(ret));
2088             g_free(private_key);
2089             return 0;
2090           }
2091
2092           buf_len = sizeof(buf_name);
2093           ret = gnutls_x509_crt_get_dn_by_oid(ssl_cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, buf_name, &buf_len);
2094           if (ret < 0) { strcpy(buf_name, "<ERROR>"); }
2095           buf_len = sizeof(buf_email);
2096           ret = gnutls_x509_crt_get_dn_by_oid(ssl_cert, GNUTLS_OID_PKCS9_EMAIL, 0, 0, buf_email, &buf_len);
2097           if (ret < 0) { strcpy(buf_email, "<ERROR>"); }
2098
2099           buf_len = sizeof(buf_keyid);
2100           ret = gnutls_x509_crt_get_key_id(ssl_cert, 0, buf_keyid, &buf_len); 
2101           if (ret < 0) { strcpy(buf_keyid, "<ERROR>"); }
2102
2103           private_key->x509_cert = ssl_cert;
2104           ssl_debug_printf( "Certificate imported: %s <%s>, KeyID %s\n", buf_name, buf_email, bytes_to_str(buf_keyid, buf_len));
2105           break;
2106
2107         case GNUTLS_BAG_PKCS8_KEY:
2108         case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY:
2109       
2110           ret = gnutls_x509_privkey_init(&ssl_pkey);
2111           if (ret < 0) {
2112             ssl_debug_printf( "gnutls_x509_privkey_init(&ssl_pkey) - %s\n", gnutls_strerror(ret));
2113             g_free(private_key);
2114             return 0;
2115           }
2116           ret = gnutls_x509_privkey_import_pkcs8(ssl_pkey, &data, GNUTLS_X509_FMT_DER, cert_passwd, 
2117                                                  (bag_type==GNUTLS_BAG_PKCS8_KEY) ? GNUTLS_PKCS_PLAIN : 0);
2118           if (ret < 0) {
2119             ssl_debug_printf( "Can not decrypt private key - %s\n", gnutls_strerror(ret));
2120             g_free(private_key);
2121             return 0;
2122           }
2123
2124           buf_len = sizeof(buf_keyid);
2125           ret = gnutls_x509_privkey_get_key_id(ssl_pkey, 0, buf_keyid, &buf_len); 
2126           if (ret < 0) {
2127             ssl_debug_printf( "gnutls_x509_privkey_get_key_id(ssl_pkey, 0, buf_keyid, &buf_len) - %s\n", gnutls_strerror(ret));
2128             return 0;
2129           }
2130           ssl_debug_printf( "Private key imported: KeyID %s\n", bytes_to_str(buf_keyid, buf_len));
2131           
2132           private_key->x509_pkey = ssl_pkey; 
2133           private_key->sexp_pkey = ssl_privkey_to_sexp(ssl_pkey);
2134           if ( !private_key->sexp_pkey ) {
2135             g_free(private_key);
2136             return NULL;
2137           } 
2138           break;
2139
2140         default: ;
2141       }
2142     }  // j 
2143   }  // i 
2144
2145   return private_key; 
2146 }
2147
2148
2149 void ssl_free_key(Ssl_private_key_t* key)
2150 {
2151 #if SSL_FAST
2152     gint i;
2153     for (i=0; i< 6; i++)
2154         gcry_mpi_release(key->sexp_pkey[i]);
2155 #else
2156     gcry_sexp_release(key->sexp_pkey);
2157 #endif
2158
2159   if (!key->x509_cert)
2160     gnutls_x509_crt_deinit (key->x509_cert);
2161   
2162   if (!key->x509_pkey)
2163     gnutls_x509_privkey_deinit(key->x509_pkey);
2164   
2165   g_free((Ssl_private_key_t*)key);
2166 }
2167
2168 void
2169 ssl_lib_init(void)
2170 {
2171     const gchar* str = gnutls_check_version(NULL);
2172
2173     /* get library version */
2174     /* old relase of gnutls does not define the appropriate macros, so get
2175      * them from the string*/
2176     ssl_debug_printf("gnutls version: %s\n", str);
2177     sscanf(str, "%d.%d.%d", &ver_major, &ver_minor, &ver_patch);
2178 }
2179
2180 #else /* HAVE_LIBGNUTLS */
2181 /* no libgnutl: dummy operation to keep interface consistent*/
2182 void
2183 ssl_lib_init(void)
2184 {
2185 }
2186
2187 Ssl_private_key_t *
2188 ssl_load_key(FILE* fp)
2189 {
2190     ssl_debug_printf("ssl_load_key: impossible without glutls. fp %p\n",fp);
2191     return NULL;
2192 }
2193
2194 Ssl_private_key_t *
2195 ssl_load_pkcs12(FILE* fp, const gchar *cert_passwd) {
2196     ssl_debug_printf("ssl_load_pkcs12: impossible without glutls. fp %p\n",fp);
2197     return NULL;
2198 }
2199
2200 void
2201 ssl_free_key(Ssl_private_key_t* key _U_)
2202 {
2203 }
2204
2205 int
2206 ssl_find_cipher(int num,SslCipherSuite* cs)
2207 {
2208     ssl_debug_printf("ssl_find_cipher: dummy without glutls. num %d cs %p\n",
2209         num,cs);
2210     return 0;
2211 }
2212 int
2213 ssl_generate_keyring_material(SslDecryptSession*ssl)
2214 {
2215     ssl_debug_printf("ssl_generate_keyring_material: impossible without glutls. ssl %p\n",
2216         ssl);
2217     return 0;
2218 }
2219 void
2220 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
2221 {
2222   ssl_debug_printf("ssl_change_cipher %s: makes no sence without gnutls. ssl %p\n", (server)?"SERVER":"CLIENT", ssl_session);
2223 }
2224
2225 int
2226 ssl_decrypt_pre_master_secret(SslDecryptSession* ssl_session,
2227     StringInfo* entrypted_pre_master, SSL_PRIVATE_KEY *pk)
2228 {
2229     ssl_debug_printf("ssl_decrypt_pre_master_secret: impossible without glutls."
2230         " ssl %p entrypted_pre_master %p pk %p\n", ssl_session,
2231         entrypted_pre_master, pk);
2232     return 0;
2233 }
2234
2235 int
2236 ssl_decrypt_record(SslDecryptSession*ssl, SslDecoder* decoder, gint ct,
2237         const guchar* in, guint inl, StringInfo* comp_str _U_, StringInfo* out, guint* outl)
2238 {
2239     ssl_debug_printf("ssl_decrypt_record: impossible without gnutls. ssl %p"
2240         "decoder %p ct %d, in %p inl %d out %p outl %p\n", ssl, decoder, ct,
2241         in, inl, out, outl);
2242     return 0;
2243 }
2244
2245 gint
2246 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher _U_, guchar* iv _U_, gint iv_len _U_)
2247 {
2248     ssl_debug_printf("ssl_cipher_setiv: impossible without glutls.\n");
2249     return 0;
2250 }
2251
2252 #endif /* HAVE_LIBGNUTLS */
2253
2254 /* get ssl data for this session. if no ssl data is found allocate a new one*/
2255 void
2256 ssl_session_init(SslDecryptSession* ssl_session)
2257 {
2258     ssl_debug_printf("ssl_session_init: initializing ptr %p size %lu\n",
2259         ssl_session, (gulong)sizeof(SslDecryptSession));
2260
2261     ssl_session->master_secret.data = ssl_session->_master_secret;
2262     ssl_session->session_id.data = ssl_session->_session_id;
2263     ssl_session->client_random.data = ssl_session->_client_random;
2264     ssl_session->server_random.data = ssl_session->_server_random;
2265     ssl_session->master_secret.data_len = 48;
2266     ssl_session->server_data_for_iv.data = 0;
2267     ssl_session->server_data_for_iv.data = ssl_session->_server_data_for_iv;
2268     ssl_session->client_data_for_iv.data = 0;
2269     ssl_session->client_data_for_iv.data = ssl_session->_client_data_for_iv;
2270     ssl_session->app_data_segment.data=NULL;
2271     ssl_session->app_data_segment.data_len=0;
2272 }
2273
2274 /* Hash Functions for TLS/DTLS sessions table and private keys table*/
2275 gint
2276 ssl_equal (gconstpointer v, gconstpointer v2)
2277 {
2278   const StringInfo *val1;
2279   const StringInfo *val2;
2280   val1 = (const StringInfo *)v;
2281   val2 = (const StringInfo *)v2;
2282
2283   if (val1->data_len == val2->data_len &&
2284       !memcmp(val1->data, val2->data, val2->data_len)) {
2285     return 1;
2286   }
2287   return 0;
2288 }
2289
2290 guint
2291 ssl_hash  (gconstpointer v)
2292 {
2293   guint l,hash;
2294   const StringInfo* id;
2295   const guint* cur;
2296   hash = 0;
2297   id = (const StringInfo*) v;
2298   cur = (const guint*) id->data;
2299
2300   for (l=4; (l<id->data_len); l+=4, cur++)
2301     hash = hash ^ (*cur);
2302
2303   return hash;
2304 }
2305
2306 gint
2307 ssl_private_key_equal (gconstpointer v, gconstpointer v2)
2308 {
2309   const SslService *val1;
2310   const SslService *val2;
2311   val1 = (const SslService *)v;
2312   val2 = (const SslService *)v2;
2313
2314   if ((val1->port == val2->port) &&
2315       ! CMP_ADDRESS(&val1->addr, &val2->addr)) {
2316     return 1;
2317   }
2318   return 0;
2319 }
2320
2321 guint
2322 ssl_private_key_hash  (gconstpointer v)
2323 {
2324   const SslService *key;
2325   guint l, hash, len ;
2326   const guint* cur;
2327   key = (const SslService *)v;
2328   hash = key->port;
2329   len = key->addr.len;
2330   cur = (const guint*) key->addr.data;
2331
2332   for (l=4; (l<len); l+=4, cur++)
2333     hash = hash ^ (*cur);
2334
2335   return hash;
2336 }
2337
2338 /* private key table entries have a scope 'larger' then packet capture,
2339  * so we can't relay on se_alloc** function */
2340 void
2341 ssl_private_key_free(gpointer id, gpointer key, gpointer dummy _U_)
2342 {
2343   g_free(id);
2344   ssl_free_key((Ssl_private_key_t*) key);
2345 }
2346
2347 /* handling of association between tls/dtls ports and clear text protocol */
2348 void
2349 ssl_association_add(GTree* associations, dissector_handle_t handle, guint port, const gchar *protocol, gboolean tcp, gboolean from_key_list)
2350 {
2351
2352   SslAssociation* assoc;
2353   assoc = g_malloc(sizeof(SslAssociation));
2354
2355   assoc->tcp = tcp;
2356   assoc->ssl_port = port;
2357   assoc->info=g_malloc(strlen(protocol)+1);
2358   strcpy(assoc->info, protocol);
2359   assoc->handle = find_dissector(protocol);
2360   assoc->from_key_list = from_key_list;
2361
2362   ssl_debug_printf("association_add %s port %d protocol %s handle %p\n",
2363                    (assoc->tcp)?"TCP":"UDP", port, protocol, assoc->handle);
2364
2365
2366   if (!assoc->handle) {
2367     ssl_debug_printf("association_add could not find handle for protocol '%s', try to find 'data' dissector\n", protocol);
2368     assoc->handle = find_dissector("data");
2369   }
2370
2371   if(!assoc->handle){
2372     fprintf(stderr, "association_add() could not find handle for protocol:%s\n",protocol);
2373   } else {
2374     if(tcp)
2375       dissector_add("tcp.port", port, handle);
2376     else
2377       dissector_add("udp.port", port, handle);
2378     g_tree_insert(associations, assoc, assoc);
2379   }
2380 }
2381
2382 void
2383 ssl_association_remove(GTree* associations, SslAssociation *assoc)
2384 {
2385   ssl_debug_printf("ssl_association_remove removing %s %u - %s handle %p\n",
2386                    (assoc->tcp)?"TCP":"UDP", assoc->ssl_port, assoc->info, assoc->handle);
2387   if (assoc->handle)
2388     dissector_delete((assoc->tcp)?"tcp.port":"udp.port", assoc->ssl_port, assoc->handle);
2389
2390   g_tree_remove(associations, assoc);
2391   g_free(assoc);
2392 }
2393
2394 gint
2395 ssl_association_cmp(gconstpointer a, gconstpointer b)
2396 {
2397   const SslAssociation *assoc_a=a, *assoc_b=b;
2398   if (assoc_a->tcp != assoc_b->tcp) return (assoc_a->tcp)?1:-1;
2399   return assoc_a->ssl_port - assoc_b->ssl_port;
2400 }
2401
2402 SslAssociation*
2403 ssl_association_find(GTree * associations, guint port, gboolean tcp)
2404 {
2405   register SslAssociation* ret;
2406   SslAssociation assoc_tmp;
2407
2408   assoc_tmp.tcp = tcp;
2409   assoc_tmp.ssl_port = port;
2410   ret = g_tree_lookup(associations, &assoc_tmp);
2411
2412   ssl_debug_printf("association_find: %s port %d found %p\n", (tcp)?"TCP":"UDP", port, ret);
2413   return ret;
2414 }
2415
2416 gint
2417 ssl_assoc_from_key_list(gpointer key _U_, gpointer data, gpointer user_data)
2418 {
2419   if (((SslAssociation*)data)->from_key_list)
2420     ep_stack_push((ep_stack_t)user_data, data);
2421   return FALSE;
2422 }
2423
2424 int
2425 ssl_packet_from_server(GTree* associations, guint port, gboolean tcp)
2426 {
2427   register gint ret;
2428   ret = ssl_association_find(associations, port, tcp) != 0;
2429
2430   ssl_debug_printf("packet_from_server: is from server - %s\n", (ret)?"TRUE":"FALSE");
2431   return ret;
2432 }
2433
2434 /* add to packet data a newly allocated tvb with the specified real data*/
2435 void
2436 ssl_add_record_info(gint proto, packet_info *pinfo, guchar* data, gint data_len, gint record_id)
2437 {
2438   guchar* real_data;
2439   SslRecordInfo* rec;
2440   SslPacketInfo* pi;
2441   real_data = se_alloc(data_len);
2442   rec = se_alloc(sizeof(SslRecordInfo));
2443   pi = p_get_proto_data(pinfo->fd, proto);
2444
2445   if (!pi)
2446     {
2447       pi = se_alloc0(sizeof(SslPacketInfo));
2448       p_add_proto_data(pinfo->fd, proto,pi);
2449     }
2450
2451   rec->id = record_id;
2452   rec->tvb = tvb_new_real_data(real_data, data_len, data_len);
2453   memcpy(real_data, data, data_len);
2454
2455   /* head insertion */
2456   rec->next= pi->handshake_data;
2457   pi->handshake_data = rec;
2458 }
2459
2460
2461 /* search in packet data the tvbuff associated to the specified id */
2462 tvbuff_t*
2463 ssl_get_record_info(int proto, packet_info *pinfo, gint record_id)
2464 {
2465   SslRecordInfo* rec;
2466   SslPacketInfo* pi;
2467   pi = p_get_proto_data(pinfo->fd, proto);
2468
2469   if (!pi)
2470     return NULL;
2471
2472   for (rec = pi->handshake_data; rec; rec = rec->next)
2473     if (rec->id == record_id)
2474       return rec->tvb;
2475
2476   return NULL;
2477 }
2478
2479 void
2480 ssl_add_data_info(gint proto, packet_info *pinfo, guchar* data, gint data_len, gint key, SslFlow *flow)
2481 {
2482   SslDataInfo *rec, **prec;
2483   SslPacketInfo *pi;
2484
2485   pi = p_get_proto_data(pinfo->fd, proto);
2486   if (!pi)
2487     {
2488       pi = se_alloc0(sizeof(SslPacketInfo));
2489       p_add_proto_data(pinfo->fd, proto,pi);
2490     }
2491
2492   rec = se_alloc(sizeof(SslDataInfo)+data_len);
2493   rec->key = key;
2494   rec->plain_data.data = (guchar*)(rec + 1);
2495   memcpy(rec->plain_data.data, data, data_len);
2496   rec->plain_data.data_len = data_len;
2497   rec->seq = flow->byte_seq;
2498   rec->nxtseq = flow->byte_seq + data_len;
2499   rec->flow = flow;
2500   rec->next = NULL;
2501
2502   flow->byte_seq += data_len;
2503
2504   /* insertion */
2505   prec = &pi->appl_data;
2506   while (*prec) prec = &(*prec)->next;
2507   *prec = rec;
2508
2509   ssl_debug_printf("ssl_add_data_info: new data inserted data_len = %d, seq = %u, nxtseq = %u\n",
2510                    rec->plain_data.data_len, rec->seq, rec->nxtseq);
2511 }
2512
2513 SslDataInfo*
2514 ssl_get_data_info(int proto, packet_info *pinfo, gint key)
2515 {
2516   SslDataInfo* rec;
2517   SslPacketInfo* pi;
2518   pi = p_get_proto_data(pinfo->fd, proto);
2519
2520   if (!pi) return NULL;
2521
2522   rec = pi->appl_data;
2523   while (rec) {
2524     if (rec->key == key) return rec;
2525     rec = rec->next;
2526   }
2527
2528   return NULL;
2529 }
2530
2531 /* initialize/reset per capture state data (ssl sessions cache) */
2532 void
2533 ssl_common_init(GHashTable **session_hash, StringInfo *decrypted_data, StringInfo *compressed_data)
2534 {
2535   if (*session_hash)
2536     g_hash_table_destroy(*session_hash);
2537   *session_hash = g_hash_table_new(ssl_hash, ssl_equal);
2538
2539   if (decrypted_data->data)
2540     g_free(decrypted_data->data);
2541   ssl_data_alloc(decrypted_data, 32);
2542
2543   if (compressed_data->data)
2544     g_free(compressed_data->data);
2545   ssl_data_alloc(compressed_data, 32);
2546 }
2547
2548 /* parse ssl related preferences (private keys and ports association strings) */
2549 void
2550 ssl_parse_key_list(const gchar * keys_list, GHashTable *key_hash, GTree* associations, dissector_handle_t handle, gboolean tcp)
2551 {
2552   gchar* end;
2553   gchar* start;
2554   gchar* tmp;
2555   guchar* ip;
2556   SslService* service;
2557   Ssl_private_key_t * private_key, *tmp_private_key;
2558   FILE* fp;
2559
2560   start = strdup(keys_list);
2561   tmp = start;
2562   ssl_debug_printf("ssl_init keys string:\n%s\n", start);
2563   do {
2564     int read_index, write_index;
2565     gchar* addr, *port, *protocol, *filename, *cert_passwd;
2566
2567     addr = start;
2568     /* split ip/file couple with ';' separator*/
2569     end = strpbrk(start, ";\n\r");
2570     if (end) {
2571       *end = 0;
2572       start = end+1;
2573     }
2574
2575     /* skip comments (in file) */
2576     if (addr[0] == '#') continue;
2577
2578     /* for each entry split ip, port, protocol, filename with ',' separator */
2579     ssl_debug_printf("ssl_init found host entry %s\n", addr);
2580     port = strchr(addr, ',');
2581     if (!port)
2582       {
2583         ssl_debug_printf("ssl_init entry malformed can't find port in '%s'\n", addr);
2584         continue;
2585       }
2586     *port = 0;
2587     port++;
2588
2589     protocol = strchr(port,',');
2590     if (!protocol)
2591       {
2592         ssl_debug_printf("ssl_init entry malformed can't find protocol in %s\n", port);
2593         continue;
2594       }
2595     *protocol=0;
2596     protocol++;
2597
2598     filename = strchr(protocol,',');
2599     if (!filename)
2600     {
2601             ssl_debug_printf("ssl_init entry malformed can't find filename in %s\n", protocol);
2602             continue;
2603     }
2604     *filename=0;
2605     filename++;
2606     
2607     cert_passwd = strchr(filename,',');
2608     if (cert_passwd)
2609     {
2610             *cert_passwd=0;
2611       cert_passwd++;  
2612     }
2613     
2614     /* convert ip and port string to network rappresentation*/
2615     service = g_malloc(sizeof(SslService) + 4);
2616     service->addr.type = AT_IPv4;
2617     service->addr.len = 4;
2618     service->addr.data = ip = ((guchar*)service) + sizeof(SslService);
2619     
2620     //remove all spaces in addr
2621     read_index = 0;
2622     write_index = 0;
2623     
2624     while(addr[read_index]) {
2625       if (addr[read_index] != ' ') {
2626         addr[write_index] = addr[read_index];
2627         write_index++;
2628       }  
2629       read_index++;     
2630     }
2631     addr[write_index] = 0;
2632     
2633     if ( !strcmp("any", addr) || !strcmp("ANY", addr) ) {
2634       ip[0] = 0;
2635       ip[1] = 0;
2636       ip[2] = 0;
2637       ip[3] = 0;
2638     } else {
2639       sscanf(addr, "%hhu.%hhu.%hhu.%hhu", &ip[0], &ip[1], &ip[2], &ip[3]);
2640     }
2641     
2642     service->port = atoi(port);
2643     ssl_debug_printf("ssl_init addr '%hhu.%hhu.%hhu.%hhu' port '%d' filename '%s' password(only for p12 file) '%s'\n",
2644                      ip[0], ip[1], ip[2], ip[3], service->port, filename, cert_passwd);
2645
2646     /* try to load pen or p12 file*/
2647     fp = eth_fopen(filename, "rb");
2648     if (!fp) {
2649       fprintf(stderr, "can't open file %s \n",filename);
2650       continue;
2651     }
2652     
2653     if (!cert_passwd) {
2654       private_key = ssl_load_key(fp);
2655     }  
2656     else  
2657     {   
2658       private_key = ssl_load_pkcs12(fp,cert_passwd);
2659     }
2660     //!!!
2661     if (!private_key) {
2662       fprintf(stderr,"can't load private key from %s\n",
2663               filename);
2664       continue;
2665     }
2666         
2667     fclose(fp);
2668
2669     ssl_debug_printf("ssl_init private key file %s successfully loaded\n",filename);
2670     
2671     //if item exists, remove first 
2672     if( tmp_private_key = g_hash_table_lookup(key_hash, service) ) {
2673       g_hash_table_remove(key_hash, service);
2674       ssl_free_key(tmp_private_key);
2675     } 
2676     g_hash_table_insert(key_hash, service, private_key);
2677
2678     ssl_association_add(associations, handle, atoi(port), protocol, tcp, TRUE);
2679
2680   } while (end != NULL);
2681   free(tmp);
2682 }
2683
2684 /* store master secret into session data cache */
2685 void
2686 ssl_save_session(SslDecryptSession* ssl, GHashTable *session_hash)
2687 {
2688   /* allocate stringinfo chunks for session id and master secret data*/
2689   StringInfo* session_id;
2690   StringInfo* master_secret;
2691   session_id = se_alloc0(sizeof(StringInfo) + ssl->session_id.data_len);
2692   master_secret = se_alloc0(48 + sizeof(StringInfo));
2693
2694   master_secret->data = ((guchar*)master_secret+sizeof(StringInfo));
2695   session_id->data = ((guchar*)session_id+sizeof(StringInfo));
2696
2697   ssl_data_set(session_id, ssl->session_id.data, ssl->session_id.data_len);
2698   ssl_data_set(master_secret, ssl->master_secret.data, ssl->master_secret.data_len);
2699   g_hash_table_insert(session_hash, session_id, master_secret);
2700   ssl_print_string("ssl_save_session stored session id", session_id);
2701   ssl_print_string("ssl_save_session stored master secret", master_secret);
2702 }
2703
2704 void
2705 ssl_restore_session(SslDecryptSession* ssl, GHashTable *session_hash)
2706 {
2707   StringInfo* ms;
2708   ms = g_hash_table_lookup(session_hash, &ssl->session_id);
2709
2710   if (!ms) {
2711     ssl_debug_printf("ssl_restore_session can't find stored session\n");
2712     return;
2713   }
2714   ssl_data_set(&ssl->master_secret, ms->data, ms->data_len);
2715   ssl->state |= SSL_MASTER_SECRET;
2716   ssl_debug_printf("ssl_restore_session master key retrived\n");
2717 }
2718
2719 int
2720 ssl_is_valid_content_type(guint8 type)
2721 {
2722   if (type >= 0x14 && type <= 0x17)
2723     {
2724       return 1;
2725     }
2726
2727   return 0;
2728 }
2729
2730 #ifdef SSL_DECRYPT_DEBUG
2731
2732 static FILE* ssl_debug_file=NULL;
2733
2734 void
2735 ssl_set_debug(char* name)
2736 {
2737     static gint debug_file_must_be_closed;
2738     gint use_stderr;
2739     debug_file_must_be_closed = 0;
2740     use_stderr = name?(strcmp(name, SSL_DEBUG_USE_STDERR) == 0):0;
2741
2742     if (debug_file_must_be_closed)
2743         fclose(ssl_debug_file);
2744     if (use_stderr)
2745         ssl_debug_file = stderr;
2746     else if (!name || (strcmp(name, "") ==0))
2747         ssl_debug_file = NULL;
2748     else
2749         ssl_debug_file = eth_fopen(name, "w");
2750     if (!use_stderr && ssl_debug_file)
2751         debug_file_must_be_closed = 1;
2752 }
2753
2754 void
2755 ssl_debug_flush(void)
2756 {
2757   if (ssl_debug_file)
2758     fflush(ssl_debug_file);
2759 }
2760
2761 void
2762 ssl_debug_printf(const gchar* fmt, ...)
2763 {
2764     va_list ap;
2765     gint ret;
2766     ret=0;
2767
2768     if (!ssl_debug_file)
2769         return;
2770
2771     va_start(ap, fmt);
2772     ret += vfprintf(ssl_debug_file, fmt, ap);
2773     va_end(ap);
2774 }
2775
2776 void
2777 ssl_print_text_data(const gchar* name, const guchar* data, gint len)
2778 {
2779     gint i;
2780     if (!ssl_debug_file)
2781         return;
2782     fprintf(ssl_debug_file,"%s: ",name);
2783     for (i=0; i< len; i++) {
2784       fprintf(ssl_debug_file,"%c",data[i]);
2785     }
2786     fprintf(ssl_debug_file,"\n");
2787 }
2788
2789 void
2790 ssl_print_data(const gchar* name, const guchar* data, gint len)
2791 {
2792     gint i;
2793     if (!ssl_debug_file)
2794         return;
2795     fprintf(ssl_debug_file,"%s[%d]:\n",name, len);
2796     for (i=0; i< len; i++) {
2797         if ((i>0) && (i%16 == 0))
2798             fprintf(ssl_debug_file,"\n");
2799         fprintf(ssl_debug_file,"%.2x ",data[i]&255);
2800     }
2801     fprintf(ssl_debug_file,"\n");
2802 }
2803
2804 void
2805 ssl_print_string(const gchar* name, const StringInfo* data)
2806 {
2807     ssl_print_data(name, data->data, data->data_len);
2808 }
2809 #endif /* SSL_DECRYPT_DEBUG */