14f5baac13a13ecfa438a27e1d7146d380d704d4
[metze/wireshark/wip.git] / epan / dissectors / packet-quic.c
1 /* packet-quic.c
2  * Routines for QUIC (IETF) dissection
3  * Copyright 2017, Alexis La Goutte <alexis.lagoutte at gmail dot com>
4  * Copyright 2018 Peter Wu <peter@lekensteyn.nl>
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * SPDX-License-Identifier: GPL-2.0-or-later
11  */
12
13 /*
14  * See https://quicwg.org
15  * https://tools.ietf.org/html/draft-ietf-quic-transport-14
16  * https://tools.ietf.org/html/draft-ietf-quic-tls-14
17  * https://tools.ietf.org/html/draft-ietf-quic-invariants-02
18  */
19
20 #include <config.h>
21
22 #include <epan/packet.h>
23 #include <epan/expert.h>
24 #include <epan/proto_data.h>
25 #include <epan/to_str.h>
26 #include "packet-tls-utils.h"
27 #include "packet-tls.h"
28 #include <epan/prefs.h>
29 #include <wsutil/pint.h>
30 #include "packet-gquic.h"
31
32 #if GCRYPT_VERSION_NUMBER >= 0x010600 /* 1.6.0 */
33 /* Whether to provide support for authentication in addition to decryption. */
34 #define HAVE_LIBGCRYPT_AEAD
35 #endif
36 #if GCRYPT_VERSION_NUMBER >= 0x010700 /* 1.7.0 */
37 /* Whether ChaCh20 PNE can be supported. */
38 #define HAVE_LIBGCRYPT_CHACHA20
39 #endif
40
41 /* Prototypes */
42 void proto_reg_handoff_quic(void);
43 void proto_register_quic(void);
44
45 /* Initialize the protocol and registered fields */
46 static int proto_quic = -1;
47 static int hf_quic_connection_number = -1;
48 static int hf_quic_header_form = -1;
49 static int hf_quic_long_packet_type = -1;
50 static int hf_quic_dcid = -1;
51 static int hf_quic_scid = -1;
52 static int hf_quic_dcil = -1;
53 static int hf_quic_scil = -1;
54 static int hf_quic_token_length = -1;
55 static int hf_quic_token = -1;
56 static int hf_quic_length = -1;
57 static int hf_quic_packet_number = -1;
58 static int hf_quic_packet_number_full = -1;
59 static int hf_quic_version = -1;
60 static int hf_quic_supported_version = -1;
61 static int hf_quic_vn_unused = -1;
62 static int hf_quic_short_kp_flag = -1;
63 static int hf_quic_short_reserved = -1;
64 static int hf_quic_payload = -1;
65 static int hf_quic_protected_payload = -1;
66 static int hf_quic_remaining_payload = -1;
67 static int hf_quic_odcil_draft13 = -1;
68 static int hf_quic_odcil = -1;
69 static int hf_quic_odcid = -1;
70 static int hf_quic_retry_token = -1;
71
72 static int hf_quic_frame = -1;
73 static int hf_quic_frame_type = -1;
74 static int hf_quic_frame_type_stream_fin = -1;
75 static int hf_quic_frame_type_stream_len = -1;
76 static int hf_quic_frame_type_stream_off = -1;
77 static int hf_quic_stream_stream_id = -1;
78 static int hf_quic_stream_offset = -1;
79 static int hf_quic_stream_length = -1;
80 static int hf_quic_stream_data = -1;
81
82 static int hf_quic_frame_type_ack_largest_acknowledged = -1;
83 static int hf_quic_frame_type_ack_ack_delay = -1;
84 static int hf_quic_frame_type_ack_ack_block_count = -1;
85 static int hf_quic_frame_type_ack_fab = -1;
86 static int hf_quic_frame_type_ack_gap = -1;
87 static int hf_quic_frame_type_ack_ack_block = -1;
88
89 static int hf_quic_frame_type_path_challenge_data = -1;
90 static int hf_quic_frame_type_path_response_data = -1;
91
92 static int hf_quic_frame_type_padding_length = -1;
93 static int hf_quic_frame_type_rsts_stream_id = -1;
94 static int hf_quic_frame_type_rsts_application_error_code = -1;
95 static int hf_quic_frame_type_rsts_final_offset = -1;
96 static int hf_quic_frame_type_cc_error_code = -1;
97 static int hf_quic_frame_type_cc_error_code_tls_alert = -1;
98 static int hf_quic_frame_type_cc_frame_type = -1;
99 static int hf_quic_frame_type_cc_reason_phrase_length = -1;
100 static int hf_quic_frame_type_cc_reason_phrase = -1;
101 static int hf_quic_frame_type_ac_error_code = -1;
102 static int hf_quic_frame_type_ac_reason_phrase_length = -1;
103 static int hf_quic_frame_type_ac_reason_phrase = -1;
104 static int hf_quic_frame_type_md_maximum_data = -1;
105 static int hf_quic_frame_type_msd_stream_id = -1;
106 static int hf_quic_frame_type_msd_maximum_stream_data = -1;
107 static int hf_quic_frame_type_msi_stream_id = -1;
108 static int hf_quic_frame_type_blocked_offset = -1;
109 static int hf_quic_frame_type_sb_stream_id = -1;
110 static int hf_quic_frame_type_sb_offset = -1;
111 static int hf_quic_frame_type_sib_stream_id = -1;
112 static int hf_quic_frame_type_nci_sequence = -1;
113 static int hf_quic_frame_type_nci_connection_id_length = -1;
114 static int hf_quic_frame_type_nci_connection_id = -1;
115 static int hf_quic_frame_type_nci_stateless_reset_token = -1;
116 static int hf_quic_frame_type_ss_stream_id = -1;
117 static int hf_quic_frame_type_ss_application_error_code = -1;
118 static int hf_quic_frame_type_crypto_offset = -1;
119 static int hf_quic_frame_type_crypto_length = -1;
120 static int hf_quic_frame_type_crypto_crypto_data = -1;
121 static int hf_quic_frame_type_nt_length = -1;
122 static int hf_quic_frame_type_nt_token = -1;
123 static int hf_quic_frame_type_ae_largest_acknowledged = -1;
124 static int hf_quic_frame_type_ae_ack_delay = -1;
125 static int hf_quic_frame_type_ae_ect0_count = -1;
126 static int hf_quic_frame_type_ae_ect1_count = -1;
127 static int hf_quic_frame_type_ae_ecn_ce_count = -1;
128 static int hf_quic_frame_type_ae_ack_block_count = -1;
129 static int hf_quic_frame_type_ae_fab = -1;
130 static int hf_quic_frame_type_ae_gap = -1;
131 static int hf_quic_frame_type_ae_ack_block = -1;
132
133 static expert_field ei_quic_connection_unknown = EI_INIT;
134 static expert_field ei_quic_ft_unknown = EI_INIT;
135 static expert_field ei_quic_decryption_failed = EI_INIT;
136 static expert_field ei_quic_protocol_violation = EI_INIT;
137
138 static gint ett_quic = -1;
139 static gint ett_quic_connection_info = -1;
140 static gint ett_quic_ft = -1;
141 static gint ett_quic_ftflags = -1;
142
143 static dissector_handle_t quic_handle;
144 static dissector_handle_t tls13_handshake_handle;
145
146 /*
147  * PROTECTED PAYLOAD DECRYPTION (done in first pass)
148  *
149  * Long packet types always use a single cipher depending on packet type.
150  * Short packet types always use 1-RTT secrets for packet protection (pp).
151  * TODO 0-RTT decryption requires another (client) cipher.
152  *
153  * Considerations:
154  * - QUIC packets might appear out-of-order (short packets before handshake
155  *   message is captured), lost or retransmitted/duplicated.
156  * - During live capture, keys might not be immediately be available. 1-RTT
157  *   client keys will be ready while client proceses Server Hello (Handshake).
158  *   1-RTT server keys will be ready while server creates Handshake message in
159  *   response to Initial Handshake.
160  * - So delay cipher creation until first short packet is received.
161  *
162  * Required input from TLS dissector: TLS-Exporter 0-RTT/1-RTT secrets and
163  * cipher/hash algorithms.
164  *
165  * to-do list:
166  * DONE key update via KEY_PHASE bit (untested)
167  * TODO 0-RTT decryption
168  */
169
170 typedef struct quic_decrypt_result {
171     const guchar   *error;      /**< Error message or NULL for success. */
172     const guint8   *data;       /**< Decrypted result on success (file-scoped). */
173     guint           data_len;   /**< Size of decrypted data. */
174 } quic_decrypt_result_t;
175
176 typedef struct quic_cid {
177     guint8      len;
178     guint8      cid[18];
179 } quic_cid_t;
180
181 /** QUIC decryption context. */
182 typedef struct quic_cipher {
183     gcry_cipher_hd_t    pn_cipher;  /* Packet number protection cipher. */
184     gcry_cipher_hd_t    pp_cipher;  /* Packet protection cipher. */
185     guint8              pp_iv[TLS13_AEAD_NONCE_LENGTH];
186 } quic_cipher;
187
188 /**
189  * Packet protection state for an endpoint.
190  */
191 typedef struct quic_pp_state {
192     guint8         *next_secret;    /**< Next application traffic secret. */
193     quic_cipher     cipher[2];      /**< Cipher for KEY_PHASE 0/1 */
194     guint64         changed_in_pkn; /**< Packet number where key change occurred. */
195     gboolean        key_phase : 1;  /**< Current key phase. */
196 } quic_pp_state_t;
197
198 /** Singly-linked list of Connection IDs. */
199 typedef struct quic_cid_item quic_cid_item_t;
200 struct quic_cid_item {
201     struct quic_cid_item   *next;
202     quic_cid_t              data;
203 };
204
205 /**
206  * State for a single QUIC connection, identified by one or more Destination
207  * Connection IDs (DCID).
208  */
209 typedef struct quic_info_data {
210     guint32         number;         /** Similar to "udp.stream", but for identifying QUIC connections across migrations. */
211     guint32         version;
212     address         server_address;
213     guint16         server_port;
214     gboolean        skip_decryption : 1; /**< Set to 1 if no keys are available. */
215     int             hash_algo;      /**< Libgcrypt hash algorithm for key derivation. */
216     int             cipher_algo;    /**< Cipher algorithm for packet number and packet encryption. */
217     int             cipher_mode;    /**< Cipher mode for packet encryption. */
218     quic_cipher     client_initial_cipher;
219     quic_cipher     server_initial_cipher;
220     quic_cipher     client_handshake_cipher;
221     quic_cipher     server_handshake_cipher;
222     quic_pp_state_t client_pp;
223     quic_pp_state_t server_pp;
224     guint64         max_client_pkn;
225     guint64         max_server_pkn;
226     quic_cid_item_t client_cids;    /**< SCID of client from first Initial Packet. */
227     quic_cid_item_t server_cids;    /**< SCID of server from first Retry/Handshake. */
228     quic_cid_t      client_dcid_initial;    /**< DCID from Initial Packet. */
229 } quic_info_data_t;
230
231 /** Per-packet information about QUIC, populated on the first pass. */
232 struct quic_packet_info {
233     struct quic_packet_info *next;
234     guint64                 packet_number;  /**< Reconstructed full packet number. */
235     quic_decrypt_result_t   decryption;
236     guint8                  pkn_len;        /**< Length of PKN (1/2/4) or unknown (0). */
237 };
238 typedef struct quic_packet_info quic_packet_info_t;
239
240 /** A UDP datagram contains one or more QUIC packets. */
241 typedef struct quic_datagram {
242     quic_info_data_t       *conn;
243     quic_packet_info_t      first_packet;
244     gboolean                from_server : 1;
245 } quic_datagram;
246
247 /**
248  * Maps CID (quic_cid_t *) to a QUIC Connection (quic_info_data_t *).
249  * This assumes that the CIDs are not shared between two different connections
250  * (potentially with different versions) as that would break dissection.
251  *
252  * These mappings are authorative. For example, Initial.SCID is stored in
253  * quic_client_connections while Retry.SCID is stored in
254  * quic_server_connections. Retry.DCID should normally correspond to an entry in
255  * quic_client_connections.
256  */
257 static wmem_map_t *quic_client_connections, *quic_server_connections;
258 static wmem_map_t *quic_initial_connections;    /* Initial.DCID -> connection */
259 static wmem_list_t *quic_connections;   /* All unique connections. */
260 static guint32 quic_cid_lengths;        /* Bitmap of CID lengths. */
261 static guint quic_connections_count;
262
263 /* Returns the QUIC draft version or 0 if not applicable. */
264 static inline guint8 quic_draft_version(guint32 version) {
265     if ((version >> 8) == 0xff0000) {
266        return (guint8) version;
267     }
268     return 0;
269 }
270 static inline gboolean is_quic_draft_max(guint32 version, guint8 max_version) {
271     guint8 draft_version = quic_draft_version(version);
272     return draft_version && draft_version <= max_version;
273 }
274
275 static inline guint8 is_gquic_version(guint32 version) {
276     return version == 0x51303434; /* Q044 is the first release to use IETF QUIC (draft-12) packet header */
277 }
278
279 const value_string quic_version_vals[] = {
280     { 0x00000000, "Version Negotiation" },
281     { 0x51303434, "Google Q044" },
282     { 0xff000004, "draft-04" },
283     { 0xff000005, "draft-05" },
284     { 0xff000006, "draft-06" },
285     { 0xff000007, "draft-07" },
286     { 0xff000008, "draft-08" },
287     { 0xff000009, "draft-09" },
288     { 0xff00000a, "draft-10" },
289     { 0xff00000b, "draft-11" },
290     { 0xff00000c, "draft-12" },
291     { 0xff00000d, "draft-13" },
292     { 0xff00000e, "draft-14" },
293     { 0, NULL }
294 };
295
296 static const value_string quic_short_long_header_vals[] = {
297     { 0, "Short Header" },
298     { 1, "Long Header" },
299     { 0, NULL }
300 };
301
302 #define SH_KP       0x40    /* since draft -11 */
303
304 static const value_string quic_cid_len_vals[] = {
305     { 0,    "0 octets" },
306     { 1,    "4 octets" },
307     { 2,    "5 octets" },
308     { 3,    "6 octets" },
309     { 4,    "7 octets" },
310     { 5,    "8 octets" },
311     { 6,    "9 octets" },
312     { 7,    "10 octets" },
313     { 8,    "11 octets" },
314     { 9,    "12 octets" },
315     { 10,   "13 octets" },
316     { 11,   "14 octets" },
317     { 12,   "15 octets" },
318     { 13,   "16 octets" },
319     { 14,   "17 octets" },
320     { 15,   "18 octets" },
321     { 0, NULL }
322 };
323
324 #define QUIC_LPT_INITIAL    0x7F
325 #define QUIC_LPT_RETRY      0x7E
326 #define QUIC_LPT_HANDSHAKE  0x7D
327 #define QUIC_LPT_0RTT       0x7C
328 #define QUIC_SHORT_PACKET   0xff    /* dummy value that is definitely not LPT */
329
330 static const value_string quic_long_packet_type_vals[] = {
331     { QUIC_LPT_INITIAL, "Initial" },
332     { QUIC_LPT_RETRY, "Retry" },
333     { QUIC_LPT_HANDSHAKE, "Handshake" },
334     { QUIC_LPT_0RTT, "0-RTT Protected" },
335     { 0, NULL }
336 };
337
338 #define FT_PADDING          0x00
339 #define FT_RST_STREAM       0x01
340 #define FT_CONNECTION_CLOSE 0x02
341 #define FT_APPLICATION_CLOSE 0x03 /* Add in draft07 */
342 #define FT_MAX_DATA         0x04
343 #define FT_MAX_STREAM_DATA  0x05
344 #define FT_MAX_STREAM_ID    0x06
345 #define FT_PING             0x07
346 #define FT_BLOCKED          0x08
347 #define FT_STREAM_BLOCKED   0x09
348 #define FT_STREAM_ID_BLOCKED 0x0a
349 #define FT_NEW_CONNECTION_ID 0x0b
350 #define FT_STOP_SENDING     0x0c
351 #define FT_ACK              0x0d
352 #define FT_PATH_CHALLENGE   0x0e
353 #define FT_PATH_RESPONSE    0x0f
354 #define FT_STREAM_10        0x10
355 #define FT_STREAM_11        0x11
356 #define FT_STREAM_12        0x12
357 #define FT_STREAM_13        0x13
358 #define FT_STREAM_14        0x14
359 #define FT_STREAM_15        0x15
360 #define FT_STREAM_16        0x16
361 #define FT_STREAM_17        0x17
362 #define FT_CRYPTO           0x18
363 #define FT_NEW_TOKEN        0x19 /* Add in draft 13 */
364 #define FT_ACK_ECN          0x1a /* Add in draft 14 */
365 #define FT_ACK_ECN_OLD      0x20 /* Remove in draft 14 */
366
367 static const range_string quic_frame_type_vals[] = {
368     { 0x00, 0x00,   "PADDING" },
369     { 0x01, 0x01,   "RST_STREAM" },
370     { 0x02, 0x02,   "CONNECTION_CLOSE" },
371     { 0x03, 0x03,   "APPLICATION_CLOSE" },
372     { 0x04, 0x04,   "MAX_DATA" },
373     { 0x05, 0x05,   "MAX_STREAM_DATA" },
374     { 0x06, 0x06,   "MAX_STREAM_ID" },
375     { 0x07, 0x07,   "PING" },
376     { 0x08, 0x08,   "BLOCKED" },
377     { 0x09, 0x09,   "STREAM_BLOCKED" },
378     { 0x0a, 0x0a,   "STREAM_ID_BLOCKED" },
379     { 0x0b, 0x0b,   "NEW_CONNECTION_ID" },
380     { 0x0c, 0x0c,   "STOP_SENDING" },
381     { 0x0d, 0x0d,   "ACK" },
382     { 0x0e, 0x0e,   "PATH_CHALLENGE" },
383     { 0x0f, 0x0f,   "PATH_RESPONSE" },
384     { 0x10, 0x17,   "STREAM" },
385     { 0x18, 0x18,   "CRYPTO" },
386     { 0x19, 0x19,   "NEW_TOKEN" },
387     { 0x1a, 0x1a,   "ACK_ECN" },
388     { 0x20, 0x20,   "ACK_ECN" },
389     { 0,    0,        NULL },
390 };
391
392
393 /* >= draft-08 */
394 #define FTFLAGS_STREAM_FIN 0x01
395 #define FTFLAGS_STREAM_LEN 0x02
396 #define FTFLAGS_STREAM_OFF 0x04
397
398 static const range_string quic_transport_error_code_vals[] = {
399     { 0x0000, 0x0000, "NO_ERROR" },
400     { 0x0001, 0x0001, "INTERNAL_ERROR" },
401     { 0x0002, 0x0002, "SERVER_BUSY" },
402     { 0x0003, 0x0003, "FLOW_CONTROL_ERROR" },
403     { 0x0004, 0x0004, "STREAM_ID_ERROR" },
404     { 0x0005, 0x0005, "STREAM_STATE_ERROR" },
405     { 0x0006, 0x0006, "FINAL_OFFSET_ERROR" },
406     { 0x0007, 0x0007, "FRAME_ENCODING_ERROR" },
407     { 0x0008, 0x0008, "TRANSPORT_PARAMETER_ERROR" },
408     { 0x0009, 0x0009, "VERSION_NEGOTIATION_ERROR" },
409     { 0x000A, 0x000A, "PROTOCOL_VIOLATION" },
410     { 0x000C, 0x000C, "INVALID_MIGRATION" },
411     { 0x0100, 0x01FF, "CRYPTO_ERROR" },
412     { 0, 0, NULL }
413 };
414
415 static const value_string quic_application_error_code_vals[] = {
416     { 0x0000, "STOPPING" },
417     { 0, NULL }
418 };
419
420 static void
421 quic_cipher_reset(quic_cipher *cipher)
422 {
423     gcry_cipher_close(cipher->pn_cipher);
424     gcry_cipher_close(cipher->pp_cipher);
425     memset(cipher, 0, sizeof(*cipher));
426 }
427
428 /* Inspired from ngtcp2 */
429 static guint64 quic_pkt_adjust_pkt_num(guint64 max_pkt_num, guint64 pkt_num,
430                                    size_t n) {
431   guint64 k = max_pkt_num == G_MAXUINT64 ? max_pkt_num : max_pkt_num + 1;
432   guint64 u = k & ~((G_GUINT64_CONSTANT(1) << n) - 1);
433   guint64 a = u | pkt_num;
434   guint64 b = (u + (G_GUINT64_CONSTANT(1) << n)) | pkt_num;
435   guint64 a1 = k < a ? a - k : k - a;
436   guint64 b1 = k < b ? b - k : k - b;
437
438   if (a1 < b1) {
439     return a;
440   }
441   return b;
442 }
443
444 #ifdef HAVE_LIBGCRYPT_AEAD
445 static guint
446 quic_decrypt_packet_number(tvbuff_t *tvb, guint offset, quic_cipher *cipher,
447                            int pn_cipher_algo, guint64 *pkn)
448 {
449     guint32 pkt_pkn;
450     guint   pkn_len;
451     guint8 *pkn_bytes = (guint8 *)&pkt_pkn;
452     gcry_cipher_hd_t h;
453     if (!cipher || !(h = cipher->pn_cipher)) {
454         // need to know the cipher.
455         return 0;
456     }
457
458     tvb_memcpy(tvb, pkn_bytes, offset, sizeof(pkt_pkn));
459
460     // Both AES-CTR and ChaCha20 use 16 octets as sample length.
461     // https://tools.ietf.org/html/draft-ietf-quic-tls-13#section-5.3
462     const guint sample_length = 16;
463     guint sample_offset = offset + 4;
464     guint8 sample[16];
465     if (sample_offset + sample_length > tvb_reported_length(tvb)) {
466         sample_offset = tvb_reported_length(tvb) - sample_length;
467     }
468     tvb_memcpy(tvb, sample, sample_offset, sample_length);
469
470     switch (pn_cipher_algo) {
471     case GCRY_CIPHER_AES128:
472     case GCRY_CIPHER_AES256:
473         if (gcry_cipher_setctr(h, sample, sample_length)) {
474             return 0;
475         }
476         break;
477 #ifdef HAVE_LIBGCRYPT_CHACHA20
478     case GCRY_CIPHER_CHACHA20:
479         /* If Gcrypt receives a 16 byte IV, it will assume the buffer to be
480          * counter || nonce (in little endian), as desired. */
481         if (gcry_cipher_setiv(h, sample, 16)) {
482             return 0;
483         }
484         break;
485 #endif /* HAVE_LIBGCRYPT_CHACHA20 */
486     default:
487         return 0;
488     }
489
490     /* in-place decrypt. */
491     if (gcry_cipher_decrypt(h, pkn_bytes, 4, NULL, 0)) {
492         return 0;
493     }
494
495     // | First octet pattern | Encoded Length | Bits Present |
496     // | 0b0xxxxxxx          | 1 octet        | 7            |
497     // | 0b10xxxxxx          | 2              | 14           |
498     // | 0b11xxxxxx          | 4              | 30           |
499     switch (pkn_bytes[0] >> 6) {
500     default:
501         pkn_len = 1;
502         break;
503     case 2:
504         pkn_len = 2;
505         pkn_bytes[0] &= 0x3f;
506         break;
507     case 3:
508         pkn_len = 4;
509         pkn_bytes[0] &= 0x3f;
510         break;
511     }
512     *pkn = g_htonl(pkt_pkn) >> (8 * (4 - pkn_len));
513     return pkn_len;
514 }
515
516 static void
517 quic_encode_packet_number(guint8 *output, guint32 pkn, guint pkn_len)
518 {
519     switch (pkn_len) {
520     default:
521         output[0] = (guint8)pkn;
522         break;
523     case 2:
524         phton16(output, (guint16)pkn);
525         output[0] |= 0x80;
526         break;
527     case 4:
528         phton32(output, pkn);
529         output[0] |= 0xc0;
530         break;
531     }
532 }
533 #else /* !HAVE_LIBGCRYPT_AEAD */
534 static inline guint
535 quic_decrypt_packet_number(tvbuff_t *tvb _U_, guint offset _U_, quic_cipher *cipher _U_,
536                            int pn_cipher_algo _U_, guint64 *pkn _U_)
537 {
538     return 0;
539 }
540 #endif /* !HAVE_LIBGCRYPT_AEAD */
541
542 /**
543  * Calculate the full packet number and store it for later use.
544  */
545 static guint32
546 dissect_quic_packet_number(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset,
547                            quic_info_data_t *quic_info, quic_packet_info_t *quic_packet,
548                            gboolean from_server,
549                            quic_cipher *cipher, int pn_cipher_algo, guint64 *pkn_out)
550 {
551     proto_item *ti;
552     guint       pkn_len;
553     guint64     pkn;
554
555     /* Try to decrypt on the first pass, reuse results on the second pass. */
556     if (!PINFO_FD_VISITED(pinfo)) {
557         pkn_len = quic_decrypt_packet_number(tvb, offset, cipher, pn_cipher_algo, &pkn);
558         quic_packet->pkn_len = pkn_len;
559     } else {
560         pkn_len = quic_packet->pkn_len;
561         pkn = quic_packet->packet_number & ((1UL << (8 * pkn_len)) - 1);
562     }
563     if (!pkn_len) {
564         expert_add_info_format(pinfo, tree, &ei_quic_decryption_failed, "Failed to decrypt packet number");
565         return 0;
566     }
567
568     // TODO separate field for encrypted and decrypted PKN?
569     proto_tree_add_uint64(tree, hf_quic_packet_number, tvb, offset, pkn_len, pkn);
570
571     if (!quic_info) {
572         // if not part of a connection, the full PKN cannot be reconstructed.
573         *pkn_out = pkn;
574         return pkn_len;
575     }
576
577     /* Sequential first pass, try to reconstruct full packet number. */
578     if (!PINFO_FD_VISITED(pinfo)) {
579         if (from_server) {
580             pkn = quic_pkt_adjust_pkt_num(quic_info->max_server_pkn, pkn, 8 * pkn_len);
581             quic_info->max_server_pkn = pkn;
582         } else {
583             pkn = quic_pkt_adjust_pkt_num(quic_info->max_client_pkn, pkn, 8 * pkn_len);
584             quic_info->max_client_pkn = pkn;
585         }
586         quic_packet->packet_number = pkn;
587     } else {
588         pkn = quic_packet->packet_number;
589     }
590
591     /* always add the full packet number for use in columns */
592     ti = proto_tree_add_uint64(tree, hf_quic_packet_number_full, tvb, offset, pkn_len, pkn);
593     PROTO_ITEM_SET_GENERATED(ti);
594
595     *pkn_out = pkn;
596     return pkn_len;
597 }
598
599 static const char *
600 cid_to_string(const quic_cid_t *cid)
601 {
602     if (cid->len == 0) {
603         return "(none)";
604     }
605     char *str = (char *)wmem_alloc0(wmem_packet_scope(), 2 * cid->len + 1);
606     bytes_to_hexstr(str, cid->cid, cid->len);
607     return str;
608 }
609
610 /* QUIC Connection tracking. {{{ */
611 static guint
612 quic_connection_hash(gconstpointer key)
613 {
614     const quic_cid_t *cid = (const quic_cid_t *)key;
615
616     return wmem_strong_hash((const guint8 *)cid, cid->len);
617 }
618
619 static gboolean
620 quic_connection_equal(gconstpointer a, gconstpointer b)
621 {
622     const quic_cid_t *cid1 = (const quic_cid_t *)a;
623     const quic_cid_t *cid2 = (const quic_cid_t *)b;
624
625     return cid1->len == cid2->len && !memcmp(cid1->cid, cid2->cid, cid1->len);
626 }
627
628 static gboolean
629 quic_cids_has_match(const quic_cid_item_t *items, const quic_cid_t *raw_cid)
630 {
631     while (items) {
632         const quic_cid_t *cid = &items->data;
633         // "raw_cid" potentially has some trailing data that is not part of the
634         // actual CID, so accept any prefix match against "cid".
635         // Note that this explicitly matches an empty CID.
636         if (raw_cid->len >= cid->len && !memcmp(raw_cid->cid, cid->cid, cid->len)) {
637             return TRUE;
638         }
639         items = items->next;
640     }
641     return FALSE;
642 }
643
644 static void
645 quic_cids_insert(quic_cid_t *cid, quic_info_data_t *conn, gboolean from_server)
646 {
647     wmem_map_t *connections = from_server ? quic_server_connections : quic_client_connections;
648     // Replace any previous CID key with the new one.
649     wmem_map_remove(connections, cid);
650     wmem_map_insert(connections, cid, conn);
651     quic_cid_lengths |= (1 << cid->len);
652 }
653
654 static inline gboolean
655 quic_cids_is_known_length(const quic_cid_t *cid)
656 {
657     return (quic_cid_lengths & (1 << cid->len)) != 0;
658 }
659
660 /**
661  * Tries to lookup a matching connection (Connection ID is optional).
662  * If connection is found, "from_server" is set accordingly.
663  */
664 static quic_info_data_t *
665 quic_connection_find_dcid(packet_info *pinfo, const quic_cid_t *dcid, gboolean *from_server)
666 {
667     /* https://tools.ietf.org/html/draft-ietf-quic-transport-13#section-6.2
668      *
669      * "If the packet has a Destination Connection ID corresponding to an
670      * existing connection, QUIC processes that packet accordingly."
671      * "If the Destination Connection ID is zero length and the packet matches
672      * the address/port tuple of a connection where the host did not require
673      * connection IDs, QUIC processes the packet as part of that connection."
674      */
675     quic_info_data_t *conn = NULL;
676     gboolean check_ports = FALSE;
677
678     if (dcid && dcid->len > 0 && quic_cids_is_known_length(dcid)) {
679         conn = (quic_info_data_t *) wmem_map_lookup(quic_client_connections, dcid);
680         if (conn) {
681             // DCID recognized by client, so it was from server.
682             *from_server = TRUE;
683             // On collision (both client and server choose the same CID), check
684             // the port to learn about the side.
685             // This is required for supporting draft -10 which has a single CID.
686             check_ports = !!wmem_map_lookup(quic_server_connections, dcid);
687         } else {
688             conn = (quic_info_data_t *) wmem_map_lookup(quic_server_connections, dcid);
689             if (conn) {
690                 // DCID recognized by server, so it was from client.
691                 *from_server = FALSE;
692             }
693         }
694     } else {
695         conversation_t *conv = find_conversation_pinfo(pinfo, 0);
696         if (conv) {
697             conn = (quic_info_data_t *)conversation_get_proto_data(conv, proto_quic);
698             check_ports = !!conn;
699         }
700     }
701
702     if (check_ports) {
703         *from_server = conn->server_port == pinfo->srcport &&
704                 addresses_equal(&conn->server_address, &pinfo->src);
705     }
706
707     return conn;
708 }
709
710 /**
711  * Try to find a QUIC connection based on DCID. For short header packets, DCID
712  * will be modified in order to find the actual length.
713  * DCID can be empty, in that case a connection is looked up by address only.
714  */
715 static quic_info_data_t *
716 quic_connection_find(packet_info *pinfo, guint8 long_packet_type,
717                      quic_cid_t *dcid, gboolean *from_server)
718 {
719     gboolean is_long_packet = long_packet_type != QUIC_SHORT_PACKET;
720     quic_info_data_t *conn = NULL;
721
722     if ((long_packet_type == QUIC_LPT_INITIAL || long_packet_type == QUIC_LPT_0RTT) && dcid->len > 0) {
723         conn = (quic_info_data_t *) wmem_map_lookup(quic_initial_connections, dcid);
724         // Both the client and server can send Initial (since draft -13).
725         if (!conn && long_packet_type == QUIC_LPT_INITIAL) {
726             conn = quic_connection_find_dcid(pinfo, dcid, from_server);
727         }
728     } else {
729         conn = quic_connection_find_dcid(pinfo, dcid, from_server);
730     }
731
732     if (!is_long_packet && !conn) {
733         // For short packets, first try to find a match based on the address.
734         conn = quic_connection_find_dcid(pinfo, NULL, from_server);
735         if (conn) {
736             if ((*from_server && !quic_cids_has_match(&conn->server_cids, dcid)) ||
737                 (!*from_server && !quic_cids_has_match(&conn->client_cids, dcid))) {
738                 // Connection does not match packet.
739                 conn = NULL;
740             }
741         }
742
743         // No match found so far, potentially connection migration. Length of
744         // actual DCID is unknown, so just keep decrementing until found.
745         while (!conn && dcid->len > 4) {
746             dcid->len--;
747             if (quic_cids_is_known_length(dcid)) {
748                 conn = quic_connection_find_dcid(pinfo, dcid, from_server);
749             }
750         }
751         if (!conn) {
752             // No match found, truncate DCID (not really needed, but this
753             // ensures that debug prints clearly show that DCID is invalid).
754             dcid->len = 0;
755         }
756     }
757     return conn;
758 }
759
760 /** Create a new QUIC Connection based on a Client Initial packet. */
761 static quic_info_data_t *
762 quic_connection_create(packet_info *pinfo, guint32 version, const quic_cid_t *scid, const quic_cid_t *dcid)
763 {
764     quic_info_data_t *conn = NULL;
765
766     conn = wmem_new0(wmem_file_scope(), quic_info_data_t);
767     wmem_list_append(quic_connections, conn);
768     conn->number = quic_connections_count++;
769     conn->version = version;
770     copy_address_wmem(wmem_file_scope(), &conn->server_address, &pinfo->dst);
771     conn->server_port = pinfo->destport;
772
773     // Key connection by Client CID (if provided).
774     if (scid->len) {
775         memcpy(&conn->client_cids.data, scid, sizeof(quic_cid_t));
776         quic_cids_insert(&conn->client_cids.data, conn, FALSE);
777     }
778     if (dcid->len > 0) {
779         // According to the spec, the Initial Packet DCID MUST be at least 8
780         // bytes, but non-conforming implementations could exist.
781         memcpy(&conn->client_dcid_initial, dcid, sizeof(quic_cid_t));
782         wmem_map_insert(quic_initial_connections, &conn->client_dcid_initial, conn);
783     }
784
785     // For faster lookups without having to check DCID
786     conversation_t *conv = find_or_create_conversation(pinfo);
787     conversation_add_proto_data(conv, proto_quic, conn);
788
789     return conn;
790 }
791
792 #ifdef HAVE_LIBGCRYPT_AEAD
793 /**
794  * Use the new CID as additional identifier for the specified connection and
795  * remember it for connection tracking.
796  */
797 static void
798 quic_connection_add_cid(quic_info_data_t *conn, const quic_cid_t *new_cid, gboolean from_server)
799 {
800     DISSECTOR_ASSERT(new_cid->len > 0);
801     quic_cid_item_t *items = from_server ? &conn->server_cids : &conn->client_cids;
802
803     if (quic_cids_has_match(items, new_cid)) {
804         // CID is already known for this connection.
805         return;
806     }
807
808     // Insert new CID right after the first known CID (the very first CID cannot
809     // be overwritten since it might be used as key somewhere else).
810     quic_cid_item_t *new_item = wmem_new0(wmem_file_scope(), quic_cid_item_t);
811     new_item->data = *new_cid;
812     new_item->next = items->next;
813     items->next = new_item;
814
815     quic_cids_insert(&new_item->data, conn, from_server);
816 }
817 #endif
818
819 /** Create or update a connection. */
820 static void
821 quic_connection_create_or_update(quic_info_data_t **conn_p,
822                                  packet_info *pinfo, guint32 long_packet_type,
823                                  guint32 version, const quic_cid_t *scid,
824                                  const quic_cid_t *dcid, gboolean from_server)
825 {
826     quic_info_data_t *conn = *conn_p;
827
828     switch (long_packet_type) {
829     case QUIC_LPT_INITIAL:
830         if (!from_server) {
831             if (!conn) {
832                 // The first Initial Packet from the client creates a new connection.
833                 *conn_p = quic_connection_create(pinfo, version, scid, dcid);
834             } else if (conn->client_dcid_initial.len == 0 && dcid->len &&
835                        scid->len && !quic_cids_has_match(&conn->server_cids, scid)) {
836                 // If this client Initial Packet responds to a Retry Packet,
837                 // then remember the new DCID for the new Initial cipher and
838                 // clear the first server CID such that the next server Initial
839                 // Packet can link the connection with that new SCID.
840                 memcpy(&conn->client_dcid_initial, dcid, sizeof(quic_cid_t));
841                 wmem_map_insert(quic_initial_connections, &conn->client_dcid_initial, conn);
842                 wmem_map_remove(quic_server_connections, &conn->server_cids.data);
843                 memset(&conn->server_cids, 0, sizeof(quic_cid_t));
844             }
845             break;
846         }
847         /* fallthrough */
848     case QUIC_LPT_RETRY:
849     case QUIC_LPT_HANDSHAKE:
850         // Remember CID from first server Retry/Handshake packet
851         // (or from the first server Initial packet, since draft -13).
852         if (from_server && conn) {
853             if (long_packet_type == QUIC_LPT_RETRY) {
854                 // Stateless Retry Packet: the next Initial Packet from the
855                 // client should start a new cryptographic handshake. Erase the
856                 // current "Initial DCID" such that the next client Initial
857                 // packet populates the new value.
858                 wmem_map_remove(quic_initial_connections, &conn->client_dcid_initial);
859                 memset(&conn->client_dcid_initial, 0, sizeof(quic_cid_t));
860             }
861             if (conn->server_cids.data.len == 0 && scid->len) {
862                 memcpy(&conn->server_cids.data, scid, sizeof(quic_cid_t));
863                 quic_cids_insert(&conn->server_cids.data, conn, TRUE);
864             }
865         }
866         break;
867     }
868 }
869
870 static void
871 quic_connection_destroy(gpointer data, gpointer user_data _U_)
872 {
873     quic_info_data_t *conn = (quic_info_data_t *)data;
874     quic_cipher_reset(&conn->client_initial_cipher);
875     quic_cipher_reset(&conn->server_initial_cipher);
876     quic_cipher_reset(&conn->client_handshake_cipher);
877     quic_cipher_reset(&conn->server_handshake_cipher);
878
879     for (int i = 0; i < 2; i++) {
880         quic_cipher_reset(&conn->client_pp.cipher[i]);
881         quic_cipher_reset(&conn->server_pp.cipher[i]);
882     }
883 }
884 /* QUIC Connection tracking. }}} */
885
886
887 #ifdef HAVE_LIBGCRYPT_AEAD
888 static int
889 dissect_quic_frame_type(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree, guint offset, quic_info_data_t *quic_info, gboolean from_server)
890 {
891     proto_item *ti_ft, *ti_ftflags, *ti;
892     proto_tree *ft_tree, *ftflags_tree;
893     guint32 frame_type;
894     guint   orig_offset = offset;
895
896     ti_ft = proto_tree_add_item(quic_tree, hf_quic_frame, tvb, offset, 1, ENC_NA);
897     ft_tree = proto_item_add_subtree(ti_ft, ett_quic_ft);
898
899     ti_ftflags = proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type, tvb, offset, 1, ENC_NA, &frame_type);
900     proto_item_set_text(ti_ft, "%s", rval_to_str(frame_type, quic_frame_type_vals, "Unknown"));
901     offset += 1;
902
903     switch(frame_type){
904         case FT_PADDING:{
905             guint32 pad_len;
906
907             col_append_fstr(pinfo->cinfo, COL_INFO, ", PADDING");
908
909             /* A padding frame consists of a single zero octet, but for brevity
910              * sake let's combine multiple zeroes into a single field. */
911             pad_len = 1 + tvb_skip_guint8(tvb, offset, tvb_reported_length_remaining(tvb, offset), '\0') - offset;
912             ti = proto_tree_add_uint(ft_tree, hf_quic_frame_type_padding_length, tvb, offset, 0, pad_len);
913             PROTO_ITEM_SET_GENERATED(ti);
914             proto_item_append_text(ti_ft, " Length: %u", pad_len);
915             offset += pad_len - 1;
916         }
917         break;
918         case FT_RST_STREAM:{
919             guint64 stream_id;
920             guint32 error_code, len_streamid = 0, len_finaloffset = 0;
921
922             col_append_fstr(pinfo->cinfo, COL_INFO, ", RS");
923
924             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_rsts_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, &stream_id, &len_streamid);
925             offset += len_streamid;
926
927             proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type_rsts_application_error_code, tvb, offset, 2, ENC_BIG_ENDIAN, &error_code);
928             offset += 2;
929
930             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_rsts_final_offset, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_finaloffset);
931             offset += len_finaloffset;
932
933             proto_item_append_text(ti_ft, " Stream ID: %" G_GINT64_MODIFIER "u, Error code: %s", stream_id, val_to_str(error_code, quic_application_error_code_vals, "0x%04x"));
934         }
935         break;
936         case FT_CONNECTION_CLOSE:{
937             guint32 len_reasonphrase, len_frametype, error_code;
938             guint64 len_reason = 0;
939             const char *tls_alert = NULL;
940
941             col_append_fstr(pinfo->cinfo, COL_INFO, ", CC");
942
943             proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type_cc_error_code, tvb, offset, 2, ENC_BIG_ENDIAN, &error_code);
944             if ((error_code & 0xff00) == 0x0100) {  // CRYPTO_ERROR
945                 tls_alert = try_val_to_str(error_code & 0xff, ssl_31_alert_description);
946                 if (tls_alert) {
947                     proto_tree_add_item(ft_tree, hf_quic_frame_type_cc_error_code_tls_alert, tvb, offset + 1, 1, ENC_BIG_ENDIAN);
948                 }
949             }
950             offset += 2;
951
952             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_cc_frame_type, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_frametype);
953             offset += len_frametype;
954
955             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_cc_reason_phrase_length, tvb, offset, -1, ENC_VARINT_QUIC, &len_reason, &len_reasonphrase);
956             offset += len_reasonphrase;
957
958             proto_tree_add_item(ft_tree, hf_quic_frame_type_cc_reason_phrase, tvb, offset, (guint32)len_reason, ENC_ASCII|ENC_NA);
959             offset += (guint32)len_reason;
960
961             proto_item_append_text(ti_ft, " Error code: %s", rval_to_str(error_code, quic_transport_error_code_vals, "Unknown (%d)"));
962             if (tls_alert) {
963                 proto_item_append_text(ti_ft, " (%s)", tls_alert);
964             }
965         }
966         break;
967         case FT_APPLICATION_CLOSE:{
968             guint32 len_reasonphrase, error_code;
969             guint64 len_reason;
970
971             col_append_fstr(pinfo->cinfo, COL_INFO, ", AC");
972
973             proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type_ac_error_code, tvb, offset, 2, ENC_BIG_ENDIAN, &error_code);
974             offset += 2;
975
976             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ac_reason_phrase_length, tvb, offset, -1, ENC_VARINT_QUIC, &len_reason, &len_reasonphrase);
977             offset += len_reasonphrase;
978             proto_tree_add_item(ft_tree, hf_quic_frame_type_ac_reason_phrase, tvb, offset, (guint32)len_reason, ENC_ASCII|ENC_NA);
979             offset += (guint32)len_reason;
980
981             proto_item_append_text(ti_ft, " Error code: %s", val_to_str(error_code, quic_application_error_code_vals, "0x%04x"));
982         }
983         break;
984         case FT_MAX_DATA:{
985             guint32 len_maximumdata;
986
987             col_append_fstr(pinfo->cinfo, COL_INFO, ", MD");
988
989             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_md_maximum_data, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_maximumdata);
990             offset += len_maximumdata;
991         }
992         break;
993         case FT_MAX_STREAM_DATA:{
994             guint32 len_streamid, len_maximumstreamdata;
995
996             col_append_fstr(pinfo->cinfo, COL_INFO, ", MSD");
997
998             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_msd_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_streamid);
999             offset += len_streamid;
1000
1001             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_msd_maximum_stream_data, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_maximumstreamdata);
1002             offset += len_maximumstreamdata;
1003         }
1004         break;
1005         case FT_MAX_STREAM_ID:{
1006             guint32 len_streamid;
1007
1008             col_append_fstr(pinfo->cinfo, COL_INFO, ", MSI");
1009
1010             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_msi_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_streamid);
1011             offset += len_streamid;
1012         }
1013         break;
1014         case FT_PING:{
1015             col_append_fstr(pinfo->cinfo, COL_INFO, ", PING");
1016         }
1017         break;
1018         case FT_BLOCKED:{
1019             guint32 len_offset;
1020
1021             col_append_fstr(pinfo->cinfo, COL_INFO, ", B");
1022
1023             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_blocked_offset, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_offset);
1024             offset += len_offset;
1025         }
1026         break;
1027         case FT_STREAM_BLOCKED:{
1028             guint32 len_streamid, len_offset;
1029
1030             col_append_fstr(pinfo->cinfo, COL_INFO, ", SB");
1031
1032             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_sb_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_streamid);
1033             offset += len_streamid;
1034
1035             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_sb_offset, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_offset);
1036             offset += len_offset;
1037         }
1038         break;
1039         case FT_STREAM_ID_BLOCKED:{
1040             guint32 len_streamid;
1041
1042             col_append_fstr(pinfo->cinfo, COL_INFO, ", SIB");
1043
1044             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_sib_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_streamid);
1045             offset += len_streamid;
1046         }
1047         break;
1048         case FT_NEW_CONNECTION_ID:{
1049             guint32 len_sequence;
1050             guint32 nci_length;
1051             gboolean valid_cid = FALSE;
1052
1053             col_append_fstr(pinfo->cinfo, COL_INFO, ", NCI");
1054
1055             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_nci_sequence, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_sequence);
1056             offset += len_sequence;
1057
1058             ti = proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type_nci_connection_id_length, tvb, offset, 1, ENC_BIG_ENDIAN, &nci_length);
1059             offset++;
1060
1061             valid_cid = nci_length >= 4 && nci_length <= 18;
1062             if (!valid_cid) {
1063                 expert_add_info_format(pinfo, ti, &ei_quic_protocol_violation,
1064                             "Connection ID Length must be between 4 and 18 bytes");
1065             }
1066
1067             proto_tree_add_item(ft_tree, hf_quic_frame_type_nci_connection_id, tvb, offset, nci_length, ENC_NA);
1068             if (valid_cid && quic_info) {
1069                 quic_cid_t cid = {.len=0};
1070                 tvb_memcpy(tvb, cid.cid, offset, nci_length);
1071                 cid.len = nci_length;
1072                 quic_connection_add_cid(quic_info, &cid, from_server);
1073             }
1074             offset += nci_length;
1075
1076             proto_tree_add_item(ft_tree, hf_quic_frame_type_nci_stateless_reset_token, tvb, offset, 16, ENC_NA);
1077             offset += 16;
1078         }
1079         break;
1080         case FT_STOP_SENDING:{
1081             guint32 len_streamid, error_code;
1082
1083             col_append_fstr(pinfo->cinfo, COL_INFO, ", SS");
1084
1085             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ss_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &len_streamid);
1086             offset += len_streamid;
1087
1088             proto_tree_add_item_ret_uint(ft_tree, hf_quic_frame_type_ss_application_error_code, tvb, offset, 2, ENC_BIG_ENDIAN, &error_code);
1089             offset += 2;
1090
1091             proto_item_append_text(ti_ft, " Error code: 0x%04x", error_code);
1092         }
1093         break;
1094         case FT_ACK:{
1095             guint64 ack_block_count;
1096             guint32 lenvar;
1097
1098             col_append_fstr(pinfo->cinfo, COL_INFO, ", ACK");
1099
1100             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_largest_acknowledged, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1101             offset += lenvar;
1102
1103             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_ack_delay, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1104             offset += lenvar;
1105
1106             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_ack_block_count, tvb, offset, -1, ENC_VARINT_QUIC, &ack_block_count, &lenvar);
1107             offset += lenvar;
1108
1109             /* ACK Block */
1110             /* First ACK Block Length */
1111             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_fab, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1112             offset += lenvar;
1113
1114             /* Repeated "Ack Block Count" */
1115             while(ack_block_count){
1116
1117                 /* Gap To Next Block */
1118                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_gap, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1119                 offset += lenvar;
1120
1121                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ack_ack_block, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1122                 offset += lenvar;
1123
1124                 ack_block_count--;
1125             }
1126         }
1127         break;
1128         case FT_PATH_CHALLENGE:{
1129             col_append_fstr(pinfo->cinfo, COL_INFO, ", PC");
1130
1131             proto_tree_add_item(ft_tree, hf_quic_frame_type_path_challenge_data, tvb, offset, 8, ENC_NA);
1132             offset += 8;
1133         }
1134         break;
1135         case FT_PATH_RESPONSE:{
1136             col_append_fstr(pinfo->cinfo, COL_INFO, ", PR");
1137
1138             proto_tree_add_item(ft_tree, hf_quic_frame_type_path_response_data, tvb, offset, 8, ENC_NA);
1139             offset += 8;
1140         }
1141         break;
1142         case FT_STREAM_10:
1143         case FT_STREAM_11:
1144         case FT_STREAM_12:
1145         case FT_STREAM_13:
1146         case FT_STREAM_14:
1147         case FT_STREAM_15:
1148         case FT_STREAM_16:
1149         case FT_STREAM_17: {
1150             guint64 stream_id, length;
1151             guint32 lenvar;
1152
1153             offset -= 1;
1154
1155             col_append_fstr(pinfo->cinfo, COL_INFO, ", STREAM");
1156
1157             ftflags_tree = proto_item_add_subtree(ti_ftflags, ett_quic_ftflags);
1158             proto_tree_add_item(ftflags_tree, hf_quic_frame_type_stream_fin, tvb, offset, 1, ENC_NA);
1159             proto_tree_add_item(ftflags_tree, hf_quic_frame_type_stream_len, tvb, offset, 1, ENC_NA);
1160             proto_tree_add_item(ftflags_tree, hf_quic_frame_type_stream_off, tvb, offset, 1, ENC_NA);
1161             offset += 1;
1162
1163             proto_tree_add_item_ret_varint(ft_tree, hf_quic_stream_stream_id, tvb, offset, -1, ENC_VARINT_QUIC, &stream_id, &lenvar);
1164             offset += lenvar;
1165
1166             proto_item_append_text(ti_ft, " Stream ID: %" G_GINT64_MODIFIER "u", stream_id);
1167             col_append_fstr(pinfo->cinfo, COL_INFO, "(%" G_GINT64_MODIFIER "u)", stream_id);
1168
1169             if (frame_type & FTFLAGS_STREAM_OFF) {
1170                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_stream_offset, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1171                 offset += lenvar;
1172             }
1173
1174             if (frame_type & FTFLAGS_STREAM_LEN) {
1175                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_stream_length, tvb, offset, -1, ENC_VARINT_QUIC, &length, &lenvar);
1176                 offset += lenvar;
1177             } else {
1178                length = tvb_reported_length_remaining(tvb, offset);
1179             }
1180
1181             proto_tree_add_item(ft_tree, hf_quic_stream_data, tvb, offset, (int)length, ENC_NA);
1182             offset += (int)length;
1183         }
1184         break;
1185         case FT_CRYPTO: {
1186             guint64 crypto_offset, crypto_length;
1187             guint32 lenvar;
1188             col_append_fstr(pinfo->cinfo, COL_INFO, ", CRYPTO");
1189             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_crypto_offset, tvb, offset, -1, ENC_VARINT_QUIC, &crypto_offset, &lenvar);
1190             offset += lenvar;
1191             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_crypto_length, tvb, offset, -1, ENC_VARINT_QUIC, &crypto_length, &lenvar);
1192             offset += lenvar;
1193             proto_tree_add_item(ft_tree, hf_quic_frame_type_crypto_crypto_data, tvb, offset, (guint32)crypto_length, ENC_NA);
1194             {
1195                 tvbuff_t *next_tvb = tvb_new_subset_length(tvb, offset, (int)crypto_length);
1196                 col_set_writable(pinfo->cinfo, -1, FALSE);
1197                 /*
1198                  * Dissect TLS handshake record. The Client/Server Hello (CH/SH)
1199                  * are contained in the Initial Packet. 0-RTT keys are ready
1200                  * after CH. HS + 1-RTT keys are ready after SH.
1201                  * (Note: keys captured from the client might become available
1202                  * after capturing the packets due to processing delay.)
1203                  * These keys will be loaded in the first HS/0-RTT/1-RTT msg.
1204                  */
1205                 call_dissector(tls13_handshake_handle, next_tvb, pinfo, ft_tree);
1206                 col_set_writable(pinfo->cinfo, -1, TRUE);
1207             }
1208             offset += (guint32)crypto_length;
1209         }
1210         break;
1211         case FT_NEW_TOKEN: {
1212             guint64 token_length;
1213             guint32 lenvar;
1214
1215             col_append_fstr(pinfo->cinfo, COL_INFO, ", NT");
1216
1217             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_nt_length, tvb, offset, -1, ENC_VARINT_QUIC, &token_length, &lenvar);
1218             offset += lenvar;
1219
1220             proto_tree_add_item(ft_tree, hf_quic_frame_type_nt_token, tvb, offset, (guint32)token_length, ENC_NA);
1221             offset += (guint32)token_length;
1222         }
1223         break;
1224         case FT_ACK_ECN:{
1225             guint64 ack_block_count;
1226             guint32 lenvar;
1227
1228             col_append_fstr(pinfo->cinfo, COL_INFO, ", AE");
1229
1230             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_largest_acknowledged, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1231             offset += lenvar;
1232
1233             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ack_delay, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1234             offset += lenvar;
1235
1236             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ect0_count, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1237             offset += lenvar;
1238
1239             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ect1_count, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1240             offset += lenvar;
1241
1242             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ecn_ce_count, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1243             offset += lenvar;
1244
1245             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ack_block_count, tvb, offset, -1, ENC_VARINT_QUIC, &ack_block_count, &lenvar);
1246             offset += lenvar;
1247
1248             /* ACK Block */
1249             /* First ACK Block Length */
1250             proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_fab, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1251             offset += lenvar;
1252
1253             /* Repeated "Ack Block Count" */
1254             while(ack_block_count){
1255
1256                 /* Gap To Next Block */
1257                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_gap, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1258                 offset += lenvar;
1259
1260                 proto_tree_add_item_ret_varint(ft_tree, hf_quic_frame_type_ae_ack_block, tvb, offset, -1, ENC_VARINT_QUIC, NULL, &lenvar);
1261                 offset += lenvar;
1262
1263                 ack_block_count--;
1264             }
1265         }
1266         break;
1267         default:
1268             expert_add_info_format(pinfo, ti_ft, &ei_quic_ft_unknown, "Unknown Frame Type %u", frame_type);
1269         break;
1270     }
1271
1272     proto_item_set_len(ti_ft, offset - orig_offset);
1273
1274     return offset;
1275 }
1276 #endif /* HAVE_LIBGCRYPT_AEAD */
1277
1278 #ifdef HAVE_LIBGCRYPT_AEAD
1279 static gcry_error_t
1280 qhkdf_expand(int md, const guint8 *secret, guint secret_len,
1281              const char *label, guint8 *out, guint out_len);
1282
1283 static gboolean
1284 quic_cipher_init(guint32 version, quic_cipher *cipher, int hash_algo, guint8 key_length, guint8 *secret);
1285
1286
1287 /**
1288  * Given a QUIC message (header + non-empty payload), the actual packet number,
1289  * try to decrypt it using the cipher.
1290  * As the header points to the original buffer with an encrypted packet number,
1291  * the (encrypted) packet number length is also included.
1292  *
1293  * The actual packet number must be constructed according to
1294  * https://tools.ietf.org/html/draft-ietf-quic-transport-13#section-4.8
1295  */
1296 static void
1297 quic_decrypt_message(quic_cipher *cipher, tvbuff_t *head, guint header_length, guint pkn_len, guint64 packet_number, quic_decrypt_result_t *result)
1298 {
1299     gcry_error_t    err;
1300     guint8         *header;
1301     guint8          nonce[TLS13_AEAD_NONCE_LENGTH];
1302     guint8         *buffer;
1303     guint8         *atag[16];
1304     guint           buffer_length;
1305     const guchar  **error = &result->error;
1306
1307     DISSECTOR_ASSERT(cipher != NULL);
1308     DISSECTOR_ASSERT(cipher->pp_cipher != NULL);
1309     DISSECTOR_ASSERT(pkn_len < header_length);
1310     DISSECTOR_ASSERT(1 <= pkn_len && pkn_len <= 4);
1311     // copy header, but replace encrypted PKN by plaintext PKN.
1312     header = (guint8 *)tvb_memdup(wmem_packet_scope(), head, 0, header_length);
1313     quic_encode_packet_number(header + header_length - pkn_len, (guint32)packet_number, pkn_len);
1314
1315     /* Input is "header || ciphertext (buffer) || auth tag (16 bytes)" */
1316     buffer_length = tvb_captured_length_remaining(head, header_length + 16);
1317     if (buffer_length == 0) {
1318         *error = "Decryption not possible, ciphertext is too short";
1319         return;
1320     }
1321     buffer = (guint8 *)tvb_memdup(wmem_file_scope(), head, header_length, buffer_length);
1322     tvb_memcpy(head, atag, header_length + buffer_length, 16);
1323
1324     memcpy(nonce, cipher->pp_iv, TLS13_AEAD_NONCE_LENGTH);
1325     /* Packet number is left-padded with zeroes and XORed with write_iv */
1326     phton64(nonce + sizeof(nonce) - 8, pntoh64(nonce + sizeof(nonce) - 8) ^ packet_number);
1327
1328     gcry_cipher_reset(cipher->pp_cipher);
1329     err = gcry_cipher_setiv(cipher->pp_cipher, nonce, TLS13_AEAD_NONCE_LENGTH);
1330     if (err) {
1331         *error = wmem_strdup_printf(wmem_file_scope(), "Decryption (setiv) failed: %s", gcry_strerror(err));
1332         return;
1333     }
1334
1335     /* associated data (A) is the contents of QUIC header */
1336     err = gcry_cipher_authenticate(cipher->pp_cipher, header, header_length);
1337     if (err) {
1338         *error = wmem_strdup_printf(wmem_file_scope(), "Decryption (authenticate) failed: %s", gcry_strerror(err));
1339         return;
1340     }
1341
1342     /* Output ciphertext (C) */
1343     err = gcry_cipher_decrypt(cipher->pp_cipher, buffer, buffer_length, NULL, 0);
1344     if (err) {
1345         *error = wmem_strdup_printf(wmem_file_scope(), "Decryption (decrypt) failed: %s", gcry_strerror(err));
1346         return;
1347     }
1348
1349     err = gcry_cipher_checktag(cipher->pp_cipher, atag, 16);
1350     if (err) {
1351         *error = wmem_strdup_printf(wmem_file_scope(), "Decryption (checktag) failed: %s", gcry_strerror(err));
1352         return;
1353     }
1354
1355     result->error = NULL;
1356     result->data = buffer;
1357     result->data_len = buffer_length;
1358 }
1359
1360 static gboolean
1361 quic_hkdf_expand_label(int hash_algo, guint8 *secret, guint secret_len, const char *label, guint8 *out, guint out_len)
1362 {
1363     const StringInfo secret_si = { secret, secret_len };
1364     guchar *out_mem = NULL;
1365     if (tls13_hkdf_expand_label(hash_algo, &secret_si, "quic ", label, out_len, &out_mem)) {
1366         memcpy(out, out_mem, out_len);
1367         wmem_free(NULL, out_mem);
1368         return TRUE;
1369     }
1370     return FALSE;
1371 }
1372
1373 /**
1374  * Compute the client and server initial secrets given Connection ID "cid".
1375  *
1376  * On success TRUE is returned and the two initial secrets are set.
1377  * FALSE is returned on error (see "error" parameter for the reason).
1378  */
1379 static gboolean
1380 quic_derive_initial_secrets(const quic_cid_t *cid,
1381                             guint8 client_initial_secret[HASH_SHA2_256_LENGTH],
1382                             guint8 server_initial_secret[HASH_SHA2_256_LENGTH],
1383                             const gchar **error)
1384 {
1385     /*
1386      * https://tools.ietf.org/html/draft-ietf-quic-tls-14#section-5.1.1
1387      *
1388      * initial_salt = 0x9c108f98520a5c5c32968e950e8a2c5fe06d6c38
1389      * initial_secret = HKDF-Extract(initial_salt, client_dst_connection_id)
1390      *
1391      * client_initial_secret = HKDF-Expand-Label(initial_secret,
1392      *                                           "client in", "", Hash.length)
1393      * server_initial_secret = HKDF-Expand-Label(initial_secret,
1394      *                                           "server in", "", Hash.length)
1395      *
1396      * Hash for handshake packets is SHA-256 (output size 32).
1397      */
1398     static const guint8 handshake_salt[20] = {
1399         0x9c, 0x10, 0x8f, 0x98, 0x52, 0x0a, 0x5c, 0x5c, 0x32, 0x96,
1400         0x8e, 0x95, 0x0e, 0x8a, 0x2c, 0x5f, 0xe0, 0x6d, 0x6c, 0x38
1401     };
1402     gcry_error_t    err;
1403     guint8          secret[HASH_SHA2_256_LENGTH];
1404
1405     err = hkdf_extract(GCRY_MD_SHA256, handshake_salt, sizeof(handshake_salt),
1406                        cid->cid, cid->len, secret);
1407     if (err) {
1408         *error = wmem_strdup_printf(wmem_packet_scope(), "Failed to extract secrets: %s", gcry_strerror(err));
1409         return FALSE;
1410     }
1411
1412     if (!quic_hkdf_expand_label(GCRY_MD_SHA256, secret, sizeof(secret), "client in",
1413                                 client_initial_secret, HASH_SHA2_256_LENGTH)) {
1414         *error = "Key expansion (client) failed";
1415         return FALSE;
1416     }
1417
1418     if (!quic_hkdf_expand_label(GCRY_MD_SHA256, secret, sizeof(secret), "server in",
1419                                 server_initial_secret, HASH_SHA2_256_LENGTH)) {
1420         *error = "Key expansion (server) failed";
1421         return FALSE;
1422     }
1423
1424     *error = NULL;
1425     return TRUE;
1426 }
1427
1428 /**
1429  * Maps a Packet Protection cipher to the Packet Number protection cipher.
1430  * See https://tools.ietf.org/html/draft-ietf-quic-tls-14#section-5.3
1431  */
1432 static gboolean
1433 quic_get_pn_cipher_algo(int cipher_algo, int *pn_cipher_mode)
1434 {
1435     switch (cipher_algo) {
1436     case GCRY_CIPHER_AES128:
1437     case GCRY_CIPHER_AES256:
1438         *pn_cipher_mode = GCRY_CIPHER_MODE_CTR;
1439         return TRUE;
1440 #ifdef HAVE_LIBGCRYPT_CHACHA20
1441     case GCRY_CIPHER_CHACHA20:
1442         *pn_cipher_mode = 0;
1443         return TRUE;
1444 #endif /* HAVE_LIBGCRYPT_CHACHA20 */
1445     default:
1446         return FALSE;
1447     }
1448 }
1449
1450 /*
1451  * (Re)initialize the PNE/PP ciphers using the given cipher algorithm.
1452  * If the optional base secret is given, then its length MUST match the hash
1453  * algorithm output.
1454  */
1455 static gboolean
1456 quic_cipher_prepare(guint32 version, quic_cipher *cipher, int hash_algo, int cipher_algo, int cipher_mode, guint8 *secret, const char **error)
1457 {
1458     /* Clear previous state (if any). */
1459     quic_cipher_reset(cipher);
1460
1461     int pn_cipher_mode;
1462     if (!quic_get_pn_cipher_algo(cipher_algo, &pn_cipher_mode)) {
1463         *error = "Unsupported cipher algorithm";
1464         return FALSE;
1465     }
1466
1467     if (gcry_cipher_open(&cipher->pn_cipher, cipher_algo, pn_cipher_mode, 0) ||
1468         gcry_cipher_open(&cipher->pp_cipher, cipher_algo, cipher_mode, 0)) {
1469         quic_cipher_reset(cipher);
1470         *error = "Failed to create ciphers";
1471         return FALSE;
1472     }
1473
1474     if (secret) {
1475         guint cipher_keylen = (guint8) gcry_cipher_get_algo_keylen(cipher_algo);
1476         if (!quic_cipher_init(version, cipher, hash_algo, cipher_keylen, secret)) {
1477             quic_cipher_reset(cipher);
1478             *error = "Failed to derive key material for cipher";
1479             return FALSE;
1480         }
1481     }
1482
1483     return TRUE;
1484 }
1485
1486 static gboolean
1487 quic_create_initial_decoders(const quic_cid_t *cid, const gchar **error, quic_info_data_t *quic_info)
1488 {
1489     guint8          client_secret[HASH_SHA2_256_LENGTH];
1490     guint8          server_secret[HASH_SHA2_256_LENGTH];
1491     guint32         version = quic_info->version;
1492
1493     if (!quic_derive_initial_secrets(cid, client_secret, server_secret, error)) {
1494         return FALSE;
1495     }
1496
1497     /* Packet numbers are protected with AES128-CTR,
1498      * initial packets are protected with AEAD_AES_128_GCM. */
1499     if (!quic_cipher_prepare(version, &quic_info->client_initial_cipher, GCRY_MD_SHA256,
1500                              GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_GCM, client_secret, error) ||
1501         !quic_cipher_prepare(version, &quic_info->server_initial_cipher, GCRY_MD_SHA256,
1502                              GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_GCM, server_secret, error)) {
1503         return FALSE;
1504     }
1505
1506     return TRUE;
1507 }
1508
1509 static gboolean
1510 quic_create_decoders(packet_info *pinfo, guint32 version, quic_info_data_t *quic_info, quic_cipher *cipher,
1511                      gboolean from_server, TLSRecordType type, const char **error)
1512 {
1513     if (!quic_info->hash_algo) {
1514         if (!tls_get_cipher_info(pinfo, &quic_info->cipher_algo, &quic_info->cipher_mode, &quic_info->hash_algo)) {
1515             *error = "Unable to retrieve cipher information";
1516             return FALSE;
1517         }
1518     }
1519
1520     guint hash_len = gcry_md_get_algo_dlen(quic_info->hash_algo);
1521     char *secret = (char *)wmem_alloc0(wmem_packet_scope(), hash_len);
1522
1523     if (!tls13_get_quic_secret(pinfo, from_server, type, hash_len, secret)) {
1524         *error = "Secrets are not available";
1525         return FALSE;
1526     }
1527
1528     if (!quic_cipher_prepare(version, cipher, quic_info->hash_algo,
1529                              quic_info->cipher_algo, quic_info->cipher_mode, secret, error)) {
1530         return FALSE;
1531     }
1532
1533     return TRUE;
1534 }
1535
1536 /**
1537  * Computes QHKDF-Expand(Secret, Label, Length).
1538  * Caller must ensure that "out" is large enough for "out_len".
1539  */
1540 static gcry_error_t
1541 qhkdf_expand(int md, const guint8 *secret, guint secret_len,
1542              const char *label, guint8 *out, guint out_len)
1543 {
1544     /* https://tools.ietf.org/html/draft-ietf-quic-tls-10#section-5.2.1
1545      *     QHKDF-Expand(Secret, Label, Length) =
1546      *          HKDF-Expand(Secret, QhkdfLabel, Length)
1547      *     struct {
1548      *         uint16 length = Length;
1549      *         opaque label<6..255> = "QUIC " + Label;
1550      *     } QhkdfLabel;
1551      */
1552     gcry_error_t err;
1553     const guint label_length = (guint) strlen(label);
1554
1555     /* Some sanity checks */
1556     DISSECTOR_ASSERT(label_length > 0 && 5 + label_length <= 255);
1557
1558     /* info = QhkdfLabel { length, label } */
1559     GByteArray *info = g_byte_array_new();
1560     const guint16 length = g_htons(out_len);
1561     g_byte_array_append(info, (const guint8 *)&length, sizeof(length));
1562
1563     const guint8 label_vector_length = 5 + label_length;
1564     g_byte_array_append(info, &label_vector_length, 1);
1565     g_byte_array_append(info, "QUIC ", 5);
1566     g_byte_array_append(info, label, label_length);
1567
1568     err = hkdf_expand(md, secret, secret_len, info->data, info->len, out, out_len);
1569     g_byte_array_free(info, TRUE);
1570     return err;
1571 }
1572
1573 /**
1574  * Tries to obtain the QUIC application traffic secrets.
1575  */
1576 static gboolean
1577 quic_get_traffic_secret(packet_info *pinfo, int hash_algo, quic_pp_state_t *pp_state, gboolean from_client)
1578 {
1579     guint hash_len = gcry_md_get_algo_dlen(hash_algo);
1580     char *secret = (char *)wmem_alloc0(wmem_packet_scope(), hash_len);
1581     if (!tls13_get_quic_secret(pinfo, !from_client, TLS_SECRET_APP, hash_len, secret)) {
1582         return FALSE;
1583     }
1584     pp_state->next_secret = (guint8 *)wmem_memdup(wmem_file_scope(), secret, hash_len);
1585     return TRUE;
1586 }
1587
1588 /**
1589  * Expands the secret (length MUST be the same as the "hash_algo" digest size)
1590  * and initialize cipher with the new key.
1591  */
1592 static gboolean
1593 quic_cipher_init(guint32 version _U_, quic_cipher *cipher, int hash_algo, guint8 key_length, guint8 *secret)
1594 {
1595     guchar      write_key[256/8];   /* Maximum key size is for AES256 cipher. */
1596     guchar      pn_key[256/8];
1597     guint       hash_len = gcry_md_get_algo_dlen(hash_algo);
1598
1599     if (key_length > sizeof(write_key)) {
1600         return FALSE;
1601     }
1602
1603     if (!quic_hkdf_expand_label(hash_algo, secret, hash_len, "key", write_key, key_length) ||
1604         !quic_hkdf_expand_label(hash_algo, secret, hash_len, "iv", cipher->pp_iv, sizeof(cipher->pp_iv)) ||
1605         !quic_hkdf_expand_label(hash_algo, secret, hash_len, "pn", pn_key, key_length)) {
1606         return FALSE;
1607     }
1608
1609     return gcry_cipher_setkey(cipher->pn_cipher, pn_key, key_length) == 0 &&
1610            gcry_cipher_setkey(cipher->pp_cipher, write_key, key_length) == 0;
1611 }
1612
1613 /**
1614  * Updates the packet protection secret to the next one.
1615  */
1616 static void
1617 quic_update_key(int hash_algo, quic_pp_state_t *pp_state, gboolean from_client)
1618 {
1619     guint hash_len = gcry_md_get_algo_dlen(hash_algo);
1620     qhkdf_expand(hash_algo, pp_state->next_secret, hash_len,
1621                  from_client ? "client 1rtt" : "server 1rtt",
1622                  pp_state->next_secret, hash_len);
1623 }
1624
1625 /**
1626  * Tries to construct the appropriate cipher for the current key phase.
1627  * See also "PROTECTED PAYLOAD DECRYPTION" comment on top of this file.
1628  */
1629 static quic_cipher *
1630 quic_get_pp_cipher(packet_info *pinfo, gboolean key_phase, quic_info_data_t *quic_info, gboolean from_server)
1631 {
1632     guint32     version = quic_info->version;
1633     const char *error = NULL;
1634     gboolean    success = FALSE;
1635
1636     /* Keys were previously not available. */
1637     if (quic_info->skip_decryption) {
1638         return NULL;
1639     }
1640
1641     quic_pp_state_t *client_pp = &quic_info->client_pp;
1642     quic_pp_state_t *server_pp = &quic_info->server_pp;
1643     quic_pp_state_t *pp_state = !from_server ? client_pp : server_pp;
1644
1645     /* Try to lookup secrets if not available. */
1646     if (!quic_info->client_pp.next_secret) {
1647         /* Query TLS for the cipher suite. */
1648         if (!tls_get_cipher_info(pinfo, &quic_info->cipher_algo, &quic_info->cipher_mode, &quic_info->hash_algo)) {
1649             /* No previous TLS handshake found or unsupported ciphers, fail. */
1650             quic_info->skip_decryption = TRUE;
1651             return NULL;
1652         }
1653
1654         /* Retrieve secrets for both the client and server. */
1655         if (!quic_get_traffic_secret(pinfo, quic_info->hash_algo, client_pp, TRUE) ||
1656             !quic_get_traffic_secret(pinfo, quic_info->hash_algo, server_pp, FALSE)) {
1657             quic_info->skip_decryption = TRUE;
1658             return NULL;
1659         }
1660
1661         /* Create initial cipher handles for KEY_PHASE 0 and 1. */
1662         if (!quic_cipher_prepare(version, &client_pp->cipher[0], quic_info->hash_algo,
1663                                  quic_info->cipher_algo, quic_info->cipher_mode, client_pp->next_secret, &error) ||
1664             !quic_cipher_prepare(version, &server_pp->cipher[0], quic_info->hash_algo,
1665                                  quic_info->cipher_algo, quic_info->cipher_mode, server_pp->next_secret, &error)) {
1666             quic_info->skip_decryption = TRUE;
1667             return NULL;
1668         }
1669         quic_update_key(quic_info->hash_algo, pp_state, !from_server);
1670     }
1671
1672     /*
1673      * If the key phase changed, try to decrypt the packet using the new cipher.
1674      * If that fails, then it is either a malicious packet or out-of-order.
1675      * In that case, try the previous cipher (unless it is the very first KP1).
1676      */
1677     if (key_phase != pp_state->key_phase) {
1678         quic_cipher new_cipher;
1679
1680         memset(&new_cipher, 0, sizeof(quic_cipher));
1681         if (!quic_cipher_prepare(version, &new_cipher, quic_info->hash_algo,
1682                                  quic_info->cipher_algo, quic_info->cipher_mode, server_pp->next_secret, &error)) {
1683             /* This should never be reached, if the parameters were wrong
1684              * before, then it should have set "skip_decryption". */
1685             REPORT_DISSECTOR_BUG("quic_cipher_prepare unexpectedly failed: %s", error);
1686             return NULL;
1687         }
1688
1689         // TODO verify decryption before switching keys.
1690         success = TRUE;
1691
1692         if (success) {
1693             /* Verified the cipher, use it from now on and rotate the key. */
1694             quic_cipher_reset(&pp_state->cipher[key_phase]);
1695             pp_state->cipher[key_phase] = new_cipher;
1696             quic_update_key(quic_info->hash_algo, pp_state, !from_server);
1697
1698             pp_state->key_phase = key_phase;
1699             //pp_state->changed_in_pkn = pkn;
1700
1701             return &pp_state->cipher[key_phase];
1702         } else {
1703             // TODO fallback to previous cipher
1704             return NULL;
1705         }
1706     }
1707
1708     return &pp_state->cipher[key_phase];
1709 }
1710 #endif /* HAVE_LIBGCRYPT_AEAD */
1711
1712 #ifdef HAVE_LIBGCRYPT_AEAD
1713 /**
1714  * Process (protected) payload, adding the encrypted payload to the tree. If
1715  * decryption is possible, frame dissection is also attempted.
1716  *
1717  * The given offset must correspond to the end of the QUIC header and begin of
1718  * the (protected) payload. Dissected frames are appended to "tree" and expert
1719  * info is attached to "ti" (the field with the encrypted payload).
1720  */
1721 static void
1722 quic_process_payload(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, proto_item *ti, guint offset,
1723                      quic_info_data_t *quic_info, quic_packet_info_t *quic_packet, gboolean from_server,
1724                      quic_cipher *cipher, guint pkn_len)
1725 {
1726     quic_decrypt_result_t *decryption = &quic_packet->decryption;
1727
1728     /*
1729      * If no decryption error has occurred yet, try decryption on the first
1730      * pass and store the result for later use.
1731      */
1732     if (!PINFO_FD_VISITED(pinfo)) {
1733         if (!quic_packet->decryption.error && cipher && cipher->pp_cipher) {
1734             quic_decrypt_message(cipher, tvb, offset, pkn_len, quic_packet->packet_number, &quic_packet->decryption);
1735         }
1736     }
1737
1738     if (decryption->error) {
1739         expert_add_info_format(pinfo, ti, &ei_quic_decryption_failed,
1740                                "Decryption failed: %s", decryption->error);
1741     } else if (decryption->data_len) {
1742         tvbuff_t *decrypted_tvb = tvb_new_child_real_data(tvb, decryption->data,
1743                 decryption->data_len, decryption->data_len);
1744         add_new_data_source(pinfo, decrypted_tvb, "Decrypted QUIC");
1745
1746         guint decrypted_offset = 0;
1747         while (tvb_reported_length_remaining(decrypted_tvb, decrypted_offset) > 0) {
1748             decrypted_offset = dissect_quic_frame_type(decrypted_tvb, pinfo, tree, decrypted_offset, quic_info, from_server);
1749         }
1750     } else if (quic_info->skip_decryption) {
1751         expert_add_info_format(pinfo, ti, &ei_quic_decryption_failed,
1752                                "Decryption skipped because keys are not available.");
1753     }
1754 }
1755 #else /* !HAVE_LIBGCRYPT_AEAD */
1756 static void
1757 quic_process_payload(tvbuff_t *tvb _U_, packet_info *pinfo, proto_tree *tree _U_, proto_item *ti, guint offset _U_,
1758                      quic_info_data_t *quic_info _U_, quic_packet_info_t *quic_packet _U_, gboolean from_server _U_,
1759                      quic_cipher *cipher _U_, guint pkn_len _U_)
1760 {
1761     expert_add_info_format(pinfo, ti, &ei_quic_decryption_failed, "Libgcrypt >= 1.6.0 is required for QUIC decryption");
1762 }
1763 #endif /* !HAVE_LIBGCRYPT_AEAD */
1764
1765 static void
1766 quic_add_connection_info(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, quic_info_data_t *conn)
1767 {
1768     proto_tree         *ctree;
1769     proto_item         *pi;
1770
1771     ctree = proto_tree_add_subtree(tree, tvb, 0, 0, ett_quic_connection_info, NULL, "QUIC Connection information");
1772     if (!conn) {
1773         expert_add_info(pinfo, ctree, &ei_quic_connection_unknown);
1774         return;
1775     }
1776
1777     pi = proto_tree_add_uint(ctree, hf_quic_connection_number, tvb, 0, 0, conn->number);
1778     PROTO_ITEM_SET_GENERATED(pi);
1779 #if 0
1780     proto_tree_add_debug_text(ctree, "Client CID: %s", cid_to_string(&conn->client_cids.data));
1781     proto_tree_add_debug_text(ctree, "Server CID: %s", cid_to_string(&conn->server_cids.data));
1782     proto_tree_add_debug_text(ctree, "InitialCID: %s", cid_to_string(&conn->client_dcid_initial));
1783 #endif
1784 }
1785
1786 /**
1787  * Dissects the common part after the first byte for packets using the Long
1788  * Header form.
1789  */
1790 static int
1791 dissect_quic_long_header_common(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree,
1792                                 guint offset, const quic_packet_info_t *quic_packet _U_,
1793                                 guint32 *version_out, quic_cid_t *dcid, quic_cid_t *scid)
1794 {
1795     guint32     version;
1796     guint32     dcil, scil;
1797
1798     version = tvb_get_ntohl(tvb, offset);
1799
1800     if (version_out) {
1801         *version_out = version;
1802     }
1803
1804     proto_tree_add_item(quic_tree, hf_quic_version, tvb, offset, 4, ENC_BIG_ENDIAN);
1805     offset += 4;
1806
1807     proto_tree_add_item_ret_uint(quic_tree, hf_quic_dcil, tvb, offset, 1, ENC_BIG_ENDIAN, &dcil);
1808     proto_tree_add_item_ret_uint(quic_tree, hf_quic_scil, tvb, offset, 1, ENC_BIG_ENDIAN, &scil);
1809     offset++;
1810
1811     if (dcil) {
1812         dcil += 3;
1813         proto_tree_add_item(quic_tree, hf_quic_dcid, tvb, offset, dcil, ENC_NA);
1814         // TODO expert info on CID mismatch with connection
1815         tvb_memcpy(tvb, dcid->cid, offset, dcil);
1816         dcid->len = dcil;
1817         offset += dcil;
1818     }
1819
1820     if (scil) {
1821         scil += 3;
1822         proto_tree_add_item(quic_tree, hf_quic_scid, tvb, offset, scil, ENC_NA);
1823         // TODO expert info on CID mismatch with connection
1824         tvb_memcpy(tvb, scid->cid, offset, scil);
1825         scid->len = scil;
1826         offset += scil;
1827     }
1828
1829     if (dcid->len > 0) {
1830         col_append_fstr(pinfo->cinfo, COL_INFO, ", DCID=%s", cid_to_string(dcid));
1831     }
1832     if (scid->len > 0) {
1833         col_append_fstr(pinfo->cinfo, COL_INFO, ", SCID=%s", cid_to_string(scid));
1834     }
1835     return offset;
1836 }
1837
1838 /* Retry Packet dissection for draft -13 and newer. */
1839 static int
1840 dissect_quic_retry_packet(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree,
1841                           quic_datagram *dgram_info _U_, quic_packet_info_t *quic_packet)
1842 {
1843     guint       offset = 0;
1844     guint32     version;
1845     guint32     len_payload_length;
1846     guint64     payload_length;
1847     quic_cid_t  dcid = {.len=0}, scid = {.len=0};
1848     guint32     odcil = 0;
1849     guint       retry_token_len;
1850
1851     proto_tree_add_item(quic_tree, hf_quic_long_packet_type, tvb, offset, 1, ENC_NA);
1852     offset += 1;
1853     col_set_str(pinfo->cinfo, COL_INFO, "Retry");
1854
1855     offset = dissect_quic_long_header_common(tvb, pinfo, quic_tree, offset, quic_packet, &version, &dcid, &scid);
1856
1857     if (is_quic_draft_max(version, 13)) {
1858         proto_tree_add_item_ret_varint(quic_tree, hf_quic_length, tvb, offset, -1, ENC_VARINT_QUIC, &payload_length, &len_payload_length);
1859         offset += len_payload_length;
1860         // PKN is encrypted, but who cares about draft -13 anyway.
1861         proto_tree_add_item(quic_tree, hf_quic_packet_number, tvb, offset, 1, ENC_NA);
1862         offset += 1;
1863         proto_tree_add_item_ret_uint(quic_tree, hf_quic_odcil_draft13, tvb, offset, 1, ENC_NA, &odcil);
1864     } else {
1865         proto_tree_add_item_ret_uint(quic_tree, hf_quic_odcil, tvb, offset, 1, ENC_NA, &odcil);
1866         if (odcil) {
1867             odcil += 3;
1868         }
1869     }
1870     offset += 1;
1871     proto_tree_add_item(quic_tree, hf_quic_odcid, tvb, offset, odcil, ENC_NA);
1872     offset += odcil;
1873     retry_token_len = tvb_reported_length_remaining(tvb, offset);
1874     proto_tree_add_item(quic_tree, hf_quic_retry_token, tvb, offset, retry_token_len, ENC_NA);
1875     offset += retry_token_len;
1876
1877     return offset;
1878 }
1879
1880 static int
1881 dissect_quic_long_header(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree,
1882                          quic_datagram *dgram_info, quic_packet_info_t *quic_packet)
1883 {
1884     guint offset = 0;
1885     guint32 long_packet_type;
1886     guint32 version;
1887     quic_cid_t  dcid = {.len=0}, scid = {.len=0};
1888     guint32 len_token_length;
1889     guint64 token_length;
1890     guint32 len_payload_length;
1891     guint64 payload_length;
1892     guint32 pkn_len;
1893     guint64 pkn;
1894     quic_info_data_t *conn = dgram_info->conn;
1895     const gboolean from_server = dgram_info->from_server;
1896     quic_cipher *cipher = NULL;
1897     proto_item *ti;
1898
1899     proto_tree_add_item_ret_uint(quic_tree, hf_quic_long_packet_type, tvb, offset, 1, ENC_NA, &long_packet_type);
1900     offset += 1;
1901     col_set_str(pinfo->cinfo, COL_INFO, val_to_str_const(long_packet_type, quic_long_packet_type_vals, "Long Header"));
1902
1903     offset = dissect_quic_long_header_common(tvb, pinfo, quic_tree, offset, quic_packet, &version, &dcid, &scid);
1904
1905     if (conn->version == 0x51303434) { /* gQUIC Q044 */
1906         return dissect_gquic_ietf(tvb, pinfo, quic_tree, offset, conn->version);
1907     }
1908
1909     if (long_packet_type == QUIC_LPT_INITIAL) {
1910         proto_tree_add_item_ret_varint(quic_tree, hf_quic_token_length, tvb, offset, -1, ENC_VARINT_QUIC, &token_length, &len_token_length);
1911         offset += len_token_length;
1912
1913         if (token_length) {
1914             proto_tree_add_item(quic_tree, hf_quic_token, tvb, offset, (guint32)token_length, ENC_NA);
1915             offset += (guint)token_length;
1916         }
1917     }
1918
1919     proto_tree_add_item_ret_varint(quic_tree, hf_quic_length, tvb, offset, -1, ENC_VARINT_QUIC, &payload_length, &len_payload_length);
1920     offset += len_payload_length;
1921
1922 #ifdef HAVE_LIBGCRYPT_AEAD
1923     if (conn) {
1924         if (long_packet_type == QUIC_LPT_INITIAL) {
1925             cipher = !from_server ? &conn->client_initial_cipher : &conn->server_initial_cipher;
1926         } else if (long_packet_type == QUIC_LPT_HANDSHAKE) {
1927             cipher = !from_server ? &conn->client_handshake_cipher : &conn->server_handshake_cipher;
1928         }
1929     }
1930     /* Build handshake cipher now for PKN (and handshake) decryption. */
1931     if (!PINFO_FD_VISITED(pinfo) && conn) {
1932         const gchar *error = NULL;
1933         if (long_packet_type == QUIC_LPT_INITIAL && !from_server &&
1934             !memcmp(&dcid, &conn->client_dcid_initial, sizeof(quic_cid_t))) {
1935             /* Create new decryption context based on the Client Connection
1936              * ID from the *very first* Client Initial packet. */
1937             quic_create_initial_decoders(&dcid, &error, conn);
1938         } else if (long_packet_type == QUIC_LPT_HANDSHAKE) {
1939             if (!cipher->pn_cipher) {
1940                 quic_create_decoders(pinfo, version, conn, cipher, from_server, TLS_SECRET_HANDSHAKE, &error);
1941             }
1942         }
1943         if (error) {
1944             quic_packet->decryption.error = wmem_strdup(wmem_file_scope(), error);
1945         }
1946     }
1947 #endif /* !HAVE_LIBGCRYPT_AEAD */
1948     if (quic_packet->decryption.error) {
1949         expert_add_info_format(pinfo, quic_tree, &ei_quic_decryption_failed,
1950                                "Failed to create decryption context: %s", quic_packet->decryption.error);
1951         return offset;
1952     }
1953
1954     pkn_len = dissect_quic_packet_number(tvb, pinfo, quic_tree, offset, conn, quic_packet, from_server,
1955                                          cipher, GCRY_CIPHER_AES128, &pkn);
1956     if (pkn_len == 0) {
1957         return offset;
1958     }
1959     offset += pkn_len;
1960     col_append_fstr(pinfo->cinfo, COL_INFO, ", PKN: %" G_GINT64_MODIFIER "u", pkn);
1961
1962     /* Payload */
1963     ti = proto_tree_add_item(quic_tree, hf_quic_payload, tvb, offset, -1, ENC_NA);
1964
1965     if (conn) {
1966         quic_process_payload(tvb, pinfo, quic_tree, ti, offset,
1967                              conn, quic_packet, from_server, cipher, pkn_len);
1968     }
1969     offset += tvb_reported_length_remaining(tvb, offset);
1970
1971     return offset;
1972 }
1973
1974 static int
1975 dissect_quic_short_header(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree,
1976                           quic_datagram *dgram_info, quic_packet_info_t *quic_packet)
1977 {
1978     guint offset = 0;
1979     quic_cid_t dcid = {.len=0};
1980     guint32 pkn_len;
1981     guint64 pkn;
1982     proto_item *ti;
1983     gboolean    key_phase = FALSE;
1984     quic_cipher *cipher = NULL;
1985     quic_info_data_t *conn = dgram_info->conn;
1986     const gboolean from_server = dgram_info->from_server;
1987
1988     proto_tree_add_item_ret_boolean(quic_tree, hf_quic_short_kp_flag, tvb, offset, 1, ENC_NA, &key_phase);
1989     proto_tree_add_item(quic_tree, hf_quic_short_reserved, tvb, offset, 1, ENC_NA);
1990     if (conn) {
1991        dcid.len = from_server ? conn->client_cids.data.len : conn->server_cids.data.len;
1992     }
1993     offset += 1;
1994
1995     col_clear(pinfo->cinfo, COL_INFO);
1996     col_append_fstr(pinfo->cinfo, COL_INFO, "Protected Payload (KP%u)", key_phase);
1997
1998     /* Connection ID */
1999     if (dcid.len > 0) {
2000         proto_tree_add_item(quic_tree, hf_quic_dcid, tvb, offset, dcid.len, ENC_NA);
2001         tvb_memcpy(tvb, dcid.cid, offset, dcid.len);
2002         offset += dcid.len;
2003         col_append_fstr(pinfo->cinfo, COL_INFO, ", DCID=%s", cid_to_string(&dcid));
2004     }
2005
2006 #ifdef HAVE_LIBGCRYPT_AEAD
2007     if (!PINFO_FD_VISITED(pinfo) && conn) {
2008         cipher = quic_get_pp_cipher(pinfo, key_phase, conn, from_server);
2009     }
2010 #endif /* !HAVE_LIBGCRYPT_AEAD */
2011     if (!conn || conn->skip_decryption) {
2012         return offset;
2013     }
2014
2015     /* Packet Number */
2016     pkn_len = dissect_quic_packet_number(tvb, pinfo, quic_tree, offset, conn, quic_packet, from_server,
2017                                          cipher, conn ? conn->cipher_algo : 0, &pkn);
2018     if (pkn_len == 0) {
2019         return offset;
2020     }
2021     offset += pkn_len;
2022
2023     col_append_fstr(pinfo->cinfo, COL_INFO, ", PKN: %" G_GINT64_MODIFIER "u", pkn);
2024
2025     /* Protected Payload */
2026     ti = proto_tree_add_item(quic_tree, hf_quic_protected_payload, tvb, offset, -1, ENC_NA);
2027
2028     if (conn) {
2029         quic_process_payload(tvb, pinfo, quic_tree, ti, offset,
2030                              conn, quic_packet, from_server, cipher, pkn_len);
2031     }
2032     offset += tvb_reported_length_remaining(tvb, offset);
2033
2034     return offset;
2035 }
2036
2037 static int
2038 dissect_quic_version_negotiation(tvbuff_t *tvb, packet_info *pinfo, proto_tree *quic_tree, const quic_packet_info_t *quic_packet)
2039 {
2040     guint       offset = 0;
2041     quic_cid_t  dcid = {.len=0}, scid = {.len=0};
2042     guint32 supported_version;
2043     proto_item *ti;
2044
2045     col_set_str(pinfo->cinfo, COL_INFO, "Version Negotiation");
2046
2047     proto_tree_add_item(quic_tree, hf_quic_vn_unused, tvb, offset, 1, ENC_NA);
2048     offset += 1;
2049
2050     offset = dissect_quic_long_header_common(tvb, pinfo, quic_tree, offset, quic_packet, NULL, &dcid, &scid);
2051
2052     /* Supported Version */
2053     while(tvb_reported_length_remaining(tvb, offset) > 0){
2054         ti = proto_tree_add_item_ret_uint(quic_tree, hf_quic_supported_version, tvb, offset, 4, ENC_BIG_ENDIAN, &supported_version);
2055         if ((supported_version & 0x0F0F0F0F) == 0x0a0a0a0a) {
2056             proto_item_append_text(ti, " (GREASE)");
2057         }
2058         offset += 4;
2059     }
2060
2061     return offset;
2062 }
2063
2064 static tvbuff_t *
2065 quic_get_message_tvb(tvbuff_t *tvb, const guint offset)
2066 {
2067     guint64 token_length;
2068     guint64 payload_length;
2069     guint8 packet_type = tvb_get_guint8(tvb, offset);
2070     guint8 long_packet_type = packet_type & 0x7f;
2071     // Retry and VN packets cannot be coalesced (clarified in draft -14).
2072     if ((packet_type & 0x80) && long_packet_type != QUIC_LPT_RETRY) {
2073         // long header form, check version
2074         guint version = tvb_get_ntohl(tvb, offset + 1);
2075         // If this is not a VN packet but a valid long form, extract a subset.
2076         // TODO check for valid QUIC versions as future versions might change the format.
2077         if (version != 0 && !is_gquic_version(version)) {
2078             guint8 cid_lengths = tvb_get_guint8(tvb, offset + 5);
2079             guint8 dcil = cid_lengths >> 4;
2080             guint8 scil = cid_lengths & 0xf;
2081             guint length = 6;
2082             if (dcil) {
2083                 length += 3 + dcil;
2084             }
2085             if (scil) {
2086                 length += 3 + scil;
2087             }
2088             if (long_packet_type == QUIC_LPT_INITIAL) {
2089                 length += tvb_get_varint(tvb, offset + length, 8, &token_length, ENC_VARINT_QUIC);
2090                 length += (guint)token_length;
2091             }
2092             length += tvb_get_varint(tvb, offset + length, 8, &payload_length, ENC_VARINT_QUIC);
2093             length += (guint)payload_length;
2094             if (payload_length <= G_MAXINT32 && length < (guint)tvb_reported_length_remaining(tvb, offset)) {
2095                 return tvb_new_subset_length(tvb, offset, length);
2096             }
2097         }
2098     }
2099
2100     // short header form, VN or unknown message, return remaining data.
2101     return tvb_new_subset_remaining(tvb, offset);
2102 }
2103
2104 /**
2105  * Extracts necessary information from header to find any existing connection.
2106  * "long_packet_type" is set to QUIC_SHORT_PACKET for short header packets.
2107  * DCID and SCID are not modified unless available. For short header packets,
2108  * DCID length is unknown, so the caller should truncate it as needed.
2109  */
2110 static void
2111 quic_extract_header(tvbuff_t *tvb, guint8 *long_packet_type, guint32 *version,
2112                     quic_cid_t *dcid, quic_cid_t *scid)
2113 {
2114     guint offset = 0;
2115
2116     guint8 packet_type = tvb_get_guint8(tvb, offset);
2117     gboolean is_long_header = packet_type & 0x80;
2118     if (is_long_header) {
2119         // long header form
2120         *long_packet_type = packet_type & 0x7f;
2121     } else {
2122         // short header form, store dummy value that is not a long packet type.
2123         *long_packet_type = QUIC_SHORT_PACKET;
2124     }
2125     offset++;
2126
2127     *version = tvb_get_ntohl(tvb, offset);
2128
2129     if (is_long_header) {
2130         // skip version
2131         offset += 4;
2132
2133         // read DCIL/SCIL (Connection ID Lengths).
2134         guint8 cid_lengths = tvb_get_guint8(tvb, offset);
2135         guint8 dcil = cid_lengths >> 4;
2136         guint8 scil = cid_lengths & 0xf;
2137         offset++;
2138
2139         if (dcil) {
2140             dcil += 3;
2141             tvb_memcpy(tvb, dcid->cid, offset, dcil);
2142             dcid->len = dcil;
2143             offset += dcil;
2144         }
2145
2146         if (scil) {
2147             scil += 3;
2148             tvb_memcpy(tvb, scid->cid, offset, scil);
2149             scid->len = scil;
2150         }
2151     } else {
2152         // Definitely not draft -10, set version to dummy value.
2153         *version = 0;
2154         // For short headers, the DCID length is unknown and could be 0 or
2155         // anything from 4 to 18 bytes. Copy the maximum possible and let the
2156         // consumer truncate it as necessary.
2157         tvb_memcpy(tvb, dcid->cid, offset, 18);
2158         dcid->len = 18;
2159     }
2160 }
2161
2162 static int
2163 dissect_quic(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
2164         void *data _U_)
2165 {
2166     proto_item *ti;
2167     proto_tree *quic_tree;
2168     guint       offset = 0;
2169     guint32     header_form;
2170     quic_datagram *dgram_info = NULL;
2171     quic_packet_info_t *quic_packet = NULL;
2172
2173     col_set_str(pinfo->cinfo, COL_PROTOCOL, "QUIC");
2174
2175     if (PINFO_FD_VISITED(pinfo)) {
2176         dgram_info = (quic_datagram *)p_get_proto_data(wmem_file_scope(), pinfo, proto_quic, 0);
2177     }
2178     if (!dgram_info) {
2179         dgram_info = wmem_new0(wmem_file_scope(), quic_datagram);
2180         p_add_proto_data(wmem_file_scope(), pinfo, proto_quic, 0, dgram_info);
2181     }
2182
2183     ti = proto_tree_add_item(tree, proto_quic, tvb, 0, -1, ENC_NA);
2184
2185     quic_tree = proto_item_add_subtree(ti, ett_quic);
2186
2187     if (!PINFO_FD_VISITED(pinfo)) {
2188         guint8      long_packet_type;
2189         guint32     version;
2190         quic_cid_t  dcid = {.len=0}, scid = {.len=0};
2191         gboolean    from_server = FALSE;
2192         quic_info_data_t *conn;
2193
2194         quic_extract_header(tvb, &long_packet_type, &version, &dcid, &scid);
2195         conn = quic_connection_find(pinfo, long_packet_type, &dcid, &from_server);
2196         quic_connection_create_or_update(&conn, pinfo, long_packet_type, version, &scid, &dcid, from_server);
2197         dgram_info->conn = conn;
2198         dgram_info->from_server = from_server;
2199 #if 0
2200         proto_tree_add_debug_text(quic_tree, "Connection: %d %p DCID=%s SCID=%s from_server:%d", pinfo->num, dgram_info->conn, cid_to_string(&dcid), cid_to_string(&scid), dgram_info->from_server);
2201     } else {
2202         proto_tree_add_debug_text(quic_tree, "Connection: %d %p from_server:%d", pinfo->num, dgram_info->conn, dgram_info->from_server);
2203 #endif
2204     }
2205
2206     quic_add_connection_info(tvb, pinfo, quic_tree, dgram_info->conn);
2207
2208     do {
2209         if (!quic_packet) {
2210             quic_packet = &dgram_info->first_packet;
2211         } else if (!PINFO_FD_VISITED(pinfo)) {
2212             quic_packet->next = wmem_new0(wmem_file_scope(), quic_packet_info_t);
2213             quic_packet = quic_packet->next;
2214         } else {
2215             quic_packet = quic_packet->next;
2216             DISSECTOR_ASSERT(quic_packet);
2217         }
2218
2219         tvbuff_t *next_tvb = quic_get_message_tvb(tvb, offset);
2220         proto_tree_add_item_ret_uint(quic_tree, hf_quic_header_form, next_tvb, 0, 1, ENC_NA, &header_form);
2221         guint new_offset = 0;
2222         if (header_form) {
2223             guint8 long_packet_type = tvb_get_guint8(next_tvb, 0) & 0x7f;
2224             guint32 version = tvb_get_ntohl(next_tvb, 1);
2225             if (version == 0) {
2226                 offset += dissect_quic_version_negotiation(next_tvb, pinfo, quic_tree, quic_packet);
2227                 break;
2228             }
2229             if (long_packet_type == QUIC_LPT_RETRY) {
2230                 new_offset = dissect_quic_retry_packet(next_tvb, pinfo, quic_tree, dgram_info, quic_packet);
2231             } else {
2232                 new_offset = dissect_quic_long_header(next_tvb, pinfo, quic_tree, dgram_info, quic_packet);
2233             }
2234         } else {
2235             new_offset = dissect_quic_short_header(next_tvb, pinfo, quic_tree, dgram_info, quic_packet);
2236         }
2237         if (tvb_reported_length_remaining(next_tvb, new_offset)) {
2238             // should usually not be present unless decryption is not possible.
2239             proto_tree_add_item(quic_tree, hf_quic_remaining_payload, next_tvb, new_offset, -1, ENC_NA);
2240         }
2241         offset += tvb_reported_length(next_tvb);
2242     } while (tvb_reported_length_remaining(tvb, offset));
2243
2244     return offset;
2245 }
2246
2247 static gboolean
2248 dissect_quic_short_header_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
2249 {
2250     // If this capture does not contain QUIC, skip the more expensive checks.
2251     if (quic_cid_lengths == 0) {
2252         return FALSE;
2253     }
2254
2255     // Is this a SH packet after connection migration? SH (draft -14):
2256     // Flag (1) + DCID (4-18) + PKN (1/2/4) + encrypted payload (>= 16).
2257     if (tvb_captured_length(tvb) < 1 + 4 + 1 + 16) {
2258         return FALSE;
2259     }
2260
2261     // DCID length is unknown, so extract the maximum and look for a match.
2262     quic_cid_t dcid = {.len=18};
2263     tvb_memcpy(tvb, dcid.cid, 1, 18);
2264     gboolean from_server;
2265     if (!quic_connection_find(pinfo, QUIC_SHORT_PACKET, &dcid, &from_server)) {
2266         return FALSE;
2267     }
2268
2269     conversation_t *conversation = find_or_create_conversation(pinfo);
2270     conversation_set_dissector(conversation, quic_handle);
2271     dissect_quic(tvb, pinfo, tree, NULL);
2272     return TRUE;
2273 }
2274
2275 static gboolean dissect_quic_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
2276 {
2277     /*
2278      * Since draft -12:
2279      * Flag (1 byte) + Version (4 bytes) + DCIL/SCIL (1 byte) +
2280      * Destination Connection ID (0/4..18 based on DCIL) +
2281      * Source Connection ID (0/4..18 based on SCIL) +
2282      * Payload length (1/2/4/8) + Packet number (1/2/4 bytes) + Payload.
2283      * (absolute minimum: 8 + payload)
2284      * (for Version Negotiation, payload len + PKN + payload is replaced by
2285      * Supported Version (multiple of 4 bytes.)
2286      */
2287     conversation_t *conversation = NULL;
2288     int offset = 0;
2289     guint8 flags;
2290     guint32 version;
2291     gboolean is_quic = FALSE;
2292
2293     /* Verify packet size  (Flag (1 byte) + Connection ID (8 bytes) + Version (4 bytes)) */
2294     if (tvb_captured_length(tvb) < 13)
2295     {
2296         return FALSE;
2297     }
2298
2299     flags = tvb_get_guint8(tvb, offset);
2300     /* Check if long Packet is set */
2301     if((flags & 0x80) == 0) {
2302         // Perhaps this is a short header, check it.
2303         return dissect_quic_short_header_heur(tvb, pinfo, tree);
2304     }
2305     offset += 1;
2306
2307     // check for draft QUIC version (for draft -11 and newer) or check for gQUIC version (= Q044)
2308     version = tvb_get_ntohl(tvb, offset);
2309     is_quic = (quic_draft_version(version) >= 11) || is_gquic_version(version);
2310
2311     if (is_quic) {
2312         conversation = find_or_create_conversation(pinfo);
2313         conversation_set_dissector(conversation, quic_handle);
2314         dissect_quic(tvb, pinfo, tree, data);
2315     }
2316     return is_quic;
2317 }
2318
2319
2320 /** Initialize QUIC dissection state for a new capture file. */
2321 static void
2322 quic_init(void)
2323 {
2324     quic_connections = wmem_list_new(wmem_file_scope());
2325     quic_connections_count = 0;
2326     quic_initial_connections = wmem_map_new(wmem_file_scope(), quic_connection_hash, quic_connection_equal);
2327     quic_client_connections = wmem_map_new(wmem_file_scope(), quic_connection_hash, quic_connection_equal);
2328     quic_server_connections = wmem_map_new(wmem_file_scope(), quic_connection_hash, quic_connection_equal);
2329     quic_cid_lengths = 0;
2330 }
2331
2332 /** Release QUIC dissection state on closing a capture file. */
2333 static void
2334 quic_cleanup(void)
2335 {
2336     wmem_list_foreach(quic_connections, quic_connection_destroy, NULL);
2337     quic_initial_connections = NULL;
2338     quic_client_connections = NULL;
2339     quic_server_connections = NULL;
2340 }
2341
2342 void
2343 proto_register_quic(void)
2344 {
2345     expert_module_t *expert_quic;
2346
2347     static hf_register_info hf[] = {
2348         { &hf_quic_connection_number,
2349           { "Connection Number", "quic.connection.number",
2350             FT_UINT32, BASE_DEC, NULL, 0x0,
2351             "Connection identifier within this capture file", HFILL }
2352         },
2353
2354         { &hf_quic_header_form,
2355           { "Header Form", "quic.header_form",
2356             FT_UINT8, BASE_DEC, VALS(quic_short_long_header_vals), 0x80,
2357             "The most significant bit (0x80) of the first octet is set to 1 for long headers and 0 for short headers.", HFILL }
2358         },
2359
2360         { &hf_quic_long_packet_type,
2361           { "Packet Type", "quic.long.packet_type",
2362             FT_UINT8, BASE_DEC, VALS(quic_long_packet_type_vals), 0x7F,
2363             "Long Header Packet Type", HFILL }
2364         },
2365         { &hf_quic_dcid,
2366           { "Destination Connection ID", "quic.dcid",
2367             FT_BYTES, BASE_NONE, NULL, 0x0,
2368             NULL, HFILL }
2369         },
2370         { &hf_quic_scid,
2371           { "Source Connection ID", "quic.scid",
2372             FT_BYTES, BASE_NONE, NULL, 0x0,
2373             NULL, HFILL }
2374         },
2375         { &hf_quic_dcil,
2376           { "Destination Connection ID Length", "quic.dcil",
2377             FT_UINT8, BASE_DEC, VALS(quic_cid_len_vals), 0xf0,
2378             "Destination Connection ID Length (for non-zero lengths, add 3 for actual length)", HFILL }
2379         },
2380         { &hf_quic_scil,
2381           { "Source Connection ID Length", "quic.scil",
2382             FT_UINT8, BASE_DEC, VALS(quic_cid_len_vals), 0x0f,
2383             "Source Connection ID Length (for non-zero lengths, add 3 for actual length)", HFILL }
2384         },
2385         { &hf_quic_token_length,
2386           { "Token Length", "quic.token_length",
2387             FT_UINT64, BASE_DEC, NULL, 0x0,
2388             NULL, HFILL }
2389         },
2390         { &hf_quic_token,
2391           { "Token", "quic.token",
2392             FT_BYTES, BASE_NONE, NULL, 0x0,
2393             NULL, HFILL }
2394         },
2395         { &hf_quic_length,
2396           { "Length", "quic.length",
2397             FT_UINT64, BASE_DEC, NULL, 0x0,
2398             "Length of Packet Number and Payload fields", HFILL }
2399         },
2400
2401         { &hf_quic_packet_number,
2402           { "Packet Number", "quic.packet_number",
2403             FT_UINT64, BASE_DEC, NULL, 0x0,
2404             NULL, HFILL }
2405         },
2406         { &hf_quic_packet_number_full,
2407           { "Packet Number (full)", "quic.packet_number_full",
2408             FT_UINT64, BASE_DEC, NULL, 0x0,
2409             "Full packet number", HFILL }
2410         },
2411         { &hf_quic_version,
2412           { "Version", "quic.version",
2413             FT_UINT32, BASE_HEX, VALS(quic_version_vals), 0x0,
2414             NULL, HFILL }
2415         },
2416         { &hf_quic_supported_version,
2417           { "Supported Version", "quic.supported_version",
2418             FT_UINT32, BASE_HEX, VALS(quic_version_vals), 0x0,
2419             NULL, HFILL }
2420         },
2421         { &hf_quic_vn_unused, /* <= draft-07 */
2422           { "Unused", "quic.vn.unused",
2423             FT_UINT8, BASE_HEX, NULL, 0x7F,
2424             NULL, HFILL }
2425         },
2426         { &hf_quic_short_kp_flag,
2427           { "Key Phase Bit", "quic.short.kp_flag",
2428             FT_BOOLEAN, 8, NULL, SH_KP,
2429             NULL, HFILL }
2430         },
2431         { &hf_quic_short_reserved,
2432           { "Reserved", "quic.short.reserved",
2433             FT_UINT8, BASE_DEC, NULL, 0x07,
2434             "Reserved bits for experimentation", HFILL }
2435         },
2436
2437         { &hf_quic_payload,
2438           { "Payload", "quic.payload",
2439             FT_BYTES, BASE_NONE, NULL, 0x0,
2440             "(Encrypted) payload of a packet", HFILL }
2441         },
2442         { &hf_quic_protected_payload,
2443           { "Protected Payload", "quic.protected_payload",
2444             FT_BYTES, BASE_NONE, NULL, 0x0,
2445             "1-RTT protected payload", HFILL }
2446         },
2447         { &hf_quic_remaining_payload,
2448           { "Remaining Payload", "quic.remaining_payload",
2449             FT_BYTES, BASE_NONE, NULL, 0x0,
2450             "Remaining payload in a packet (possibly PKN followed by encrypted payload)", HFILL }
2451         },
2452
2453         { &hf_quic_odcil_draft13,
2454           { "Original Destination Connection ID Length", "quic.odcil_draft13",
2455             FT_UINT8, BASE_DEC, NULL, 0x0,
2456             NULL, HFILL }
2457         },
2458         { &hf_quic_odcil,
2459           { "Original Destination Connection ID Length", "quic.odcil",
2460             FT_UINT8, BASE_DEC, VALS(quic_cid_len_vals), 0x0f,
2461             NULL, HFILL }
2462         },
2463         { &hf_quic_odcid,
2464           { "Original Destination Connection ID", "quic.odcid",
2465             FT_BYTES, BASE_NONE, NULL, 0x0,
2466             NULL, HFILL }
2467         },
2468         { &hf_quic_retry_token,
2469           { "Retry Token", "quic.retry_token",
2470             FT_BYTES, BASE_NONE, NULL, 0x0,
2471             NULL, HFILL }
2472         },
2473
2474         { &hf_quic_frame,
2475           { "Frame", "quic.frame",
2476             FT_NONE, BASE_NONE, NULL, 0x0,
2477             NULL, HFILL }
2478         },
2479         { &hf_quic_frame_type,
2480           { "Frame Type", "quic.frame_type",
2481             FT_UINT8, BASE_RANGE_STRING | BASE_HEX, RVALS(quic_frame_type_vals), 0x0,
2482             NULL, HFILL }
2483         },
2484
2485         /* >= draft-08*/
2486         { &hf_quic_frame_type_stream_fin,
2487           { "Fin", "quic.frame_type.stream.fin",
2488             FT_BOOLEAN, 8, NULL, FTFLAGS_STREAM_FIN,
2489             NULL, HFILL }
2490         },
2491         { &hf_quic_frame_type_stream_len,
2492           { "Len(gth)", "quic.frame_type.stream.len",
2493             FT_BOOLEAN, 8, NULL, FTFLAGS_STREAM_LEN,
2494             NULL, HFILL }
2495         },
2496         { &hf_quic_frame_type_stream_off,
2497           { "Off(set)", "quic.frame_type.stream.off",
2498             FT_BOOLEAN, 8, NULL, FTFLAGS_STREAM_OFF,
2499             NULL, HFILL }
2500         },
2501
2502         { &hf_quic_stream_stream_id,
2503           { "Stream ID", "quic.stream.stream_id",
2504             FT_UINT64, BASE_DEC, NULL, 0x0,
2505             NULL, HFILL }
2506         },
2507         { &hf_quic_stream_offset,
2508           { "Offset", "quic.stream.offset",
2509             FT_UINT64, BASE_DEC, NULL, 0x0,
2510             NULL, HFILL }
2511         },
2512         { &hf_quic_stream_length,
2513           { "Length", "quic.stream.length",
2514             FT_UINT64, BASE_DEC, NULL, 0x0,
2515             NULL, HFILL }
2516         },
2517         { &hf_quic_stream_data,
2518           { "Stream Data", "quic.stream_data",
2519             FT_BYTES, BASE_NONE, NULL, 0x0,
2520             NULL, HFILL }
2521         },
2522
2523         { &hf_quic_frame_type_ack_largest_acknowledged,
2524           { "Largest Acknowledged", "quic.frame_type.ack.largest_acknowledged",
2525             FT_UINT64, BASE_DEC, NULL, 0x0,
2526             "Representing the largest packet number the peer is acknowledging in this packet", HFILL }
2527         },
2528         { &hf_quic_frame_type_ack_ack_delay,
2529           { "ACK Delay", "quic.frame_type.ack.ack_delay",
2530             FT_UINT64, BASE_DEC, NULL, 0x0,
2531             "The time from when the largest acknowledged packet, as indicated in the Largest Acknowledged field, was received by this peer to when this ACK was sent", HFILL }
2532         },
2533         { &hf_quic_frame_type_ack_ack_block_count,
2534           { "ACK Block Count", "quic.frame_type.ack.ack_block_count",
2535             FT_UINT64, BASE_DEC, NULL, 0x0,
2536             "The number of Additional ACK Block (and Gap) fields after the First ACK Block", HFILL }
2537         },
2538         { &hf_quic_frame_type_ack_fab,
2539           { "First ACK Block", "quic.frame_type.ack.fab",
2540             FT_UINT64, BASE_DEC, NULL, 0x0,
2541             "Indicates the number of contiguous additional packets being acknowledged starting at the Largest Acknowledged", HFILL }
2542         },
2543         { &hf_quic_frame_type_ack_gap,
2544           { "Gap", "quic.frame_type.ack.gap",
2545             FT_UINT64, BASE_DEC, NULL, 0x0,
2546             "Indicating the number of contiguous unacknowledged packets preceding the packet number one lower than the smallest in the preceding ACK Block", HFILL }
2547         },
2548         { &hf_quic_frame_type_ack_ack_block,
2549           { "ACK Block", "quic.frame_type.ack.ack_block",
2550             FT_UINT64, BASE_DEC, NULL, 0x0,
2551             "Indicating the number of contiguous acknowledged packets preceding the largest packet number, as determined by the preceding Gap", HFILL }
2552         },
2553         /* PATH_CHALLENGE */
2554         { &hf_quic_frame_type_path_challenge_data,
2555           { "Data", "quic.frame_type.path_challenge.data",
2556             FT_BYTES, BASE_NONE, NULL, 0x0,
2557             "Arbitrary data that must be matched by a PATH_RESPONSE frame", HFILL }
2558         },
2559         /* PATH_RESPONSE */
2560         { &hf_quic_frame_type_path_response_data,
2561           { "Data", "quic.frame_type.path_response.data",
2562             FT_BYTES, BASE_NONE, NULL, 0x0,
2563             "Arbitrary data that must match a PATH_CHALLENGE frame", HFILL }
2564         },
2565         /* PADDING */
2566         { &hf_quic_frame_type_padding_length,
2567           { "Padding Length", "quic.frame_type.padding_length",
2568             FT_UINT32, BASE_DEC, NULL, 0x0,
2569             NULL, HFILL }
2570         },
2571         /* RST_STREAM */
2572         { &hf_quic_frame_type_rsts_stream_id,
2573             { "Stream ID", "quic.frame_type.rsts.stream_id",
2574               FT_UINT64, BASE_DEC, NULL, 0x0,
2575               "Stream ID of the stream being terminated", HFILL }
2576         },
2577         { &hf_quic_frame_type_rsts_application_error_code,
2578             { "Application Error code", "quic.frame_type.rsts.application_error_code",
2579               FT_UINT16, BASE_DEC, VALS(quic_application_error_code_vals), 0x0,
2580               "Indicates why the stream is being closed", HFILL }
2581         },
2582         { &hf_quic_frame_type_rsts_final_offset,
2583             { "Final offset", "quic.frame_type.rsts.byte_offset",
2584               FT_UINT64, BASE_DEC, NULL, 0x0,
2585               "Indicating the absolute byte offset of the end of data written on this stream", HFILL }
2586         },
2587         /* CONNECTION_CLOSE */
2588         { &hf_quic_frame_type_cc_error_code,
2589             { "Error code", "quic.frame_type.cc.error_code",
2590               FT_UINT16, BASE_DEC|BASE_RANGE_STRING, RVALS(quic_transport_error_code_vals), 0x0,
2591               "Indicates the reason for closing this connection", HFILL }
2592         },
2593         { &hf_quic_frame_type_cc_error_code_tls_alert,
2594             { "TLS Alert Description", "quic.frame_type.cc.error_code.tls_alert",
2595               FT_UINT8, BASE_DEC, VALS(ssl_31_alert_description), 0x0,
2596               NULL, HFILL }
2597         },
2598         { &hf_quic_frame_type_cc_frame_type,
2599             { "Frame Type", "quic.frame_type.cc.frame_type",
2600               FT_UINT64, BASE_DEC, NULL, 0x0,
2601               "The type of frame that triggered the error", HFILL }
2602         },
2603         { &hf_quic_frame_type_cc_reason_phrase_length,
2604             { "Reason phrase Length", "quic.frame_type.cc.reason_phrase.length",
2605               FT_UINT64, BASE_DEC, NULL, 0x0,
2606               "Specifying the length of the reason phrase", HFILL }
2607         },
2608         { &hf_quic_frame_type_cc_reason_phrase,
2609             { "Reason phrase", "quic.frame_type.cc.reason_phrase",
2610               FT_STRING, BASE_NONE, NULL, 0x0,
2611               "A human-readable explanation for why the connection was closed", HFILL }
2612         },
2613         /* APPLICATION_CLOSE */
2614         { &hf_quic_frame_type_ac_error_code,
2615             { "Application Error code", "quic.frame_type.ac.error_code",
2616               FT_UINT16, BASE_DEC, VALS(quic_application_error_code_vals), 0x0,
2617               "Indicates the reason for closing this application", HFILL }
2618         },
2619         { &hf_quic_frame_type_ac_reason_phrase_length,
2620             { "Reason phrase Length", "quic.frame_type.ac.reason_phrase.length",
2621               FT_UINT64, BASE_DEC, NULL, 0x0,
2622               "Specifying the length of the reason phrase", HFILL }
2623         },
2624         { &hf_quic_frame_type_ac_reason_phrase,
2625             { "Reason phrase", "quic.frame_type.ac.reason_phrase",
2626               FT_STRING, BASE_NONE, NULL, 0x0,
2627               "A human-readable explanation for why the application was closed", HFILL }
2628         },
2629         /* MAX_DATA */
2630         { &hf_quic_frame_type_md_maximum_data,
2631             { "Maximum Data", "quic.frame_type.md.maximum_data",
2632               FT_UINT64, BASE_DEC, NULL, 0x0,
2633               "Indicating the maximum amount of data that can be sent on the entire connection, in units of 1024 octets", HFILL }
2634         },
2635         /* MAX_STREAM_DATA */
2636         { &hf_quic_frame_type_msd_stream_id,
2637             { "Stream ID", "quic.frame_type.msd.stream_id",
2638               FT_UINT64, BASE_DEC, NULL, 0x0,
2639               "The stream ID of the stream that is affected", HFILL }
2640         },
2641         { &hf_quic_frame_type_msd_maximum_stream_data,
2642             { "Maximum Stream Data", "quic.frame_type.msd.maximum_stream_data",
2643               FT_UINT64, BASE_DEC, NULL, 0x0,
2644               "Indicating the maximum amount of data that can be sent on the identified stream, in units of octets", HFILL }
2645         },
2646         /* MAX_STREAM_ID */
2647         { &hf_quic_frame_type_msi_stream_id,
2648             { "Stream ID", "quic.frame_type.msi.stream_id",
2649               FT_UINT64, BASE_DEC, NULL, 0x0,
2650               "ID of the maximum peer-initiated stream ID for the connection", HFILL }
2651         },
2652         /* BLOCKED */
2653         { &hf_quic_frame_type_blocked_offset,
2654             { "Offset", "quic.frame_type.sb.offset",
2655               FT_UINT64, BASE_DEC, NULL, 0x0,
2656               "Indicating the connection-level offset at which the blocking occurred", HFILL }
2657         },
2658         /* STREAM_BLOCKED */
2659         { &hf_quic_frame_type_sb_stream_id,
2660             { "Stream ID", "quic.frame_type.sb.stream_id",
2661               FT_UINT64, BASE_DEC, NULL, 0x0,
2662               "Indicating the stream which is flow control blocked", HFILL }
2663         },
2664         { &hf_quic_frame_type_sb_offset,
2665             { "Offset", "quic.frame_type.sb.offset",
2666               FT_UINT64, BASE_DEC, NULL, 0x0,
2667               "Indicating the offset of the stream at which the blocking occurred", HFILL }
2668         },
2669         /* STREAM_ID_BLOCKED */
2670         { &hf_quic_frame_type_sib_stream_id,
2671             { "Stream ID", "quic.frame_type.sib.stream_id",
2672               FT_UINT64, BASE_DEC, NULL, 0x0,
2673               "Indicating the highest stream ID that the sender was permitted to open", HFILL }
2674         },
2675         /* NEW_CONNECTION_ID */
2676         { &hf_quic_frame_type_nci_sequence,
2677             { "Sequence", "quic.frame_type.nci.sequence",
2678               FT_UINT64, BASE_DEC, NULL, 0x0,
2679               "Increases by 1 for each connection ID that is provided by the server", HFILL }
2680         },
2681         { &hf_quic_frame_type_nci_connection_id_length,
2682             { "Connection ID Length", "quic.frame_type.nci.connection_id.length",
2683               FT_UINT8, BASE_DEC, NULL, 0x0,
2684               NULL, HFILL }
2685         },
2686         { &hf_quic_frame_type_nci_connection_id,
2687             { "Connection ID", "quic.frame_type.nci.connection_id",
2688               FT_BYTES, BASE_NONE, NULL, 0x0,
2689               NULL, HFILL }
2690         },
2691         { &hf_quic_frame_type_nci_stateless_reset_token,
2692             { "Stateless Reset Token", "quic.frame_type.stateless_reset_token",
2693               FT_BYTES, BASE_NONE, NULL, 0x0,
2694               NULL, HFILL }
2695         },
2696         /* STOP_SENDING */
2697         { &hf_quic_frame_type_ss_stream_id,
2698             { "Stream ID", "quic.frame_type.ss.stream_id",
2699               FT_UINT64, BASE_DEC, NULL, 0x0,
2700               "Stream ID of the stream being ignored", HFILL }
2701         },
2702         { &hf_quic_frame_type_ss_application_error_code,
2703             { "Application Error code", "quic.frame_type.ss.application_error_code",
2704               FT_UINT16, BASE_DEC, NULL, 0x0,
2705               "Indicates why the sender is ignoring the stream", HFILL }
2706         },
2707
2708         /* CRYPTO */
2709         { &hf_quic_frame_type_crypto_offset,
2710             { "Offset", "quic.frame_type.crypto.offset",
2711               FT_UINT64, BASE_DEC, NULL, 0x0,
2712               "Byte offset into the stream", HFILL }
2713         },
2714         { &hf_quic_frame_type_crypto_length,
2715             { "Length", "quic.frame_type.crypto.length",
2716               FT_UINT64, BASE_DEC, NULL, 0x0,
2717               "Length of the Crypto Data field", HFILL }
2718         },
2719         { &hf_quic_frame_type_crypto_crypto_data,
2720             { "Crypto Data", "quic.frame_type.crypto.crypto_data",
2721               FT_NONE, BASE_NONE, NULL, 0x0,
2722               "The cryptographic message data", HFILL }
2723         },
2724
2725         /* NEW_TOKEN */
2726         { &hf_quic_frame_type_nt_length,
2727             { "(Token) Length", "quic.frame_type.nt.length",
2728               FT_UINT64, BASE_DEC, NULL, 0x0,
2729               "Specifying the length of the token", HFILL }
2730         },
2731         { &hf_quic_frame_type_nt_token,
2732             { "Token", "quic.frame_type.nt.token",
2733               FT_BYTES, BASE_NONE, NULL, 0x0,
2734               "An opaque blob that the client may use with a future Initial packet", HFILL }
2735         },
2736
2737         /* ACK_ECN */
2738         { &hf_quic_frame_type_ae_largest_acknowledged,
2739           { "Largest Acknowledged", "quic.frame_type.ae.largest_acknowledged",
2740             FT_UINT64, BASE_DEC, NULL, 0x0,
2741             "Representing the largest packet number the peer is acknowledging in this packet", HFILL }
2742         },
2743         { &hf_quic_frame_type_ae_ack_delay,
2744           { "ACK Delay", "quic.frame_type.ae.ack_delay",
2745             FT_UINT64, BASE_DEC, NULL, 0x0,
2746             "The time from when the largest acknowledged packet, as indicated in the Largest Acknowledged field, was received by this peer to when this ACK was sent", HFILL }
2747         },
2748         { &hf_quic_frame_type_ae_ect0_count,
2749           { "ECT(0) Count", "quic.frame_type.ae.ect0_count",
2750             FT_UINT64, BASE_DEC, NULL, 0x0,
2751             "Representing the total number packets received with the ECT(0) codepoint", HFILL }
2752         },
2753         { &hf_quic_frame_type_ae_ect1_count,
2754           { "ECT(1) Count", "quic.frame_type.ae.ect1_count",
2755             FT_UINT64, BASE_DEC, NULL, 0x0,
2756             "Representing the total number packets received with the ECT(1) codepoint", HFILL }
2757         },
2758         { &hf_quic_frame_type_ae_ecn_ce_count,
2759           { "CE Count", "quic.frame_type.ae.ecn_ce_count",
2760             FT_UINT64, BASE_DEC, NULL, 0x0,
2761             "Representing the total number packets received with the CE codepoint", HFILL }
2762         },
2763         { &hf_quic_frame_type_ae_ack_block_count,
2764           { "ACK Block Count", "quic.frame_type.ae.ack_block_count",
2765             FT_UINT64, BASE_DEC, NULL, 0x0,
2766             "The number of Additional ACK Block (and Gap) fields after the First ACK Block", HFILL }
2767         },
2768         { &hf_quic_frame_type_ae_fab,
2769           { "First ACK Block", "quic.frame_type.ack.fab",
2770             FT_UINT64, BASE_DEC, NULL, 0x0,
2771             "Indicates the number of contiguous additional packets being acknowledged starting at the Largest Acknowledged", HFILL }
2772         },
2773         { &hf_quic_frame_type_ae_gap,
2774           { "Gap", "quic.frame_type.ae.gap",
2775             FT_UINT64, BASE_DEC, NULL, 0x0,
2776             "Indicating the number of contiguous unacknowledged packets preceding the packet number one lower than the smallest in the preceding ACK Block", HFILL }
2777         },
2778         { &hf_quic_frame_type_ae_ack_block,
2779           { "ACK Block", "quic.frame_type.ae.ack_block",
2780             FT_UINT64, BASE_DEC, NULL, 0x0,
2781             "Indicating the number of contiguous acknowledged packets preceding the largest packet number, as determined by the preceding Gap", HFILL }
2782         },
2783     };
2784
2785     static gint *ett[] = {
2786         &ett_quic,
2787         &ett_quic_connection_info,
2788         &ett_quic_ft,
2789         &ett_quic_ftflags
2790     };
2791
2792     static ei_register_info ei[] = {
2793         { &ei_quic_connection_unknown,
2794           { "quic.connection.unknown", PI_PROTOCOL, PI_NOTE,
2795             "Unknown QUIC connection. Missing Initial Packet or migrated connection?", EXPFILL }
2796         },
2797         { &ei_quic_ft_unknown,
2798           { "quic.ft.unknown", PI_UNDECODED, PI_NOTE,
2799             "Unknown Frame Type", EXPFILL }
2800         },
2801         { &ei_quic_decryption_failed,
2802           { "quic.decryption_failed", PI_DECRYPTION, PI_WARN,
2803             "Failed to decrypt handshake", EXPFILL }
2804         },
2805         { &ei_quic_protocol_violation,
2806           { "quic.protocol_violation", PI_PROTOCOL, PI_WARN,
2807             "Invalid data according to the protocol", EXPFILL }
2808         },
2809     };
2810
2811     proto_quic = proto_register_protocol("QUIC IETF", "QUIC", "quic");
2812
2813     proto_register_field_array(proto_quic, hf, array_length(hf));
2814     proto_register_subtree_array(ett, array_length(ett));
2815
2816     expert_quic = expert_register_protocol(proto_quic);
2817     expert_register_field_array(expert_quic, ei, array_length(ei));
2818
2819     quic_handle = register_dissector("quic", dissect_quic, proto_quic);
2820
2821     register_init_routine(quic_init);
2822     register_cleanup_routine(quic_cleanup);
2823 }
2824
2825 void
2826 proto_reg_handoff_quic(void)
2827 {
2828     tls13_handshake_handle = find_dissector("tls13-handshake");
2829     dissector_add_uint_with_preference("udp.port", 0, quic_handle);
2830     heur_dissector_add("udp", dissect_quic_heur, "QUIC", "quic", proto_quic, HEURISTIC_ENABLE);
2831 }
2832
2833 /*
2834  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
2835  *
2836  * Local variables:
2837  * c-basic-offset: 4
2838  * tab-width: 8
2839  * indent-tabs-mode: nil
2840  * End:
2841  *
2842  * vi: set shiftwidth=4 tabstop=8 expandtab:
2843  * :indentSize=4:tabSize=8:noTabs=true:
2844  */