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