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