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