Ubuntu 14.04 complains about unititialized variable proto_name_length
[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  * Copyright (c) 2013, Hauke Mehrtens <hauke@hauke-m.de>
6  * Copyright (c) 2014, Peter Wu <peter@lekensteyn.nl>
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26
27 #include "config.h"
28
29 #ifdef HAVE_ZLIB
30 #define ZLIB_CONST
31 #include <zlib.h>
32 #endif
33
34 #include <stdlib.h>
35 #include <errno.h>
36
37 #include <epan/packet.h>
38 #include <epan/strutil.h>
39 #include <epan/addr_resolv.h>
40 #include <epan/ipv6.h>
41 #include <epan/expert.h>
42 #include <epan/asn1.h>
43 #include <epan/proto_data.h>
44
45 #include <wsutil/filesystem.h>
46 #include <wsutil/file_util.h>
47 #include <wsutil/str_util.h>
48 #include <wsutil/report_err.h>
49 #include <wsutil/pint.h>
50 #include <wsutil/strtoi.h>
51 #include <ws_version_info.h>
52 #include "packet-x509af.h"
53 #include "packet-x509if.h"
54 #include "packet-ssl-utils.h"
55 #include "packet-ssl.h"
56 #include "packet-dtls.h"
57 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
58 #include <gnutls/abstract.h>
59 #endif
60 #if GCRYPT_VERSION_NUMBER >= 0x010600 /* 1.6.0 */
61 /* Whether to provide support for authentication in addition to decryption. */
62 #define HAVE_LIBGCRYPT_AEAD
63 #endif
64
65 /* Lookup tables {{{ */
66 const value_string ssl_version_short_names[] = {
67     { SSL_VER_UNKNOWN,      "SSL" },
68     { SSLV2_VERSION,        "SSLv2" },
69     { SSLV3_VERSION,        "SSLv3" },
70     { TLSV1_VERSION,        "TLSv1" },
71     { TLSV1DOT1_VERSION,    "TLSv1.1" },
72     { TLSV1DOT2_VERSION,    "TLSv1.2" },
73     { TLSV1DOT3_VERSION,    "TLSv1.3" },
74     { DTLSV1DOT0_VERSION,   "DTLSv1.0" },
75     { DTLSV1DOT2_VERSION,   "DTLSv1.2" },
76     { DTLSV1DOT0_OPENSSL_VERSION, "DTLS 1.0 (OpenSSL pre 0.9.8f)" },
77     { PCT_VERSION,          "PCT" },
78     { 0x00, NULL }
79 };
80
81 const value_string ssl_versions[] = {
82     { SSLV2_VERSION,        "SSL 2.0" },
83     { SSLV3_VERSION,        "SSL 3.0" },
84     { TLSV1_VERSION,        "TLS 1.0" },
85     { TLSV1DOT1_VERSION,    "TLS 1.1" },
86     { TLSV1DOT2_VERSION,    "TLS 1.2" },
87     { TLSV1DOT3_VERSION,    "TLS 1.3" },
88     { 0x7F0E,               "TLS 1.3 (draft 14)" },
89     { 0x7F0F,               "TLS 1.3 (draft 15)" },
90     { 0x7F10,               "TLS 1.3 (draft 16)" },
91     { 0x7F11,               "TLS 1.3 (draft 17)" },
92     { 0x7F12,               "TLS 1.3 (draft 18)" },
93     { DTLSV1DOT0_OPENSSL_VERSION, "DTLS 1.0 (OpenSSL pre 0.9.8f)" },
94     { DTLSV1DOT0_VERSION,   "DTLS 1.0" },
95     { DTLSV1DOT2_VERSION,   "DTLS 1.2" },
96     { 0x00, NULL }
97 };
98
99 const value_string ssl_20_msg_types[] = {
100     { SSL2_HND_ERROR,               "Error" },
101     { SSL2_HND_CLIENT_HELLO,        "Client Hello" },
102     { SSL2_HND_CLIENT_MASTER_KEY,   "Client Master Key" },
103     { SSL2_HND_CLIENT_FINISHED,     "Client Finished" },
104     { SSL2_HND_SERVER_HELLO,        "Server Hello" },
105     { SSL2_HND_SERVER_VERIFY,       "Server Verify" },
106     { SSL2_HND_SERVER_FINISHED,     "Server Finished" },
107     { SSL2_HND_REQUEST_CERTIFICATE, "Request Certificate" },
108     { SSL2_HND_CLIENT_CERTIFICATE,  "Client Certificate" },
109     { 0x00, NULL }
110 };
111 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml */
112 /* Note: sorted by ascending value so value_string-ext can do a binary search */
113 static const value_string ssl_20_cipher_suites[] = {
114     { 0x000000, "TLS_NULL_WITH_NULL_NULL" },
115     { 0x000001, "TLS_RSA_WITH_NULL_MD5" },
116     { 0x000002, "TLS_RSA_WITH_NULL_SHA" },
117     { 0x000003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
118     { 0x000004, "TLS_RSA_WITH_RC4_128_MD5" },
119     { 0x000005, "TLS_RSA_WITH_RC4_128_SHA" },
120     { 0x000006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
121     { 0x000007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
122     { 0x000008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
123     { 0x000009, "TLS_RSA_WITH_DES_CBC_SHA" },
124     { 0x00000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
125     { 0x00000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
126     { 0x00000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
127     { 0x00000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
128     { 0x00000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
129     { 0x00000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
130     { 0x000010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
131     { 0x000011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
132     { 0x000012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
133     { 0x000013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
134     { 0x000014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
135     { 0x000015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
136     { 0x000016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
137     { 0x000017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
138     { 0x000018, "TLS_DH_anon_WITH_RC4_128_MD5" },
139     { 0x000019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
140     { 0x00001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
141     { 0x00001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
142     { 0x00001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
143     { 0x00001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
144 #if 0
145     { 0x00001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
146 #endif
147     /* RFC 2712 */
148     { 0x00001E, "TLS_KRB5_WITH_DES_CBC_SHA" },
149     { 0x00001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
150     { 0x000020, "TLS_KRB5_WITH_RC4_128_SHA" },
151     { 0x000021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
152     { 0x000022, "TLS_KRB5_WITH_DES_CBC_MD5" },
153     { 0x000023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
154     { 0x000024, "TLS_KRB5_WITH_RC4_128_MD5" },
155     { 0x000025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
156     { 0x000026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
157     { 0x000027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
158     { 0x000028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
159     { 0x000029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
160     { 0x00002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
161     { 0x00002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
162     /* RFC 4785 */
163     { 0x00002C, "TLS_PSK_WITH_NULL_SHA" },
164     { 0x00002D, "TLS_DHE_PSK_WITH_NULL_SHA" },
165     { 0x00002E, "TLS_RSA_PSK_WITH_NULL_SHA" },
166     /* RFC 5246 */
167     { 0x00002f, "TLS_RSA_WITH_AES_128_CBC_SHA" },
168     { 0x000030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
169     { 0x000031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
170     { 0x000032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
171     { 0x000033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
172     { 0x000034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
173     { 0x000035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
174     { 0x000036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
175     { 0x000037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
176     { 0x000038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
177     { 0x000039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
178     { 0x00003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
179     { 0x00003B, "TLS_RSA_WITH_NULL_SHA256" },
180     { 0x00003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
181     { 0x00003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
182     { 0x00003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
183     { 0x00003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
184     { 0x000040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
185     { 0x000041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
186     { 0x000042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
187     { 0x000043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
188     { 0x000044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
189     { 0x000045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
190     { 0x000046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
191     { 0x000047, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
192     { 0x000048, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
193     { 0x000049, "TLS_ECDH_ECDSA_WITH_DES_CBC_SHA" },
194     { 0x00004A, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
195     { 0x00004B, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
196     { 0x00004C, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
197     { 0x000060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
198     { 0x000061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
199     { 0x000062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
200     { 0x000063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
201     { 0x000064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
202     { 0x000065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
203     { 0x000066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
204     { 0x000067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
205     { 0x000068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
206     { 0x000069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
207     { 0x00006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
208     { 0x00006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
209     { 0x00006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
210     { 0x00006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
211     /* 0x00,0x6E-83 Unassigned  */
212     { 0x000084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
213     { 0x000085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
214     { 0x000086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
215     { 0x000087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
216     { 0x000088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
217     { 0x000089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
218     /* RFC 4279 */
219     { 0x00008A, "TLS_PSK_WITH_RC4_128_SHA" },
220     { 0x00008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
221     { 0x00008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
222     { 0x00008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
223     { 0x00008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
224     { 0x00008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
225     { 0x000090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
226     { 0x000091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
227     { 0x000092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
228     { 0x000093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
229     { 0x000094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
230     { 0x000095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
231     /* RFC 4162 */
232     { 0x000096, "TLS_RSA_WITH_SEED_CBC_SHA" },
233     { 0x000097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
234     { 0x000098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
235     { 0x000099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
236     { 0x00009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
237     { 0x00009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
238     /* RFC 5288 */
239     { 0x00009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
240     { 0x00009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
241     { 0x00009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
242     { 0x00009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
243     { 0x0000A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
244     { 0x0000A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
245     { 0x0000A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
246     { 0x0000A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
247     { 0x0000A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
248     { 0x0000A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
249     { 0x0000A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
250     { 0x0000A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
251     /* RFC 5487 */
252     { 0x0000A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
253     { 0x0000A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
254     { 0x0000AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
255     { 0x0000AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
256     { 0x0000AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
257     { 0x0000AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
258     { 0x0000AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
259     { 0x0000AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
260     { 0x0000B0, "TLS_PSK_WITH_NULL_SHA256" },
261     { 0x0000B1, "TLS_PSK_WITH_NULL_SHA384" },
262     { 0x0000B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
263     { 0x0000B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384" },
264     { 0x0000B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
265     { 0x0000B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
266     { 0x0000B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
267     { 0x0000B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
268     { 0x0000B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
269     { 0x0000B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
270     /* From RFC 5932 */
271     { 0x0000BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
272     { 0x0000BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
273     { 0x0000BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
274     { 0x0000BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
275     { 0x0000BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
276     { 0x0000BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
277     { 0x0000C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
278     { 0x0000C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
279     { 0x0000C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
280     { 0x0000C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
281     { 0x0000C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
282     { 0x0000C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
283     /* 0x00,0xC6-FE Unassigned  */
284     { 0x0000FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
285     /* 0x01-BF,* Unassigned  */
286     /* From RFC 4492 */
287     { 0x00c001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
288     { 0x00c002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
289     { 0x00c003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
290     { 0x00c004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
291     { 0x00c005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
292     { 0x00c006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
293     { 0x00c007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
294     { 0x00c008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
295     { 0x00c009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
296     { 0x00c00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
297     { 0x00c00b, "TLS_ECDH_RSA_WITH_NULL_SHA" },
298     { 0x00c00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
299     { 0x00c00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
300     { 0x00c00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
301     { 0x00c00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
302     { 0x00c010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
303     { 0x00c011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
304     { 0x00c012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
305     { 0x00c013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
306     { 0x00c014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
307     { 0x00c015, "TLS_ECDH_anon_WITH_NULL_SHA" },
308     { 0x00c016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
309     { 0x00c017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
310     { 0x00c018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
311     { 0x00c019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
312     /* RFC 5054 */
313     { 0x00C01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
314     { 0x00C01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
315     { 0x00C01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
316     { 0x00C01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
317     { 0x00C01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
318     { 0x00C01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
319     { 0x00C020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
320     { 0x00C021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
321     { 0x00C022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
322     /* RFC 5589 */
323     { 0x00C023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
324     { 0x00C024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
325     { 0x00C025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
326     { 0x00C026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
327     { 0x00C027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
328     { 0x00C028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
329     { 0x00C029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
330     { 0x00C02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
331     { 0x00C02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
332     { 0x00C02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
333     { 0x00C02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
334     { 0x00C02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
335     { 0x00C02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
336     { 0x00C030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
337     { 0x00C031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
338     { 0x00C032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
339     /* RFC 5489 */
340     { 0x00C033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA" },
341     { 0x00C034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA" },
342     { 0x00C035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA" },
343     { 0x00C036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA" },
344     { 0x00C037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" },
345     { 0x00C038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384" },
346     { 0x00C039, "TLS_ECDHE_PSK_WITH_NULL_SHA" },
347     { 0x00C03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256" },
348     { 0x00C03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384" },
349     /* 0xC0,0x3C-FF Unassigned
350             0xC1-FD,* Unassigned
351             0xFE,0x00-FD Unassigned
352             0xFE,0xFE-FF Reserved to avoid conflicts with widely deployed implementations [Pasi_Eronen]
353             0xFF,0x00-FF Reserved for Private Use [RFC5246]
354             */
355
356     /* old numbers used in the beginning
357      * http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305 */
358     { 0x00CC13, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
359     { 0x00CC14, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
360     { 0x00CC15, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
361
362     /* http://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305 */
363     { 0x00CCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
364     { 0x00CCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
365     { 0x00CCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
366     { 0x00CCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256" },
367     { 0x00CCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
368     { 0x00CCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
369     { 0x00CCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256" },
370
371     /* http://tools.ietf.org/html/draft-josefsson-salsa20-tls */
372     { 0x00E410, "TLS_RSA_WITH_ESTREAM_SALSA20_SHA1" },
373     { 0x00E411, "TLS_RSA_WITH_SALSA20_SHA1" },
374     { 0x00E412, "TLS_ECDHE_RSA_WITH_ESTREAM_SALSA20_SHA1" },
375     { 0x00E413, "TLS_ECDHE_RSA_WITH_SALSA20_SHA1" },
376     { 0x00E414, "TLS_ECDHE_ECDSA_WITH_ESTREAM_SALSA20_SHA1" },
377     { 0x00E415, "TLS_ECDHE_ECDSA_WITH_SALSA20_SHA1" },
378     { 0x00E416, "TLS_PSK_WITH_ESTREAM_SALSA20_SHA1" },
379     { 0x00E417, "TLS_PSK_WITH_SALSA20_SHA1" },
380     { 0x00E418, "TLS_ECDHE_PSK_WITH_ESTREAM_SALSA20_SHA1" },
381     { 0x00E419, "TLS_ECDHE_PSK_WITH_SALSA20_SHA1" },
382     { 0x00E41A, "TLS_RSA_PSK_WITH_ESTREAM_SALSA20_SHA1" },
383     { 0x00E41B, "TLS_RSA_PSK_WITH_SALSA20_SHA1" },
384     { 0x00E41C, "TLS_DHE_PSK_WITH_ESTREAM_SALSA20_SHA1" },
385     { 0x00E41D, "TLS_DHE_PSK_WITH_SALSA20_SHA1" },
386     { 0x00E41E, "TLS_DHE_RSA_WITH_ESTREAM_SALSA20_SHA1" },
387     { 0x00E41F, "TLS_DHE_RSA_WITH_SALSA20_SHA1" },
388
389     /* these from http://www.mozilla.org/projects/
390          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
391     { 0x00fefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
392     { 0x00feff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
393     { 0x00ffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
394     { 0x00ffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
395     /* note that ciphersuites of {0x00????} are TLS cipher suites in
396      * a sslv2 client hello message; the ???? above is the two-byte
397      * tls cipher suite id
398      */
399
400     { 0x010080, "SSL2_RC4_128_WITH_MD5" },
401     { 0x020080, "SSL2_RC4_128_EXPORT40_WITH_MD5" },
402     { 0x030080, "SSL2_RC2_128_CBC_WITH_MD5" },
403     { 0x040080, "SSL2_RC2_128_CBC_EXPORT40_WITH_MD5" },
404     { 0x050080, "SSL2_IDEA_128_CBC_WITH_MD5" },
405     { 0x060040, "SSL2_DES_64_CBC_WITH_MD5" },
406     { 0x0700c0, "SSL2_DES_192_EDE3_CBC_WITH_MD5" },
407     { 0x080080, "SSL2_RC4_64_WITH_MD5" },
408
409     /* Microsoft's old PCT protocol. These are from Eric Rescorla's
410        book "SSL and TLS" */
411     { 0x800001, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509" },
412     { 0x800003, "PCT_SSL_CERT_TYPE | PCT1_CERT_X509_CHAIN" },
413     { 0x810001, "PCT_SSL_HASH_TYPE | PCT1_HASH_MD5" },
414     { 0x810003, "PCT_SSL_HASH_TYPE | PCT1_HASH_SHA" },
415     { 0x820001, "PCT_SSL_EXCH_TYPE | PCT1_EXCH_RSA_PKCS1" },
416     { 0x830004, "PCT_SSL_CIPHER_TYPE_1ST_HALF | PCT1_CIPHER_RC4" },
417     { 0x842840, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_40 | PCT1_MAC_BITS_128" },
418     { 0x848040, "PCT_SSL_CIPHER_TYPE_2ND_HALF | PCT1_ENC_BITS_128 | PCT1_MAC_BITS_128" },
419     { 0x8f8001, "PCT_SSL_COMPAT | PCT_VERSION_1" },
420     { 0x00, NULL }
421 };
422
423 value_string_ext ssl_20_cipher_suites_ext = VALUE_STRING_EXT_INIT(ssl_20_cipher_suites);
424
425
426 const value_string ssl_extension_curves[] = {
427     {  1, "sect163k1" },
428     {  2, "sect163r1" },
429     {  3, "sect163r2" },
430     {  4, "sect193r1" },
431     {  5, "sect193r2" },
432     {  6, "sect233k1" },
433     {  7, "sect233r1" },
434     {  8, "sect239k1" },
435     {  9, "sect283k1" },
436     { 10, "sect283r1" },
437     { 11, "sect409k1" },
438     { 12, "sect409r1" },
439     { 13, "sect571k1" },
440     { 14, "sect571r1" },
441     { 15, "secp160k1" },
442     { 16, "secp160r1" },
443     { 17, "secp160r2" },
444     { 18, "secp192k1" },
445     { 19, "secp192r1" },
446     { 20, "secp224k1" },
447     { 21, "secp224r1" },
448     { 22, "secp256k1" },
449     { 23, "secp256r1" },
450     { 24, "secp384r1" },
451     { 25, "secp521r1" },
452     { 26, "brainpoolP256r1" }, /* RFC 7027 */
453     { 27, "brainpoolP384r1" }, /* RFC 7027 */
454     { 28, "brainpoolP512r1" }, /* RFC 7027 */
455     { 29, "ecdh_x25519" }, /* https://tools.ietf.org/html/draft-ietf-tls-rfc4492bis */
456     { 30, "ecdh_x448" }, /* https://tools.ietf.org/html/draft-ietf-tls-rfc4492bis */
457     { 256, "ffdhe2048" }, /* https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe */
458     { 257, "ffdhe3072" }, /* https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe */
459     { 258, "ffdhe4096" }, /* https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe */
460     { 259, "ffdhe6144" }, /* https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe */
461     { 260, "ffdhe8192" }, /* https://tools.ietf.org/html/draft-ietf-tls-negotiated-ff-dhe */
462     { 0xFF01, "arbitrary_explicit_prime_curves" },
463     { 0xFF02, "arbitrary_explicit_char2_curves" },
464     { 0x00, NULL }
465 };
466
467 const value_string ssl_curve_types[] = {
468     { 1, "explicit_prime" },
469     { 2, "explicit_char2" },
470     { 3, "named_curve" },
471     { 0x00, NULL }
472 };
473
474 const value_string ssl_extension_ec_point_formats[] = {
475     { 0, "uncompressed" },
476     { 1, "ansiX962_compressed_prime" },
477     { 2, "ansiX962_compressed_char2" },
478     { 0x00, NULL }
479 };
480
481 const value_string ssl_20_certificate_type[] = {
482     { 0x00, "N/A" },
483     { 0x01, "X.509 Certificate" },
484     { 0x00, NULL }
485 };
486
487 const value_string ssl_31_content_type[] = {
488     { 20, "Change Cipher Spec" },
489     { 21, "Alert" },
490     { 22, "Handshake" },
491     { 23, "Application Data" },
492     { 24, "Heartbeat" },
493     { 0x00, NULL }
494 };
495
496 #if 0
497 /* XXX - would be used if we dissected the body of a Change Cipher Spec
498    message. */
499 const value_string ssl_31_change_cipher_spec[] = {
500     { 1, "Change Cipher Spec" },
501     { 0x00, NULL }
502 };
503 #endif
504
505 const value_string ssl_31_alert_level[] = {
506     { 1, "Warning" },
507     { 2, "Fatal" },
508     { 0x00, NULL }
509 };
510
511 const value_string ssl_31_alert_description[] = {
512     {   0,  "Close Notify" },
513     {   1,  "End of Early Data" },
514     {  10,  "Unexpected Message" },
515     {  20,  "Bad Record MAC" },
516     {  21,  "Decryption Failed" },
517     {  22,  "Record Overflow" },
518     {  30,  "Decompression Failure" },
519     {  40,  "Handshake Failure" },
520     {  41,  "No Certificate" },
521     {  42,  "Bad Certificate" },
522     {  43,  "Unsupported Certificate" },
523     {  44,  "Certificate Revoked" },
524     {  45,  "Certificate Expired" },
525     {  46,  "Certificate Unknown" },
526     {  47,  "Illegal Parameter" },
527     {  48,  "Unknown CA" },
528     {  49,  "Access Denied" },
529     {  50,  "Decode Error" },
530     {  51,  "Decrypt Error" },
531     {  60,  "Export Restriction" },
532     {  70,  "Protocol Version" },
533     {  71,  "Insufficient Security" },
534     {  80,  "Internal Error" },
535     {  86,  "Inappropriate Fallback" },
536     {  90,  "User Canceled" },
537     { 100, "No Renegotiation" },
538     { 109, "Missing Extension" },
539     { 110, "Unsupported Extension" },
540     { 111, "Certificate Unobtainable" },
541     { 112, "Unrecognized Name" },
542     { 113, "Bad Certificate Status Response" },
543     { 114, "Bad Certificate Hash Value" },
544     { 115, "Unknown PSK Identity" },
545     { 116, "Certificate Required" },
546     { 120, "No application Protocol" },
547     { 0x00, NULL }
548 };
549
550 const value_string ssl_31_handshake_type[] = {
551     { SSL_HND_HELLO_REQUEST,     "Hello Request" },
552     { SSL_HND_CLIENT_HELLO,      "Client Hello" },
553     { SSL_HND_SERVER_HELLO,      "Server Hello" },
554     { SSL_HND_HELLO_VERIFY_REQUEST, "Hello Verify Request"},
555     { SSL_HND_NEWSESSION_TICKET, "New Session Ticket" },
556     { SSL_HND_HELLO_RETRY_REQUEST, "Hello Retry Request" },
557     { SSL_HND_ENCRYPTED_EXTENSIONS, "Encrypted Extensions" },
558     { SSL_HND_CERTIFICATE,       "Certificate" },
559     { SSL_HND_SERVER_KEY_EXCHG,  "Server Key Exchange" },
560     { SSL_HND_CERT_REQUEST,      "Certificate Request" },
561     { SSL_HND_SVR_HELLO_DONE,    "Server Hello Done" },
562     { SSL_HND_CERT_VERIFY,       "Certificate Verify" },
563     { SSL_HND_CLIENT_KEY_EXCHG,  "Client Key Exchange" },
564     { SSL_HND_FINISHED,          "Finished" },
565     { SSL_HND_CERT_URL,          "Client Certificate URL" },
566     { SSL_HND_CERT_STATUS,       "Certificate Status" },
567     { SSL_HND_SUPPLEMENTAL_DATA, "Supplemental Data" },
568     { SSL_HND_ENCRYPTED_EXTS,    "Encrypted Extensions" },
569     { 0x00, NULL }
570 };
571
572 const value_string tls_heartbeat_type[] = {
573     { 1, "Request" },
574     { 2, "Response" },
575     { 0x00, NULL }
576 };
577
578 const value_string tls_heartbeat_mode[] = {
579     { 1, "Peer allowed to send requests" },
580     { 2, "Peer not allowed to send requests" },
581     { 0x00, NULL }
582 };
583
584 const value_string ssl_31_compression_method[] = {
585     {  0, "null" },
586     {  1, "DEFLATE" },
587     { 64, "LZS" },
588     { 0x00, NULL }
589 };
590
591 #if 0
592 /* XXX - would be used if we dissected a Signature, as would be
593    seen in a server key exchange or certificate verify message. */
594 const value_string ssl_31_key_exchange_algorithm[] = {
595     { 0, "RSA" },
596     { 1, "Diffie Hellman" },
597     { 0x00, NULL }
598 };
599
600 const value_string ssl_31_signature_algorithm[] = {
601     { 0, "Anonymous" },
602     { 1, "RSA" },
603     { 2, "DSA" },
604     { 0x00, NULL }
605 };
606 #endif
607
608 const value_string ssl_31_client_certificate_type[] = {
609     { 1, "RSA Sign" },
610     { 2, "DSS Sign" },
611     { 3, "RSA Fixed DH" },
612     { 4, "DSS Fixed DH" },
613     /* GOST certificate types */
614     /* Section 3.5 of draft-chudov-cryptopro-cptls-04 */
615     { 21, "GOST R 34.10-94" },
616     { 22, "GOST R 34.10-2001" },
617     /* END GOST certificate types */
618     { 64, "ECDSA Sign" },
619     { 65, "RSA Fixed ECDH" },
620     { 66, "ECDSA Fixed ECDH" },
621     { 0x00, NULL }
622 };
623
624 #if 0
625 /* XXX - would be used if we dissected exchange keys, as would be
626    seen in a client key exchange message. */
627 const value_string ssl_31_public_value_encoding[] = {
628     { 0, "Implicit" },
629     { 1, "Explicit" },
630     { 0x00, NULL }
631 };
632 #endif
633
634 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml */
635 /* Note: sorted by ascending value so value_string_ext fcns can do a binary search */
636 static const value_string ssl_31_ciphersuite[] = {
637     /* RFC 2246, RFC 4346, RFC 5246 */
638     { 0x0000, "TLS_NULL_WITH_NULL_NULL" },
639     { 0x0001, "TLS_RSA_WITH_NULL_MD5" },
640     { 0x0002, "TLS_RSA_WITH_NULL_SHA" },
641     { 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5" },
642     { 0x0004, "TLS_RSA_WITH_RC4_128_MD5" },
643     { 0x0005, "TLS_RSA_WITH_RC4_128_SHA" },
644     { 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5" },
645     { 0x0007, "TLS_RSA_WITH_IDEA_CBC_SHA" },
646     { 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA" },
647     { 0x0009, "TLS_RSA_WITH_DES_CBC_SHA" },
648     { 0x000a, "TLS_RSA_WITH_3DES_EDE_CBC_SHA" },
649     { 0x000b, "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA" },
650     { 0x000c, "TLS_DH_DSS_WITH_DES_CBC_SHA" },
651     { 0x000d, "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA" },
652     { 0x000e, "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA" },
653     { 0x000f, "TLS_DH_RSA_WITH_DES_CBC_SHA" },
654     { 0x0010, "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA" },
655     { 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA" },
656     { 0x0012, "TLS_DHE_DSS_WITH_DES_CBC_SHA" },
657     { 0x0013, "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA" },
658     { 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA" },
659     { 0x0015, "TLS_DHE_RSA_WITH_DES_CBC_SHA" },
660     { 0x0016, "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" },
661     { 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5" },
662     { 0x0018, "TLS_DH_anon_WITH_RC4_128_MD5" },
663     { 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA" },
664     { 0x001a, "TLS_DH_anon_WITH_DES_CBC_SHA" },
665     { 0x001b, "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA" },
666
667     { 0x001c, "SSL_FORTEZZA_KEA_WITH_NULL_SHA" },
668     { 0x001d, "SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA" },
669 #if 0 /* Because it clashes with KRB5, is never used any more, and is safe
670          to remove according to David Hopwood <david.hopwood@zetnet.co.uk>
671          of the ietf-tls list */
672     { 0x001e, "SSL_FORTEZZA_KEA_WITH_RC4_128_SHA" },
673 #endif
674
675     /* RFC 2712 */
676     { 0x001E, "TLS_KRB5_WITH_DES_CBC_SHA" },
677     { 0x001F, "TLS_KRB5_WITH_3DES_EDE_CBC_SHA" },
678     { 0x0020, "TLS_KRB5_WITH_RC4_128_SHA" },
679     { 0x0021, "TLS_KRB5_WITH_IDEA_CBC_SHA" },
680     { 0x0022, "TLS_KRB5_WITH_DES_CBC_MD5" },
681     { 0x0023, "TLS_KRB5_WITH_3DES_EDE_CBC_MD5" },
682     { 0x0024, "TLS_KRB5_WITH_RC4_128_MD5" },
683     { 0x0025, "TLS_KRB5_WITH_IDEA_CBC_MD5" },
684     { 0x0026, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA" },
685     { 0x0027, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA" },
686     { 0x0028, "TLS_KRB5_EXPORT_WITH_RC4_40_SHA" },
687     { 0x0029, "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5" },
688     { 0x002A, "TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5" },
689     { 0x002B, "TLS_KRB5_EXPORT_WITH_RC4_40_MD5" },
690
691     /* RFC 4785 */
692     { 0x002C, "TLS_PSK_WITH_NULL_SHA" },
693     { 0x002D, "TLS_DHE_PSK_WITH_NULL_SHA" },
694     { 0x002E, "TLS_RSA_PSK_WITH_NULL_SHA" },
695
696     /* RFC 5246 */
697     { 0x002F, "TLS_RSA_WITH_AES_128_CBC_SHA" },
698     { 0x0030, "TLS_DH_DSS_WITH_AES_128_CBC_SHA" },
699     { 0x0031, "TLS_DH_RSA_WITH_AES_128_CBC_SHA" },
700     { 0x0032, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA" },
701     { 0x0033, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA" },
702     { 0x0034, "TLS_DH_anon_WITH_AES_128_CBC_SHA" },
703     { 0x0035, "TLS_RSA_WITH_AES_256_CBC_SHA" },
704     { 0x0036, "TLS_DH_DSS_WITH_AES_256_CBC_SHA" },
705     { 0x0037, "TLS_DH_RSA_WITH_AES_256_CBC_SHA" },
706     { 0x0038, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" },
707     { 0x0039, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA" },
708     { 0x003A, "TLS_DH_anon_WITH_AES_256_CBC_SHA" },
709     { 0x003B, "TLS_RSA_WITH_NULL_SHA256" },
710     { 0x003C, "TLS_RSA_WITH_AES_128_CBC_SHA256" },
711     { 0x003D, "TLS_RSA_WITH_AES_256_CBC_SHA256" },
712     { 0x003E, "TLS_DH_DSS_WITH_AES_128_CBC_SHA256" },
713     { 0x003F, "TLS_DH_RSA_WITH_AES_128_CBC_SHA256" },
714     { 0x0040, "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256" },
715
716     /* RFC 4132 */
717     { 0x0041, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA" },
718     { 0x0042, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA" },
719     { 0x0043, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA" },
720     { 0x0044, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA" },
721     { 0x0045, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA" },
722     { 0x0046, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA" },
723
724     /* 0x00,0x60-66 Reserved to avoid conflicts with widely deployed implementations  */
725     /* --- ??? --- */
726     { 0x0060, "TLS_RSA_EXPORT1024_WITH_RC4_56_MD5" },
727     { 0x0061, "TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5" },
728     /* draft-ietf-tls-56-bit-ciphersuites-01.txt */
729     { 0x0062, "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA" },
730     { 0x0063, "TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA" },
731     { 0x0064, "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA" },
732     { 0x0065, "TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA" },
733     { 0x0066, "TLS_DHE_DSS_WITH_RC4_128_SHA" },
734     /* --- ??? ---*/
735
736     { 0x0067, "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256" },
737     { 0x0068, "TLS_DH_DSS_WITH_AES_256_CBC_SHA256" },
738     { 0x0069, "TLS_DH_RSA_WITH_AES_256_CBC_SHA256" },
739     { 0x006A, "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256" },
740     { 0x006B, "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256" },
741     { 0x006C, "TLS_DH_anon_WITH_AES_128_CBC_SHA256" },
742     { 0x006D, "TLS_DH_anon_WITH_AES_256_CBC_SHA256" },
743
744     /* draft-chudov-cryptopro-cptls-04.txt */
745     { 0x0080,  "TLS_GOSTR341094_WITH_28147_CNT_IMIT" },
746     { 0x0081,  "TLS_GOSTR341001_WITH_28147_CNT_IMIT" },
747     { 0x0082,  "TLS_GOSTR341094_WITH_NULL_GOSTR3411" },
748     { 0x0083,  "TLS_GOSTR341001_WITH_NULL_GOSTR3411" },
749
750     /* RFC 4132 */
751     { 0x0084, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA" },
752     { 0x0085, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA" },
753     { 0x0086, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA" },
754     { 0x0087, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA" },
755     { 0x0088, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA" },
756     { 0x0089, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA" },
757
758     /* RFC 4279 */
759     { 0x008A, "TLS_PSK_WITH_RC4_128_SHA" },
760     { 0x008B, "TLS_PSK_WITH_3DES_EDE_CBC_SHA" },
761     { 0x008C, "TLS_PSK_WITH_AES_128_CBC_SHA" },
762     { 0x008D, "TLS_PSK_WITH_AES_256_CBC_SHA" },
763     { 0x008E, "TLS_DHE_PSK_WITH_RC4_128_SHA" },
764     { 0x008F, "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA" },
765     { 0x0090, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA" },
766     { 0x0091, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA" },
767     { 0x0092, "TLS_RSA_PSK_WITH_RC4_128_SHA" },
768     { 0x0093, "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA" },
769     { 0x0094, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA" },
770     { 0x0095, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA" },
771
772     /* RFC 4162 */
773     { 0x0096, "TLS_RSA_WITH_SEED_CBC_SHA" },
774     { 0x0097, "TLS_DH_DSS_WITH_SEED_CBC_SHA" },
775     { 0x0098, "TLS_DH_RSA_WITH_SEED_CBC_SHA" },
776     { 0x0099, "TLS_DHE_DSS_WITH_SEED_CBC_SHA" },
777     { 0x009A, "TLS_DHE_RSA_WITH_SEED_CBC_SHA" },
778     { 0x009B, "TLS_DH_anon_WITH_SEED_CBC_SHA" },
779
780     /* RFC 5288 */
781     { 0x009C, "TLS_RSA_WITH_AES_128_GCM_SHA256" },
782     { 0x009D, "TLS_RSA_WITH_AES_256_GCM_SHA384" },
783     { 0x009E, "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256" },
784     { 0x009F, "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384" },
785     { 0x00A0, "TLS_DH_RSA_WITH_AES_128_GCM_SHA256" },
786     { 0x00A1, "TLS_DH_RSA_WITH_AES_256_GCM_SHA384" },
787     { 0x00A2, "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256" },
788     { 0x00A3, "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384" },
789     { 0x00A4, "TLS_DH_DSS_WITH_AES_128_GCM_SHA256" },
790     { 0x00A5, "TLS_DH_DSS_WITH_AES_256_GCM_SHA384" },
791     { 0x00A6, "TLS_DH_anon_WITH_AES_128_GCM_SHA256" },
792     { 0x00A7, "TLS_DH_anon_WITH_AES_256_GCM_SHA384" },
793
794     /* RFC 5487 */
795     { 0x00A8, "TLS_PSK_WITH_AES_128_GCM_SHA256" },
796     { 0x00A9, "TLS_PSK_WITH_AES_256_GCM_SHA384" },
797     { 0x00AA, "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256" },
798     { 0x00AB, "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384" },
799     { 0x00AC, "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256" },
800     { 0x00AD, "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384" },
801     { 0x00AE, "TLS_PSK_WITH_AES_128_CBC_SHA256" },
802     { 0x00AF, "TLS_PSK_WITH_AES_256_CBC_SHA384" },
803     { 0x00B0, "TLS_PSK_WITH_NULL_SHA256" },
804     { 0x00B1, "TLS_PSK_WITH_NULL_SHA384" },
805     { 0x00B2, "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256" },
806     { 0x00B3, "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384" },
807     { 0x00B4, "TLS_DHE_PSK_WITH_NULL_SHA256" },
808     { 0x00B5, "TLS_DHE_PSK_WITH_NULL_SHA384" },
809     { 0x00B6, "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256" },
810     { 0x00B7, "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384" },
811     { 0x00B8, "TLS_RSA_PSK_WITH_NULL_SHA256" },
812     { 0x00B9, "TLS_RSA_PSK_WITH_NULL_SHA384" },
813
814     /* From RFC 5932 */
815     { 0x00BA, "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
816     { 0x00BB, "TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
817     { 0x00BC, "TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
818     { 0x00BD, "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256" },
819     { 0x00BE, "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
820     { 0x00BF, "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256" },
821     { 0x00C0, "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
822     { 0x00C1, "TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
823     { 0x00C2, "TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
824     { 0x00C3, "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256" },
825     { 0x00C4, "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256" },
826     { 0x00C5, "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256" },
827     /* 0x00,0xC6-FE Unassigned  */
828     /* From RFC 5746 */
829     { 0x00FF, "TLS_EMPTY_RENEGOTIATION_INFO_SCSV" },
830     /* https://tools.ietf.org/html/draft-ietf-tls-tls13 */
831     { 0x1301, "TLS_AES_128_GCM_SHA256" },
832     { 0x1302, "TLS_AES_256_GCM_SHA384" },
833     { 0x1303, "TLS_CHACHA20_POLY1305_SHA256" },
834     { 0x1304, "TLS_AES_128_CCM_SHA256" },
835     { 0x1305, "TLS_AES_128_CCM_8_SHA256" },
836     /* From RFC 7507 */
837     { 0x5600, "TLS_FALLBACK_SCSV" },
838     /* From RFC 4492 */
839     { 0xc001, "TLS_ECDH_ECDSA_WITH_NULL_SHA" },
840     { 0xc002, "TLS_ECDH_ECDSA_WITH_RC4_128_SHA" },
841     { 0xc003, "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA" },
842     { 0xc004, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA" },
843     { 0xc005, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA" },
844     { 0xc006, "TLS_ECDHE_ECDSA_WITH_NULL_SHA" },
845     { 0xc007, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA" },
846     { 0xc008, "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA" },
847     { 0xc009, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA" },
848     { 0xc00a, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA" },
849     { 0xc00b, "TLS_ECDH_RSA_WITH_NULL_SHA" },
850     { 0xc00c, "TLS_ECDH_RSA_WITH_RC4_128_SHA" },
851     { 0xc00d, "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA" },
852     { 0xc00e, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA" },
853     { 0xc00f, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA" },
854     { 0xc010, "TLS_ECDHE_RSA_WITH_NULL_SHA" },
855     { 0xc011, "TLS_ECDHE_RSA_WITH_RC4_128_SHA" },
856     { 0xc012, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA" },
857     { 0xc013, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA" },
858     { 0xc014, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA" },
859     { 0xc015, "TLS_ECDH_anon_WITH_NULL_SHA" },
860     { 0xc016, "TLS_ECDH_anon_WITH_RC4_128_SHA" },
861     { 0xc017, "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA" },
862     { 0xc018, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA" },
863     { 0xc019, "TLS_ECDH_anon_WITH_AES_256_CBC_SHA" },
864
865     /* RFC 5054 */
866     { 0xC01A, "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA" },
867     { 0xC01B, "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA" },
868     { 0xC01C, "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA" },
869     { 0xC01D, "TLS_SRP_SHA_WITH_AES_128_CBC_SHA" },
870     { 0xC01E, "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA" },
871     { 0xC01F, "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA" },
872     { 0xC020, "TLS_SRP_SHA_WITH_AES_256_CBC_SHA" },
873     { 0xC021, "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA" },
874     { 0xC022, "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA" },
875
876     /* RFC 5589 */
877     { 0xC023, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256" },
878     { 0xC024, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384" },
879     { 0xC025, "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256" },
880     { 0xC026, "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384" },
881     { 0xC027, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256" },
882     { 0xC028, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384" },
883     { 0xC029, "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256" },
884     { 0xC02A, "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384" },
885     { 0xC02B, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" },
886     { 0xC02C, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" },
887     { 0xC02D, "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256" },
888     { 0xC02E, "TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384" },
889     { 0xC02F, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" },
890     { 0xC030, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" },
891     { 0xC031, "TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256" },
892     { 0xC032, "TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384" },
893
894     /* RFC 5489 */
895     { 0xC033, "TLS_ECDHE_PSK_WITH_RC4_128_SHA" },
896     { 0xC034, "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA" },
897     { 0xC035, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA" },
898     { 0xC036, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA" },
899     { 0xC037, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" },
900     { 0xC038, "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384" },
901     { 0xC039, "TLS_ECDHE_PSK_WITH_NULL_SHA" },
902     { 0xC03A, "TLS_ECDHE_PSK_WITH_NULL_SHA256" },
903     { 0xC03B, "TLS_ECDHE_PSK_WITH_NULL_SHA384" },
904
905     /* RFC 6209 */
906     { 0xC03C, "TLS_RSA_WITH_ARIA_128_CBC_SHA256" },
907     { 0xC03D, "TLS_RSA_WITH_ARIA_256_CBC_SHA384" },
908     { 0xC03E, "TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256" },
909     { 0xC03F, "TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384" },
910     { 0xC040, "TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256" },
911     { 0xC041, "TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384" },
912     { 0xC042, "TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256" },
913     { 0xC043, "TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384" },
914     { 0xC044, "TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256" },
915     { 0xC045, "TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384" },
916     { 0xC046, "TLS_DH_anon_WITH_ARIA_128_CBC_SHA256" },
917     { 0xC047, "TLS_DH_anon_WITH_ARIA_256_CBC_SHA384" },
918     { 0xC048, "TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256" },
919     { 0xC049, "TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384" },
920     { 0xC04A, "TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256" },
921     { 0xC04B, "TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384" },
922     { 0xC04C, "TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256" },
923     { 0xC04D, "TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384" },
924     { 0xC04E, "TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256" },
925     { 0xC04F, "TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384" },
926     { 0xC050, "TLS_RSA_WITH_ARIA_128_GCM_SHA256" },
927     { 0xC051, "TLS_RSA_WITH_ARIA_256_GCM_SHA384" },
928     { 0xC052, "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256" },
929     { 0xC053, "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384" },
930     { 0xC054, "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256" },
931     { 0xC055, "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384" },
932     { 0xC056, "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256" },
933     { 0xC057, "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384" },
934     { 0xC058, "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256" },
935     { 0xC059, "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384" },
936     { 0xC05A, "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256" },
937     { 0xC05B, "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384" },
938     { 0xC05C, "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256" },
939     { 0xC05D, "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384" },
940     { 0xC05E, "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256" },
941     { 0xC05F, "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384" },
942     { 0xC060, "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256" },
943     { 0xC061, "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384" },
944     { 0xC062, "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256" },
945     { 0xC063, "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384" },
946     { 0xC064, "TLS_PSK_WITH_ARIA_128_CBC_SHA256" },
947     { 0xC065, "TLS_PSK_WITH_ARIA_256_CBC_SHA384" },
948     { 0xC066, "TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256" },
949     { 0xC067, "TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384" },
950     { 0xC068, "TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256" },
951     { 0xC069, "TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384" },
952     { 0xC06A, "TLS_PSK_WITH_ARIA_128_GCM_SHA256" },
953     { 0xC06B, "TLS_PSK_WITH_ARIA_256_GCM_SHA384" },
954     { 0xC06C, "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256" },
955     { 0xC06D, "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384" },
956     { 0xC06E, "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256" },
957     { 0xC06F, "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384" },
958     { 0xC070, "TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256" },
959     { 0xC071, "TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384" },
960
961     /* RFC 6367 */
962     { 0xC072, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256" },
963     { 0xC073, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384" },
964     { 0xC074, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256" },
965     { 0xC075, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384" },
966     { 0xC076, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
967     { 0xC077, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384" },
968     { 0xC078, "TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256" },
969     { 0xC079, "TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384" },
970     { 0xC07A, "TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
971     { 0xC07B, "TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
972     { 0xC07C, "TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
973     { 0xC07D, "TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
974     { 0xC07E, "TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
975     { 0xC07F, "TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
976     { 0xC080, "TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256" },
977     { 0xC081, "TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384" },
978     { 0xC082, "TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256" },
979     { 0xC083, "TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384" },
980     { 0xC084, "TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256" },
981     { 0xC085, "TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384" },
982     { 0xC086, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256" },
983     { 0xC087, "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384" },
984     { 0xC088, "TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256" },
985     { 0xC089, "TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384" },
986     { 0xC08A, "TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
987     { 0xC08B, "TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
988     { 0xC08C, "TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256" },
989     { 0xC08D, "TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384" },
990     { 0xC08E, "TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256" },
991     { 0xC08F, "TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384" },
992     { 0xC090, "TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256" },
993     { 0xC091, "TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384" },
994     { 0xC092, "TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256" },
995     { 0xC093, "TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384" },
996     { 0xC094, "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256" },
997     { 0xC095, "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384" },
998     { 0xC096, "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256" },
999     { 0xC097, "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384" },
1000     { 0xC098, "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256" },
1001     { 0xC099, "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384" },
1002     { 0xC09A, "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256" },
1003     { 0xC09B, "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384" },
1004
1005     /* RFC 6655 */
1006     { 0xC09C, "TLS_RSA_WITH_AES_128_CCM" },
1007     { 0xC09D, "TLS_RSA_WITH_AES_256_CCM" },
1008     { 0xC09E, "TLS_DHE_RSA_WITH_AES_128_CCM" },
1009     { 0xC09F, "TLS_DHE_RSA_WITH_AES_256_CCM" },
1010     { 0xC0A0, "TLS_RSA_WITH_AES_128_CCM_8" },
1011     { 0xC0A1, "TLS_RSA_WITH_AES_256_CCM_8" },
1012     { 0xC0A2, "TLS_DHE_RSA_WITH_AES_128_CCM_8" },
1013     { 0xC0A3, "TLS_DHE_RSA_WITH_AES_256_CCM_8" },
1014     { 0xC0A4, "TLS_PSK_WITH_AES_128_CCM" },
1015     { 0xC0A5, "TLS_PSK_WITH_AES_256_CCM" },
1016     { 0xC0A6, "TLS_DHE_PSK_WITH_AES_128_CCM" },
1017     { 0xC0A7, "TLS_DHE_PSK_WITH_AES_256_CCM" },
1018     { 0xC0A8, "TLS_PSK_WITH_AES_128_CCM_8" },
1019     { 0xC0A9, "TLS_PSK_WITH_AES_256_CCM_8" },
1020     { 0xC0AA, "TLS_PSK_DHE_WITH_AES_128_CCM_8" },
1021     { 0xC0AB, "TLS_PSK_DHE_WITH_AES_256_CCM_8" },
1022
1023     /* RFC 7251 */
1024     { 0xC0AC, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM" },
1025     { 0xC0AD, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM" },
1026     { 0xC0AE, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8" },
1027     { 0xC0AF, "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8" },
1028 /*
1029 0xC0,0xAB-FF Unassigned
1030 0xC1-FD,* Unassigned
1031 0xFE,0x00-FD Unassigned
1032 0xFE,0xFE-FF Reserved to avoid conflicts with widely deployed implementations [Pasi_Eronen]
1033 0xFF,0x00-FF Reserved for Private Use [RFC5246]
1034 */
1035
1036     /* old numbers used in the beginning
1037      * http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305 */
1038     { 0xCC13, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1039     { 0xCC14, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
1040     { 0xCC15, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1041
1042     /* http://tools.ietf.org/html/draft-ietf-tls-chacha20-poly1305 */
1043     { 0xCCA8, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1044     { 0xCCA9, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256" },
1045     { 0xCCAA, "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256" },
1046     { 0xCCAB, "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1047     { 0xCCAC, "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1048     { 0xCCAD, "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1049     { 0xCCAE, "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256" },
1050
1051     /* http://tools.ietf.org/html/draft-josefsson-salsa20-tls */
1052     { 0xE410, "TLS_RSA_WITH_ESTREAM_SALSA20_SHA1" },
1053     { 0xE411, "TLS_RSA_WITH_SALSA20_SHA1" },
1054     { 0xE412, "TLS_ECDHE_RSA_WITH_ESTREAM_SALSA20_SHA1" },
1055     { 0xE413, "TLS_ECDHE_RSA_WITH_SALSA20_SHA1" },
1056     { 0xE414, "TLS_ECDHE_ECDSA_WITH_ESTREAM_SALSA20_SHA1" },
1057     { 0xE415, "TLS_ECDHE_ECDSA_WITH_SALSA20_SHA1" },
1058     { 0xE416, "TLS_PSK_WITH_ESTREAM_SALSA20_SHA1" },
1059     { 0xE417, "TLS_PSK_WITH_SALSA20_SHA1" },
1060     { 0xE418, "TLS_ECDHE_PSK_WITH_ESTREAM_SALSA20_SHA1" },
1061     { 0xE419, "TLS_ECDHE_PSK_WITH_SALSA20_SHA1" },
1062     { 0xE41A, "TLS_RSA_PSK_WITH_ESTREAM_SALSA20_SHA1" },
1063     { 0xE41B, "TLS_RSA_PSK_WITH_SALSA20_SHA1" },
1064     { 0xE41C, "TLS_DHE_PSK_WITH_ESTREAM_SALSA20_SHA1" },
1065     { 0xE41D, "TLS_DHE_PSK_WITH_SALSA20_SHA1" },
1066     { 0xE41E, "TLS_DHE_RSA_WITH_ESTREAM_SALSA20_SHA1" },
1067     { 0xE41F, "TLS_DHE_RSA_WITH_SALSA20_SHA1" },
1068
1069     /* these from http://www.mozilla.org/projects/
1070          security/pki/nss/ssl/fips-ssl-ciphersuites.html */
1071     { 0xfefe, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
1072     { 0xfeff, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
1073     { 0xffe0, "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA" },
1074     { 0xffe1, "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
1075     /* note that ciphersuites 0xff00 - 0xffff are private */
1076     { 0x00, NULL }
1077 };
1078
1079 value_string_ext ssl_31_ciphersuite_ext = VALUE_STRING_EXT_INIT(ssl_31_ciphersuite);
1080
1081
1082 const value_string pct_msg_types[] = {
1083     { PCT_MSG_CLIENT_HELLO,         "Client Hello" },
1084     { PCT_MSG_SERVER_HELLO,         "Server Hello" },
1085     { PCT_MSG_CLIENT_MASTER_KEY,    "Client Master Key" },
1086     { PCT_MSG_SERVER_VERIFY,        "Server Verify" },
1087     { PCT_MSG_ERROR,                "Error" },
1088     { 0x00, NULL }
1089 };
1090
1091 const value_string pct_cipher_type[] = {
1092     { PCT_CIPHER_DES, "DES" },
1093     { PCT_CIPHER_IDEA, "IDEA" },
1094     { PCT_CIPHER_RC2, "RC2" },
1095     { PCT_CIPHER_RC4, "RC4" },
1096     { PCT_CIPHER_DES_112, "DES 112 bit" },
1097     { PCT_CIPHER_DES_168, "DES 168 bit" },
1098     { 0x00, NULL }
1099 };
1100
1101 const value_string pct_hash_type[] = {
1102     { PCT_HASH_MD5, "MD5" },
1103     { PCT_HASH_MD5_TRUNC_64, "MD5_TRUNC_64"},
1104     { PCT_HASH_SHA, "SHA"},
1105     { PCT_HASH_SHA_TRUNC_80, "SHA_TRUNC_80"},
1106     { PCT_HASH_DES_DM, "DES_DM"},
1107     { 0x00, NULL }
1108 };
1109
1110 const value_string pct_cert_type[] = {
1111     { PCT_CERT_NONE, "None" },
1112     { PCT_CERT_X509, "X.509" },
1113     { PCT_CERT_PKCS7, "PKCS #7" },
1114     { 0x00, NULL }
1115 };
1116 const value_string pct_sig_type[] = {
1117     { PCT_SIG_NONE, "None" },
1118     { PCT_SIG_RSA_MD5, "MD5" },
1119     { PCT_SIG_RSA_SHA, "RSA SHA" },
1120     { PCT_SIG_DSA_SHA, "DSA SHA" },
1121     { 0x00, NULL }
1122 };
1123
1124 const value_string pct_exch_type[] = {
1125     { PCT_EXCH_RSA_PKCS1, "RSA PKCS#1" },
1126     { PCT_EXCH_RSA_PKCS1_TOKEN_DES, "RSA PKCS#1 Token DES" },
1127     { PCT_EXCH_RSA_PKCS1_TOKEN_DES3, "RSA PKCS#1 Token 3DES" },
1128     { PCT_EXCH_RSA_PKCS1_TOKEN_RC2, "RSA PKCS#1 Token RC-2" },
1129     { PCT_EXCH_RSA_PKCS1_TOKEN_RC4, "RSA PKCS#1 Token RC-4" },
1130     { PCT_EXCH_DH_PKCS3, "DH PKCS#3" },
1131     { PCT_EXCH_DH_PKCS3_TOKEN_DES, "DH PKCS#3 Token DES" },
1132     { PCT_EXCH_DH_PKCS3_TOKEN_DES3, "DH PKCS#3 Token 3DES" },
1133     { PCT_EXCH_FORTEZZA_TOKEN, "Fortezza" },
1134     { 0x00, NULL }
1135 };
1136
1137 const value_string pct_error_code[] = {
1138     { PCT_ERR_BAD_CERTIFICATE, "PCT_ERR_BAD_CERTIFICATE" },
1139     { PCT_ERR_CLIENT_AUTH_FAILED, "PCT_ERR_CLIENT_AUTH_FAILE" },
1140     { PCT_ERR_ILLEGAL_MESSAGE, "PCT_ERR_ILLEGAL_MESSAGE" },
1141     { PCT_ERR_INTEGRITY_CHECK_FAILED, "PCT_ERR_INTEGRITY_CHECK_FAILED" },
1142     { PCT_ERR_SERVER_AUTH_FAILED, "PCT_ERR_SERVER_AUTH_FAILED" },
1143     { PCT_ERR_SPECS_MISMATCH, "PCT_ERR_SPECS_MISMATCH" },
1144     { 0x00, NULL }
1145 };
1146
1147 /* http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#tls-extensiontype-values-1 */
1148 const value_string tls_hello_extension_types[] = {
1149     { SSL_HND_HELLO_EXT_SERVER_NAME, "server_name" }, /* RFC 6066 */
1150     { SSL_HND_HELLO_EXT_MAX_FRAGMENT_LENGTH, "max_fragment_length" },/* RFC 6066 */
1151     { SSL_HND_HELLO_EXT_CLIENT_CERTIFICATE_URL, "client_certificate_url" }, /* RFC 6066 */
1152     { SSL_HND_HELLO_EXT_TRUSTED_CA_KEYS, "trusted_ca_keys" }, /* RFC 6066 */
1153     { SSL_HND_HELLO_EXT_TRUNCATED_HMAC, "truncated_hmac" }, /* RFC 6066 */
1154     { SSL_HND_HELLO_EXT_STATUS_REQUEST, "status_request" }, /* RFC 6066 */
1155     { SSL_HND_HELLO_EXT_USER_MAPPING, "user_mapping" }, /* RFC 4681 */
1156     { SSL_HND_HELLO_EXT_CLIENT_AUTHZ, "client_authz" }, /* RFC 5878 */
1157     { SSL_HND_HELLO_EXT_SERVER_AUTHZ, "server_authz" }, /* RFC 5878 */
1158     { SSL_HND_HELLO_EXT_CERT_TYPE, "cert_type" }, /* RFC 6091 */
1159     { SSL_HND_HELLO_EXT_SUPPORTED_GROUPS, "elliptic_curves" }, /* RFC 4492 */
1160     { SSL_HND_HELLO_EXT_EC_POINT_FORMATS, "ec_point_formats" }, /* RFC 4492 */
1161     { SSL_HND_HELLO_EXT_SRP, "srp" }, /* RFC 5054 */
1162     { SSL_HND_HELLO_EXT_SIGNATURE_ALGORITHMS, "signature_algorithms" }, /* RFC 5246 */
1163     { SSL_HND_HELLO_EXT_USE_SRTP, "use_srtp" }, /* RFC 5764 */
1164     { SSL_HND_HELLO_EXT_HEARTBEAT, "heartbeat" }, /* RFC 6520 */
1165     { SSL_HND_HELLO_EXT_ALPN, "application_layer_protocol_negotiation" }, /* RFC 7301 */
1166     { SSL_HND_HELLO_EXT_STATUS_REQUEST_V2, "status_request_v2" }, /* RFC 6961 */
1167     { SSL_HND_HELLO_EXT_SIGNED_CERTIFICATE_TIMESTAMP, "signed_certificate_timestamp" }, /* RFC 6962 */
1168     { SSL_HND_HELLO_EXT_CLIENT_CERT_TYPE, "client_certificate_type" }, /* RFC 7250 */
1169     { SSL_HND_HELLO_EXT_SERVER_CERT_TYPE, "server_certificate_type" }, /* RFC 7250 */
1170     { SSL_HND_HELLO_EXT_PADDING, "padding" }, /* RFC 7685 */
1171     { SSL_HND_HELLO_EXT_ENCRYPT_THEN_MAC, "encrypt_then_mac" }, /* RFC 7366 */
1172     { SSL_HND_HELLO_EXT_EXTENDED_MASTER_SECRET, "extended_master_secret" }, /* RFC 7627 */
1173     { SSL_HND_HELLO_EXT_TOKEN_BINDING, "token_binding" }, /* https://tools.ietf.org/html/draft-ietf-tokbind-negotiation */
1174     { SSL_HND_HELLO_EXT_CACHED_INFO, "cached_info" }, /* RFC 7924 */
1175     { SSL_HND_HELLO_EXT_SESSION_TICKET_TLS, "SessionTicket TLS" }, /* RFC 4507 */
1176     { SSL_HND_HELLO_EXT_KEY_SHARE, "key_share" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1177     { SSL_HND_HELLO_EXT_PRE_SHARED_KEY, "pre_shared_key" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1178     { SSL_HND_HELLO_EXT_EARLY_DATA, "early_data" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1179     { SSL_HND_HELLO_EXT_SUPPORTED_VERSIONS, "supported_versions" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1180     { SSL_HND_HELLO_EXT_COOKIE, "cookie" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1181     { SSL_HND_HELLO_EXT_PSK_KEY_EXCHANGE_MODES, "psk_key_exchange_modes" }, /* TLS 1.3 https://tools.ietf.org/html/draft-ietf-tls-tls13 */
1182     { SSL_HND_HELLO_EXT_NPN, "next_protocol_negotiation"}, /* https://tools.ietf.org/id/draft-agl-tls-nextprotoneg-03.html */
1183     { SSL_HND_HELLO_EXT_CHANNEL_ID_OLD, "channel_id_old" }, /* http://tools.ietf.org/html/draft-balfanz-tls-channelid-00
1184        https://twitter.com/ericlaw/status/274237352531083264 */
1185     { SSL_HND_HELLO_EXT_CHANNEL_ID, "channel_id" }, /* http://tools.ietf.org/html/draft-balfanz-tls-channelid-01
1186        https://code.google.com/p/chromium/codesearch#chromium/src/net/third_party/nss/ssl/sslt.h&l=209 */
1187     { SSL_HND_HELLO_EXT_RENEGOTIATION_INFO, "renegotiation_info" }, /* RFC 5746 */
1188     { SSL_HND_HELLO_EXT_DRAFT_VERSION_TLS13, "Draft version of TLS 1.3" }, /* for experimentation only  https://www.ietf.org/mail-archive/web/tls/current/msg20853.html */
1189     { 0, NULL }
1190 };
1191
1192 const value_string tls_hello_ext_server_name_type_vs[] = {
1193     { 0, "host_name" },
1194     { 0, NULL }
1195 };
1196
1197 /* draft-ietf-tls-tls13-18 4.2.7 */
1198 const value_string tls_hello_ext_psk_ke_mode[] = {
1199     { 0, "PSK-only key establishment (psk_ke)" },
1200     { 1, "PSK key establishment with (EC)DHE key establishment (psk_dhe_ke)" },
1201     { 0, NULL }
1202 };
1203
1204 /* RFC 5246 7.4.1.4.1 */
1205 const value_string tls_hash_algorithm[] = {
1206     { 0, "None" },
1207     { 1, "MD5" },
1208     { 2, "SHA1" },
1209     { 3, "SHA224" },
1210     { 4, "SHA256" },
1211     { 5, "SHA384" },
1212     { 6, "SHA512" },
1213     { 0, NULL }
1214 };
1215
1216 const value_string tls_signature_algorithm[] = {
1217     { 0, "Anonymous" },
1218     { 1, "RSA" },
1219     { 2, "DSA" },
1220     { 3, "ECDSA" },
1221     { 0, NULL }
1222 };
1223
1224 /* RFC 6091 3.1 */
1225 const value_string tls_certificate_type[] = {
1226     { 0, "X.509" },
1227     { 1, "OpenPGP" },
1228     { SSL_HND_CERT_TYPE_RAW_PUBLIC_KEY, "Raw Public Key" }, /* RFC 7250 */
1229     { 0, NULL }
1230 };
1231
1232 const value_string tls_cert_chain_type[] = {
1233     { SSL_HND_CERT_URL_TYPE_INDIVIDUAL_CERT,    "Individual Certificates" },
1234     { SSL_HND_CERT_URL_TYPE_PKIPATH,            "PKI Path" },
1235     { 0, NULL }
1236 };
1237
1238 const value_string tls_cert_status_type[] = {
1239     { SSL_HND_CERT_STATUS_TYPE_OCSP,            "OCSP" },
1240     { SSL_HND_CERT_STATUS_TYPE_OCSP_MULTI,      "OCSP Multi" },
1241     { 0, NULL }
1242 };
1243
1244 /* string_string is inappropriate as it compares strings while
1245  * "byte strings MUST NOT be truncated" (RFC 7301) */
1246 typedef struct ssl_alpn_protocol {
1247     const char      *proto_name;
1248     gboolean         match_exact;
1249     const char      *dissector_name;
1250 } ssl_alpn_protocol_t;
1251 /* http://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids */
1252 static const ssl_alpn_protocol_t ssl_alpn_protocols[] = {
1253     { "http/1.1",           TRUE,   "http" },
1254     /* SPDY moves so fast, just 1, 2 and 3 are registered with IANA but there
1255      * already exists 3.1 as of this writing... match the prefix. */
1256     { "spdy/",              FALSE,  "spdy" },
1257     { "stun.turn",          TRUE,   "turnchannel" },
1258     { "stun.nat-discovery", TRUE,   "stun" },
1259     /* draft-ietf-httpbis-http2-16 */
1260     { "h2-",                FALSE,  "http2" }, /* draft versions */
1261     { "h2",                 TRUE,   "http2" }, /* final version */
1262 };
1263
1264 /* Lookup tables }}} */
1265
1266 /* we keep this internal to packet-ssl-utils, as there should be
1267    no need to access it any other way.
1268
1269    This also allows us to hide the dependency on zlib.
1270 */
1271 struct _SslDecompress {
1272     gint compression;
1273 #ifdef HAVE_ZLIB
1274     z_stream istream;
1275 #endif
1276 };
1277
1278 /* To assist in parsing client/server key exchange messages
1279    0 indicates unknown */
1280 gint ssl_get_keyex_alg(gint cipher)
1281 {
1282     /* Map Cipher suite number to Key Exchange algorithm {{{ */
1283     switch(cipher) {
1284     case 0x0017:
1285     case 0x0018:
1286     case 0x0019:
1287     case 0x001a:
1288     case 0x001b:
1289     case 0x0034:
1290     case 0x003a:
1291     case 0x0046:
1292     case 0x006c:
1293     case 0x006d:
1294     case 0x0089:
1295     case 0x009b:
1296     case 0x00a6:
1297     case 0x00a7:
1298     case 0x00bf:
1299     case 0x00c5:
1300     case 0xc084:
1301     case 0xc085:
1302         return KEX_DH_ANON;
1303     case 0x000b:
1304     case 0x000c:
1305     case 0x000d:
1306     case 0x0030:
1307     case 0x0036:
1308     case 0x003e:
1309     case 0x0042:
1310     case 0x0068:
1311     case 0x0085:
1312     case 0x0097:
1313     case 0x00a4:
1314     case 0x00a5:
1315     case 0x00bb:
1316     case 0x00c1:
1317     case 0xc082:
1318     case 0xc083:
1319         return KEX_DH_DSS;
1320     case 0x000e:
1321     case 0x000f:
1322     case 0x0010:
1323     case 0x0031:
1324     case 0x0037:
1325     case 0x003f:
1326     case 0x0043:
1327     case 0x0069:
1328     case 0x0086:
1329     case 0x0098:
1330     case 0x00a0:
1331     case 0x00a1:
1332     case 0x00bc:
1333     case 0x00c2:
1334     case 0xc07e:
1335     case 0xc07f:
1336         return KEX_DH_RSA;
1337     case 0x0011:
1338     case 0x0012:
1339     case 0x0013:
1340     case 0x0032:
1341     case 0x0038:
1342     case 0x0040:
1343     case 0x0044:
1344     case 0x0063:
1345     case 0x0065:
1346     case 0x0066:
1347     case 0x006a:
1348     case 0x0087:
1349     case 0x0099:
1350     case 0x00a2:
1351     case 0x00a3:
1352     case 0x00bd:
1353     case 0x00c3:
1354     case 0xc080:
1355     case 0xc081:
1356         return KEX_DHE_DSS;
1357     case 0x002d:
1358     case 0x008e:
1359     case 0x008f:
1360     case 0x0090:
1361     case 0x0091:
1362     case 0x00aa:
1363     case 0x00ab:
1364     case 0x00b2:
1365     case 0x00b3:
1366     case 0x00b4:
1367     case 0x00b5:
1368     case 0xc090:
1369     case 0xc091:
1370     case 0xc096:
1371     case 0xc097:
1372     case 0xc0a6:
1373     case 0xc0a7:
1374     case 0xc0aa:
1375     case 0xc0ab:
1376     case 0xe41c:
1377     case 0xe41d:
1378         return KEX_DHE_PSK;
1379     case 0x0014:
1380     case 0x0015:
1381     case 0x0016:
1382     case 0x0033:
1383     case 0x0039:
1384     case 0x0045:
1385     case 0x0067:
1386     case 0x006b:
1387     case 0x0088:
1388     case 0x009a:
1389     case 0x009e:
1390     case 0x009f:
1391     case 0x00be:
1392     case 0x00c4:
1393     case 0xc07c:
1394     case 0xc07d:
1395     case 0xc09e:
1396     case 0xc09f:
1397     case 0xc0a2:
1398     case 0xc0a3:
1399     case 0xe41e:
1400     case 0xe41f:
1401         return KEX_DHE_RSA;
1402     case 0xc015:
1403     case 0xc016:
1404     case 0xc017:
1405     case 0xc018:
1406     case 0xc019:
1407         return KEX_ECDH_ANON;
1408     case 0xc001:
1409     case 0xc002:
1410     case 0xc003:
1411     case 0xc004:
1412     case 0xc005:
1413     case 0xc025:
1414     case 0xc026:
1415     case 0xc02d:
1416     case 0xc02e:
1417     case 0xc074:
1418     case 0xc075:
1419     case 0xc088:
1420     case 0xc089:
1421         return KEX_ECDH_ECDSA;
1422     case 0xc00b:
1423     case 0xc00c:
1424     case 0xc00d:
1425     case 0xc00e:
1426     case 0xc00f:
1427     case 0xc029:
1428     case 0xc02a:
1429     case 0xc031:
1430     case 0xc032:
1431     case 0xc078:
1432     case 0xc079:
1433     case 0xc08c:
1434     case 0xc08d:
1435         return KEX_ECDH_RSA;
1436     case 0xc006:
1437     case 0xc007:
1438     case 0xc008:
1439     case 0xc009:
1440     case 0xc00a:
1441     case 0xc023:
1442     case 0xc024:
1443     case 0xc02b:
1444     case 0xc02c:
1445     case 0xc072:
1446     case 0xc073:
1447     case 0xc086:
1448     case 0xc087:
1449     case 0xc0ac:
1450     case 0xc0ad:
1451     case 0xc0ae:
1452     case 0xc0af:
1453     case 0xe414:
1454     case 0xe415:
1455         return KEX_ECDHE_ECDSA;
1456     case 0xc033:
1457     case 0xc034:
1458     case 0xc035:
1459     case 0xc036:
1460     case 0xc037:
1461     case 0xc038:
1462     case 0xc039:
1463     case 0xc03a:
1464     case 0xc03b:
1465     case 0xc09a:
1466     case 0xc09b:
1467     case 0xe418:
1468     case 0xe419:
1469         return KEX_ECDHE_PSK;
1470     case 0xc010:
1471     case 0xc011:
1472     case 0xc012:
1473     case 0xc013:
1474     case 0xc014:
1475     case 0xc027:
1476     case 0xc028:
1477     case 0xc02f:
1478     case 0xc030:
1479     case 0xc076:
1480     case 0xc077:
1481     case 0xc08a:
1482     case 0xc08b:
1483     case 0xe412:
1484     case 0xe413:
1485         return KEX_ECDHE_RSA;
1486     case 0x001e:
1487     case 0x001f:
1488     case 0x0020:
1489     case 0x0021:
1490     case 0x0022:
1491     case 0x0023:
1492     case 0x0024:
1493     case 0x0025:
1494     case 0x0026:
1495     case 0x0027:
1496     case 0x0028:
1497     case 0x0029:
1498     case 0x002a:
1499     case 0x002b:
1500         return KEX_KRB5;
1501     case 0x002c:
1502     case 0x008a:
1503     case 0x008b:
1504     case 0x008c:
1505     case 0x008d:
1506     case 0x00a8:
1507     case 0x00a9:
1508     case 0x00ae:
1509     case 0x00af:
1510     case 0x00b0:
1511     case 0x00b1:
1512     case 0xc064:
1513     case 0xc065:
1514     case 0xc08e:
1515     case 0xc08f:
1516     case 0xc094:
1517     case 0xc095:
1518     case 0xc0a4:
1519     case 0xc0a5:
1520     case 0xc0a8:
1521     case 0xc0a9:
1522     case 0xe416:
1523     case 0xe417:
1524         return KEX_PSK;
1525     case 0x0001:
1526     case 0x0002:
1527     case 0x0003:
1528     case 0x0004:
1529     case 0x0005:
1530     case 0x0006:
1531     case 0x0007:
1532     case 0x0008:
1533     case 0x0009:
1534     case 0x000a:
1535     case 0x002f:
1536     case 0x0035:
1537     case 0x003b:
1538     case 0x003c:
1539     case 0x003d:
1540     case 0x0041:
1541     case 0x0060:
1542     case 0x0061:
1543     case 0x0062:
1544     case 0x0064:
1545     case 0x0084:
1546     case 0x0096:
1547     case 0x009c:
1548     case 0x009d:
1549     case 0x00ba:
1550     case 0x00c0:
1551     case 0xc07a:
1552     case 0xc07b:
1553     case 0xc09c:
1554     case 0xc09d:
1555     case 0xc0a0:
1556     case 0xc0a1:
1557     case 0xe410:
1558     case 0xe411:
1559     case 0xfefe:
1560     case 0xfeff:
1561     case 0xffe0:
1562     case 0xffe1:
1563         return KEX_RSA;
1564     case 0x002e:
1565     case 0x0092:
1566     case 0x0093:
1567     case 0x0094:
1568     case 0x0095:
1569     case 0x00ac:
1570     case 0x00ad:
1571     case 0x00b6:
1572     case 0x00b7:
1573     case 0x00b8:
1574     case 0x00b9:
1575     case 0xc092:
1576     case 0xc093:
1577     case 0xc098:
1578     case 0xc099:
1579     case 0xe41a:
1580     case 0xe41b:
1581         return KEX_RSA_PSK;
1582     case 0xc01a:
1583     case 0xc01d:
1584     case 0xc020:
1585         return KEX_SRP_SHA;
1586     case 0xc01c:
1587     case 0xc01f:
1588     case 0xc022:
1589         return KEX_SRP_SHA_DSS;
1590     case 0xc01b:
1591     case 0xc01e:
1592     case 0xc021:
1593         return KEX_SRP_SHA_RSA;
1594     default:
1595         break;
1596     }
1597
1598     return 0;
1599     /* }}} */
1600 }
1601
1602
1603 /* StringInfo structure (len + data) functions {{{ */
1604
1605 static gint
1606 ssl_data_alloc(StringInfo* str, size_t len)
1607 {
1608     str->data = (guchar *)g_malloc(len);
1609     /* the allocator can return a null pointer for a size equal to 0,
1610      * and that must be allowed */
1611     if (len > 0 && !str->data)
1612         return -1;
1613     str->data_len = (guint) len;
1614     return 0;
1615 }
1616
1617 void
1618 ssl_data_set(StringInfo* str, const guchar* data, guint len)
1619 {
1620     DISSECTOR_ASSERT(data);
1621     memcpy(str->data, data, len);
1622     str->data_len = len;
1623 }
1624
1625 #ifdef HAVE_LIBGCRYPT
1626 static gint
1627 ssl_data_realloc(StringInfo* str, guint len)
1628 {
1629     str->data = (guchar *)g_realloc(str->data, len);
1630     if (!str->data)
1631         return -1;
1632     str->data_len = len;
1633     return 0;
1634 }
1635
1636 static StringInfo *
1637 ssl_data_clone(StringInfo *str)
1638 {
1639     StringInfo *cloned_str;
1640     cloned_str = (StringInfo *) wmem_alloc0(wmem_file_scope(),
1641             sizeof(StringInfo) + str->data_len);
1642     cloned_str->data = (guchar *) (cloned_str + 1);
1643     ssl_data_set(cloned_str, str->data, str->data_len);
1644     return cloned_str;
1645 }
1646
1647 static gint
1648 ssl_data_copy(StringInfo* dst, StringInfo* src)
1649 {
1650     if (dst->data_len < src->data_len) {
1651       if (ssl_data_realloc(dst, src->data_len))
1652         return -1;
1653     }
1654     memcpy(dst->data, src->data, src->data_len);
1655     dst->data_len = src->data_len;
1656     return 0;
1657 }
1658 #endif
1659
1660 /* from_hex converts |hex_len| bytes of hex data from |in| and sets |*out| to
1661  * the result. |out->data| will be allocated using wmem_file_scope. Returns TRUE on
1662  * success. */
1663 static gboolean from_hex(StringInfo* out, const char* in, gsize hex_len) {
1664     gsize i;
1665
1666     if (hex_len & 1)
1667         return FALSE;
1668
1669     out->data = (guchar *)wmem_alloc(wmem_file_scope(), hex_len / 2);
1670     for (i = 0; i < hex_len / 2; i++) {
1671         int a = ws_xton(in[i*2]);
1672         int b = ws_xton(in[i*2 + 1]);
1673         if (a == -1 || b == -1)
1674             return FALSE;
1675         out->data[i] = a << 4 | b;
1676     }
1677     out->data_len = (guint)hex_len / 2;
1678     return TRUE;
1679 }
1680 /* StringInfo structure (len + data) functions }}} */
1681
1682
1683 #ifdef HAVE_LIBGCRYPT
1684
1685 /* libgcrypt wrappers for HMAC/message digest operations {{{ */
1686 /* hmac abstraction layer */
1687 #define SSL_HMAC gcry_md_hd_t
1688
1689 static inline gint
1690 ssl_hmac_init(SSL_HMAC* md, const void * key, gint len, gint algo)
1691 {
1692     gcry_error_t  err;
1693     const char   *err_str, *err_src;
1694
1695     err = gcry_md_open(md,algo, GCRY_MD_FLAG_HMAC);
1696     if (err != 0) {
1697         err_str = gcry_strerror(err);
1698         err_src = gcry_strsource(err);
1699         ssl_debug_printf("ssl_hmac_init(): gcry_md_open failed %s/%s", err_str, err_src);
1700         return -1;
1701     }
1702     gcry_md_setkey (*(md), key, len);
1703     return 0;
1704 }
1705 static inline void
1706 ssl_hmac_update(SSL_HMAC* md, const void* data, gint len)
1707 {
1708     gcry_md_write(*(md), data, len);
1709 }
1710 static inline void
1711 ssl_hmac_final(SSL_HMAC* md, guchar* data, guint* datalen)
1712 {
1713     gint  algo;
1714     guint len;
1715
1716     algo = gcry_md_get_algo (*(md));
1717     len  = gcry_md_get_algo_dlen(algo);
1718     DISSECTOR_ASSERT(len <= *datalen);
1719     memcpy(data, gcry_md_read(*(md), algo), len);
1720     *datalen = len;
1721 }
1722 static inline void
1723 ssl_hmac_cleanup(SSL_HMAC* md)
1724 {
1725     gcry_md_close(*(md));
1726 }
1727
1728 /* message digest abstraction layer*/
1729 #define SSL_MD gcry_md_hd_t
1730
1731 static inline gint
1732 ssl_md_init(SSL_MD* md, gint algo)
1733 {
1734     gcry_error_t  err;
1735     const char   *err_str, *err_src;
1736     err = gcry_md_open(md,algo, 0);
1737     if (err != 0) {
1738         err_str = gcry_strerror(err);
1739         err_src = gcry_strsource(err);
1740         ssl_debug_printf("ssl_md_init(): gcry_md_open failed %s/%s", err_str, err_src);
1741         return -1;
1742     }
1743     return 0;
1744 }
1745 static inline void
1746 ssl_md_update(SSL_MD* md, guchar* data, gint len)
1747 {
1748     gcry_md_write(*(md), data, len);
1749 }
1750 static inline void
1751 ssl_md_final(SSL_MD* md, guchar* data, guint* datalen)
1752 {
1753     gint algo;
1754     gint len;
1755     algo = gcry_md_get_algo (*(md));
1756     len = gcry_md_get_algo_dlen (algo);
1757     memcpy(data, gcry_md_read(*(md),  algo), len);
1758     *datalen = len;
1759 }
1760 static inline void
1761 ssl_md_cleanup(SSL_MD* md)
1762 {
1763     gcry_md_close(*(md));
1764 }
1765
1766 /* md5 /sha abstraction layer */
1767 #define SSL_SHA_CTX gcry_md_hd_t
1768 #define SSL_MD5_CTX gcry_md_hd_t
1769
1770 static inline void
1771 ssl_sha_init(SSL_SHA_CTX* md)
1772 {
1773     gcry_md_open(md,GCRY_MD_SHA1, 0);
1774 }
1775 static inline void
1776 ssl_sha_update(SSL_SHA_CTX* md, guchar* data, gint len)
1777 {
1778     gcry_md_write(*(md), data, len);
1779 }
1780 static inline void
1781 ssl_sha_final(guchar* buf, SSL_SHA_CTX* md)
1782 {
1783     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_SHA1),
1784            gcry_md_get_algo_dlen(GCRY_MD_SHA1));
1785 }
1786 static inline void
1787 ssl_sha_cleanup(SSL_SHA_CTX* md)
1788 {
1789     gcry_md_close(*(md));
1790 }
1791
1792 static inline gint
1793 ssl_md5_init(SSL_MD5_CTX* md)
1794 {
1795     return gcry_md_open(md,GCRY_MD_MD5, 0);
1796 }
1797 static inline void
1798 ssl_md5_update(SSL_MD5_CTX* md, guchar* data, gint len)
1799 {
1800     gcry_md_write(*(md), data, len);
1801 }
1802 static inline void
1803 ssl_md5_final(guchar* buf, SSL_MD5_CTX* md)
1804 {
1805     memcpy(buf, gcry_md_read(*(md),  GCRY_MD_MD5),
1806            gcry_md_get_algo_dlen(GCRY_MD_MD5));
1807 }
1808 static inline void
1809 ssl_md5_cleanup(SSL_MD5_CTX* md)
1810 {
1811     gcry_md_close(*(md));
1812 }
1813 /* libgcrypt wrappers for HMAC/message digest operations }}} */
1814
1815 /* libgcrypt wrappers for Cipher state manipulation {{{ */
1816 gint
1817 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher, guchar* iv, gint iv_len)
1818 {
1819     gint ret;
1820 #if 0
1821     guchar *ivp;
1822     gint i;
1823     gcry_cipher_hd_t c;
1824     c=(gcry_cipher_hd_t)*cipher;
1825 #endif
1826     ssl_debug_printf("--------------------------------------------------------------------");
1827 #if 0
1828     for(ivp=c->iv,i=0; i < iv_len; i++ )
1829         {
1830         ssl_debug_printf("%d ",ivp[i]);
1831         i++;
1832         }
1833 #endif
1834     ssl_debug_printf("--------------------------------------------------------------------");
1835     ret = gcry_cipher_setiv(*(cipher), iv, iv_len);
1836 #if 0
1837     for(ivp=c->iv,i=0; i < iv_len; i++ )
1838         {
1839         ssl_debug_printf("%d ",ivp[i]);
1840         i++;
1841         }
1842 #endif
1843     ssl_debug_printf("--------------------------------------------------------------------");
1844     return ret;
1845 }
1846 /* stream cipher abstraction layer*/
1847 static gint
1848 ssl_cipher_init(gcry_cipher_hd_t *cipher, gint algo, guchar* sk,
1849         guchar* iv, gint mode)
1850 {
1851     gint gcry_modes[] = {
1852         GCRY_CIPHER_MODE_STREAM,
1853         GCRY_CIPHER_MODE_CBC,
1854 #ifdef HAVE_LIBGCRYPT_AEAD
1855         GCRY_CIPHER_MODE_GCM,
1856         GCRY_CIPHER_MODE_CCM,
1857         GCRY_CIPHER_MODE_CCM
1858 #else
1859         GCRY_CIPHER_MODE_CTR,
1860         GCRY_CIPHER_MODE_CTR,
1861         GCRY_CIPHER_MODE_CTR,
1862 #endif
1863     };
1864     gint err;
1865     if (algo == -1) {
1866         /* NULL mode */
1867         *(cipher) = (gcry_cipher_hd_t)-1;
1868         return 0;
1869     }
1870     err = gcry_cipher_open(cipher, algo, gcry_modes[mode], 0);
1871     if (err !=0)
1872         return  -1;
1873     err = gcry_cipher_setkey(*(cipher), sk, gcry_cipher_get_algo_keylen (algo));
1874     if (err != 0)
1875         return -1;
1876     /* AEAD cipher suites will set the nonce later. */
1877     if (mode == MODE_CBC) {
1878         err = gcry_cipher_setiv(*(cipher), iv, gcry_cipher_get_algo_blklen(algo));
1879         if (err != 0)
1880             return -1;
1881     }
1882     return 0;
1883 }
1884 static inline gint
1885 ssl_cipher_decrypt(gcry_cipher_hd_t *cipher, guchar * out, gint outl,
1886                    const guchar * in, gint inl)
1887 {
1888     if ((*cipher) == (gcry_cipher_hd_t)-1)
1889     {
1890         if (in && inl)
1891             memcpy(out, in, outl < inl ? outl : inl);
1892         return 0;
1893     }
1894     return gcry_cipher_decrypt ( *(cipher), out, outl, in, inl);
1895 }
1896 static inline gint
1897 ssl_get_digest_by_name(const gchar*name)
1898 {
1899     return gcry_md_map_name(name);
1900 }
1901 static inline gint
1902 ssl_get_cipher_by_name(const gchar* name)
1903 {
1904     return gcry_cipher_map_name(name);
1905 }
1906
1907 static inline void
1908 ssl_cipher_cleanup(gcry_cipher_hd_t *cipher)
1909 {
1910     if ((*cipher) != (gcry_cipher_hd_t)-1)
1911         gcry_cipher_close(*cipher);
1912     *cipher = NULL;
1913 }
1914 /* libgcrypt wrappers for Cipher state manipulation }}} */
1915
1916 #ifdef HAVE_LIBGNUTLS
1917 /* libgcrypt wrapper to decrypt using a RSA private key {{{ */
1918 /* decrypt data with private key. Store decrypted data directly into input
1919  * buffer */
1920 static int
1921 ssl_private_decrypt(const guint len, guchar* data, gcry_sexp_t pk)
1922 {
1923     gint        rc = 0;
1924     size_t      decr_len = 0, i = 0;
1925     gcry_sexp_t s_data = NULL, s_plain = NULL;
1926     gcry_mpi_t  encr_mpi = NULL, text = NULL;
1927
1928     /* create mpi representation of encrypted data */
1929     rc = gcry_mpi_scan(&encr_mpi, GCRYMPI_FMT_USG, data, len, NULL);
1930     if (rc != 0 ) {
1931         ssl_debug_printf("pcry_private_decrypt: can't convert data to mpi (size %d):%s\n",
1932             len, gcry_strerror(rc));
1933         return 0;
1934     }
1935
1936     /* put the data into a simple list */
1937     rc = gcry_sexp_build(&s_data, NULL, "(enc-val(rsa(a%m)))", encr_mpi);
1938     if (rc != 0) {
1939         ssl_debug_printf("pcry_private_decrypt: can't build encr_sexp:%s\n",
1940              gcry_strerror(rc));
1941         decr_len = 0;
1942         goto out;
1943     }
1944
1945     /* pass it to libgcrypt */
1946     rc = gcry_pk_decrypt(&s_plain, s_data, pk);
1947     if (rc != 0)
1948     {
1949         ssl_debug_printf("pcry_private_decrypt: can't decrypt key:%s\n",
1950             gcry_strerror(rc));
1951         decr_len = 0;
1952         goto out;
1953     }
1954
1955     /* convert plain text sexp to mpi format */
1956     text = gcry_sexp_nth_mpi(s_plain, 0, 0);
1957     if (! text) {
1958         ssl_debug_printf("pcry_private_decrypt: can't convert sexp to mpi\n");
1959         decr_len = 0;
1960         goto out;
1961     }
1962
1963     /* compute size requested for plaintext buffer */
1964     rc = gcry_mpi_print(GCRYMPI_FMT_USG, NULL, 0, &decr_len, text);
1965     if (rc != 0) {
1966         ssl_debug_printf("pcry_private_decrypt: can't compute decr size:%s\n",
1967             gcry_strerror(rc));
1968         decr_len = 0;
1969         goto out;
1970     }
1971
1972     /* sanity check on out buffer */
1973     if (decr_len > len) {
1974         ssl_debug_printf("pcry_private_decrypt: decrypted data is too long ?!? (%" G_GSIZE_MODIFIER "u max %d)\n", decr_len, len);
1975         decr_len = 0;
1976         goto out;
1977     }
1978
1979     /* write plain text to newly allocated buffer */
1980     rc = gcry_mpi_print(GCRYMPI_FMT_USG, data, len, &decr_len, text);
1981     if (rc != 0) {
1982         ssl_debug_printf("pcry_private_decrypt: can't print decr data to mpi (size %" G_GSIZE_MODIFIER "u):%s\n", decr_len, gcry_strerror(rc));
1983         decr_len = 0;
1984         goto out;
1985     }
1986
1987     ssl_print_data("decrypted_unstrip_pre_master", data, decr_len);
1988
1989     /* strip the padding*/
1990     rc = 0;
1991     for (i = 1; i < decr_len; i++) {
1992         if (data[i] == 0) {
1993             rc = (gint) i+1;
1994             break;
1995         }
1996     }
1997
1998     ssl_debug_printf("pcry_private_decrypt: stripping %d bytes, decr_len %" G_GSIZE_MODIFIER "u\n", rc, decr_len);
1999     decr_len -= rc;
2000     memmove(data, data+rc, decr_len);
2001
2002 out:
2003     gcry_sexp_release(s_data);
2004     gcry_sexp_release(s_plain);
2005     gcry_mpi_release(encr_mpi);
2006     gcry_mpi_release(text);
2007     return (int) decr_len;
2008 } /* }}} */
2009 #endif /* HAVE_LIBGNUTLS */
2010
2011 #else /* ! HAVE_LIBGCRYPT */
2012
2013 gint
2014 ssl_cipher_setiv(SSL_CIPHER_CTX *cipher _U_, guchar* iv _U_, gint iv_len _U_)
2015 {
2016     ssl_debug_printf("ssl_cipher_setiv: impossible without gnutls.\n");
2017     return 0;
2018 }
2019 #endif /* ! HAVE_LIBGCRYPT */
2020
2021
2022 #ifdef HAVE_LIBGCRYPT /* Save space if decryption is not enabled. */
2023
2024 /* Digests, Ciphers and Cipher Suites registry {{{ */
2025 static const SslDigestAlgo digests[]={
2026     {"MD5",     16},
2027     {"SHA1",    20},
2028     {"SHA256",  32},
2029     {"SHA384",  48},
2030     {"Not Applicable",  0},
2031 };
2032
2033 #define DIGEST_MAX_SIZE 48
2034
2035 /* get index digest index */
2036 static const SslDigestAlgo *
2037 ssl_cipher_suite_dig(const SslCipherSuite *cs) {
2038     return &digests[cs->dig - DIG_MD5];
2039 }
2040
2041 static const gchar *ciphers[]={
2042     "DES",
2043     "3DES",
2044     "ARCFOUR", /* libgcrypt does not support rc4, but this should be 100% compatible*/
2045     "RFC2268_128", /* libgcrypt name for RC2 with a 128-bit key */
2046     "IDEA",
2047     "AES",
2048     "AES256",
2049     "CAMELLIA128",
2050     "CAMELLIA256",
2051     "SEED",
2052     "*UNKNOWN*"
2053 };
2054
2055 static const SslCipherSuite cipher_suites[]={
2056     {0x0001,KEX_RSA,            ENC_NULL,       DIG_MD5,    MODE_STREAM},   /* TLS_RSA_WITH_NULL_MD5 */
2057     {0x0002,KEX_RSA,            ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_RSA_WITH_NULL_SHA */
2058     {0x0003,KEX_RSA,            ENC_RC4,        DIG_MD5,    MODE_STREAM},   /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
2059     {0x0004,KEX_RSA,            ENC_RC4,        DIG_MD5,    MODE_STREAM},   /* TLS_RSA_WITH_RC4_128_MD5 */
2060     {0x0005,KEX_RSA,            ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_RSA_WITH_RC4_128_SHA */
2061     {0x0006,KEX_RSA,            ENC_RC2,        DIG_MD5,    MODE_CBC   },   /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
2062     {0x0007,KEX_RSA,            ENC_IDEA,       DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_IDEA_CBC_SHA */
2063     {0x0008,KEX_RSA,            ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
2064     {0x0009,KEX_RSA,            ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_DES_CBC_SHA */
2065     {0x000A,KEX_RSA,            ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_3DES_EDE_CBC_SHA */
2066     {0x000B,KEX_DH_DSS,         ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
2067     {0x000C,KEX_DH_DSS,         ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_DES_CBC_SHA */
2068     {0x000D,KEX_DH_DSS,         ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA */
2069     {0x000E,KEX_DH_RSA,         ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
2070     {0x000F,KEX_DH_RSA,         ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_DES_CBC_SHA */
2071     {0x0010,KEX_DH_RSA,         ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA */
2072     {0x0011,KEX_DHE_DSS,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
2073     {0x0012,KEX_DHE_DSS,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_DES_CBC_SHA */
2074     {0x0013,KEX_DHE_DSS,        ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA */
2075     {0x0014,KEX_DHE_RSA,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
2076     {0x0015,KEX_DHE_RSA,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_DES_CBC_SHA */
2077     {0x0016,KEX_DHE_RSA,        ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA */
2078     {0x0017,KEX_DH_ANON,        ENC_RC4,        DIG_MD5,    MODE_STREAM},   /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
2079     {0x0018,KEX_DH_ANON,        ENC_RC4,        DIG_MD5,    MODE_STREAM},   /* TLS_DH_anon_WITH_RC4_128_MD5 */
2080     {0x0019,KEX_DH_ANON,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
2081     {0x001A,KEX_DH_ANON,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_DES_CBC_SHA */
2082     {0x001B,KEX_DH_ANON,        ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_3DES_EDE_CBC_SHA */
2083     {0x002C,KEX_PSK,            ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_PSK_WITH_NULL_SHA */
2084     {0x002D,KEX_DHE_PSK,        ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_DHE_PSK_WITH_NULL_SHA */
2085     {0x002E,KEX_RSA_PSK,        ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_RSA_PSK_WITH_NULL_SHA */
2086     {0x002F,KEX_RSA,            ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_AES_128_CBC_SHA */
2087     {0x0030,KEX_DH_DSS,         ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_AES_128_CBC_SHA */
2088     {0x0031,KEX_DH_RSA,         ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_AES_128_CBC_SHA */
2089     {0x0032,KEX_DHE_DSS,        ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_AES_128_CBC_SHA */
2090     {0x0033,KEX_DHE_RSA,        ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_AES_128_CBC_SHA */
2091     {0x0034,KEX_DH_ANON,        ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_AES_128_CBC_SHA */
2092     {0x0035,KEX_RSA,            ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_AES_256_CBC_SHA */
2093     {0x0036,KEX_DH_DSS,         ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_AES_256_CBC_SHA */
2094     {0x0037,KEX_DH_RSA,         ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_AES_256_CBC_SHA */
2095     {0x0038,KEX_DHE_DSS,        ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_AES_256_CBC_SHA */
2096     {0x0039,KEX_DHE_RSA,        ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_AES_256_CBC_SHA */
2097     {0x003A,KEX_DH_ANON,        ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_AES_256_CBC_SHA */
2098     {0x003B,KEX_RSA,            ENC_NULL,       DIG_SHA256, MODE_STREAM},   /* TLS_RSA_WITH_NULL_SHA256 */
2099     {0x003C,KEX_RSA,            ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_RSA_WITH_AES_128_CBC_SHA256 */
2100     {0x003D,KEX_RSA,            ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_RSA_WITH_AES_256_CBC_SHA256 */
2101     {0x003E,KEX_DH_DSS,         ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DH_DSS_WITH_AES_128_CBC_SHA256 */
2102     {0x003F,KEX_DH_RSA,         ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DH_RSA_WITH_AES_128_CBC_SHA256 */
2103     {0x0040,KEX_DHE_DSS,        ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 */
2104     {0x0041,KEX_RSA,            ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_CAMELLIA_128_CBC_SHA */
2105     {0x0042,KEX_DH_DSS,         ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA */
2106     {0x0043,KEX_DH_RSA,         ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA */
2107     {0x0044,KEX_DHE_DSS,        ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA */
2108     {0x0045,KEX_DHE_RSA,        ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA */
2109     {0x0046,KEX_DH_ANON,        ENC_CAMELLIA128,DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA */
2110     {0x0060,KEX_RSA,            ENC_RC4,        DIG_MD5,    MODE_STREAM},   /* TLS_RSA_EXPORT1024_WITH_RC4_56_MD5 */
2111     {0x0061,KEX_RSA,            ENC_RC2,        DIG_MD5,    MODE_STREAM},   /* TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 */
2112     {0x0062,KEX_RSA,            ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA */
2113     {0x0063,KEX_DHE_DSS,        ENC_DES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA */
2114     {0x0064,KEX_RSA,            ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_RSA_EXPORT1024_WITH_RC4_56_SHA */
2115     {0x0065,KEX_DHE_DSS,        ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA */
2116     {0x0066,KEX_DHE_DSS,        ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_DHE_DSS_WITH_RC4_128_SHA */
2117     {0x0067,KEX_DHE_RSA,        ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 */
2118     {0x0068,KEX_DH_DSS,         ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_DH_DSS_WITH_AES_256_CBC_SHA256 */
2119     {0x0069,KEX_DH_RSA,         ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_DH_RSA_WITH_AES_256_CBC_SHA256 */
2120     {0x006A,KEX_DHE_DSS,        ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 */
2121     {0x006B,KEX_DHE_RSA,        ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 */
2122     {0x006C,KEX_DH_ANON,        ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DH_anon_WITH_AES_128_CBC_SHA256 */
2123     {0x006D,KEX_DH_ANON,        ENC_AES256,     DIG_SHA256, MODE_CBC   },   /* TLS_DH_anon_WITH_AES_256_CBC_SHA256 */
2124     {0x0084,KEX_RSA,            ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_CAMELLIA_256_CBC_SHA */
2125     {0x0085,KEX_DH_DSS,         ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA */
2126     {0x0086,KEX_DH_RSA,         ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA */
2127     {0x0087,KEX_DHE_DSS,        ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA */
2128     {0x0088,KEX_DHE_RSA,        ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA */
2129     {0x0089,KEX_DH_ANON,        ENC_CAMELLIA256,DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA */
2130     {0x008A,KEX_PSK,            ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_PSK_WITH_RC4_128_SHA */
2131     {0x008B,KEX_PSK,            ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_PSK_WITH_3DES_EDE_CBC_SHA */
2132     {0x008C,KEX_PSK,            ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_PSK_WITH_AES_128_CBC_SHA */
2133     {0x008D,KEX_PSK,            ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_PSK_WITH_AES_256_CBC_SHA */
2134     {0x008E,KEX_DHE_PSK,        ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_DHE_PSK_WITH_RC4_128_SHA */
2135     {0x008F,KEX_DHE_PSK,        ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA */
2136     {0x0090,KEX_DHE_PSK,        ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_DHE_PSK_WITH_AES_128_CBC_SHA */
2137     {0x0091,KEX_DHE_PSK,        ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_DHE_PSK_WITH_AES_256_CBC_SHA */
2138     {0x0092,KEX_RSA_PSK,        ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_RSA_PSK_WITH_RC4_128_SHA */
2139     {0x0093,KEX_RSA_PSK,        ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA */
2140     {0x0094,KEX_RSA_PSK,        ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_RSA_PSK_WITH_AES_128_CBC_SHA */
2141     {0x0095,KEX_RSA_PSK,        ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_RSA_PSK_WITH_AES_256_CBC_SHA */
2142     {0x0096,KEX_RSA,            ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_RSA_WITH_SEED_CBC_SHA */
2143     {0x0097,KEX_DH_DSS,         ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_DSS_WITH_SEED_CBC_SHA */
2144     {0x0098,KEX_DH_RSA,         ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_RSA_WITH_SEED_CBC_SHA */
2145     {0x0099,KEX_DHE_DSS,        ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_DHE_DSS_WITH_SEED_CBC_SHA */
2146     {0x009A,KEX_DHE_RSA,        ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_DHE_RSA_WITH_SEED_CBC_SHA */
2147     {0x009B,KEX_DH_ANON,        ENC_SEED,       DIG_SHA,    MODE_CBC   },   /* TLS_DH_anon_WITH_SEED_CBC_SHA */
2148     {0x009C,KEX_RSA,            ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_RSA_WITH_AES_128_GCM_SHA256 */
2149     {0x009D,KEX_RSA,            ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_RSA_WITH_AES_256_GCM_SHA384 */
2150     {0x009E,KEX_DHE_RSA,        ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 */
2151     {0x009F,KEX_DHE_RSA,        ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 */
2152     {0x00A0,KEX_DH_RSA,         ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DH_RSA_WITH_AES_128_GCM_SHA256 */
2153     {0x00A1,KEX_DH_RSA,         ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DH_RSA_WITH_AES_256_GCM_SHA384 */
2154     {0x00A2,KEX_DHE_DSS,        ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 */
2155     {0x00A3,KEX_DHE_DSS,        ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 */
2156     {0x00A4,KEX_DH_DSS,         ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DH_DSS_WITH_AES_128_GCM_SHA256 */
2157     {0x00A5,KEX_DH_DSS,         ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DH_DSS_WITH_AES_256_GCM_SHA384 */
2158     {0x00A6,KEX_DH_ANON,        ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DH_anon_WITH_AES_128_GCM_SHA256 */
2159     {0x00A7,KEX_DH_ANON,        ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DH_anon_WITH_AES_256_GCM_SHA384 */
2160     {0x00A8,KEX_PSK,            ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_PSK_WITH_AES_128_GCM_SHA256 */
2161     {0x00A9,KEX_PSK,            ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_PSK_WITH_AES_256_GCM_SHA384 */
2162     {0x00AA,KEX_DHE_PSK,        ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 */
2163     {0x00AB,KEX_DHE_PSK,        ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 */
2164     {0x00AC,KEX_RSA_PSK,        ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 */
2165     {0x00AD,KEX_RSA_PSK,        ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 */
2166     {0x00AE,KEX_PSK,            ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_PSK_WITH_AES_128_CBC_SHA256 */
2167     {0x00AF,KEX_PSK,            ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_PSK_WITH_AES_256_CBC_SHA384 */
2168     {0x00B0,KEX_PSK,            ENC_NULL,       DIG_SHA256, MODE_STREAM},   /* TLS_PSK_WITH_NULL_SHA256 */
2169     {0x00B1,KEX_PSK,            ENC_NULL,       DIG_SHA384, MODE_STREAM},   /* TLS_PSK_WITH_NULL_SHA384 */
2170     {0x00B2,KEX_DHE_PSK,        ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 */
2171     {0x00B3,KEX_DHE_PSK,        ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 */
2172     {0x00B4,KEX_DHE_PSK,        ENC_NULL,       DIG_SHA256, MODE_STREAM},   /* TLS_DHE_PSK_WITH_NULL_SHA256 */
2173     {0x00B5,KEX_DHE_PSK,        ENC_NULL,       DIG_SHA384, MODE_STREAM},   /* TLS_DHE_PSK_WITH_NULL_SHA384 */
2174     {0x00B6,KEX_RSA_PSK,        ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 */
2175     {0x00B7,KEX_RSA_PSK,        ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 */
2176     {0x00B8,KEX_RSA_PSK,        ENC_NULL,       DIG_SHA256, MODE_STREAM},   /* TLS_RSA_PSK_WITH_NULL_SHA256 */
2177     {0x00B9,KEX_RSA_PSK,        ENC_NULL,       DIG_SHA384, MODE_STREAM},   /* TLS_RSA_PSK_WITH_NULL_SHA384 */
2178     {0x00BA,KEX_RSA,            ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 */
2179     {0x00BB,KEX_DH_DSS,         ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 */
2180     {0x00BC,KEX_DH_RSA,         ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 */
2181     {0x00BD,KEX_DHE_DSS,        ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 */
2182     {0x00BE,KEX_DHE_RSA,        ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 */
2183     {0x00BF,KEX_DH_ANON,        ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 */
2184     {0x00C0,KEX_RSA,            ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 */
2185     {0x00C1,KEX_DH_DSS,         ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 */
2186     {0x00C2,KEX_DH_RSA,         ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 */
2187     {0x00C3,KEX_DHE_DSS,        ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 */
2188     {0x00C4,KEX_DHE_RSA,        ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 */
2189     {0x00C5,KEX_DH_ANON,        ENC_CAMELLIA256,DIG_SHA256, MODE_CBC   },   /* TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 */
2190
2191     /* NOTE: TLS 1.3 cipher suites are incompatible with TLS 1.2. */
2192     {0x1301,KEX_TLS13,          ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_AES_128_GCM_SHA256 */
2193     {0x1302,KEX_TLS13,          ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_AES_256_GCM_SHA384 */
2194     /* TODO TLS_CHACHA20_POLY1305_SHA256 */
2195     {0x1304,KEX_TLS13,          ENC_AES,        DIG_SHA256, MODE_CCM   },   /* TLS_AES_128_CCM_SHA256 */
2196     {0x1305,KEX_TLS13,          ENC_AES,        DIG_SHA256, MODE_CCM_8 },   /* TLS_AES_128_CCM_8_SHA256 */
2197
2198     {0xC001,KEX_ECDH_ECDSA,     ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_ECDSA_WITH_NULL_SHA */
2199     {0xC002,KEX_ECDH_ECDSA,     ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_ECDSA_WITH_RC4_128_SHA */
2200     {0xC003,KEX_ECDH_ECDSA,     ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA */
2201     {0xC004,KEX_ECDH_ECDSA,     ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA */
2202     {0xC005,KEX_ECDH_ECDSA,     ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA */
2203     {0xC006,KEX_ECDHE_ECDSA,    ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_ECDSA_WITH_NULL_SHA */
2204     {0xC007,KEX_ECDHE_ECDSA,    ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA */
2205     {0xC008,KEX_ECDHE_ECDSA,    ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA */
2206     {0xC009,KEX_ECDHE_ECDSA,    ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA */
2207     {0xC00A,KEX_ECDHE_ECDSA,    ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */
2208     {0xC00B,KEX_ECDH_RSA,       ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_RSA_WITH_NULL_SHA */
2209     {0xC00C,KEX_ECDH_RSA,       ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_RSA_WITH_RC4_128_SHA */
2210     {0xC00D,KEX_ECDH_RSA,       ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA */
2211     {0xC00E,KEX_ECDH_RSA,       ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA */
2212     {0xC00F,KEX_ECDH_RSA,       ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_RSA_WITH_AES_256_CBC_SHA */
2213     {0xC010,KEX_ECDHE_RSA,      ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_RSA_WITH_NULL_SHA */
2214     {0xC011,KEX_ECDHE_RSA,      ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_RSA_WITH_RC4_128_SHA */
2215     {0xC012,KEX_ECDHE_RSA,      ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA */
2216     {0xC013,KEX_ECDHE_RSA,      ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA */
2217     {0xC014,KEX_ECDHE_RSA,      ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA */
2218     {0xC015,KEX_ECDH_ANON,      ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_anon_WITH_NULL_SHA */
2219     {0xC016,KEX_ECDH_ANON,      ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDH_anon_WITH_RC4_128_SHA */
2220     {0xC017,KEX_ECDH_ANON,      ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA */
2221     {0xC018,KEX_ECDH_ANON,      ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_anon_WITH_AES_128_CBC_SHA */
2222     {0xC019,KEX_ECDH_ANON,      ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDH_anon_WITH_AES_256_CBC_SHA */
2223     {0xC023,KEX_ECDHE_ECDSA,    ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 */
2224     {0xC024,KEX_ECDHE_ECDSA,    ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 */
2225     {0xC025,KEX_ECDH_ECDSA,     ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 */
2226     {0xC026,KEX_ECDH_ECDSA,     ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 */
2227     {0xC027,KEX_ECDHE_RSA,      ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 */
2228     {0xC028,KEX_ECDHE_RSA,      ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 */
2229     {0xC029,KEX_ECDH_RSA,       ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 */
2230     {0xC02A,KEX_ECDH_RSA,       ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 */
2231     {0xC02B,KEX_ECDHE_ECDSA,    ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 */
2232     {0xC02C,KEX_ECDHE_ECDSA,    ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 */
2233     {0xC02D,KEX_ECDH_ECDSA,     ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 */
2234     {0xC02E,KEX_ECDH_ECDSA,     ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 */
2235     {0xC02F,KEX_ECDHE_RSA,      ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 */
2236     {0xC030,KEX_ECDHE_RSA,      ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 */
2237     {0xC031,KEX_ECDH_RSA,       ENC_AES,        DIG_SHA256, MODE_GCM   },   /* TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 */
2238     {0xC032,KEX_ECDH_RSA,       ENC_AES256,     DIG_SHA384, MODE_GCM   },   /* TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 */
2239     {0xC033,KEX_ECDHE_PSK,      ENC_RC4,        DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_PSK_WITH_RC4_128_SHA */
2240     {0xC034,KEX_ECDHE_PSK,      ENC_3DES,       DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA */
2241     {0xC035,KEX_ECDHE_PSK,      ENC_AES,        DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA */
2242     {0xC036,KEX_ECDHE_PSK,      ENC_AES256,     DIG_SHA,    MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA */
2243     {0xC037,KEX_ECDHE_PSK,      ENC_AES,        DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 */
2244     {0xC038,KEX_ECDHE_PSK,      ENC_AES256,     DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 */
2245     {0xC039,KEX_ECDHE_PSK,      ENC_NULL,       DIG_SHA,    MODE_STREAM},   /* TLS_ECDHE_PSK_WITH_NULL_SHA */
2246     {0xC03A,KEX_ECDHE_PSK,      ENC_NULL,       DIG_SHA256, MODE_STREAM},   /* TLS_ECDHE_PSK_WITH_NULL_SHA256 */
2247     {0xC03B,KEX_ECDHE_PSK,      ENC_NULL,       DIG_SHA384, MODE_STREAM},   /* TLS_ECDHE_PSK_WITH_NULL_SHA384 */
2248     {0xC072,KEX_ECDHE_ECDSA,    ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 */
2249     {0xC073,KEX_ECDHE_ECDSA,    ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 */
2250     {0xC074,KEX_ECDH_ECDSA,     ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 */
2251     {0xC075,KEX_ECDH_ECDSA,     ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 */
2252     {0xC076,KEX_ECDHE_RSA,      ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 */
2253     {0xC077,KEX_ECDHE_RSA,      ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 */
2254     {0xC078,KEX_ECDH_RSA,       ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 */
2255     {0xC079,KEX_ECDH_RSA,       ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 */
2256     {0xC07A,KEX_RSA,            ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 */
2257     {0xC07B,KEX_RSA,            ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 */
2258     {0xC07C,KEX_DHE_RSA,        ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 */
2259     {0xC07D,KEX_DHE_RSA,        ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 */
2260     {0xC07E,KEX_DH_RSA,         ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 */
2261     {0xC07F,KEX_DH_RSA,         ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 */
2262     {0xC080,KEX_DHE_DSS,        ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 */
2263     {0xC081,KEX_DHE_DSS,        ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 */
2264     {0xC082,KEX_DH_DSS,         ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 */
2265     {0xC083,KEX_DH_DSS,         ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 */
2266     {0xC084,KEX_DH_ANON,        ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 */
2267     {0xC085,KEX_DH_ANON,        ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 */
2268     {0xC086,KEX_ECDHE_ECDSA,    ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 */
2269     {0xC087,KEX_ECDHE_ECDSA,    ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 */
2270     {0xC088,KEX_ECDH_ECDSA,     ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 */
2271     {0xC089,KEX_ECDH_ECDSA,     ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 */
2272     {0xC08A,KEX_ECDHE_RSA,      ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 */
2273     {0xC08B,KEX_ECDHE_RSA,      ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 */
2274     {0xC08C,KEX_ECDH_RSA,       ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 */
2275     {0xC08D,KEX_ECDH_RSA,       ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 */
2276     {0xC08E,KEX_PSK,            ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 */
2277     {0xC08F,KEX_PSK,            ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 */
2278     {0xC090,KEX_DHE_PSK,        ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 */
2279     {0xC091,KEX_DHE_PSK,        ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 */
2280     {0xC092,KEX_RSA_PSK,        ENC_CAMELLIA128,DIG_SHA256, MODE_GCM   },   /* TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 */
2281     {0xC093,KEX_RSA_PSK,        ENC_CAMELLIA256,DIG_SHA384, MODE_GCM   },   /* TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 */
2282     {0xC094,KEX_PSK,            ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 */
2283     {0xC095,KEX_PSK,            ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 */
2284     {0xC096,KEX_DHE_PSK,        ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 */
2285     {0xC097,KEX_DHE_PSK,        ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 */
2286     {0xC098,KEX_RSA_PSK,        ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 */
2287     {0xC099,KEX_RSA_PSK,        ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 */
2288     {0xC09A,KEX_ECDHE_PSK,      ENC_CAMELLIA128,DIG_SHA256, MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 */
2289     {0xC09B,KEX_ECDHE_PSK,      ENC_CAMELLIA256,DIG_SHA384, MODE_CBC   },   /* TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 */
2290     {0xC09C,KEX_RSA,            ENC_AES,        DIG_NA,     MODE_CCM   },   /* TLS_RSA_WITH_AES_128_CCM */
2291     {0xC09D,KEX_RSA,            ENC_AES256,     DIG_NA,     MODE_CCM   },   /* TLS_RSA_WITH_AES_256_CCM */
2292     {0xC09E,KEX_DHE_RSA,        ENC_AES,        DIG_NA,     MODE_CCM   },   /* TLS_DHE_RSA_WITH_AES_128_CCM */
2293     {0xC09F,KEX_DHE_RSA,        ENC_AES256,     DIG_NA,     MODE_CCM   },   /* TLS_DHE_RSA_WITH_AES_256_CCM */
2294     {0xC0A0,KEX_RSA,            ENC_AES,        DIG_NA,     MODE_CCM_8 },   /* TLS_RSA_WITH_AES_128_CCM_8 */
2295     {0xC0A1,KEX_RSA,            ENC_AES256,     DIG_NA,     MODE_CCM_8 },   /* TLS_RSA_WITH_AES_256_CCM_8 */
2296     {0xC0A2,KEX_DHE_RSA,        ENC_AES,        DIG_NA,     MODE_CCM_8 },   /* TLS_DHE_RSA_WITH_AES_128_CCM_8 */
2297     {0xC0A3,KEX_DHE_RSA,        ENC_AES256,     DIG_NA,     MODE_CCM_8 },   /* TLS_DHE_RSA_WITH_AES_256_CCM_8 */
2298     {0xC0A4,KEX_PSK,            ENC_AES,        DIG_NA,     MODE_CCM   },   /* TLS_PSK_WITH_AES_128_CCM */
2299     {0xC0A5,KEX_PSK,            ENC_AES256,     DIG_NA,     MODE_CCM   },   /* TLS_PSK_WITH_AES_256_CCM */
2300     {0xC0A6,KEX_DHE_PSK,        ENC_AES,        DIG_NA,     MODE_CCM   },   /* TLS_DHE_PSK_WITH_AES_128_CCM */
2301     {0xC0A7,KEX_DHE_PSK,        ENC_AES256,     DIG_NA,     MODE_CCM   },   /* TLS_DHE_PSK_WITH_AES_256_CCM */
2302     {0xC0A8,KEX_PSK,            ENC_AES,        DIG_NA,     MODE_CCM_8 },   /* TLS_PSK_WITH_AES_128_CCM_8 */
2303     {0xC0A9,KEX_PSK,            ENC_AES256,     DIG_NA,     MODE_CCM_8 },   /* TLS_PSK_WITH_AES_256_CCM_8 */
2304     {0xC0AA,KEX_DHE_PSK,        ENC_AES,        DIG_NA,     MODE_CCM_8 },   /* TLS_PSK_DHE_WITH_AES_128_CCM_8 */
2305     {0xC0AB,KEX_DHE_PSK,        ENC_AES256,     DIG_NA,     MODE_CCM_8 },   /* TLS_PSK_DHE_WITH_AES_256_CCM_8 */
2306     {0xC0AC,KEX_ECDHE_ECDSA,    ENC_AES,        DIG_NA,     MODE_CCM   },   /* TLS_ECDHE_ECDSA_WITH_AES_128_CCM */
2307     {0xC0AD,KEX_ECDHE_ECDSA,    ENC_AES256,     DIG_NA,     MODE_CCM   },   /* TLS_ECDHE_ECDSA_WITH_AES_256_CCM */
2308     {0xC0AE,KEX_ECDHE_ECDSA,    ENC_AES,        DIG_NA,     MODE_CCM_8 },   /* TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 */
2309     {0xC0AF,KEX_ECDHE_ECDSA,    ENC_AES256,     DIG_NA,     MODE_CCM_8 },   /* TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 */
2310     {-1,    0,                  0,              0,          MODE_STREAM}
2311 };
2312
2313 #define MAX_BLOCK_SIZE 16
2314 #define MAX_KEY_SIZE 32
2315
2316 const SslCipherSuite *
2317 ssl_find_cipher(int num)
2318 {
2319     const SslCipherSuite *c;
2320     for(c=cipher_suites;c->number!=-1;c++){
2321         if(c->number==num){
2322             return c;
2323         }
2324     }
2325
2326     return NULL;
2327 }
2328
2329 guint
2330 ssl_get_cipher_blocksize(const SslCipherSuite *cipher_suite)
2331 {
2332     gint cipher_algo;
2333     if (cipher_suite->mode != MODE_CBC) return 0;
2334     cipher_algo = ssl_get_cipher_by_name(ciphers[cipher_suite->enc - 0x30]);
2335     return (guint)gcry_cipher_get_algo_blklen(cipher_algo);
2336 }
2337
2338 static guint
2339 ssl_get_cipher_export_keymat_size(int cipher_suite_num)
2340 {
2341     switch (cipher_suite_num) {
2342     /* See RFC 6101 (SSL 3.0), Table 2, column Key Material. */
2343     case 0x0003:    /* TLS_RSA_EXPORT_WITH_RC4_40_MD5 */
2344     case 0x0006:    /* TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 */
2345     case 0x0008:    /* TLS_RSA_EXPORT_WITH_DES40_CBC_SHA */
2346     case 0x000B:    /* TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA */
2347     case 0x000E:    /* TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA */
2348     case 0x0011:    /* TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA */
2349     case 0x0014:    /* TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA */
2350     case 0x0017:    /* TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 */
2351     case 0x0019:    /* TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA */
2352         return 5;
2353
2354     /* not defined in below draft, but "implemented by several vendors",
2355      * https://www.ietf.org/mail-archive/web/tls/current/msg00036.html */
2356     case 0x0060:    /* TLS_RSA_EXPORT1024_WITH_RC4_56_MD5 */
2357     case 0x0061:    /* TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5 */
2358         return 7;
2359
2360     /* Note: the draft states that DES_CBC needs 8 bytes, but Wireshark always
2361      * used 7. Until a pcap proves 8, let's use the old value. Link:
2362      * https://tools.ietf.org/html/draft-ietf-tls-56-bit-ciphersuites-01 */
2363     case 0x0062:    /* TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA */
2364     case 0x0063:    /* TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA */
2365     case 0x0064:    /* TLS_RSA_EXPORT1024_WITH_RC4_56_SHA */
2366     case 0x0065:    /* TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA */
2367         return 7;
2368
2369     default:
2370         return 0;
2371     }
2372 }
2373 #else /* ! HAVE_LIBGCRYPT */
2374 const SslCipherSuite *
2375 ssl_find_cipher(int num)
2376 {
2377     ssl_debug_printf("ssl_find_cipher: dummy without gnutls. num %d\n",
2378         num);
2379     return NULL;
2380 }
2381
2382 guint
2383 ssl_get_cipher_blocksize(const SslCipherSuite *cipher_suite _U_)
2384 {
2385     return 0;
2386 }
2387 #endif /* ! HAVE_LIBGCRYPT */
2388
2389 /* Digests, Ciphers and Cipher Suites registry }}} */
2390
2391
2392 #ifdef HAVE_LIBGCRYPT
2393
2394 /* HMAC and the Pseudorandom function {{{ */
2395 static void
2396 tls_hash(StringInfo *secret, StringInfo *seed, gint md,
2397          StringInfo *out, guint out_len)
2398 {
2399     /* RFC 2246 5. HMAC and the pseudorandom function
2400      * '+' denotes concatenation.
2401      * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
2402      *                        HMAC_hash(secret, A(2) + seed) + ...
2403      * A(0) = seed
2404      * A(i) = HMAC_hash(secret, A(i - 1))
2405      */
2406     guint8   *ptr;
2407     guint     left, tocpy;
2408     guint8   *A;
2409     guint8    _A[DIGEST_MAX_SIZE], tmp[DIGEST_MAX_SIZE];
2410     guint     A_l, tmp_l;
2411     SSL_HMAC  hm;
2412
2413     ptr  = out->data;
2414     left = out_len;
2415
2416     ssl_print_string("tls_hash: hash secret", secret);
2417     ssl_print_string("tls_hash: hash seed", seed);
2418     /* A(0) = seed */
2419     A = seed->data;
2420     A_l = seed->data_len;
2421
2422     while (left) {
2423         /* A(i) = HMAC_hash(secret, A(i-1)) */
2424         ssl_hmac_init(&hm, secret->data, secret->data_len, md);
2425         ssl_hmac_update(&hm, A, A_l);
2426         A_l = sizeof(_A); /* upper bound len for hash output */
2427         ssl_hmac_final(&hm, _A, &A_l);
2428         ssl_hmac_cleanup(&hm);
2429         A = _A;
2430
2431         /* HMAC_hash(secret, A(i) + seed) */
2432         ssl_hmac_init(&hm, secret->data, secret->data_len, md);
2433         ssl_hmac_update(&hm, A, A_l);
2434         ssl_hmac_update(&hm, seed->data, seed->data_len);
2435         tmp_l = sizeof(tmp); /* upper bound len for hash output */
2436         ssl_hmac_final(&hm, tmp, &tmp_l);
2437         ssl_hmac_cleanup(&hm);
2438
2439         /* ssl_hmac_final puts the actual digest output size in tmp_l */
2440         tocpy = MIN(left, tmp_l);
2441         memcpy(ptr, tmp, tocpy);
2442         ptr += tocpy;
2443         left -= tocpy;
2444     }
2445     out->data_len = out_len;
2446
2447     ssl_print_string("hash out", out);
2448 }
2449
2450 static gboolean
2451 tls_prf(StringInfo* secret, const gchar *usage,
2452         StringInfo* rnd1, StringInfo* rnd2, StringInfo* out, guint out_len)
2453 {
2454     StringInfo  seed, sha_out, md5_out;
2455     guint8     *ptr;
2456     StringInfo  s1, s2;
2457     guint       i,s_l;
2458     size_t      usage_len, rnd2_len;
2459     gboolean    success = FALSE;
2460     usage_len = strlen(usage);
2461     rnd2_len = rnd2 ? rnd2->data_len : 0;
2462
2463     /* initalize buffer for sha, md5 random seed*/
2464     if (ssl_data_alloc(&sha_out, MAX(out_len, 20)) < 0) {
2465         ssl_debug_printf("tls_prf: can't allocate sha out\n");
2466         return FALSE;
2467     }
2468     if (ssl_data_alloc(&md5_out, MAX(out_len, 16)) < 0) {
2469         ssl_debug_printf("tls_prf: can't allocate md5 out\n");
2470         goto free_sha;
2471     }
2472     if (ssl_data_alloc(&seed, usage_len+rnd1->data_len+rnd2_len) < 0) {
2473         ssl_debug_printf("tls_prf: can't allocate rnd %d\n",
2474                          (int) (usage_len+rnd1->data_len+rnd2_len));
2475         goto free_md5;
2476     }
2477
2478     ptr=seed.data;
2479     memcpy(ptr,usage,usage_len);
2480     ptr+=usage_len;
2481     memcpy(ptr,rnd1->data,rnd1->data_len);
2482     if (rnd2_len > 0) {
2483         ptr+=rnd1->data_len;
2484         memcpy(ptr,rnd2->data,rnd2->data_len);
2485         /*ptr+=rnd2->data_len;*/
2486     }
2487
2488     /* initalize buffer for client/server seeds*/
2489     s_l=secret->data_len/2 + secret->data_len%2;
2490     if (ssl_data_alloc(&s1, s_l) < 0) {
2491         ssl_debug_printf("tls_prf: can't allocate secret %d\n", s_l);
2492         goto free_seed;
2493     }
2494     if (ssl_data_alloc(&s2, s_l) < 0) {
2495         ssl_debug_printf("tls_prf: can't allocate secret(2) %d\n", s_l);
2496         goto free_s1;
2497     }
2498
2499     memcpy(s1.data,secret->data,s_l);
2500     memcpy(s2.data,secret->data + (secret->data_len - s_l),s_l);
2501
2502     ssl_debug_printf("tls_prf: tls_hash(md5 secret_len %d seed_len %d )\n", s1.data_len, seed.data_len);
2503     tls_hash(&s1, &seed, ssl_get_digest_by_name("MD5"), &md5_out, out_len);
2504     ssl_debug_printf("tls_prf: tls_hash(sha)\n");
2505     tls_hash(&s2, &seed, ssl_get_digest_by_name("SHA1"), &sha_out, out_len);
2506
2507     for (i = 0; i < out_len; i++)
2508         out->data[i] = md5_out.data[i] ^ sha_out.data[i];
2509     /* success, now store the new meaningful data length */
2510     out->data_len = out_len;
2511     success = TRUE;
2512
2513     ssl_print_string("PRF out",out);
2514     g_free(s2.data);
2515 free_s1:
2516     g_free(s1.data);
2517 free_seed:
2518     g_free(seed.data);
2519 free_md5:
2520     g_free(md5_out.data);
2521 free_sha:
2522     g_free(sha_out.data);
2523     return success;
2524 }
2525
2526 static gboolean
2527 tls12_prf(gint md, StringInfo* secret, const gchar* usage,
2528           StringInfo* rnd1, StringInfo* rnd2, StringInfo* out, guint out_len)
2529 {
2530     StringInfo label_seed;
2531     size_t     usage_len, rnd2_len;
2532     rnd2_len = rnd2 ? rnd2->data_len : 0;
2533
2534     usage_len = strlen(usage);
2535     if (ssl_data_alloc(&label_seed, usage_len+rnd1->data_len+rnd2_len) < 0) {
2536         ssl_debug_printf("tls12_prf: can't allocate label_seed\n");
2537         return FALSE;
2538     }
2539     memcpy(label_seed.data, usage, usage_len);
2540     memcpy(label_seed.data+usage_len, rnd1->data, rnd1->data_len);
2541     if (rnd2_len > 0)
2542         memcpy(label_seed.data+usage_len+rnd1->data_len, rnd2->data, rnd2->data_len);
2543
2544     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);
2545     tls_hash(secret, &label_seed, md, out, out_len);
2546     g_free(label_seed.data);
2547     ssl_print_string("PRF out", out);
2548     return TRUE;
2549 }
2550
2551 static void
2552 ssl3_generate_export_iv(StringInfo *r1, StringInfo *r2,
2553                         StringInfo *out, guint out_len)
2554 {
2555     SSL_MD5_CTX md5;
2556     guint8      tmp[16];
2557
2558     ssl_md5_init(&md5);
2559     ssl_md5_update(&md5,r1->data,r1->data_len);
2560     ssl_md5_update(&md5,r2->data,r2->data_len);
2561     ssl_md5_final(tmp,&md5);
2562     ssl_md5_cleanup(&md5);
2563
2564     DISSECTOR_ASSERT(out_len <= sizeof(tmp));
2565     ssl_data_set(out, tmp, out_len);
2566     ssl_print_string("export iv", out);
2567 }
2568
2569 static gboolean
2570 ssl3_prf(StringInfo* secret, const gchar* usage,
2571          StringInfo* rnd1, StringInfo* rnd2, StringInfo* out, guint out_len)
2572 {
2573     SSL_MD5_CTX  md5;
2574     SSL_SHA_CTX  sha;
2575     guint        off;
2576     gint         i = 0,j;
2577     guint8       buf[20];
2578
2579     for (off = 0; off < out_len; off += 16) {
2580         guchar outbuf[16];
2581         i++;
2582
2583         ssl_debug_printf("ssl3_prf: sha1_hash(%d)\n",i);
2584         /* A, BB, CCC,  ... */
2585         for(j=0;j<i;j++){
2586             buf[j]=64+i;
2587         }
2588
2589         ssl_sha_init(&sha);
2590         ssl_sha_update(&sha,buf,i);
2591         ssl_sha_update(&sha,secret->data,secret->data_len);
2592
2593         if(!strcmp(usage,"client write key") || !strcmp(usage,"server write key")){
2594             if (rnd2)
2595                 ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
2596             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
2597         }
2598         else{
2599             ssl_sha_update(&sha,rnd1->data,rnd1->data_len);
2600             if (rnd2)
2601                 ssl_sha_update(&sha,rnd2->data,rnd2->data_len);
2602         }
2603
2604         ssl_sha_final(buf,&sha);
2605         ssl_sha_cleanup(&sha);
2606
2607         ssl_debug_printf("ssl3_prf: md5_hash(%d) datalen %d\n",i,
2608             secret->data_len);
2609         ssl_md5_init(&md5);
2610         ssl_md5_update(&md5,secret->data,secret->data_len);
2611         ssl_md5_update(&md5,buf,20);
2612         ssl_md5_final(outbuf,&md5);
2613         ssl_md5_cleanup(&md5);
2614
2615         memcpy(out->data + off, outbuf, MIN(out_len - off, 16));
2616     }
2617     out->data_len = out_len;
2618
2619     return TRUE;
2620 }
2621
2622 /* out_len is the wanted output length for the pseudorandom function.
2623  * Ensure that ssl->cipher_suite is set. */
2624 static gboolean
2625 prf(SslDecryptSession *ssl, StringInfo *secret, const gchar *usage,
2626     StringInfo *rnd1, StringInfo *rnd2, StringInfo *out, guint out_len)
2627 {
2628     switch (ssl->session.version) {
2629     case SSLV3_VERSION:
2630         return ssl3_prf(secret, usage, rnd1, rnd2, out, out_len);
2631
2632     case TLSV1_VERSION:
2633     case TLSV1DOT1_VERSION:
2634     case DTLSV1DOT0_VERSION:
2635     case DTLSV1DOT0_OPENSSL_VERSION:
2636         return tls_prf(secret, usage, rnd1, rnd2, out, out_len);
2637
2638     default: /* TLSv1.2 */
2639         switch (ssl->cipher_suite->dig) {
2640         case DIG_SHA384:
2641             return tls12_prf(GCRY_MD_SHA384, secret, usage, rnd1, rnd2,
2642                              out, out_len);
2643         default:
2644             return tls12_prf(GCRY_MD_SHA256, secret, usage, rnd1, rnd2,
2645                              out, out_len);
2646         }
2647     }
2648 }
2649
2650 static gint tls_handshake_hash(SslDecryptSession* ssl, StringInfo* out)
2651 {
2652     SSL_MD5_CTX  md5;
2653     SSL_SHA_CTX  sha;
2654
2655     if (ssl_data_alloc(out, 36) < 0)
2656         return -1;
2657
2658     ssl_md5_init(&md5);
2659     ssl_md5_update(&md5,ssl->handshake_data.data,ssl->handshake_data.data_len);
2660     ssl_md5_final(out->data,&md5);
2661     ssl_md5_cleanup(&md5);
2662
2663     ssl_sha_init(&sha);
2664     ssl_sha_update(&sha,ssl->handshake_data.data,ssl->handshake_data.data_len);
2665     ssl_sha_final(out->data+16,&sha);
2666     ssl_sha_cleanup(&sha);
2667     return 0;
2668 }
2669
2670 static gint tls12_handshake_hash(SslDecryptSession* ssl, gint md, StringInfo* out)
2671 {
2672     SSL_MD  mc;
2673     guint8 tmp[48];
2674     guint  len;
2675
2676     ssl_md_init(&mc, md);
2677     ssl_md_update(&mc,ssl->handshake_data.data,ssl->handshake_data.data_len);
2678     ssl_md_final(&mc, tmp, &len);
2679     ssl_md_cleanup(&mc);
2680
2681     if (ssl_data_alloc(out, len) < 0)
2682         return -1;
2683     memcpy(out->data, tmp, len);
2684     return 0;
2685 }
2686
2687 static gboolean
2688 tls13_hkdf_expand_label(int md, const StringInfo *secret, const char *label, const char *hash_value,
2689                         guint16 out_len, guchar **out)
2690 {
2691     /* draft-ietf-tls-tls13-18:
2692      * HKDF-Expand-Label(Secret, Label, HashValue, Length) =
2693      *      HKDF-Expand(Secret, HkdfLabel, Length)
2694      * struct {
2695      *     uint16 length = Length;
2696      *     opaque label<9..255> = "TLS 1.3, " + Label;
2697      *     opaque hash_value<0..255> = HashValue;
2698      * } HkdfLabel;
2699      *
2700      * RFC 5869 HMAC-based Extract-and-Expand Key Derivation Function (HKDF):
2701      * HKDF-Expand(PRK, info, L) -> OKM
2702      */
2703     guchar  lastoutput[DIGEST_MAX_SIZE];
2704     gcry_md_hd_t h;
2705     gcry_error_t err;
2706     const guint label_length = (guint) strlen(label);
2707     const guint hash_value_length = (guint) strlen(hash_value);
2708     const guint hash_len = gcry_md_get_algo_dlen(md);
2709
2710     /* Some sanity checks */
2711     DISSECTOR_ASSERT(out_len > 0 && out_len <= 255 * hash_len);
2712     DISSECTOR_ASSERT(label_length <= 255 - 9);
2713     DISSECTOR_ASSERT(hash_value_length <= 255);
2714     DISSECTOR_ASSERT(hash_len > 0 && hash_len <= DIGEST_MAX_SIZE);
2715
2716     err = gcry_md_open(&h, md, GCRY_MD_FLAG_HMAC);
2717     if (err) {
2718         ssl_debug_printf("%s failed to invoke hash func %d: %s\n", G_STRFUNC, md, gcry_strerror(err));
2719         return FALSE;
2720     }
2721
2722     *out = (guchar *)wmem_alloc(NULL, out_len);
2723
2724     for (guint offset = 0; offset < out_len; offset += hash_len) {
2725         gcry_md_reset(h);
2726         gcry_md_setkey(h, secret->data, secret->data_len);  /* Set PRK */
2727
2728         if (offset > 0) {
2729             gcry_md_write(h, lastoutput, hash_len);         /* T(1..N) */
2730         }
2731
2732         /* info = HkdfLabel { length, label, hash_value } */
2733         gcry_md_putc(h, out_len >> 8);                      /* length */
2734         gcry_md_putc(h, (guint8) out_len);
2735         gcry_md_putc(h, 9 + label_length);                  /* label */
2736         gcry_md_write(h, "TLS 1.3, ", 9);
2737         gcry_md_write(h, label, label_length);
2738         gcry_md_putc(h, hash_value_length);                 /* hash_value */
2739         gcry_md_write(h, hash_value, hash_value_length);
2740
2741         gcry_md_putc(h, (guint8) (offset / hash_len + 1));  /* constant 0x01..N */
2742
2743         memcpy(lastoutput, gcry_md_read(h, md), hash_len);
2744         memcpy(*out + offset, lastoutput, MIN(hash_len, out_len - offset));
2745     }
2746
2747     gcry_md_close(h);
2748     return TRUE;
2749 }
2750 /* HMAC and the Pseudorandom function }}} */
2751
2752 #else /* ! HAVE_LIBGCRYPT */
2753 /* Stub code when decryption support is not available. {{{ */
2754 gboolean
2755 ssl_generate_pre_master_secret(SslDecryptSession *ssl_session _U_,
2756         guint32 length _U_, tvbuff_t *tvb _U_, guint32 offset _U_,
2757         const gchar *ssl_psk _U_, const ssl_master_key_map_t *mk_map _U_)
2758 {
2759     ssl_debug_printf("%s: impossible without gnutls.\n", G_STRFUNC);
2760     return FALSE;
2761 }
2762 int
2763 ssl_generate_keyring_material(SslDecryptSession*ssl)
2764 {
2765     ssl_debug_printf("ssl_generate_keyring_material: impossible without gnutls. ssl %p\n",
2766         ssl);
2767     /* We cannot determine whether the cipher suite is valid. Fail such that
2768      * ssl_set_master_secret bails out. */
2769     return -1;
2770 }
2771 void
2772 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
2773 {
2774     ssl_debug_printf("ssl_change_cipher %s: makes no sense without gnutls. ssl %p\n",
2775         (server)?"SERVER":"CLIENT", ssl_session);
2776 }
2777
2778 int
2779 ssl_decrypt_record(SslDecryptSession *ssl, SslDecoder *decoder, guint8 ct, guint16 record_version,
2780         const guchar *in, guint16 inl, StringInfo *comp_str _U_, StringInfo *out_str, guint *outl)
2781 {
2782     ssl_debug_printf("ssl_decrypt_record: impossible without gnutls. ssl %p"
2783         "decoder %p ct %d version %d in %p inl %d out %p outl %p\n", ssl, decoder, ct,
2784         record_version, in, inl, out_str, outl);
2785     return 0;
2786 }
2787 /* }}} */
2788 #endif /* ! HAVE_LIBGCRYPT */
2789
2790 #ifdef HAVE_LIBGCRYPT
2791 /* Record Decompression (after decryption) {{{ */
2792 #ifdef HAVE_ZLIB
2793 /* memory allocation functions for zlib initialization */
2794 static void* ssl_zalloc(void* opaque _U_, unsigned int no, unsigned int size)
2795 {
2796     return g_malloc0(no*size);
2797 }
2798 static void ssl_zfree(void* opaque _U_, void* addr)
2799 {
2800     g_free(addr);
2801 }
2802 #endif
2803
2804 static SslDecompress*
2805 ssl_create_decompressor(gint compression)
2806 {
2807     SslDecompress *decomp;
2808 #ifdef HAVE_ZLIB
2809     int err;
2810 #endif
2811
2812     if (compression == 0) return NULL;
2813     ssl_debug_printf("ssl_create_decompressor: compression method %d\n", compression);
2814     decomp = (SslDecompress *)wmem_alloc(wmem_file_scope(), sizeof(SslDecompress));
2815     decomp->compression = compression;
2816     switch (decomp->compression) {
2817 #ifdef HAVE_ZLIB
2818         case 1:  /* DEFLATE */
2819             decomp->istream.zalloc = ssl_zalloc;
2820             decomp->istream.zfree = ssl_zfree;
2821             decomp->istream.opaque = Z_NULL;
2822             decomp->istream.next_in = Z_NULL;
2823             decomp->istream.next_out = Z_NULL;
2824             decomp->istream.avail_in = 0;
2825             decomp->istream.avail_out = 0;
2826             err = inflateInit(&decomp->istream);
2827             if (err != Z_OK) {
2828                 ssl_debug_printf("ssl_create_decompressor: inflateInit_() failed - %d\n", err);
2829                 return NULL;
2830             }
2831             break;
2832 #endif
2833         default:
2834             ssl_debug_printf("ssl_create_decompressor: unsupported compression method %d\n", decomp->compression);
2835             return NULL;
2836     }
2837     return decomp;
2838 }
2839
2840 #ifdef HAVE_ZLIB
2841 static int
2842 ssl_decompress_record(SslDecompress* decomp, const guchar* in, guint inl, StringInfo* out_str, guint* outl)
2843 {
2844     gint err;
2845
2846     switch (decomp->compression) {
2847         case 1:  /* DEFLATE */
2848             err = Z_OK;
2849             if (out_str->data_len < 16384) {  /* maximal plain length */
2850                 ssl_data_realloc(out_str, 16384);
2851             }
2852 #ifdef z_const
2853             decomp->istream.next_in = in;
2854 #else
2855 DIAG_OFF(cast-qual)
2856             decomp->istream.next_in = (Bytef *)in;
2857 DIAG_ON(cast-qual)
2858 #endif
2859             decomp->istream.avail_in = inl;
2860             decomp->istream.next_out = out_str->data;
2861             decomp->istream.avail_out = out_str->data_len;
2862             if (inl > 0)
2863                 err = inflate(&decomp->istream, Z_SYNC_FLUSH);
2864             if (err != Z_OK) {
2865                 ssl_debug_printf("ssl_decompress_record: inflate() failed - %d\n", err);
2866                 return -1;
2867             }
2868             *outl = out_str->data_len - decomp->istream.avail_out;
2869             break;
2870         default:
2871             ssl_debug_printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
2872             return -1;
2873     }
2874     return 0;
2875 }
2876 #else
2877 int
2878 ssl_decompress_record(SslDecompress* decomp _U_, const guchar* in _U_, guint inl _U_, StringInfo* out_str _U_, guint* outl _U_)
2879 {
2880     ssl_debug_printf("ssl_decompress_record: unsupported compression method %d\n", decomp->compression);
2881     return -1;
2882 }
2883 #endif
2884 /* Record Decompression (after decryption) }}} */
2885 #endif /* HAVE_LIBGCRYPT */
2886
2887 #ifdef HAVE_LIBGCRYPT
2888 /* Create a new structure to store decrypted chunks. {{{ */
2889 static SslFlow*
2890 ssl_create_flow(void)
2891 {
2892   SslFlow *flow;
2893
2894   flow = (SslFlow *)wmem_alloc(wmem_file_scope(), sizeof(SslFlow));
2895   flow->byte_seq = 0;
2896   flow->flags = 0;
2897   flow->multisegment_pdus = wmem_tree_new(wmem_file_scope());
2898   return flow;
2899 }
2900 /* }}} */
2901
2902 /* Use the negotiated security parameters for decryption. {{{ */
2903 void
2904 ssl_change_cipher(SslDecryptSession *ssl_session, gboolean server)
2905 {
2906     ssl_debug_printf("ssl_change_cipher %s\n", (server)?"SERVER":"CLIENT");
2907     if (server) {
2908         ssl_session->server = ssl_session->server_new;
2909         ssl_session->server_new = NULL;
2910     } else {
2911         ssl_session->client = ssl_session->client_new;
2912         ssl_session->client_new = NULL;
2913     }
2914 }
2915 /* }}} */
2916
2917 /* Init cipher state given some security parameters. {{{ */
2918 static gboolean
2919 ssl_decoder_destroy_cb(wmem_allocator_t *, wmem_cb_event_t, void *);
2920
2921 static SslDecoder*
2922 ssl_create_decoder(const SslCipherSuite *cipher_suite, gint cipher_algo,
2923         gint compression, guint8 *mk, guint8 *sk, guint8 *iv, guint iv_length)
2924 {
2925     SslDecoder *dec;
2926     ssl_cipher_mode_t mode = cipher_suite->mode;
2927
2928     dec = (SslDecoder *)wmem_alloc0(wmem_file_scope(), sizeof(SslDecoder));
2929     /* init mac buffer: mac storage is embedded into decoder struct to save a
2930      memory allocation and waste samo more memory*/
2931     dec->cipher_suite=cipher_suite;
2932     dec->compression = compression;
2933     if ((mode == MODE_STREAM && mk != NULL) || mode == MODE_CBC) {
2934         // AEAD ciphers use no MAC key, but stream and block ciphers do. Note
2935         // the special case for NULL ciphers, even if there is insufficieny
2936         // keying material (including MAC key), we will can still create
2937         // decoders since "decryption" is easy for such ciphers.
2938         dec->mac_key.data = dec->_mac_key_or_write_iv;
2939         ssl_data_set(&dec->mac_key, mk, ssl_cipher_suite_dig(cipher_suite)->len);
2940     } else if (mode == MODE_GCM || mode == MODE_CCM || mode == MODE_CCM_8) {
2941         // Input for the nonce, to be used with AEAD ciphers.
2942         DISSECTOR_ASSERT(iv_length <= sizeof(dec->_mac_key_or_write_iv));
2943         dec->write_iv.data = dec->_mac_key_or_write_iv;
2944         ssl_data_set(&dec->write_iv, iv, iv_length);
2945     }
2946     dec->seq = 0;
2947     dec->decomp = ssl_create_decompressor(compression);
2948     wmem_register_callback(wmem_file_scope(), ssl_decoder_destroy_cb, dec);
2949
2950     if (ssl_cipher_init(&dec->evp,cipher_algo,sk,iv,cipher_suite->mode) < 0) {
2951         ssl_debug_printf("%s: can't create cipher id:%d mode:%d\n", G_STRFUNC,
2952             cipher_algo, cipher_suite->mode);
2953         return NULL;
2954     }
2955
2956     ssl_debug_printf("decoder initialized (digest len %d)\n", ssl_cipher_suite_dig(cipher_suite)->len);
2957     return dec;
2958 }
2959
2960 static gboolean
2961 ssl_decoder_destroy_cb(wmem_allocator_t *allocator _U_, wmem_cb_event_t event _U_, void *user_data)
2962 {
2963     SslDecoder *dec = (SslDecoder *) user_data;
2964
2965     if (dec->evp)
2966         ssl_cipher_cleanup(&dec->evp);
2967
2968 #ifdef HAVE_ZLIB
2969     if (dec->decomp != NULL && dec->decomp->compression == 1 /* DEFLATE */)
2970         inflateEnd(&dec->decomp->istream);
2971 #endif
2972
2973     return FALSE;
2974 }
2975 /* }}} */
2976
2977 /* (Pre-)master secrets calculations {{{ */
2978 #ifdef HAVE_LIBGNUTLS
2979 static int
2980 ssl_decrypt_pre_master_secret(SslDecryptSession *ssl_session,
2981                               StringInfo *encrypted_pre_master,
2982                               gcry_sexp_t pk);
2983 #endif /* HAVE_LIBGNUTLS */
2984
2985 static gboolean
2986 ssl_restore_master_key(SslDecryptSession *ssl, const char *label,
2987                        gboolean is_pre_master, GHashTable *ht, StringInfo *key);
2988
2989 gboolean
2990 ssl_generate_pre_master_secret(SslDecryptSession *ssl_session,
2991                                guint32 length, tvbuff_t *tvb, guint32 offset,
2992                                const gchar *ssl_psk,
2993                                const ssl_master_key_map_t *mk_map)
2994 {
2995     /* check for required session data */
2996     ssl_debug_printf("%s: found SSL_HND_CLIENT_KEY_EXCHG, state %X\n",
2997                      G_STRFUNC, ssl_session->state);
2998     if ((ssl_session->state & (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) !=
2999         (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION)) {
3000         ssl_debug_printf("%s: not enough data to generate key (required state %X)\n", G_STRFUNC,
3001                          (SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION));
3002         return FALSE;
3003     }
3004
3005     if (ssl_session->session.version == TLSV1DOT3_VERSION) {
3006         ssl_debug_printf("%s: detected TLS 1.3 which has no pre-master secrets\n", G_STRFUNC);
3007         return FALSE;
3008     }
3009
3010     /* check to see if the PMS was provided to us*/
3011     if (ssl_restore_master_key(ssl_session, "Unencrypted pre-master secret", TRUE,
3012            mk_map->pms, &ssl_session->client_random)) {
3013         return TRUE;
3014     }
3015
3016     if (ssl_session->cipher_suite->kex == KEX_PSK)
3017     {
3018         /* calculate pre master secret*/
3019         StringInfo pre_master_secret;
3020         guint psk_len, pre_master_len;
3021
3022         if (!ssl_psk || (ssl_psk[0] == 0)) {
3023             ssl_debug_printf("%s: can't find pre-shared-key\n", G_STRFUNC);
3024             return FALSE;
3025         }
3026
3027         /* convert hex string into char*/
3028         if (!from_hex(&ssl_session->psk, ssl_psk, strlen(ssl_psk))) {
3029             ssl_debug_printf("%s: ssl.psk/dtls.psk contains invalid hex\n",
3030                              G_STRFUNC);
3031             return FALSE;
3032         }
3033
3034         psk_len = ssl_session->psk.data_len;
3035         if (psk_len >= (2 << 15)) {
3036             ssl_debug_printf("%s: ssl.psk/dtls.psk must not be larger than 2^15 - 1\n",
3037                              G_STRFUNC);
3038             return FALSE;
3039         }
3040
3041
3042         pre_master_len = psk_len * 2 + 4;
3043
3044         pre_master_secret.data = (guchar *)wmem_alloc(wmem_file_scope(), pre_master_len);
3045         pre_master_secret.data_len = pre_master_len;
3046         /* 2 bytes psk_len*/
3047         pre_master_secret.data[0] = psk_len >> 8;
3048         pre_master_secret.data[1] = psk_len & 0xFF;
3049         /* psk_len bytes times 0*/
3050         memset(&pre_master_secret.data[2], 0, psk_len);
3051         /* 2 bytes psk_len*/
3052         pre_master_secret.data[psk_len + 2] = psk_len >> 8;
3053         pre_master_secret.data[psk_len + 3] = psk_len & 0xFF;
3054         /* psk*/
3055         memcpy(&pre_master_secret.data[psk_len + 4], ssl_session->psk.data, psk_len);
3056
3057         ssl_session->pre_master_secret.data = pre_master_secret.data;
3058         ssl_session->pre_master_secret.data_len = pre_master_len;
3059         /*ssl_debug_printf("pre master secret",&ssl->pre_master_secret);*/
3060
3061         /* Remove the master secret if it was there.
3062            This forces keying material regeneration in
3063            case we're renegotiating */
3064         ssl_session->state &= ~(SSL_MASTER_SECRET|SSL_HAVE_SESSION_KEY);
3065         ssl_session->state |= SSL_PRE_MASTER_SECRET;
3066         return TRUE;
3067     }
3068     else
3069     {
3070         StringInfo encrypted_pre_master;
3071         guint encrlen, skip;
3072         encrlen = length;
3073         skip = 0;
3074
3075         /* get encrypted data, on tls1 we have to skip two bytes
3076          * (it's the encrypted len and should be equal to record len - 2)
3077          * in case of rsa1024 that would be 128 + 2 = 130; for psk not necessary
3078          */
3079         if (ssl_session->cipher_suite->kex == KEX_RSA &&
3080            (ssl_session->session.version == TLSV1_VERSION ||
3081             ssl_session->session.version == TLSV1DOT1_VERSION ||
3082             ssl_session->session.version == TLSV1DOT2_VERSION ||
3083             ssl_session->session.version == DTLSV1DOT0_VERSION ||
3084             ssl_session->session.version == DTLSV1DOT2_VERSION))
3085         {
3086             encrlen  = tvb_get_ntohs(tvb, offset);
3087             skip = 2;
3088             if (encrlen > length - 2)
3089             {
3090                 ssl_debug_printf("%s: wrong encrypted length (%d max %d)\n",
3091                                  G_STRFUNC, encrlen, length);
3092                 return FALSE;
3093             }
3094         }
3095         /* the valid lower bound is higher than 8, but it is sufficient for the
3096          * ssl keylog file below */
3097         if (encrlen < 8) {
3098             ssl_debug_printf("%s: invalid encrypted pre-master key length %d\n",
3099                              G_STRFUNC, encrlen);
3100             return FALSE;
3101         }
3102
3103         encrypted_pre_master.data = (guchar *)wmem_alloc(wmem_file_scope(), encrlen);
3104         encrypted_pre_master.data_len = encrlen;
3105         tvb_memcpy(tvb, encrypted_pre_master.data, offset+skip, encrlen);
3106
3107 #ifdef HAVE_LIBGNUTLS
3108         if (ssl_session->private_key) {
3109             /* try to decrypt encrypted pre-master with RSA key */
3110             if (ssl_decrypt_pre_master_secret(ssl_session,
3111                 &encrypted_pre_master, ssl_session->private_key))
3112                 return TRUE;
3113
3114             ssl_debug_printf("%s: can't decrypt pre-master secret\n",
3115                              G_STRFUNC);
3116         }
3117 #endif /* HAVE_LIBGNUTLS */
3118
3119         /* try to find the pre-master secret from the encrypted one. The
3120          * ssl key logfile stores only the first 8 bytes, so truncate it */
3121         encrypted_pre_master.data_len = 8;
3122         if (ssl_restore_master_key(ssl_session, "Encrypted pre-master secret",
3123             TRUE, mk_map->pre_master, &encrypted_pre_master))
3124             return TRUE;
3125     }
3126     return FALSE;
3127 }
3128
3129 /* Used for (D)TLS 1.2 and earlier versions (not with TLS 1.3). */
3130 int
3131 ssl_generate_keyring_material(SslDecryptSession*ssl_session)
3132 {
3133     StringInfo  key_block = { NULL, 0 };
3134     guint8      _iv_c[MAX_BLOCK_SIZE],_iv_s[MAX_BLOCK_SIZE];
3135     guint8      _key_c[MAX_KEY_SIZE],_key_s[MAX_KEY_SIZE];
3136     gint        needed;
3137     gint        cipher_algo = -1;   /* special value (-1) for NULL encryption */
3138     guint       encr_key_len, write_iv_len = 0;
3139     gboolean    is_export_cipher;
3140     guint8     *ptr, *c_iv = NULL, *s_iv = NULL;
3141     guint8     *c_wk = NULL, *s_wk = NULL, *c_mk = NULL, *s_mk = NULL;
3142     const SslCipherSuite *cipher_suite = ssl_session->cipher_suite;
3143
3144     /* TLS 1.3 is handled directly in tls13_change_key. */
3145     if (ssl_session->session.version == TLSV1DOT3_VERSION) {
3146         ssl_debug_printf("%s: detected TLS 1.3. Should not have been called!\n", G_STRFUNC);
3147         return -1;
3148     }
3149
3150     /* check for enough info to proced */
3151     guint need_all = SSL_CIPHER|SSL_CLIENT_RANDOM|SSL_SERVER_RANDOM|SSL_VERSION;
3152     guint need_any = SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET;
3153     if (((ssl_session->state & need_all) != need_all) || ((ssl_session->state & need_any) == 0)) {
3154         ssl_debug_printf("ssl_generate_keyring_material not enough data to generate key "
3155                          "(0x%02X required 0x%02X or 0x%02X)\n", ssl_session->state,
3156                          need_all|SSL_MASTER_SECRET, need_all|SSL_PRE_MASTER_SECRET);
3157         /* Special case: for NULL encryption, allow dissection of data even if
3158          * the Client Hello is missing (MAC keys are now skipped though). */
3159         need_all = SSL_CIPHER|SSL_VERSION;
3160         if ((ssl_session->state & need_all) == need_all &&
3161                 cipher_suite->enc == ENC_NULL) {
3162             ssl_debug_printf("%s NULL cipher found, will create a decoder but "
3163                     "skip MAC validation as keys are missing.\n", G_STRFUNC);
3164             goto create_decoders;
3165         }
3166
3167         return -1;
3168     }
3169
3170     /* if master key is not available, generate is from the pre-master secret */
3171     if (!(ssl_session->state & SSL_MASTER_SECRET)) {
3172         if ((ssl_session->state & SSL_EXTENDED_MASTER_SECRET_MASK) == SSL_EXTENDED_MASTER_SECRET_MASK) {
3173             StringInfo handshake_hashed_data;
3174             gint ret;
3175
3176             handshake_hashed_data.data = NULL;
3177             handshake_hashed_data.data_len = 0;
3178
3179             ssl_debug_printf("%s:PRF(pre_master_secret_extended)\n", G_STRFUNC);
3180             ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
3181             DISSECTOR_ASSERT(ssl_session->handshake_data.data_len > 0);
3182
3183             switch(ssl_session->session.version) {
3184             case TLSV1_VERSION:
3185             case TLSV1DOT1_VERSION:
3186             case DTLSV1DOT0_VERSION:
3187             case DTLSV1DOT0_OPENSSL_VERSION:
3188                 ret = tls_handshake_hash(ssl_session, &handshake_hashed_data);
3189                 break;
3190             default:
3191                 switch (cipher_suite->dig) {
3192                 case DIG_SHA384:
3193                     ret = tls12_handshake_hash(ssl_session, GCRY_MD_SHA384, &handshake_hashed_data);
3194                     break;
3195                 default:
3196                     ret = tls12_handshake_hash(ssl_session, GCRY_MD_SHA256, &handshake_hashed_data);
3197                     break;
3198                 }
3199                 break;
3200             }
3201             if (ret) {
3202                 ssl_debug_printf("%s can't generate handshake hash\n", G_STRFUNC);
3203                 return -1;
3204             }
3205
3206             wmem_free(wmem_file_scope(), ssl_session->handshake_data.data);
3207             ssl_session->handshake_data.data = NULL;
3208             ssl_session->handshake_data.data_len = 0;
3209
3210             if (!prf(ssl_session, &ssl_session->pre_master_secret, "extended master secret",
3211                      &handshake_hashed_data,
3212                      NULL, &ssl_session->master_secret,
3213                      SSL_MASTER_SECRET_LENGTH)) {
3214                 ssl_debug_printf("%s can't generate master_secret\n", G_STRFUNC);
3215                 g_free(handshake_hashed_data.data);
3216                 return -1;
3217             }
3218             g_free(handshake_hashed_data.data);
3219         } else {
3220             ssl_debug_printf("%s:PRF(pre_master_secret)\n", G_STRFUNC);
3221             ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
3222             ssl_print_string("client random",&ssl_session->client_random);
3223             ssl_print_string("server random",&ssl_session->server_random);
3224             if (!prf(ssl_session, &ssl_session->pre_master_secret, "master secret",
3225                      &ssl_session->client_random,
3226                      &ssl_session->server_random, &ssl_session->master_secret,
3227                      SSL_MASTER_SECRET_LENGTH)) {
3228                 ssl_debug_printf("%s can't generate master_secret\n", G_STRFUNC);
3229                 return -1;
3230             }
3231         }
3232         ssl_print_string("master secret",&ssl_session->master_secret);
3233
3234         /* the pre-master secret has been 'consumend' so we must clear it now */
3235         ssl_session->state &= ~SSL_PRE_MASTER_SECRET;
3236         ssl_session->state |= SSL_MASTER_SECRET;
3237     }
3238
3239     /* Find the Libgcrypt cipher algorithm for the given SSL cipher suite ID */
3240     if (cipher_suite->enc != ENC_NULL) {
3241         const char *cipher_name = ciphers[cipher_suite->enc-0x30];
3242         ssl_debug_printf("%s CIPHER: %s\n", G_STRFUNC, cipher_name);
3243         cipher_algo = ssl_get_cipher_by_name(cipher_name);
3244         if (cipher_algo == 0) {
3245             ssl_debug_printf("%s can't find cipher %s\n", G_STRFUNC, cipher_name);
3246             return -1;
3247         }
3248     }
3249
3250     /* Export ciphers consume less material from the key block. */
3251     encr_key_len = ssl_get_cipher_export_keymat_size(cipher_suite->number);
3252     is_export_cipher = encr_key_len > 0;
3253     if (!is_export_cipher && cipher_suite->enc != ENC_NULL) {
3254         encr_key_len = (guint)gcry_cipher_get_algo_keylen(cipher_algo);
3255     }
3256
3257     if (cipher_suite->mode == MODE_CBC) {
3258         write_iv_len = (guint)gcry_cipher_get_algo_blklen(cipher_algo);
3259     } else if (cipher_suite->mode == MODE_GCM || cipher_suite->mode == MODE_CCM || cipher_suite->mode == MODE_CCM_8) {
3260         /* account for a four-byte salt for client and server side (from
3261          * client_write_IV and server_write_IV), see GCMNonce (RFC 5288) */
3262         write_iv_len = 4;
3263     }
3264
3265     /* Compute the key block. First figure out how much data we need */
3266     needed = ssl_cipher_suite_dig(cipher_suite)->len*2;     /* MAC key  */
3267     needed += 2 * encr_key_len;                             /* encryption key */
3268     needed += 2 * write_iv_len;                             /* write IV */
3269
3270     key_block.data = (guchar *)g_malloc(needed);
3271     ssl_debug_printf("%s sess key generation\n", G_STRFUNC);
3272     if (!prf(ssl_session, &ssl_session->master_secret, "key expansion",
3273             &ssl_session->server_random,&ssl_session->client_random,
3274             &key_block, needed)) {
3275         ssl_debug_printf("%s can't generate key_block\n", G_STRFUNC);
3276         goto fail;
3277     }
3278     ssl_print_string("key expansion", &key_block);
3279
3280     ptr=key_block.data;
3281     /* client/server write MAC key (for non-AEAD ciphers) */
3282     if (cipher_suite->mode == MODE_STREAM || cipher_suite->mode == MODE_CBC) {
3283         c_mk=ptr; ptr+=ssl_cipher_suite_dig(cipher_suite)->len;
3284         s_mk=ptr; ptr+=ssl_cipher_suite_dig(cipher_suite)->len;
3285     }
3286     /* client/server write encryption key */
3287     c_wk=ptr; ptr += encr_key_len;
3288     s_wk=ptr; ptr += encr_key_len;
3289     /* client/server write IV (used as IV (for CBC) or salt (for AEAD)) */
3290     if (write_iv_len > 0) {
3291         c_iv=ptr; ptr += write_iv_len;
3292         s_iv=ptr; /* ptr += write_iv_len; */
3293     }
3294
3295     /* export ciphers work with a smaller key length */
3296     if (is_export_cipher) {
3297         if (cipher_suite->mode == MODE_CBC) {
3298
3299             /* We only have room for MAX_BLOCK_SIZE bytes IVs, but that's
3300              all we should need. This is a sanity check */
3301             if (write_iv_len > MAX_BLOCK_SIZE) {
3302                 ssl_debug_printf("%s cipher suite block must be at most %d nut is %d\n",
3303                         G_STRFUNC, MAX_BLOCK_SIZE, write_iv_len);
3304                 goto fail;
3305             }
3306
3307             if(ssl_session->session.version==SSLV3_VERSION){
3308                 /* The length of these fields are ignored by this caller */
3309                 StringInfo iv_c, iv_s;
3310                 iv_c.data = _iv_c;
3311                 iv_s.data = _iv_s;
3312
3313                 ssl_debug_printf("%s ssl3_generate_export_iv\n", G_STRFUNC);
3314                 ssl3_generate_export_iv(&ssl_session->client_random,
3315                         &ssl_session->server_random, &iv_c, write_iv_len);
3316                 ssl_debug_printf("%s ssl3_generate_export_iv(2)\n", G_STRFUNC);
3317                 ssl3_generate_export_iv(&ssl_session->server_random,
3318                         &ssl_session->client_random, &iv_s, write_iv_len);
3319             }
3320             else{
3321                 guint8 _iv_block[MAX_BLOCK_SIZE * 2];
3322                 StringInfo iv_block;
3323                 StringInfo key_null;
3324                 guint8 _key_null;
3325
3326                 key_null.data = &_key_null;
3327                 key_null.data_len = 0;
3328
3329                 iv_block.data = _iv_block;
3330
3331                 ssl_debug_printf("%s prf(iv_block)\n", G_STRFUNC);
3332                 if (!prf(ssl_session, &key_null, "IV block",
3333                         &ssl_session->client_random,
3334                         &ssl_session->server_random, &iv_block,
3335                         write_iv_len * 2)) {
3336                     ssl_debug_printf("%s can't generate tls31 iv block\n", G_STRFUNC);
3337                     goto fail;
3338                 }
3339
3340                 memcpy(_iv_c, iv_block.data, write_iv_len);
3341                 memcpy(_iv_s, iv_block.data + write_iv_len, write_iv_len);
3342             }
3343
3344             c_iv=_iv_c;
3345             s_iv=_iv_s;
3346         }
3347
3348         if (ssl_session->session.version==SSLV3_VERSION){
3349
3350             SSL_MD5_CTX md5;
3351             ssl_debug_printf("%s MD5(client_random)\n", G_STRFUNC);
3352
3353             ssl_md5_init(&md5);
3354             ssl_md5_update(&md5,c_wk,encr_key_len);
3355             ssl_md5_update(&md5,ssl_session->client_random.data,
3356                 ssl_session->client_random.data_len);
3357             ssl_md5_update(&md5,ssl_session->server_random.data,
3358                 ssl_session->server_random.data_len);
3359             ssl_md5_final(_key_c,&md5);
3360             ssl_md5_cleanup(&md5);
3361             c_wk=_key_c;
3362
3363             ssl_md5_init(&md5);
3364             ssl_debug_printf("%s MD5(server_random)\n", G_STRFUNC);
3365             ssl_md5_update(&md5,s_wk,encr_key_len);
3366             ssl_md5_update(&md5,ssl_session->server_random.data,
3367                 ssl_session->server_random.data_len);
3368             ssl_md5_update(&md5,ssl_session->client_random.data,
3369                 ssl_session->client_random.data_len);
3370             ssl_md5_final(_key_s,&md5);
3371             ssl_md5_cleanup(&md5);
3372             s_wk=_key_s;
3373         }
3374         else{
3375             StringInfo key_c, key_s, k;
3376             key_c.data = _key_c;
3377             key_s.data = _key_s;
3378
3379             k.data = c_wk;
3380             k.data_len = encr_key_len;
3381             ssl_debug_printf("%s PRF(key_c)\n", G_STRFUNC);
3382             if (!prf(ssl_session, &k, "client write key",
3383                     &ssl_session->client_random,
3384                     &ssl_session->server_random, &key_c, sizeof(_key_c))) {
3385                 ssl_debug_printf("%s can't generate tll31 server key \n", G_STRFUNC);
3386                 goto fail;
3387             }
3388             c_wk=_key_c;
3389
3390             k.data = s_wk;
3391             k.data_len = encr_key_len;
3392             ssl_debug_printf("%s PRF(key_s)\n", G_STRFUNC);
3393             if (!prf(ssl_session, &k, "server write key",
3394                     &ssl_session->client_random,
3395                     &ssl_session->server_random, &key_s, sizeof(_key_s))) {
3396                 ssl_debug_printf("%s can't generate tll31 client key \n", G_STRFUNC);
3397                 goto fail;
3398             }
3399             s_wk=_key_s;
3400         }
3401     }
3402
3403     /* show key material info */
3404     if (c_mk != NULL) {
3405         ssl_print_data("Client MAC key",c_mk,ssl_cipher_suite_dig(cipher_suite)->len);
3406         ssl_print_data("Server MAC key",s_mk,ssl_cipher_suite_dig(cipher_suite)->len);
3407     }
3408     ssl_print_data("Client Write key", c_wk, encr_key_len);
3409     ssl_print_data("Server Write key", s_wk, encr_key_len);
3410     /* used as IV for CBC mode and the AEAD implicit nonce (salt) */
3411     if (write_iv_len > 0) {
3412         ssl_print_data("Client Write IV", c_iv, write_iv_len);
3413         ssl_print_data("Server Write IV", s_iv, write_iv_len);
3414     }
3415
3416 create_decoders:
3417     /* create both client and server ciphers*/
3418     ssl_debug_printf("%s ssl_create_decoder(client)\n", G_STRFUNC);
3419     ssl_session->client_new = ssl_create_decoder(cipher_suite, cipher_algo, ssl_session->session.compression, c_mk, c_wk, c_iv, write_iv_len);
3420     if (!ssl_session->client_new) {
3421         ssl_debug_printf("%s can't init client decoder\n", G_STRFUNC);
3422         goto fail;
3423     }
3424     ssl_debug_printf("%s ssl_create_decoder(server)\n", G_STRFUNC);
3425     ssl_session->server_new = ssl_create_decoder(cipher_suite, cipher_algo, ssl_session->session.compression, s_mk, s_wk, s_iv, write_iv_len);
3426     if (!ssl_session->server_new) {
3427         ssl_debug_printf("%s can't init client decoder\n", G_STRFUNC);
3428         goto fail;
3429     }
3430
3431     /* Continue the SSL stream after renegotiation with new keys. */
3432     ssl_session->client_new->flow = ssl_session->client ? ssl_session->client->flow : ssl_create_flow();
3433     ssl_session->server_new->flow = ssl_session->server ? ssl_session->server->flow : ssl_create_flow();
3434
3435     ssl_debug_printf("%s: client seq %" G_GUINT64_FORMAT ", server seq %" G_GUINT64_FORMAT "\n",
3436         G_STRFUNC, ssl_session->client_new->seq, ssl_session->server_new->seq);
3437     g_free(key_block.data);
3438     ssl_session->state |= SSL_HAVE_SESSION_KEY;
3439     return 0;
3440
3441 fail:
3442     g_free(key_block.data);
3443     return -1;
3444 }
3445
3446 /* Generated the key material based on the given secret. */
3447 static gboolean
3448 tls13_generate_keys(SslDecryptSession *ssl_session, const StringInfo *secret, gboolean is_from_server)
3449 {
3450     gboolean    success = FALSE;
3451     guchar     *write_key = NULL, *write_iv = NULL;
3452     SslDecoder *decoder;
3453     guint       key_length, iv_length;
3454     int         hash_algo;
3455     const SslCipherSuite *cipher_suite = ssl_session->cipher_suite;
3456     int         cipher_algo;
3457
3458     if (ssl_session->session.version != TLSV1DOT3_VERSION) {
3459         ssl_debug_printf("%s only usable for TLS 1.3, not %#x!\n", G_STRFUNC,
3460                 ssl_session->session.version);
3461         return FALSE;
3462     }
3463
3464     if (cipher_suite == NULL) {
3465         ssl_debug_printf("%s Unknown cipher\n", G_STRFUNC);
3466         return FALSE;
3467     }
3468
3469     if (cipher_suite->kex != KEX_TLS13) {
3470         ssl_debug_printf("%s Invalid cipher suite 0x%04x spotted!\n", G_STRFUNC, cipher_suite->number);
3471         return FALSE;
3472     }
3473
3474     /* Find the Libgcrypt cipher algorithm for the given SSL cipher suite ID */
3475     const char *cipher_name = ciphers[cipher_suite->enc-0x30];
3476     ssl_debug_printf("%s CIPHER: %s\n", G_STRFUNC, cipher_name);
3477     cipher_algo = ssl_get_cipher_by_name(cipher_name);
3478     if (cipher_algo == 0) {
3479         ssl_debug_printf("%s can't find cipher %s\n", G_STRFUNC, cipher_name);
3480         return FALSE;
3481     }
3482
3483     const char *hash_name = ssl_cipher_suite_dig(cipher_suite)->name;
3484     hash_algo = ssl_get_digest_by_name(hash_name);
3485     if (!hash_algo) {
3486         ssl_debug_printf("%s can't find hash function %s\n", G_STRFUNC, hash_name);
3487         return FALSE;
3488     }
3489
3490     key_length = (guint) gcry_cipher_get_algo_blklen(cipher_algo);
3491     /* AES-GCM/AES-CCM/Poly1305-ChaCha20 all have N_MIN=N_MAX = 12. */
3492     iv_length = 12;
3493     ssl_debug_printf("%s key_length %u iv_length %u\n", G_STRFUNC, key_length, iv_length);
3494
3495     if (!tls13_hkdf_expand_label(hash_algo, secret, "key", "", key_length, &write_key)) {
3496         ssl_debug_printf("%s write_key expansion failed\n", G_STRFUNC);
3497         return FALSE;
3498     }
3499     if (!tls13_hkdf_expand_label(hash_algo, secret, "iv", "", iv_length, &write_iv)) {
3500         ssl_debug_printf("%s write_iv expansion failed\n", G_STRFUNC);
3501         goto end;
3502     }
3503
3504     ssl_print_data(is_from_server ? "Server Write Key" : "Client Write Key", write_key, key_length);
3505     ssl_print_data(is_from_server ? "Server Write IV" : "Client Write IV", write_iv, iv_length);
3506
3507     ssl_debug_printf("%s ssl_create_decoder(%s)\n", G_STRFUNC, is_from_server ? "server" : "client");
3508     decoder = ssl_create_decoder(cipher_suite, cipher_algo, 0, NULL, write_key, write_iv, iv_length);
3509     if (!decoder) {
3510         ssl_debug_printf("%s can't init %s decoder\n", G_STRFUNC, is_from_server ? "server" : "client");
3511         goto end;
3512     }
3513
3514     /* Continue the TLS session with new keys, but reuse old flow to keep things
3515      * like "Follow SSL" working (by linking application data records). */
3516     if (is_from_server) {
3517         decoder->flow = ssl_session->server ? ssl_session->server->flow : ssl_create_flow();
3518         ssl_session->server = decoder;
3519     } else {
3520         decoder->flow = ssl_session->client ? ssl_session->client->flow : ssl_create_flow();
3521         ssl_session->client = decoder;
3522     }
3523     ssl_debug_printf("%s %s ready using cipher suite 0x%04x (cipher %s hash %s)\n", G_STRFUNC,
3524                      is_from_server ? "Server" : "Client", cipher_suite->number, cipher_name, hash_name);
3525     success = TRUE;
3526
3527 end:
3528     wmem_free(NULL, write_key);
3529     wmem_free(NULL, write_iv);
3530     return success;
3531 }
3532 /* (Pre-)master secrets calculations }}} */
3533
3534 #ifdef HAVE_LIBGNUTLS
3535 /* Decrypt RSA pre-master secret using RSA private key. {{{ */
3536 static gboolean
3537 ssl_decrypt_pre_master_secret(SslDecryptSession*ssl_session,
3538     StringInfo* encrypted_pre_master, gcry_sexp_t pk)
3539 {
3540     gint i;
3541
3542     if (!encrypted_pre_master)
3543         return FALSE;
3544
3545     if (KEX_IS_DH(ssl_session->cipher_suite->kex)) {
3546         ssl_debug_printf("%s: session uses Diffie-Hellman key exchange "
3547                          "(cipher suite 0x%04X %s) and cannot be decrypted "
3548                          "using a RSA private key file.\n",
3549                          G_STRFUNC, ssl_session->session.cipher,
3550                          val_to_str_ext_const(ssl_session->session.cipher,
3551                              &ssl_31_ciphersuite_ext, "unknown"));
3552         return FALSE;
3553     } else if(ssl_session->cipher_suite->kex != KEX_RSA) {
3554          ssl_debug_printf("%s key exchange %d different from KEX_RSA (%d)\n",
3555                           G_STRFUNC, ssl_session->cipher_suite->kex, KEX_RSA);
3556         return FALSE;
3557     }
3558
3559     /* with tls key loading will fail if not rsa type, so no need to check*/
3560     ssl_print_string("pre master encrypted",encrypted_pre_master);
3561     ssl_debug_printf("%s: RSA_private_decrypt\n", G_STRFUNC);
3562     i=ssl_private_decrypt(encrypted_pre_master->data_len,
3563         encrypted_pre_master->data, pk);
3564
3565     if (i!=48) {
3566         ssl_debug_printf("%s wrong pre_master_secret length (%d, expected "
3567                          "%d)\n", G_STRFUNC, i, 48);
3568         return FALSE;
3569     }
3570
3571     /* the decrypted data has been written into the pre_master key buffer */
3572     ssl_session->pre_master_secret.data = encrypted_pre_master->data;
3573     ssl_session->pre_master_secret.data_len=48;
3574     ssl_print_string("pre master secret",&ssl_session->pre_master_secret);
3575
3576     /* Remove the master secret if it was there.
3577        This forces keying material regeneration in
3578        case we're renegotiating */
3579     ssl_session->state &= ~(SSL_MASTER_SECRET|SSL_HAVE_SESSION_KEY);
3580     ssl_session->state |= SSL_PRE_MASTER_SECRET;
3581     return TRUE;
3582 } /* }}} */
3583 #endif /* HAVE_LIBGNUTLS */
3584
3585 /* Decryption integrity check {{{ */
3586
3587 static gint
3588 tls_check_mac(SslDecoder*decoder, gint ct, gint ver, guint8* data,
3589         guint32 datalen, guint8* mac)
3590 {
3591     SSL_HMAC hm;
3592     gint     md;
3593     guint32  len;
3594     guint8   buf[DIGEST_MAX_SIZE];
3595     gint16   temp;
3596
3597     md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
3598     ssl_debug_printf("tls_check_mac mac type:%s md %d\n",
3599         ssl_cipher_suite_dig(decoder->cipher_suite)->name, md);
3600
3601     if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
3602         return -1;
3603
3604     /* hash sequence number */
3605     phton64(buf, decoder->seq);
3606
3607     decoder->seq++;
3608
3609     ssl_hmac_update(&hm,buf,8);
3610
3611     /* hash content type */
3612     buf[0]=ct;
3613     ssl_hmac_update(&hm,buf,1);
3614
3615     /* hash version,data length and data*/
3616     /* *((gint16*)buf) = g_htons(ver); */
3617     temp = g_htons(ver);
3618     memcpy(buf, &temp, 2);
3619     ssl_hmac_update(&hm,buf,2);
3620
3621     /* *((gint16*)buf) = g_htons(datalen); */
3622     temp = g_htons(datalen);
3623     memcpy(buf, &temp, 2);
3624     ssl_hmac_update(&hm,buf,2);
3625     ssl_hmac_update(&hm,data,datalen);
3626
3627     /* get digest and digest len*/
3628     len = sizeof(buf);
3629     ssl_hmac_final(&hm,buf,&len);
3630     ssl_hmac_cleanup(&hm);
3631     ssl_print_data("Mac", buf, len);
3632     if(memcmp(mac,buf,len))
3633         return -1;
3634
3635     return 0;
3636 }
3637
3638 static int
3639 ssl3_check_mac(SslDecoder*decoder,int ct,guint8* data,
3640         guint32 datalen, guint8* mac)
3641 {
3642     SSL_MD  mc;
3643     gint    md;
3644     guint32 len;
3645     guint8  buf[64],dgst[20];
3646     gint    pad_ct;
3647     gint16  temp;
3648
3649     pad_ct=(decoder->cipher_suite->dig==DIG_SHA)?40:48;
3650
3651     /* get cipher used for digest comptuation */
3652     md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
3653     if (ssl_md_init(&mc,md) !=0)
3654         return -1;
3655
3656     /* do hash computation on data && padding */
3657     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
3658
3659     /* hash padding*/
3660     memset(buf,0x36,pad_ct);
3661     ssl_md_update(&mc,buf,pad_ct);
3662
3663     /* hash sequence number */
3664     phton64(buf, decoder->seq);
3665     decoder->seq++;
3666     ssl_md_update(&mc,buf,8);
3667
3668     /* hash content type */
3669     buf[0]=ct;
3670     ssl_md_update(&mc,buf,1);
3671
3672     /* hash data length in network byte order and data*/
3673     /* *((gint16* )buf) = g_htons(datalen); */
3674     temp = g_htons(datalen);
3675     memcpy(buf, &temp, 2);
3676     ssl_md_update(&mc,buf,2);
3677     ssl_md_update(&mc,data,datalen);
3678
3679     /* get partial digest */
3680     ssl_md_final(&mc,dgst,&len);
3681     ssl_md_cleanup(&mc);
3682
3683     ssl_md_init(&mc,md);
3684
3685     /* hash mac key */
3686     ssl_md_update(&mc,decoder->mac_key.data,decoder->mac_key.data_len);
3687
3688     /* hash padding and partial digest*/
3689     memset(buf,0x5c,pad_ct);
3690     ssl_md_update(&mc,buf,pad_ct);
3691     ssl_md_update(&mc,dgst,len);
3692
3693     ssl_md_final(&mc,dgst,&len);
3694     ssl_md_cleanup(&mc);
3695
3696     if(memcmp(mac,dgst,len))
3697         return -1;
3698
3699     return(0);
3700 }
3701
3702 static gint
3703 dtls_check_mac(SslDecoder*decoder, gint ct,int ver, guint8* data,
3704         guint32 datalen, guint8* mac)
3705 {
3706     SSL_HMAC hm;
3707     gint     md;
3708     guint32  len;
3709     guint8   buf[DIGEST_MAX_SIZE];
3710     gint16   temp;
3711
3712     md=ssl_get_digest_by_name(ssl_cipher_suite_dig(decoder->cipher_suite)->name);
3713     ssl_debug_printf("dtls_check_mac mac type:%s md %d\n",
3714         ssl_cipher_suite_dig(decoder->cipher_suite)->name, md);
3715
3716     if (ssl_hmac_init(&hm,decoder->mac_key.data,decoder->mac_key.data_len,md) != 0)
3717         return -1;
3718     ssl_debug_printf("dtls_check_mac seq: %" G_GUINT64_FORMAT " epoch: %d\n",decoder->seq,decoder->epoch);
3719     /* hash sequence number */
3720     phton64(buf, decoder->seq);
3721     buf[0]=decoder->epoch>>8;
3722     buf[1]=(guint8)decoder->epoch;
3723
3724     ssl_hmac_update(&hm,buf,8);
3725
3726     /* hash content type */
3727     buf[0]=ct;
3728     ssl_hmac_update(&hm,buf,1);
3729
3730     /* hash version,data length and data */
3731     temp = g_htons(ver);
3732     memcpy(buf, &temp, 2);
3733     ssl_hmac_update(&hm,buf,2);
3734
3735     temp = g_htons(datalen);
3736     memcpy(buf, &temp, 2);
3737     ssl_hmac_update(&hm,buf,2);
3738     ssl_hmac_update(&hm,data,datalen);
3739     /* get digest and digest len */
3740     len = sizeof(buf);
3741     ssl_hmac_final(&hm,buf,&len);
3742     ssl_hmac_cleanup(&hm);
3743     ssl_print_data("Mac", buf, len);
3744     if(memcmp(mac,buf,len))
3745         return -1;
3746
3747     return(0);
3748 }
3749 /* Decryption integrity check }}} */
3750
3751
3752 static gboolean
3753 tls_decrypt_aead_record(SslDecryptSession *ssl, SslDecoder *decoder,
3754 #ifdef HAVE_LIBGCRYPT_AEAD
3755         guint8 ct, guint16 record_version,
3756 #else
3757         guint8 ct _U_, guint16 record_version _U_,
3758 #endif
3759         const guchar *in, guint16 inl, StringInfo *out_str, guint *outl)
3760 {
3761     /* RFC 5246 (TLS 1.2) 6.2.3.3 defines the TLSCipherText.fragment as:
3762      * GenericAEADCipher: { nonce_explicit, [content] }
3763      * In TLS 1.3 this explicit nonce is gone.
3764      * With AES GCM/CCM, "[content]" is actually the concatenation of the
3765      * ciphertext and authentication tag.
3766      */
3767     const guint16   version = ssl->session.version;
3768     const gboolean  is_v12 = version == TLSV1DOT2_VERSION || version == DTLSV1DOT2_VERSION;
3769     gcry_error_t    err;
3770     const guchar   *explicit_nonce = NULL, *ciphertext;
3771     guint           ciphertext_len, auth_tag_len;
3772     guchar          nonce[12];
3773 #ifdef HAVE_LIBGCRYPT_AEAD
3774     const guchar   *auth_tag_wire;
3775     guchar          auth_tag_calc[16];
3776 #else
3777     guchar          nonce_with_counter[16] = { 0 };
3778 #endif
3779
3780     switch (decoder->cipher_suite->mode) {
3781     case MODE_GCM:
3782     case MODE_CCM:
3783         auth_tag_len = 16;
3784         break;
3785     case MODE_CCM_8:
3786         auth_tag_len = 8;
3787         break;
3788     default:
3789         ssl_debug_printf("%s unsupported cipher!\n", G_STRFUNC);
3790         return FALSE;
3791     }
3792
3793     /* Parse input into explicit nonce (TLS 1.2 only), ciphertext and tag. */
3794     if (is_v12) {
3795         if (inl < EXPLICIT_NONCE_LEN + auth_tag_len) {
3796             ssl_debug_printf("%s input %d is too small for explicit nonce %d and auth tag %d\n",
3797                     G_STRFUNC, inl, EXPLICIT_NONCE_LEN, auth_tag_len);
3798             return FALSE;
3799         }
3800         explicit_nonce = in;
3801         ciphertext = explicit_nonce + EXPLICIT_NONCE_LEN;
3802         ciphertext_len = inl - EXPLICIT_NONCE_LEN - auth_tag_len;
3803     } else if (version == TLSV1DOT3_VERSION) {
3804         if (inl < auth_tag_len) {
3805             ssl_debug_printf("%s input %d has no space for auth tag %d\n", G_STRFUNC, inl, auth_tag_len);
3806             return FALSE;
3807         }
3808         ciphertext = in;
3809         ciphertext_len = inl - auth_tag_len;
3810     } else {
3811         ssl_debug_printf("%s Unexpected TLS version %#x\n", G_STRFUNC, version);
3812         return FALSE;
3813     }
3814 #ifdef HAVE_LIBGCRYPT_AEAD
3815     auth_tag_wire = ciphertext + ciphertext_len;
3816 #endif
3817
3818     /* Nonce construction is version-specific. */
3819     if (is_v12) {
3820         DISSECTOR_ASSERT(decoder->write_iv.data_len == IMPLICIT_NONCE_LEN);
3821         /* Implicit (4) and explicit (8) part of nonce. */
3822         memcpy(nonce, decoder->write_iv.data, IMPLICIT_NONCE_LEN);
3823         memcpy(nonce + IMPLICIT_NONCE_LEN, explicit_nonce, EXPLICIT_NONCE_LEN);
3824
3825 #ifndef HAVE_LIBGCRYPT_AEAD
3826         if (decoder->cipher_suite->mode == MODE_GCM) {
3827             /* NIST SP 800-38D, sect. 7.2 says that the 32-bit counter part starts
3828              * at 1, and gets incremented before passing to the block cipher. */
3829             memcpy(nonce_with_counter, nonce, IMPLICIT_NONCE_LEN + EXPLICIT_NONCE_LEN);
3830             nonce_with_counter[IMPLICIT_NONCE_LEN + EXPLICIT_NONCE_LEN + 3] = 2;
3831         } else { /* MODE_CCM and MODE_CCM_8 */
3832             /* The nonce for CCM and GCM are the same, but the nonce is used as input
3833              * in the CCM algorithm described in RFC 3610. The nonce generated here is
3834              * the one from RFC 3610 sect 2.3. Encryption. */
3835             /* Flags: (L-1) ; L = 16 - 1 - nonceSize */
3836             nonce_with_counter[0] = 3 - 1;
3837             memcpy(nonce_with_counter + 1, nonce, IMPLICIT_NONCE_LEN + EXPLICIT_NONCE_LEN);
3838             /* struct { opaque salt[4]; opaque nonce_explicit[8] } CCMNonce (RFC 6655) */
3839             nonce_with_counter[IMPLICIT_NONCE_LEN + EXPLICIT_NONCE_LEN + 3] = 1;
3840         }
3841 #endif
3842     } else if (version == TLSV1DOT3_VERSION) {
3843         /*
3844          * Technically the nonce length must be at least 8 bytes, but for
3845          * AES-GCM, AES-CCM and Poly1305-ChaCha20 the nonce length is exact 12.
3846          */
3847         const guint nonce_len = 12;
3848         DISSECTOR_ASSERT(decoder->write_iv.data_len == nonce_len);
3849         memcpy(nonce, decoder->write_iv.data, decoder->write_iv.data_len);
3850         /* Sequence number is left-padded with zeroes and XORed with write_iv */
3851         phton64(nonce + nonce_len - 8, pntoh64(nonce + nonce_len - 8) ^ decoder->seq);
3852         ssl_debug_printf("%s seq %" G_GUINT64_FORMAT "\n", G_STRFUNC, decoder->seq);
3853         decoder->seq++;             /* Implicit sequence number for TLS 1.3. */
3854     }
3855
3856     /* Set nonce and additional authentication data */
3857 #ifdef HAVE_LIBGCRYPT_AEAD
3858     gcry_cipher_reset(decoder->evp);
3859     ssl_print_data("nonce", nonce, 12);
3860     err = gcry_cipher_setiv(decoder->evp, nonce, 12);
3861     if (err) {
3862         ssl_debug_printf("%s failed to set nonce: %s\n", G_STRFUNC, gcry_strerror(err));
3863         return FALSE;
3864     }
3865
3866     if (decoder->cipher_suite->mode == MODE_CCM || decoder->cipher_suite->mode == MODE_CCM_8) {
3867         /* size of plaintext, additional authenticated data and auth tag. */
3868         guint64 lengths[3] = { ciphertext_len, is_v12 ? 13 : 0, auth_tag_len };
3869         gcry_cipher_ctl(decoder->evp, GCRYCTL_SET_CCM_LENGTHS, lengths, sizeof(lengths));
3870     }
3871
3872     /* (D)TLS 1.2 needs specific AAD, TLS 1.3 uses empty AAD. */
3873     if (is_v12) {
3874         guchar aad[13];
3875         phton64(aad, decoder->seq);         /* record sequence number */
3876         if (version == TLSV1DOT2_VERSION) {
3877             decoder->seq++;                 /* Implicit sequence number for TLS 1.2. */
3878         } else {
3879             phton16(aad, decoder->epoch);   /* DTLS 1.2 includes epoch. */
3880         }
3881         aad[8] = ct;                        /* TLSCompressed.type */
3882         phton16(aad + 9, record_version);   /* TLSCompressed.version */
3883         phton16(aad + 11, ciphertext_len);  /* TLSCompressed.length */
3884         ssl_print_data("AAD", aad, sizeof(aad));
3885         err = gcry_cipher_authenticate(decoder->evp, aad, sizeof(aad));
3886         if (err) {
3887             ssl_debug_printf("%s failed to set AAD: %s\n", G_STRFUNC, gcry_strerror(err));
3888             return FALSE;
3889         }
3890     }
3891 #else
3892     err = gcry_cipher_setctr(decoder->evp, nonce_with_counter, 16);
3893     if (err) {
3894         ssl_debug_printf("%s failed: failed to set CTR: %s\n", G_STRFUNC, gcry_strerror(err));
3895         return FALSE;
3896     }
3897 #endif
3898
3899     /* Decrypt now that nonce and AAD are set. */
3900     err = gcry_cipher_decrypt(decoder->evp, out_str->data, out_str->data_len, ciphertext, ciphertext_len);
3901     if (err) {
3902         ssl_debug_printf("%s decrypt failed: %s\n", G_STRFUNC, gcry_strerror(err));
3903         return FALSE;
3904     }
3905
3906     /* Check authentication tag for authenticity (replaces MAC) */
3907 #ifdef HAVE_LIBGCRYPT_AEAD
3908     err = gcry_cipher_gettag(decoder->evp, auth_tag_calc, auth_tag_len);
3909     if (err == 0 && !memcmp(auth_tag_calc, auth_tag_wire, auth_tag_len)) {
3910         ssl_print_data("auth_tag(OK)", auth_tag_calc, auth_tag_len);
3911     } else {
3912         if (err) {
3913             ssl_debug_printf("%s cannot obtain tag: %s\n", G_STRFUNC, gcry_strerror(err));
3914         } else {
3915             ssl_debug_printf("%s auth tag mismatch\n", G_STRFUNC);
3916             ssl_print_data("auth_tag(expect)", auth_tag_calc, auth_tag_len);
3917             ssl_print_data("auth_tag(actual)", auth_tag_wire, auth_tag_len);
3918         }
3919         if (ssl_ignore_mac_failed) {
3920             ssl_debug_printf("%s: auth check failed, but ignored for troubleshooting ;-)\n", G_STRFUNC);
3921         } else {
3922             return FALSE;
3923         }
3924     }
3925 #else
3926     ssl_debug_printf("Libgcrypt is older than 1.6, unable to verify auth tag!\n");
3927 #endif
3928
3929     ssl_print_data("Plaintext", out_str->data, ciphertext_len);
3930     *outl = ciphertext_len;
3931     return TRUE;
3932 }
3933
3934 /* Record decryption glue based on security parameters {{{ */
3935 /* Assume that we are called only for a non-NULL decoder which also means that
3936  * we have a non-NULL decoder->cipher_suite. */
3937 int
3938 ssl_decrypt_record(SslDecryptSession *ssl, SslDecoder *decoder, guint8 ct, guint16 record_version,
3939         const guchar *in, guint16 inl, StringInfo *comp_str, StringInfo *out_str, guint *outl)
3940 {
3941     guint   pad, worklen, uncomplen;
3942     guint8 *mac;
3943
3944     ssl_debug_printf("ssl_decrypt_record ciphertext len %d\n", inl);
3945     ssl_print_data("Ciphertext",in, inl);
3946
3947     if ((ssl->session.version == TLSV1DOT3_VERSION) != (decoder->cipher_suite->kex == KEX_TLS13)) {
3948         ssl_debug_printf("%s Invalid cipher suite for the protocol version!\n", G_STRFUNC);
3949         return -1;
3950     }
3951
3952     /* ensure we have enough storage space for decrypted data */
3953     if (inl > out_str->data_len)
3954     {
3955         ssl_debug_printf("ssl_decrypt_record: allocating %d bytes for decrypt data (old len %d)\n",
3956                 inl + 32, out_str->data_len);
3957         ssl_data_realloc(out_str, inl + 32);
3958     }
3959
3960     /* AEAD ciphers (GenericAEADCipher in TLS 1.2; TLS 1.3) have no padding nor
3961      * a separate MAC, so use a different routine for simplicity. */
3962     if (decoder->cipher_suite->mode == MODE_GCM ||
3963         decoder->cipher_suite->mode == MODE_CCM ||
3964         decoder->cipher_suite->mode == MODE_CCM_8 ||
3965         ssl->session.version == TLSV1DOT3_VERSION) {
3966
3967         if (!tls_decrypt_aead_record(ssl, decoder, ct, record_version, in, inl, out_str, &worklen)) {
3968             /* decryption failed */
3969             return -1;
3970         }
3971
3972         goto skip_mac;
3973     }
3974
3975     /* RFC 6101/2246: SSLCipherText/TLSCipherText has two structures for types:
3976      * (notation: { unencrypted, [ encrypted ] })
3977      * GenericStreamCipher: { [content, mac] }
3978      * GenericBlockCipher: { IV (TLS 1.1+), [content, mac, padding, padding_len] }
3979      * RFC 5426 (TLS 1.2): TLSCipherText has additionally:
3980      * GenericAEADCipher: { nonce_explicit, [content] }
3981      * RFC 4347 (DTLS): based on TLS 1.1, only GenericBlockCipher is supported.
3982      * RFC 6347 (DTLS 1.2): based on TLS 1.2, includes GenericAEADCipher too.
3983      */
3984
3985     /* (TLS 1.1 and later, DTLS) Extract explicit IV for GenericBlockCipher */
3986     if (decoder->cipher_suite->mode == MODE_CBC) {
3987         guint blocksize;
3988
3989         switch (ssl->session.version) {
3990         case TLSV1DOT1_VERSION:
3991         case TLSV1DOT2_VERSION:
3992         case DTLSV1DOT0_VERSION:
3993         case DTLSV1DOT2_VERSION:
3994         case DTLSV1DOT0_OPENSSL_VERSION:
3995             blocksize = ssl_get_cipher_blocksize(decoder->cipher_suite);
3996             if (inl < blocksize) {
3997                 ssl_debug_printf("ssl_decrypt_record failed: input %d has no space for IV %d\n",
3998                         inl, blocksize);
3999                 return -1;
4000             }
4001             pad = gcry_cipher_setiv(decoder->evp, in, blocksize);
4002             if (pad != 0) {
4003                 ssl_debug_printf("ssl_decrypt_record failed: failed to set IV: %s %s\n",
4004                         gcry_strsource (pad), gcry_strerror (pad));
4005             }
4006
4007             inl -= blocksize;
4008             in += blocksize;
4009             break;
4010         }
4011     }
4012
4013     /* First decrypt*/
4014     if ((pad = ssl_cipher_decrypt(&decoder->evp, out_str->data, out_str->data_len, in, inl)) != 0) {
4015         ssl_debug_printf("ssl_decrypt_record failed: ssl_cipher_decrypt: %s %s\n", gcry_strsource (pad),
4016                     gcry_strerror (pad));
4017         return -1;
4018     }
4019
4020     ssl_print_data("Plaintext", out_str->data, inl);
4021     worklen=inl;
4022
4023
4024     /* strip padding for GenericBlockCipher */
4025     if (decoder->cipher_suite->mode == MODE_CBC) {
4026         if (inl < 1) { /* Should this check happen earlier? */
4027             ssl_debug_printf("ssl_decrypt_record failed: input length %d too small\n", inl);
4028             return -1;
4029         }
4030         pad=out_str->data[inl-1];
4031         if (worklen <= pad) {
4032             ssl_debug_printf("ssl_decrypt_record failed: padding %d too large for work %d\n",
4033                 pad, worklen);
4034             return -1;
4035         }
4036         worklen-=(pad+1);
4037         ssl_debug_printf("ssl_decrypt_record found padding %d final len %d\n",
4038             pad, worklen);
4039     }
4040
4041     /* MAC for GenericStreamCipher and GenericBlockCipher */
4042     if (ssl_cipher_suite_dig(decoder->cipher_suite)->len > (gint)worklen) {
4043         ssl_debug_printf("ssl_decrypt_record wrong record len/padding outlen %d\n work %d\n",*outl, worklen);
4044         return -1;
4045     }
4046     worklen -= ssl_cipher_suite_dig(decoder->cipher_suite)->len;
4047     mac = out_str->data + worklen;
4048
4049     /* If NULL encryption active and no keys are available, do not bother
4050      * checking the MAC. We do not have keys for that. */
4051     if (decoder->cipher_suite->mode == MODE_STREAM &&
4052             decoder->cipher_suite->enc == ENC_NULL &&
4053             !(ssl->state & SSL_MASTER_SECRET)) {
4054         ssl_debug_printf("MAC check skipped due to missing keys\n");
4055         goto skip_mac;
4056     }
4057
4058     /* Now check the MAC */
4059     ssl_debug_printf("checking mac (len %d, version %X, ct %d seq %" G_GUINT64_FORMAT ")\n",
4060         worklen, ssl->session.version, ct, decoder->seq);
4061     if(ssl->session.version==SSLV3_VERSION){
4062         if(ssl3_check_mac(decoder,ct,out_str->data,worklen,mac) < 0) {
4063             if(ssl_ignore_mac_failed) {
4064                 ssl_debug_printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
4065             }
4066             else{
4067                 ssl_debug_printf("ssl_decrypt_record: mac failed\n");
4068                 return -1;
4069             }
4070         }
4071         else{
4072             ssl_debug_printf("ssl_decrypt_record: mac ok\n");
4073         }
4074     }
4075     else if(ssl->session.version==TLSV1_VERSION || ssl->session.version==TLSV1DOT1_VERSION || ssl->session.version==TLSV1DOT2_VERSION){
4076         if(tls_check_mac(decoder,ct,ssl->session.version,out_str->data,worklen,mac)< 0) {
4077             if(ssl_ignore_mac_failed) {
4078                 ssl_debug_printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
4079             }
4080             else{
4081                 ssl_debug_printf("ssl_decrypt_record: mac failed\n");
4082                 return -1;
4083             }
4084         }
4085         else{
4086             ssl_debug_printf("ssl_decrypt_record: mac ok\n");
4087         }
4088     }
4089     else if(ssl->session.version==DTLSV1DOT0_VERSION ||
4090         ssl->session.version==DTLSV1DOT2_VERSION ||
4091         ssl->session.version==DTLSV1DOT0_OPENSSL_VERSION){
4092         /* Try rfc-compliant mac first, and if failed, try old openssl's non-rfc-compliant mac */
4093         if(dtls_check_mac(decoder,ct,ssl->session.version,out_str->data,worklen,mac)>= 0) {
4094             ssl_debug_printf("ssl_decrypt_record: mac ok\n");
4095         }
4096         else if(tls_check_mac(decoder,ct,TLSV1_VERSION,out_str->data,worklen,mac)>= 0) {
4097             ssl_debug_printf("ssl_decrypt_record: dtls rfc-compliant mac failed, but old openssl's non-rfc-compliant mac ok\n");
4098         }
4099         else if(ssl_ignore_mac_failed) {
4100             ssl_debug_printf("ssl_decrypt_record: mac failed, but ignored for troubleshooting ;-)\n");
4101         }
4102         else{
4103             ssl_debug_printf("ssl_decrypt_record: mac failed\n");
4104             return -1;
4105         }
4106     }
4107 skip_mac:
4108
4109     *outl = worklen;
4110
4111     if (decoder->compression > 0) {
4112         ssl_debug_printf("ssl_decrypt_record: compression method %d\n", decoder->compression);
4113         ssl_data_copy(comp_str, out_str);
4114         ssl_print_data("Plaintext compressed", comp_str->data, worklen);
4115         if (!decoder->decomp) {
4116             ssl_debug_printf("decrypt_ssl3_record: no decoder available\n");
4117             return -1;
4118         }
4119         if (ssl_decompress_record(decoder->decomp, comp_str->data, worklen, out_str, &uncomplen) < 0) return -1;
4120         ssl_print_data("Plaintext uncompressed", out_str->data, uncomplen);
4121         *outl = uncomplen;
4122     }
4123
4124     return 0;
4125 }
4126 /* Record decryption glue based on security parameters }}} */
4127
4128 #endif /* HAVE_LIBGCRYPT */
4129
4130
4131 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
4132 /* RSA private key file processing {{{ */
4133 #define RSA_PARS 6
4134 static gcry_sexp_t
4135 ssl_privkey_to_sexp(gnutls_x509_privkey_t priv_key)
4136 {
4137     gnutls_datum_t rsa_datum[RSA_PARS]; /* m, e, d, p, q, u */
4138     size_t         tmp_size;
4139     gcry_error_t   gret;
4140     gcry_sexp_t    rsa_priv_key = NULL;
4141     gint           i;
4142     gcry_mpi_t     rsa_params[RSA_PARS];
4143
4144     /* RSA get parameter */
4145     if (gnutls_x509_privkey_export_rsa_raw(priv_key,
4146                                            &rsa_datum[0],
4147                                            &rsa_datum[1],
4148                                            &rsa_datum[2],
4149                                            &rsa_datum[3],
4150                                            &rsa_datum[4],
4151                                            &rsa_datum[5])  != 0) {
4152         ssl_debug_printf("ssl_load_key: can't export rsa param (is a rsa private key file ?!?)\n");
4153         return NULL;
4154     }
4155
4156     /* convert each rsa parameter to mpi format*/
4157     for(i=0; i<RSA_PARS; i++) {
4158       gret = gcry_mpi_scan(&rsa_params[i], GCRYMPI_FMT_USG, rsa_datum[i].data, rsa_datum[i].size,&tmp_size);
4159       /* these buffers were allocated by gnutls_x509_privkey_export_rsa_raw() */
4160       g_free(rsa_datum[i].data);
4161       if (gret != 0) {
4162         ssl_debug_printf("ssl_load_key: can't convert m rsa param to int (size %d)\n", rsa_datum[i].size);
4163         return NULL;
4164       }
4165     }
4166
4167     /* libgcrypt expects p < q, and gnutls might not return it as such, depending on gnutls version and its crypto backend */
4168     if (gcry_mpi_cmp(rsa_params[3], rsa_params[4]) > 0)
4169     {
4170         ssl_debug_printf("ssl_load_key: swapping p and q parameters and recomputing u\n");
4171         /* p, q = q, p */
4172         gcry_mpi_swap(rsa_params[3], rsa_params[4]);
4173         /* due to swapping p and q, u = p^-1 mod p which happens to be needed. */
4174     }
4175     /* libgcrypt expects u = p^-1 mod q (for OpenPGP), but the u parameter
4176      * says u = q^-1 mod p. Recompute u = p^-1 mod q. Do this unconditionally as
4177      * at least GnuTLS 2.12.23 computes an invalid value. */
4178     gcry_mpi_invm(rsa_params[5], rsa_params[3], rsa_params[4]);
4179
4180     if  (gcry_sexp_build( &rsa_priv_key, NULL,
4181             "(private-key(rsa((n%m)(e%m)(d%m)(p%m)(q%m)(u%m))))", rsa_params[0],
4182             rsa_params[1], rsa_params[2], rsa_params[3], rsa_params[4],
4183             rsa_params[5]) != 0) {
4184         ssl_debug_printf("ssl_load_key: can't build rsa private key s-exp\n");
4185         return NULL;
4186     }
4187
4188     for (i=0; i< 6; i++)
4189         gcry_mpi_release(rsa_params[i]);
4190     return rsa_priv_key;
4191 }
4192
4193 /** Load an RSA private key from specified file
4194  @param fp the file that contain the key data
4195  @return a pointer to the loaded key on success, or NULL */
4196 static gnutls_x509_privkey_t
4197 ssl_load_key(FILE* fp)
4198 {
4199     /* gnutls makes our work much harder, since we have to work internally with
4200      * s-exp formatted data, but PEM loader exports only in "gnutls_datum_t"
4201      * format, and a datum -> s-exp convertion function does not exist.
4202      */
4203     gnutls_x509_privkey_t priv_key;
4204     gnutls_datum_t        key;
4205     ws_statb64            statbuf;
4206     gint                  ret;
4207     guint                 bytes;
4208
4209     if (ws_fstat64(ws_fileno(fp), &statbuf) == -1) {
4210         ssl_debug_printf("ssl_load_key: can't ws_fstat64 file\n");
4211         return NULL;
4212     }
4213     if (S_ISDIR(statbuf.st_mode)) {
4214         ssl_debug_printf("ssl_load_key: file is a directory\n");
4215         errno = EISDIR;
4216         return NULL;
4217     }
4218     if (S_ISFIFO(statbuf.st_mode)) {
4219         ssl_debug_printf("ssl_load_key: file is a named pipe\n");
4220         errno = EINVAL;
4221         return NULL;
4222     }
4223     if (!S_ISREG(statbuf.st_mode)) {
4224         ssl_debug_printf("ssl_load_key: file is not a regular file\n");
4225         errno = EINVAL;
4226         return NULL;
4227     }
4228     /* XXX - check for a too-big size */
4229     /* load all file contents into a datum buffer*/
4230     key.data = (unsigned char *)g_malloc((size_t)statbuf.st_size);
4231     key.size = (int)statbuf.st_size;
4232     bytes = (guint) fread(key.data, 1, key.size, fp);
4233     if (bytes < key.size) {
4234         ssl_debug_printf("ssl_load_key: can't read from file %d bytes, got %d\n",
4235             key.size, bytes);
4236         g_free(key.data);
4237         return NULL;
4238     }
4239
4240     /* init private key data*/
4241     gnutls_x509_privkey_init(&priv_key);
4242
4243     /* import PEM data*/
4244     if ((ret = gnutls_x509_privkey_import(priv_key, &key, GNUTLS_X509_FMT_PEM)) != GNUTLS_E_SUCCESS) {
4245         ssl_debug_printf("ssl_load_key: can't import pem data: %s\n", gnutls_strerror(ret));
4246         g_free(key.data);
4247         return NULL;
4248     }
4249
4250     if (gnutls_x509_privkey_get_pk_algorithm(priv_key) != GNUTLS_PK_RSA) {
4251         ssl_debug_printf("ssl_load_key: private key public key algorithm isn't RSA\n");
4252         g_free(key.data);
4253         return NULL;
4254     }
4255
4256     g_free(key.data);
4257
4258     return priv_key;
4259 }
4260
4261 static const char *
4262 BAGTYPE(gnutls_pkcs12_bag_type_t x) {
4263     switch (x) {
4264         case GNUTLS_BAG_EMPTY:               return "Empty";
4265         case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: return "PKCS#8 Encrypted key";
4266         case GNUTLS_BAG_PKCS8_KEY:           return "PKCS#8 Key";
4267         case GNUTLS_BAG_CERTIFICATE:         return "Certificate";
4268         case GNUTLS_BAG_CRL:                 return "CRL";
4269         case GNUTLS_BAG_ENCRYPTED:           return "Encrypted";
4270         case GNUTLS_BAG_UNKNOWN:             return "Unknown";
4271         default:                             return "<undefined>";
4272     }
4273 }
4274
4275 /**
4276  * Load a RSA private key from a PKCS#12 file.
4277  * @param fp the file that contains the key data.
4278  * @param cert_passwd password to decrypt the PKCS#12 file.
4279  * @param[out] err error message upon failure; NULL upon success.
4280  * @return a pointer to the loaded key on success; NULL upon failure.
4281  */
4282 static gnutls_x509_privkey_t
4283 ssl_load_pkcs12(FILE* fp, const gchar *cert_passwd, char** err) {
4284
4285     int                       i, j, ret;
4286     int                       rest;
4287     unsigned char            *p;
4288     gnutls_datum_t            data;
4289     gnutls_pkcs12_bag_t       bag = NULL;
4290     gnutls_pkcs12_bag_type_t  bag_type;
4291     size_t                    len;
4292
4293     gnutls_pkcs12_t       ssl_p12  = NULL;
4294     gnutls_x509_privkey_t ssl_pkey = NULL;
4295
4296     gnutls_x509_privkey_t     priv_key = NULL;
4297     *err = NULL;
4298
4299     rest = 4096;
4300     data.data = (unsigned char *)g_malloc(rest);
4301     data.size = rest;
4302     p = data.data;
4303     while ((len = fread(p, 1, rest, fp)) > 0) {
4304         p += len;
4305         rest -= (int) len;
4306         if (!rest) {
4307             rest = 1024;
4308             data.data = (unsigned char *)g_realloc(data.data, data.size + rest);
4309             p = data.data + data.size;
4310             data.size += rest;
4311         }
4312     }
4313     data.size -= rest;
4314     ssl_debug_printf("%d bytes read\n", data.size);
4315     if (!feof(fp)) {
4316         *err = g_strdup("Error during certificate reading.");
4317         ssl_debug_printf("%s\n", *err);
4318         g_free(data.data);
4319         return 0;
4320     }
4321
4322     ret = gnutls_pkcs12_init(&ssl_p12);
4323     if (ret < 0) {
4324         *err = g_strdup_printf("gnutls_pkcs12_init(&st_p12) - %s", gnutls_strerror(ret));
4325         ssl_debug_printf("%s\n", *err);
4326         g_free(data.data);
4327         return 0;
4328     }
4329
4330     /* load PKCS#12 in DER or PEM format */
4331     ret = gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_DER, 0);
4332     if (ret < 0) {
4333         *err = g_strdup_printf("could not load PKCS#12 in DER format: %s", gnutls_strerror(ret));
4334         ssl_debug_printf("%s\n", *err);
4335         g_free(*err);
4336
4337         ret = gnutls_pkcs12_import(ssl_p12, &data, GNUTLS_X509_FMT_PEM, 0);
4338         if (ret < 0) {
4339             *err = g_strdup_printf("could not load PKCS#12 in PEM format: %s", gnutls_strerror(ret));
4340             ssl_debug_printf("%s\n", *err);
4341         } else {
4342             *err = NULL;
4343         }
4344     }
4345     g_free(data.data);
4346     if (ret < 0) {
4347         return 0;
4348     }
4349
4350     ssl_debug_printf( "PKCS#12 imported\n");
4351
4352     /* TODO: Use gnutls_pkcs12_simple_parse, since 3.1.0 (August 2012) */
4353     for (i=0; ; i++) {
4354
4355         ret = gnutls_pkcs12_bag_init(&bag);
4356         if (ret < 0) break;
4357
4358         ret = gnutls_pkcs12_get_bag(ssl_p12, i, bag);
4359         if (ret < 0) break;
4360
4361         for (j=0; j<gnutls_pkcs12_bag_get_count(bag); j++) {
4362
4363             ret = gnutls_pkcs12_bag_get_type(bag, j);
4364             if (ret < 0) goto done;
4365             bag_type = (gnutls_pkcs12_bag_type_t)ret;
4366             if (bag_type >= GNUTLS_BAG_UNKNOWN) goto done;
4367             ssl_debug_printf( "Bag %d/%d: %s\n", i, j, BAGTYPE(bag_type));
4368             if (bag_type == GNUTLS_BAG_ENCRYPTED) {
4369                 ret = gnutls_pkcs12_bag_decrypt(bag, cert_passwd);
4370                 if (ret == 0) {
4371                     ret = gnutls_pkcs12_bag_get_type(bag, j);
4372                     if (ret < 0) goto done;
4373                     bag_type = (gnutls_pkcs12_bag_type_t)ret;
4374                     if (bag_type >= GNUTLS_BAG_UNKNOWN) goto done;
4375                     ssl_debug_printf( "Bag %d/%d decrypted: %s\n", i, j, BAGTYPE(bag_type));
4376                 }
4377             }
4378
4379             ret = gnutls_pkcs12_bag_get_data(bag, j, &data);
4380             if (ret < 0) goto done;
4381
4382             switch (bag_type) {
4383
4384                 case GNUTLS_BAG_PKCS8_KEY:
4385                 case GNUTLS_BAG_PKCS8_ENCRYPTED_KEY:
4386
4387                     ret = gnutls_x509_privkey_init(&ssl_pkey);
4388                     if (ret < 0) {
4389                         *err = g_strdup_printf("gnutls_x509_privkey_init(&ssl_pkey) - %s", gnutls_strerror(ret));
4390                         ssl_debug_printf("%s\n", *err);
4391                         goto done;
4392                     }
4393                     ret = gnutls_x509_privkey_import_pkcs8(ssl_pkey, &data, GNUTLS_X509_FMT_DER, cert_passwd,
4394                                                            (bag_type==GNUTLS_BAG_PKCS8_KEY) ? GNUTLS_PKCS_PLAIN : 0);
4395                     if (ret < 0) {
4396                         *err = g_strdup_printf("Can not decrypt private key - %s", gnutls_strerror(ret));
4397                         ssl_debug_printf("%s\n", *err);
4398                         goto done;
4399                     }
4400
4401                     if (gnutls_x509_privkey_get_pk_algorithm(ssl_pkey) != GNUTLS_PK_RSA) {
4402                         *err = g_strdup("ssl_load_pkcs12: private key public key algorithm isn't RSA");
4403                         ssl_debug_printf("%s\n", *err);
4404                         goto done;
4405                     }
4406
4407                     /* Private key found, return it. */
4408                     priv_key = ssl_pkey;
4409                     goto done;
4410
4411                 default: ;
4412             }
4413         }  /* j */
4414         if (bag) { gnutls_pkcs12_bag_deinit(bag); bag = NULL; }
4415     }  /* i */
4416
4417 done:
4418     if (!priv_key && ssl_pkey)
4419         gnutls_x509_privkey_deinit(ssl_pkey);
4420     if (bag)
4421         gnutls_pkcs12_bag_deinit(bag);
4422
4423     return priv_key;
4424 }
4425
4426
4427 void
4428 ssl_private_key_free(gpointer key)
4429 {
4430     gcry_sexp_release((gcry_sexp_t) key);
4431 }
4432
4433 static void
4434 ssl_find_private_key_by_pubkey(SslDecryptSession *ssl, GHashTable *key_hash,
4435                                gnutls_datum_t *subjectPublicKeyInfo)
4436 {
4437     gnutls_pubkey_t pubkey = NULL;
4438     guchar key_id[20];
4439     size_t key_id_len = sizeof(key_id);
4440     int r;
4441
4442     if (!subjectPublicKeyInfo->size) {
4443         ssl_debug_printf("%s: could not find SubjectPublicKeyInfo\n", G_STRFUNC);
4444         return;
4445     }
4446
4447     r = gnutls_pubkey_init(&pubkey);
4448     if (r < 0) {
4449         ssl_debug_printf("%s: failed to init pubkey: %s\n",
4450                 G_STRFUNC, gnutls_strerror(r));
4451         return;
4452     }
4453
4454     r = gnutls_pubkey_import(pubkey, subjectPublicKeyInfo, GNUTLS_X509_FMT_DER);
4455     if (r < 0) {
4456         ssl_debug_printf("%s: failed to import pubkey from handshake: %s\n",
4457                 G_STRFUNC, gnutls_strerror(r));
4458         goto end;
4459     }
4460
4461     /* Generate a 20-byte SHA-1 hash. */
4462     r = gnutls_pubkey_get_key_id(pubkey, 0, key_id, &key_id_len);
4463     if (r < 0) {
4464         ssl_debug_printf("%s: failed to extract key id from pubkey: %s\n",
4465                 G_STRFUNC, gnutls_strerror(r));
4466         goto end;
4467     }
4468
4469     ssl_print_data("lookup(KeyID)", key_id, key_id_len);
4470     ssl->private_key = (gcry_sexp_t)g_hash_table_lookup(key_hash, key_id);
4471     ssl_debug_printf("%s: lookup result: %p\n", G_STRFUNC, (void *) ssl->private_key);
4472
4473 end:
4474     gnutls_pubkey_deinit(pubkey);
4475 }
4476
4477 /* RSA private key file processing }}} */
4478
4479 #else /* ! (defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)) */
4480 void
4481 ssl_private_key_free(gpointer key _U_)
4482 {
4483 }
4484 #endif /* ! (defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)) */
4485
4486
4487 /*--- Start of dissector-related code below ---*/
4488
4489 /* get ssl data for this session. if no ssl data is found allocate a new one*/
4490 SslDecryptSession *
4491 ssl_get_session(conversation_t *conversation, dissector_handle_t ssl_handle)
4492 {
4493     void               *conv_data;
4494     SslDecryptSession  *ssl_session;
4495     int                 proto_ssl;
4496
4497     proto_ssl = dissector_handle_get_protocol_index(ssl_handle);
4498     conv_data = conversation_get_proto_data(conversation, proto_ssl);
4499     if (conv_data != NULL)
4500         return (SslDecryptSession *)conv_data;
4501
4502     /* no previous SSL conversation info, initialize it. */
4503     ssl_session = wmem_new0(wmem_file_scope(), SslDecryptSession);
4504
4505     /* data_len is the part that is meaningful, not the allocated length */
4506     ssl_session->master_secret.data_len = 0;
4507     ssl_session->master_secret.data = ssl_session->_master_secret;
4508     ssl_session->session_id.data_len = 0;
4509     ssl_session->session_id.data = ssl_session->_session_id;
4510     ssl_session->client_random.data_len = 0;
4511     ssl_session->client_random.data = ssl_session->_client_random;
4512     ssl_session->server_random.data_len = 0;
4513     ssl_session->server_random.data = ssl_session->_server_random;
4514     ssl_session->session_ticket.data_len = 0;
4515     ssl_session->session_ticket.data = NULL; /* will be re-alloced as needed */
4516     ssl_session->server_data_for_iv.data_len = 0;
4517     ssl_session->server_data_for_iv.data = ssl_session->_server_data_for_iv;
4518     ssl_session->client_data_for_iv.data_len = 0;
4519     ssl_session->client_data_for_iv.data = ssl_session->_client_data_for_iv;
4520     ssl_session->app_data_segment.data = NULL;
4521     ssl_session->app_data_segment.data_len = 0;
4522     ssl_session->handshake_data.data=NULL;
4523     ssl_session->handshake_data.data_len=0;
4524
4525     /* Initialize parameters which are not necessary specific to decryption. */
4526     ssl_session->session.version = SSL_VER_UNKNOWN;
4527     clear_address(&ssl_session->session.srv_addr);
4528     ssl_session->session.srv_ptype = PT_NONE;
4529     ssl_session->session.srv_port = 0;
4530
4531     conversation_add_proto_data(conversation, proto_ssl, ssl_session);
4532     return ssl_session;
4533 }
4534
4535 /* Resets the decryption parameters for the next decoder. */
4536 static void ssl_reset_session(SslSession *session, SslDecryptSession *ssl, gboolean is_client)
4537 {
4538     if (ssl) {
4539         /* Ensure that secrets are not restored using stale identifiers. Split
4540          * between client and server in case the packets somehow got out of order. */
4541         gint clear_flags = SSL_HAVE_SESSION_KEY | SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET;
4542
4543         if (is_client) {
4544             clear_flags |= SSL_CLIENT_EXTENDED_MASTER_SECRET;
4545             ssl->session_id.data_len = 0;
4546             ssl->session_ticket.data_len = 0;
4547             ssl->master_secret.data_len = 0;
4548             ssl->client_random.data_len = 0;
4549         } else {
4550             clear_flags |= SSL_SERVER_EXTENDED_MASTER_SECRET | SSL_NEW_SESSION_TICKET;
4551             ssl->server_random.data_len = 0;
4552             ssl->pre_master_secret.data_len = 0;
4553 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
4554             ssl->private_key = NULL;
4555 #endif
4556             ssl->psk.data_len = 0;
4557         }
4558
4559         if (ssl->state & clear_flags) {
4560             ssl_debug_printf("%s detected renegotiation, clearing 0x%02x (%s side)\n",
4561                     G_STRFUNC, ssl->state & clear_flags, is_client ? "client" : "server");
4562             ssl->state &= ~clear_flags;
4563         }
4564     }
4565
4566     /* These flags might be used for non-decryption purposes and may affect the
4567      * dissection, so reset them as well. */
4568     if (is_client) {
4569         session->client_cert_type = 0;
4570     } else {
4571         session->compression = 0;
4572         session->server_cert_type = 0;
4573         /* session->is_session_resumed is already handled in the ServerHello dissection. */
4574     }
4575 }
4576
4577 static guint32
4578 ssl_starttls(dissector_handle_t ssl_handle, packet_info *pinfo,
4579                  dissector_handle_t app_handle, guint32 last_nontls_frame)
4580 {
4581     conversation_t  *conversation;
4582     SslSession      *session;
4583
4584     /* Ignore if the SSL dissector is disabled. */
4585     if (!ssl_handle)
4586         return 0;
4587     /* The caller should always pass a valid handle to its own dissector. */
4588     DISSECTOR_ASSERT(app_handle);
4589
4590     conversation = find_or_create_conversation(pinfo);
4591     session = &ssl_get_session(conversation, ssl_handle)->session;
4592
4593     ssl_debug_printf("%s: old frame %d, app_handle=%p (%s)\n", G_STRFUNC,
4594                      session->last_nontls_frame,
4595                      (void *)session->app_handle,
4596                      dissector_handle_get_dissector_name(session->app_handle));
4597     ssl_debug_printf("%s: current frame %d, app_handle=%p (%s)\n", G_STRFUNC,
4598                      pinfo->num, (void *)app_handle,
4599                      dissector_handle_get_dissector_name(app_handle));
4600
4601     /* Do not switch again if a dissector did it before. */
4602     if (session->last_nontls_frame) {
4603         ssl_debug_printf("%s: not overriding previous app handle!\n", G_STRFUNC);
4604         return session->last_nontls_frame;
4605     }
4606
4607     session->app_handle = app_handle;
4608     /* The SSL dissector should be called first for this conversation. */
4609     conversation_set_dissector(conversation, ssl_handle);
4610     /* SSL starts after this frame. */
4611     session->last_nontls_frame = last_nontls_frame;
4612     return 0;
4613 } /* }}} */
4614
4615 /* ssl_starttls_ack: mark future frames as encrypted. {{{ */
4616 guint32
4617 ssl_starttls_ack(dissector_handle_t ssl_handle, packet_info *pinfo,
4618                  dissector_handle_t app_handle)
4619 {
4620     return ssl_starttls(ssl_handle, pinfo, app_handle, pinfo->num);
4621 }
4622
4623 guint32
4624 ssl_starttls_post_ack(dissector_handle_t ssl_handle, packet_info *pinfo,
4625                  dissector_handle_t app_handle)
4626 {
4627     return ssl_starttls(ssl_handle, pinfo, app_handle, pinfo->num - 1);
4628 }
4629
4630 dissector_handle_t
4631 ssl_find_appdata_dissector(const char *name)
4632 {
4633     /* Accept 'http' for backwards compatibility and sanity. */
4634     if (!strcmp(name, "http"))
4635         name = "http-over-tls";
4636     return find_dissector(name);
4637 }
4638
4639 /* Functions for TLS/DTLS sessions and RSA private keys hashtables. {{{ */
4640 static gint
4641 ssl_equal (gconstpointer v, gconstpointer v2)
4642 {
4643     const StringInfo *val1;
4644     const StringInfo *val2;
4645     val1 = (const StringInfo *)v;
4646     val2 = (const StringInfo *)v2;
4647
4648     if (val1->data_len == val2->data_len &&
4649         !memcmp(val1->data, val2->data, val2->data_len)) {
4650         return 1;
4651     }
4652     return 0;
4653 }
4654
4655 static guint
4656 ssl_hash  (gconstpointer v)
4657 {
4658     guint l,hash;
4659     const StringInfo* id;
4660     const guint* cur;
4661     hash = 0;
4662     id = (const StringInfo*) v;
4663
4664     /*  id and id->data are mallocated in ssl_save_master_key().  As such 'data'
4665      *  should be aligned for any kind of access (for example as a guint as
4666      *  is done below).  The intermediate void* cast is to prevent "cast
4667      *  increases required alignment of target type" warnings on CPUs (such
4668      *  as SPARCs) that do not allow misaligned memory accesses.
4669      */
4670     cur = (const guint*)(void*) id->data;
4671
4672     for (l=4; (l < id->data_len); l+=4, cur++)
4673         hash = hash ^ (*cur);
4674
4675     return hash;
4676 }
4677
4678 gboolean
4679 ssl_private_key_equal (gconstpointer v, gconstpointer v2)
4680 {
4681     /* key ID length (SHA-1 hash, per GNUTLS_KEYID_USE_SHA1) */
4682     return !memcmp(v, v2, 20);
4683 }
4684
4685 guint
4686 ssl_private_key_hash (gconstpointer v)
4687 {
4688     guint        l, hash = 0;
4689     const guint8 *cur = (const guint8 *)v;
4690
4691     /* The public key' SHA-1 hash (which maps to a private key) has a uniform
4692      * distribution, hence simply xor'ing them should be sufficient. */
4693     for (l = 0; l < 20; l += 4, cur += 4)
4694         hash ^= pntoh32(cur);
4695
4696     return hash;
4697 }
4698 /* Functions for TLS/DTLS sessions and RSA private keys hashtables. }}} */
4699
4700 /* Handling of association between tls/dtls ports and clear text protocol. {{{ */
4701 void
4702 ssl_association_add(const char* dissector_table_name, dissector_handle_t main_handle, dissector_handle_t subdissector_handle, guint port, gboolean tcp)
4703 {
4704     DISSECTOR_ASSERT(main_handle);
4705     DISSECTOR_ASSERT(subdissector_handle);
4706     /* Registration is required for Export PDU feature to work properly. */
4707     DISSECTOR_ASSERT_HINT(dissector_handle_get_dissector_name(subdissector_handle),
4708             "SSL appdata dissectors must register with register_dissector()!");
4709     ssl_debug_printf("association_add %s port %d handle %p\n", dissector_table_name, port, (void *)subdissector_handle);
4710
4711     if (port) {
4712         dissector_add_uint(dissector_table_name, port, subdissector_handle);
4713         if (tcp)
4714             dissector_add_uint("tcp.port", port, main_handle);
4715         else
4716             dissector_add_uint("udp.port", port, main_handle);
4717         dissector_add_uint("sctp.port", port, main_handle);
4718     } else {
4719         dissector_add_for_decode_as(dissector_table_name, subdissector_handle);
4720     }
4721 }
4722
4723 void
4724 ssl_association_remove(const char* dissector_table_name, dissector_handle_t main_handle, dissector_handle_t subdissector_handle, guint port, gboolean tcp)
4725 {
4726     ssl_debug_printf("ssl_association_remove removing %s %u - handle %p\n",
4727                      tcp?"TCP":"UDP", port, (void *)subdissector_handle);
4728     if (main_handle) {
4729         dissector_delete_uint(tcp?"tcp.port":"udp.port", port, main_handle);
4730         dissector_delete_uint("sctp.port", port, main_handle);
4731     }
4732
4733     if (port) {
4734         dissector_delete_uint(dissector_table_name, port, subdissector_handle);
4735     }
4736 }
4737
4738 void
4739 ssl_set_server(SslSession *session, address *addr, port_type ptype, guint32 port)
4740 {
4741     copy_address_wmem(wmem_file_scope(), &session->srv_addr, addr);
4742     session->srv_ptype = ptype;
4743     session->srv_port = port;
4744 }
4745
4746 int
4747 ssl_packet_from_server(SslSession *session, dissector_table_t table, packet_info *pinfo)
4748 {
4749     gint ret;
4750     if (session->srv_addr.type != AT_NONE) {
4751         ret = (session->srv_ptype == pinfo->ptype) &&
4752               (session->srv_port == pinfo->srcport) &&
4753               addresses_equal(&session->srv_addr, &pinfo->src);
4754     } else {
4755         ret = (dissector_get_uint_handle(table, pinfo->srcport) != 0);
4756     }
4757
4758     ssl_debug_printf("packet_from_server: is from server - %s\n", (ret)?"TRUE":"FALSE");
4759     return ret;
4760 }
4761 /* Handling of association between tls/dtls ports and clear text protocol. }}} */
4762
4763
4764 /* Links SSL records with the real packet data. {{{ */
4765 /**
4766  * Remembers the decrypted TLS record fragment (TLSInnerPlaintext in TLS 1.3) to
4767  * avoid the need for a decoder in the second pass. Additionally, it remembers
4768  * sequence numbers (for reassembly and Follow SSL Stream).
4769  *
4770  * @param proto The protocol identifier (proto_ssl or proto_dtls).
4771  * @param pinfo The packet where the record originates from.
4772  * @param data Decrypted data to store in the record.
4773  * @param data_len Length of decrypted record data.
4774  * @param record_id The identifier for this record within the current packet.
4775  * @param flow Information about sequence numbers, etc.
4776  * @param type TLS Content Type (such as handshake or application_data).
4777  */
4778 void
4779 ssl_add_record_info(gint proto, packet_info *pinfo, const guchar *data, gint data_len, gint record_id, SslFlow *flow, ContentType type)
4780 {
4781     SslRecordInfo* rec, **prec;
4782     SslPacketInfo* pi;
4783
4784     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto, 0);
4785     if (!pi)
4786     {
4787         pi = wmem_new0(wmem_file_scope(), SslPacketInfo);
4788         p_add_proto_data(wmem_file_scope(), pinfo, proto, 0, pi);
4789     }
4790
4791     rec = wmem_new(wmem_file_scope(), SslRecordInfo);
4792     rec->plain_data = (guchar *)wmem_memdup(wmem_file_scope(), data, data_len);
4793     rec->data_len = data_len;
4794     rec->id = record_id;
4795     rec->type = type;
4796     rec->next = NULL;
4797
4798     /* TODO allow Handshake records also to be reassembled. There needs to be
4799      * one "flow" for each record type (appdata, handshake). "seq" for the
4800      * record should then be relative within this flow. */
4801     if (flow && type == SSL_ID_APP_DATA) {
4802         rec->seq = flow->byte_seq;
4803         rec->flow = flow;
4804         flow->byte_seq += data_len;
4805         ssl_debug_printf("%s stored decrypted record seq=%d nxtseq=%d flow=%p\n",
4806                          G_STRFUNC, rec->seq, rec->seq + data_len, (void*)flow);
4807     }
4808
4809     /* Remember decrypted records. */
4810     prec = &pi->records;
4811     while (*prec) prec = &(*prec)->next;
4812     *prec = rec;
4813 }
4814
4815 /* search in packet data for the specified id; return a newly created tvb for the associated data */
4816 tvbuff_t*
4817 ssl_get_record_info(tvbuff_t *parent_tvb, int proto, packet_info *pinfo, gint record_id, SslRecordInfo **matched_record)
4818 {
4819     SslRecordInfo* rec;
4820     SslPacketInfo* pi;
4821     pi = (SslPacketInfo *)p_get_proto_data(wmem_file_scope(), pinfo, proto, 0);
4822
4823     if (!pi)
4824         return NULL;
4825
4826     for (rec = pi->records; rec; rec = rec->next)
4827         if (rec->id == record_id) {
4828             *matched_record = rec;
4829             /* link new real_data_tvb with a parent tvb so it is freed when frame dissection is complete */
4830             return tvb_new_child_real_data(parent_tvb, rec->plain_data, rec->data_len, rec->data_len);
4831         }
4832
4833     return NULL;
4834 }
4835 /* Links SSL records with the real packet data. }}} */
4836
4837 /* initialize/reset per capture state data (ssl sessions cache). {{{ */
4838 void
4839 ssl_common_init(ssl_master_key_map_t *mk_map,
4840                 StringInfo *decrypted_data, StringInfo *compressed_data)
4841 {
4842     mk_map->session = g_hash_table_new(ssl_hash, ssl_equal);
4843     mk_map->tickets = g_hash_table_new(ssl_hash, ssl_equal);
4844     mk_map->crandom = g_hash_table_new(ssl_hash, ssl_equal);
4845     mk_map->pre_master = g_hash_table_new(ssl_hash, ssl_equal);
4846     mk_map->pms = g_hash_table_new(ssl_hash, ssl_equal);
4847     mk_map->tls13_client_handshake = g_hash_table_new(ssl_hash, ssl_equal);
4848     mk_map->tls13_server_handshake = g_hash_table_new(ssl_hash, ssl_equal);
4849     mk_map->tls13_client_appdata = g_hash_table_new(ssl_hash, ssl_equal);
4850     mk_map->tls13_server_appdata = g_hash_table_new(ssl_hash, ssl_equal);
4851     ssl_data_alloc(decrypted_data, 32);
4852     ssl_data_alloc(compressed_data, 32);
4853 }
4854
4855 void
4856 ssl_common_cleanup(ssl_master_key_map_t *mk_map, FILE **ssl_keylog_file,
4857                    StringInfo *decrypted_data, StringInfo *compressed_data)
4858 {
4859     g_hash_table_destroy(mk_map->session);
4860     g_hash_table_destroy(mk_map->tickets);
4861     g_hash_table_destroy(mk_map->crandom);
4862     g_hash_table_destroy(mk_map->pre_master);
4863     g_hash_table_destroy(mk_map->pms);
4864     g_hash_table_destroy(mk_map->tls13_client_handshake);
4865     g_hash_table_destroy(mk_map->tls13_server_handshake);
4866     g_hash_table_destroy(mk_map->tls13_client_appdata);
4867     g_hash_table_destroy(mk_map->tls13_server_appdata);
4868
4869     g_free(decrypted_data->data);
4870     g_free(compressed_data->data);
4871
4872     /* close the previous keylog file now that the cache are cleared, this
4873      * allows the cache to be filled with the full keylog file contents. */
4874     if (*ssl_keylog_file) {
4875         fclose(*ssl_keylog_file);
4876         *ssl_keylog_file = NULL;
4877     }
4878 }
4879 /* }}} */
4880
4881 /* parse ssl related preferences (private keys and ports association strings) */
4882 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
4883 /* Load a single RSA key file item from preferences. {{{ */
4884 void
4885 ssl_parse_key_list(const ssldecrypt_assoc_t *uats, GHashTable *key_hash, const char* dissector_table_name, dissector_handle_t main_handle, gboolean tcp)
4886 {
4887     gnutls_x509_privkey_t priv_key;
4888     gcry_sexp_t        private_key;
4889     FILE*              fp     = NULL;
4890     int                ret;
4891     size_t             key_id_len = 20;
4892     guchar            *key_id = NULL;
4893     dissector_handle_t handle;
4894     /* try to load keys file first */
4895     fp = ws_fopen(uats->keyfile, "rb");
4896     if (!fp) {
4897         report_open_failure(uats->keyfile, errno, FALSE);
4898         return;
4899     }
4900
4901     if ((gint)strlen(uats->password) == 0) {
4902         priv_key = ssl_load_key(fp);
4903     } else {
4904         char *err = NULL;
4905         priv_key = ssl_load_pkcs12(fp, uats->password, &err);
4906         if (err) {
4907             report_failure("%s\n", err);
4908             g_free(err);
4909         }
4910     }
4911     fclose(fp);
4912
4913     if (!priv_key) {
4914         report_failure("Can't load private key from %s\n", uats->keyfile);
4915         return;
4916     }
4917
4918     key_id = (guchar *) g_malloc0(key_id_len);
4919     ret = gnutls_x509_privkey_get_key_id(priv_key, 0, key_id, &key_id_len);
4920     if (ret < 0) {
4921         report_failure("Can't calculate public key ID for %s: %s",
4922                 uats->keyfile, gnutls_strerror(ret));
4923         goto end;
4924     }
4925     ssl_print_data("KeyID", key_id, key_id_len);
4926
4927     private_key = ssl_privkey_to_sexp(priv_key);
4928     if (!private_key) {
4929         report_failure("Can't extract private key parameters for %s", uats->keyfile);
4930         goto end;
4931     }
4932
4933     g_hash_table_replace(key_hash, key_id, private_key);
4934     key_id = NULL; /* used in key_hash, do not free. */
4935     ssl_debug_printf("ssl_init private key file %s successfully loaded.\n", uats->keyfile);
4936
4937     handle = ssl_find_appdata_dissector(uats->protocol);
4938     if (handle) {
4939         /* Port to subprotocol mapping */
4940         guint16 port = 0;
4941         if (ws_strtou16(uats->port, NULL, &port)) {
4942             if (port > 0) {
4943                 ssl_debug_printf("ssl_init port '%d' filename '%s' password(only for p12 file) '%s'\n",
4944                     port, uats->keyfile, uats->password);
4945
4946                 ssl_association_add(dissector_table_name, main_handle, handle, port, tcp);
4947             }
4948         } else {
4949             if (strcmp(uats->port, "start_tls"))
4950                 ssl_debug_printf("invalid ssl_init_port: %s\n", uats->port);
4951         }
4952     }
4953
4954 end:
4955     gnutls_x509_privkey_deinit(priv_key);
4956     g_free(key_id);
4957 }
4958 /* }}} */
4959 #else
4960 void
4961 ssl_parse_key_list(const ssldecrypt_assoc_t *uats _U_, GHashTable *key_hash _U_, const char* dissector_table_name _U_, dissector_handle_t main_handle _U_, gboolean tcp _U_)
4962 {
4963     report_failure("Can't load private key files, support is not compiled in.");
4964 }
4965 #endif
4966
4967
4968 #ifdef HAVE_LIBGCRYPT /* useless without decryption support. */
4969 /* Store/load a known (pre-)master secret from/for this SSL session. {{{ */
4970 /** store a known (pre-)master secret into cache */
4971 static void
4972 ssl_save_master_key(const char *label, GHashTable *ht, StringInfo *key,
4973                     StringInfo *mk)
4974 {
4975     StringInfo *ht_key, *master_secret;
4976
4977     if (key->data_len == 0) {
4978         ssl_debug_printf("%s: not saving empty %s!\n", G_STRFUNC, label);
4979         return;
4980     }
4981
4982     if (mk->data_len == 0) {
4983         ssl_debug_printf("%s not saving empty (pre-)master secret for %s!\n",
4984                          G_STRFUNC, label);
4985         return;
4986     }
4987
4988     /* ssl_hash() depends on session_ticket->data being aligned for guint access
4989      * so be careful in changing how it is allocated. */
4990     ht_key = ssl_data_clone(key);
4991     master_secret = ssl_data_clone(mk);
4992     g_hash_table_insert(ht, ht_key, master_secret);
4993
4994     ssl_debug_printf("%s inserted (pre-)master secret for %s\n", G_STRFUNC, label);
4995     ssl_print_string("stored key", ht_key);
4996     ssl_print_string("stored (pre-)master secret", master_secret);
4997 }
4998
4999 /** restore a (pre-)master secret given some key in the cache */
5000 static gboolean
5001 ssl_restore_master_key(SslDecryptSession *ssl, const char *label,
5002                        gboolean is_pre_master, GHashTable *ht, StringInfo *key)
5003 {
5004     StringInfo *ms;
5005
5006     if (key->data_len == 0) {
5007         ssl_debug_printf("%s can't restore %smaster secret using an empty %s\n",
5008                          G_STRFUNC, is_pre_master ? "pre-" : "", label);
5009         return FALSE;
5010     }
5011
5012     ms = (StringInfo *)g_hash_table_lookup(ht, key);
5013     if (!ms) {
5014         ssl_debug_printf("%s can't find %smaster secret by %s\n", G_STRFUNC,
5015                          is_pre_master ? "pre-" : "", label);
5016         return FALSE;
5017     }
5018
5019     /* (pre)master secret found, clear knowledge of other keys and set it in the
5020      * current conversation */
5021     ssl->state &= ~(SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET |
5022                     SSL_HAVE_SESSION_KEY);
5023     if (is_pre_master) {
5024         /* unlike master secret, pre-master secret has a variable size (48 for
5025          * RSA, varying for PSK) and is therefore not statically allocated */
5026         ssl->pre_master_secret.data = (guchar *) wmem_alloc(wmem_file_scope(),
5027                                                             ms->data_len);
5028         ssl_data_set(&ssl->pre_master_secret, ms->data, ms->data_len);
5029         ssl->state |= SSL_PRE_MASTER_SECRET;
5030     } else {
5031         ssl_data_set(&ssl->master_secret, ms->data, ms->data_len);
5032         ssl->state |= SSL_MASTER_SECRET;
5033     }
5034     ssl_debug_printf("%s %smaster secret retrieved using %s\n", G_STRFUNC,
5035                      is_pre_master ? "pre-" : "", label);
5036     ssl_print_string(label, key);
5037     ssl_print_string("(pre-)master secret", ms);
5038     return TRUE;
5039 }
5040 /* Store/load a known (pre-)master secret from/for this SSL session. }}} */
5041
5042 /* Should be called when all parameters are ready (after ChangeCipherSpec), and
5043  * the decoder should be attempted to be initialized. {{{*/
5044 void
5045 ssl_finalize_decryption(SslDecryptSession *ssl, ssl_master_key_map_t *mk_map)
5046 {
5047     if (ssl->session.version == TLSV1DOT3_VERSION) {
5048         /* TLS 1.3 implementations only provide secrets derived from the master
5049          * secret which are loaded in tls13_change_key. No master secrets can be
5050          * loaded here, so just return. */
5051         return;
5052     }
5053     ssl_debug_printf("%s state = 0x%02X\n", G_STRFUNC, ssl->state);
5054     if (ssl->state & SSL_HAVE_SESSION_KEY) {
5055         ssl_debug_printf("  session key already available, nothing to do.\n");
5056         return;
5057     }
5058     if (!(ssl->state & SSL_CIPHER)) {
5059         ssl_debug_printf("  Cipher suite (Server Hello) is missing!\n");
5060         return;
5061     }
5062
5063     /* for decryption, there needs to be a master secret (which can be derived
5064      * from pre-master secret). If missing, try to pick a master key from cache
5065      * (an earlier packet in the capture or key logfile). */
5066     if (!(ssl->state & (SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET)) &&
5067         !ssl_restore_master_key(ssl, "Session ID", FALSE,
5068                                 mk_map->session, &ssl->session_id) &&
5069         (!ssl->session.is_session_resumed ||
5070          !ssl_restore_master_key(ssl, "Session Ticket", FALSE,
5071                                  mk_map->tickets, &ssl->session_ticket)) &&
5072         !ssl_restore_master_key(ssl, "Client Random", FALSE,
5073                                 mk_map->crandom, &ssl->client_random)) {
5074         if (ssl->cipher_suite->enc != ENC_NULL) {
5075             /* how unfortunate, the master secret could not be found */
5076             ssl_debug_printf("  Cannot find master secret\n");
5077             return;
5078         } else {
5079             ssl_debug_printf(" Cannot find master secret, continuing anyway "
5080                     "because of a NULL cipher\n");
5081         }
5082     }
5083
5084     if (ssl_generate_keyring_material(ssl) < 0) {
5085         ssl_debug_printf("%s can't generate keyring material\n", G_STRFUNC);
5086         return;
5087     }
5088     /* Save Client Random/ Session ID for "SSL Export Session keys" */
5089     ssl_save_master_key("Client Random", mk_map->crandom,
5090                         &ssl->client_random, &ssl->master_secret);
5091     ssl_save_master_key("Session ID", mk_map->session,
5092                         &ssl->session_id, &ssl->master_secret);
5093     /* Only save the new secrets if the server sent the ticket. The client
5094      * ticket might have become stale. */
5095     if (ssl->state & SSL_NEW_SESSION_TICKET) {
5096         ssl_save_master_key("Session Ticket", mk_map->tickets,
5097                             &ssl->session_ticket, &ssl->master_secret);
5098     }
5099 } /* }}} */
5100
5101 /* Load the new key. */
5102 void
5103 tls13_change_key(SslDecryptSession *ssl, ssl_master_key_map_t *mk_map,
5104                  gboolean is_from_server, TLSRecordType type)
5105 {
5106     GHashTable *key_map;
5107     const char *label;
5108
5109     if (ssl->session.version != TLSV1DOT3_VERSION) {
5110         ssl_debug_printf("%s TLS version %#x is not 1.3\n", G_STRFUNC, ssl->session.version);
5111         return;
5112     }
5113
5114     if (ssl->client_random.data_len == 0) {
5115         /* May happen if Hello message is missing and Finished is found. */
5116         ssl_debug_printf("%s missing Client Random\n", G_STRFUNC);
5117         return;
5118     }
5119
5120     switch (type) {
5121     case TLS_SECRET_0RTT_APP:
5122         /* TODO 0-RTT decryption is not implemented yet */
5123         return;
5124     case TLS_SECRET_HANDSHAKE:
5125         if (is_from_server) {
5126             label = "SERVER_HANDSHAKE_TRAFFIC_SECRET";
5127             key_map = mk_map->tls13_server_handshake;
5128         } else {
5129             label = "CLIENT_HANDSHAKE_TRAFFIC_SECRET";
5130             key_map = mk_map->tls13_client_handshake;
5131         }
5132         break;
5133     case TLS_SECRET_APP:
5134         if (is_from_server) {
5135             label = "SERVER_TRAFFIC_SECRET_0";
5136             key_map = mk_map->tls13_server_appdata;
5137         } else {
5138             label = "CLIENT_TRAFFIC_SECRET_0";
5139             key_map = mk_map->tls13_client_appdata;
5140         }
5141         break;
5142     default:
5143         g_assert_not_reached();
5144     }
5145
5146     /* Transitioning to new keys, mark old ones as unusable. */
5147     ssl_debug_printf("%s transitioning to new key, old state 0x%02x\n", G_STRFUNC, ssl->state);
5148     ssl->state &= ~(SSL_MASTER_SECRET | SSL_PRE_MASTER_SECRET | SSL_HAVE_SESSION_KEY);
5149
5150     StringInfo *secret = (StringInfo *)g_hash_table_lookup(key_map, &ssl->client_random);
5151     if (!secret) {
5152         ssl_debug_printf("%s Cannot find %s, decryption impossible\n", G_STRFUNC, label);
5153         /* Disable decryption, the keys are invalid. */
5154         if (is_from_server) {
5155             ssl->server = NULL;
5156         } else {
5157             ssl->client = NULL;
5158         }
5159         return;
5160     }
5161
5162     /* TLS 1.3 secret found, set new keys. */
5163     ssl->traffic_secret.data = (guchar *) wmem_realloc(wmem_file_scope(),
5164             ssl->traffic_secret.data, secret->data_len);
5165     ssl_data_set(&ssl->traffic_secret, secret->data, secret->data_len);
5166     ssl_debug_printf("%s Retrieved TLS 1.3 traffic secret.\n", G_STRFUNC);
5167     ssl_print_string("Client Random", &ssl->client_random);
5168     ssl_print_string(label, secret);
5169     tls13_generate_keys(ssl, secret, is_from_server);
5170 }
5171 #endif /* HAVE_LIBGCRYPT */
5172
5173 /** SSL keylog file handling. {{{ */
5174
5175 static GRegex *
5176 ssl_compile_keyfile_regex(void)
5177 {
5178 #define OCTET "(?:[[:xdigit:]]{2})"
5179     const gchar *pattern =
5180         "(?:"
5181         /* Matches Client Hellos having this Client Random */
5182         "PMS_CLIENT_RANDOM (?<client_random_pms>" OCTET "{32}) "
5183         /* Matches first part of encrypted RSA pre-master secret */
5184         "|RSA (?<encrypted_pmk>" OCTET "{8}) "
5185         /* Pre-Master-Secret is given, it is 48 bytes for RSA,
5186            but it can be of any length for DHE */
5187         ")(?<pms>" OCTET "+)"
5188         "|(?:"
5189         /* Matches Server Hellos having a Session ID */
5190         "RSA Session-ID:(?<session_id>" OCTET "+) Master-Key:"
5191         /* Matches Client Hellos having this Client Random */
5192         "|CLIENT_RANDOM (?<client_random>" OCTET "{32}) "
5193         /* Master-Secret is given, its length is fixed */
5194         ")(?<master_secret>" OCTET "{" G_STRINGIFY(SSL_MASTER_SECRET_LENGTH) "})"
5195         "|(?"
5196         /* TLS 1.3 Client Random to Derived Secrets mapping. */
5197         ":CLIENT_HANDSHAKE_TRAFFIC_SECRET (?<client_handshake>" OCTET "{32})"
5198         "|SERVER_HANDSHAKE_TRAFFIC_SECRET (?<server_handshake>" OCTET "{32})"
5199         "|CLIENT_TRAFFIC_SECRET_0 (?<client_appdata>" OCTET "{32})"
5200         "|SERVER_TRAFFIC_SECRET_0 (?<server_appdata>" OCTET "{32})"
5201         ") (?<derived_secret>" OCTET "+)";
5202 #undef OCTET
5203     static GRegex *regex = NULL;
5204     GError *gerr = NULL;
5205
5206     if (!regex) {
5207         regex = g_regex_new(pattern,
5208                 (GRegexCompileFlags)(G_REGEX_OPTIMIZE | G_REGEX_ANCHORED),
5209                 G_REGEX_MATCH_ANCHORED, &gerr);
5210         if (gerr) {
5211             ssl_debug_printf("%s failed to compile regex: %s\n", G_STRFUNC,
5212                              gerr->message);
5213             g_error_free(gerr);
5214             regex = NULL;
5215         }
5216     }
5217
5218     return regex;
5219 }
5220
5221 static gboolean
5222 file_needs_reopen(FILE *fp, const char *filename)
5223 {
5224     ws_statb64 open_stat, current_stat;
5225
5226     /* consider a file deleted when stat fails for either file,
5227      * or when the residing device / inode has changed. */
5228     if (0 != ws_fstat64(ws_fileno(fp), &open_stat))
5229         return TRUE;
5230     if (0 != ws_stat64(filename, &current_stat))
5231         return TRUE;
5232
5233     /* Note: on Windows, ino may be 0. Existing files cannot be deleted on
5234      * Windows, but hopefully the size is a good indicator when a file got
5235      * removed and recreated */
5236     return  open_stat.st_dev != current_stat.st_dev ||
5237             open_stat.st_ino != current_stat.st_ino ||
5238             open_stat.st_size > current_stat.st_size;
5239 }
5240
5241 typedef struct ssl_master_key_match_group {
5242     const char *re_group_name;
5243     GHashTable *master_key_ht;
5244 } ssl_master_key_match_group_t;
5245
5246 void
5247 ssl_load_keyfile(const gchar *ssl_keylog_filename, FILE **keylog_file,
5248                  const ssl_master_key_map_t *mk_map)
5249 {
5250     unsigned i;
5251     GRegex *regex;
5252     ssl_master_key_match_group_t mk_groups[] = {
5253         { "encrypted_pmk",  mk_map->pre_master },
5254         { "session_id",     mk_map->session },
5255         { "client_random",  mk_map->crandom },
5256         { "client_random_pms",  mk_map->pms },
5257         /* TLS 1.3 map from Client Random to derived secret. */
5258         { "client_handshake",   mk_map->tls13_client_handshake },
5259         { "server_handshake",   mk_map->tls13_server_handshake },
5260         { "client_appdata",     mk_map->tls13_client_appdata },
5261         { "server_appdata",     mk_map->tls13_server_appdata },
5262     };
5263     /* no need to try if no key log file is configured. */
5264     if (!ssl_keylog_filename || !*ssl_keylog_filename) {
5265         ssl_debug_printf("%s dtls/ssl.keylog_file is not configured!\n",
5266                          G_STRFUNC);
5267         return;
5268     }
5269
5270     /* The format of the file is a series of records with one of the following formats:
5271      *   - "RSA xxxx yyyy"
5272      *     Where xxxx are the first 8 bytes of the encrypted pre-master secret (hex-encoded)
5273      *     Where yyyy is the cleartext pre-master secret (hex-encoded)
5274      *     (this is the original format introduced with bug 4349)
5275      *
5276      *   - "RSA Session-ID:xxxx Master-Key:yyyy"
5277      *     Where xxxx is the SSL session ID (hex-encoded)
5278      *     Where yyyy is the cleartext master secret (hex-encoded)
5279      *     (added to support openssl s_client Master-Key output)
5280      *     This is somewhat is a misnomer because there's nothing RSA specific
5281      *     about this.
5282      *
5283      *   - "PMS_CLIENT_RANDOM xxxx yyyy"
5284      *     Where xxxx is the client_random from the ClientHello (hex-encoded)
5285      *     Where yyyy is the cleartext pre-master secret (hex-encoded)
5286      *     (This format allows SSL connections to be decrypted, if a user can
5287      *     capture the PMS but could not recover the MS for a specific session
5288      *     with a SSL Server.)
5289      *
5290      *   - "CLIENT_RANDOM xxxx yyyy"
5291      *     Where xxxx is the client_random from the ClientHello (hex-encoded)
5292      *     Where yyyy is the cleartext master secret (hex-encoded)
5293      *     (This format allows non-RSA SSL connections to be decrypted, i.e.
5294      *     ECDHE-RSA.)
5295      *
5296      *   - "CLIENT_HANDSHAKE_TRAFFIC_SECRET xxxx yyyy"
5297      *   - "SERVER_HANDSHAKE_TRAFFIC_SECRET xxxx yyyy"
5298      *   - "CLIENT_TRAFFIC_SECRET_0 xxxx yyyy"
5299      *   - "SERVER_TRAFFIC_SECRET_0 xxxx yyyy"
5300      *     Where xxxx is the client_random from the ClientHello (hex-encoded)
5301      *     Where yyyy is the secret (hex-encoded) derived from the handshake or
5302      *     master secrets. (This format is introduced with TLS 1.3 and supported
5303      *     by BoringSSL, OpenSSL, etc. See bug 12779.)
5304      */
5305     regex = ssl_compile_keyfile_regex();
5306     if (!regex)
5307         return;
5308
5309     ssl_debug_printf("trying to use SSL keylog in %s\n", ssl_keylog_filename);
5310
5311     /* if the keylog file was deleted, re-open it */
5312     if (*keylog_file && file_needs_reopen(*keylog_file, ssl_keylog_filename)) {
5313         ssl_debug_printf("%s file got deleted, trying to re-open\n", G_STRFUNC);
5314         fclose(*keylog_file);
5315         *keylog_file = NULL;
5316     }
5317
5318     if (*keylog_file == NULL) {
5319         *keylog_file = ws_fopen(ssl_keylog_filename, "r");
5320         if (!*keylog_file) {
5321             ssl_debug_printf("%s failed to open SSL keylog\n", G_STRFUNC);
5322             return;
5323         }
5324     }
5325
5326     for (;;) {
5327         char buf[512], *line;
5328         gsize bytes_read;
5329         GMatchInfo *mi;
5330
5331         line = fgets(buf, sizeof(buf), *keylog_file);
5332         if (!line)
5333             break;
5334
5335         bytes_read = strlen(line);
5336         /* fgets includes the \n at the end of the line. */
5337         if (bytes_read > 0 && line[bytes_read - 1] == '\n') {
5338             line[bytes_read - 1] = 0;
5339             bytes_read--;
5340         }
5341         if (bytes_read > 0 && line[bytes_read - 1] == '\r') {
5342             line[bytes_read - 1] = 0;
5343             bytes_read--;
5344         }
5345
5346         ssl_debug_printf("  checking keylog line: %s\n", line);
5347         if (g_regex_match(regex, line, G_REGEX_MATCH_ANCHORED, &mi)) {
5348             gchar *hex_key, *hex_pre_ms_or_ms;
5349             StringInfo *key = wmem_new(wmem_file_scope(), StringInfo);
5350             StringInfo *pre_ms_or_ms = NULL;
5351             GHashTable *ht = NULL;
5352
5353             /* Is the PMS being supplied with the PMS_CLIENT_RANDOM
5354              * otherwise we will use the Master Secret
5355              */
5356             hex_pre_ms_or_ms = g_match_info_fetch_named(mi, "master_secret");
5357             if (hex_pre_ms_or_ms == NULL || !*hex_pre_ms_or_ms) {
5358                 g_free(hex_pre_ms_or_ms);
5359                 hex_pre_ms_or_ms = g_match_info_fetch_named(mi, "pms");
5360             }
5361             if (hex_pre_ms_or_ms == NULL || !*hex_pre_ms_or_ms) {
5362                 g_free(hex_pre_ms_or_ms);
5363                 hex_pre_ms_or_ms = g_match_info_fetch_named(mi, "derived_secret");
5364             }
5365             /* There is always a match, otherwise the regex is wrong. */
5366             DISSECTOR_ASSERT(hex_pre_ms_or_ms && strlen(hex_pre_ms_or_ms));
5367
5368             /* convert from hex to bytes and save to hashtable */
5369             pre_ms_or_ms = wmem_new(wmem_file_scope(), StringInfo);
5370             from_hex(pre_ms_or_ms, hex_pre_ms_or_ms, strlen(hex_pre_ms_or_ms));
5371             g_free(hex_pre_ms_or_ms);
5372
5373             /* Find a master key from any format (CLIENT_RANDOM, SID, ...) */
5374             for (i = 0; i < G_N_ELEMENTS(mk_groups); i++) {
5375                 ssl_master_key_match_group_t *g = &mk_groups[i];
5376                 hex_key = g_match_info_fetch_named(mi, g->re_group_name);
5377                 if (hex_key && *hex_key) {
5378                     ssl_debug_printf("    matched %s\n", g->re_group_name);
5379                     ht = g->master_key_ht;
5380                     from_hex(key, hex_key, strlen(hex_key));
5381                     g_free(hex_key);
5382                     break;
5383                 }
5384                 g_free(hex_key);
5385             }
5386             DISSECTOR_ASSERT(ht); /* Cannot be reached, or regex is wrong. */
5387
5388             g_hash_table_insert(ht, key, pre_ms_or_ms);
5389
5390         } else {
5391             ssl_debug_printf("    unrecognized line\n");
5392         }
5393         /* always free match info even if there is no match. */
5394         g_match_info_free(mi);
5395     }
5396 }
5397 /** SSL keylog file handling. }}} */
5398
5399 #ifdef SSL_DECRYPT_DEBUG /* {{{ */
5400
5401 static FILE* ssl_debug_file=NULL;
5402
5403 void
5404 ssl_set_debug(const gchar* name)
5405 {
5406     static gint debug_file_must_be_closed;
5407     gint        use_stderr;
5408
5409     use_stderr                = name?(strcmp(name, SSL_DEBUG_USE_STDERR) == 0):0;
5410
5411     if (debug_file_must_be_closed)
5412         fclose(ssl_debug_file);
5413
5414     if (use_stderr)
5415         ssl_debug_file = stderr;
5416     else if (!name || (strcmp(name, "") ==0))
5417         ssl_debug_file = NULL;
5418     else
5419         ssl_debug_file = ws_fopen(name, "w");
5420
5421     if (!use_stderr && ssl_debug_file)
5422         debug_file_must_be_closed = 1;
5423     else
5424         debug_file_must_be_closed = 0;
5425
5426     ssl_debug_printf("Wireshark SSL debug log \n\n");
5427     ssl_debug_printf("Wireshark version: %s\n", get_ws_vcs_version_info());
5428 #ifdef HAVE_LIBGNUTLS
5429     ssl_debug_printf("GnuTLS version:    %s\n", gnutls_check_version(NULL));
5430 #endif
5431 #ifdef HAVE_LIBGCRYPT
5432     ssl_debug_printf("Libgcrypt version: %s\n", gcry_check_version(NULL));
5433 #endif
5434     ssl_debug_printf("\n");
5435 }
5436
5437 void
5438 ssl_debug_flush(void)
5439 {
5440     if (ssl_debug_file)
5441         fflush(ssl_debug_file);
5442 }
5443
5444 void
5445 ssl_debug_printf(const gchar* fmt, ...)
5446 {
5447     va_list ap;
5448
5449     if (!ssl_debug_file)
5450         return;
5451
5452     va_start(ap, fmt);
5453     vfprintf(ssl_debug_file, fmt, ap);
5454     va_end(ap);
5455 }
5456
5457 void
5458 ssl_print_data(const gchar* name, const guchar* data, size_t len)
5459 {
5460     size_t i, j, k;
5461     if (!ssl_debug_file)
5462         return;
5463     fprintf(ssl_debug_file,"%s[%d]:\n",name, (int) len);
5464     for (i=0; i<len; i+=16) {
5465         fprintf(ssl_debug_file,"| ");
5466         for (j=i, k=0; k<16 && j<len; ++j, ++k)
5467             fprintf(ssl_debug_file,"%.2x ",data[j]);
5468         for (; k<16; ++k)
5469             fprintf(ssl_debug_file,"   ");
5470         fputc('|', ssl_debug_file);
5471         for (j=i, k=0; k<16 && j<len; ++j, ++k) {
5472             guchar c = data[j];
5473             if (!g_ascii_isprint(c) || (c=='\t')) c = '.';
5474             fputc(c, ssl_debug_file);
5475         }
5476         for (; k<16; ++k)
5477             fputc(' ', ssl_debug_file);
5478         fprintf(ssl_debug_file,"|\n");
5479     }
5480 }
5481
5482 void
5483 ssl_print_string(const gchar* name, const StringInfo* data)
5484 {
5485     ssl_print_data(name, data->data, data->data_len);
5486 }
5487 #endif /* SSL_DECRYPT_DEBUG }}} */
5488
5489 /* UAT preferences callbacks. {{{ */
5490 /* checks for SSL and DTLS UAT key list fields */
5491
5492 gboolean
5493 ssldecrypt_uat_fld_ip_chk_cb(void* r _U_, const char* p, guint len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
5494 {
5495     if (!p || strlen(p) == 0u) {
5496         *err = g_strdup("No IP address given.");
5497         return FALSE;
5498     }
5499
5500     *err = NULL;
5501     return TRUE;
5502 }
5503
5504 gboolean
5505 ssldecrypt_uat_fld_port_chk_cb(void* r _U_, const char* p, guint len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
5506 {
5507     if (!p || strlen(p) == 0u) {
5508         *err = g_strdup("No Port given.");
5509         return FALSE;
5510     }
5511
5512     if (strcmp(p, "start_tls") != 0){
5513         guint16 port;
5514         if (!ws_strtou16(p, NULL, &port)) {
5515             *err = g_strdup("Invalid port given.");
5516             return FALSE;
5517         }
5518     }
5519
5520     *err = NULL;
5521     return TRUE;
5522 }
5523
5524 gboolean
5525 ssldecrypt_uat_fld_fileopen_chk_cb(void* r _U_, const char* p, guint len _U_, const void* u1 _U_, const void* u2 _U_, char** err)
5526 {
5527     ws_statb64 st;
5528
5529     if (!p || strlen(p) == 0u) {
5530         *err = g_strdup("No filename given.");
5531         return FALSE;
5532     } else {
5533         if (ws_stat64(p, &st) != 0) {
5534             *err = g_strdup_printf("File '%s' does not exist or access is denied.", p);
5535             return FALSE;
5536         }
5537     }
5538
5539     *err = NULL;
5540     return TRUE;
5541 }
5542
5543 gboolean
5544 ssldecrypt_uat_fld_password_chk_cb(void *r _U_, const char *p _U_, guint len _U_, const void *u1 _U_, const void *u2 _U_, char **err)
5545 {
5546 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
5547     ssldecrypt_assoc_t*  f  = (ssldecrypt_assoc_t *)r;
5548     FILE                *fp = NULL;
5549
5550     if (p && (strlen(p) > 0u)) {
5551         fp = ws_fopen(f->keyfile, "rb");
5552         if (fp) {
5553             char *msg = NULL;
5554             gnutls_x509_privkey_t priv_key = ssl_load_pkcs12(fp, p, &msg);
5555             if (!priv_key) {
5556                 fclose(fp);
5557                 *err = g_strdup_printf("Could not load PKCS#12 key file: %s", msg);
5558                 g_free(msg);
5559                 return FALSE;
5560             }
5561             g_free(msg);
5562             gnutls_x509_privkey_deinit(priv_key);
5563             fclose(fp);
5564         } else {
5565             *err = g_strdup_printf("Leave this field blank if the keyfile is not PKCS#12.");
5566             return FALSE;
5567         }
5568     }
5569
5570     *err = NULL;
5571     return TRUE;
5572 #else
5573     *err = g_strdup("Cannot load key files, support is not compiled in.");
5574     return FALSE;
5575 #endif
5576 }
5577 /* UAT preferences callbacks. }}} */
5578
5579 /** maximum size of ssl_association_info() string */
5580 #define SSL_ASSOC_MAX_LEN 8192
5581
5582 typedef struct ssl_association_info_callback_data
5583 {
5584     gchar *str;
5585     const char *table_protocol;
5586 } ssl_association_info_callback_data_t;
5587
5588 /**
5589  * callback function used by ssl_association_info() to traverse the SSL associations.
5590  */
5591 static void
5592 ssl_association_info_(const gchar *table _U_, gpointer handle, gpointer user_data)
5593 {
5594     ssl_association_info_callback_data_t* data = (ssl_association_info_callback_data_t*)user_data;
5595     const int l = (const int)strlen(data->str);
5596     g_snprintf(data->str+l, SSL_ASSOC_MAX_LEN-l, "'%s' %s\n", dissector_handle_get_short_name((dissector_handle_t)handle), data->table_protocol);
5597 }
5598
5599 /**
5600  * @return an information string on the SSL protocol associations. The string has ephemeral lifetime/scope.
5601  */
5602 gchar*
5603 ssl_association_info(const char* dissector_table_name, const char* table_protocol)
5604 {
5605     ssl_association_info_callback_data_t data;
5606
5607     data.str = (gchar *)g_malloc0(SSL_ASSOC_MAX_LEN);
5608     data.table_protocol = table_protocol;
5609     dissector_table_foreach_handle(dissector_table_name, ssl_association_info_, &data);
5610     return data.str;
5611 }
5612
5613
5614 /** Begin of code related to dissection of wire data. */
5615
5616 /* Helpers for dissecting Variable-Length Vectors. {{{ */
5617 gboolean
5618 ssl_add_vector(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
5619                guint offset, guint offset_end, guint32 *ret_length,
5620                int hf_length, guint32 min_value, guint32 max_value)
5621 {
5622     guint       veclen_size;
5623     guint32     veclen_value;
5624     proto_item *pi;
5625
5626     DISSECTOR_ASSERT(offset <= offset_end);
5627     DISSECTOR_ASSERT(min_value <= max_value);
5628
5629     if (max_value > 0xffffff) {
5630         veclen_size = 4;
5631     } else if (max_value > 0xffff) {
5632         veclen_size = 3;
5633     } else if (max_value > 0xff) {
5634         veclen_size = 2;
5635     } else {
5636         veclen_size = 1;
5637     }
5638
5639     if (offset_end - offset < veclen_size) {
5640         proto_tree_add_expert_format(tree, pinfo, &hf->ei.malformed_buffer_too_small,
5641                                      tvb, offset, offset_end - offset,
5642                                      "No more room for vector of length %u",
5643                                      veclen_size);
5644         *ret_length = 0;
5645         return FALSE;   /* Cannot read length. */
5646     }
5647
5648     pi = proto_tree_add_item_ret_uint(tree, hf_length, tvb, offset, veclen_size, ENC_BIG_ENDIAN, &veclen_value);
5649     offset += veclen_size;
5650
5651     if (veclen_value < min_value) {
5652         expert_add_info_format(pinfo, pi, &hf->ei.malformed_vector_length,
5653                                "Vector length %u is smaller than minimum %u",
5654                                veclen_value, min_value);
5655     } else if (veclen_value > max_value) {
5656         expert_add_info_format(pinfo, pi, &hf->ei.malformed_vector_length,
5657                                "Vector length %u is larger than maximum %u",
5658                                veclen_value, max_value);
5659     }
5660
5661     if (offset_end - offset < veclen_value) {
5662         expert_add_info_format(pinfo, pi, &hf->ei.malformed_buffer_too_small,
5663                                "Vector length %u is too large, truncating it to %u",
5664                                veclen_value, offset_end - offset);
5665         *ret_length = offset_end - offset;
5666         return FALSE;   /* Length is truncated to avoid overflow. */
5667     }
5668
5669     *ret_length = veclen_value;
5670     return TRUE;        /* Length is OK. */
5671 }
5672
5673 gboolean
5674 ssl_end_vector(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
5675                guint offset, guint offset_end)
5676 {
5677     if (offset < offset_end) {
5678         guint trailing = offset_end - offset;
5679         proto_tree_add_expert_format(tree, pinfo, &hf->ei.malformed_trailing_data,
5680                                      tvb, offset, trailing,
5681                                      "%u trailing byte%s unprocessed",
5682                                      trailing, plurality(trailing, " was", "s were"));
5683         return FALSE;   /* unprocessed data warning */
5684     } else if (offset > offset_end) {
5685         /*
5686          * Returned offset runs past the end. This should not happen and is
5687          * possibly a dissector bug.
5688          */
5689         guint excess = offset - offset_end;
5690         proto_tree_add_expert_format(tree, pinfo, &hf->ei.malformed_buffer_too_small,
5691                                      tvb, offset_end, excess,
5692                                      "Dissector processed too much data (%u byte%s)",
5693                                      excess, plurality(excess, "", "s"));
5694         return FALSE;   /* overflow error */
5695     }
5696
5697     return TRUE;    /* OK, offset matches. */
5698 }
5699 /** }}} */
5700
5701
5702 /* change_cipher_spec(20) dissection */
5703 void
5704 ssl_dissect_change_cipher_spec(ssl_common_dissect_t *hf, tvbuff_t *tvb,
5705                                packet_info *pinfo, proto_tree *tree,
5706                                guint32 offset, SslSession *session,
5707                                gboolean is_from_server,
5708                                const SslDecryptSession *ssl)
5709 {
5710     /*
5711      * struct {
5712      *     enum { change_cipher_spec(1), (255) } type;
5713      * } ChangeCipherSpec;
5714      */
5715     proto_item *ti;
5716     proto_item_set_text(tree,
5717             "%s Record Layer: %s Protocol: Change Cipher Spec",
5718             val_to_str_const(session->version, ssl_version_short_names, "SSL"),
5719             val_to_str_const(SSL_ID_CHG_CIPHER_SPEC, ssl_31_content_type, "unknown"));
5720     ti = proto_tree_add_item(tree, hf->hf.change_cipher_spec, tvb, offset, 1, ENC_NA);
5721
5722     /* Use heuristics to detect an abbreviated handshake, assume that missing
5723      * ServerHelloDone implies reusing previously negotiating keys. Then when
5724      * a Session ID or ticket is present, it must be a resumed session.
5725      * Normally this should be done at the Finished message, but that may be
5726      * encrypted so we do it here, at the last cleartext message. */
5727     if (is_from_server && ssl) {
5728         if (session->is_session_resumed) {
5729             const char *resumed = NULL;
5730             if (ssl->session_ticket.data_len) {
5731                 resumed = "Session Ticket";
5732             } else if (ssl->session_id.data_len) {
5733                 resumed = "Session ID";
5734             }
5735             if (resumed) {
5736                 ssl_debug_printf("%s Session resumption using %s\n", G_STRFUNC, resumed);
5737             } else {
5738                 /* Can happen if the capture somehow starts in the middle */
5739                 ssl_debug_printf("%s No Session resumption, missing packets?\n", G_STRFUNC);
5740             }
5741         } else {
5742             ssl_debug_printf("%s Not using Session resumption\n", G_STRFUNC);
5743         }
5744     }
5745     if (is_from_server && session->is_session_resumed)
5746         expert_add_info(pinfo, ti, &hf->ei.resumed);
5747 }
5748
5749 /** Begin of handshake(22) record dissections */
5750 /* dissect a list of hash algorithms, return the number of bytes dissected
5751    this is used for the signature algorithms extension and for the
5752    TLS1.2 certificate request. {{{ */
5753 static gint
5754 ssl_dissect_hash_alg_list(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
5755                           packet_info* pinfo, guint32 offset, guint32 offset_end)
5756 {
5757     /* https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
5758      *  struct {
5759      *       HashAlgorithm hash;
5760      *       SignatureAlgorithm signature;
5761      *  } SignatureAndHashAlgorithm;
5762      *  SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
5763      */
5764     proto_tree *subtree, *alg_tree;
5765     proto_item *ti;
5766     guint sh_alg_length;
5767     guint32     next_offset;
5768
5769     /* SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2> */
5770     if (!ssl_add_vector(hf, tvb, pinfo, tree, offset, offset_end, &sh_alg_length,
5771                         hf->hf.hs_sig_hash_alg_len, 2, G_MAXUINT16 - 1)) {
5772         return offset_end;
5773     }
5774     offset += 2;
5775     next_offset = offset + sh_alg_length;
5776
5777     ti = proto_tree_add_none_format(tree, hf->hf.hs_sig_hash_algs, tvb, offset, sh_alg_length,
5778                                     "Signature Hash Algorithms (%u algorithm%s)",
5779                                     sh_alg_length / 2, plurality(sh_alg_length / 2, "", "s"));
5780     subtree = proto_item_add_subtree(ti, hf->ett.hs_sig_hash_algs);
5781
5782     while (offset + 2 <= next_offset) {
5783         ti = proto_tree_add_item(subtree, hf->hf.hs_sig_hash_alg,
5784                                  tvb, offset, 2, ENC_BIG_ENDIAN);
5785         alg_tree = proto_item_add_subtree(ti, hf->ett.hs_sig_hash_alg);
5786
5787         proto_tree_add_item(alg_tree, hf->hf.hs_sig_hash_hash,
5788                             tvb, offset, 1, ENC_BIG_ENDIAN);
5789         proto_tree_add_item(alg_tree, hf->hf.hs_sig_hash_sig,
5790                             tvb, offset+1, 1, ENC_BIG_ENDIAN);
5791
5792         offset += 2;
5793     }
5794
5795     if (!ssl_end_vector(hf, tvb, pinfo, subtree, offset, next_offset)) {
5796         offset = next_offset;
5797     }
5798
5799     return offset;
5800 } /* }}} */
5801
5802 /** TLS Extensions (in Client Hello and Server Hello). {{{ */
5803 static gint
5804 ssl_dissect_hnd_hello_ext_sig_hash_algs(ssl_common_dissect_t *hf, tvbuff_t *tvb,
5805                                         proto_tree *tree, packet_info* pinfo, guint32 offset, guint32 offset_end)
5806 {
5807     return ssl_dissect_hash_alg_list(hf, tvb, tree, pinfo, offset, offset_end);
5808 }
5809
5810 static gint
5811 ssl_dissect_hnd_hello_ext_alpn(ssl_common_dissect_t *hf, tvbuff_t *tvb,
5812                                packet_info *pinfo, proto_tree *tree,
5813                                guint32 offset, guint32 offset_end,
5814                                guint8 hnd_type, SslSession *session)
5815 {
5816
5817     /* https://tools.ietf.org/html/rfc7301#section-3.1
5818      *  opaque ProtocolName<1..2^8-1>;
5819      *  struct {
5820      *      ProtocolName protocol_name_list<2..2^16-1>
5821      *  } ProtocolNameList;
5822      */
5823     proto_tree *alpn_tree;
5824     proto_item *ti;
5825     guint32     next_offset, alpn_length, name_length;
5826     guint8     *proto_name = NULL;
5827     guint32     proto_name_length = 0;
5828
5829     /* ProtocolName protocol_name_list<2..2^16-1> */
5830     if (!ssl_add_vector(hf, tvb, pinfo, tree, offset, offset_end, &alpn_length,
5831                         hf->hf.hs_ext_alpn_len, 2, G_MAXUINT16)) {
5832         return offset_end;
5833     }
5834     offset += 2;
5835     next_offset = offset + alpn_length;
5836
5837     ti = proto_tree_add_item(tree, hf->hf.hs_ext_alpn_list,
5838                              tvb, offset, alpn_length, ENC_NA);
5839     alpn_tree = proto_item_add_subtree(ti, hf->ett.hs_ext_alpn);
5840
5841     /* Parse list (note missing check for end of vector, ssl_add_vector below
5842      * ensures that data is always available.) */
5843     while (offset < next_offset) {
5844         /* opaque ProtocolName<1..2^8-1> */
5845         if (!ssl_add_vector(hf, tvb, pinfo, alpn_tree, offset, next_offset, &name_length,
5846                             hf->hf.hs_ext_alpn_str_len, 1, G_MAXUINT8)) {
5847             return next_offset;
5848         }
5849         offset++;
5850
5851         proto_tree_add_item(alpn_tree, hf->hf.hs_ext_alpn_str,
5852                             tvb, offset, name_length, ENC_ASCII|ENC_NA);
5853         /* Remember first ALPN ProtocolName entry for server. */
5854         if (hnd_type == SSL_HND_SERVER_HELLO) {
5855             proto_name_length = name_length;
5856             proto_name = tvb_get_string_enc(wmem_packet_scope(), tvb, offset,
5857                                             proto_name_length, ENC_ASCII);
5858         }
5859         offset += name_length;
5860     }
5861
5862     /* If ALPN is given in ServerHello, then ProtocolNameList MUST contain
5863      * exactly one "ProtocolName". */
5864     if (hnd_type == SSL_HND_SERVER_HELLO && proto_name) {
5865         /* '\0'-terminated string for prefix/full string comparison purposes. */
5866         for (size_t i = 0; i < G_N_ELEMENTS(ssl_alpn_protocols); i++) {
5867             const ssl_alpn_protocol_t *alpn_proto = &ssl_alpn_protocols[i];
5868
5869             if ((alpn_proto->match_exact &&
5870                         proto_name_length == strlen(alpn_proto->proto_name) &&
5871                         !strcmp(proto_name, alpn_proto->proto_name)) ||
5872                 (!alpn_proto->match_exact && g_str_has_prefix(proto_name, alpn_proto->proto_name))) {
5873
5874                 dissector_handle_t handle;
5875                 /* ProtocolName match, so set the App data dissector handle.
5876                  * This may override protocols given via the UAT dialog, but
5877                  * since the ALPN hint is precise, do it anyway. */
5878                 handle = ssl_find_appdata_dissector(alpn_proto->dissector_name);
5879                 ssl_debug_printf("%s: changing handle %p to %p (%s)", G_STRFUNC,
5880                                  (void *)session->app_handle,
5881                                  (void *)handle, alpn_proto->dissector_name);
5882                 /* if dissector is disabled, do not overwrite previous one */
5883                 if (handle)
5884                     session->app_handle = handle;
5885                 break;
5886             }
5887         }
5888     }
5889
5890     return offset;
5891 }
5892
5893 static gint
5894 ssl_dissect_hnd_hello_ext_npn(ssl_common_dissect_t *hf, tvbuff_t *tvb,
5895                               packet_info *pinfo, proto_tree *tree,
5896                               guint32 offset, guint32 offset_end)
5897 {
5898     /* https://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04#page-3
5899      *   The "extension_data" field of a "next_protocol_negotiation" extension
5900      *   in a "ServerHello" contains an optional list of protocols advertised
5901      *   by the server.  Protocols are named by opaque, non-empty byte strings
5902      *   and the list of protocols is serialized as a concatenation of 8-bit,
5903      *   length prefixed byte strings.  Implementations MUST ensure that the
5904      *   empty string is not included and that no byte strings are truncated.
5905      */
5906     guint32     npn_length;
5907     proto_tree *npn_tree;
5908
5909     /* List is optional, do not add tree if there are no entries. */
5910     if (offset == offset_end) {
5911         return offset;
5912     }
5913
5914     npn_tree = proto_tree_add_subtree(tree, tvb, offset, offset_end - offset, hf->ett.hs_ext_npn, NULL, "Next Protocol Negotiation");
5915
5916     while (offset < offset_end) {
5917         /* non-empty, 8-bit length prefixed strings means range 1..255 */
5918         if (!ssl_add_vector(hf, tvb, pinfo, npn_tree, offset, offset_end, &npn_length,
5919                             hf->hf.hs_ext_npn_str_len, 1, G_MAXUINT8)) {
5920             return offset_end;
5921         }
5922         offset++;
5923
5924         proto_tree_add_item(npn_tree, hf->hf.hs_ext_npn_str,
5925                             tvb, offset, npn_length, ENC_ASCII|ENC_NA);
5926         offset += npn_length;
5927     }
5928
5929     return offset;
5930 }
5931
5932 static gint
5933 ssl_dissect_hnd_hello_ext_reneg_info(ssl_common_dissect_t *hf, tvbuff_t *tvb,
5934                                      packet_info *pinfo, proto_tree *tree,
5935                                      guint32 offset, guint32 offset_end)
5936 {
5937     /* https://tools.ietf.org/html/rfc5746#section-3.2
5938      *  struct {
5939      *      opaque renegotiated_connection<0..255>;
5940      *  } RenegotiationInfo;
5941      *
5942      */
5943     proto_tree *reneg_info_tree;
5944     guint32     reneg_info_length;
5945
5946     reneg_info_tree = proto_tree_add_subtree(tree, tvb, offset, offset_end - offset, hf->ett.hs_ext_reneg_info, NULL, "Renegotiation Info extension");
5947
5948     /* opaque renegotiated_connection<0..255> */
5949     if (!ssl_add_vector(hf, tvb, pinfo, reneg_info_tree, offset, offset_end, &reneg_info_length,
5950                         hf->hf.hs_ext_reneg_info_len, 0, 255)) {
5951         return offset_end;
5952     }
5953     offset++;
5954
5955     if (reneg_info_length > 0) {
5956         proto_tree_add_item(reneg_info_tree, hf->hf.hs_ext_reneg_info, tvb, offset, reneg_info_length, ENC_NA);
5957         offset += reneg_info_length;
5958     }
5959
5960     return offset;
5961 }
5962
5963 static gint
5964 ssl_dissect_hnd_hello_ext_key_share_entry(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo,
5965                                           proto_tree *tree, guint32 offset, guint32 offset_end)
5966 {
5967    /* https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.5
5968     *   struct {
5969     *       NamedGroup group;
5970     *       opaque key_exchange<1..2^16-1>;
5971     *   } KeyShareEntry;
5972     */
5973     guint32 key_exchange_length, group;
5974     proto_tree *ks_tree;
5975
5976     ks_tree = proto_tree_add_subtree(tree, tvb, offset, 4, hf->ett.hs_ext_key_share_ks, NULL, "Key Share Entry");
5977
5978     proto_tree_add_item_ret_uint(ks_tree, hf->hf.hs_ext_key_share_group, tvb, offset, 2, ENC_BIG_ENDIAN, &group);
5979     offset += 2;
5980     proto_item_append_text(ks_tree, ": Group: %s", val_to_str(group, ssl_extension_curves, "Unknown (%u)"));
5981
5982     /* opaque key_exchange<1..2^16-1> */
5983     if (!ssl_add_vector(hf, tvb, pinfo, ks_tree, offset, offset_end, &key_exchange_length,
5984                         hf->hf.hs_ext_key_share_key_exchange_length, 1, G_MAXUINT16)) {
5985         return offset_end;  /* Bad (possible truncated) length, skip to end of KeyShare extension. */
5986     }
5987     offset += 2;
5988     proto_item_set_len(ks_tree, 2 + 2 + key_exchange_length);
5989     proto_item_append_text(ks_tree, ", Key Exchange length: %u", key_exchange_length);
5990
5991     proto_tree_add_item(ks_tree, hf->hf.hs_ext_key_share_key_exchange, tvb, offset, key_exchange_length, ENC_NA);
5992     offset += key_exchange_length;
5993
5994     return offset;
5995 }
5996
5997 static gint
5998 ssl_dissect_hnd_hello_ext_key_share(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo,
5999                                     proto_tree *tree, guint32 offset, guint32 offset_end,
6000                                     guint8 hnd_type)
6001 {
6002     proto_tree *key_share_tree;
6003     guint32 next_offset;
6004     guint32 client_shares_length;
6005
6006     if (offset_end <= offset) {  /* Check if ext_len == 0 and "overflow" (offset + ext_len) > guint32) */
6007         return offset;
6008     }
6009
6010     key_share_tree = proto_tree_add_subtree(tree, tvb, offset, offset_end - offset, hf->ett.hs_ext_key_share, NULL, "Key Share extension");
6011
6012     switch(hnd_type){
6013         case SSL_HND_CLIENT_HELLO:
6014             /* KeyShareEntry client_shares<0..2^16-1> */
6015             if (!ssl_add_vector(hf, tvb, pinfo, key_share_tree, offset, offset_end, &client_shares_length,
6016                                 hf->hf.hs_ext_key_share_client_length, 0, G_MAXUINT16)) {
6017                 return offset_end;
6018             }
6019             offset += 2;
6020             next_offset = offset + client_shares_length;
6021             while (offset + 4 <= next_offset) { /* (NamedGroup (2 bytes), key_exchange (1 byte for length, 1 byte minimum data) */
6022                 offset = ssl_dissect_hnd_hello_ext_key_share_entry(hf, tvb, pinfo, key_share_tree, offset, next_offset);
6023             }
6024             if (!ssl_end_vector(hf, tvb, pinfo, key_share_tree, offset, next_offset)) {
6025                 return next_offset;
6026             }
6027         break;
6028         case SSL_HND_SERVER_HELLO:
6029             offset = ssl_dissect_hnd_hello_ext_key_share_entry(hf, tvb, pinfo, key_share_tree, offset, offset_end);
6030         break;
6031         case SSL_HND_HELLO_RETRY_REQUEST:
6032             proto_tree_add_item(key_share_tree, hf->hf.hs_ext_key_share_selected_group, tvb, offset, 2, ENC_BIG_ENDIAN );
6033             offset += 2;
6034         break;
6035         default: /* no default */
6036         break;
6037     }
6038
6039     return offset;
6040 }
6041
6042 static gint
6043 ssl_dissect_hnd_hello_ext_pre_shared_key(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6044                                          proto_tree *tree, guint32 offset, guint32 offset_end,
6045                                          guint8 hnd_type)
6046 {
6047     /*  struct {
6048      *      opaque identity<0..2^16-1>;
6049      *      uint32 obfuscated_ticket_age;
6050      *  } PskIdentity;
6051      *  opaque PskBinderEntry<32..255>;
6052      *  struct {
6053      *      select (Handshake.msg_type) {
6054      *          case client_hello:
6055      *              PskIdentity identities<6..2^16-1>;
6056      *              PskBinderEntry binders<33..2^16-1>;
6057      *          case server_hello:
6058      *              uint16 selected_identity;
6059      *      };
6060      *  } PreSharedKeyExtension;
6061      */
6062
6063     proto_tree *psk_tree;
6064
6065     if (offset_end <= offset) { /* Check if ext_len == 0 and "overflow" (offset + ext_len) > guint32) */
6066         return offset;
6067     }
6068
6069     psk_tree = proto_tree_add_subtree(tree, tvb, offset, offset_end - offset, hf->ett.hs_ext_pre_shared_key, NULL, "Pre-Shared Key extension");
6070
6071     switch (hnd_type){
6072         case SSL_HND_CLIENT_HELLO: {
6073             guint32 identities_length, identities_end, binders_length;
6074
6075             proto_tree_add_item_ret_uint(psk_tree, hf->hf.hs_ext_psk_identities_length, tvb, offset, 2, ENC_BIG_ENDIAN, &identities_length);
6076             offset += 2;
6077
6078             if (offset_end - offset < identities_length) {
6079                 /* XXX expert info */
6080                 return offset;
6081             }
6082
6083             identities_end = offset + identities_length;
6084             while (offset < identities_end) {
6085                 guint32 identity_length;
6086                 proto_tree *identity_tree;
6087
6088                 identity_tree = proto_tree_add_subtree(psk_tree, tvb, offset, 4, hf->ett.hs_ext_psk_identity, NULL, "PSK Identity (");
6089
6090                 proto_tree_add_item_ret_uint(identity_tree, hf->hf.hs_ext_psk_identity_identity_length, tvb, offset, 2, ENC_BIG_ENDIAN, &identity_length);
6091                 offset += 2;
6092                 proto_item_append_text(identity_tree, "length: %u)", identity_length);
6093
6094                 if (identity_length > identities_end - offset) {
6095                     /* XXX expert info */
6096                     return offset;
6097                 }
6098
6099                 proto_tree_add_item(identity_tree, hf->hf.hs_ext_psk_identity_identity, tvb, offset, identity_length, ENC_BIG_ENDIAN);
6100                 offset += identity_length;
6101
6102                 proto_tree_add_item(identity_tree, hf->hf.hs_ext_psk_identity_obfuscated_ticket_age, tvb, offset, 4, ENC_BIG_ENDIAN);
6103                 offset += 4;
6104
6105                 proto_item_set_len(identity_tree, 2 + identity_length + 4);
6106             }
6107
6108             proto_tree_add_item_ret_uint(psk_tree, hf->hf.hs_ext_psk_binders_length, tvb, offset, 2, ENC_BIG_ENDIAN, &binders_length);
6109             offset += 2;
6110
6111             if (binders_length > offset_end - offset) {
6112                 /* XXX expert info */
6113                 return offset;
6114             }
6115
6116             proto_tree_add_item(psk_tree, hf->hf.hs_ext_psk_binders, tvb, offset, binders_length, ENC_NA);
6117             offset += binders_length;
6118         }
6119         break;
6120         case SSL_HND_SERVER_HELLO: {
6121             proto_tree_add_item(psk_tree, hf->hf.hs_ext_psk_identity_selected, tvb, offset, 2, ENC_BIG_ENDIAN);
6122             offset += 2;
6123         }
6124         break;
6125         default:
6126         break;
6127     }
6128
6129     return offset;
6130 }
6131
6132 static gint
6133 ssl_dissect_hnd_hello_ext_early_data(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6134                                          proto_tree *tree, guint32 offset, guint32 offset_end _U_,
6135                                          guint8 hnd_type)
6136 {
6137
6138     switch (hnd_type){
6139         case SSL_HND_CLIENT_HELLO:
6140             proto_tree_add_item(tree, hf->hf.hs_ext_early_data_obfuscated_ticket_age, tvb, offset, 4, ENC_BIG_ENDIAN);
6141             offset += 4;
6142             break;
6143         case SSL_HND_SERVER_HELLO: /* empty extension_data */
6144             break;
6145         default: /* no default */
6146         break;
6147     }
6148
6149     return offset;
6150 }
6151
6152 static gint
6153 ssl_dissect_hnd_hello_ext_supported_versions(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6154                                              proto_tree *tree, guint32 offset, guint32 offset_end)
6155 {
6156     if (offset_end - offset < 1) {
6157         return offset;
6158     }
6159
6160     proto_tree_add_item(tree, hf->hf.hs_ext_supported_versions_len, tvb, offset, 1, ENC_BIG_ENDIAN);
6161     offset += 1;
6162
6163     while(offset_end - offset >= 2){
6164         proto_tree_add_item(tree, hf->hf.hs_ext_supported_versions, tvb, offset, 2, ENC_BIG_ENDIAN);
6165         offset += 2;
6166     }
6167
6168     return offset;
6169 }
6170
6171 static gint
6172 ssl_dissect_hnd_hello_ext_cookie(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6173                                  packet_info *pinfo, proto_tree *tree,
6174                                  guint32 offset, guint32 offset_end)
6175 {
6176     /* https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.2.2
6177      *  struct {
6178      *      opaque cookie<1..2^16-1>;
6179      *  } Cookie;
6180      */
6181     guint32 cookie_length;
6182     /* opaque cookie<1..2^16-1> */
6183     if (!ssl_add_vector(hf, tvb, pinfo, tree, offset, offset_end, &cookie_length,
6184                         hf->hf.hs_ext_cookie_len, 1, G_MAXUINT16)) {
6185         return offset_end;
6186     }
6187     offset += 2;
6188
6189     proto_tree_add_item(tree, hf->hf.hs_ext_cookie, tvb, offset, cookie_length, ENC_NA);
6190     offset += cookie_length;
6191
6192     return offset;
6193 }
6194
6195 static gint
6196 ssl_dissect_hnd_hello_ext_psk_key_exchange_modes(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6197                                                  proto_tree *tree, guint32 offset, guint32 offset_end)
6198 {
6199     /*
6200      * enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode;
6201      *
6202      * struct {
6203      *     PskKeyExchangeMode ke_modes<1..255>;
6204      * } PskKeyExchangeModes;
6205      */
6206     guint32 ke_modes_length, i;
6207
6208     if (offset_end - offset < 1) {
6209         /* XXX expert info, there must be at least 1 ke mode */
6210         return offset;
6211     }
6212
6213     proto_tree_add_item_ret_uint(tree, hf->hf.hs_ext_psk_ke_modes_len, tvb, offset, 1, ENC_NA, &ke_modes_length);
6214     offset += 1;
6215
6216     if (ke_modes_length > offset_end - offset) {
6217         ke_modes_length = offset_end - offset;
6218         /* XXX expert info: size too large */
6219     }
6220
6221     for (i = 0; i < ke_modes_length; i++) {
6222         proto_tree_add_item(tree, hf->hf.hs_ext_psk_ke_mode, tvb, offset, 1, ENC_NA);
6223         offset += 1;
6224     }
6225
6226     return offset;
6227 }
6228
6229 static gint
6230 ssl_dissect_hnd_hello_ext_server_name(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6231                                       packet_info *pinfo, proto_tree *tree,
6232                                       guint32 offset, guint32 offset_end)
6233 {
6234     /* https://tools.ietf.org/html/rfc6066#section-3
6235      *
6236      *  struct {
6237      *      NameType name_type;
6238      *      select (name_type) {
6239      *          case host_name: HostName;
6240      *      } name;
6241      *  } ServerName;
6242      *
6243      *  enum {
6244      *      host_name(0), (255)
6245      *  } NameType;
6246      *
6247      *  opaque HostName<1..2^16-1>;
6248      *
6249      *  struct {
6250      *      ServerName server_name_list<1..2^16-1>
6251      *  } ServerNameList;
6252      */
6253     proto_tree *server_name_tree;
6254     guint32     list_length, server_name_length, next_offset;
6255
6256     /* The server SHALL include "server_name" extension with empty data. */
6257     if (offset == offset_end) {
6258         return offset;
6259     }
6260
6261     server_name_tree = proto_tree_add_subtree(tree, tvb, offset, offset_end - offset, hf->ett.hs_ext_server_name, NULL, "Server Name Indication extension");
6262
6263     /* ServerName server_name_list<1..2^16-1> */
6264     if (!ssl_add_vector(hf, tvb, pinfo, server_name_tree, offset, offset_end, &list_length,
6265                         hf->hf.hs_ext_server_name_list_len, 1, G_MAXUINT16)) {
6266         return offset_end;
6267     }
6268     offset += 2;
6269     next_offset = offset + list_length;
6270
6271     while (offset < next_offset) {
6272         proto_tree_add_item(server_name_tree, hf->hf.hs_ext_server_name_type,
6273                             tvb, offset, 1, ENC_NA);
6274         offset++;
6275
6276         /* opaque HostName<1..2^16-1> */
6277         if (!ssl_add_vector(hf, tvb, pinfo, server_name_tree, offset, next_offset, &server_name_length,
6278                            hf->hf.hs_ext_server_name_len, 1, G_MAXUINT16)) {
6279             return next_offset;
6280         }
6281         offset += 2;
6282
6283         proto_tree_add_item(server_name_tree, hf->hf.hs_ext_server_name,
6284                             tvb, offset, server_name_length, ENC_ASCII|ENC_NA);
6285         offset += server_name_length;
6286     }
6287     return offset;
6288 }
6289
6290 static gint
6291 ssl_dissect_hnd_hello_ext_session_ticket(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6292                                       proto_tree *tree, guint32 offset, guint32 offset_end, guint8 hnd_type, SslDecryptSession *ssl)
6293 {
6294     guint       ext_len = offset_end - offset;
6295     if (hnd_type == SSL_HND_CLIENT_HELLO && ssl && ext_len != 0) {
6296         tvb_ensure_bytes_exist(tvb, offset, ext_len);
6297         /* Save the Session Ticket such that it can be used as identifier for
6298          * restoring a previous Master Secret (in ChangeCipherSpec) */
6299         ssl->session_ticket.data = (guchar*)wmem_realloc(wmem_file_scope(),
6300                                     ssl->session_ticket.data, ext_len);
6301         ssl->session_ticket.data_len = ext_len;
6302         tvb_memcpy(tvb,ssl->session_ticket.data, offset, ext_len);
6303     }
6304     proto_tree_add_bytes_format(tree, hf->hf.hs_ext_data,
6305                                 tvb, offset, ext_len, NULL,
6306                                 "Data (%u byte%s)",
6307                                 ext_len, plurality(ext_len, "", "s"));
6308     return offset + ext_len;
6309 }
6310
6311 static gint
6312 ssl_dissect_hnd_hello_ext_cert_type(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6313                                     proto_tree *tree, guint32 offset, guint32 offset_end,
6314                                     guint8 hnd_type, guint16 ext_type, SslSession *session)
6315 {
6316     guint8      cert_list_length;
6317     guint8      cert_type;
6318     proto_tree *cert_list_tree;
6319     proto_item *ti;
6320
6321     switch(hnd_type){
6322     case SSL_HND_CLIENT_HELLO:
6323         cert_list_length = tvb_get_guint8(tvb, offset);
6324         proto_tree_add_item(tree, hf->hf.hs_ext_cert_types_len,
6325                             tvb, offset, 1, ENC_BIG_ENDIAN);
6326         offset += 1;
6327         if (offset_end - offset != (guint32)cert_list_length)
6328             return offset;
6329
6330         ti = proto_tree_add_item(tree, hf->hf.hs_ext_cert_types, tvb, offset,
6331                                  cert_list_length, cert_list_length);
6332         proto_item_append_text(ti, " (%d)", cert_list_length);
6333
6334         /* make this a subtree */
6335         cert_list_tree = proto_item_add_subtree(ti, hf->ett.hs_ext_cert_types);
6336
6337         /* loop over all point formats */
6338         while (cert_list_length > 0)
6339         {
6340             proto_tree_add_item(cert_list_tree, hf->hf.hs_ext_cert_type, tvb, offset, 1, ENC_BIG_ENDIAN);
6341             offset++;
6342             cert_list_length--;
6343         }
6344     break;
6345     case SSL_HND_SERVER_HELLO:
6346         cert_type = tvb_get_guint8(tvb, offset);
6347         proto_tree_add_item(tree, hf->hf.hs_ext_cert_type, tvb, offset, 1, ENC_BIG_ENDIAN);
6348         offset += 1;
6349         if (ext_type == SSL_HND_HELLO_EXT_CERT_TYPE || ext_type == SSL_HND_HELLO_EXT_CLIENT_CERT_TYPE) {
6350             session->client_cert_type = cert_type;
6351         }
6352         if (ext_type == SSL_HND_HELLO_EXT_CERT_TYPE || ext_type == SSL_HND_HELLO_EXT_SERVER_CERT_TYPE) {
6353            session->server_cert_type = cert_type;
6354         }
6355     break;
6356     default: /* no default */
6357     break;
6358     }
6359
6360     return offset;
6361 }
6362
6363 static gint
6364 ssl_dissect_hnd_hello_common(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6365                              proto_tree *tree, guint32 offset,
6366                              SslSession *session, SslDecryptSession *ssl,
6367                              gboolean from_server)
6368 {
6369     nstime_t     gmt_unix_time;
6370     guint8       sessid_length;
6371     proto_tree  *rnd_tree;
6372     proto_tree  *ti_rnd;
6373
6374     /* Prepare for renegotiation by resetting the state. */
6375     ssl_reset_session(session, ssl, !from_server);
6376
6377     if (ssl) {
6378         StringInfo *rnd;
6379         if (from_server)
6380             rnd = &ssl->server_random;
6381         else
6382             rnd = &ssl->client_random;
6383
6384         /* save provided random for later keyring generation */
6385         tvb_memcpy(tvb, rnd->data, offset, 32);
6386         rnd->data_len = 32;
6387         if (from_server)
6388             ssl->state |= SSL_SERVER_RANDOM;
6389         else
6390             ssl->state |= SSL_CLIENT_RANDOM;
6391         ssl_debug_printf("%s found %s RANDOM -> state 0x%02X\n", G_STRFUNC,
6392                 from_server ? "SERVER" : "CLIENT", ssl->state);
6393     }
6394
6395     ti_rnd = proto_tree_add_item(tree, hf->hf.hs_random, tvb, offset, 32, ENC_NA);
6396
6397     if (session->version != TLSV1DOT3_VERSION) { /* No time on first bytes random with TLS 1.3 */
6398
6399         rnd_tree = proto_item_add_subtree(ti_rnd, hf->ett.hs_random);
6400         /* show the time */
6401         gmt_unix_time.secs  = tvb_get_ntohl(tvb, offset);
6402         gmt_unix_time.nsecs = 0;
6403         proto_tree_add_time(rnd_tree, hf->hf.hs_random_time,
6404                 tvb, offset, 4, &gmt_unix_time);
6405         offset += 4;
6406
6407         /* show the random bytes */
6408         proto_tree_add_item(rnd_tree, hf->hf.hs_random_bytes,
6409                 tvb, offset, 28, ENC_NA);
6410         offset += 28;
6411     } else {
6412         offset += 32;
6413     }
6414
6415     if (from_server == 0 || session->version != TLSV1DOT3_VERSION) { /* No Session ID with TLS 1.3 on Server Hello */
6416         /* show the session id (length followed by actual Session ID) */
6417         sessid_length = tvb_get_guint8(tvb, offset);
6418         proto_tree_add_item(tree, hf->hf.hs_session_id_len,
6419                 tvb, offset, 1, ENC_BIG_ENDIAN);
6420         offset++;
6421
6422         if (ssl) {
6423             /* save the authorative SID for later use in ChangeCipherSpec.
6424              * (D)TLS restricts the SID to 32 chars, it does not make sense to
6425              * save more, so ignore larger ones. */
6426             if (from_server && sessid_length <= 32) {
6427                 tvb_memcpy(tvb, ssl->session_id.data, offset, sessid_length);
6428                 ssl->session_id.data_len = sessid_length;
6429             }
6430         }
6431         if (sessid_length > 0) {
6432             proto_tree_add_item(tree, hf->hf.hs_session_id,
6433                     tvb, offset, sessid_length, ENC_NA);
6434             offset += sessid_length;
6435         }
6436     }
6437
6438     return offset;
6439 }
6440
6441 static gint
6442 ssl_dissect_hnd_hello_ext_status_request(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
6443                                          guint32 offset, gboolean has_length)
6444 {
6445     guint    cert_status_type;
6446
6447     cert_status_type = tvb_get_guint8(tvb, offset);
6448     proto_tree_add_item(tree, hf->hf.hs_ext_cert_status_type,
6449                         tvb, offset, 1, ENC_NA);
6450     offset++;
6451
6452     if (has_length) {
6453         proto_tree_add_item(tree, hf->hf.hs_ext_cert_status_request_len,
6454                             tvb, offset, 2, ENC_BIG_ENDIAN);
6455         offset += 2;
6456     }
6457
6458     switch (cert_status_type) {
6459     case SSL_HND_CERT_STATUS_TYPE_OCSP:
6460     case SSL_HND_CERT_STATUS_TYPE_OCSP_MULTI:
6461         {
6462             guint16      responder_id_list_len;
6463             guint16      request_extensions_len;
6464             proto_item  *responder_id;
6465             proto_item  *request_extensions;
6466
6467             responder_id_list_len = tvb_get_ntohs(tvb, offset);
6468             responder_id =
6469                 proto_tree_add_item(tree,
6470                                     hf->hf.hs_ext_cert_status_responder_id_list_len,
6471                                     tvb, offset, 2, ENC_BIG_ENDIAN);
6472             offset += 2;
6473             if (responder_id_list_len != 0) {
6474                 expert_add_info_format(NULL, responder_id,
6475                                        &hf->ei.hs_ext_cert_status_undecoded,
6476                                        "Responder ID list is not implemented, contact Wireshark"
6477                                        " developers if you want this to be supported");
6478                 /* Non-empty responder ID list would mess with extensions. */
6479                 break;
6480             }
6481
6482             request_extensions_len = tvb_get_ntohs(tvb, offset);
6483             request_extensions =
6484                 proto_tree_add_item(tree,
6485                                     hf->hf.hs_ext_cert_status_request_extensions_len, tvb, offset,
6486                                     2, ENC_BIG_ENDIAN);
6487             offset += 2;
6488             if (request_extensions_len != 0)
6489                 expert_add_info_format(NULL, request_extensions,
6490                                        &hf->ei.hs_ext_cert_status_undecoded,
6491                                        "Request Extensions are not implemented, contact"
6492                                        " Wireshark developers if you want this to be supported");
6493             break;
6494         }
6495     }
6496
6497     return offset;
6498 }
6499
6500 static gint
6501 ssl_dissect_hnd_hello_ext_status_request_v2(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
6502                                             guint32 offset)
6503 {
6504     gint32   list_len;
6505
6506     list_len = tvb_get_ntohs(tvb, offset);
6507     offset += 2;
6508
6509     while (list_len > 0) {
6510         guint32 prev_offset = offset;
6511         offset = ssl_dissect_hnd_hello_ext_status_request(hf, tvb, tree, offset, TRUE);
6512         list_len -= (offset - prev_offset);
6513     }
6514
6515     return offset;
6516 }
6517
6518 static gint
6519 ssl_dissect_hnd_hello_ext_elliptic_curves(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6520                                           proto_tree *tree, guint32 offset)
6521 {
6522     guint16     curves_length;
6523     proto_tree *curves_tree;
6524     proto_item *ti;
6525
6526     curves_length = tvb_get_ntohs(tvb, offset);
6527     proto_tree_add_item(tree, hf->hf.hs_ext_elliptic_curves_len,
6528                         tvb, offset, 2, ENC_BIG_ENDIAN);
6529
6530     offset += 2;
6531     ti = proto_tree_add_none_format(tree,
6532                                     hf->hf.hs_ext_elliptic_curves,
6533                                     tvb, offset, curves_length,
6534                                     "Elliptic curves (%d curve%s)",
6535                                     curves_length / 2,
6536                                     plurality(curves_length/2, "", "s"));
6537
6538     /* make this a subtree */
6539     curves_tree = proto_item_add_subtree(ti, hf->ett.hs_ext_curves);
6540
6541     /* loop over all curves */
6542     while (curves_length > 0)
6543     {
6544         proto_tree_add_item(curves_tree, hf->hf.hs_ext_elliptic_curve, tvb, offset, 2, ENC_BIG_ENDIAN);
6545         offset += 2;
6546         curves_length -= 2;
6547     }
6548
6549     return offset;
6550 }
6551
6552 static gint
6553 ssl_dissect_hnd_hello_ext_ec_point_formats(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6554                                            proto_tree *tree, guint32 offset)
6555 {
6556     guint8      ecpf_length;
6557     proto_tree *ecpf_tree;
6558     proto_item *ti;
6559
6560     ecpf_length = tvb_get_guint8(tvb, offset);
6561     proto_tree_add_item(tree, hf->hf.hs_ext_ec_point_formats_len,
6562         tvb, offset, 1, ENC_BIG_ENDIAN);
6563
6564     offset += 1;
6565     ti = proto_tree_add_none_format(tree,
6566                                     hf->hf.hs_ext_elliptic_curves,
6567                                     tvb, offset, ecpf_length,
6568                                     "Elliptic curves point formats (%d)",
6569                                     ecpf_length);
6570
6571     /* make this a subtree */
6572     ecpf_tree = proto_item_add_subtree(ti, hf->ett.hs_ext_curves_point_formats);
6573
6574     /* loop over all point formats */
6575     while (ecpf_length > 0)
6576     {
6577         proto_tree_add_item(ecpf_tree, hf->hf.hs_ext_ec_point_format, tvb, offset, 1, ENC_BIG_ENDIAN);
6578         offset++;
6579         ecpf_length--;
6580     }
6581
6582     return offset;
6583 }
6584 /** TLS Extensions (in Client Hello and Server Hello). }}} */
6585
6586 /* Whether the Content and Handshake Types are valid; handle Protocol Version. {{{ */
6587 gboolean
6588 ssl_is_valid_content_type(guint8 type)
6589 {
6590     switch ((ContentType) type) {
6591     case SSL_ID_CHG_CIPHER_SPEC:
6592     case SSL_ID_ALERT:
6593     case SSL_ID_HANDSHAKE:
6594     case SSL_ID_APP_DATA:
6595     case SSL_ID_HEARTBEAT:
6596         return TRUE;
6597     }
6598     return FALSE;
6599 }
6600
6601 gboolean
6602 ssl_is_valid_handshake_type(guint8 hs_type, gboolean is_dtls)
6603 {
6604     switch ((HandshakeType) hs_type) {
6605     case SSL_HND_HELLO_VERIFY_REQUEST:
6606         /* hello_verify_request is DTLS-only */
6607         return is_dtls;
6608
6609     case SSL_HND_HELLO_REQUEST:
6610     case SSL_HND_CLIENT_HELLO:
6611     case SSL_HND_SERVER_HELLO:
6612     case SSL_HND_NEWSESSION_TICKET:
6613     case SSL_HND_HELLO_RETRY_REQUEST:
6614     case SSL_HND_ENCRYPTED_EXTENSIONS:
6615     case SSL_HND_CERTIFICATE:
6616     case SSL_HND_SERVER_KEY_EXCHG:
6617     case SSL_HND_CERT_REQUEST:
6618     case SSL_HND_SVR_HELLO_DONE:
6619     case SSL_HND_CERT_VERIFY:
6620     case SSL_HND_CLIENT_KEY_EXCHG:
6621     case SSL_HND_FINISHED:
6622     case SSL_HND_CERT_URL:
6623     case SSL_HND_CERT_STATUS:
6624     case SSL_HND_SUPPLEMENTAL_DATA:
6625     case SSL_HND_ENCRYPTED_EXTS:
6626         return TRUE;
6627     }
6628     return FALSE;
6629 }
6630
6631 static gboolean
6632 ssl_is_authoritative_version_message(guint8 content_type, guint8 handshake_type,
6633                                      gboolean is_dtls)
6634 {
6635     /* Consider all valid Handshake messages (except for Client Hello) and
6636      * all other valid record types (other than Handshake) */
6637     return (content_type == SSL_ID_HANDSHAKE &&
6638             ssl_is_valid_handshake_type(handshake_type, is_dtls) &&
6639             handshake_type != SSL_HND_CLIENT_HELLO) ||
6640            (content_type != SSL_ID_HANDSHAKE &&
6641             ssl_is_valid_content_type(content_type));
6642 }
6643
6644 void
6645 ssl_try_set_version(SslSession *session, SslDecryptSession *ssl,
6646                     guint8 content_type, guint8 handshake_type,
6647                     gboolean is_dtls, guint16 version)
6648 {
6649     if (!ssl_is_authoritative_version_message(content_type, handshake_type,
6650                 is_dtls))
6651         return;
6652
6653     switch (version) {
6654     case SSLV3_VERSION:
6655     case TLSV1_VERSION:
6656     case TLSV1DOT1_VERSION:
6657     case TLSV1DOT2_VERSION:
6658     case TLSV1DOT3_VERSION:
6659         if (is_dtls)
6660             return;
6661         break;
6662
6663     case DTLSV1DOT0_VERSION:
6664     case DTLSV1DOT0_OPENSSL_VERSION:
6665     case DTLSV1DOT2_VERSION:
6666         if (!is_dtls)
6667             return;
6668         break;
6669
6670     default: /* invalid version number */
6671         return;
6672     }
6673
6674     session->version = version;
6675     if (ssl) {
6676         ssl->state |= SSL_VERSION;
6677         ssl_debug_printf("%s found version 0x%04X -> state 0x%02X\n", G_STRFUNC, version, ssl->state);
6678     }
6679 }
6680 /* }}} */
6681
6682
6683 /* Client Hello and Server Hello dissections. {{{ */
6684 static gint
6685 ssl_dissect_hnd_hello_ext(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
6686                           packet_info* pinfo, guint32 offset, guint32 offset_end, guint8 hnd_type,
6687                           SslSession *session, SslDecryptSession *ssl,
6688                           gboolean is_dtls);
6689 void
6690 ssl_dissect_hnd_cli_hello(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6691                           packet_info *pinfo, proto_tree *tree, guint32 offset,
6692                           guint32 length, SslSession *session,
6693                           SslDecryptSession *ssl, dtls_hfs_t *dtls_hfs)
6694 {
6695     /* struct {
6696      *     ProtocolVersion client_version;
6697      *     Random random;
6698      *     SessionID session_id;
6699      *     opaque cookie<0..32>;                   //new field for DTLS
6700      *     CipherSuite cipher_suites<2..2^16-1>;
6701      *     CompressionMethod compression_methods<1..2^8-1>;
6702      *     Extension client_hello_extension_list<0..2^16-1>;
6703      * } ClientHello;
6704      *
6705      */
6706     proto_item *ti;
6707     proto_tree *cs_tree;
6708     guint16     cipher_suite_length;
6709     guint8      compression_methods_length;
6710     guint8      compression_method;
6711     guint16     start_offset = offset;
6712
6713     /* show the client version */
6714     proto_tree_add_item(tree, hf->hf.hs_client_version, tvb,
6715                         offset, 2, ENC_BIG_ENDIAN);
6716     offset += 2;
6717
6718     /* dissect fields that are also present in ClientHello */
6719     offset = ssl_dissect_hnd_hello_common(hf, tvb, tree, offset, session, ssl, FALSE);
6720
6721     /* fields specific for DTLS (cookie_len, cookie) */
6722     if (dtls_hfs != NULL) {
6723         /* look for a cookie */
6724         guint8 cookie_length = tvb_get_guint8(tvb, offset);
6725
6726         proto_tree_add_uint(tree, dtls_hfs->hf_dtls_handshake_cookie_len,
6727                             tvb, offset, 1, cookie_length);
6728         offset++;
6729         if (cookie_length > 0) {
6730             proto_tree_add_item(tree, dtls_hfs->hf_dtls_handshake_cookie,
6731                                 tvb, offset, cookie_length, ENC_NA);
6732             offset += cookie_length;
6733         }
6734     }
6735
6736     /* tell the user how many cipher suites there are */
6737     cipher_suite_length = tvb_get_ntohs(tvb, offset);
6738     ti = proto_tree_add_item(tree, hf->hf.hs_cipher_suites_len,
6739                              tvb, offset, 2, ENC_BIG_ENDIAN);
6740     offset += 2;
6741     if (cipher_suite_length > 0) {
6742         if (cipher_suite_length % 2) {
6743             expert_add_info_format(pinfo, ti, &hf->ei.hs_cipher_suites_len_bad,
6744                 "Cipher suite length (%d) must be a multiple of 2",
6745                 cipher_suite_length);
6746             return;
6747         }
6748         ti = proto_tree_add_none_format(tree,
6749                                         hf->hf.hs_cipher_suites,
6750                                         tvb, offset, cipher_suite_length,
6751                                         "Cipher Suites (%d suite%s)",
6752                                         cipher_suite_length / 2,
6753                                         plurality(cipher_suite_length/2, "", "s"));
6754
6755         /* make this a subtree */
6756         cs_tree = proto_item_add_subtree(ti, hf->ett.cipher_suites);
6757
6758         while (cipher_suite_length > 0) {
6759             proto_tree_add_item(cs_tree, hf->hf.hs_cipher_suite,
6760                                 tvb, offset, 2, ENC_BIG_ENDIAN);
6761             offset += 2;
6762             cipher_suite_length -= 2;
6763         }
6764     }
6765     /* tell the user how many compression methods there are */
6766     compression_methods_length = tvb_get_guint8(tvb, offset);
6767     proto_tree_add_uint(tree, hf->hf.hs_comp_methods_len,
6768                         tvb, offset, 1, compression_methods_length);
6769     offset += 1;
6770     if (compression_methods_length > 0) {
6771         ti = proto_tree_add_none_format(tree,
6772                                         hf->hf.hs_comp_methods,
6773                                         tvb, offset, compression_methods_length,
6774                                         "Compression Methods (%u method%s)",
6775                                         compression_methods_length,
6776                                         plurality(compression_methods_length,
6777                                           "", "s"));
6778
6779         /* make this a subtree */
6780         cs_tree = proto_item_add_subtree(ti, hf->ett.comp_methods);
6781
6782         while (compression_methods_length > 0) {
6783             compression_method = tvb_get_guint8(tvb, offset);
6784             /* TODO: make reserved/private comp meth. fields selectable */
6785             if (compression_method < 64)
6786                 proto_tree_add_uint(cs_tree, hf->hf.hs_comp_method,
6787                                     tvb, offset, 1, compression_method);
6788             else if (compression_method > 63 && compression_method < 193)
6789                 proto_tree_add_uint_format_value(cs_tree, hf->hf.hs_comp_method, tvb, offset, 1,
6790                                     compression_method, "Reserved - to be assigned by IANA (%u)",
6791                                     compression_method);
6792             else
6793                 proto_tree_add_uint_format_value(cs_tree, hf->hf.hs_comp_method, tvb, offset, 1,
6794                                     compression_method, "Private use range (%u)",
6795                                     compression_method);
6796             offset++;
6797             compression_methods_length--;
6798         }
6799     }
6800     if (length > offset - start_offset) {
6801         ssl_dissect_hnd_hello_ext(hf, tvb, tree, pinfo, offset,
6802                                   start_offset + length, SSL_HND_CLIENT_HELLO,
6803                                   session, ssl, dtls_hfs != NULL);
6804     }
6805 }
6806
6807 void
6808 ssl_dissect_hnd_srv_hello(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6809                           packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 length,
6810                           SslSession *session, SslDecryptSession *ssl,
6811                           gboolean is_dtls)
6812 {
6813     /* struct {
6814      *     ProtocolVersion server_version;
6815      *     Random random;
6816      *     SessionID session_id;
6817      *     CipherSuite cipher_suite;
6818      *     CompressionMethod compression_method;
6819      *     Extension server_hello_extension_list<0..2^16-1>;
6820      * } ServerHello;
6821      */
6822     guint16 server_version;
6823     guint16 start_offset = offset;
6824
6825     /* This version is always better than the guess at the Record Layer */
6826     server_version = tvb_get_ntohs(tvb, offset);
6827     if((server_version & 0xFF00) == 0x7f00) { /* if server_version start with 0x7f, it is (and force) TLS 1.3 */
6828         server_version = TLSV1DOT3_VERSION;
6829     }
6830     ssl_try_set_version(session, ssl, SSL_ID_HANDSHAKE, SSL_HND_SERVER_HELLO,
6831             is_dtls, server_version);
6832     col_set_str(pinfo->cinfo, COL_PROTOCOL,
6833                 val_to_str_const(server_version, ssl_version_short_names, "SSL"));
6834
6835     /* Initially assume that the session is resumed. If this is not the case, a
6836      * ServerHelloDone will be observed before the ChangeCipherSpec message
6837      * which will reset this flag. */
6838     session->is_session_resumed = TRUE;
6839
6840     /* show the server version */
6841     proto_tree_add_item(tree, hf->hf.hs_server_version, tvb,
6842                         offset, 2, ENC_BIG_ENDIAN);
6843     offset += 2;
6844
6845     /* dissect fields that are also present in ClientHello */
6846     offset = ssl_dissect_hnd_hello_common(hf, tvb, tree, offset, session, ssl, TRUE);
6847
6848     if (ssl) {
6849         /* store selected cipher suite for decryption */
6850         ssl->session.cipher = tvb_get_ntohs(tvb, offset);
6851
6852         if (!(ssl->cipher_suite = ssl_find_cipher(ssl->session.cipher))) {
6853             ssl->state &= ~SSL_CIPHER;
6854             ssl_debug_printf("%s can't find cipher suite 0x%04X\n",
6855                              G_STRFUNC, ssl->session.cipher);
6856         } else {
6857             /* Cipher found, save this for the delayed decoder init */
6858             ssl->state |= SSL_CIPHER;
6859             ssl_debug_printf("%s found CIPHER 0x%04X %s -> state 0x%02X\n",
6860                              G_STRFUNC, ssl->session.cipher,
6861                              val_to_str_ext_const(ssl->session.cipher,
6862                                  &ssl_31_ciphersuite_ext, "unknown"),
6863                              ssl->state);
6864         }
6865     }
6866
6867     /* now the server-selected cipher suite */
6868     proto_tree_add_item(tree, hf->hf.hs_cipher_suite,
6869                         tvb, offset, 2, ENC_BIG_ENDIAN);
6870     offset += 2;
6871
6872     if (session->version != TLSV1DOT3_VERSION) { /* No compression with TLS 1.3 */
6873         if (ssl) {
6874             /* store selected compression method for decryption */
6875             ssl->session.compression = tvb_get_guint8(tvb, offset);
6876         }
6877         /* and the server-selected compression method */
6878         proto_tree_add_item(tree, hf->hf.hs_comp_method,
6879                             tvb, offset, 1, ENC_BIG_ENDIAN);
6880         offset++;
6881     }
6882
6883     /* remaining data are extensions */
6884     if (length > offset - start_offset) {
6885         ssl_dissect_hnd_hello_ext(hf, tvb, tree, pinfo, offset,
6886                                   start_offset + length, SSL_HND_SERVER_HELLO,
6887                                   session, ssl, is_dtls);
6888     }
6889 }
6890 /* Client Hello and Server Hello dissections. }}} */
6891
6892 /* New Session Ticket dissection. {{{ */
6893 void
6894 ssl_dissect_hnd_new_ses_ticket(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6895                                proto_tree *tree, guint32 offset,
6896                                SslDecryptSession *ssl _U_,
6897                                GHashTable *session_hash _U_)
6898 {
6899     proto_tree  *subtree;
6900     guint16      ticket_len;
6901
6902     /* length of session ticket, may be 0 if the server has sent the
6903      * SessionTicket extension, but decides not to use one. */
6904     ticket_len = tvb_get_ntohs(tvb, offset + 4);
6905     subtree = proto_tree_add_subtree(tree, tvb, offset, 6 + ticket_len,
6906                                      hf->ett.session_ticket, NULL,
6907                                      "TLS Session Ticket");
6908
6909     /* ticket lifetime hint */
6910     proto_tree_add_item(subtree, hf->hf.hs_session_ticket_lifetime_hint,
6911                         tvb, offset, 4, ENC_BIG_ENDIAN);
6912     offset += 4;
6913
6914     /* opaque ticket (length, data) */
6915     proto_tree_add_item(subtree, hf->hf.hs_session_ticket_len,
6916                         tvb, offset, 2, ENC_BIG_ENDIAN);
6917     offset += 2;
6918     /* Content depends on implementation, so just show data! */
6919     proto_tree_add_item(subtree, hf->hf.hs_session_ticket,
6920                         tvb, offset, ticket_len, ENC_NA);
6921     /* save the session ticket to cache for ssl_finalize_decryption */
6922 #ifdef HAVE_LIBGCRYPT
6923     if (ssl) {
6924         tvb_ensure_bytes_exist(tvb, offset, ticket_len);
6925         ssl->session_ticket.data = (guchar*)wmem_realloc(wmem_file_scope(),
6926                                     ssl->session_ticket.data, ticket_len);
6927         ssl->session_ticket.data_len = ticket_len;
6928         tvb_memcpy(tvb, ssl->session_ticket.data, offset, ticket_len);
6929         /* NewSessionTicket is received after the first (client)
6930          * ChangeCipherSpec, and before the second (server) ChangeCipherSpec.
6931          * Since the second CCS has already the session key available it will
6932          * just return. To ensure that the session ticket is mapped to a
6933          * master key (from the first CCS), save the ticket here too. */
6934         ssl_save_master_key("Session Ticket", session_hash,
6935                             &ssl->session_ticket, &ssl->master_secret);
6936         ssl->state |= SSL_NEW_SESSION_TICKET;
6937     }
6938 #endif
6939 } /* }}} */
6940
6941 void
6942 ssl_dissect_hnd_hello_retry_request(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6943                                     packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 length,
6944                                     SslSession *session, SslDecryptSession *ssl,
6945                                     gboolean is_dtls)
6946 {
6947     /* struct {
6948      *     ProtocolVersion server_version;
6949      *     Extension extensions<2..2^16-1>;
6950      * } HelloRetryRequest;
6951      */
6952     guint16 start_offset = offset;
6953
6954     proto_tree_add_item(tree, hf->hf.hs_server_version, tvb,
6955                         offset, 2, ENC_BIG_ENDIAN);
6956     offset += 2;
6957
6958     /* remaining data are extensions */
6959     if (length > offset - start_offset) {
6960         ssl_dissect_hnd_hello_ext(hf, tvb, tree, pinfo, offset,
6961                                   start_offset + length, SSL_HND_HELLO_RETRY_REQUEST,
6962                                   session, ssl, is_dtls);
6963     }
6964 }
6965
6966 void
6967 ssl_dissect_hnd_encrypted_extensions(ssl_common_dissect_t *hf, tvbuff_t *tvb,
6968                                      packet_info* pinfo, proto_tree *tree, guint32 offset, guint32 length,
6969                                      SslSession *session, SslDecryptSession *ssl,
6970                                      gboolean is_dtls)
6971 {
6972     /* struct {
6973      *     Extension extensions<0..2^16-1>;
6974      * } EncryptedExtensions;
6975      */
6976     ssl_dissect_hnd_hello_ext(hf, tvb, tree, pinfo, offset,
6977                               offset + length, SSL_HND_ENCRYPTED_EXTENSIONS,
6978                               session, ssl, is_dtls);
6979 }
6980
6981 /* Certificate and Certificate Request dissections. {{{ */
6982 void
6983 ssl_dissect_hnd_cert(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
6984                      guint32 offset, packet_info *pinfo,
6985                      const SslSession *session, SslDecryptSession *ssl _U_,
6986                      GHashTable *key_hash _U_, gint is_from_server)
6987 {
6988     /* opaque ASN.1Cert<1..2^24-1>;
6989      *
6990      * struct {
6991      *     select(certificate_type) {
6992      *
6993      *         // certificate type defined in RFC 7250
6994      *         case RawPublicKey:
6995      *           opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
6996      *
6997      *         // X.509 certificate defined in RFC 5246
6998      *         case X.509:
6999      *           ASN.1Cert certificate_list<0..2^24-1>;
7000      *     };
7001      * } Certificate;
7002      *
7003      * draft-ietf-tls-tls13-18:
7004      *     opaque ASN1Cert<1..2^24-1>;
7005      *     struct {
7006      *         ASN1Cert cert_data;
7007      *         Extension extensions<0..2^16-1>;
7008      *     } CertificateEntry;
7009      *     struct {
7010      *         opaque certificate_request_context<0..2^8-1>;
7011      *         CertificateEntry certificate_list<0..2^24-1>;
7012      *     } Certificate;
7013      */
7014     enum { CERT_X509, CERT_RPK } cert_type;
7015     asn1_ctx_t  asn1_ctx;
7016 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
7017     gnutls_datum_t subjectPublicKeyInfo = { NULL, 0 };
7018 #endif
7019
7020     asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
7021
7022     if ((is_from_server && session->server_cert_type == SSL_HND_CERT_TYPE_RAW_PUBLIC_KEY) ||
7023         (!is_from_server && session->client_cert_type == SSL_HND_CERT_TYPE_RAW_PUBLIC_KEY)) {
7024         cert_type = CERT_RPK;
7025     } else {
7026         cert_type = CERT_X509;
7027     }
7028
7029 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
7030     /* Ask the pkcs1 dissector to return the public key details */
7031     if (ssl)
7032         asn1_ctx.private_data = &subjectPublicKeyInfo;
7033 #endif
7034
7035     switch (cert_type) {
7036     case CERT_RPK:
7037         {
7038             proto_tree_add_item(tree, hf->hf.hs_certificate_len,
7039                                 tvb, offset, 3, ENC_BIG_ENDIAN);
7040             offset += 3;
7041
7042             dissect_x509af_SubjectPublicKeyInfo(FALSE, tvb, offset, &asn1_ctx, tree, hf->hf.hs_certificate);
7043
7044             break;
7045         }
7046     case CERT_X509:
7047         {
7048             guint32     certificate_list_length;
7049             proto_item *ti;
7050             proto_tree *subtree;
7051
7052             /* TLS 1.3: opaque certificate_request_context<0..2^8-1> */
7053             if (session->version == TLSV1DOT3_VERSION) {
7054                 guint32 context_length;
7055                 proto_tree_add_item_ret_uint(tree, hf->hf.hs_certificate_request_context_length,
7056                                              tvb, offset, 1, ENC_NA, &context_length);
7057                 offset++;
7058                 if (context_length > 0) {
7059                     proto_tree_add_item(tree, hf->hf.hs_certificate_request_context,
7060                                         tvb, offset, context_length, ENC_NA);
7061                     offset += context_length;
7062                 }
7063             }
7064
7065             proto_tree_add_item_ret_uint(tree, hf->hf.hs_certificates_len,
7066                                          tvb, offset, 3, ENC_BIG_ENDIAN, &certificate_list_length);
7067             offset += 3;            /* 24-bit length value */
7068
7069             if (certificate_list_length > 0) {
7070                 ti = proto_tree_add_none_format(tree,
7071                                                 hf->hf.hs_certificates,
7072                                                 tvb, offset, certificate_list_length,
7073                                                 "Certificates (%u bytes)",
7074                                                 certificate_list_length);
7075
7076                 /* make it a subtree */
7077                 subtree = proto_item_add_subtree(ti, hf->ett.certificates);
7078
7079                 /* iterate through each certificate */
7080                 while (certificate_list_length > 0) {
7081                     /* get the length of the current certificate */
7082                     guint32 cert_length;
7083                     proto_tree_add_item_ret_uint(subtree, hf->hf.hs_certificate_len,
7084                                                  tvb, offset, 3, ENC_BIG_ENDIAN, &cert_length);
7085                     offset += 3;
7086                     certificate_list_length -= 3 + cert_length;
7087
7088                     dissect_x509af_Certificate(FALSE, tvb, offset, &asn1_ctx, subtree, hf->hf.hs_certificate);
7089 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
7090                     /* Only attempt to get the RSA modulus for the first cert. */
7091                     asn1_ctx.private_data = NULL;
7092 #endif
7093
7094                     offset += cert_length;
7095
7096                     /* TLS 1.3: Extension extensions<0..2^16-1> */
7097                     if (session->version == TLSV1DOT3_VERSION) {
7098                         guint32 extensions_length;
7099                         proto_tree_add_item_ret_uint(subtree, hf->hf.hs_exts_len,
7100                                                      tvb, offset, 2, ENC_BIG_ENDIAN, &extensions_length);
7101                         offset += 2;
7102
7103                         // XXX dissect OCSP and SCT extensions
7104                         // https://tools.ietf.org/html/draft-ietf-tls-tls13-18#section-4.4.1.1
7105                         offset += extensions_length;
7106                         certificate_list_length -= 2 + extensions_length;
7107                     }
7108                 }
7109             }
7110             break;
7111         }
7112     }
7113
7114 #if defined(HAVE_LIBGNUTLS) && defined(HAVE_LIBGCRYPT)
7115     if (is_from_server && ssl)
7116         ssl_find_private_key_by_pubkey(ssl, key_hash, &subjectPublicKeyInfo);
7117 #endif
7118 }
7119
7120 void
7121 ssl_dissect_hnd_cert_req(ssl_common_dissect_t *hf, tvbuff_t *tvb, packet_info *pinfo,
7122                          proto_tree *tree, guint32 offset, guint32 offset_end,
7123                          const SslSession *session)
7124 {
7125     /*
7126      *    enum {
7127      *        rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
7128      *        (255)
7129      *    } ClientCertificateType;
7130      *
7131      *    opaque DistinguishedName<1..2^16-1>;
7132      *
7133      *    struct {
7134      *        ClientCertificateType certificate_types<1..2^8-1>;
7135      *        DistinguishedName certificate_authorities<3..2^16-1>;
7136      *    } CertificateRequest;
7137      *
7138      *
7139      * As per TLSv1.2 (RFC 5246) the format has changed to:
7140      *
7141      *    enum {
7142      *        rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
7143      *        rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),
7144      *        fortezza_dms_RESERVED(20), (255)
7145      *    } ClientCertificateType;
7146      *
7147      *    enum {
7148      *        none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
7149      *        sha512(6), (255)
7150      *    } HashAlgorithm;
7151      *
7152      *    enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
7153      *      SignatureAlgorithm;
7154      *
7155      *    struct {
7156      *          HashAlgorithm hash;
7157      *          SignatureAlgorithm signature;
7158      *    } SignatureAndHashAlgorithm;
7159      *
7160      *    SignatureAndHashAlgorithm
7161      *      supported_signature_algorithms<2..2^16-2>;
7162      *
7163      *    opaque DistinguishedName<1..2^16-1>;
7164      *
7165      *    struct {
7166      *        ClientCertificateType certificate_types<1..2^8-1>;
7167      *        SignatureAndHashAlgorithm
7168      *          supported_signature_algorithms<2^16-1>;
7169      *        DistinguishedName certificate_authorities<0..2^16-1>;
7170      *    } CertificateRequest;
7171      *
7172      * draft-ietf-tls-tls13-18 (soon obsolete!):
7173      * Note: certificate_extensions is not dissected since it is removed in next
7174      * draft.
7175      *
7176      *    struct {
7177      *        opaque certificate_request_context<0..2^8-1>;
7178      *        SignatureScheme supported_signature_algorithms<2..2^16-2>;
7179      *        DistinguishedName certificate_authorities<0..2^16-1>;
7180      *        CertificateExtension certificate_extensions<0..2^16-1>;
7181      *    } CertificateRequest;
7182      *
7183      * draft-ietf-tls-tls13 (between -18 and -19, 2017-01-30):
7184      *
7185      *    struct {
7186      *        opaque certificate_request_context<0..2^8-1>;
7187      *        Extension extensions<2..2^16-1>;
7188      *    } CertificateRequest;
7189      */
7190     proto_item *ti;
7191     proto_tree *subtree;
7192     guint8      cert_types_count;
7193     gint        dnames_length;
7194     asn1_ctx_t  asn1_ctx;
7195
7196     if (!tree)
7197         return;
7198
7199     asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo);
7200
7201     if (session->version == TLSV1DOT3_VERSION) {
7202         guint32 context_length;
7203         proto_tree_add_item_ret_uint(tree, hf->hf.hs_certificate_request_context_length,
7204                                      tvb, offset, 1, ENC_NA, &context_length);
7205         offset++;
7206         if (context_length > 0) {
7207             proto_tree_add_item(tree, hf->hf.hs_certificate_request_context,
7208                                 tvb, offset, context_length, ENC_NA);
7209             offset += context_length;
7210         }
7211     } else {
7212         cert_types_count = tvb_get_guint8(tvb, offset);
7213         proto_tree_add_uint(tree, hf->hf.hs_cert_types_count,
7214                 tvb, offset, 1, cert_types_count);
7215         offset++;
7216
7217         if (cert_types_count > 0) {
7218             ti = proto_tree_add_none_format(tree,
7219                     hf->hf.hs_cert_types,
7220                     tvb, offset, cert_types_count,
7221                     "Certificate types (%u type%s)",
7222                     cert_types_count,
7223                     plurality(cert_types_count, "", "s"));
7224             subtree = proto_item_add_subtree(ti, hf->ett.cert_types);
7225
7226             while (cert_types_count > 0) {
7227                 proto_tree_add_item(subtree, hf->hf.hs_cert_type,
7228                         tvb, offset, 1, ENC_BIG_ENDIAN);
7229                 offset++;
7230                 cert_types_count--;
7231             }
7232         }
7233     }
7234
7235     switch (session->version) {
7236         case TLSV1DOT2_VERSION:
7237         case DTLSV1DOT2_VERSION:
7238         case TLSV1DOT3_VERSION: /* XXX draft -18 only, remove for next version */
7239             offset = ssl_dissect_hash_alg_list(hf, tvb, tree, pinfo, offset, offset_end);
7240             break;
7241
7242         default:
7243             break;
7244     }
7245
7246     dnames_length = tvb_get_ntohs(tvb, offset);
7247     proto_tree_add_uint(tree, hf->hf.hs_dnames_len,
7248             tvb, offset, 2, dnames_length);
7249     offset += 2;
7250
7251     if (dnames_length > 0) {
7252         ti = proto_tree_add_none_format(tree,
7253                 hf->hf.hs_dnames,
7254                 tvb, offset, dnames_length,
7255                 "Distinguished Names (%d byte%s)",
7256                 dnames_length,
7257                 plurality(dnames_length, "", "s"));
7258         subtree = proto_item_add_subtree(ti, hf->ett.dnames);
7259
7260         while (dnames_length > 0) {
7261             /* get the length of the current certificate */
7262             guint16 name_length;
7263             name_length = tvb_get_ntohs(tvb, offset);
7264             dnames_length -= 2 + name_length;
7265
7266             proto_tree_add_item(subtree, hf->hf.hs_dname_len,
7267                     tvb, offset, 2, ENC_BIG_ENDIAN);
7268             offset += 2;
7269
7270             dissect_x509if_DistinguishedName(FALSE, tvb, offset, &asn1_ctx,
7271                                              subtree, hf->hf.hs_dname);
7272             offset += name_length;
7273         }
7274     }
7275 }
7276 /* Certificate and Certificate Request dissections. }}} */
7277
7278 static void
7279 ssl_dissect_digitally_signed(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7280                              proto_tree *tree, guint32 offset,
7281                              const SslSession *session,
7282                              gint hf_sig_len, gint hf_sig);
7283
7284 void
7285 ssl_dissect_hnd_cli_cert_verify(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7286                                 proto_tree *tree, guint32 offset,
7287                                 const SslSession *session)
7288 {
7289     ssl_dissect_digitally_signed(hf, tvb, tree, offset, session,
7290                                  hf->hf.hs_client_cert_vrfy_sig_len,
7291                                  hf->hf.hs_client_cert_vrfy_sig);
7292 }
7293
7294 /* Finished dissection. {{{ */
7295 void
7296 ssl_dissect_hnd_finished(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7297                          proto_tree *tree, guint32 offset,
7298                          const SslSession *session, ssl_hfs_t *ssl_hfs)
7299 {
7300     /* For SSLv3:
7301      *     struct {
7302      *         opaque md5_hash[16];
7303      *         opaque sha_hash[20];
7304      *     } Finished;
7305      *
7306      * For (D)TLS:
7307      *     struct {
7308      *         opaque verify_data[12];
7309      *     } Finished;
7310      */
7311     if (!tree)
7312         return;
7313
7314     if (session->version == SSLV3_VERSION) {
7315         if (ssl_hfs != NULL) {
7316             proto_tree_add_item(tree, ssl_hfs->hs_md5_hash,
7317                                 tvb, offset, 16, ENC_NA);
7318             proto_tree_add_item(tree, ssl_hfs->hs_sha_hash,
7319                                 tvb, offset + 16, 20, ENC_NA);
7320         }
7321     } else {
7322         proto_tree_add_item(tree, hf->hf.hs_finished,
7323                             tvb, offset, 12, ENC_NA);
7324     }
7325 } /* }}} */
7326
7327 /* RFC 6066 Certificate URL handshake message dissection. {{{ */
7328 void
7329 ssl_dissect_hnd_cert_url(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree, guint32 offset)
7330 {
7331     guint16  url_hash_len;
7332
7333     /* enum {
7334      *     individual_certs(0), pkipath(1), (255)
7335      * } CertChainType;
7336      *
7337      * struct {
7338      *     CertChainType type;
7339      *     URLAndHash url_and_hash_list<1..2^16-1>;
7340      * } CertificateURL;
7341      *
7342      * struct {
7343      *     opaque url<1..2^16-1>;
7344      *     unint8 padding;
7345      *     opaque SHA1Hash[20];
7346      * } URLAndHash;
7347      */
7348
7349     proto_tree_add_item(tree, hf->hf.hs_ext_cert_url_type,
7350                         tvb, offset, 1, ENC_NA);
7351     offset++;
7352
7353     url_hash_len = tvb_get_ntohs(tvb, offset);
7354     proto_tree_add_item(tree, hf->hf.hs_ext_cert_url_url_hash_list_len,
7355                         tvb, offset, 2, ENC_BIG_ENDIAN);
7356     offset += 2;
7357     while (url_hash_len-- > 0) {
7358         proto_item  *urlhash_item;
7359         proto_tree  *urlhash_tree;
7360         guint16      url_len;
7361
7362         urlhash_item = proto_tree_add_item(tree, hf->hf.hs_ext_cert_url_item,
7363                                            tvb, offset, -1, ENC_NA);
7364         urlhash_tree = proto_item_add_subtree(urlhash_item, hf->ett.urlhash);
7365
7366         url_len = tvb_get_ntohs(tvb, offset);
7367         proto_tree_add_item(urlhash_tree, hf->hf.hs_ext_cert_url_url_len,
7368                             tvb, offset, 2, ENC_BIG_ENDIAN);
7369         offset += 2;
7370
7371         proto_tree_add_item(urlhash_tree, hf->hf.hs_ext_cert_url_url,
7372                             tvb, offset, url_len, ENC_ASCII|ENC_NA);
7373         offset += url_len;
7374
7375         proto_tree_add_item(urlhash_tree, hf->hf.hs_ext_cert_url_padding,
7376                             tvb, offset, 1, ENC_NA);
7377         offset++;
7378         /* Note: RFC 6066 says that padding must be 0x01 */
7379
7380         proto_tree_add_item(urlhash_tree, hf->hf.hs_ext_cert_url_sha1,
7381                             tvb, offset, 20, ENC_NA);
7382         offset += 20;
7383     }
7384 } /* }}} */
7385
7386 /* Client Hello and Server Hello TLS extensions dissection. {{{ */
7387 static gint
7388 ssl_dissect_hnd_hello_ext(ssl_common_dissect_t *hf, tvbuff_t *tvb, proto_tree *tree,
7389                           packet_info* pinfo, guint32 offset, guint32 offset_end, guint8 hnd_type,
7390                           SslSession *session, SslDecryptSession *ssl,
7391                           gboolean is_dtls)
7392 {
7393     guint16     extension_length;
7394     guint16     ext_type;
7395     guint32     ext_len;
7396     guint32     next_offset;
7397     proto_tree *ext_tree;
7398
7399     if (offset_end - offset < 2)
7400         return offset;
7401
7402     extension_length = tvb_get_ntohs(tvb, offset);
7403     proto_tree_add_uint(tree, hf->hf.hs_exts_len,
7404                         tvb, offset, 2, extension_length);
7405     offset += 2;
7406
7407     while (offset_end - offset >= 4)
7408     {
7409         ext_type = tvb_get_ntohs(tvb, offset);
7410         ext_len  = tvb_get_ntohs(tvb, offset + 2);
7411
7412         ext_tree = proto_tree_add_subtree_format(tree, tvb, offset, 4 + ext_len, hf->ett.hs_ext, NULL,
7413                                   "Extension: %s (len=%u)", val_to_str(ext_type,
7414                                             tls_hello_extension_types,
7415                                             "Unknown type %u"), ext_len);
7416
7417         proto_tree_add_uint(ext_tree, hf->hf.hs_ext_type,
7418                             tvb, offset, 2, ext_type);
7419         offset += 2;
7420
7421         /* opaque extension_data<0..2^16-1> */
7422         if (!ssl_add_vector(hf, tvb, pinfo, ext_tree, offset, offset_end, &ext_len,
7423                             hf->hf.hs_ext_len, 0, G_MAXUINT16)) {
7424             return offset_end;
7425         }
7426         offset += 2;
7427         next_offset = offset + ext_len;
7428
7429         switch (ext_type) {
7430         case SSL_HND_HELLO_EXT_STATUS_REQUEST:
7431             if (hnd_type == SSL_HND_CLIENT_HELLO)
7432                 offset = ssl_dissect_hnd_hello_ext_status_request(hf, tvb, ext_tree, offset, FALSE);
7433             break;
7434         case SSL_HND_HELLO_EXT_STATUS_REQUEST_V2:
7435             if (hnd_type == SSL_HND_CLIENT_HELLO)
7436                 offset = ssl_dissect_hnd_hello_ext_status_request_v2(hf, tvb, ext_tree, offset);
7437             break;
7438         case SSL_HND_HELLO_EXT_SUPPORTED_GROUPS:
7439             offset = ssl_dissect_hnd_hello_ext_elliptic_curves(hf, tvb, ext_tree, offset);
7440             break;
7441         case SSL_HND_HELLO_EXT_EC_POINT_FORMATS:
7442             offset = ssl_dissect_hnd_hello_ext_ec_point_formats(hf, tvb, ext_tree, offset);
7443             break;
7444         case SSL_HND_HELLO_EXT_SIGNATURE_ALGORITHMS:
7445             offset = ssl_dissect_hnd_hello_ext_sig_hash_algs(hf, tvb, ext_tree, pinfo, offset, next_offset);
7446             break;
7447         case SSL_HND_HELLO_EXT_ALPN:
7448             offset = ssl_dissect_hnd_hello_ext_alpn(hf, tvb, pinfo, ext_tree, offset, next_offset, hnd_type, session);
7449             break;
7450         case SSL_HND_HELLO_EXT_NPN:
7451             offset = ssl_dissect_hnd_hello_ext_npn(hf, tvb, pinfo, ext_tree, offset, next_offset);
7452             break;
7453         case SSL_HND_HELLO_EXT_RENEGOTIATION_INFO:
7454             offset = ssl_dissect_hnd_hello_ext_reneg_info(hf, tvb, pinfo, ext_tree, offset, next_offset);
7455             break;
7456         case SSL_HND_HELLO_EXT_KEY_SHARE:
7457             offset = ssl_dissect_hnd_hello_ext_key_share(hf, tvb, pinfo, ext_tree, offset, next_offset, hnd_type);
7458             break;
7459         case SSL_HND_HELLO_EXT_PRE_SHARED_KEY:
7460             offset = ssl_dissect_hnd_hello_ext_pre_shared_key(hf, tvb, ext_tree, offset, next_offset, hnd_type);
7461             break;
7462         case SSL_HND_HELLO_EXT_EARLY_DATA:
7463             offset = ssl_dissect_hnd_hello_ext_early_data(hf, tvb, ext_tree, offset, next_offset, hnd_type);
7464             break;
7465         case SSL_HND_HELLO_EXT_SUPPORTED_VERSIONS:
7466             offset = ssl_dissect_hnd_hello_ext_supported_versions(hf, tvb, ext_tree, offset, next_offset);
7467             break;
7468         case SSL_HND_HELLO_EXT_COOKIE:
7469             offset = ssl_dissect_hnd_hello_ext_cookie(hf, tvb, pinfo, ext_tree, offset, next_offset);
7470             break;
7471         case SSL_HND_HELLO_EXT_PSK_KEY_EXCHANGE_MODES:
7472             offset = ssl_dissect_hnd_hello_ext_psk_key_exchange_modes(hf, tvb, ext_tree, offset, next_offset);
7473             break;
7474         case SSL_HND_HELLO_EXT_DRAFT_VERSION_TLS13:
7475             proto_tree_add_item(ext_tree, hf->hf.hs_ext_draft_version_tls13,
7476                                 tvb, offset, 2, ENC_BIG_ENDIAN);
7477             offset += 2;
7478             break;
7479         case SSL_HND_HELLO_EXT_SERVER_NAME:
7480             offset = ssl_dissect_hnd_hello_ext_server_name(hf, tvb, pinfo, ext_tree, offset, next_offset);
7481             break;
7482         case SSL_HND_HELLO_EXT_USE_SRTP:
7483             if (is_dtls) {
7484                 offset = dtls_dissect_hnd_hello_ext_use_srtp(tvb, ext_tree, offset, next_offset);
7485             } else {
7486                 // XXX expert info: This extension MUST only be used with DTLS, and not with TLS.
7487             }
7488             break;
7489         case SSL_HND_HELLO_EXT_HEARTBEAT:
7490             proto_tree_add_item(ext_tree, hf->hf.hs_ext_heartbeat_mode,
7491                                 tvb, offset, 1, ENC_BIG_ENDIAN);
7492             offset++;
7493             break;
7494         case SSL_HND_HELLO_EXT_PADDING:
7495             proto_tree_add_item(ext_tree, hf->hf.hs_ext_padding_data, tvb, offset, ext_len, ENC_NA);
7496             offset += ext_len;
7497             break;
7498         case SSL_HND_HELLO_EXT_SESSION_TICKET_TLS:
7499             offset = ssl_dissect_hnd_hello_ext_session_ticket(hf, tvb, ext_tree, offset, next_offset, hnd_type, ssl);
7500             break;
7501         case SSL_HND_HELLO_EXT_CERT_TYPE:
7502         case SSL_HND_HELLO_EXT_SERVER_CERT_TYPE:
7503         case SSL_HND_HELLO_EXT_CLIENT_CERT_TYPE:
7504             offset = ssl_dissect_hnd_hello_ext_cert_type(hf, tvb, ext_tree,
7505                                                          offset, next_offset,
7506                                                          hnd_type, ext_type,
7507                                                          session);
7508             break;
7509         case SSL_HND_HELLO_EXT_EXTENDED_MASTER_SECRET:
7510             if (ssl){
7511                 switch(hnd_type){
7512                     case SSL_HND_CLIENT_HELLO:
7513                         ssl->state |= SSL_CLIENT_EXTENDED_MASTER_SECRET;
7514                     break;
7515                     case SSL_HND_SERVER_HELLO:
7516                         ssl->state |= SSL_SERVER_EXTENDED_MASTER_SECRET;
7517                     break;
7518                     default: /* no default */
7519                     break;
7520                 }
7521             }
7522             break;
7523         default:
7524             proto_tree_add_item(ext_tree, hf->hf.hs_ext_data,
7525                                         tvb, offset, ext_len, ENC_NA);
7526             offset += ext_len;
7527             break;
7528         }
7529
7530         if (!ssl_end_vector(hf, tvb, pinfo, ext_tree, offset, next_offset)) {
7531             /* Dissection did not end at expected location, fix it. */
7532             offset = next_offset;
7533         }
7534     }
7535
7536     return offset;
7537 } /* }}} */
7538
7539
7540 /* ClientKeyExchange algo-specific dissectors. {{{ */
7541
7542 static void
7543 dissect_ssl3_hnd_cli_keyex_ecdh(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7544                                 proto_tree *tree, guint32 offset,
7545                                 guint32 length)
7546 {
7547     gint        point_len;
7548     proto_tree *ssl_ecdh_tree;
7549
7550     ssl_ecdh_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7551                                   hf->ett.keyex_params, NULL, "EC Diffie-Hellman Client Params");
7552
7553     /* point */
7554     point_len = tvb_get_guint8(tvb, offset);
7555     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_client_keyex_point_len, tvb,
7556                         offset, 1, ENC_BIG_ENDIAN);
7557     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_client_keyex_point, tvb,
7558                         offset + 1, point_len, ENC_NA);
7559 }
7560
7561 static void
7562 dissect_ssl3_hnd_cli_keyex_dh(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7563                               proto_tree *tree, guint32 offset, guint32 length)
7564 {
7565     gint        yc_len;
7566     proto_tree *ssl_dh_tree;
7567
7568     ssl_dh_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7569                                 hf->ett.keyex_params, NULL, "Diffie-Hellman Client Params");
7570
7571     /* ClientDiffieHellmanPublic.dh_public (explicit) */
7572     yc_len  = tvb_get_ntohs(tvb, offset);
7573     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_client_keyex_yc_len, tvb,
7574                         offset, 2, ENC_BIG_ENDIAN);
7575     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_client_keyex_yc, tvb,
7576                         offset + 2, yc_len, ENC_NA);
7577 }
7578
7579 static void
7580 dissect_ssl3_hnd_cli_keyex_rsa(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7581                                proto_tree *tree, guint32 offset,
7582                                guint32 length, const SslSession *session)
7583 {
7584     gint        epms_len;
7585     proto_tree *ssl_rsa_tree;
7586
7587     ssl_rsa_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7588                                  hf->ett.keyex_params, NULL, "RSA Encrypted PreMaster Secret");
7589
7590     /* EncryptedPreMasterSecret.pre_master_secret */
7591     switch (session->version) {
7592     case SSLV2_VERSION:
7593     case SSLV3_VERSION:
7594     case DTLSV1DOT0_OPENSSL_VERSION:
7595         /* OpenSSL pre-0.9.8f DTLS and pre-TLS quirk: 2-octet length vector is
7596          * not present. The handshake contents represents the EPMS, see:
7597          * https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=10222 */
7598         epms_len = length;
7599         break;
7600
7601     default:
7602         /* TLS and DTLS include vector length before EPMS */
7603         epms_len = tvb_get_ntohs(tvb, offset);
7604         proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_client_keyex_epms_len, tvb,
7605                             offset, 2, ENC_BIG_ENDIAN);
7606         offset += 2;
7607         break;
7608     }
7609     proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_client_keyex_epms, tvb,
7610                         offset, epms_len, ENC_NA);
7611 }
7612
7613 /* Used in PSK cipher suites */
7614 static void
7615 dissect_ssl3_hnd_cli_keyex_psk(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7616                                proto_tree *tree, guint32 offset, guint32 length)
7617 {
7618     guint        identity_len;
7619     proto_tree *ssl_psk_tree;
7620
7621     ssl_psk_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7622                                  hf->ett.keyex_params, NULL, "PSK Client Params");
7623     /* identity */
7624     identity_len = tvb_get_ntohs(tvb, offset);
7625     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_identity_len, tvb,
7626                         offset, 2, ENC_BIG_ENDIAN);
7627     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_identity, tvb,
7628                         offset + 2, identity_len, ENC_NA);
7629 }
7630
7631 /* Used in RSA PSK cipher suites */
7632 static void
7633 dissect_ssl3_hnd_cli_keyex_rsa_psk(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7634                                    proto_tree *tree, guint32 offset,
7635                                    guint32 length)
7636 {
7637     gint        identity_len, epms_len;
7638     proto_tree *ssl_psk_tree;
7639
7640     ssl_psk_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7641                                  hf->ett.keyex_params, NULL, "RSA PSK Client Params");
7642
7643     /* identity */
7644     identity_len = tvb_get_ntohs(tvb, offset);
7645     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_identity_len,
7646                         tvb, offset, 2, ENC_BIG_ENDIAN);
7647     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_identity,
7648                         tvb, offset + 2, identity_len, ENC_NA);
7649     offset += 2 + identity_len;
7650
7651     /* Yc */
7652     epms_len = tvb_get_ntohs(tvb, offset);
7653     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_epms_len, tvb,
7654                         offset, 2, ENC_BIG_ENDIAN);
7655     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_client_keyex_epms, tvb,
7656                         offset + 2, epms_len, ENC_NA);
7657 }
7658 /* ClientKeyExchange algo-specific dissectors. }}} */
7659
7660
7661 /* Dissects DigitallySigned (see RFC 5246 4.7 Cryptographic Attributes). {{{ */
7662 static void
7663 ssl_dissect_digitally_signed(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7664                              proto_tree *tree, guint32 offset,
7665                              const SslSession *session,
7666                              gint hf_sig_len, gint hf_sig)
7667 {
7668     gint        sig_len;
7669     proto_item *ti_algo;
7670     proto_tree *ssl_algo_tree;
7671
7672     switch (session->version) {
7673     case TLSV1DOT2_VERSION:
7674     case DTLSV1DOT2_VERSION:
7675     case TLSV1DOT3_VERSION: /* XXX merge both fields into one SignatureScheme? */
7676         ti_algo = proto_tree_add_item(tree, hf->hf.hs_sig_hash_alg, tvb,
7677                                       offset, 2, ENC_BIG_ENDIAN);
7678         ssl_algo_tree = proto_item_add_subtree(ti_algo, hf->ett.hs_sig_hash_alg);
7679
7680         /* SignatureAndHashAlgorithm { hash, signature } */
7681         proto_tree_add_item(ssl_algo_tree, hf->hf.hs_sig_hash_hash, tvb,
7682                             offset, 1, ENC_BIG_ENDIAN);
7683         proto_tree_add_item(ssl_algo_tree, hf->hf.hs_sig_hash_sig, tvb,
7684                             offset + 1, 1, ENC_BIG_ENDIAN);
7685         offset += 2;
7686         break;
7687
7688     default:
7689         break;
7690     }
7691
7692     /* Sig */
7693     sig_len = tvb_get_ntohs(tvb, offset);
7694     proto_tree_add_item(tree, hf_sig_len, tvb, offset, 2, ENC_BIG_ENDIAN);
7695     proto_tree_add_item(tree, hf_sig, tvb, offset + 2, sig_len, ENC_NA);
7696 } /* }}} */
7697
7698 /* ServerKeyExchange algo-specific dissectors. {{{ */
7699
7700 /* dissects signed_params inside a ServerKeyExchange for some keyex algos */
7701 static void
7702 dissect_ssl3_hnd_srv_keyex_sig(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7703                                proto_tree *tree, guint32 offset,
7704                                const SslSession *session)
7705 {
7706     /*
7707      * TLSv1.2 (RFC 5246 sec 7.4.8)
7708      *  struct {
7709      *      digitally-signed struct {
7710      *          opaque handshake_messages[handshake_messages_length];
7711      *      }
7712      *  } CertificateVerify;
7713      *
7714      * TLSv1.0/TLSv1.1 (RFC 5436 sec 7.4.8 and 7.4.3) works essentially the same
7715      * as TLSv1.2, but the hash algorithms are not explicit in digitally-signed.
7716      *
7717      * SSLv3 (RFC 6101 sec 5.6.8) esseentially works the same as TLSv1.0 but it
7718      * does more hashing including the master secret and padding.
7719      */
7720     ssl_dissect_digitally_signed(hf, tvb, tree, offset, session,
7721                                  hf->hf.hs_server_keyex_sig_len,
7722                                  hf->hf.hs_server_keyex_sig);
7723 }
7724
7725 static void
7726 dissect_ssl3_hnd_srv_keyex_ecdh(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7727                                 proto_tree *tree, guint32 offset,
7728                                 guint32 length, const SslSession *session,
7729                                 gboolean anon)
7730 {
7731     /*
7732      * RFC 4492 ECC cipher suites for TLS
7733      *
7734      *  struct {
7735      *      ECCurveType    curve_type;
7736      *      select (curve_type) {
7737      *          case explicit_prime:
7738      *              ...
7739      *          case explicit_char2:
7740      *              ...
7741      *          case named_curve:
7742      *              NamedCurve namedcurve;
7743      *      };
7744      *  } ECParameters;
7745      *
7746      *  struct {
7747      *      opaque point <1..2^8-1>;
7748      *  } ECPoint;
7749      *
7750      *  struct {
7751      *      ECParameters    curve_params;
7752      *      ECPoint         public;
7753      *  } ServerECDHParams;
7754      *
7755      *  select (KeyExchangeAlgorithm) {
7756      *      case ec_diffie_hellman:
7757      *          ServerECDHParams    params;
7758      *          Signature           signed_params;
7759      *  } ServerKeyExchange;
7760      */
7761
7762     gint        curve_type;
7763     gint        point_len;
7764     proto_tree *ssl_ecdh_tree;
7765
7766     ssl_ecdh_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7767                                   hf->ett.keyex_params, NULL, "EC Diffie-Hellman Server Params");
7768
7769     /* ECParameters.curve_type */
7770     curve_type = tvb_get_guint8(tvb, offset);
7771     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_server_keyex_curve_type, tvb,
7772                         offset, 1, ENC_BIG_ENDIAN);
7773     offset++;
7774     if (curve_type != 3)
7775         return; /* only named_curves are supported */
7776
7777     /* case curve_type == named_curve; ECParameters.namedcurve */
7778     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_server_keyex_named_curve, tvb,
7779                         offset, 2, ENC_BIG_ENDIAN);
7780     offset += 2;
7781
7782     /* ECPoint.point */
7783     point_len = tvb_get_guint8(tvb, offset);
7784     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_server_keyex_point_len, tvb,
7785                         offset, 1, ENC_BIG_ENDIAN);
7786     proto_tree_add_item(ssl_ecdh_tree, hf->hf.hs_server_keyex_point, tvb,
7787                         offset + 1, point_len, ENC_NA);
7788     offset += 1 + point_len;
7789
7790     /* Signature (if non-anonymous KEX) */
7791     if (!anon) {
7792         dissect_ssl3_hnd_srv_keyex_sig(hf, tvb, ssl_ecdh_tree, offset, session);
7793     }
7794 }
7795
7796 static void
7797 dissect_ssl3_hnd_srv_keyex_dhe(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7798                                proto_tree *tree, guint32 offset, guint32 length,
7799                                const SslSession *session, gboolean anon)
7800 {
7801     gint        p_len, g_len, ys_len;
7802     proto_tree *ssl_dh_tree;
7803
7804     ssl_dh_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7805                                 hf->ett.keyex_params, NULL, "Diffie-Hellman Server Params");
7806
7807     /* p */
7808     p_len = tvb_get_ntohs(tvb, offset);
7809     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_server_keyex_p_len, tvb,
7810                         offset, 2, ENC_BIG_ENDIAN);
7811     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_server_keyex_p, tvb,
7812                         offset + 2, p_len, ENC_NA);
7813     offset += 2 + p_len;
7814
7815     /* g */
7816     g_len = tvb_get_ntohs(tvb, offset);
7817     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_server_keyex_g_len, tvb,
7818                         offset, 2, ENC_BIG_ENDIAN);
7819     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_server_keyex_g, tvb,
7820                         offset + 2, g_len, ENC_NA);
7821     offset += 2 + g_len;
7822
7823     /* Ys */
7824     ys_len = tvb_get_ntohs(tvb, offset);
7825     proto_tree_add_uint(ssl_dh_tree, hf->hf.hs_server_keyex_ys_len, tvb,
7826                         offset, 2, ys_len);
7827     proto_tree_add_item(ssl_dh_tree, hf->hf.hs_server_keyex_ys, tvb,
7828                         offset + 2, ys_len, ENC_NA);
7829     offset += 2 + ys_len;
7830
7831     /* Signature (if non-anonymous KEX) */
7832     if (!anon) {
7833         dissect_ssl3_hnd_srv_keyex_sig(hf, tvb, ssl_dh_tree, offset, session);
7834     }
7835 }
7836
7837 /* Only used in RSA-EXPORT cipher suites */
7838 static void
7839 dissect_ssl3_hnd_srv_keyex_rsa(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7840                                proto_tree *tree, guint32 offset, guint32 length,
7841                                const SslSession *session)
7842 {
7843     gint        modulus_len, exponent_len;
7844     proto_tree *ssl_rsa_tree;
7845
7846     ssl_rsa_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7847                                  hf->ett.keyex_params, NULL, "RSA-EXPORT Server Params");
7848
7849     /* modulus */
7850     modulus_len = tvb_get_ntohs(tvb, offset);
7851     proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_server_keyex_modulus_len, tvb,
7852                         offset, 2, ENC_BIG_ENDIAN);
7853     proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_server_keyex_modulus, tvb,
7854                         offset + 2, modulus_len, ENC_NA);
7855     offset += 2 + modulus_len;
7856
7857     /* exponent */
7858     exponent_len = tvb_get_ntohs(tvb, offset);
7859     proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_server_keyex_exponent_len,
7860                         tvb, offset, 2, ENC_BIG_ENDIAN);
7861     proto_tree_add_item(ssl_rsa_tree, hf->hf.hs_server_keyex_exponent,
7862                         tvb, offset + 2, exponent_len, ENC_NA);
7863     offset += 2 + exponent_len;
7864
7865     /* Signature */
7866     dissect_ssl3_hnd_srv_keyex_sig(hf, tvb, ssl_rsa_tree, offset, session);
7867 }
7868
7869 /* Used in RSA PSK and PSK cipher suites */
7870 static void
7871 dissect_ssl3_hnd_srv_keyex_psk(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7872                                proto_tree *tree, guint32 offset, guint32 length)
7873 {
7874     guint        hint_len;
7875     proto_tree *ssl_psk_tree;
7876
7877     hint_len = tvb_get_ntohs(tvb, offset);
7878     if ((2 + hint_len) != length) {
7879         /* Lengths don't line up (wasn't what we expected?) */
7880         return;
7881     }
7882
7883     ssl_psk_tree = proto_tree_add_subtree(tree, tvb, offset, length,
7884                                  hf->ett.keyex_params, NULL, "PSK Server Params");
7885
7886     /* hint */
7887     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_server_keyex_hint_len, tvb,
7888                         offset, 2, ENC_BIG_ENDIAN);
7889     proto_tree_add_item(ssl_psk_tree, hf->hf.hs_server_keyex_hint, tvb,
7890                         offset + 2, hint_len, ENC_NA);
7891 }
7892 /* ServerKeyExchange algo-specific dissectors. }}} */
7893
7894 /* Client Key Exchange and Server Key Exchange handshake dissections. {{{ */
7895 void
7896 ssl_dissect_hnd_cli_keyex(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7897                           proto_tree *tree, guint32 offset, guint32 length,
7898                           const SslSession *session)
7899 {
7900     switch (ssl_get_keyex_alg(session->cipher)) {
7901     case KEX_DH_ANON: /* RFC 5246; DHE_DSS, DHE_RSA, DH_DSS, DH_RSA, DH_ANON: ClientDiffieHellmanPublic */
7902     case KEX_DH_DSS:
7903     case KEX_DH_RSA:
7904     case KEX_DHE_DSS:
7905     case KEX_DHE_RSA:
7906         dissect_ssl3_hnd_cli_keyex_dh(hf, tvb, tree, offset, length);
7907         break;
7908     case KEX_DHE_PSK: /* RFC 4279; diffie_hellman_psk: psk_identity, ClientDiffieHellmanPublic */
7909         /* XXX: implement support for DHE_PSK */
7910         break;
7911     case KEX_ECDH_ANON: /* RFC 4492; ec_diffie_hellman: ClientECDiffieHellmanPublic */
7912     case KEX_ECDH_ECDSA:
7913     case KEX_ECDH_RSA:
7914     case KEX_ECDHE_ECDSA:
7915     case KEX_ECDHE_RSA:
7916         dissect_ssl3_hnd_cli_keyex_ecdh(hf, tvb, tree, offset, length);
7917         break;
7918     case KEX_ECDHE_PSK: /* RFC 5489; ec_diffie_hellman_psk: psk_identity, ClientECDiffieHellmanPublic */
7919         /* XXX: implement support for ECDHE_PSK */
7920         break;
7921     case KEX_KRB5: /* RFC 2712; krb5: KerberosWrapper */
7922         /* XXX: implement support for KRB5 */
7923         break;
7924     case KEX_PSK: /* RFC 4279; psk: psk_identity */
7925         dissect_ssl3_hnd_cli_keyex_psk(hf, tvb, tree, offset, length);
7926         break;
7927     case KEX_RSA: /* RFC 5246; rsa: EncryptedPreMasterSecret */
7928         dissect_ssl3_hnd_cli_keyex_rsa(hf, tvb, tree, offset, length, session);
7929         break;
7930     case KEX_RSA_PSK: /* RFC 4279; rsa_psk: psk_identity, EncryptedPreMasterSecret */
7931         dissect_ssl3_hnd_cli_keyex_rsa_psk(hf, tvb, tree, offset, length);
7932         break;
7933     case KEX_SRP_SHA: /* RFC 5054; srp: ClientSRPPublic */
7934     case KEX_SRP_SHA_DSS:
7935     case KEX_SRP_SHA_RSA:
7936         /* XXX: implement support for SRP_SHA* */
7937         break;
7938     default:
7939         /* XXX: add info message for not supported KEX algo */
7940         break;
7941     }
7942 }
7943
7944 void
7945 ssl_dissect_hnd_srv_keyex(ssl_common_dissect_t *hf, tvbuff_t *tvb,
7946                           proto_tree *tree, guint32 offset, guint32 length,
7947                           const SslSession *session)
7948 {
7949     switch (ssl_get_keyex_alg(session->cipher)) {
7950     case KEX_DH_ANON: /* RFC 5246; ServerDHParams */
7951         dissect_ssl3_hnd_srv_keyex_dhe(hf, tvb, tree, offset, length, session, TRUE);
7952         break;
7953     case KEX_DH_DSS: /* RFC 5246; not allowed */
7954     case KEX_DH_RSA:
7955         /* XXX: add error on not allowed KEX */
7956         break;
7957     case KEX_DHE_DSS: /* RFC 5246; dhe_dss, dhe_rsa: ServerDHParams, Signature */
7958     case KEX_DHE_RSA:
7959         dissect_ssl3_hnd_srv_keyex_dhe(hf, tvb, tree, offset, length, session, FALSE);
7960         break;
7961     case KEX_DHE_PSK: /* RFC 4279; diffie_hellman_psk: psk_identity_hint, ServerDHParams */
7962         /* XXX: implement support for DHE_PSK */
7963         break;
7964     case KEX_ECDH_ANON: /* RFC 4492; ec_diffie_hellman: ServerECDHParams (without signature for anon) */
7965         dissect_ssl3_hnd_srv_keyex_ecdh(hf, tvb, tree, offset, length, session, TRUE);
7966         break;
7967     case KEX_ECDHE_PSK: /* RFC 5489; psk_identity_hint, ServerECDHParams */
7968         /* XXX: implement support for ECDHE_PSK */
7969         break;
7970     case KEX_ECDH_ECDSA: /* RFC 4492; ec_diffie_hellman: ServerECDHParams, Signature */
7971     case KEX_ECDH_RSA:
7972     case KEX_ECDHE_ECDSA:
7973     case KEX_ECDHE_RSA:
7974         dissect_ssl3_hnd_srv_keyex_ecdh(hf, tvb, tree, offset, length, session, FALSE);
7975         break;
7976     case KEX_KRB5: /* RFC 2712; not allowed */
7977         /* XXX: add error on not allowed KEX */
7978         break;
7979     case KEX_PSK: /* RFC 4279; psk, rsa: psk_identity*/
7980     case KEX_RSA_PSK:
7981         dissect_ssl3_hnd_srv_keyex_psk(hf, tvb, tree, offset, length);
7982         break;
7983     case KEX_RSA: /* only allowed if the public key in the server certificate is longer than 512 bits*/
7984         dissect_ssl3_hnd_srv_keyex_rsa(hf, tvb, tree, offset, length, session);
7985         break;
7986     case KEX_SRP_SHA: /* RFC 5054; srp: ServerSRPParams, Signature */
7987     case KEX_SRP_SHA_DSS:
7988     case KEX_SRP_SHA_RSA:
7989         /* XXX: implement support for SRP_SHA* */
7990         break;
7991     default:
7992         /* XXX: add info message for not supported KEX algo */
7993         break;
7994     }
7995 }
7996 /* Client Key Exchange and Server Key Exchange handshake dissections. }}} */
7997
7998 #ifdef HAVE_LIBGCRYPT
7999 void
8000 ssl_common_register_options(module_t *module, ssl_common_options_t *options)
8001 {
8002         prefs_register_string_preference(module, "psk", "Pre-Shared-Key",
8003              "Pre-Shared-Key as HEX string. Should be 0 to 16 bytes.",
8004              &(options->psk));
8005
8006         prefs_register_filename_preference(module, "keylog_file", "(Pre)-Master-Secret log filename",
8007              "The name of a file which contains a list of \n"
8008              "(pre-)master secrets in one of the following formats:\n"
8009              "\n"
8010              "RSA <EPMS> <PMS>\n"
8011              "RSA Session-ID:<SSLID> Master-Key:<MS>\n"
8012              "CLIENT_RANDOM <CRAND> <MS>\n"
8013              "PMS_CLIENT_RANDOM <CRAND> <PMS>\n"
8014              "\n"
8015              "Where:\n"
8016              "<EPMS> = First 8 bytes of the Encrypted PMS\n"
8017              "<PMS> = The Pre-Master-Secret (PMS) used to derive the MS\n"
8018              "<SSLID> = The SSL Session ID\n"
8019              "<MS> = The Master-Secret (MS)\n"
8020              "<CRAND> = The Client's random number from the ClientHello message\n"
8021              "\n"
8022              "(All fields are in hex notation)",
8023              &(options->keylog_filename));
8024 }
8025 #else
8026 void
8027 ssl_common_register_options(module_t *module _U_, ssl_common_options_t *options _U_)
8028 {
8029 }
8030 #endif
8031
8032 void
8033 ssl_calculate_handshake_hash(SslDecryptSession *ssl_session, tvbuff_t *tvb, guint32 offset, guint32 length)
8034 {
8035     if (ssl_session && ssl_session->session.version != TLSV1DOT3_VERSION && !(ssl_session->state & SSL_MASTER_SECRET)) {
8036         guint32 old_length = ssl_session->handshake_data.data_len;
8037         ssl_debug_printf("Calculating hash with offset %d %d\n", offset, length);
8038         ssl_session->handshake_data.data = (guchar *)wmem_realloc(wmem_file_scope(), ssl_session->handshake_data.data, old_length + length);
8039         tvb_memcpy(tvb, ssl_session->handshake_data.data + old_length, offset, length);
8040         ssl_session->handshake_data.data_len += length;
8041     }
8042 }
8043
8044
8045 /*
8046  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
8047  *
8048  * Local variables:
8049  * c-basic-offset: 4
8050  * tab-width: 8
8051  * indent-tabs-mode: nil
8052  * End:
8053  *
8054  * vi: set shiftwidth=4 tabstop=8 expandtab:
8055  * :indentSize=4:tabSize=8:noTabs=true:
8056  */