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