Define some fcns & vars as static ...
[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 <wsutil/file_util.h>
41
42 /*
43  * Lookup tables
44  */
45 const value_string ssl_version_short_names[] = {
46     { SSL_VER_UNKNOWN,    "SSL" },
47     { SSL_VER_SSLv2,      "SSLv2" },
48     { SSL_VER_SSLv3,      "SSLv3" },
49     { SSL_VER_TLS,        "TLSv1" },
50     { SSL_VER_TLSv1DOT1,  "TLSv1.1" },
51     { SSL_VER_DTLS,       "DTLSv1.0" },
52     { SSL_VER_PCT,        "PCT" },
53     { SSL_VER_TLSv1DOT2,  "TLSv1.2" },
54     { 0x00, NULL }
55 };
56
57 const value_string ssl_20_msg_types[] = {
58     { SSL2_HND_ERROR,               "Error" },
59     { SSL2_HND_CLIENT_HELLO,        "Client Hello" },
60     { SSL2_HND_CLIENT_MASTER_KEY,   "Client Master Key" },
61     { SSL2_HND_CLIENT_FINISHED,     "Client Finished" },
62     { SSL2_HND_SERVER_HELLO,        "Server Hello" },
63     { SSL2_HND_SERVER_VERIFY,       "Server Verify" },
64     { SSL2_HND_SERVER_FINISHED,     "Server Finished" },
65     { SSL2_HND_REQUEST_CERTIFICATE, "Request Certificate" },
66     { SSL2_HND_CLIENT_CERTIFICATE,  "Client Certificate" },
67     { 0x00, NULL }
68 };
69 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml */
70 const value_string ssl_20_cipher_suites[] = {
71     { 0x010080, "SSL2_RC4_128_WITH_MD5" },
72     { 0x020080, "SSL2_RC4_128_EXPORT40_WITH_MD5" },
73     { 0x030080, "SSL2_RC2_CBC_128_CBC_WITH_MD5" },
74     { 0x040080, "SSL2_RC2_CBC_128_CBC_WITH_MD5" },
75     { 0x050080, "SSL2_IDEA_128_CBC_WITH_MD5" },
76     { 0x060040, "SSL2_DES_64_CBC_WITH_MD5" },
77     { 0x0700c0, "SSL2_DES_192_EDE3_CBC_WITH_MD5" },
78     { 0x080080, "SSL2_RC4_64_WITH_MD5" },
79     { 0x000000, "TLS_NULL_WITH_NULL_NULL" },
80     { 0x000001, "TLS_RSA_WITH_NULL_MD5" },
81     { 0x000002, "TLS_RSA_WITH_NULL_SHA" },
82     { 0x000003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
83     { 0x000004, "TLS_RSA_WITH_RC4_128_MD5" },
84     { 0x000005, "TLS_RSA_WITH_RC4_128_SHA" },
85     { 0x000006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
86     { 0x000007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
87     { 0x000008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
88     { 0x000009, "TLS_RSA_WITH_DES_CBC_SHA" },
89     { 0x00000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
90     { 0x00000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
91     { 0x00000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
92     { 0x00000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
93     { 0x00000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
94     { 0x00000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
95     { 0x000010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
96     { 0x000011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
97     { 0x000012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
98     { 0x000013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
99     { 0x000014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
100     { 0x000015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
101     { 0x000016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
102     { 0x000017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
103     { 0x000018, "TLS_DH_anon_WITH_RC4_128_MD5" },
104     { 0x000019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
105     { 0x00001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
106     { 0x00001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
107     { 0x00001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
108     { 0x00001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
109 #if 0
110     { 0x00001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
111 #endif
112     /* RFC 2712 */
113     { 0x00001E, "TLS_KRB5_WITH_DES_CBC_SHA" },
114     { 0x00001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
115     { 0x000020, "TLS_KRB5_WITH_RC4_128_SHA" },
116     { 0x000021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
117     { 0x000022, "TLS_KRB5_WITH_DES_CBC_MD5" },
118     { 0x000023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
119     { 0x000024, "TLS_KRB5_WITH_RC4_128_MD5" },
120     { 0x000025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
121     { 0x000026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
122     { 0x000027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
123     { 0x000028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
124     { 0x000029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
125     { 0x00002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
126     { 0x00002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
127     /* RFC 4785 */
128     { 0x00002C, "TLS_PSK_WITH_NULL_SHA" },
129     { 0x00002D, "TLS_DHE_PSK_WITH_NULL_SHA" },
130     { 0x00002E, "TLS_RSA_PSK_WITH_NULL_SHA" },
131     /* RFC 5246 */
132     { 0x00002f, "TLS_RSA_WITH_AES_128_CBC_SHA" },
133     { 0x000030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
134     { 0x000031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
135     { 0x000032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
136     { 0x000033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
137     { 0x000034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
138     { 0x000035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
139     { 0x000036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
140     { 0x000037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
141     { 0x000038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
142     { 0x000039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
143     { 0x00003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
144     { 0x00003B, "TLS_RSA_WITH_NULL_SHA256" },
145     { 0x00003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
146     { 0x00003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
147     { 0x00003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
148     { 0x00003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
149     { 0x000040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
150     { 0x000041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
151     { 0x000042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
152     { 0x000043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
153     { 0x000044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
154     { 0x000045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
155     { 0x000046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
156     { 0x000047, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
157     { 0x000048, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
158     { 0x000049, "TLS_ECDH_ECDSA_WITH_DES_CBC_SHA" },
159     { 0x00004A, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
160     { 0x00004B, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
161     { 0x00004C, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
162     { 0x000060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
163     { 0x000061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
164     { 0x000062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
165     { 0x000063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
166     { 0x000064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
167     { 0x000065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
168     { 0x000066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
169     { 0x000067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
170     { 0x000068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
171     { 0x000069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
172     { 0x00006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
173     { 0x00006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
174     { 0x00006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
175     { 0x00006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
176         /* 0x00,0x6E-83 Unassigned  */
177     { 0x000084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
178     { 0x000085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
179     { 0x000086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
180     { 0x000087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
181     { 0x000088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
182     { 0x000089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
183     /* RFC 4279 */
184     { 0x00008A, "TLS_PSK_WITH_RC4_128_SHA" },
185     { 0x00008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
186     { 0x00008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
187     { 0x00008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
188     { 0x00008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
189     { 0x00008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
190     { 0x000090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
191     { 0x000091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
192     { 0x000092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
193     { 0x000093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
194     { 0x000094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
195     { 0x000095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
196     /* RFC 4162 */
197     { 0x000096, "TLS_RSA_WITH_SEED_CBC_SHA" },
198     { 0x000097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
199     { 0x000098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
200     { 0x000099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
201     { 0x00009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
202     { 0x00009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
203     /* RFC 5288 */
204     { 0x00009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
205     { 0x00009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
206     { 0x00009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
207     { 0x00009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
208     { 0x0000A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
209     { 0x0000A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
210     { 0x0000A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
211     { 0x0000A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
212     { 0x0000A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
213     { 0x0000A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
214     { 0x0000A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
215     { 0x0000A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
216     /* RFC 5487 */
217     { 0x0000A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
218     { 0x0000A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
219     { 0x0000AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
220     { 0x0000AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
221     { 0x0000AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
222     { 0x0000AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
223     { 0x0000AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
224     { 0x0000AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
225     { 0x0000B0, "TLS_PSK_WITH_NULL_SHA256" },
226     { 0x0000B1, "TLS_PSK_WITH_NULL_SHA384" },
227     { 0x0000B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
228     { 0x0000B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384" },
229     { 0x0000B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
230     { 0x0000B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
231     { 0x0000B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
232     { 0x0000B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
233     { 0x0000B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
234     { 0x0000B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
235     /* From RFC 5932 */
236     { 0x0000BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
237     { 0x0000BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
238     { 0x0000BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
239     { 0x0000BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
240     { 0x0000BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
241     { 0x0000BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
242     { 0x0000C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
243     { 0x0000C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
244     { 0x0000C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
245     { 0x0000C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
246     { 0x0000C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
247     { 0x0000C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
248         /* 0x00,0xC6-FE Unassigned  */
249         { 0x0000FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
250         /* 0x01-BF,* Unassigned  */
251     /* From RFC 4492 */
252     { 0x00c001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
253     { 0x00c002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
254     { 0x00c003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
255     { 0x00c004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
256     { 0x00c005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
257     { 0x00c006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
258     { 0x00c007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
259     { 0x00c008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
260     { 0x00c009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
261     { 0x00c00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
262     { 0x00c00b, "TLS_ECDH_RSA_WITH_NULL_SHA" },
263     { 0x00c00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
264     { 0x00c00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
265     { 0x00c00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
266     { 0x00c00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
267     { 0x00c010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
268     { 0x00c011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
269     { 0x00c012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
270     { 0x00c013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
271     { 0x00c014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
272     { 0x00c015, "TLS_ECDH_anon_WITH_NULL_SHA" },
273     { 0x00c016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
274     { 0x00c017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
275     { 0x00c018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
276     { 0x00c019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
277     /* RFC 5054 */
278     { 0x00C01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
279     { 0x00C01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
280     { 0x00C01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
281     { 0x00C01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
282     { 0x00C01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
283     { 0x00C01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
284     { 0x00C020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
285     { 0x00C021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
286     { 0x00C022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
287     /* RFC 5589 */
288     { 0x00C023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
289     { 0x00C024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
290     { 0x00C025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
291     { 0x00C026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
292     { 0x00C027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
293     { 0x00C028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
294     { 0x00C029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
295     { 0x00C02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
296     { 0x00C02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
297     { 0x00C02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
298     { 0x00C02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
299     { 0x00C02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
300     { 0x00C02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
301     { 0x00C030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
302     { 0x00C031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
303     { 0x00C032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
304     /* RFC 5489 */
305     { 0x00C033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA" },
306     { 0x00C034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA" },
307     { 0x00C035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA" },
308     { 0x00C036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA" },
309     { 0x00C037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" },
310     { 0x00C038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384" },
311     { 0x00C039, "TLS_ECDHE_PSK_WITH_NULL_SHA" },
312     { 0x00C03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256" },
313     { 0x00C03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384" },
314         /*      0xC0,0x3C-FF Unassigned
315                 0xC1-FD,* Unassigned
316                 0xFE,0x00-FD Unassigned
317                 0xFE,0xFE-FF Reserved to avoid conflicts with widely deployed implementations [Pasi_Eronen]
318                 0xFF,0x00-FF Reserved for Private Use [RFC5246]
319                 */
320
321     /* these from http://www.mozilla.org/projects/
322          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
323     { 0x00fefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
324     { 0x00feff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
325     { 0x00ffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
326     { 0x00ffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
327     /* Microsoft's old PCT protocol. These are from Eric Rescorla's
328        book "SSL and TLS" */
329     { 0x8f8001, "PCT_SSL_COMPAT | PCT_VERSION_1" },
330     { 0x800003, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509_CHAIN" },
331     { 0x800001, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509" },
332     { 0x810001, "PCT_SSL_HASH_TYPE | PCT1_HASH_MD5" },
333     { 0x810003, "PCT_SSL_HASH_TYPE | PCT1_HASH_SHA" },
334     { 0x820001, "PCT_SSL_EXCH_TYPE | PCT1_EXCH_RSA_PKCS1" },
335     { 0x830004, "PCT_SSL_CIPHER_TYPE_1ST_HALF | PCT1_CIPHER_RC4" },
336     { 0x848040, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_128 | PCT1_MAC_BITS_128" },
337     { 0x842840, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_40 | PCT1_MAC_BITS_128" },
338     /* note that ciphersuites of {0x00????} are TLS cipher suites in
339      * a sslv2 client hello message; the ???? above is the two-byte
340      * tls cipher suite id
341      */
342     { 0x00, NULL }
343 };
344
345 const value_string ssl_extension_curves[] = {
346     { 1, "sect163k1" },
347     { 2, "sect163r1" },
348     { 3, "sect163r2" },
349     { 4, "sect193r1" },
350     { 5, "sect193r2" },
351     { 6, "sect233k1" },
352     { 7, "sect233r1" },
353     { 8, "sect239k1" },
354     { 9, "sect283k1" },
355     { 10, "sect283r1" },
356     { 11, "sect409k1" },
357     { 12, "sect409r1" },
358     { 13, "sect571k1" },
359     { 14, "sect571r1" },
360     { 15, "secp160k1" },
361     { 16, "secp160r1" },
362     { 17, "secp160r2" },
363     { 18, "secp192k1" },
364     { 19, "secp192r1" },
365     { 20, "secp224k1" },
366     { 21, "secp224r1" },
367     { 22, "secp256k1" },
368     { 23, "secp256r1" },
369     { 24, "secp384r1" },
370     { 25, "secp521r1" },
371     { 0xFF01, "arbitrary_explicit_prime_curves" },
372     { 0xFF02, "arbitrary_explicit_char2_curves" },
373     { 0x00, NULL }
374 };
375
376 const value_string ssl_extension_ec_point_formats[] = {
377     { 0, "uncompressed" },
378     { 1, "ansiX962_compressed_prime" },
379     { 2, "ansiX962_compressed_char2" },
380     { 0x00, NULL }
381 };
382
383 const value_string ssl_20_certificate_type[] = {
384     { 0x00, "N/A" },
385     { 0x01, "X.509 Certificate" },
386     { 0x00, NULL }
387 };
388
389 const value_string ssl_31_content_type[] = {
390     { 20, "Change Cipher Spec" },
391     { 21, "Alert" },
392     { 22, "Handshake" },
393     { 23, "Application Data" },
394     { 0x00, NULL }
395 };
396
397 const value_string ssl_versions[] = {
398     { 0xfeff, "DTLS 1.0" },
399     { 0x0100, "DTLS 1.0 (OpenSSL pre 0.9.8f)" },
400     { 0x0303, "TLS 1.2" },
401     { 0x0302, "TLS 1.1" },
402     { 0x0301, "TLS 1.0" },
403     { 0x0300, "SSL 3.0" },
404     { 0x0002, "SSL 2.0" },
405     { 0x00, NULL }
406 };
407
408 #if 0
409 /* XXX - would be used if we dissected the body of a Change Cipher Spec
410    message. */
411 const value_string ssl_31_change_cipher_spec[] = {
412     { 1, "Change Cipher Spec" },
413     { 0x00, NULL }
414 };
415 #endif
416
417 const value_string ssl_31_alert_level[] = {
418     { 1, "Warning" },
419     { 2, "Fatal" },
420     { 0x00, NULL }
421 };
422
423 const value_string ssl_31_alert_description[] = {
424     {  0,  "Close Notify" },
425     { 10,  "Unexpected Message" },
426     { 20,  "Bad Record MAC" },
427     { 21,  "Decryption Failed" },
428     { 22,  "Record Overflow" },
429     { 30,  "Decompression Failure" },
430     { 40,  "Handshake Failure" },
431     { 41,  "No Certificate" },
432     { 42,  "Bad Certificate" },
433     { 43,  "Unsupported Certificate" },
434     { 44,  "Certificate Revoked" },
435     { 45,  "Certificate Expired" },
436     { 46,  "Certificate Unknown" },
437     { 47,  "Illegal Parameter" },
438     { 48,  "Unknown CA" },
439     { 49,  "Access Denied" },
440     { 50,  "Decode Error" },
441     { 51,  "Decrypt Error" },
442     { 60,  "Export Restriction" },
443     { 70,  "Protocol Version" },
444     { 71,  "Insufficient Security" },
445     { 80,  "Internal Error" },
446     { 90,  "User Canceled" },
447     { 100, "No Renegotiation" },
448     { 110, "Unsupported Extension" },
449     { 111, "Certificate Unobtainable" },
450     { 112, "Unrecognized Name" },
451     { 113, "Bad Certificate Status Response" },
452     { 114, "Bad Certificate Hash Value" },
453     { 115, "Unknown PSK Identity" },
454     { 0x00, NULL }
455 };
456
457 const value_string ssl_31_handshake_type[] = {
458     { SSL_HND_HELLO_REQUEST,     "Hello Request" },
459     { SSL_HND_CLIENT_HELLO,      "Client Hello" },
460     { SSL_HND_SERVER_HELLO,      "Server Hello" },
461     { SSL_HND_HELLO_VERIFY_REQUEST, "Hello Verify Request"},
462     { SSL_HND_CERTIFICATE,       "Certificate" },
463     { SSL_HND_SERVER_KEY_EXCHG,  "Server Key Exchange" },
464     { SSL_HND_CERT_REQUEST,      "Certificate Request" },
465     { SSL_HND_SVR_HELLO_DONE,    "Server Hello Done" },
466     { SSL_HND_CERT_VERIFY,       "Certificate Verify" },
467     { SSL_HND_CLIENT_KEY_EXCHG,  "Client Key Exchange" },
468     { SSL_HND_FINISHED,          "Finished" },
469     { 0x00, NULL }
470 };
471
472 const value_string ssl_31_compression_method[] = {
473     { 0, "null" },
474     { 1, "DEFLATE" },
475     { 64, "LZS" },
476     { 0x00, NULL }
477 };
478
479 #if 0
480 /* XXX - would be used if we dissected a Signature, as would be
481    seen in a server key exchange or certificate verify message. */
482 const value_string ssl_31_key_exchange_algorithm[] = {
483     { 0, "RSA" },
484     { 1, "Diffie Hellman" },
485     { 0x00, NULL }
486 };
487
488 const value_string ssl_31_signature_algorithm[] = {
489     { 0, "Anonymous" },
490     { 1, "RSA" },
491     { 2, "DSA" },
492     { 0x00, NULL }
493 };
494 #endif
495
496 const value_string ssl_31_client_certificate_type[] = {
497     { 1, "RSA Sign" },
498     { 2, "DSS Sign" },
499     { 3, "RSA Fixed DH" },
500     { 4, "DSS Fixed DH" },
501     { 64, "ECDSA Sign" },
502     { 65, "RSA Fixed ECDH" },
503     { 66, "ECDSA Fixed ECDH" },
504     { 0x00, NULL }
505 };
506
507 #if 0
508 /* XXX - would be used if we dissected exchange keys, as would be
509    seen in a client key exchange message. */
510 const value_string ssl_31_public_value_encoding[] = {
511     { 0, "Implicit" },
512     { 1, "Explicit" },
513     { 0x00, NULL }
514 };
515 #endif
516 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml */
517
518 const value_string ssl_31_ciphersuite[] = {
519     /* RFC 2246, RFC 4346, RFC 5246 */
520     { 0x0000, "TLS_NULL_WITH_NULL_NULL" },
521     { 0x0001, "TLS_RSA_WITH_NULL_MD5" },
522     { 0x0002, "TLS_RSA_WITH_NULL_SHA" },
523     { 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
524     { 0x0004, "TLS_RSA_WITH_RC4_128_MD5" },
525     { 0x0005, "TLS_RSA_WITH_RC4_128_SHA" },
526     { 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
527     { 0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
528     { 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
529     { 0x0009, "TLS_RSA_WITH_DES_CBC_SHA" },
530     { 0x000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
531     { 0x000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
532     { 0x000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
533     { 0x000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
534     { 0x000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
535     { 0x000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
536     { 0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
537     { 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
538     { 0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
539     { 0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
540     { 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
541     { 0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
542     { 0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
543     { 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
544     { 0x0018, "TLS_DH_anon_WITH_RC4_128_MD5" },
545     { 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
546     { 0x001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
547     { 0x001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
548
549     { 0x001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
550     { 0x001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
551 #if 0 /* Because it clashes with KRB5, is never used any more, and is safe
552          to remove according to David Hopwood <david.hopwood@zetnet.co.uk>
553          of the ietf-tls list */
554     { 0x001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
555 #endif
556
557     /* RFC 2712 */
558     { 0x001E, "TLS_KRB5_WITH_DES_CBC_SHA" },
559     { 0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
560     { 0x0020, "TLS_KRB5_WITH_RC4_128_SHA" },
561     { 0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
562     { 0x0022, "TLS_KRB5_WITH_DES_CBC_MD5" },
563     { 0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
564     { 0x0024, "TLS_KRB5_WITH_RC4_128_MD5" },
565     { 0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
566     { 0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
567     { 0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
568     { 0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
569     { 0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
570     { 0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
571     { 0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
572
573     /* RFC 4785 */
574     { 0x002C, "TLS_PSK_WITH_NULL_SHA" },
575     { 0x002D, "TLS_DHE_PSK_WITH_NULL_SHA" },
576     { 0x002E, "TLS_RSA_PSK_WITH_NULL_SHA" },
577
578     /* RFC 5246 */
579     { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA" },
580     { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
581     { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
582     { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
583     { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
584     { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
585     { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
586     { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
587     { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
588     { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
589     { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
590     { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
591     { 0x003B, "TLS_RSA_WITH_NULL_SHA256" },
592     { 0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
593     { 0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
594     { 0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
595     { 0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
596     { 0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
597     { 0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
598     { 0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
599     { 0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
600     { 0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
601     { 0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
602     { 0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
603     { 0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
604
605         /* 0x00,0x60-66 Reserved to avoid conflicts with widely deployed implementations  */
606     /* ??? */
607     { 0x0060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
608     { 0x0061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
609
610     /* draft-ietf-tls-56-bit-ciphersuites-01.txt */
611     { 0x0062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
612     { 0x0063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
613     { 0x0064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
614     { 0x0065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
615     { 0x0066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
616
617     /* RFC 4132 */
618     { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
619     { 0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
620     { 0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
621     { 0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
622     { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
623     { 0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
624     { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
625     { 0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
626     { 0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
627     { 0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
628     { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
629     { 0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
630
631     /* RFC 4279 */
632     { 0x008A, "TLS_PSK_WITH_RC4_128_SHA" },
633     { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
634     { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
635     { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
636     { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
637     { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
638     { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
639     { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
640     { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
641     { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
642     { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
643     { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
644
645     /* RFC 4162 */
646     { 0x0096, "TLS_RSA_WITH_SEED_CBC_SHA" },
647     { 0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
648     { 0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
649     { 0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
650     { 0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
651     { 0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
652
653     /* RFC 5288 */
654     { 0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
655     { 0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
656     { 0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
657     { 0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
658     { 0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
659     { 0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
660     { 0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
661     { 0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
662     { 0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
663     { 0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
664     { 0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
665     { 0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
666
667     /* RFC 5487 */
668     { 0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
669     { 0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
670     { 0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
671     { 0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
672     { 0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
673     { 0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
674     { 0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
675     { 0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
676     { 0x00B0, "TLS_PSK_WITH_NULL_SHA256" },
677     { 0x00B1, "TLS_PSK_WITH_NULL_SHA384" },
678     { 0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
679     { 0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384" },
680     { 0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
681     { 0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
682     { 0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
683     { 0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
684     { 0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
685     { 0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
686
687     /* From RFC 5932 */
688     { 0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
689     { 0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
690     { 0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
691     { 0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
692     { 0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
693     { 0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
694     { 0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
695     { 0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
696     { 0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
697     { 0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
698     { 0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
699     { 0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
700         /* 0x00,0xC6-FE Unassigned  */
701     /* From RFC 5746 */
702     { 0x0000FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
703         /* 0x01-BF,* Unassigned */
704     /* From RFC 4492 */
705     { 0xc001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
706     { 0xc002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
707     { 0xc003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
708     { 0xc004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
709     { 0xc005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
710     { 0xc006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
711     { 0xc007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
712     { 0xc008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
713     { 0xc009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
714     { 0xc00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
715     { 0xc00b, "TLS_ECDH_RSA_WITH_NULL_SHA" },
716     { 0xc00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
717     { 0xc00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
718     { 0xc00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
719     { 0xc00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
720     { 0xc010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
721     { 0xc011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
722     { 0xc012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
723     { 0xc013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
724     { 0xc014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
725     { 0xc015, "TLS_ECDH_anon_WITH_NULL_SHA" },
726     { 0xc016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
727     { 0xc017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
728     { 0xc018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
729     { 0xc019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
730
731     /* RFC 5054 */
732     { 0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
733     { 0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
734     { 0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
735     { 0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
736     { 0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
737     { 0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
738     { 0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
739     { 0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
740     { 0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
741
742     /* RFC 5589 */
743     { 0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
744     { 0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
745     { 0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
746     { 0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
747     { 0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
748     { 0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
749     { 0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
750     { 0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
751     { 0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
752     { 0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
753     { 0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
754     { 0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
755     { 0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
756     { 0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
757     { 0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
758     { 0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
759
760     /* RFC 5489 */
761     { 0xC033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA" },
762     { 0xC034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA" },
763     { 0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA" },
764     { 0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA" },
765     { 0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" },
766     { 0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384" },
767     { 0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA" },
768     { 0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256" },
769     { 0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384" },
770 /*
771 0xC0,0x3C-FF Unassigned
772 0xC1-FD,* Unassigned
773 0xFE,0x00-FD Unassigned
774 0xFE,0xFE-FF Reserved to avoid conflicts with widely deployed implementations [Pasi_Eronen]
775 0xFF,0x00-FF Reserved for Private Use [RFC5246]
776 */
777     /* these from http://www.mozilla.org/projects/
778          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
779     { 0xfefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
780     { 0xfeff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
781     { 0xffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
782     { 0xffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
783     /* note that ciphersuites 0xff00 - 0xffff are private */
784     { 0x00, NULL }
785 };
786
787 const value_string pct_msg_types[] = {
788     { PCT_MSG_CLIENT_HELLO,         "Client Hello" },
789     { PCT_MSG_SERVER_HELLO,         "Server Hello" },
790     { PCT_MSG_CLIENT_MASTER_KEY,    "Client Master Key" },
791     { PCT_MSG_SERVER_VERIFY,        "Server Verify" },
792     { PCT_MSG_ERROR,                "Error" },
793     { 0x00, NULL }
794 };
795
796 const value_string pct_cipher_type[] = {
797     { PCT_CIPHER_DES, "DES" },
798     { PCT_CIPHER_IDEA, "IDEA" },
799     { PCT_CIPHER_RC2, "RC2" },
800     { PCT_CIPHER_RC4, "RC4" },
801     { PCT_CIPHER_DES_112, "DES 112 bit" },
802     { PCT_CIPHER_DES_168, "DES 168 bit" },
803     { 0x00, NULL }
804 };
805
806 const value_string pct_hash_type[] = {
807     { PCT_HASH_MD5, "MD5" },
808     { PCT_HASH_MD5_TRUNC_64, "MD5_TRUNC_64"},
809     { PCT_HASH_SHA, "SHA"},
810     { PCT_HASH_SHA_TRUNC_80, "SHA_TRUNC_80"},
811     { PCT_HASH_DES_DM, "DES_DM"},
812     { 0x00, NULL }
813 };
814
815 const value_string pct_cert_type[] = {
816     { PCT_CERT_NONE, "None" },
817     { PCT_CERT_X509, "X.509" },
818     { PCT_CERT_PKCS7, "PKCS #7" },
819     { 0x00, NULL }
820 };
821 const value_string pct_sig_type[] = {
822     { PCT_SIG_NONE, "None" },
823     { PCT_SIG_RSA_MD5, "MD5" },
824     { PCT_SIG_RSA_SHA, "RSA SHA" },
825     { PCT_SIG_DSA_SHA, "DSA SHA" },
826     { 0x00, NULL }
827 };
828
829 const value_string pct_exch_type[] = {
830     { PCT_EXCH_RSA_PKCS1, "RSA PKCS#1" },
831     { PCT_EXCH_RSA_PKCS1_TOKEN_DES, "RSA PKCS#1 Token DES" },
832     { PCT_EXCH_RSA_PKCS1_TOKEN_DES3, "RSA PKCS#1 Token 3DES" },
833     { PCT_EXCH_RSA_PKCS1_TOKEN_RC2, "RSA PKCS#1 Token RC-2" },
834     { PCT_EXCH_RSA_PKCS1_TOKEN_RC4, "RSA PKCS#1 Token RC-4" },
835     { PCT_EXCH_DH_PKCS3, "DH PKCS#3" },
836     { PCT_EXCH_DH_PKCS3_TOKEN_DES, "DH PKCS#3 Token DES" },
837     { PCT_EXCH_DH_PKCS3_TOKEN_DES3, "DH PKCS#3 Token 3DES" },
838     { PCT_EXCH_FORTEZZA_TOKEN, "Fortezza" },
839     { 0x00, NULL }
840 };
841
842 const value_string pct_error_code[] = {
843     { PCT_ERR_BAD_CERTIFICATE, "PCT_ERR_BAD_CERTIFICATE" },
844     { PCT_ERR_CLIENT_AUTH_FAILED, "PCT_ERR_CLIENT_AUTH_FAILE" },
845     { PCT_ERR_ILLEGAL_MESSAGE, "PCT_ERR_ILLEGAL_MESSAGE" },
846     { PCT_ERR_INTEGRITY_CHECK_FAILED, "PCT_ERR_INTEGRITY_CHECK_FAILED" },
847     { PCT_ERR_SERVER_AUTH_FAILED, "PCT_ERR_SERVER_AUTH_FAILED" },
848     { PCT_ERR_SPECS_MISMATCH, "PCT_ERR_SPECS_MISMATCH" },
849     { 0x00, NULL }
850 };
851
852 /* RFC 4366 */
853 const value_string tls_hello_extension_types[] = {
854     { 0, "server_name" },
855     { 1, "max_fragment_length" },
856     { 2, "client_certificate_url" },
857     { 3, "trusted_ca_keys" },
858     { 4, "truncated_hmac" },
859     { 5, "status_request" },
860     { 6, "user_mapping" },  /* RFC 4681 */
861     { 7, "client_authz" },
862     { 8, "server_authz" },
863     { 9, "cert_type" },  /* RFC 5081 */
864     { SSL_HND_HELLO_EXT_ELLIPTIC_CURVES, "elliptic_curves" },  /* RFC 4492 */
865     { SSL_HND_HELLO_EXT_EC_POINT_FORMATS, "ec_point_formats" },  /* RFC 4492 */
866     { 12, "srp" },  /* RFC 5054 */
867     { 13, "signature_algorithms" },  /* RFC 5246 */
868     { 14, "use_srtp" },
869     { 35, "SessionTicket TLS" },  /* RFC 4507 */
870     { 65281, "renegotiation_info" },
871     { 0, NULL }
872 };
873
874
875 /* we keep this internal to packet-ssl-utils, as there should be
876    no need to access it any other way.
877
878    This also allows us to hide the dependency on zlib.
879 */
880 struct _SslDecompress {
881     gint compression;
882 #ifdef HAVE_LIBZ
883     z_stream istream;
884 #endif
885 };
886
887 static gint
888 ssl_data_alloc(StringInfo* str, size_t len)
889 {
890     str->data = g_malloc(len);
891     /* the allocator can return a null pointer for a size equal to 0,
892      * and that must be allowed */
893     if (len > 0 && !str->data)
894         return -1;
895     str->data_len = (guint) len;
896     return 0;
897 }
898
899 void
900 ssl_data_set(StringInfo* str, const guchar* data, guint len)
901 {
902     memcpy(str->data, data, len);
903     str->data_len = len;
904 }
905
906 #ifdef HAVE_LIBGNUTLS
907
908 static gint ver_major, ver_minor, ver_patch;
909
910 /* hmac abstraction layer */
911 #define SSL_HMAC gcry_md_hd_t
912
913 static inline gint
914 ssl_hmac_init(SSL_HMAC* md, const void * key, gint len, gint algo)
915 {
916     gcry_error_t err;
917     const char *err_str, *err_src;
918     err = gcry_md_open(md,algo, GCRY_MD_FLAG_HMAC);
919     if (err != 0) {
920         err_str = gcry_strerror(err);
921         err_src = gcry_strsource(err);
922         ssl_debug_printf("ssl_hmac_init(): gcry_md_open failed %s/%s", err_str, err_src);
923         return -1;
924     }
925     gcry_md_setkey (*(md), key, len);
926     return 0;
927 }
928 static inline void
929 ssl_hmac_update(SSL_HMAC* md, const void* data, gint len)
930 {
931     gcry_md_write(*(md), data, len);
932 }
933 static inline void
934 ssl_hmac_final(SSL_HMAC* md, guchar* data, guint* datalen)
935 {
936     gint algo;
937     guint len;
938     algo = gcry_md_get_algo (*(md));
939     len = gcry_md_get_algo_dlen(algo);
940     memcpy(data, gcry_md_read(*(md), algo), len);
941     *datalen =len;
942 }
943 static inline void
944 ssl_hmac_cleanup(SSL_HMAC* md)
945 {
946     gcry_md_close(*(md));
947 }
948
949 /* memory digest abstraction layer*/
950 #define SSL_MD gcry_md_hd_t
951
952 static inline gint
953 ssl_md_init(SSL_MD* md, gint algo)
954 {
955     gcry_error_t err;
956     const char *err_str, *err_src;
957     err = gcry_md_open(md,algo, 0);
958     if (err != 0) {
959         err_str = gcry_strerror(err);
960         err_src = gcry_strsource(err);
961         ssl_debug_printf("ssl_md_init(): gcry_md_open failed %s/%s", err_str, err_src);
962         return -1;
963     }
964     return 0;
965 }
966 static inline void
967 ssl_md_update(SSL_MD* md, guchar* data, gint len)
968 {
969     gcry_md_write(*(md), data, len);
970 }
971 static inline void
972 ssl_md_final(SSL_MD* md, guchar* data, guint* datalen)
973 {
974     gint algo;
975     gint len;
976     algo = gcry_md_get_algo (*(md));
977     len = gcry_md_get_algo_dlen (algo);
978     memcpy(data, gcry_md_read(*(md),  algo), len);
979     *datalen = len;
980 }
981 static inline void
982 ssl_md_cleanup(SSL_MD* md)
983 {
984     gcry_md_close(*(md));
985 }
986
987 /* md5 /sha abstraction layer */
988 #define SSL_SHA_CTX gcry_md_hd_t
989 #define SSL_MD5_CTX gcry_md_hd_t
990
991 static inline void
992 ssl_sha_init(SSL_SHA_CTX* md)
993 {
994     gcry_md_open(md,GCRY_MD_SHA1, 0);
995 }
996 static inline void
997 ssl_sha_update(SSL_SHA_CTX* md, guchar* data, gint len)
998 {
999     gcry_md_write(*(md), data, len);
1000 }
1001 static inline void
1002 ssl_sha_final(guchar* buf, SSL_SHA_CTX* md)
1003 {
1004     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_SHA1),
1005         gcry_md_get_algo_dlen(GCRY_MD_SHA1));
1006 }
1007 static inline void
1008 ssl_sha_cleanup(SSL_SHA_CTX* md)
1009 {
1010     gcry_md_close(*(md));
1011 }
1012
1013 static inline gint
1014 ssl_md5_init(SSL_MD5_CTX* md)
1015 {
1016     return gcry_md_open(md,GCRY_MD_MD5, 0);
1017 }
1018 static inline void
1019 ssl_md5_update(SSL_MD5_CTX* md, guchar* data, gint len)
1020 {
1021     gcry_md_write(*(md), data, len);
1022 }
1023 static inline void
1024 ssl_md5_final(guchar* buf, SSL_MD5_CTX* md)
1025 {
1026     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_MD5),
1027         gcry_md_get_algo_dlen(GCRY_MD_MD5));
1028 }
1029 static inline void
1030 ssl_md5_cleanup(SSL_MD5_CTX* md)
1031 {
1032     gcry_md_close(*(md));
1033 }
1034
1035 gint
1036 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher, guchar* iv, gint iv_len)
1037 {
1038     /* guchar * ivp; */
1039     gint ret;
1040     /* gint i; */
1041     gcry_cipher_hd_t c;
1042     ret=0;
1043     c=(gcry_cipher_hd_t)*cipher;
1044
1045     ssl_debug_printf("--------------------------------------------------------------------");
1046     /*for(ivp=c->iv,i=0; i < iv_len; i++ )
1047         {
1048         ssl_debug_printf("%d ",ivp[i]);
1049         i++;
1050         }
1051     */
1052     ssl_debug_printf("--------------------------------------------------------------------");
1053     ret = gcry_cipher_setiv(*(cipher), iv, iv_len);
1054     /*for(ivp=c->iv,i=0; i < iv_len; i++ )
1055         {
1056         ssl_debug_printf("%d ",ivp[i]);
1057         i++;
1058         }
1059     */
1060     ssl_debug_printf("--------------------------------------------------------------------");
1061     return ret;
1062 }
1063 /* stream cipher abstraction layer*/
1064 static gint
1065 ssl_cipher_init(gcry_cipher_hd_t *cipher, gint algo, guchar* sk,
1066         guchar* iv, gint mode)
1067 {
1068     gint gcry_modes[]={GCRY_CIPHER_MODE_STREAM,GCRY_CIPHER_MODE_CBC};
1069     gint err;
1070     if (algo == -1) {
1071         /* NULL mode */
1072         *(cipher) = (gcry_cipher_hd_t)-1;
1073         return 0;
1074     }
1075     err = gcry_cipher_open(cipher, algo, gcry_modes[mode], 0);
1076     if (err !=0)
1077         return  -1;
1078     err = gcry_cipher_setkey(*(cipher), sk, gcry_cipher_get_algo_keylen (algo));
1079     if (err != 0)
1080         return -1;
1081     err = gcry_cipher_setiv(*(cipher), iv, gcry_cipher_get_algo_blklen (algo));
1082     if (err != 0)
1083         return -1;
1084     return 0;
1085 }
1086 static inline gint
1087 ssl_cipher_decrypt(gcry_cipher_hd_t *cipher, guchar * out, gint outl,
1088                    const guchar * in, gint inl)
1089 {
1090     if ((*cipher) == (gcry_cipher_hd_t)-1)
1091     {
1092         if (in && inl)
1093             memcpy(out, in, outl < inl ? outl : inl);
1094         return 0;
1095     }
1096     return gcry_cipher_decrypt ( *(cipher), out, outl, in, inl);
1097 }
1098 static inline gint
1099 ssl_get_digest_by_name(const gchar*name)
1100 {
1101     return gcry_md_map_name(name);
1102 }
1103 static inline gint
1104 ssl_get_cipher_by_name(const gchar* name)
1105 {
1106     return gcry_cipher_map_name(name);
1107 }
1108
1109 static inline void
1110 ssl_cipher_cleanup(gcry_cipher_hd_t *cipher)
1111 {
1112     if ((*cipher) != (gcry_cipher_hd_t)-1)
1113         gcry_cipher_close(*cipher);
1114     *cipher = NULL;
1115 }
1116
1117 /* private key abstraction layer */
1118 static inline gint
1119 ssl_get_key_len(SSL_PRIVATE_KEY* pk) {return gcry_pk_get_nbits (pk); }
1120
1121 gcry_err_code_t
1122 _gcry_rsa_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
1123                    gcry_mpi_t *skey, gint flags);
1124
1125 #define PUBKEY_FLAG_NO_BLINDING (1 << 0)
1126
1127 const gchar*
1128 ssl_private_key_to_str(SSL_PRIVATE_KEY* pk)
1129 {
1130     const gchar *str="NULL";
1131     size_t n;
1132     gchar *buf;
1133
1134     if (!pk) return str;
1135 #ifndef SSL_FAST
1136     n = gcry_sexp_sprint(pk, GCRYSEXP_FMT_ADVANCED, NULL, 0);
1137     buf = ep_alloc(n);
1138     n = gcry_sexp_sprint(pk, GCRYSEXP_FMT_ADVANCED, buf, n);
1139     str = buf;
1140 #else /* SSL_FAST */
1141     str = "TO DO: dump mpi gcry_mpi_print()";
1142 #endif /* SSL_FAST */
1143
1144     return str;
1145 }
1146
1147 /* decrypt data with private key. Store decrypted data directly into input
1148  * buffer */
1149 int
1150 ssl_private_decrypt(guint len, guchar* encr_data, SSL_PRIVATE_KEY* pk)
1151 {
1152     gint rc;
1153     size_t decr_len;
1154     gcry_sexp_t  s_data, s_plain;
1155     gcry_mpi_t encr_mpi;
1156     size_t i, encr_len;
1157     guchar* decr_data_ptr;
1158     gcry_mpi_t text;
1159     decr_len = 0;
1160     encr_len = len;
1161     text=NULL;
1162
1163     /* build up a mpi rappresentation for encrypted data */
1164     rc = gcry_mpi_scan(&encr_mpi, GCRYMPI_FMT_USG,encr_data, encr_len, &encr_len);
1165     if (rc != 0 ) {
1166         ssl_debug_printf("pcry_private_decrypt: can't convert encr_data to mpi (size %d):%s\n",
1167             len, gcry_strerror(rc));
1168         return 0;
1169     }
1170
1171     /*ssl_debug_printf("pcry_private_decrypt: pk=%s\n", ssl_private_key_to_str(pk));*/
1172
1173 #ifndef SSL_FAST
1174     /* put the data into a simple list */
1175     rc = gcry_sexp_build(&s_data, NULL, "(enc-val(rsa(a%m)))", encr_mpi);
1176     if (rc != 0) {
1177         ssl_debug_printf("pcry_private_decrypt: can't build encr_sexp:%s \n",
1178              gcry_strerror(rc));
1179         return 0;
1180     }
1181
1182     /* pass it to libgcrypt */
1183     rc = gcry_pk_decrypt(&s_plain, s_data, pk);
1184     gcry_sexp_release(s_data);
1185     if (rc != 0)
1186     {
1187         ssl_debug_printf("pcry_private_decrypt: can't decrypt key:%s\n",
1188             gcry_strerror(rc));
1189         goto out;
1190     }
1191
1192     /* convert plain text sexp to mpi format */
1193     text = gcry_sexp_nth_mpi(s_plain, 0, 0);
1194
1195     /* compute size requested for plaintext buffer */
1196     decr_len = len;
1197     if (gcry_mpi_print(GCRYMPI_FMT_USG, NULL, decr_len, &decr_len, text) != 0) {
1198         ssl_debug_printf("pcry_private_decrypt: can't compute decr size:%s\n",
1199             gcry_strerror(rc));
1200         decr_len = 0;
1201         goto out;
1202     }
1203
1204     /* sanity check on out buffer */
1205     if (decr_len > len) {
1206         ssl_debug_printf("pcry_private_decrypt: decrypted data is too long ?!? (%" G_GSIZE_MODIFIER "u max %d)\n",
1207             decr_len, len);
1208         return 0;
1209     }
1210
1211     /* write plain text to encrypted data buffer */
1212     decr_data_ptr = encr_data;
1213     if (gcry_mpi_print( GCRYMPI_FMT_USG, decr_data_ptr, decr_len, &decr_len,
1214             text) != 0) {
1215         ssl_debug_printf("pcry_private_decrypt: can't print decr data to mpi (size %" G_GSIZE_MODIFIER "u):%s\n",
1216             decr_len, gcry_strerror(rc));
1217         g_free(decr_data_ptr);
1218         decr_len = 0;
1219         goto out;
1220     }
1221
1222     /* strip the padding*/
1223     rc = 0;
1224     for (i = 1; i < decr_len; i++) {
1225         if (decr_data_ptr[i] == 0) {
1226             rc = (gint) i+1;
1227             break;
1228         }
1229     }
1230
1231     ssl_debug_printf("pcry_private_decrypt: stripping %d bytes, decr_len %" G_GSIZE_MODIFIER "u\n",
1232         rc, decr_len);
1233     ssl_print_data("decrypted_unstrip_pre_master", decr_data_ptr, decr_len);
1234     g_memmove(decr_data_ptr, &decr_data_ptr[rc], decr_len - rc);
1235     decr_len -= rc;
1236
1237 out:
1238     gcry_sexp_release(s_plain);
1239 #else /* SSL_FAST */
1240     rc = _gcry_rsa_decrypt(0, &text,  &encr_mpi, pk,0);
1241     gcry_mpi_print( GCRYMPI_FMT_USG, 0, 0, &decr_len, text);
1242
1243     /* sanity check on out buffer */
1244     if (decr_len > len) {
1245         ssl_debug_printf("pcry_private_decrypt: decrypted data is too long ?!? (%d max %d)\n",
1246             decr_len, len);
1247         return 0;
1248     }
1249
1250     /* write plain text to newly allocated buffer */
1251     decr_data_ptr = encr_data;
1252     if (gcry_mpi_print( GCRYMPI_FMT_USG, decr_data_ptr, decr_len, &decr_len,
1253             text) != 0) {
1254         ssl_debug_printf("pcry_private_decrypt: can't print decr data to mpi (size %d):%s\n",
1255             decr_len, gcry_strerror(rc));
1256         return 0;
1257     }
1258
1259     /* strip the padding*/
1260     rc = 0;
1261     for (i = 1; i < decr_len; i++) {
1262         if (decr_data_ptr[i] == 0) {
1263             rc = i+1;
1264             break;
1265         }
1266     }
1267
1268     ssl_debug_printf("pcry_private_decrypt: stripping %d bytes, decr_len %d\n",
1269         rc, decr_len);
1270     ssl_print_data("decrypted_unstrip_pre_master", decr_data_ptr, decr_len);
1271     g_memmove(decr_data_ptr, &decr_data_ptr[rc], decr_len - rc);
1272     decr_len -= rc;
1273 #endif /* SSL_FAST */
1274     gcry_mpi_release(text);
1275     return (int) decr_len;
1276 }
1277
1278 /* stringinfo interface */
1279 static gint
1280 ssl_data_realloc(StringInfo* str, guint len)
1281 {
1282     str->data = g_realloc(str->data, len);
1283     if (!str->data)
1284         return -1;
1285     str->data_len = len;
1286     return 0;
1287 }
1288
1289 static gint
1290 ssl_data_copy(StringInfo* dst, StringInfo* src)
1291 {
1292     if (dst->data_len < src->data_len) {
1293       if (ssl_data_realloc(dst, src->data_len))
1294         return -1;
1295     }
1296     memcpy(dst->data, src->data, src->data_len);
1297     dst->data_len = src->data_len;
1298     return 0;
1299 }
1300
1301 #define PRF(ssl,secret,usage,rnd1,rnd2,out) ((ssl->version_netorder==SSLV3_VERSION)? \
1302         ssl3_prf(secret,usage,rnd1,rnd2,out): \
1303         tls_prf(secret,usage,rnd1,rnd2,out))
1304
1305 static const gchar *digests[]={
1306     "MD5",
1307     "SHA1"
1308 };
1309
1310 static const gchar *ciphers[]={
1311     "DES",
1312     "3DES",
1313     "ARCFOUR", /* gnutls does not support rc4, but this should be 100% compatible*/
1314     "RC2",
1315     "IDEA",
1316     "AES",
1317     "AES256",
1318     "*UNKNOWN*"
1319 };
1320
1321 static SslCipherSuite cipher_suites[]={
1322     {1,KEX_RSA,SIG_RSA,ENC_NULL,1,0,0,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
1323     {2,KEX_RSA,SIG_RSA,ENC_NULL,1,0,0,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
1324     {3,KEX_RSA,SIG_RSA,ENC_RC4,1,128,40,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
1325     {4,KEX_RSA,SIG_RSA,ENC_RC4,1,128,128,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
1326     {5,KEX_RSA,SIG_RSA,ENC_RC4,1,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
1327     {6,KEX_RSA,SIG_RSA,ENC_RC2,8,128,40,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
1328     {7,KEX_RSA,SIG_RSA,ENC_IDEA,8,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
1329     {8,KEX_RSA,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
1330     {9,KEX_RSA,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1331     {10,KEX_RSA,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1332     {11,KEX_DH,SIG_DSS,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
1333     {12,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1334     {13,KEX_DH,SIG_DSS,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1335     {14,KEX_DH,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
1336     {15,KEX_DH,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1337     {16,KEX_DH,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1338     {17,KEX_DH,SIG_DSS,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
1339     {18,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1340     {19,KEX_DH,SIG_DSS,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1341     {20,KEX_DH,SIG_RSA,ENC_DES,8,64,40,DIG_SHA,20,1, SSL_CIPHER_MODE_CBC},
1342     {21,KEX_DH,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1343     {22,KEX_DH,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1344     {23,KEX_DH,SIG_NONE,ENC_RC4,1,128,40,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
1345     {24,KEX_DH,SIG_NONE,ENC_RC4,1,128,128,DIG_MD5,16,0, SSL_CIPHER_MODE_STREAM},
1346     {25,KEX_DH,SIG_NONE,ENC_DES,8,64,40,DIG_MD5,16,1, SSL_CIPHER_MODE_CBC},
1347     {26,KEX_DH,SIG_NONE,ENC_DES,8,64,64,DIG_MD5,16,0, SSL_CIPHER_MODE_CBC},
1348     {27,KEX_DH,SIG_NONE,ENC_3DES,8,192,192,DIG_MD5,16,0, SSL_CIPHER_MODE_CBC},
1349     {47,KEX_RSA,SIG_RSA,ENC_AES,16,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1350     {51,KEX_DH, SIG_RSA,ENC_AES,16,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1351     {53,KEX_RSA,SIG_RSA,ENC_AES256,16,256,256,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1352     {96,KEX_RSA,SIG_RSA,ENC_RC4,1,128,56,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
1353     {97,KEX_RSA,SIG_RSA,ENC_RC2,1,128,56,DIG_MD5,16,1, SSL_CIPHER_MODE_STREAM},
1354     {98,KEX_RSA,SIG_RSA,ENC_DES,8,64,64,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
1355     {99,KEX_DH,SIG_DSS,ENC_DES,8,64,64,DIG_SHA,16,1, SSL_CIPHER_MODE_CBC},
1356     {100,KEX_RSA,SIG_RSA,ENC_RC4,1,128,56,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
1357     {101,KEX_DH,SIG_DSS,ENC_RC4,1,128,56,DIG_SHA,20,1, SSL_CIPHER_MODE_STREAM},
1358     {102,KEX_DH,SIG_DSS,ENC_RC4,1,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_STREAM},
1359     /*{138,KEX_PSK,SIG_RSA,ENC_RC4,16,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},*/
1360     {139,KEX_PSK,SIG_RSA,ENC_3DES,8,192,192,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1361     {140,KEX_PSK,SIG_RSA,ENC_AES,16,128,128,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1362     {141,KEX_PSK,SIG_RSA,ENC_AES256,16,256,256,DIG_SHA,20,0, SSL_CIPHER_MODE_CBC},
1363     {-1, 0,0,0,0,0,0,0,0,0, 0}
1364 };
1365
1366 #define MAX_BLOCK_SIZE 16
1367 #define MAX_KEY_SIZE 32
1368
1369 int
1370 ssl_find_cipher(int num,SslCipherSuite* cs)
1371 {
1372     SslCipherSuite *c;
1373
1374     for(c=cipher_suites;c->number!=-1;c++){
1375         if(c->number==num){
1376             *cs=*c;
1377             return 0;
1378         }
1379     }
1380
1381     return -1;
1382 }
1383
1384 static gint
1385 tls_hash(StringInfo* secret, StringInfo* seed, gint md, StringInfo* out)
1386 {
1387     guint8 *ptr;
1388     guint left;
1389     gint tocpy;
1390     guint8 *A;
1391     guint8 _A[20],tmp[20];
1392     guint A_l,tmp_l;
1393     SSL_HMAC hm;
1394     ptr=out->data;
1395     left=out->data_len;
1396
1397
1398     ssl_print_string("tls_hash: hash secret", secret);
1399     ssl_print_string("tls_hash: hash seed", seed);
1400     A=seed->data;
1401     A_l=seed->data_len;
1402
1403     while(left){
1404         ssl_hmac_init(&hm,secret->data,secret->data_len,md);
1405         ssl_hmac_update(&hm,A,A_l);
1406         ssl_hmac_final(&hm,_A,&A_l);
1407         ssl_hmac_cleanup(&hm);
1408         A=_A;
1409
1410         ssl_hmac_init(&hm,secret->data,secret->data_len,md);
1411         ssl_hmac_update(&hm,A,A_l);
1412         ssl_hmac_update(&hm,seed->data,seed->data_len);
1413         ssl_hmac_final(&hm,tmp,&tmp_l);
1414         ssl_hmac_cleanup(&hm);
1415
1416         tocpy=MIN(left,tmp_l);
1417         memcpy(ptr,tmp,tocpy);
1418         ptr+=tocpy;
1419         left-=tocpy;
1420     }
1421
1422     ssl_print_string("hash out", out);
1423     return (0);
1424 }
1425
1426 static gint
1427 tls_prf(StringInfo* secret, const gchar *usage,
1428         StringInfo* rnd1, StringInfo* rnd2, StringInfo* out)
1429 {
1430     StringInfo seed, sha_out, md5_out;
1431     guint8 *ptr;
1432     StringInfo s1, s2;
1433     guint i,s_l, r;
1434     size_t usage_len;
1435     r=-1;
1436     usage_len = strlen(usage);
1437
1438     /* initalize buffer for sha, md5 random seed*/
1439     if (ssl_data_alloc(&sha_out, MAX(out->data_len,20)) < 0) {
1440         ssl_debug_printf("tls_prf: can't allocate sha out\n");
1441         return -1;
1442     }
1443     if (ssl_data_alloc(&md5_out, MAX(out->data_len,16)) < 0) {
1444         ssl_debug_printf("tls_prf: can't allocate md5 out\n");
1445         goto free_sha;
1446     }
1447     if (ssl_data_alloc(&seed, usage_len+rnd1->data_len+rnd2->data_len) < 0) {
1448         ssl_debug_printf("tls_prf: can't allocate rnd %d\n",
1449                          (int) (usage_len+rnd1->data_len+rnd2->data_len));
1450         goto free_md5;
1451     }
1452
1453     ptr=seed.data;
1454     memcpy(ptr,usage,usage_len); ptr+=usage_len;
1455     memcpy(ptr,rnd1->data,rnd1->data_len); ptr+=rnd1->data_len;
1456     memcpy(ptr,rnd2->data,rnd2->data_len); ptr+=rnd2->data_len;
1457
1458     /* initalize buffer for client/server seeds*/
1459     s_l=secret->data_len/2 + secret->data_len%2;
1460     if (ssl_data_alloc(&s1, s_l) < 0) {
1461         ssl_debug_printf("tls_prf: can't allocate secret %d\n", s_l);
1462         goto free_seed;
1463     }
1464     if (ssl_data_alloc(&s2, s_l) < 0) {
1465         ssl_debug_printf("tls_prf: can't allocate secret(2) %d\n", s_l);
1466         goto free_s1;
1467     }
1468
1469     memcpy(s1.data,secret->data,s_l);
1470     memcpy(s2.data,secret->data + (secret->data_len - s_l),s_l);
1471
1472     ssl_debug_printf("tls_prf: tls_hash(md5 secret_len %d seed_len %d )\n", s1.data_len, seed.data_len);
1473     if(tls_hash(&s1,&seed,ssl_get_digest_by_name("MD5"),&md5_out) != 0)
1474         goto free_all;
1475     ssl_debug_printf("tls_prf: tls_hash(sha)\n");
1476     if(tls_hash(&s2,&seed,ssl_get_digest_by_name("SHA1"),&sha_out) != 0)
1477         goto free_all;
1478
1479     for(i=0;i<out->data_len;i++)
1480       out->data[i]=md5_out.data[i] ^ sha_out.data[i];
1481     r =0;
1482
1483     ssl_print_string("PRF out",out);
1484 free_all:
1485     g_free(s2.data);
1486 free_s1:
1487     g_free(s1.data);
1488 free_seed:
1489     g_free(seed.data);
1490 free_md5:
1491     g_free(md5_out.data);
1492 free_sha:
1493     g_free(sha_out.data);
1494     return r;
1495 }
1496
1497 static gint
1498 ssl3_generate_export_iv(StringInfo* r1,
1499         StringInfo* r2, StringInfo* out)
1500 {
1501     SSL_MD5_CTX md5;
1502     guint8 tmp[16];
1503
1504     ssl_md5_init(&md5);
1505     ssl_md5_update(&md5,r1->data,r1->data_len);
1506     ssl_md5_update(&md5,r2->data,r2->data_len);
1507     ssl_md5_final(tmp,&md5);
1508     ssl_md5_cleanup(&md5);
1509
1510     memcpy(out->data,tmp,out->data_len);
1511     ssl_print_string("export iv", out);
1512
1513     return(0);
1514 }
1515
1516 static gint
1517 ssl3_prf(StringInfo* secret, const gchar* usage,
1518         StringInfo* r1,
1519         StringInfo* r2,StringInfo* out)
1520 {
1521     SSL_MD5_CTX md5;
1522     SSL_SHA_CTX sha;
1523     StringInfo *rnd1,*rnd2;
1524     guint off;
1525     gint i=0,j;
1526     guint8 buf[20];
1527
1528     rnd1=r1; rnd2=r2;
1529
1530     for(off=0;off<out->data_len;off+=16){
1531         guchar outbuf[16];
1532         gint tocpy;
1533         i++;
1534
1535         ssl_debug_printf("ssl3_prf: sha1_hash(%d)\n",i);
1536         /* A, BB, CCC,  ... */
1537         for(j=0;j<i;j++){
1538             buf[j]=64+i;
1539         }
1540
1541         ssl_sha_init(&sha);
1542         ssl_sha_update(&sha,buf,i);
1543         ssl_sha_update(&sha,secret->data,secret->data_len);
1544
1545         if(!strcmp(usage,"client write key") || !strcmp(usage,"server write key")){
1546             ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
1547             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
1548         }
1549         else{
1550             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
1551             ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
1552         }
1553
1554         ssl_sha_final(buf,&sha);
1555         ssl_sha_cleanup(&sha);
1556
1557         ssl_debug_printf("ssl3_prf: md5_hash(%d) datalen %d\n",i,
1558             secret->data_len);
1559         ssl_md5_init(&md5);
1560         ssl_md5_update(&md5,secret->data,secret->data_len);
1561         ssl_md5_update(&md5,buf,20);
1562         ssl_md5_final(outbuf,&md5);
1563         ssl_md5_cleanup(&md5);
1564
1565         tocpy=MIN(out->data_len-off,16);
1566         memcpy(out->data+off,outbuf,tocpy);
1567     }
1568
1569     return(0);
1570 }
1571
1572 static SslFlow*
1573 ssl_create_flow(void)
1574 {
1575   SslFlow *flow;
1576
1577   flow = se_alloc(sizeof(SslFlow));
1578   flow->byte_seq = 0;
1579   flow->flags = 0;
1580   flow->multisegment_pdus = se_tree_create_non_persistent(EMEM_TREE_TYPE_RED_BLACK, "ssl_multisegment_pdus");
1581   return flow;
1582 }
1583
1584 #ifdef HAVE_LIBZ
1585 /* memory allocation functions for zlib initialization */
1586 static void* ssl_zalloc(void* opaque _U_, unsigned int no, unsigned int size)
1587 {
1588     return g_malloc0(no*size);
1589 }
1590 static void ssl_zfree(void* opaque _U_, void* addr)
1591 {
1592     g_free(addr);
1593 }
1594 #endif
1595
1596 static SslDecompress*
1597 ssl_create_decompressor(gint compression)
1598 {
1599     SslDecompress *decomp;
1600 #ifdef HAVE_LIBZ
1601     int err;
1602 #endif
1603
1604     if (compression == 0) return NULL;
1605     ssl_debug_printf("ssl_create_decompressor: compression method %d\n", compression);
1606     decomp = se_alloc(sizeof(SslDecompress));
1607     decomp->compression = compression;
1608     switch (decomp->compression) {
1609 #ifdef HAVE_LIBZ
1610         case 1:  /* DEFLATE */
1611             decomp->istream.zalloc = ssl_zalloc;
1612             decomp->istream.zfree = ssl_zfree;
1613             decomp->istream.opaque = Z_NULL;
1614             decomp->istream.next_in = Z_NULL;
1615             decomp->istream.next_out = Z_NULL;
1616             decomp->istream.avail_in = 0;
1617             decomp->istream.avail_out = 0;
1618             err = inflateInit_(&decomp->istream, ZLIB_VERSION, sizeof(z_stream));
1619             if (err != Z_OK) {
1620                 ssl_debug_printf("ssl_create_decompressor: inflateInit_() failed - %d\n", err);
1621                 return NULL;
1622             }
1623             break;
1624 #endif
1625         default:
1626             ssl_debug_printf("ssl_create_decompressor: unsupported compression method %d\n", decomp->compression);
1627             return NULL;
1628     }
1629     return decomp;
1630 }
1631
1632 static SslDecoder*
1633 ssl_create_decoder(SslCipherSuite *cipher_suite, gint compression,
1634         guint8 *mk, guint8 *sk, guint8 *iv)
1635 {
1636     SslDecoder *dec;
1637     gint ciph;
1638     ciph=0;
1639
1640     dec = se_alloc0(sizeof(SslDecoder));
1641     /* Find the SSLeay cipher */
1642     if(cipher_suite->enc!=ENC_NULL) {
1643         ssl_debug_printf("ssl_create_decoder CIPHER: %s\n", ciphers[cipher_suite->enc-0x30]);
1644         ciph=ssl_get_cipher_by_name(ciphers[cipher_suite->enc-0x30]);
1645     } else {
1646         ssl_debug_printf("ssl_create_decoder CIPHER: %s\n", "NULL");
1647         ciph = -1;
1648     }
1649     if (ciph == 0) {
1650         ssl_debug_printf("ssl_create_decoder can't find cipher %s\n",
1651             ciphers[(cipher_suite->enc-0x30) > 7 ? 7 : (cipher_suite->enc-0x30)]);
1652         return NULL;
1653     }
1654
1655     /* init mac buffer: mac storage is embedded into decoder struct to save a
1656      memory allocation and waste samo more memory*/
1657     dec->cipher_suite=cipher_suite;
1658     dec->compression = compression;
1659     dec->mac_key.data = dec->_mac_key;
1660     ssl_data_set(&dec->mac_key, mk, cipher_suite->dig_len);
1661     dec->seq = 0;
1662     dec->decomp = ssl_create_decompressor(compression);
1663     dec->flow = ssl_create_flow();
1664
1665     if (dec->evp)
1666         ssl_cipher_cleanup(&dec->evp);
1667
1668     if (ssl_cipher_init(&dec->evp,ciph,sk,iv,cipher_suite->mode) < 0) {
1669         ssl_debug_printf("ssl_create_decoder: can't create cipher id:%d mode:%d\n",
1670             ciph, cipher_suite->mode);
1671         return NULL;
1672     }
1673
1674     ssl_debug_printf("decoder initialized (digest len %d)\n", cipher_suite->dig_len);
1675     return dec;
1676 }
1677
1678 int
1679 ssl_generate_keyring_material(SslDecryptSession*ssl_session)
1680 {
1681     StringInfo key_block;
1682     guint8 _iv_c[MAX_BLOCK_SIZE],_iv_s[MAX_BLOCK_SIZE];
1683     guint8 _key_c[MAX_KEY_SIZE],_key_s[MAX_KEY_SIZE];
1684     gint needed;
1685     guint8 *ptr,*c_wk,*s_wk,*c_mk,*s_mk,*c_iv = _iv_c,*s_iv = _iv_s;
1686
1687     /* check for enough info to proced */
1688     guint need_all = SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION;
1689     guint need_any = SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET;
1690     if (((ssl_session->state & need_all) != need_all) || ((ssl_session->state & need_any) == 0)) {
1691         ssl_debug_printf("ssl_generate_keyring_material not enough data to generate key "
1692                          "(0x%02X required 0x%02X or 0x%02X)\n", ssl_session->state,
1693                          need_all|SSL_MASTER_SECRET, need_all|SSL_PRE_MASTER_SECRET);
1694         return -1;
1695     }
1696
1697     /* if master_key is not yet generate, create it now*/
1698     if (!(ssl_session->state & SSL_MASTER_SECRET)) {
1699         ssl_debug_printf("ssl_generate_keyring_material:PRF(pre_master_secret)\n");
1700         ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
1701         ssl_print_string("client random",&ssl_session->client_random);
1702         ssl_print_string("server random",&ssl_session->server_random);
1703         if (PRF(ssl_session,&ssl_session->pre_master_secret,"master secret",
1704                 &ssl_session->client_random,
1705                 &ssl_session->server_random, &ssl_session->master_secret)) {
1706             ssl_debug_printf("ssl_generate_keyring_material can't generate master_secret\n");
1707             return -1;
1708         }
1709         ssl_print_string("master secret",&ssl_session->master_secret);
1710
1711         /* the pre-master secret has been 'consumend' so we must clear it now */
1712         ssl_session->state &= ~SSL_PRE_MASTER_SECRET;
1713         ssl_session->state |= SSL_MASTER_SECRET;
1714     }
1715
1716     /* Compute the key block. First figure out how much data we need*/
1717     needed=ssl_session->cipher_suite.dig_len*2;
1718     needed+=ssl_session->cipher_suite.bits / 4;
1719     if(ssl_session->cipher_suite.block>1)
1720         needed+=ssl_session->cipher_suite.block*2;
1721
1722     key_block.data_len = needed;
1723     key_block.data = g_malloc(needed);
1724     if (!key_block.data) {
1725         ssl_debug_printf("ssl_generate_keyring_material can't allocate key_block (len %d)\n", needed);
1726         return -1;
1727     }
1728     ssl_debug_printf("ssl_generate_keyring_material sess key generation\n");
1729     if (PRF(ssl_session,&ssl_session->master_secret,"key expansion",
1730             &ssl_session->server_random,&ssl_session->client_random,
1731             &key_block)) {
1732         ssl_debug_printf("ssl_generate_keyring_material can't generate key_block\n");
1733         goto fail;
1734     }
1735     ssl_print_string("key expansion", &key_block);
1736
1737     ptr=key_block.data;
1738     c_mk=ptr; ptr+=ssl_session->cipher_suite.dig_len;
1739     s_mk=ptr; ptr+=ssl_session->cipher_suite.dig_len;
1740
1741     c_wk=ptr; ptr+=ssl_session->cipher_suite.eff_bits/8;
1742     s_wk=ptr; ptr+=ssl_session->cipher_suite.eff_bits/8;
1743
1744     if(ssl_session->cipher_suite.block>1){
1745         c_iv=ptr; ptr+=ssl_session->cipher_suite.block;
1746         s_iv=ptr; ptr+=ssl_session->cipher_suite.block;
1747     }
1748
1749     if(ssl_session->cipher_suite.export){
1750         StringInfo iv_c,iv_s;
1751         StringInfo key_c,key_s;
1752         StringInfo k;
1753
1754         if(ssl_session->cipher_suite.block>1){
1755
1756             /* We only have room for MAX_BLOCK_SIZE bytes IVs, but that's
1757              all we should need. This is a sanity check */
1758             if(ssl_session->cipher_suite.block>MAX_BLOCK_SIZE) {
1759                 ssl_debug_printf("ssl_generate_keyring_material cipher suite block must be at most %d nut is %d\n",
1760                     MAX_BLOCK_SIZE, ssl_session->cipher_suite.block);
1761                 goto fail;
1762             }
1763
1764             iv_c.data = _iv_c;
1765             iv_c.data_len = ssl_session->cipher_suite.block;
1766             iv_s.data = _iv_s;
1767             iv_s.data_len = ssl_session->cipher_suite.block;
1768
1769             if(ssl_session->version_netorder==SSLV3_VERSION){
1770                 ssl_debug_printf("ssl_generate_keyring_material ssl3_generate_export_iv\n");
1771                 if (ssl3_generate_export_iv(&ssl_session->client_random,
1772                         &ssl_session->server_random,&iv_c)) {
1773                     ssl_debug_printf("ssl_generate_keyring_material can't generate sslv3 client iv\n");
1774                     goto fail;
1775                 }
1776                 ssl_debug_printf("ssl_generate_keyring_material ssl3_generate_export_iv(2)\n");
1777                 if (ssl3_generate_export_iv(&ssl_session->server_random,
1778                         &ssl_session->client_random,&iv_s)) {
1779                     ssl_debug_printf("ssl_generate_keyring_material can't generate sslv3 server iv\n");
1780                     goto fail;
1781                 }
1782             }
1783             else{
1784                 guint8 _iv_block[MAX_BLOCK_SIZE * 2];
1785                 StringInfo iv_block;
1786                 StringInfo key_null;
1787                 guint8 _key_null;
1788
1789                 key_null.data = &_key_null;
1790                 key_null.data_len = 0;
1791
1792                 iv_block.data = _iv_block;
1793                 iv_block.data_len = ssl_session->cipher_suite.block*2;
1794
1795                 ssl_debug_printf("ssl_generate_keyring_material prf(iv_block)\n");
1796                 if(PRF(ssl_session,&key_null, "IV block",
1797                         &ssl_session->client_random,
1798                         &ssl_session->server_random,&iv_block)) {
1799                     ssl_debug_printf("ssl_generate_keyring_material can't generate tls31 iv block\n");
1800                     goto fail;
1801                 }
1802
1803                 memcpy(_iv_c,iv_block.data,ssl_session->cipher_suite.block);
1804                 memcpy(_iv_s,iv_block.data+ssl_session->cipher_suite.block,
1805                     ssl_session->cipher_suite.block);
1806             }
1807
1808             c_iv=_iv_c;
1809             s_iv=_iv_s;
1810         }
1811
1812         if (ssl_session->version_netorder==SSLV3_VERSION){
1813
1814             SSL_MD5_CTX md5;
1815             ssl_debug_printf("ssl_generate_keyring_material MD5(client_random)\n");
1816
1817             ssl_md5_init(&md5);
1818             ssl_md5_update(&md5,c_wk,ssl_session->cipher_suite.eff_bits/8);
1819             ssl_md5_update(&md5,ssl_session->client_random.data,
1820                 ssl_session->client_random.data_len);
1821             ssl_md5_update(&md5,ssl_session->server_random.data,
1822                 ssl_session->server_random.data_len);
1823             ssl_md5_final(_key_c,&md5);
1824             ssl_md5_cleanup(&md5);
1825             c_wk=_key_c;
1826
1827             ssl_md5_init(&md5);
1828             ssl_debug_printf("ssl_generate_keyring_material MD5(server_random)\n");
1829             ssl_md5_update(&md5,s_wk,ssl_session->cipher_suite.eff_bits/8);
1830             ssl_md5_update(&md5,ssl_session->server_random.data,
1831                 ssl_session->server_random.data_len);
1832             ssl_md5_update(&md5,ssl_session->client_random.data,
1833                 ssl_session->client_random.data_len);
1834             ssl_md5_final(_key_s,&md5);
1835             ssl_md5_cleanup(&md5);
1836             s_wk=_key_s;
1837         }
1838         else{
1839             key_c.data = _key_c;
1840             key_c.data_len = sizeof(_key_c);
1841             key_s.data = _key_s;
1842             key_s.data_len = sizeof(_key_s);
1843
1844             k.data = c_wk;
1845             k.data_len = ssl_session->cipher_suite.eff_bits/8;
1846             ssl_debug_printf("ssl_generate_keyring_material PRF(key_c)\n");
1847             if (PRF(ssl_session,&k,"client write key",
1848                     &ssl_session->client_random,
1849                     &ssl_session->server_random, &key_c)) {
1850                 ssl_debug_printf("ssl_generate_keyring_material can't generate tll31 server key \n");
1851                 goto fail;
1852             }
1853             c_wk=_key_c;
1854
1855             k.data = s_wk;
1856             k.data_len = ssl_session->cipher_suite.eff_bits/8;
1857             ssl_debug_printf("ssl_generate_keyring_material PRF(key_s)\n");
1858             if(PRF(ssl_session,&k,"server write key",
1859                     &ssl_session->client_random,
1860                     &ssl_session->server_random, &key_s)) {
1861                 ssl_debug_printf("ssl_generate_keyring_material can't generate tll31 client key \n");
1862                 goto fail;
1863             }
1864             s_wk=_key_s;
1865         }
1866     }
1867
1868     /* show key material info */
1869     ssl_print_data("Client MAC key",c_mk,ssl_session->cipher_suite.dig_len);
1870     ssl_print_data("Server MAC key",s_mk,ssl_session->cipher_suite.dig_len);
1871     ssl_print_data("Client Write key",c_wk,ssl_session->cipher_suite.bits/8);
1872     ssl_print_data("Server Write key",s_wk,ssl_session->cipher_suite.bits/8);
1873
1874     if(ssl_session->cipher_suite.block>1) {
1875         ssl_print_data("Client Write IV",c_iv,ssl_session->cipher_suite.block);
1876         ssl_print_data("Server Write IV",s_iv,ssl_session->cipher_suite.block);
1877     }
1878     else {
1879         ssl_print_data("Client Write IV",c_iv,8);
1880         ssl_print_data("Server Write IV",s_iv,8);
1881     }
1882
1883     /* create both client and server ciphers*/
1884     ssl_debug_printf("ssl_generate_keyring_material ssl_create_decoder(client)\n");
1885     ssl_session->client_new = ssl_create_decoder(&ssl_session->cipher_suite, ssl_session->compression, c_mk, c_wk, c_iv);
1886     if (!ssl_session->client_new) {
1887         ssl_debug_printf("ssl_generate_keyring_material can't init client decoder\n");
1888         goto fail;
1889     }
1890     ssl_debug_printf("ssl_generate_keyring_material ssl_create_decoder(server)\n");
1891     ssl_session->server_new = ssl_create_decoder(&ssl_session->cipher_suite, ssl_session->compression, s_mk, s_wk, s_iv);
1892     if (!ssl_session->server_new) {
1893         ssl_debug_printf("ssl_generate_keyring_material can't init client decoder\n");
1894         goto fail;
1895     }
1896
1897     ssl_debug_printf("ssl_generate_keyring_material: client seq %d, server seq %d\n",
1898         ssl_session->client_new->seq, ssl_session->server_new->seq);
1899     g_free(key_block.data);
1900     ssl_session->state |= SSL_HAVE_SESSION_KEY;
1901     return 0;
1902
1903 fail:
1904     g_free(key_block.data);
1905     return -1;
1906 }
1907
1908 void
1909 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
1910 {
1911     ssl_debug_printf("ssl_change_cipher %s\n", (server)?"SERVER":"CLIENT");
1912     if (server) {
1913         ssl_session->server = ssl_session->server_new;
1914         ssl_session->server_new = NULL;
1915     } else {
1916         ssl_session->client = ssl_session->client_new;
1917         ssl_session->client_new = NULL;
1918     }
1919 }
1920
1921 int
1922 ssl_decrypt_pre_master_secret(SslDecryptSession*ssl_session,
1923     StringInfo* encrypted_pre_master, SSL_PRIVATE_KEY *pk)
1924 {
1925     gint i;
1926
1927     if(ssl_session->cipher_suite.kex == KEX_DH) {
1928         ssl_debug_printf("ssl_decrypt_pre_master_secret session uses DH (%d) key exchange, which is impossible to decrypt\n",
1929             KEX_DH);
1930         return -1;
1931     } else if(ssl_session->cipher_suite.kex != KEX_RSA) {
1932          ssl_debug_printf("ssl_decrypt_pre_master_secret key exchange %d different from KEX_RSA (%d)\n",
1933             ssl_session->cipher_suite.kex, KEX_RSA);
1934         return -1;
1935     }
1936
1937     /* with tls key loading will fail if not rsa type, so no need to check*/
1938     ssl_print_string("pre master encrypted",encrypted_pre_master);
1939     ssl_debug_printf("ssl_decrypt_pre_master_secret:RSA_private_decrypt\n");
1940     i=ssl_private_decrypt(encrypted_pre_master->data_len,
1941         encrypted_pre_master->data, pk);
1942
1943     if (i!=48) {
1944         ssl_debug_printf("ssl_decrypt_pre_master_secret wrong "
1945             "pre_master_secret length (%d, expected %d)\n", i, 48);
1946         return -1;
1947     }
1948
1949     /* the decrypted data has been written into the pre_master key buffer */
1950     ssl_session->pre_master_secret.data = encrypted_pre_master->data;
1951     ssl_session->pre_master_secret.data_len=48;
1952     ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
1953
1954     /* Remove the master secret if it was there.
1955        This forces keying material regeneration in
1956        case we're renegotiating */
1957     ssl_session->state &= ~(SSL_MASTER_SECRET|SSL_HAVE_SESSION_KEY);
1958     ssl_session->state |= SSL_PRE_MASTER_SECRET;
1959     return 0;
1960 }
1961
1962 /* convert network byte order 32 byte number to right-aligned host byte order *
1963  * 8 bytes buffer */
1964 static gint fmt_seq(guint32 num, guint8* buf)
1965 {
1966     guint32 netnum;
1967
1968     memset(buf,0,8);
1969     netnum=g_htonl(num);
1970     memcpy(buf+4,&netnum,4);
1971
1972     return(0);
1973 }
1974
1975 static gint
1976 tls_check_mac(SslDecoder*decoder, gint ct, gint ver, guint8* data,
1977         guint32 datalen, guint8* mac)
1978 {
1979     SSL_HMAC hm;
1980     gint md;
1981     guint32 len;
1982     guint8 buf[20];
1983     gint16 temp;
1984
1985     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
1986     ssl_debug_printf("tls_check_mac mac type:%s md %d\n",
1987         digests[decoder->cipher_suite->dig-0x40], md);
1988
1989     if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
1990         return -1;;
1991
1992     /* hash sequence number */
1993     fmt_seq(decoder->seq,buf);
1994
1995     decoder->seq++;
1996
1997     ssl_hmac_update(&hm,buf,8);
1998
1999     /* hash content type */
2000     buf[0]=ct;
2001     ssl_hmac_update(&hm,buf,1);
2002
2003     /* hash version,data length and data*/
2004     /* *((gint16*)buf) = g_htons(ver); */
2005     temp = g_htons(ver);
2006     memcpy(buf, &temp, 2);
2007     ssl_hmac_update(&hm,buf,2);
2008
2009     /* *((gint16*)buf) = g_htons(datalen); */
2010     temp = g_htons(datalen);
2011     memcpy(buf, &temp, 2);
2012     ssl_hmac_update(&hm,buf,2);
2013     ssl_hmac_update(&hm,data,datalen);
2014
2015     /* get digest and digest len*/
2016     ssl_hmac_final(&hm,buf,&len);
2017     ssl_hmac_cleanup(&hm);
2018     ssl_print_data("Mac", buf, len);
2019     if(memcmp(mac,buf,len))
2020         return -1;
2021
2022     return 0;
2023 }
2024
2025 int
2026 ssl3_check_mac(SslDecoder*decoder,int ct,guint8* data,
2027         guint32 datalen, guint8* mac)
2028 {
2029     SSL_MD mc;
2030     gint md;
2031     guint32 len;
2032     guint8 buf[64],dgst[20];
2033     gint pad_ct;
2034     gint16 temp;
2035
2036     pad_ct=(decoder->cipher_suite->dig==DIG_SHA)?40:48;
2037
2038     /* get cipher used for digest comptuation */
2039     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
2040     if (ssl_md_init(&mc,md) !=0)
2041         return -1;
2042
2043     /* do hash computation on data && padding */
2044     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
2045
2046     /* hash padding*/
2047     memset(buf,0x36,pad_ct);
2048     ssl_md_update(&mc,buf,pad_ct);
2049
2050     /* hash sequence number */
2051     fmt_seq(decoder->seq,buf);
2052     decoder->seq++;
2053     ssl_md_update(&mc,buf,8);
2054
2055     /* hash content type */
2056     buf[0]=ct;
2057     ssl_md_update(&mc,buf,1);
2058
2059     /* hash data length in network byte order and data*/
2060     /* *((gint16* )buf) = g_htons(datalen); */
2061     temp = g_htons(datalen);
2062     memcpy(buf, &temp, 2);
2063     ssl_md_update(&mc,buf,2);
2064     ssl_md_update(&mc,data,datalen);
2065
2066     /* get partial digest */
2067     ssl_md_final(&mc,dgst,&len);
2068     ssl_md_cleanup(&mc);
2069
2070     ssl_md_init(&mc,md);
2071
2072     /* hash mac key */
2073     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
2074
2075     /* hash padding and partial digest*/
2076     memset(buf,0x5c,pad_ct);
2077     ssl_md_update(&mc,buf,pad_ct);
2078     ssl_md_update(&mc,dgst,len);
2079
2080     ssl_md_final(&mc,dgst,&len);
2081     ssl_md_cleanup(&mc);
2082
2083     if(memcmp(mac,dgst,len))
2084         return -1;
2085
2086     return(0);
2087 }
2088
2089 #if 0
2090 static gint
2091 dtls_check_mac(SslDecoder*decoder, gint ct,int ver, guint8* data,
2092         guint32 datalen, guint8* mac)
2093 {
2094     SSL_HMAC hm;
2095     gint md;
2096     guint32 len;
2097     guint8 buf[20];
2098     guint32 netnum;
2099     md=ssl_get_digest_by_name(digests[decoder->cipher_suite->dig-0x40]);
2100     ssl_debug_printf("dtls_check_mac mac type:%s md %d\n",
2101         digests[decoder->cipher_suite->dig-0x40], md);
2102
2103     if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
2104         return -1;
2105     ssl_debug_printf("dtls_check_mac seq: %d epoch: %d\n",decoder->seq,decoder->epoch);
2106     /* hash sequence number */
2107     fmt_seq(decoder->seq,buf);
2108     buf[0]=decoder->epoch>>8;
2109     buf[1]=decoder->epoch;
2110
2111     ssl_hmac_update(&hm,buf,8);
2112
2113     /* hash content type */
2114     buf[0]=ct;
2115     ssl_hmac_update(&hm,buf,1);
2116
2117     /* hash version,data length and data */
2118     *((gint16*)buf) = g_htons(ver);
2119     ssl_hmac_update(&hm,buf,2);
2120
2121     *((gint16*)buf) = g_htons(datalen);
2122     ssl_hmac_update(&hm,buf,2);
2123     ssl_hmac_update(&hm,data,datalen);
2124     /* get digest and digest len */
2125     ssl_hmac_final(&hm,buf,&len);
2126     ssl_hmac_cleanup(&hm);
2127     ssl_print_data("Mac", buf, len);
2128     if(memcmp(mac,buf,len))
2129         return -1;
2130
2131     return(0);
2132 }
2133 #endif
2134
2135 #ifdef HAVE_LIBZ
2136 int
2137 ssl_decompress_record(SslDecompress* decomp, const guchar* in, guint inl, StringInfo* out_str, guint* outl)
2138 {
2139     gint err;
2140
2141     switch (decomp->compression) {
2142         case 1:  /* DEFLATE */
2143             err = Z_OK;
2144             if (out_str->data_len < 16384) {  /* maximal plain length */
2145                 ssl_data_realloc(out_str, 16384);
2146             }
2147             decomp->istream.next_in = (guchar*)in;
2148             decomp->istream.avail_in = inl;
2149             decomp->istream.next_out = out_str->data;
2150             decomp->istream.avail_out = out_str->data_len;
2151             if (inl > 0)
2152                 err = inflate(&decomp->istream, Z_SYNC_FLUSH);
2153             if (err != Z_OK) {
2154                 ssl_debug_printf("ssl_decompress_record: inflate() failed - %d\n", err);
2155                 return -1;
2156             }
2157             *outl = out_str->data_len - decomp->istream.avail_out;
2158             break;
2159         default:
2160             ssl_debug_printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
2161             return -1;
2162     }
2163     return 0;
2164 }
2165 #else
2166 int
2167 ssl_decompress_record(SslDecompress* decomp _U_, const guchar* in _U_, guint inl _U_, StringInfo* out_str _U_, guint* outl _U_)
2168 {
2169     ssl_debug_printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
2170     return -1;
2171 }
2172 #endif
2173
2174 int
2175 ssl_decrypt_record(SslDecryptSession*ssl,SslDecoder* decoder, gint ct,
2176         const guchar* in, guint inl, StringInfo* comp_str, StringInfo* out_str, guint* outl)
2177 {
2178     guint pad, worklen, uncomplen;
2179     guint8 *mac;
2180
2181     ssl_debug_printf("ssl_decrypt_record ciphertext len %d\n", inl);
2182     ssl_print_data("Ciphertext",in, inl);
2183
2184     /* ensure we have enough storage space for decrypted data */
2185     if (inl > out_str->data_len)
2186     {
2187         ssl_debug_printf("ssl_decrypt_record: allocating %d bytes for decrypt data (old len %d)\n",
2188                 inl + 32, out_str->data_len);
2189         ssl_data_realloc(out_str, inl + 32);
2190     }
2191
2192     /* First decrypt*/
2193     if ((pad = ssl_cipher_decrypt(&decoder->evp, out_str->data, out_str->data_len, in, inl))!= 0) {
2194         ssl_debug_printf("ssl_decrypt_record failed: ssl_cipher_decrypt: %s %s\n", gcry_strsource (pad),
2195                     gcry_strerror (pad));
2196         return -1;
2197     }
2198
2199     ssl_print_data("Plaintext", out_str->data, inl);
2200     worklen=inl;
2201
2202     /* Now strip off the padding*/
2203     if(decoder->cipher_suite->block!=1) {
2204         pad=out_str->data[inl-1];
2205         worklen-=(pad+1);
2206         ssl_debug_printf("ssl_decrypt_record found padding %d final len %d\n",
2207             pad, worklen);
2208     }
2209
2210     /* And the MAC */
2211     if (decoder->cipher_suite->dig_len > (gint)worklen)
2212     {
2213         ssl_debug_printf("ssl_decrypt_record wrong record len/padding outlen %d\n work %d\n",*outl, worklen);
2214         return -1;
2215     }
2216     worklen-=decoder->cipher_suite->dig_len;
2217     mac = out_str->data + worklen;
2218
2219     /* if TLS 1.1 we use the transmitted IV and remove it after (to not modify dissector in others parts)*/
2220     if(ssl->version_netorder==TLSV1DOT1_VERSION){
2221         worklen=worklen-decoder->cipher_suite->block;
2222         memcpy(out_str->data,out_str->data+decoder->cipher_suite->block,worklen);
2223     }
2224     if(ssl->version_netorder==DTLSV1DOT0_VERSION ||
2225       ssl->version_netorder==DTLSV1DOT0_VERSION_NOT){
2226         worklen=worklen-decoder->cipher_suite->block;
2227         memcpy(out_str->data,out_str->data+decoder->cipher_suite->block,worklen);
2228     }
2229     /* Now check the MAC */
2230     ssl_debug_printf("checking mac (len %d, version %X, ct %d seq %d)\n",
2231         worklen, ssl->version_netorder, ct, decoder->seq);
2232     if(ssl->version_netorder==SSLV3_VERSION){
2233         if(ssl3_check_mac(decoder,ct,out_str->data,worklen,mac) < 0) {
2234             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
2235             return -1;
2236         }
2237     }
2238     else if(ssl->version_netorder==TLSV1_VERSION || ssl->version_netorder==TLSV1DOT1_VERSION){
2239         if(tls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)< 0) {
2240             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
2241             return -1;
2242         }
2243     }
2244     else if(ssl->version_netorder==DTLSV1DOT0_VERSION ||
2245         ssl->version_netorder==DTLSV1DOT0_VERSION_NOT){
2246         /* following the openssl dtls errors the right test is:
2247         if(dtls_check_mac(decoder,ct,ssl->version_netorder,out_str->data,worklen,mac)< 0) { */
2248         if(tls_check_mac(decoder,ct,TLSV1_VERSION,out_str->data,worklen,mac)< 0) {
2249             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
2250             return -1;
2251         }
2252     }
2253     ssl_debug_printf("ssl_decrypt_record: mac ok\n");
2254     *outl = worklen;
2255
2256     if (decoder->compression > 0) {
2257       ssl_debug_printf("ssl_decrypt_record: compression method %d\n", decoder->compression);
2258       ssl_data_copy(comp_str, out_str);
2259       ssl_print_data("Plaintext compressed", comp_str->data, worklen);
2260       if (!decoder->decomp) {
2261         ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
2262         return -1;
2263       }
2264       if (ssl_decompress_record(decoder->decomp, comp_str->data, worklen, out_str, &uncomplen) < 0) return -1;
2265       ssl_print_data("Plaintext uncompressed", out_str->data, uncomplen);
2266       *outl = uncomplen;
2267     }
2268
2269     return 0;
2270 }
2271
2272 static void
2273 ssl_get_version(gint* major, gint* minor, gint* patch)
2274 {
2275   *major = ver_major;
2276   *minor = ver_minor;
2277   *patch = ver_patch;
2278 }
2279
2280 #define RSA_PARS 6
2281 SSL_PRIVATE_KEY*
2282 ssl_privkey_to_sexp(struct gnutls_x509_privkey_int* priv_key)
2283 {
2284     gnutls_datum_t rsa_datum[RSA_PARS]; /* m, e, d, p, q, u */
2285     size_t tmp_size;
2286     gcry_sexp_t rsa_priv_key;
2287     gint major, minor, patch;
2288     gint i, p_idx, q_idx;
2289     int ret;
2290     size_t buf_len;
2291     unsigned char buf_keyid[32];
2292
2293 #ifdef SSL_FAST
2294     gcry_mpi_t* rsa_params = g_malloc(sizeof(gcry_mpi_t)*RSA_PARS);
2295 #else
2296     gcry_mpi_t rsa_params[RSA_PARS];
2297 #endif
2298
2299     buf_len = sizeof(buf_keyid);
2300     ret = gnutls_x509_privkey_get_key_id(priv_key, 0, buf_keyid, &buf_len);
2301     if (ret != 0) {
2302         ssl_debug_printf( "gnutls_x509_privkey_get_key_id(ssl_pkey, 0, buf_keyid, &buf_len) - %s\n", gnutls_strerror(ret));
2303     } else {
2304         ssl_debug_printf( "Private key imported: KeyID %s\n", bytes_to_str_punct(buf_keyid, (int) buf_len, ':'));
2305     }
2306
2307     /*
2308      * note: openssl and gnutls use 'p' and 'q' with opposite meaning:
2309      * our 'p' must be equal to 'q' as provided from openssl and viceversa
2310      */
2311
2312 #if (LIBGNUTLS_VERSION_MAJOR>2)||((LIBGNUTLS_VERSION_MAJOR==2)&&(LIBGNUTLS_VERSION_MINOR>=5))
2313     p_idx = 3; q_idx = 4;
2314 #else /* versions 2.4.x and older need 'p' and 'q' swapped */
2315     p_idx = 4; q_idx = 3;
2316 #endif
2317
2318     /* RSA get parameter */
2319     if (gnutls_x509_privkey_export_rsa_raw(priv_key,
2320                                            &rsa_datum[0],
2321                                            &rsa_datum[1],
2322                                            &rsa_datum[2],
2323                                            &rsa_datum[p_idx],
2324                                            &rsa_datum[q_idx],
2325                                            &rsa_datum[5])  != 0) {
2326         ssl_debug_printf("ssl_load_key: can't export rsa param (is a rsa private key file ?!?)\n");
2327 #ifdef SSL_FAST
2328         g_free(rsa_params);
2329 #endif
2330         return NULL;
2331     }
2332
2333     /* convert each rsa parameter to mpi format*/
2334     for(i=0; i<RSA_PARS; i++) {
2335       if (gcry_mpi_scan(&rsa_params[i], GCRYMPI_FMT_USG, rsa_datum[i].data, rsa_datum[i].size,&tmp_size) != 0) {
2336         ssl_debug_printf("ssl_load_key: can't convert m rsa param to int (size %d)\n", rsa_datum[i].size);
2337 #ifdef SSL_FAST
2338         g_free(rsa_params);
2339 #endif
2340         return NULL;
2341       }
2342     }
2343
2344     ssl_get_version(&major, &minor, &patch);
2345
2346     /* certain versions of gnutls require swap of rsa params 'p' and 'q' */
2347     if ((major <= 1) && (minor <= 0) && (patch <=13))
2348     {
2349         gcry_mpi_t tmp;
2350         ssl_debug_printf("ssl_load_key: swapping p and q parameters\n");
2351         tmp = rsa_params[4];
2352         rsa_params[4] = rsa_params[3];
2353         rsa_params[3] = tmp;
2354     }
2355
2356     if  (gcry_sexp_build( &rsa_priv_key, NULL,
2357             "(private-key(rsa((n%m)(e%m)(d%m)(p%m)(q%m)(u%m))))", rsa_params[0],
2358             rsa_params[1], rsa_params[2], rsa_params[3], rsa_params[4],
2359             rsa_params[5]) != 0) {
2360         ssl_debug_printf("ssl_load_key: can't build rsa private key s-exp\n");
2361 #ifdef SSL_FAST
2362         g_free(rsa_params);
2363 #endif
2364         return NULL;
2365     }
2366
2367 #if SSL_FAST
2368     return rsa_params;
2369 #else
2370     for (i=0; i< 6; i++)
2371         gcry_mpi_release(rsa_params[i]);
2372     return rsa_priv_key;
2373 #endif
2374
2375 }
2376
2377 Ssl_private_key_t *
2378 ssl_load_key(FILE* fp)
2379 {
2380     /* gnutls make our work much harded, since we have to work internally with
2381      * s-exp formatted data, but PEM loader export only in "gnutls_datum"
2382      * format, and a datum -> s-exp convertion function does not exist.
2383      */
2384     gnutls_x509_privkey_t priv_key;
2385     gnutls_datum key;
2386     gint size;
2387     guint bytes;
2388
2389     Ssl_private_key_t *private_key = g_malloc(sizeof(Ssl_private_key_t));
2390     private_key->x509_cert = 0;
2391     private_key->x509_pkey = 0;
2392     private_key->sexp_pkey = 0;
2393
2394     /* init private key data*/
2395     gnutls_x509_privkey_init(&priv_key);
2396
2397     /* compute file size and load all file contents into a datum buffer*/
2398     if (fseek(fp, 0, SEEK_END) < 0) {
2399         ssl_debug_printf("ssl_load_key: can't fseek file\n");
2400         g_free(private_key);
2401         return NULL;
2402     }
2403     if ((size = ftell(fp)) < 0) {
2404         ssl_debug_printf("ssl_load_key: can't ftell file\n");
2405         g_free(private_key);
2406         return NULL;
2407     }
2408     if (fseek(fp, 0, SEEK_SET) < 0) {
2409         ssl_debug_printf("ssl_load_key: can't re-fseek file\n");
2410         g_free(private_key);
2411         return NULL;
2412     }
2413     key.data = g_malloc(size);
2414     key.size = size;
2415     bytes = (guint) fread(key.data, 1, key.size, fp);
2416     if (bytes < key.size) {
2417         ssl_debug_printf("ssl_load_key: can't read from file %d bytes, got %d\n",
2418             key.size, bytes);
2419         g_free(private_key);
2420         g_free(key.data);
2421         return NULL;
2422     }
2423
2424     /* import PEM data*/
2425     if (gnutls_x509_privkey_import(priv_key, &key, GNUTLS_X509_FMT_PEM)!=0) {
2426         ssl_debug_printf("ssl_load_key: can't import pem data\n");
2427         g_free(private_key);
2428         g_free(key.data);
2429         return NULL;
2430     }
2431     g_free(key.data);
2432
2433     private_key->x509_pkey = priv_key;
2434     private_key->sexp_pkey = ssl_privkey_to_sexp(priv_key);
2435     if ( !private_key->sexp_pkey ) {
2436         g_free(private_key);
2437         return NULL;
2438     }
2439     return private_key;
2440 }
2441
2442 static const char *
2443 BAGTYPE(gnutls_pkcs12_bag_type_t x) {
2444     switch (x) {
2445         case GNUTLS_BAG_EMPTY:               return "Empty";
2446         case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: return "PKCS#8 Encrypted key";
2447         case GNUTLS_BAG_PKCS8_KEY:           return "PKCS#8 Key";
2448         case GNUTLS_BAG_CERTIFICATE:         return "Certificate";
2449         case GNUTLS_BAG_CRL:                 return "CRL";
2450         case GNUTLS_BAG_ENCRYPTED:           return "Encrypted";
2451         case GNUTLS_BAG_UNKNOWN:             return "Unknown";
2452         default:                             return "<undefined>";
2453     }
2454 }
2455
2456 Ssl_private_key_t *
2457 ssl_load_pkcs12(FILE* fp, const gchar *cert_passwd) {
2458
2459     int i, j, ret;
2460     int rest;
2461     unsigned char *p;
2462     gnutls_datum_t data;
2463     gnutls_pkcs12_bag_t bag = NULL;
2464     gnutls_pkcs12_bag_type_t bag_type;
2465     size_t len, buf_len;
2466     static char buf_name[256];
2467     static char buf_email[128];
2468     unsigned char buf_keyid[32];
2469
2470     gnutls_pkcs12_t       ssl_p12  = NULL;
2471     gnutls_x509_crt_t     ssl_cert = NULL;
2472     gnutls_x509_privkey_t ssl_pkey = NULL;
2473
2474     Ssl_private_key_t *private_key = g_malloc(sizeof(Ssl_private_key_t));
2475     private_key->x509_cert = 0;
2476     private_key->x509_pkey = 0;
2477     private_key->sexp_pkey = 0;
2478
2479     rest = 4096;
2480     data.data = g_malloc(rest);
2481     data.size = rest;
2482     p = data.data;
2483     while ((len = fread(p, 1, rest, fp)) > 0) {
2484         p += len;
2485         rest -= (int) len;
2486         if (!rest) {
2487             rest = 1024;
2488             data.data = g_realloc(data.data, data.size + rest);
2489             p = data.data + data.size;
2490             data.size += rest;
2491         }
2492     }
2493     data.size -= rest;
2494     ssl_debug_printf("%d bytes read\n", data.size);
2495     if (!feof(fp)) {
2496         ssl_debug_printf( "Error during certificate reading.\n");
2497         g_free(private_key);
2498         return 0;
2499     }
2500
2501     ret = gnutls_pkcs12_init(&ssl_p12);
2502     if (ret < 0) {
2503         ssl_debug_printf("gnutls_pkcs12_init(&st_p12) - %s", gnutls_strerror(ret));
2504         g_free(private_key);
2505         return 0;
2506     }
2507     ret = gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_DER, 0);
2508     g_free(data.data);
2509     if (ret < 0) {
2510         ssl_debug_printf("gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_DER, 0) - %s\n", gnutls_strerror(ret));
2511         g_free(private_key);
2512         return 0;
2513     }
2514
2515     ssl_debug_printf( "PKCS#12 imported\n");
2516
2517     for (i=0; ret==0; i++) {
2518
2519         if (bag) { gnutls_pkcs12_bag_deinit(bag); bag = NULL; }
2520
2521         ret = gnutls_pkcs12_bag_init(&bag);
2522         if (ret < 0) continue;
2523
2524         ret = gnutls_pkcs12_get_bag(ssl_p12, i, bag);
2525         if (ret < 0) continue;
2526
2527         for (j=0; ret==0 && j<gnutls_pkcs12_bag_get_count(bag); j++) {
2528
2529             bag_type = gnutls_pkcs12_bag_get_type(bag, j);
2530             if (bag_type >= GNUTLS_BAG_UNKNOWN) continue;
2531             ssl_debug_printf( "Bag %d/%d: %s\n", i, j, BAGTYPE(bag_type));
2532             if (bag_type == GNUTLS_BAG_ENCRYPTED) {
2533                 ret = gnutls_pkcs12_bag_decrypt(bag, cert_passwd);
2534                 if (ret == 0) {
2535                     bag_type = gnutls_pkcs12_bag_get_type(bag, j);
2536                     if (bag_type >= GNUTLS_BAG_UNKNOWN) continue;
2537                     ssl_debug_printf( "Bag %d/%d decrypted: %s\n", i, j, BAGTYPE(bag_type));
2538                 }
2539                 ret = 0;
2540             }
2541
2542             ret = gnutls_pkcs12_bag_get_data(bag, j, &data);
2543             if (ret < 0) continue;
2544
2545             switch (bag_type) {
2546
2547                 case GNUTLS_BAG_CERTIFICATE:
2548
2549                     ret = gnutls_x509_crt_init(&ssl_cert);
2550                     if (ret < 0) {
2551                         ssl_debug_printf( "gnutls_x509_crt_init(&ssl_cert) - %s\n", gnutls_strerror(ret));
2552                         g_free(private_key);
2553                         return 0;
2554                     }
2555
2556                     ret = gnutls_x509_crt_import(ssl_cert, &data, GNUTLS_X509_FMT_DER);
2557                     if (ret < 0) {
2558                         ssl_debug_printf( "gnutls_x509_crt_import(ssl_cert, &data, GNUTLS_X509_FMT_DER) - %s\n", gnutls_strerror(ret));
2559                         g_free(private_key);
2560                         return 0;
2561                     }
2562
2563                     buf_len = sizeof(buf_name);
2564                     ret = gnutls_x509_crt_get_dn_by_oid(ssl_cert, GNUTLS_OID_X520_COMMON_NAME, 0, 0, buf_name, &buf_len);
2565                     if (ret < 0) { g_strlcpy(buf_name, "<ERROR>", 256); }
2566                     buf_len = sizeof(buf_email);
2567                     ret = gnutls_x509_crt_get_dn_by_oid(ssl_cert, GNUTLS_OID_PKCS9_EMAIL, 0, 0, buf_email, &buf_len);
2568                     if (ret < 0) { g_strlcpy(buf_email, "<ERROR>", 128); }
2569
2570                     buf_len = sizeof(buf_keyid);
2571                     ret = gnutls_x509_crt_get_key_id(ssl_cert, 0, buf_keyid, &buf_len);
2572                     if (ret < 0) { g_strlcpy(buf_keyid, "<ERROR>", 32); }
2573
2574                     private_key->x509_cert = ssl_cert;
2575                     ssl_debug_printf( "Certificate imported: %s <%s>, KeyID %s\n", buf_name, buf_email, bytes_to_str(buf_keyid, (int) buf_len));
2576                     break;
2577
2578                 case GNUTLS_BAG_PKCS8_KEY:
2579                 case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY:
2580
2581                     ret = gnutls_x509_privkey_init(&ssl_pkey);
2582                     if (ret < 0) {
2583                         ssl_debug_printf( "gnutls_x509_privkey_init(&ssl_pkey) - %s\n", gnutls_strerror(ret));
2584                         g_free(private_key);
2585                         return 0;
2586                     }
2587                     ret = gnutls_x509_privkey_import_pkcs8(ssl_pkey, &data, GNUTLS_X509_FMT_DER, cert_passwd,
2588                                                            (bag_type==GNUTLS_BAG_PKCS8_KEY) ? GNUTLS_PKCS_PLAIN : 0);
2589                     if (ret < 0) {
2590                         ssl_debug_printf( "Can not decrypt private key - %s\n", gnutls_strerror(ret));
2591                         g_free(private_key);
2592                         return 0;
2593                     }
2594
2595                     private_key->x509_pkey = ssl_pkey;
2596                     private_key->sexp_pkey = ssl_privkey_to_sexp(ssl_pkey);
2597                     if ( !private_key->sexp_pkey ) {
2598                         g_free(private_key);
2599                         return NULL;
2600                     }
2601                     break;
2602
2603                 default: ;
2604             }
2605         }  /* j */
2606     }  /* i */
2607
2608     return private_key;
2609 }
2610
2611
2612 void ssl_free_key(Ssl_private_key_t* key)
2613 {
2614 #if SSL_FAST
2615     gint i;
2616     for (i=0; i< 6; i++)
2617         gcry_mpi_release(key->sexp_pkey[i]);
2618 #else
2619     gcry_sexp_release(key->sexp_pkey);
2620 #endif
2621
2622     if (!key->x509_cert)
2623         gnutls_x509_crt_deinit (key->x509_cert);
2624
2625     if (!key->x509_pkey)
2626         gnutls_x509_privkey_deinit(key->x509_pkey);
2627
2628     g_free((Ssl_private_key_t*)key);
2629 }
2630
2631 gint
2632 ssl_find_private_key(SslDecryptSession *ssl_session, GHashTable *key_hash, GTree* associations, packet_info *pinfo) {
2633     SslService dummy;
2634     char ip_addr_any[] = {0,0,0,0};
2635     guint32 port = 0;
2636     Ssl_private_key_t * private_key;
2637
2638     /* we need to know which side of the conversation is speaking */
2639     if (ssl_packet_from_server(ssl_session, associations, pinfo)) {
2640         dummy.addr = pinfo->src;
2641         dummy.port = port = pinfo->srcport;
2642     } else {
2643         dummy.addr = pinfo->dst;
2644         dummy.port = port = pinfo->destport;
2645     }
2646     ssl_debug_printf("ssl_find_private_key server %s:%u\n",
2647                      ep_address_to_str(&dummy.addr),dummy.port);
2648
2649     /* try to retrieve private key for this service. Do it now 'cause pinfo
2650      * is not always available
2651      * Note that with HAVE_LIBGNUTLS undefined private_key is allways 0
2652      * and thus decryption never engaged*/
2653
2654
2655     ssl_session->private_key = 0;
2656     private_key = g_hash_table_lookup(key_hash, &dummy);
2657
2658     if (!private_key) {
2659         ssl_debug_printf("ssl_find_private_key can't find private key for this server! Try it again with universal port 0\n");
2660
2661         dummy.port = 0;
2662         private_key = g_hash_table_lookup(key_hash, &dummy);
2663     }
2664
2665     if (!private_key) {
2666         ssl_debug_printf("ssl_find_private_key can't find private key for this server (universal port)! Try it again with universal address 0.0.0.0\n");
2667
2668         dummy.addr.type = AT_IPv4;
2669         dummy.addr.len = 4;
2670         dummy.addr.data = ip_addr_any;
2671
2672         dummy.port = port;
2673         private_key = g_hash_table_lookup(key_hash, &dummy);
2674     }
2675
2676     if (!private_key) {
2677         ssl_debug_printf("ssl_find_private_key can't find any private key!\n");
2678     } else {
2679         ssl_session->private_key = private_key->sexp_pkey;
2680     }
2681
2682     return 0;
2683 }
2684
2685 void
2686 ssl_lib_init(void)
2687 {
2688     const gchar* str = gnutls_check_version(NULL);
2689
2690     /* get library version */
2691     /* old relase of gnutls does not define the appropriate macros, so get
2692      * them from the string*/
2693     ssl_debug_printf("gnutls version: %s\n", str);
2694     sscanf(str, "%d.%d.%d", &ver_major, &ver_minor, &ver_patch);
2695 }
2696
2697 #else /* HAVE_LIBGNUTLS */
2698 /* no libgnutl: dummy operation to keep interface consistent*/
2699 void
2700 ssl_lib_init(void)
2701 {
2702 }
2703
2704 Ssl_private_key_t *
2705 ssl_load_key(FILE* fp)
2706 {
2707     ssl_debug_printf("ssl_load_key: impossible without gnutls. fp %p\n",fp);
2708     return NULL;
2709 }
2710
2711 Ssl_private_key_t *
2712 ssl_load_pkcs12(FILE* fp, const gchar *cert_passwd _U_) {
2713     ssl_debug_printf("ssl_load_pkcs12: impossible without gnutls. fp %p\n",fp);
2714     return NULL;
2715 }
2716
2717 void
2718 ssl_free_key(Ssl_private_key_t* key _U_)
2719 {
2720 }
2721
2722 gint
2723 ssl_find_private_key(SslDecryptSession *ssl_session _U_, GHashTable *key_hash _U_, GTree* associations _U_, packet_info *pinfo _U_)
2724 {
2725     return 0;
2726 }
2727
2728 int
2729 ssl_find_cipher(int num,SslCipherSuite* cs)
2730 {
2731     ssl_debug_printf("ssl_find_cipher: dummy without gnutls. num %d cs %p\n",
2732         num,cs);
2733     return 0;
2734 }
2735 int
2736 ssl_generate_keyring_material(SslDecryptSession*ssl)
2737 {
2738     ssl_debug_printf("ssl_generate_keyring_material: impossible without gnutls. ssl %p\n",
2739         ssl);
2740     return 0;
2741 }
2742 void
2743 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
2744 {
2745     ssl_debug_printf("ssl_change_cipher %s: makes no sense without gnutls. ssl %p\n",
2746         (server)?"SERVER":"CLIENT", ssl_session);
2747 }
2748
2749 int
2750 ssl_decrypt_pre_master_secret(SslDecryptSession* ssl_session,
2751     StringInfo* encrypted_pre_master, SSL_PRIVATE_KEY *pk)
2752 {
2753     ssl_debug_printf("ssl_decrypt_pre_master_secret: impossible without gnutls."
2754         " ssl %p encrypted_pre_master %p pk %p\n", ssl_session,
2755         encrypted_pre_master, pk);
2756     return 0;
2757 }
2758
2759 int
2760 ssl_decrypt_record(SslDecryptSession*ssl, SslDecoder* decoder, gint ct,
2761         const guchar* in, guint inl, StringInfo* comp_str _U_, StringInfo* out, guint* outl)
2762 {
2763     ssl_debug_printf("ssl_decrypt_record: impossible without gnutls. ssl %p"
2764         "decoder %p ct %d, in %p inl %d out %p outl %p\n", ssl, decoder, ct,
2765         in, inl, out, outl);
2766     return 0;
2767 }
2768
2769 gint
2770 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher _U_, guchar* iv _U_, gint iv_len _U_)
2771 {
2772     ssl_debug_printf("ssl_cipher_setiv: impossible without gnutls.\n");
2773     return 0;
2774 }
2775
2776 #endif /* HAVE_LIBGNUTLS */
2777
2778 /* get ssl data for this session. if no ssl data is found allocate a new one*/
2779 void
2780 ssl_session_init(SslDecryptSession* ssl_session)
2781 {
2782     ssl_debug_printf("ssl_session_init: initializing ptr %p size %" G_GSIZE_MODIFIER "u\n",
2783                      (void *)ssl_session, sizeof(SslDecryptSession));
2784
2785     ssl_session->master_secret.data = ssl_session->_master_secret;
2786     ssl_session->session_id.data = ssl_session->_session_id;
2787     ssl_session->client_random.data = ssl_session->_client_random;
2788     ssl_session->server_random.data = ssl_session->_server_random;
2789     ssl_session->master_secret.data_len = 48;
2790     ssl_session->server_data_for_iv.data_len = 0;
2791     ssl_session->server_data_for_iv.data = ssl_session->_server_data_for_iv;
2792     ssl_session->client_data_for_iv.data_len = 0;
2793     ssl_session->client_data_for_iv.data = ssl_session->_client_data_for_iv;
2794     ssl_session->app_data_segment.data=NULL;
2795     ssl_session->app_data_segment.data_len=0;
2796     SET_ADDRESS(&ssl_session->srv_addr, AT_NONE, 0, NULL);
2797     ssl_session->srv_ptype = PT_NONE;
2798     ssl_session->srv_port = 0;
2799 }
2800
2801 void
2802 ssl_set_server(SslDecryptSession* ssl, address *addr, port_type ptype, guint32 port)
2803 {
2804     SE_COPY_ADDRESS(&ssl->srv_addr, addr);
2805     ssl->srv_ptype = ptype;
2806     ssl->srv_port = port;
2807 }
2808
2809 /* Hash Functions for TLS/DTLS sessions table and private keys table*/
2810 gint
2811 ssl_equal (gconstpointer v, gconstpointer v2)
2812 {
2813     const StringInfo *val1;
2814     const StringInfo *val2;
2815     val1 = (const StringInfo *)v;
2816     val2 = (const StringInfo *)v2;
2817
2818     if (val1->data_len == val2->data_len &&
2819         !memcmp(val1->data, val2->data, val2->data_len)) {
2820         return 1;
2821     }
2822     return 0;
2823 }
2824
2825 guint
2826 ssl_hash  (gconstpointer v)
2827 {
2828     guint l,hash;
2829     const StringInfo* id;
2830     const guint* cur;
2831     hash = 0;
2832     id = (const StringInfo*) v;
2833
2834     /*  id and id->data are mallocated in ssl_save_session().  As such 'data'
2835      *  should be aligned for any kind of access (for example as a guint as
2836      *  is done below).  The intermediate void* cast is to prevent "cast
2837      *  increases required alignment of target type" warnings on CPUs (such
2838      *  as SPARCs) that do not allow misaligned memory accesses.
2839      */
2840     cur = (const guint*)(void*) id->data;
2841
2842     for (l=4; (l < id->data_len); l+=4, cur++)
2843         hash = hash ^ (*cur);
2844
2845     return hash;
2846 }
2847
2848 gint
2849 ssl_private_key_equal (gconstpointer v, gconstpointer v2)
2850 {
2851     const SslService *val1;
2852     const SslService *val2;
2853     val1 = (const SslService *)v;
2854     val2 = (const SslService *)v2;
2855
2856     if ((val1->port == val2->port) &&
2857         ! CMP_ADDRESS(&val1->addr, &val2->addr)) {
2858         return 1;
2859     }
2860     return 0;
2861 }
2862
2863 guint
2864 ssl_private_key_hash  (gconstpointer v)
2865 {
2866     const SslService *key;
2867     guint l, hash, len ;
2868     const guint* cur;
2869     key = (const SslService *)v;
2870     hash = key->port;
2871     len = key->addr.len;
2872     cur = (const guint*) key->addr.data;
2873
2874     for (l=4; (l<len); l+=4, cur++)
2875         hash = hash ^ (*cur);
2876
2877     return hash;
2878 }
2879
2880 /* private key table entries have a scope 'larger' then packet capture,
2881  * so we can't relay on se_alloc** function */
2882 void
2883 ssl_private_key_free(gpointer id, gpointer key, gpointer dummy _U_)
2884 {
2885     g_free(id);
2886     ssl_free_key((Ssl_private_key_t*) key);
2887 }
2888
2889 /* handling of association between tls/dtls ports and clear text protocol */
2890 void
2891 ssl_association_add(GTree* associations, dissector_handle_t handle, guint port, const gchar *protocol, gboolean tcp, gboolean from_key_list)
2892 {
2893
2894     SslAssociation* assoc;
2895     assoc = g_malloc(sizeof(SslAssociation));
2896
2897     assoc->tcp = tcp;
2898     assoc->ssl_port = port;
2899     assoc->info=g_strdup(protocol);
2900     assoc->handle = find_dissector(protocol);
2901     assoc->from_key_list = from_key_list;
2902
2903     ssl_debug_printf("association_add %s port %d protocol %s handle %p\n",
2904                      (assoc->tcp)?"TCP":"UDP", port, protocol, (void *)(assoc->handle));
2905
2906
2907     if (!assoc->handle) {
2908         ssl_debug_printf("association_add could not find handle for protocol '%s', try to find 'data' dissector\n", protocol);
2909         assoc->handle = find_dissector("data");
2910     }
2911
2912     if(!assoc->handle) {
2913         fprintf(stderr, "association_add() could not find handle for protocol:%s\n",protocol);
2914     } else {
2915         if(port) {
2916             if(tcp)
2917                 dissector_add("tcp.port", port, handle);
2918             else
2919                 dissector_add("udp.port", port, handle);
2920         }
2921         g_tree_insert(associations, assoc, assoc);
2922     }
2923 }
2924
2925 void
2926 ssl_association_remove(GTree* associations, SslAssociation *assoc)
2927 {
2928     ssl_debug_printf("ssl_association_remove removing %s %u - %s handle %p\n",
2929                      (assoc->tcp)?"TCP":"UDP", assoc->ssl_port, assoc->info, (void *)(assoc->handle));
2930     if (assoc->handle)
2931         dissector_delete((assoc->tcp)?"tcp.port":"udp.port", assoc->ssl_port, assoc->handle);
2932
2933     g_free(assoc->info);
2934
2935     g_tree_remove(associations, assoc);
2936     g_free(assoc);
2937 }
2938
2939 gint
2940 ssl_association_cmp(gconstpointer a, gconstpointer b)
2941 {
2942     const SslAssociation *assoc_a=a, *assoc_b=b;
2943     if (assoc_a->tcp != assoc_b->tcp) return (assoc_a->tcp)?1:-1;
2944     return assoc_a->ssl_port - assoc_b->ssl_port;
2945 }
2946
2947 SslAssociation*
2948 ssl_association_find(GTree * associations, guint port, gboolean tcp)
2949 {
2950     register SslAssociation* ret;
2951     SslAssociation assoc_tmp;
2952
2953     assoc_tmp.tcp = tcp;
2954     assoc_tmp.ssl_port = port;
2955     ret = g_tree_lookup(associations, &assoc_tmp);
2956
2957     ssl_debug_printf("association_find: %s port %d found %p\n", (tcp)?"TCP":"UDP", port, (void *)ret);
2958     return ret;
2959 }
2960
2961 gint
2962 ssl_assoc_from_key_list(gpointer key _U_, gpointer data, gpointer user_data)
2963 {
2964     if (((SslAssociation*)data)->from_key_list)
2965         ep_stack_push((ep_stack_t)user_data, data);
2966     return FALSE;
2967 }
2968
2969 int
2970 ssl_packet_from_server(SslDecryptSession* ssl, GTree* associations, packet_info *pinfo)
2971 {
2972     gint ret;
2973     if (ssl && (ssl->srv_ptype != PT_NONE)) {
2974         ret = (ssl->srv_ptype == pinfo->ptype) && (ssl->srv_port == pinfo->srcport) && ADDRESSES_EQUAL(&ssl->srv_addr, &pinfo->src);
2975     } else {
2976         ret = ssl_association_find(associations, pinfo->srcport, pinfo->ptype == PT_TCP) != 0;
2977     }
2978
2979     ssl_debug_printf("packet_from_server: is from server - %s\n", (ret)?"TRUE":"FALSE");
2980     return ret;
2981 }
2982
2983 /* add to packet data a newly allocated tvb with the specified real data*/
2984 void
2985 ssl_add_record_info(gint proto, packet_info *pinfo, guchar* data, gint data_len, gint record_id)
2986 {
2987     guchar* real_data;
2988     SslRecordInfo* rec;
2989     SslPacketInfo* pi;
2990     real_data = se_alloc(data_len);
2991     rec = se_alloc(sizeof(SslRecordInfo));
2992     pi = p_get_proto_data(pinfo->fd, proto);
2993
2994     if (!pi)
2995     {
2996         pi = se_alloc0(sizeof(SslPacketInfo));
2997         p_add_proto_data(pinfo->fd, proto,pi);
2998     }
2999
3000     rec->id = record_id;
3001     rec->tvb = tvb_new_real_data(real_data, data_len, data_len);
3002     memcpy(real_data, data, data_len);
3003
3004     /* head insertion */
3005     rec->next= pi->handshake_data;
3006     pi->handshake_data = rec;
3007 }
3008
3009
3010 /* search in packet data the tvbuff associated to the specified id */
3011 tvbuff_t*
3012 ssl_get_record_info(int proto, packet_info *pinfo, gint record_id)
3013 {
3014     SslRecordInfo* rec;
3015     SslPacketInfo* pi;
3016     pi = p_get_proto_data(pinfo->fd, proto);
3017
3018     if (!pi)
3019         return NULL;
3020
3021     for (rec = pi->handshake_data; rec; rec = rec->next)
3022         if (rec->id == record_id)
3023             return rec->tvb;
3024
3025     return NULL;
3026 }
3027
3028 void
3029 ssl_add_data_info(gint proto, packet_info *pinfo, guchar* data, gint data_len, gint key, SslFlow *flow)
3030 {
3031     SslDataInfo *rec, **prec;
3032     SslPacketInfo *pi;
3033
3034     pi = p_get_proto_data(pinfo->fd, proto);
3035     if (!pi)
3036     {
3037         pi = se_alloc0(sizeof(SslPacketInfo));
3038         p_add_proto_data(pinfo->fd, proto,pi);
3039     }
3040
3041     rec = se_alloc(sizeof(SslDataInfo)+data_len);
3042     rec->key = key;
3043     rec->plain_data.data = (guchar*)(rec + 1);
3044     memcpy(rec->plain_data.data, data, data_len);
3045     rec->plain_data.data_len = data_len;
3046     rec->seq = flow->byte_seq;
3047     rec->nxtseq = flow->byte_seq + data_len;
3048     rec->flow = flow;
3049     rec->next = NULL;
3050
3051     flow->byte_seq += data_len;
3052
3053     /* insertion */
3054     prec = &pi->appl_data;
3055     while (*prec) prec = &(*prec)->next;
3056     *prec = rec;
3057
3058     ssl_debug_printf("ssl_add_data_info: new data inserted data_len = %d, seq = %u, nxtseq = %u\n",
3059                      rec->plain_data.data_len, rec->seq, rec->nxtseq);
3060 }
3061
3062 SslDataInfo*
3063 ssl_get_data_info(int proto, packet_info *pinfo, gint key)
3064 {
3065     SslDataInfo* rec;
3066     SslPacketInfo* pi;
3067     pi = p_get_proto_data(pinfo->fd, proto);
3068
3069     if (!pi) return NULL;
3070
3071     rec = pi->appl_data;
3072     while (rec) {
3073         if (rec->key == key) return rec;
3074         rec = rec->next;
3075     }
3076
3077     return NULL;
3078 }
3079
3080 /* initialize/reset per capture state data (ssl sessions cache) */
3081 void
3082 ssl_common_init(GHashTable **session_hash, StringInfo *decrypted_data, StringInfo *compressed_data)
3083 {
3084     if (*session_hash)
3085         g_hash_table_destroy(*session_hash);
3086     *session_hash = g_hash_table_new(ssl_hash, ssl_equal);
3087
3088     g_free(decrypted_data->data);
3089     ssl_data_alloc(decrypted_data, 32);
3090
3091     g_free(compressed_data->data);
3092     ssl_data_alloc(compressed_data, 32);
3093 }
3094
3095 /* parse ssl related preferences (private keys and ports association strings) */
3096 void
3097 ssl_parse_key_list(const gchar * keys_list, GHashTable *key_hash, GTree* associations, dissector_handle_t handle, gboolean tcp)
3098 {
3099     gchar* end;
3100     gchar* start;
3101     gchar* tmp;
3102     guchar* ip;
3103     SslService* service;
3104     Ssl_private_key_t * private_key, *tmp_private_key;
3105     FILE* fp;
3106
3107     start = g_strdup(keys_list);
3108     tmp = start;
3109     ssl_debug_printf("ssl_init keys string:\n%s\n", start);
3110     do {
3111         int read_index, write_index;
3112         gchar* addr, *port, *protocol, *filename, *cert_passwd;
3113
3114         addr = start;
3115         /* split ip/file couple with ';' separator*/
3116         end = strpbrk(start, ";\n\r");
3117         if (end) {
3118             *end = 0;
3119             start = end+1;
3120         }
3121
3122         /* skip comments (in file) */
3123         if (addr[0] == '#') continue;
3124
3125         /* for each entry split ip, port, protocol, filename with ',' separator */
3126         ssl_debug_printf("ssl_init found host entry %s\n", addr);
3127         port = strchr(addr, ',');
3128         if (!port)
3129         {
3130             ssl_debug_printf("ssl_init entry malformed can't find port in '%s'\n", addr);
3131             continue;
3132         }
3133         *port = 0;
3134         port++;
3135
3136         protocol = strchr(port,',');
3137         if (!protocol)
3138         {
3139             ssl_debug_printf("ssl_init entry malformed can't find protocol in %s\n", port);
3140             continue;
3141         }
3142         *protocol=0;
3143         protocol++;
3144
3145         filename = strchr(protocol,',');
3146         if (!filename)
3147         {
3148             ssl_debug_printf("ssl_init entry malformed can't find filename in %s\n", protocol);
3149             continue;
3150         }
3151         *filename=0;
3152         filename++;
3153
3154         cert_passwd = strchr(filename,',');
3155         if (cert_passwd)
3156         {
3157             *cert_passwd=0;
3158             cert_passwd++;
3159         }
3160
3161         /* convert ip and port string to network rappresentation*/
3162         service = g_malloc(sizeof(SslService) + 4);
3163         service->addr.type = AT_IPv4;
3164         service->addr.len = 4;
3165         service->addr.data = ip = ((guchar*)service) + sizeof(SslService);
3166
3167         /* remove all spaces in addr */
3168         read_index = 0;
3169         write_index = 0;
3170
3171         while(addr[read_index]) {
3172             if (addr[read_index] != ' ') {
3173                 addr[write_index] = addr[read_index];
3174                 write_index++;
3175             }
3176             read_index++;
3177         }
3178         addr[write_index] = 0;
3179
3180         if ( !strcmp("any", addr) || !strcmp("ANY", addr) ) {
3181             ip[0] = 0;
3182             ip[1] = 0;
3183             ip[2] = 0;
3184             ip[3] = 0;
3185         } else {
3186             guint tmp0, tmp1, tmp2, tmp3;
3187
3188             sscanf(addr, "%u.%u.%u.%u", &tmp0, &tmp1, &tmp2, &tmp3);
3189             ip[0] = (guchar)tmp0;
3190             ip[1] = (guchar)tmp1;
3191             ip[2] = (guchar)tmp2;
3192             ip[3] = (guchar)tmp3;
3193         }
3194
3195         if(!strcmp("start_tls", port)) {
3196             service->port = 0;
3197         } else {
3198             service->port = atoi(port);
3199         }
3200         ssl_debug_printf("ssl_init addr '%u.%u.%u.%u' port '%d' filename '%s' password(only for p12 file) '%s'\n",
3201                          ip[0], ip[1], ip[2], ip[3], service->port, filename, cert_passwd ? cert_passwd : "(null)");
3202
3203         /* try to load pen or p12 file*/
3204         fp = ws_fopen(filename, "rb");
3205         if (!fp) {
3206             fprintf(stderr, "can't open file %s \n",filename);
3207             continue;
3208         }
3209
3210         if (!cert_passwd) {
3211             private_key = ssl_load_key(fp);
3212         }
3213         else
3214         {
3215             private_key = ssl_load_pkcs12(fp,cert_passwd);
3216         }
3217         /* !!! */
3218         if (!private_key) {
3219             fprintf(stderr,"can't load private key from %s\n",
3220                     filename);
3221             continue;
3222         }
3223
3224         fclose(fp);
3225
3226         ssl_debug_printf("ssl_init private key file %s successfully loaded\n",filename);
3227
3228         /* if item exists, remove first */
3229         tmp_private_key = g_hash_table_lookup(key_hash, service);
3230         if (tmp_private_key) {
3231             g_hash_table_remove(key_hash, service);
3232             ssl_free_key(tmp_private_key);
3233         }
3234         g_hash_table_insert(key_hash, service, private_key);
3235
3236         ssl_association_add(associations, handle, service->port, protocol, tcp, TRUE);
3237
3238     } while (end != NULL);
3239     g_free(tmp);
3240 }
3241
3242 /* store master secret into session data cache */
3243 void
3244 ssl_save_session(SslDecryptSession* ssl, GHashTable *session_hash)
3245 {
3246     /* allocate stringinfo chunks for session id and master secret data*/
3247     StringInfo* session_id;
3248     StringInfo* master_secret;
3249     session_id = se_alloc0(sizeof(StringInfo) + ssl->session_id.data_len);
3250     master_secret = se_alloc0(48 + sizeof(StringInfo));
3251
3252     master_secret->data = ((guchar*)master_secret+sizeof(StringInfo));
3253
3254     /*  ssl_hash() depends on session_id->data being aligned for guint access
3255      *  so be careful in changing how it is allocated.
3256      */
3257     session_id->data = ((guchar*)session_id+sizeof(StringInfo));
3258
3259     ssl_data_set(session_id, ssl->session_id.data, ssl->session_id.data_len);
3260     ssl_data_set(master_secret, ssl->master_secret.data, ssl->master_secret.data_len);
3261     g_hash_table_insert(session_hash, session_id, master_secret);
3262     ssl_print_string("ssl_save_session stored session id", session_id);
3263     ssl_print_string("ssl_save_session stored master secret", master_secret);
3264 }
3265
3266 void
3267 ssl_restore_session(SslDecryptSession* ssl, GHashTable *session_hash)
3268 {
3269     StringInfo* ms;
3270     ms = g_hash_table_lookup(session_hash, &ssl->session_id);
3271
3272     if (!ms) {
3273         ssl_debug_printf("ssl_restore_session can't find stored session\n");
3274         return;
3275     }
3276     ssl_data_set(&ssl->master_secret, ms->data, ms->data_len);
3277     ssl->state |= SSL_MASTER_SECRET;
3278     ssl_debug_printf("ssl_restore_session master key retrieved\n");
3279 }
3280
3281 int
3282 ssl_is_valid_content_type(guint8 type)
3283 {
3284     if (type >= 0x14 && type <= 0x17)
3285     {
3286         return 1;
3287     }
3288
3289     return 0;
3290 }
3291
3292 #ifdef SSL_DECRYPT_DEBUG
3293
3294 static FILE* ssl_debug_file=NULL;
3295
3296 void
3297 ssl_set_debug(char* name)
3298 {
3299     static gint debug_file_must_be_closed;
3300     gint use_stderr;
3301     debug_file_must_be_closed = 0;
3302     use_stderr = name?(strcmp(name, SSL_DEBUG_USE_STDERR) == 0):0;
3303
3304     if (debug_file_must_be_closed)
3305         fclose(ssl_debug_file);
3306     if (use_stderr)
3307         ssl_debug_file = stderr;
3308     else if (!name || (strcmp(name, "") ==0))
3309         ssl_debug_file = NULL;
3310     else
3311         ssl_debug_file = ws_fopen(name, "w");
3312     if (!use_stderr && ssl_debug_file)
3313         debug_file_must_be_closed = 1;
3314 }
3315
3316 void
3317 ssl_debug_flush(void)
3318 {
3319     if (ssl_debug_file)
3320         fflush(ssl_debug_file);
3321 }
3322
3323 void
3324 ssl_debug_printf(const gchar* fmt, ...)
3325 {
3326     va_list ap;
3327     gint ret;
3328     ret=0;
3329
3330     if (!ssl_debug_file)
3331         return;
3332
3333     va_start(ap, fmt);
3334     ret += vfprintf(ssl_debug_file, fmt, ap);
3335     va_end(ap);
3336 }
3337
3338 void
3339 ssl_print_text_data(const gchar* name, const guchar* data, size_t len)
3340 {
3341     size_t i;
3342     if (!ssl_debug_file)
3343         return;
3344     fprintf(ssl_debug_file,"%s: ",name);
3345     for (i=0; i< len; i++) {
3346       fprintf(ssl_debug_file,"%c",data[i]);
3347     }
3348     fprintf(ssl_debug_file,"\n");
3349 }
3350
3351 void
3352 ssl_print_data(const gchar* name, const guchar* data, size_t len)
3353 {
3354     size_t i;
3355     if (!ssl_debug_file)
3356         return;
3357     fprintf(ssl_debug_file,"%s[%d]:\n",name, (int) len);
3358     for (i=0; i< len; i++) {
3359         if ((i>0) && (i%16 == 0))
3360             fprintf(ssl_debug_file,"\n");
3361         fprintf(ssl_debug_file,"%.2x ",data[i]&255);
3362     }
3363     fprintf(ssl_debug_file,"\n");
3364 }
3365
3366 void
3367 ssl_print_string(const gchar* name, const StringInfo* data)
3368 {
3369     ssl_print_data(name, data->data, data->data_len);
3370 }
3371 #endif /* SSL_DECRYPT_DEBUG */