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