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