net: introduce QUIC infrastructure and core subcomponents
Subsystems (8)
v13 cover net: introduce QUIC infrastructure and core subcomponents
Introduction
============
The QUIC protocol, defined in RFC 9000, is a secure, multiplexed transport built on top of UDP. It enables low-latency connection establishment, stream-based communication with flow control, and supports connection migration across network paths, while ensuring confidentiality, integrity, and availability.
This implementation introduces QUIC support in Linux Kernel, offering several key advantages:
- In-Kernel QUIC Support for Subsystems: Enables kernel subsystems such as SMB and NFS to operate over QUIC with minimal changes. Once the handshake is complete via the net/handshake APIs, data exchange proceeds over standard in-kernel transport interfaces.
- Standard Socket API Semantics: Implements core socket operations (listen(), accept(), connect(), sendmsg(), recvmsg(), close(), getsockopt(), setsockopt(), getsockname(), and getpeername()), allowing user space to interact with QUIC sockets in a familiar, POSIX-compliant way.
- ALPN-Based Connection Dispatching: Supports in-kernel ALPN (Application-Layer Protocol Negotiation) routing, allowing demultiplexing of QUIC connections across different user-space processes based on the ALPN identifiers.
- Performance Enhancements: Handles all control messages in-kernel to reduce syscall overhead, incorporates zero-copy mechanisms such as sendfile() to minimize data movement, and is also structured to support future crypto hardware offloads.
This implementation offers fundamental support for the following RFCs:
- RFC9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC9001 - Using TLS to Secure QUIC
- RFC9002 - QUIC Loss Detection and Congestion Control
- RFC9221 - An Unreliable Datagram Extension to QUIC
- RFC9287 - Greasing the QUIC Bit
- RFC9368 - Compatible Version Negotiation for QUIC
- RFC9369 - QUIC Version 2
The socket APIs for QUIC follow the RFC draft [1]:
- The Sockets API Extensions for In-kernel QUIC Implementations
Implementation
==============
The central design is to implement QUIC within the kernel while delegating the handshake to userspace.
Only the processing and creation of raw TLS Handshake Messages are handled in userspace, facilitated by a TLS library like GnuTLS. These messages are exchanged between kernel and userspace via sendmsg() and recvmsg(), with cryptographic details conveyed through control messages (cmsg).
The entire QUIC protocol, aside from the TLS Handshake Messages processing and creation, is managed in the kernel. Rather than using an Upper Layer Protocol (ULP) layer, this implementation establishes a socket of type IPPROTO_QUIC (similar to IPPROTO_MPTCP), operating over UDP tunnels.
For kernel consumers, they can initiate a handshake request from the kernel to userspace using the existing net/handshake netlink. The userspace component, such as tlshd service [2], then manages the processing of the QUIC handshake request.
- Handshake Architecture:
┌──────┐ ┌──────┐
│ APP1 │ │ APP2 │ ...
└──────┘ └──────┘
┌──────────────────────────────────────────┐
│ {quic_client/server_handshake()} │<─────────────┐
└──────────────────────────────────────────┘ ┌─────────────┐
{send/recvmsg()} {set/getsockopt()} │ tlshd │
[CMSG handshake_info] [SOCKOPT_CRYPTO_SECRET] └─────────────┘
[SOCKOPT_TRANSPORT_PARAM_EXT] │ ^
│ ^ │ ^ │ │
Userspace │ │ │ │ │ │
──────────────│─│──────────────────│─│──────────────────│───│───────
Kernel │ │ │ │ │ │
v │ v │ v │
┌──────────────────┬───────────────────────┐ ┌─────────────┐
│ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐ │ handshake │
│ ├───────────────────────┤ │ │netlink APIs │
│ common, family, │ outqueue | inqueue │ │ └─────────────┘
│ ├───────────────────────┤ │ │ │
│ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐
│ ├───────────────────────┤ │ │ │ │ │
│ path, pnspace, │ packet │ │───│ SMB │ │ NFS │...
│ ├───────────────────────┤ │ │ │ │ │
│ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘
└──────────────────┴───────────────────────┘ └──────┴───────┘- User Data Architecture:
┌──────┐ ┌──────┐
│ APP1 │ │ APP2 │ ...
└──────┘ └──────┘
{send/recvmsg()} {set/getsockopt()} {recvmsg()}
[CMSG stream_info] [SOCKOPT_KEY_UPDATE] [EVENT conn update]
[SOCKOPT_CONNECTION_MIGRATION] [EVENT stream update]
[SOCKOPT_STREAM_OPEN/RESET/STOP]
│ ^ │ ^ ^
Userspace │ │ │ │ │
──────────────│─│───────────────│─│─────────────────────│───────────
Kernel │ │ │ │ │
v │ v │ ┌──────────────────┘
┌──────────────────┬───────────────────────┐
│ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐{kernel_send/recvmsg()}
│ ├───────────────────────┤ │{kernel_set/getsockopt()}
│ common, family, │ outqueue | inqueue │ │{kernel_recvmsg()}
│ ├───────────────────────┤ │
│ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐
│ ├───────────────────────┤ │ │ │ │ │
│ path, pnspace, │ packet │ │───│ SMB │ │ NFS │...
│ ├───────────────────────┤ │ │ │ │ │
│ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘
└──────────────────┴───────────────────────┘ └──────┴───────┘Interface
=========
This implementation supports a mapping of QUIC into sockets APIs. Similar to TCP and SCTP, a typical Server and Client use the following system call sequence to communicate:
Client Server
────────────────────────────────────────────────────────────────────── sockfd = socket(IPPROTO_QUIC) listenfd = socket(IPPROTO_QUIC) bind(sockfd) bind(listenfd)
listen(listenfd)
connect(sockfd)
quic_client_handshake(sockfd)
sockfd = accept(listenfd) quic_server_handshake(sockfd, cert)
sendmsg(sockfd) recvmsg(sockfd)
close(sockfd) close(sockfd)
close(listenfd)
Please note that quic_client_handshake() and quic_server_handshake() functions are currently sourced from libquic [3]. These functions are responsible for receiving and processing the raw TLS handshake messages until the completion of the handshake process.
For utilization by kernel consumers, it is essential to have tlshd service [2] installed and running in userspace. This service receives and manages kernel handshake requests for kernel sockets. In the kernel, the APIs closely resemble those used in userspace:
Client Server
────────────────────────────────────────────────────────────────────────
__sock_create(IPPROTO_QUIC, &sock) __sock_create(IPPROTO_QUIC, &sock)
kernel_bind(sock) kernel_bind(sock)
kernel_listen(sock)
kernel_connect(sock)
tls_client_hello_x509(args:{sock})
kernel_accept(sock, &newsock)
tls_server_hello_x509(args:{newsock}) kernel_sendmsg(sock) kernel_recvmsg(newsock)
sock_release(sock) sock_release(newsock)
sock_release(sock)
Please be aware that tls_client_hello_x509() and tls_server_hello_x509() are APIs from net/handshake/. They are used to dispatch the handshake request to the userspace tlshd service and subsequently block until the handshake process is completed.
Use Cases
=========
- Samba
Stefan Metzmacher has integrated Linux QUIC into Samba for both client and server roles [4].
- tlshd
The tlshd daemon [2] facilitates Linux QUIC handshake requests from kernel sockets. This is essential for enabling protocols like SMB and NFS over QUIC.
- curl
Linux QUIC is being integrated into curl [5] for HTTP/3. Example usage:
# curl --http3-only https://nghttp2.org:4433/ # curl --http3-only https://www.google.com/ # curl --http3-only https://facebook.com/ # curl --http3-only https://outlook.office.com/ # curl --http3-only https://cloudflare-quic.com/
- httpd-portable
Moritz Buhl has deployed an HTTP/3 server over Linux QUIC [6] that is accessible via Firefox and curl:
- NetPerfMeter
The latest NetPerfMeter release supports Linux QUIC and can be used to run performance evaluations [10].
Test Coverage
=============
The Coverage (gcov) of Functional and Interop Tests:
- Functional Tests
The libquic self-tests (make check) pass on all major architectures:
x86_64, i386, s390x, aarch64, ppc64le.
- Interop tests
Interoperability was validated using the QUIC Interop Runner [7] against all major userland QUIC stacks. Results are available at:
- Fuzzing via Syzkaller
Syzkaller has been running kernel fuzzing with QUIC for weeks using tests/syzkaller/ in libquic [3].
- Performance Testing
Performance was benchmarked using iperf [8] over a 100G NIC using various MTUs and packet sizes:
- QUIC vs. kTLS:
UNIT size:1024 size:4096 size:16384 size:65536
Gbits/sec QUIC | kTLS QUIC | kTLS QUIC | kTLS QUIC | kTLS
────────────────────────────────────────────────────────────────────
mtu:1500 2.27 | 3.26 3.02 | 6.97 3.36 | 9.74 3.48 | 10.8
────────────────────────────────────────────────────────────────────
mtu:9000 3.66 | 3.72 5.87 | 8.92 7.03 | 11.2 8.04 | 11.4 - QUIC(disable_1rtt_encryption) vs. TCP:
UNIT size:1024 size:4096 size:16384 size:65536
Gbits/sec QUIC | TCP QUIC | TCP QUIC | TCP QUIC | TCP
────────────────────────────────────────────────────────────────────
mtu:1500 3.09 | 4.59 4.46 | 14.2 5.07 | 21.3 5.18 | 23.9
────────────────────────────────────────────────────────────────────
mtu:9000 4.60 | 4.65 8.41 | 14.0 11.3 | 28.9 13.5 | 39.2The performance gap between QUIC and kTLS may be attributed to:
- The absence of Generic Segmentation Offload (GSO) for QUIC.
- An additional data copy on the transmission (TX) path.
- Extra encryption required for header protection in QUIC.
- A longer header length for the stream data in QUIC.
Patches
=======
Note: This implementation is organized into five parts and submitted across two patchsets for review. This patchset includes Parts 1–2, while Parts 3–5 will be submitted in a subsequent patchset. For complete series, see [9].
1. Infrastructure (2):
net: define IPPROTO_QUIC and SOL_QUIC constants
net: build socket infrastructure for QUIC protocol
2. Subcomponents (13):
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: provide quic.h header files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add packet builder base
quic: add packet parser base
3. Data Processing (8):
quic: add frame encoder and decoder base
quic: implement outqueue transmission and flow control
quic: implement outqueue sack and retransmission
quic: implement inqueue receiving and flow control
quic: implement frame creation functions
quic: implement frame processing functions
quic: implement packet creation functions
quic: implement packet processing functions
4. Socket APIs (6):
quic: support bind/listen/connect/accept/close()
quic: support sendmsg() and recvmsg()
quic: support socket options related to interaction after handshake
quic: support socket options related to settings prior to handshake
quic: support socket options related to setup during handshake
quic: support socket ioctls and socket dump via procfs
5. Documentation and Selftests (3):
Documentation: describe QUIC protocol interface in quic.rst
quic: create sample test using handshake APIs for kernel consumers
selftests: net: add tests for QUIC protocol
Notice: The QUIC module is currently labeled as "EXPERIMENTAL".
All contributors are recognized in the respective patches with the tag of 'Signed-off-by:'. Special thanks to Moritz Buhl and Stefan Metzmacher whose practical use cases and insightful feedback have been instrumental in shaping the design and advancing the development.
References
==========
[1] https://datatracker.ietf.org/doc/html/draft-lxin-quic-socket-apis [2] https://github.com/oracle/ktls-utils [3] https://github.com/lxin/quic [4] https://gitlab.com/samba-team/samba/-/merge_requests/4019 [5] https://github.com/moritzbuhl/curl/tree/linux_curl [6] https://github.com/moritzbuhl/httpd-portable [7] https://github.com/quic-interop/quic-interop-runner [8] https://github.com/lxin/iperf [9] https://github.com/lxin/net-next/commits/quic/
[10] https://www.nntb.no/~dreibh/netperfmeter/
Changes in v2-v13: See individual patch changelogs for details.
Xin Long (15):
net: define IPPROTO_QUIC and SOL_QUIC constants
net: build socket infrastructure for QUIC protocol
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: provide quic.h header files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add packet builder base
quic: add packet parser base
Documentation/networking/ip-sysctl.rst | 39 + MAINTAINERS | 9 + include/linux/quic.h | 24 + include/linux/socket.h | 1 + include/uapi/linux/in.h | 2 + include/uapi/linux/quic.h | 241 +++++ net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 35 + net/quic/Makefile | 9 + net/quic/common.c | 559 +++++++++++ net/quic/common.h | 220 +++++ net/quic/cong.c | 333 +++++++ net/quic/cong.h | 130 +++ net/quic/connid.c | 256 +++++ net/quic/connid.h | 182 ++++ net/quic/crypto.c | 1245 ++++++++++++++++++++++++ net/quic/crypto.h | 89 ++ net/quic/family.c | 452 +++++++++ net/quic/family.h | 44 + net/quic/packet.c | 887 +++++++++++++++++ net/quic/packet.h | 120 +++ net/quic/path.c | 568 +++++++++++ net/quic/path.h | 190 ++++ net/quic/pnspace.c | 253 +++++ net/quic/pnspace.h | 201 ++++ net/quic/protocol.c | 418 ++++++++ net/quic/protocol.h | 63 ++ net/quic/socket.c | 477 +++++++++ net/quic/socket.h | 209 ++++ net/quic/stream.c | 416 ++++++++ net/quic/stream.h | 131 +++ net/quic/timer.c | 154 +++ net/quic/timer.h | 45 + usr/include/Makefile | 1 + 35 files changed, 8005 insertions(+) create mode 100644 include/linux/quic.h create mode 100644 include/uapi/linux/quic.h create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/common.c create mode 100644 net/quic/common.h create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.h create mode 100644 net/quic/connid.c create mode 100644 net/quic/connid.h create mode 100644 net/quic/crypto.c create mode 100644 net/quic/crypto.h create mode 100644 net/quic/family.c create mode 100644 net/quic/family.h create mode 100644 net/quic/packet.c create mode 100644 net/quic/packet.h create mode 100644 net/quic/path.c create mode 100644 net/quic/path.h create mode 100644 net/quic/pnspace.c create mode 100644 net/quic/pnspace.h create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.h create mode 100644 net/quic/stream.c create mode 100644 net/quic/stream.h create mode 100644 net/quic/timer.c create mode 100644 net/quic/timer.h
Signature · 1 line
2.47.1
PATCH v13 1/15 net: define IPPROTO_QUIC and SOL_QUIC constants
This patch adds IPPROTO_QUIC and SOL_QUIC constants to the networking subsystem. These definitions are essential for applications to set socket options and protocol identifiers related to the QUIC protocol.
QUIC does not possess a protocol number allocated from IANA, and like IPPROTO_MPTCP, IPPROTO_QUIC is merely a value used when opening a QUIC socket with:
socket(AF_INET, SOCK_STREAM, IPPROTO_QUIC);
Note we did not opt for UDP ULP for QUIC implementation due to several considerations:
- QUIC's connection Migration requires at least 2 UDP sockets for one QUIC connection at the same time, not to mention the multipath feature in one of its draft RFCs.
- In-Kernel QUIC, as a Transport Protocol, wants to provide users with the TCP or SCTP like Socket APIs, like connect()/listen()/accept()... Note that a single UDP socket might even be used for multiple QUIC connections.
The use of IPPROTO_QUIC type sockets over UDP tunnel will effectively address these challenges and provides a more flexible and scalable solution.
---
v11:
- Set maximum line length to 80 characters.
--- include/linux/socket.h | 1 + include/uapi/linux/in.h | 2 ++ 2 files changed, 3 insertions(+)
include/linux/socket.h +1 -0
@@ -401,6 +401,7 @@ struct ucred {#define SOL_MCTP 285#define SOL_SMC 286#define SOL_VSOCK 287 +#define SOL_QUIC 288/* IPX options */ #define IPX_TYPE 1
include/uapi/linux/in.h +2 -0
@@ -85,6 +85,8 @@ enum {#define IPPROTO_RAW IPPROTO_RAW IPPROTO_SMC = 256, /* Shared Memory Communications */#define IPPROTO_SMC IPPROTO_SMC + IPPROTO_QUIC = 261, /* A UDP-Based Multiplexed Secure Transport */ +#define IPPROTO_QUIC IPPROTO_QUIC IPPROTO_MPTCP = 262, /* Multipath TCP connection */#define IPPROTO_MPTCP IPPROTO_MPTCPIPPROTO_MAX
Signature · 1 line
2.47.1
PATCH v13 2/15 net: build socket infrastructure for QUIC protocol
In reply to Xin LongThis patch lays the groundwork for QUIC socket support in the kernel. It defines the core structures and protocol hooks needed to create QUIC sockets, without implementing any protocol behavior at this stage.
Basic integration is included to allow building the module via CONFIG_IP_QUIC=m.
This provides the scaffolding necessary for adding actual QUIC socket behavior in follow-up patches.
---
v3:
- Kconfig: add 'default n' for IP_QUIC (reported by Paolo).
- quic_disconnect(): return -EOPNOTSUPP (suggested by Paolo).
- quic_init/destroy_sock(): drop local_bh_disable/enable() calls (noted by Paolo).
- sysctl: add alpn_demux option to en/disable ALPN-based demux.
- SNMP: remove SNMP_MIB_SENTINEL, switch to snmp_get_cpu_field_batch_cnt() to align with latest net-next changes.
v4:
- Remove unnecessary READ_ONCE() in quic_inet_connect() (reported by
Paolo).
v5:
- Update the type of the parameter 'addr' in quic_inet_connect(), quic_connect(), and quic_bind() to match the latest net-next changes.
- Define quic_is_serv() to reuse sk->sk_max_ack_backlog for server-side
detection; path->serv will be deleted in a later patch.
- Use MODULE_ALIAS_NET_PF_PROTO instead of MODULE_ALIAS (suggested by
Stefan).
- Add the missing Documentation entry for the new sysctl options (noted
by Paolo).
- Add the missing MAINTAINERS entry for the QUIC PROTOCOL (noted by
Jakub).v6:
- Relocate the QUIC PROTOCOL MAINTAINERS entry to its proper section (noted by Jakub).
v7:
- Replace #ifdef CONFIG_XXX with #if IS_ENABLED(CONFIG_XXX) (noted by
Paolo).
v8:
- Fix an issue where an uninitialized value could be returned from quic_net_init() by initializing err to 0 (reported by AI review).
- Replace the global ALPN demultiplexing sysctl with a static key that will be enabled only when ALPN is configured on a listening socket (noted by Stefan).
v10:
- Note for AI reviews: inet6_register_protosw() never fails for QUIC, so checking its return value is unnecessary.
- Remove sk_sndbuf/sk_rcvbuf initialization in quic_init_sock(), as it's already done in sock_init_data_uid() with sysctl_w/rmem_default.
v11:
- Note for AI review: quic_sk(sk)->reqs is used only for listen sockets and will be initialized in quic_inet_listen() in a later patch, so there is no need to initialize it in quic_init_sock().
- Set maximum line length to 80 characters.
- Drop addr_len from quic_recvmsg() to match the latest proto_ops.recvmsg() update.
- Use %lu for SNMP counters in quic_snmp_seq_show().
v12:
- Move the quic_table definition under #if IS_ENABLED(CONFIG_SYSCTL).
- Add comments and invoke sk_wake_async_rcu() in quic_write_space().
- Avoid overwriting sk->sk_destruct in quic_init_sock().
- Add quic_reqs list initialization in quic_init_sock().
--- Documentation/networking/ip-sysctl.rst | 39 +++ MAINTAINERS | 7 + net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 35 +++ net/quic/Makefile | 8 + net/quic/protocol.c | 378 +++++++++++++++++++++++++ net/quic/protocol.h | 57 ++++ net/quic/socket.c | 214 ++++++++++++++ net/quic/socket.h | 89 ++++++ 10 files changed, 829 insertions(+) create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.h
Documentation/networking/ip-sysctl.rst +39 -0
@@ -3805,6 +3805,45 @@ l3mdev_accept - BOOLEAN Default: 1 (enabled) +``/proc/sys/net/quic/*`` Variables +=================================== + +quic_mem - vector of 3 LONGs: min, pressure, max + Number of pages allowed for queueing by all QUIC sockets. + + min: below this number of pages QUIC is not bothered about its + memory appetite. + + pressure: when amount of memory allocated by QUIC exceeds this number + of pages, QUIC moderates its memory consumption and enters memory + pressure mode, which is exited when memory consumption falls + under "min". + + max: number of pages allowed for queueing by all QUIC sockets. + + Defaults are calculated at boot time from amount of available + memory. + +quic_rmem - vector of 3 INTEGERs: min, default, max + Only the first value ("min") is used, "default" and "max" are + ignored. + + min: Minimal size of receive buffer used by QUIC sockets. + It is guaranteed to each QUIC socket, even under moderate memory + pressure. + + Default: 4K + +quic_wmem - vector of 3 INTEGERs: min, default, max + Only the first value ("min") is used, "default" and "max" are + ignored. + + min: Amount of memory reserved for send buffers for QUIC sockets. + Each QUIC socket has rights to use it due to fact of its birth. + + Default: 4K + + ``/proc/sys/net/core/*`` ========================
MAINTAINERS +7 -0
@@ -22171,6 +22171,13 @@ L: [email protected] S: Maintained F: drivers/net/wireless/quantenna/ +QUIC PROTOCOL +M: Xin Long <[email protected]> +L: [email protected] +S: Maintained +W: https://github.com/lxin/quic +F: net/quic/ + RADEON and AMDGPU DRM DRIVERS M: Alex Deucher <[email protected]> M: Christian König <[email protected]>
net/Kconfig +1 -0
@@ -251,6 +251,7 @@ source "net/bridge/netfilter/Kconfig" endif # if NETFILTER +source "net/quic/Kconfig" source "net/sctp/Kconfig" source "net/rds/Kconfig" source "net/tipc/Kconfig"
net/Makefile +1 -0
@@ -40,6 +40,7 @@ obj-$(CONFIG_PHONET) += phonet/ ifneq ($(CONFIG_VLAN_8021Q),) obj-y += 8021q/ endif +obj-$(CONFIG_IP_QUIC) += quic/ obj-$(CONFIG_IP_SCTP) += sctp/ obj-$(CONFIG_RDS) += rds/ obj-$(CONFIG_WIRELESS) += wireless/
net/quic/Kconfig new file +35 -0
@@ -0,0 +1,35 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# QUIC configuration +# + +menuconfig IP_QUIC + tristate "QUIC: A UDP-Based Multiplexed Secure Transport (Experimental)" + depends on INET + depends on IPV6 + select CRYPTO + select CRYPTO_HMAC + select CRYPTO_AES + select CRYPTO_GCM + select CRYPTO_CCM + select CRYPTO_CHACHA20POLY1305 + select NET_UDP_TUNNEL + default n + help + QUIC: A UDP-Based Multiplexed and Secure Transport + + From rfc9000 <https://www.rfc-editor.org/rfc/rfc9000.html>. + + QUIC provides applications with flow-controlled streams for structured + communication, low-latency connection establishment, and network path + migration. QUIC includes security measures that ensure + confidentiality, integrity, and availability in a range of deployment + circumstances. Accompanying documents describe the integration of + TLS for key negotiation, loss detection, and an exemplary congestion + control algorithm. + + To compile this protocol support as a module, choose M here: the + module will be called quic. Debug messages are handled by the + kernel's dynamic debugging framework. + + If in doubt, say N.
net/quic/Makefile new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Makefile for QUIC support code. +# + +obj-$(CONFIG_IP_QUIC) += quic.o + +quic-y := protocol.o socket.o
net/quic/protocol.c new file +378 -0
378 lines not on this page · raw message
net/quic/protocol.h new file +57 -0
57 lines not on this page · raw message
net/quic/socket.c new file +214 -0
214 lines not on this page · raw message
net/quic/socket.h new file +89 -0
89 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v13 3/15 quic: provide common utilities and data structures
In reply to Xin LongThis patch provides foundational data structures and utilities used throughout the QUIC stack.
It introduces packet header types, connection ID support, and address handling. Hash tables are added to manage socket lookup and connection ID mapping.
A flexible binary data type is provided, along with helpers for parsing, matching, and memory management. Helpers for encoding and decoding transport parameters and frames are also included.
---
v3:
- Rework hashtables: split into two types and size them based on totalram_pages(), similar to SCTP (reported by Paolo).
- struct quic_shash_table: use rwlock instead of spinlock.
- quic_data_from/to_string(): add safety and common-case checks (noted by Paolo).
v4:
- Handle the error returned by quic_hash_tables_init() properly (reported by Simon).
- Use vmalloc() to simplify hashtable allocations (suggested by Paolo).
- Replace rwlock_t with spinlock_t and use hlist_nulls_head in quic_shash_head for lockless lookup/access (suggested by Paolo).
- Define QUIC_PN_BITS to replace a magical number in quic_get_num() (reported by Paolo)
- Rename several hash-related functions:
* quic_(listen_)sock_hash() → quic_(listen_)sock_head()
* quic_(listen_)sock_head() → quic_(listen_)sock_hash()
* quic_shash() → quic_addr_hash()
* quic_ahash() → call its code directly in quic_sock_hash().
- Include net in the hash calculations in quic_listen_sock_hash() and quic_udp_sock_head(), and include len in quic_source_conn_id_head().
v5:
- Use u64 for skb_cb->time and u32 for skb_cb->seqno, and introduce quic_ktime_get_us() to obtain timestamps in microseconds.
- Remove skb_cb->number_max and reuse number as the largest previously
seen, and add skb_cb->crypto_ctx for async crypto context freeing.
- Add case 8 to quic_put_int(), which will be used to pack a u64 timestamp into the token in a later patch.
v6:
- Since transport_header is no longer set for QUIC, use skb->data instead in quic_hdr() and quic_hshdr(). As the UDP header can now be accessed via udp_hdr(), drop udph_offset from struct quic_skb_cb.
- Note for AI reviews: although ticket/token/alpn are not initialized in quic_init_sock(), it is safe to kfree() them in quic_destroy_sock() because they are always set to NULL (via sk_alloc() in inet/6_create() or memset(0) in quic_accept() in a later patchset).
v7:
- Add the missing check len < length in quic_data_has/match() (reported by AI review).
v9:
- Add BUILD_BUG_ON() to check size of struct quic_skb_cb in quic_init() (suggested by Paolo).
v10:
- Add a comment to quic_conn_id_update() to clarify that the caller is responsible for ensuring the connection ID length does not exceed QUIC_CONN_ID_MAX_LEN.
- Ensure quic_get_param() validates that the decoded parameter value consumes exactly the expected valuelen in quic_get_param() (noted by AI review).
- Replace manual memcpy() + endian conversion and temporary union usage with get_unaligned_beNN() and put_unaligned_beNN() helpers for reading and writing integers in network byte order.
- Replace vmalloc(size * sizeof(type)) with vmalloc_array() in hash table allocations.
- Move *plen update to after successful parse in quic_get_int().
v11:
- Set maximum line length to 80 characters.
- Change return type of quic_data_match() and quic_data_has() to bool.
- Add a check for len in quic_conn_id_update().
- Avoid roundup_pow_of_two(0) in quic_hash_tables_init().
v12:
- Move QUIC_VARINT_nBYTE_MAX definitions to common.h for later use.
- Add sync field to struct quic_skb_cb to support forcing synchronous crypto processing for specific packets late.
- Remove errframe from struct quic_skb_cb as it is no longer used.
--- net/quic/Makefile | 2 +- net/quic/common.c | 559 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/common.h | 220 +++++++++++++++++ net/quic/protocol.c | 10 + net/quic/socket.c | 4 + net/quic/socket.h | 21 ++ 6 files changed, 815 insertions(+), 1 deletion(-) create mode 100644 net/quic/common.c create mode 100644 net/quic/common.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := protocol.o socket.o +quic-y := common.o protocol.o socket.o
net/quic/common.c new file +559 -0
559 lines not on this page · raw message
net/quic/common.h new file +220 -0
220 lines not on this page · raw message
net/quic/protocol.c +10 -0
@@ -311,6 +311,9 @@ static __init int quic_init(void)int max_share, err = -ENOMEM ;unsigned long limit; +BUILD_BUG_ON (sizeof (struct quic_skb_cb ) > + sizeof_field(struct sk_buff, cb)); +/* Set QUIC memory limits based on available system memory, similar to * sctp_init(). */
@@ -335,6 +338,10 @@ static __init int quic_init(void)if (err) goto err_percpu_counter; + err =quic_hash_tables_init (); +if (err) + goto err_hash; + err =register_pernet_subsys (&quic_net_ops);if (err) goto err_def_ops;
@@ -352,6 +359,8 @@ static __init int quic_init(void) err_protosw:unregister_pernet_subsys (&quic_net_ops); err_def_ops: +quic_hash_tables_destroy (); +err_hash:percpu_counter_destroy (&quic_sockets_allocated); err_percpu_counter:return err;
@@ -364,6 +373,7 @@ static __exit void quic_exit(void)#endif quic_protosw_exit ();unregister_pernet_subsys (&quic_net_ops); +quic_hash_tables_destroy ();percpu_counter_destroy (&quic_sockets_allocated);pr_info ("quic: exit\n" ); }
net/quic/socket.c +4 -0
@@ -54,6 +54,10 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_data_free (quic_ticket (sk)); +quic_data_free (quic_token (sk)); +quic_data_free (quic_alpn (sk)); +sk_sockets_allocated_dec (sk);sock_prot_inuse_add (sock_net (sk), sk->sk_prot,-1 ); }
net/quic/socket.h +21 -0
@@ -10,6 +10,8 @@#include <net/udp_tunnel.h> +#include "common.h" +#include "protocol.h" extern struct proto quic_prot;
@@ -25,6 +27,10 @@ enum quic_state {struct quic_sock {struct inet_sock inet;struct list_head reqs; + +struct quic_data ticket; +struct quic_data token; +struct quic_data alpn; };struct quic6_sock {
@@ -42,6 +48,21 @@ static inline struct list_head *quic_reqs(const struct sock *sk)return &quic_sk (sk)->reqs; } +static inline struct quic_data *quic_token (const struct sock *sk) +{ +return &quic_sk (sk)->token; +} + +static inline struct quic_data *quic_ticket (const struct sock *sk) +{ +return &quic_sk (sk)->ticket; +} + +static inline struct quic_data *quic_alpn (const struct sock *sk) +{ +return &quic_sk (sk)->alpn; +} +static inline bool quic_is_serv (const struct sock *sk) {return !!sk->sk_max_ack_backlog;
Signature · 1 line
2.47.1
PATCH v13 4/15 quic: provide family ops for address and protocol
In reply to Xin LongIntroduce QUIC address and protocol family operations to handle IPv4/IPv6 specifics consistently, similar to SCTP. The new quic_family.{c,h} provide helpers for routing, skb transmit handling, address parsing and comparison and UDP socket config initializing etc.
This consolidates protocol-family logic and enables cleaner dual-stack support in the QUIC socket implementation.
---
v2:
- Add more checks for addrs in .get_user_addr() and .get_pref_addr().
- Consider sk_bound_dev_if in .udp_conf_init() and .flow_route() to support vrf.
v3:
- Remove quic_addr_family/proto_ops abstraction; use if statements to reduce indirect call overhead (suggested by Paolo).
- quic_v6_set_sk_addr(): add quic_v6_copy_sk_addr() helper to avoid duplicate code (noted by Paolo).
- quic_v4_flow_route(): use flowi4_dscp per latest net-next changes.
v4:
- Remove unnecessary _fl variable from flow_route() functions (noted by Paolo).
- Fix coding style of ?: operator (noted by Paolo).
v5:
- Remove several unused functions from this patch series (suggested by Paolo):
* quic_seq_dump_addr()
* quic_get_msg_ecn()
* quic_get_user_addr()
* quic_get_pref_addr()
* quic_set_pref_addr()
* quic_set_sk_addr()
* quic_set_sk_ecn()
- Replace the sa->v4/v6.sin_family checks with quic_v4/v6_is_any_addr() in quic_v4/v6_flow_route() (suggested by Paolo).
- Introduce quic_v4_match_v6_addr() to simplify family-mismatch checks between sk and addr in quic_v6_cmp_sk_addr() (notied by Paolo).
v6:
- Use udp_hdr(skb) to access UDP header in quic_v4/6_get_msg_addrs(), as transport_header is no longer reset for QUIC.
v10:
- Fix argument types passed to ip6_dst_store() in quic_v6_flow_route().
v11:
- Set maximum line length to 80 characters.
- Change return type of quic_is_any_addr() to bool.
- Call local_bh_disable() in quic_lower_xmit() because udp(6)_tunnel_xmit_skb() requires a non-preemptible context.
- Return a negative errno (-EINVAL) instead of 1 in
quic_v4/v6_get_mtu_info().
v12:
- Add helper functions quic_get_dev_if(), quic_set_skb_iif(), quic_sk_accept_pmtu(), and quic_sk_destruct().
- Remove use_udp6_rx_checksums setting in quic_v4_udp_conf_init().
- Enable use_udp6_tx_checksums and set bind_ifindex via
quic_get_dev_if() in quic_v6_udp_conf_init().
- Switch to ip_route_output_flow() in quic_v4_flow_route().
- Set flowi4/6_uid, flowi4/6_mark, and derive flowi4/6_oif via
quic_get_dev_if() in quic_v4/6_flow_route().
- Call fl6_update_dst() for final_dst, and ip6_make_flowinfo() for
flow label; also set sin6_scope_id for IPv6 link-local addresses in
quic_v6_flow_route().
- Set sin6_scope_id from skb->skb_iif in quic_v6_get_msg_addrs().
- Fix indentation in quic_v4/6_get_mtu_info().
- Do not match specific socket addresses against ANY in
quic_v4/6_cmp_sk_addr() and quic_v4_match_v6_addr().
- Handle sin6_scope_id for IPv6 link-local addresses and call
quic_v4_cmp_sk_addr() instead of open-coding it in
quic_v6_cmp_sk_addr().
- Change the type of parameter peer from bool to int in
quic_get_sk_addr().
---
net/quic/Makefile | 2 +-
net/quic/family.c | 452 ++++++++++++++++++++++++++++++++++++++++++++
net/quic/family.h | 44 +++++
net/quic/protocol.c | 2 +-
net/quic/socket.c | 6 +-
net/quic/socket.h | 1 +
6 files changed, 503 insertions(+), 4 deletions(-)
create mode 100644 net/quic/family.c
create mode 100644 net/quic/family.hnet/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o protocol.o socket.o +quic-y := common.o family.o protocol.o socket.o
net/quic/family.c new file +452 -0
452 lines not on this page · raw message
net/quic/family.h new file +44 -0
44 lines not on this page · raw message
net/quic/protocol.c +1 -1
@@ -47,7 +47,7 @@ static int quic_inet_listen(struct socket *sock, int backlog)static int quic_inet_getname (struct socket *sock,struct sockaddr *uaddr,int peer) { -return -EOPNOTSUPP ; +return quic_get_sk_addr (sock, uaddr, peer); } static __poll_t quic_inet_poll(struct file *file, struct socket *sock,
net/quic/socket.c +4 -2
@@ -121,7 +121,8 @@ static int quic_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval, unsigned int optlen) {if (level !=SOL_QUIC ) -return -EOPNOTSUPP ; +return quic_common_setsockopt (sk, level, optname, optval, + optlen);return quic_do_setsockopt (sk, optname, optval, optlen); }
@@ -136,7 +137,8 @@ static int quic_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) {if (level !=SOL_QUIC ) -return -EOPNOTSUPP ; +return quic_common_getsockopt (sk, level, optname, optval, + optlen);return quic_do_getsockopt (sk, optname,USER_SOCKPTR (optval),USER_SOCKPTR (optlen));
net/quic/socket.h +1 -0
@@ -11,6 +11,7 @@#include <net/udp_tunnel.h> #include "common.h" +#include "family.h" #include "protocol.h"
Signature · 1 line
2.47.1
Re: [PATCH net-next v13 04/15] quic: provide family ops for address and protocol
[sashiko-claude]
net/quic/family.c line 151
Quoted 12 lines
net/quic/family.c new file +12
-0+static void quic_v4_lower_xmit (struct sock *sk,struct sk_buff *skb, +struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tos = (inet_sk (sk)->tos | cb->ecn), ttl; +struct flowi4 *fl4 = &fl->u.ip4; +struct dst_entry *dst; +__be16 df =0 ; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI4:%d -> %pI4:%d\n" , + __func__, skb, skb->len, cb->number, &fl4->saddr, +ntohs (fl4->fl4_sport), &fl4->daddr,ntohs (fl4->fl4_dport));
Should cb->number use %lld here rather than %llu? Looking at struct quic_skb_cb in net/quic/common.h:
s64 number; /* Parsed packet number, or the largest previously seen */
Since number is s64, a negative initial value (such as -1 for "largest previously seen") would be printed as 18446744073709551615 with %llu, and compilers with -Wformat-signedness flag the mismatch.
[ ... ]
net/quic/family.c line 178
Quoted 12 lines
net/quic/family.c new file +12
-0+static void quic_v6_lower_xmit (struct sock *sk,struct sk_buff *skb, +struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tc = (inet6_sk (sk)->tclass | cb->ecn), ttl; +struct flowi6 *fl6 = &fl->u.ip6; +struct dst_entry *dst; +__be32 label; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI6c:%d -> %pI6c:%d\n" , + __func__, skb, skb->len, cb->number, &fl6->saddr, +ntohs (fl6->fl6_sport), &fl6->daddr,ntohs (fl6->fl6_dport));
Same question about cb->number being printed with %llu while the field is declared s64.
A minor one but legit, will fix it.
Thanks.
PATCH v13 5/15 quic: provide quic.h header files for kernel and userspace
In reply to Xin LongThis commit adds quic.h to include/uapi/linux, providing the necessary definitions for the QUIC socket API. Exporting this header allows both user space applications and kernel subsystems to access QUIC-related control messages, socket options, and event/notification interfaces.
Since kernel_get/setsockopt() is no longer available to kernel consumers, a corresponding internal header, include/linux/quic.h, is added. This exposes quic_do_get/setsockopt() to handle QUIC socket options directly for kernel subsystems.
Detailed descriptions of these structures are available in [1], and will be also provided when adding corresponding socket interfaces in the later patches.
[1] https://datatracker.ietf.org/doc/html/draft-lxin-quic-socket-apis
---
v2:
- Fix a kernel API description warning, found by Jakub.
- Replace uintN_t with __uN, capitalize _UAPI_LINUX_QUIC_H, and assign explicit values for QUIC_TRANSPORT_ERROR_ enum in UAPI quic.h, suggested by David Howells.
v4:
- Use MSG_QUIC_ prefix for MSG_* flags to avoid conflicts with other protocols, such as MSG_NOTIFICATION in SCTP (reported by Thomas).
- Remove QUIC_CONG_ALG_CUBIC; only NEW RENO congestion control is supported in this version.
v5:
- Add include/linux/quic.h and include/uapi/linux/quic.h to the QUIC PROTOCOL entry in MAINTAINERS.
v6:
- Fix the copy/pasted the uAPI path for SCTP to the QUIC entry (noted by Jakub).
v7:
- Expose quic_do_get/setsockopt() instead of quic_kernel_get/setsockopt() (suggested by Paolo).
v10:
- Fix typo: 'extented' -> 'extended' (noted by AI review).
- Add comment for inclusion of sys/socket.h in uapi quic.h.
- Add uses-libc += linux/quic.h in usr/include/Makefile to fix the new build error.
- Delete config from struct quic_sock, its members will be split into other subcomponents in the future patches.
- Add explicit reserved fields to multiple structs to account for implicit padding and ensure UAPI stability.
- Expand reserved fields in struct transport_param and config, handshake and stream_info to allow future extensions without breaking the UAPI.
v11:
- Set maximum line length to 80 characters.
- Drop trailing reserved fields in structs and rely on copy_struct_to/from_user() for extensibility; keep reserved fields in the middle to indicate memory holes.
v12:
- Make the phrase field in struct quic_connection_close a fixed-size array.
- Add QUIC_TRANSPORT_ERROR_VERSION_NEGOTIATION for late use.
- Add keepalive_probe_interval to struct quic_transport_param to make keepalive probing configurable.
- Relace uses-libc += linux/quic.h with no-header-test += linux/quic.h in usr/include/Makefile to fix the new build error.
- Add forward declaration for struct sock in include/linux/quic.h.
--- MAINTAINERS | 2 + include/linux/quic.h | 24 ++++ include/uapi/linux/quic.h | 241 ++++++++++++++++++++++++++++++++++++++ net/quic/socket.c | 36 +++++- net/quic/socket.h | 1 + usr/include/Makefile | 1 + 6 files changed, 301 insertions(+), 4 deletions(-) create mode 100644 include/linux/quic.h create mode 100644 include/uapi/linux/quic.h
MAINTAINERS +2 -0
@@ -22176,6 +22176,8 @@ M: Xin Long <[email protected]> L: [email protected] S: Maintained W: https://github.com/lxin/quic +F: include/linux/quic.h +F: include/uapi/linux/quic.h F: net/quic/ RADEON and AMDGPU DRM DRIVERS
include/linux/quic.h new file +24 -0
@@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#ifndef _LINUX_QUIC_H +#define _LINUX_QUIC_H + +#include <linux/sockptr.h> +#include <uapi/linux/quic.h> + +struct sock ; + +int quic_do_setsockopt (struct sock *sk,int optname,sockptr_t optval, +unsigned int optlen); +int quic_do_getsockopt (struct sock *sk,int optname,sockptr_t optval, +sockptr_t optlen); + +#endif
include/uapi/linux/quic.h new file +241 -0
241 lines not on this page · raw message
net/quic/socket.c +32 -4
@@ -111,11 +111,25 @@ static void quic_close(struct sock *sk, long timeout)sk_common_release (sk); } -static int quic_do_setsockopt (struct sock *sk,int optname,sockptr_t optval, -unsigned int optlen) +/** +* quic_do_setsockopt - set a QUIC socket option +* @sk: socket to configure +* @optname: option name (QUIC-level) +* @optval: user buffer containing the option value +* @optlen: size of the option value +* +* Sets a QUIC socket option on a given socket. +* +* Return: +* - On success, 0 is returned. +* - On error, a negative error value is returned. +*/ +int quic_do_setsockopt (struct sock *sk,int optname,sockptr_t optval, +unsigned int optlen) {return -EOPNOTSUPP ; } +EXPORT_SYMBOL_GPL (quic_do_setsockopt);static int quic_setsockopt (struct sock *sk,int level,int optname,sockptr_t optval,unsigned int optlen)
@@ -127,11 +141,25 @@ static int quic_setsockopt(struct sock *sk, int level, int optname,return quic_do_setsockopt (sk, optname, optval, optlen); } -static int quic_do_getsockopt (struct sock *sk,int optname,sockptr_t optval, -sockptr_t optlen) +/** +* quic_do_getsockopt - get a QUIC socket option +* @sk: socket to query +* @optname: option name (QUIC-level) +* @optval: user buffer to receive the option value +* @optlen: pointer to buffer size; updated with actual size on return +* +* Gets a QUIC socket option from a given socket. +* +* Return: +* - On success, 0 is returned. +* - On error, a negative error value is returned. +*/ +int quic_do_getsockopt (struct sock *sk,int optname,sockptr_t optval, +sockptr_t optlen) {return -EOPNOTSUPP ; } +EXPORT_SYMBOL_GPL (quic_do_getsockopt);static int quic_getsockopt (struct sock *sk,int level,int optname,char __user *optval,int __user *optlen)
net/quic/socket.h +1 -0
@@ -9,6 +9,7 @@*/ #include <net/udp_tunnel.h> +#include <linux/quic.h> #include "common.h" #include "family.h"
usr/include/Makefile +1 -0
@@ -31,6 +31,7 @@ no-header-test += linux/omap3isp.h no-header-test += linux/omapfb.h no-header-test += linux/patchkey.h no-header-test += linux/phonet.h +no-header-test += linux/quic.h no-header-test += linux/sctp.h no-header-test += linux/sysctl.h no-header-test += linux/usb/audio.h
Signature · 1 line
2.47.1
PATCH v13 6/15 quic: add stream management
In reply to Xin LongThis patch introduces 'struct quic_stream_table' for managing QUIC streams, each represented by 'struct quic_stream'.
It implements mechanisms for acquiring and releasing streams on both the send and receive paths, ensuring efficient lifecycle management during transmission and reception.
- quic_stream_get(): Acquire a send-side stream by ID and flags during TX path, or a receive-side stream by ID during RX path.
- quic_stream_put(): Release a send-side stream when sending is done, or a receive-side stream when receiving is done.
It includes logic to detect when stream ID limits are reached and when control frames should be sent to update or request limits from the peer.
- quic_stream_id_exceeds(): Check a stream ID would exceed local (recv) or peer (send) limits.
- quic_stream_max_streams_update(): Determines whether a MAX_STREAMS_UNI/BIDI frame should be sent to the peer.
Note stream hash table is per socket, the operations on it are always protected by the sock lock.
---
v3:
- Merge send/recv stream helpers into unified functions to reduce code:
* quic_stream_id_send/recv() → quic_stream_id_valid()
* quic_stream_id_send/recv_closed() → quic_stream_id_closed()
* quic_stream_id_send/recv_exceeds() → quic_stream_id_exceeds() (pointed out by Paolo).
- Clarify in changelog that stream hash table is always protected by sock lock (suggested by Paolo).
- quic_stream_init/free(): adjust for new hashtable type; call quic_stream_delete() in quic_stream_free() to avoid open-coded logic.
- Receiving streams: delete stream only when fully read or reset, instead of when no data was received. Prevents freeing a stream while a FIN with no data is still queued.
v4:
- Replace struct quic_shash_table with struct hlist_head for the stream hashtable. Since they are protected by the socket lock, no per-chain lock is needed.
- Initialize stream to NULL in stream creation functions to avoid warnings from Smatch (reported by Simon).
- Allocate send streams with GFP_KERNEL_ACCOUNT and receive streams with GFP_ATOMIC | __GFP_ACCOUNT for memory accounting (suggested by Paolo).
v5:
- Introduce struct quic_stream_limits to merge quic_stream_send_create() and quic_stream_recv_create(), and to simplify quic_stream_get_param() (suggested by Paolo).
- Annotate the sock-lock requirement for quic_stream_send/recv_get() and quic_stream_send/recv_put() (notied by Paolo).
- Add quic_stream_bidi_put() to deduplicate the common logic between quic_stream_send_put() and quic_stream_recv_put().
- Remove the unnecessary check when incrementing
streams->send.next_bidi/uni_stream_id in quic_stream_create().
- Remove the unused 'is_serv' parameter from quic_stream_get_param().
v7:
- Free the allocated streams on error path in quic_stream_create() (noted by Paolo).
- Merge quic_stream_send_get/put() and quic_stream_recv_get/put() helpers to quic_stream_get/put() (suggested by Paolo).
- Add more comments in quic_stream_id_exceeds() and quic_stream_create().
v8:
- Replace bitfields with plain u8 in struct quic_stream_limits and struct quic_stream (suggested by Paolo).
v9:
- Fix grammar in the comment for quic_stream::send.window.
v10:
- Move quic_stream_init() to after sock_prot_inuse_add() ensure counters are incremented before any early return paths in quic_init_sock(), preventing underflow in quic_destroy_sock() (noted by AI review).
- Initialize the output parameters '*max_uni' and '*max_bidi' to 0 at the start of quic_stream_max_streams_update()
- Use 'stream->recv.state > QUIC_STREAM_RECV_STATE_RECVD' instead of '!=' for clearer intent.
- Simplify some state checks in quic_stream_put() by using range
comparisons (> or <) instead of multiple != conditions.
- streams_uni/bidi are u16 type, and their overflow is already prevented by QUIC_MAX_STREAMS indirectly. Update comment in quic_stream_create().
- Replace open-coded kzalloc(sizeof(*stream)) with kzalloc_obj(*stream) in quic_stream_create().
v11:
- Set maximum line length to 80 characters.
- Change is_serv parameter type to bool in quic_stream_id_local().
v12:
- Skip the server-initiator bit in quic_stream_head().
- Return -ENOMEM if quic_stream_get() returns NULL in quic_stream_get().
- Release the stream in quic_stream_put() instead of waiting for all data to be read by users, and remove the no longer used done fields from struct quic_stream.
- Remove the extra MSG_QUIC_STREAM_NEW check for send streams and do it later in the caller, so the current check also applies to recv streams.
v13:
- Fix the comment for recv.max_uni/bidi_stream_id check in quic_stream_id_exceeds().
- Use kmalloc_objs() instead of kmalloc_array() in quic_stream_init().
--- net/quic/Makefile | 2 +- net/quic/socket.c | 5 + net/quic/socket.h | 8 + net/quic/stream.c | 416 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/stream.h | 131 +++++++++++++++ 5 files changed, 561 insertions(+), 1 deletion(-) create mode 100644 net/quic/stream.c create mode 100644 net/quic/stream.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o +quic-y := common.o family.o protocol.o socket.o stream.o
net/quic/socket.c +5 -0
@@ -49,11 +49,16 @@ static int quic_init_sock(struct sock *sk)sock_prot_inuse_add (sock_net (sk), sk->sk_prot,1 );INIT_LIST_HEAD (quic_reqs (sk)); +if (quic_stream_init (quic_streams (sk))) +return -ENOMEM ; +return 0 ; }static void quic_destroy_sock (struct sock *sk) { +quic_stream_free (quic_streams (sk)); +quic_data_free (quic_ticket (sk));quic_data_free (quic_token (sk));quic_data_free (quic_alpn (sk));
net/quic/socket.h +8 -0
@@ -13,6 +13,7 @@#include "common.h" #include "family.h" +#include "stream.h" #include "protocol.h"
@@ -33,6 +34,8 @@ struct quic_sock {struct quic_data ticket;struct quic_data token;struct quic_data alpn; + +struct quic_stream_table streams; };struct quic6_sock {
@@ -65,6 +68,11 @@ static inline struct quic_data *quic_alpn(const struct sock *sk)return &quic_sk (sk)->alpn; } +static inline struct quic_stream_table *quic_streams (const struct sock *sk) +{ +return &quic_sk (sk)->streams; +} +static inline bool quic_is_serv (const struct sock *sk) {return !!sk->sk_max_ack_backlog;
net/quic/stream.c new file +416 -0
416 lines not on this page · raw message
net/quic/stream.h new file +131 -0
131 lines not on this page · raw message
Signature · 1 line
2.47.1
Re: [PATCH net-next v13 06/15] quic: add stream management
[sashiko-claude]
Quoted 9 lines
net/quic/stream.c new file +9
-0+/* Get or create a send or recv stream by ID. Requires sock lock held. */ +struct quic_stream *quic_stream_get (struct quic_stream_table *streams, +s64 stream_id,u32 flags,bool is_serv, +bool send) +{ +struct quic_stream *stream; + +if (!quic_stream_id_valid (stream_id, is_serv, send)) +return ERR_PTR (-EINVAL );
net/quic/stream.c line 239
Quoted 10 lines
net/quic/stream.c new file +10
-0+ + stream =quic_stream_find (streams, stream_id); +if (stream) +return stream; + +if (!send &&quic_stream_id_local (stream_id, is_serv)) { +if (quic_stream_id_closed (streams, stream_id, !send)) +return ERR_PTR (-ENOSTR ); +return ERR_PTR (-EINVAL ); + }
The recv path here rejects stream IDs whose initiator does not match the caller's role (a server cannot accept a SERVER_BIDI on the recv path without it being closed/already-open). Should the send path have the symmetric guard for peer-initiated bidi stream IDs?
Walking through quic_stream_get() with is_serv=true, send=true, stream_id=4 (CLIENT_BIDI), flags=MSG_QUIC_STREAM_NEW:
- quic_stream_id_valid(4, true, true) only rejects CLIENT_UNI on the server send path, so CLIENT_BIDI passes.
- The !send && local block is skipped because send is true.
- quic_stream_id_closed() compares 4 < next_bidi_stream_id (initially SERVER_BIDI = 1) and returns false.
- quic_stream_id_exceeds() can pass when the peer's max_streams_bidi is non-trivial.
Control then reaches quic_stream_create():
Quoted 3 lines
+
stream_id=limits->next_bidi_stream_id;
+ if (quic_stream_id_uni(max_stream_id))
+stream_id=limits->next_uni_stream_id;
For a non-uni max_stream_id, stream_id is initialised from streams->send.next_bidi_stream_id (SERVER_BIDI = 1), so the loop creates a stream with id=1 instead of the requested id=4, increments streams->send.streams_bidi as if locally initiated, and advances streams->send.next_bidi_stream_id past 4.
This is a good catch, will add quic_stream_id_local() for send.
Thanks.
PATCH v13 7/15 quic: add connection id management
In reply to Xin LongThis patch introduces 'struct quic_conn_id_set' for managing Connection IDs (CIDs), which are represented by 'struct quic_source_conn_id' and 'struct quic_dest_conn_id'.
It provides helpers to add and remove CIDs from the set, and handles insertion of source CIDs into the global connection ID hash table when necessary.
- quic_conn_id_add(): Add a new Connection ID to the set, and inserts it to conn_id hash table if it is a source conn_id.
- quic_conn_id_remove(): Remove connection IDs the set with sequence numbers less than or equal to a number.
It also adds utilities to look up CIDs by value or sequence number, search the global hash table for incoming packets, and check for stateless reset tokens among destination CIDs. These functions are essential for RX path connection lookup and stateless reset processing.
- quic_conn_id_find(): Find a Connection ID in the set by seq number.
- quic_conn_id_lookup(): Lookup a Connection ID from global hash table using the ID value, typically used for socket lookup on the RX path.
- quic_conn_id_token_exists(): Check if a stateless reset token exists in any dest Connection ID (used during stateless reset processing).
Note source/dest conn_id set is per socket, the operations on it are always protected by the sock lock.
---
v3:
- Clarify in changelog that conn_id set is always protected by sock lock (suggested by Paolo).
- Adjust global source conn_id hashtable operations for the new hashtable type.
v4:
- Replace struct hlist_node with hlist_nulls_node for the node in struct quic_source_conn_id to support lockless lookup.
v7:
- Break the loop earlier if common->number > number in quic_conn_id_remove/find() (suggested by Paolo).
- Add a comment in quic_conn_id_first_number().
v8:
- Add a comment to quic_conn_id_remove() clarifying that the ID number must be smaller than the sequence number of the last ID in the set.
v11:
- Note for AI review: each id_set contains at most 8 connection IDs, so using an RB-tree for faster lookup is unnecessary.
- Set maximum line length to 80 characters.
- Add a check for number in quic_conn_id_remove().
v12:
- Add a comment in quic_conn_id_lookup() clarifying why a get_nulls_value() check is not needed.
- Do not match zero-valued tokens in quic_conn_id_token_exists().
- Update id_set->alt to the next entry when the current one is removed in quic_conn_id_remove().
- Call quic_conn_id_set_init() with true/false instead of 1/0 in
quic_init_sock(). --- net/quic/Makefile | 2 +- net/quic/connid.c | 256 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/connid.h | 182 ++++++++++++++++++++++++++++++++ net/quic/socket.c | 6 ++ net/quic/socket.h | 13 +++ 5 files changed, 458 insertions(+), 1 deletion(-) create mode 100644 net/quic/connid.c create mode 100644 net/quic/connid.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o
net/quic/connid.c new file +256 -0
256 lines not on this page · raw message
net/quic/connid.h new file +182 -0
182 lines not on this page · raw message
net/quic/socket.c +6 -0
@@ -49,6 +49,9 @@ static int quic_init_sock(struct sock *sk)sock_prot_inuse_add (sock_net (sk), sk->sk_prot,1 );INIT_LIST_HEAD (quic_reqs (sk)); +quic_conn_id_set_init (quic_source (sk), true); +quic_conn_id_set_init (quic_dest (sk), false); +if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
@@ -57,6 +60,9 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_conn_id_set_free (quic_source (sk)); +quic_conn_id_set_free (quic_dest (sk)); +quic_stream_free (quic_streams (sk));quic_data_free (quic_ticket (sk));
net/quic/socket.h +13 -0
@@ -14,6 +14,7 @@#include "common.h" #include "family.h" #include "stream.h" +#include "connid.h" #include "protocol.h"
@@ -36,6 +37,8 @@ struct quic_sock {struct quic_data alpn;struct quic_stream_table streams; +struct quic_conn_id_set source; +struct quic_conn_id_set dest; };struct quic6_sock {
@@ -73,6 +76,16 @@ static inline struct quic_stream_table *quic_streams(const struct sock *sk)return &quic_sk (sk)->streams; } +static inline struct quic_conn_id_set *quic_source (const struct sock *sk) +{ +return &quic_sk (sk)->source; +} + +static inline struct quic_conn_id_set *quic_dest (const struct sock *sk) +{ +return &quic_sk (sk)->dest; +} +static inline bool quic_is_serv (const struct sock *sk) {return !!sk->sk_max_ack_backlog;
Signature · 1 line
2.47.1
Paolo Abeni
maintainerRe: [PATCH net-next v13 07/15] quic: add connection id management
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
Now I have enough information to produce the report.
commit e00266d0eea858a744fd827548eb8ebc6868f92c
Author: Xin Long <[email protected]>
quic: add connection id management
This commit introduces struct quic_conn_id_set for managing QUIC Connection IDs along with helpers to add, remove, and look up source and destination CIDs, including a global hash table for source CID lookup on the RX path.
Quoted 34 lines
net/quic/connid.c new file +28
-0@@ -0,0 +1,256 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <linux/quic.h> +#include <net/sock.h> + +#include "common.h" +#include "connid.h" + +/* Lookup a source connection ID (scid) in the global source connection ID hash +* table. +*/ +struct quic_conn_id *quic_conn_id_lookup (struct net *net,u8 *scid,u32 len) +{ +struct quic_shash_head *head =quic_source_conn_id_head (net, scid, len); +struct quic_source_conn_id *s_conn_id; +struct quic_conn_id *conn_id =NULL ; +struct hlist_nulls_node *node; +
net/quic/connid.c line 38
Quoted 10 lines
net/quic/connid.c new file +10
-0+hlist_nulls_for_each_entry_rcu (s_conn_id, node, &head->head, node) { +if (net !=sock_net (s_conn_id->sk)) +continue ; +if (s_conn_id->common.id.len != len || +memcmp (scid, &s_conn_id->common.id.data, len)) +continue ; +if (likely (refcount_inc_not_zero (&s_conn_id->sk->sk_refcnt))) + conn_id = &s_conn_id->common.id; +break ; + }
[Critical]
Can s_conn_id->sk be freed while this RCU walk is running? The s_conn_id itself is freed via call_rcu() in quic_source_conn_id_free(), but the struct sock it points to does not appear to be RCU-protected.
A grep across this series for SOCK_RCU_FREE and SLAB_TYPESAFE_BY_RCU under net/quic returns no matches, and quic_init_sock() does not call sock_set_flag(sk, SOCK_RCU_FREE), so sk_destruct() will free the sock synchronously rather than after a grace period.
Consider this sequence:
CPU0 (RX path, rcu_read_lock held) CPU1 (close path)
hlist_nulls_for_each_entry_rcu(..)
/* sees s_conn_id still linked */
sk_destruct()
quic_destroy_sock()
quic_conn_id_set_free()
/* unhash + call_rcu
defers s_conn_id
free, but not sk */
sk_prot_free() /* sk gone */
sock_net(s_conn_id->sk) /* UAF read of freed sock */
refcount_inc_not_zero(
&s_conn_id->sk->sk_refcnt) /* UAF refcount op */Once quic_packet_get_sock() (in the later 'quic: add packet parser base' patch) wires this lookup into every short- and long-header packet, an incoming packet racing with close() on the matching socket would dereference freed sock memory.
Would setting SOCK_RCU_FREE on the QUIC sockets, switching the proto slabs to SLAB_TYPESAFE_BY_RCU, taking sock_hold() when the sk pointer is stored in s_conn_id, or otherwise gating the sk free behind an RCU grace period address this?
Quoted 14 lines
net/quic/connid.c new file +14
-0+ +/* Check if a given stateless reset token exists in any connection ID in the +* connection ID set. +*/ +bool quic_conn_id_token_exists (struct quic_conn_id_set *id_set,u8 *token) +{ +struct quic_common_conn_id *common; +struct quic_dest_conn_id *dcid; + + dcid = (struct quic_dest_conn_id *)id_set->active; +if (memchr_inv (dcid->token,0 ,QUIC_CONN_ID_TOKEN_LEN ) && + !memcmp (dcid->token, token,QUIC_CONN_ID_TOKEN_LEN )) +return true;/* Fast path. */ +
net/quic/connid.c line 67
Quoted 10 lines
net/quic/connid.c new file +10
-0+list_for_each_entry (common, &id_set->head, list) { + dcid = (struct quic_dest_conn_id *)common; +if (common == id_set->active) +continue ; +if (memchr_inv (dcid->token,0 ,QUIC_CONN_ID_TOKEN_LEN ) && + !memcmp (dcid->token, token,QUIC_CONN_ID_TOKEN_LEN )) +return true; + } +return false; +}
[Medium]
Is memcmp() the right comparison primitive for the stateless reset token here? RFC 9000 section 10.3 treats the token as a secret that authorises tearing down a connection, and the commit message states this helper is used during stateless reset processing on incoming packets.
lib/string.c's memcmp() returns at the first differing byte (and performs unaligned word-sized loads on architectures that allow it), so the time taken to return false leaks how many leading bytes of the supplied token match a stored token. Would crypto_memneq() from <crypto/algapi.h>, which is constant-time, be more appropriate for comparing the token bytes?
Quoted 1 line
net/quic/connid.c new file +1
-0+
[ ... ]
Quoted 6 lines
net/quic/connid.c new file +6
-0+/* Add a connection ID with sequence number and associated private data to the +* connection ID set. +*/ +int quic_conn_id_add (struct quic_conn_id_set *id_set, +struct quic_conn_id *conn_id,u32 number,void *data) +{
[ ... ]
Quoted 10 lines
net/quic/connid.c new file +10
-0+/* Locate insertion point to keep list ordered by number. */ + list = &id_set->head; +list_for_each_entry (common, list, list) { +if (number == common->number) +return 0 ;/* Ignore if it already exists on the list. */ +if (number < common->number) { + list = &common->list; +break ; + } + }
[ ... ]
Quoted 6 lines
net/quic/connid.c new file +6
-0+list_add_tail (&common->list, list); + +if (number ==quic_conn_id_last_number (id_set) +1 ) { +if (!id_set->active) + id_set->active = common; + id_set->count++;
net/quic/connid.c line 175
Quoted 10 lines
net/quic/connid.c new file +10
-0+ +/* Increment count for consecutive following IDs. */ +list_for_each_entry_continue (common, &id_set->head, list) { +if (common->number != ++number) +break ; + id_set->count++; + } + } +return 0 ; +}
[Medium]
Does this function correctly maintain id_set->count when a CID is inserted before all existing entries? The loop above explicitly handles the "number < common->number" case, suggesting out-of-order insertion is intended to be supported.
Consider starting from list=[5], count=1 (so first=5, last=5) and calling quic_conn_id_add(..., number=3, ...):
- The location loop sets list = &common(5)->list and breaks.
- list_add_tail() inserts common(3) before common(5),
yielding list=[3, 5].
- The post-insert check evaluates:
quic_conn_id_last_number(id_set)
= quic_conn_id_first_number(id_set) + count - 1
= 3 + 1 - 1
= 3
so the test "number == last + 1" becomes "3 == 4" and the count
update branch is skipped.The end state is list=[3, 5] with count still 1, so entry 5 is silently uncounted. A subsequent quic_conn_id_remove(id_set, 3) then trips the WARN_ON_ONCE(number >= last_number) because last_number reads as 3.
Should the count adjustment also handle the case where the inserted CID lowers first_number?
Quoted 5 lines
net/quic/connid.c new file +5
-0+ +/* Remove consecutive connection IDs from the set with sequence numbers less +* than or equal to a number. +*/ +void quic_conn_id_remove (struct quic_conn_id_set *id_set,u32 number)
[ ... ]
Signature · 1 line
This is an AI-generated review.
Re: [PATCH net-next v13 07/15] quic: add connection id management
Quoted 95 lines · Paolo Abeni
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
Now I have enough information to produce the report.commit
e00266d0eea858a744fd827548eb8ebc6868f92c
Author: Xin Long <[email protected]>quic: add connection id management
This commit introduces struct
quic_conn_id_setfor managing QUIC Connection IDs along with helpers to add, remove, and look up source and destination CIDs, including a global hash table for source CID lookup on the RX path.Quoted 34 lines
net/quic/connid.c new file +28
-0@@ -0,0 +1,256 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <linux/quic.h> +#include <net/sock.h> + +#include "common.h" +#include "connid.h" + +/* Lookup a source connection ID (scid) in the global source connection ID hash +* table. +*/ +struct quic_conn_id *quic_conn_id_lookup (struct net *net,u8 *scid,u32 len) +{ +struct quic_shash_head *head =quic_source_conn_id_head (net, scid, len); +struct quic_source_conn_id *s_conn_id; +struct quic_conn_id *conn_id =NULL ; +struct hlist_nulls_node *node; +net/quic/connid.c line 38
Quoted 10 lines
net/quic/connid.c new file +10
-0+hlist_nulls_for_each_entry_rcu (s_conn_id, node, &head->head, node) { +if (net !=sock_net (s_conn_id->sk)) +continue ; +if (s_conn_id->common.id.len != len || +memcmp (scid, &s_conn_id->common.id.data, len)) +continue ; +if (likely (refcount_inc_not_zero (&s_conn_id->sk->sk_refcnt))) + conn_id = &s_conn_id->common.id; +break ; + }[Critical]
Cans_conn_id->skbe freed while this RCU walk is running? Thes_conn_iditself is freed viacall_rcu()inquic_source_conn_id_free(), but the struct sock it points to does not appear to be RCU-protected.A grep across this series for
SOCK_RCU_FREEandSLAB_TYPESAFE_BY_RCUunder net/quic returns no matches, andquic_init_sock()does not callsock_set_flag(sk, SOCK_RCU_FREE), sosk_destruct()will free the sock synchronously rather than after a grace period.Consider this sequence:
CPU0 (RX path,
rcu_read_lockheld) CPU1 (close path)
hlist_nulls_for_each_entry_rcu(..)/* sees s_conn_id still linked */ sk_destruct() quic_destroy_sock() quic_conn_id_set_free() /* unhash + call_rcu defers s_conn_id free, but not sk */ sk_prot_free() /* sk gone */ sock_net(s_conn_id->sk) /* UAF read of freed sock */ refcount_inc_not_zero( &s_conn_id->sk->sk_refcnt) /* UAF refcount op */Once
quic_packet_get_sock()(in the later 'quic: add packet parser base' patch) wires this lookup into every short- and long-header packet, an incoming packet racing withclose()on the matching socket would dereference freed sock memory.
Quoted 5 lines
Would setting
SOCK_RCU_FREEon the QUIC sockets, switching the proto slabs toSLAB_TYPESAFE_BY_RCU, takingsock_hold()when the sk pointer is stored ins_conn_id, or otherwise gating the sk free behind an RCU grace period address this?
This is not an issue, as sock_set_flag(sk, SOCK_RCU_FREE) will be called in quic_hash(), which will be added in the patchset-2.
Quoted 32 lines
Quoted 14 lines
net/quic/connid.c new file +14
-0+ +/* Check if a given stateless reset token exists in any connection ID in the +* connection ID set. +*/ +bool quic_conn_id_token_exists (struct quic_conn_id_set *id_set,u8 *token) +{ +struct quic_common_conn_id *common; +struct quic_dest_conn_id *dcid; + + dcid = (struct quic_dest_conn_id *)id_set->active; +if (memchr_inv (dcid->token,0 ,QUIC_CONN_ID_TOKEN_LEN ) && + !memcmp (dcid->token, token,QUIC_CONN_ID_TOKEN_LEN )) +return true;/* Fast path. */ +net/quic/connid.c line 67
Quoted 10 lines
net/quic/connid.c new file +10
-0+list_for_each_entry (common, &id_set->head, list) { + dcid = (struct quic_dest_conn_id *)common; +if (common == id_set->active) +continue ; +if (memchr_inv (dcid->token,0 ,QUIC_CONN_ID_TOKEN_LEN ) && + !memcmp (dcid->token, token,QUIC_CONN_ID_TOKEN_LEN )) +return true; + } +return false; +}[Medium]
Ismemcmp()the right comparison primitive for the stateless reset token here? RFC 9000 section 10.3 treats the token as a secret that authorises tearing down a connection, and the commit message states this helper is used during stateless reset processing on incoming packets.
Quoted 7 lines
lib/string.c's
memcmp()returns at the first differing byte (and performs unaligned word-sized loads on architectures that allow it), so the time taken to return false leaks how many leading bytes of the supplied token match a stored token. Wouldcrypto_memneq()from <crypto/algapi.h>, which is constant-time, be more appropriate for comparing the token bytes?
OK, will change to crypto_memneq() and replace 4 similar places.
Quoted 57 lines
Quoted 1 line
net/quic/connid.c new file +1
-0+[ ... ]
Quoted 6 lines
net/quic/connid.c new file +6
-0+/* Add a connection ID with sequence number and associated private data to the +* connection ID set. +*/ +int quic_conn_id_add (struct quic_conn_id_set *id_set, +struct quic_conn_id *conn_id,u32 number,void *data) +{[ ... ]
Quoted 10 lines
net/quic/connid.c new file +10
-0+/* Locate insertion point to keep list ordered by number. */ + list = &id_set->head; +list_for_each_entry (common, list, list) { +if (number == common->number) +return 0 ;/* Ignore if it already exists on the list. */ +if (number < common->number) { + list = &common->list; +break ; + } + }[ ... ]
Quoted 6 lines
net/quic/connid.c new file +6
-0+list_add_tail (&common->list, list); + +if (number ==quic_conn_id_last_number (id_set) +1 ) { +if (!id_set->active) + id_set->active = common; + id_set->count++;net/quic/connid.c line 175
Quoted 10 lines
net/quic/connid.c new file +10
-0+ +/* Increment count for consecutive following IDs. */ +list_for_each_entry_continue (common, &id_set->head, list) { +if (common->number != ++number) +break ; + id_set->count++; + } + } +return 0 ; +}[Medium]
Does this function correctly maintainid_set->countwhen a CID is inserted before all existing entries? The loop above explicitly handles the "number <common->number" case, suggesting out-of-order insertion is intended to be supported.Consider starting from list=[5], count=1 (so first=5, last=5) and calling
quic_conn_id_add(..., number=3, ...):- The location loop sets list = &common(5)->list and breaks.
-list_add_tail()inserts common(3) before common(5),yielding list=[3, 5]. - The post-insert check evaluates: quic_conn_id_last_number(id_set) = quic_conn_id_first_number(id_set) + count - 1 = 3 + 1 - 1 = 3 so the test "number == last + 1" becomes "3 == 4" and the count update branch is skipped.
Quoted 2 lines
The end state is list=[3, 5] with count still 1, so entry 5 is silently uncounted.
This is expected, count only count contiguous connection IDs.
Quoted 4 lines
A subsequent
quic_conn_id_remove(id_set, 3)
then trips theWARN_ON_ONCE(number >= last_number)becauselast_numberreads as 3.
This will never happen, the callers will prevent passing the last seqno to quic_conn_id_remove().
Thanks.
Quoted 12 lines
Should the count adjustment also handle the case where the inserted CID lowers
first_number?net/quic/connid.c line 180
Quoted 5 lines
net/quic/connid.c new file +5
-0+ +/* Remove consecutive connection IDs from the set with sequence numbers less +* than or equal to a number. +*/ +void quic_conn_id_remove (struct quic_conn_id_set *id_set,u32 number)[ ... ]
--
This is an AI-generated review.
PATCH v13 8/15 quic: add path management
In reply to Xin LongThis patch introduces 'quic_path_group' for managing paths, represented by 'struct quic_path'. A connection may use two paths simultaneously for connection migration.
Each path is associated with a UDP tunnel socket (sk), and a single UDP tunnel socket can be related to multiple paths from different sockets. These UDP tunnel sockets are wrapped in 'quic_udp_sock' structures and stored in a hash table.
It includes mechanisms to bind and unbind paths, detect alternative paths for migration, and swap paths to support seamless transition between networks.
- quic_path_bind(): Bind a path to a port and associate it with a UDP sk.
- quic_path_unbind(): Unbind a path from a port and disassociate it from a UDP sk.
- quic_path_swap(): Swap two paths to facilitate connection migration.
- quic_path_detect_alt(): Determine if a packet is using an alternative path, used for connection migration.
It also integrates basic support for Packetization Layer Path MTU
Discovery (PLPMTUD), using PING frames and ICMP feedback to adjust path MTU and handle probe confirmation or resets during routing changes.
- quic_path_pl_recv(): state transition and pmtu update after the probe packet is acked.
- quic_path_pl_toobig(): state transition and pmtu update after receiving a toobig or needfrag icmp packet.
- quic_path_pl_send(): state transition and pmtu update after sending a probe packet.
- quic_path_pl_reset(): restart the probing when path routing changes.
- quic_path_pl_confirm(): check if probe packet gets acked.
---
v3:
- Fix annotation in quic_udp_sock_lookup() (noted by Paolo).
- Use inet_sk_get_local_port_range() instead of inet_get_local_port_range() (suggested by Paolo).
- Adjust global UDP tunnel socket hashtable operations for the new hashtable type.
- Delete quic_workqueue; use system_wq for UDP tunnel socket destroy.
v4:
- Cache UDP tunnel socket pointer and its source address in struct quic_path for RCU-protected lookup/access.
- Return -EAGAIN instead of -EINVAL in quic_path_bind() when UDP socket is being released in workqueue.
- Move udp_tunnel_sock_release() out of the mutex_lock to avoid a warning of lockdep in quic_udp_sock_put_work().
- Introduce quic_wq for UDP socket release work, so all pending works can be flushed before destroying the hashtable in quic_exit().
v5:
- Rename quic_path_free() to quic_path_unbind() (suggested by Paolo).
- Remove the 'serv' member from struct quic_path_group, since quic_is_serv() defined in a previous patch now uses sk->sk_max_ack_backlog for server-side detection.
- Use quic_ktime_get_us() to set skb_cb->time, as RTT is measured in microseconds and jiffies_to_usecs() is not accurate enough.
v6:
- Do not reset transport_header for QUIC in quic_udp_rcv(), allowing
removal of udph_offset and enabling access to the UDP header via
udp_hdr(); Pull skb->data in quic_udp_rcv() to allow access to the
QUIC header via skb->data.v7:
- Pass udp sk to quic_path_rcv() and move the call to skb_linearize() and skb_set_owner_sk_safe() to .quic_path_rcv().
- Delete the call to skb_linearize() and skb_set_owner_sk_safe() from quic_udp_err(), as it should not change skb in .encap_err_lookup() (noted by AI review).
v8:
- Remove indirect quic_path_rcv and late call quic_packet_rcv() directly via extern (noted by Paolo).
- Add a comment in quic_udp_rcv() clarifying it must return 0.
- Add a comment in quic_udp_sock_put() clarifying the UDP socket may be freed in atomic RX context during connection migration.
- Reorder some quic_path_group members to reduce struct size.
v10:
- Replace open-coded kzalloc(sizeof(*us)) with kzalloc_obj(*us) in quic_stream_create().
- Use get_random_u32_below() for ephemeral port selection instead of manual scaling of get_random_u32() in quic_path_bind().
- Reset additional PLPMTUD probe state (probe_high, probe_count) in quic_path_pl_reset() to ensure a clean probe restart.
- Add plpmtud_interval to struct quic_path_group to store the PLPMTUD probe timer interval, previously kept in struct quic_sock.config.
v11:
- Set maximum line length to 80 characters.
- Add additional comments in quic_path_bind() and quic_path_pl_send() for clarity.
- Return ERR_PTR() instead of NULL on error in quic_udp_sock_create().
- Change return type of quic_path_detect_alt() to bool.
- Allocate quic_wq using alloc_workqueue(WQ_MEM_RECLAIM | WQ_UNBOUND) for UDP socket destruction and backlog packet processing (noted by AI review).
v12:
- Call quic_set_skb_iif() at the start of quic_udp_rcv().
- Set us->bind_ifindex from udp_conf.bind_ifindex instead of
sk->sk_bound_dev_if in quic_udp_sock_create().
- Compare us->bind_ifindex against quic_get_dev_if(sk, a) instead of
sk->sk_bound_dev_if, and do not match when only one is zero in
quic_udp_sock_lookup().
- Call cond_resched() in the retry loop of quic_path_bind() when
quic_udp_sock_create() returns -EADDRINUSE.
- Improve address-change handling and disable_saddr/daddr_alt checks
in quic_path_detect_alt().
- Do not pass WQ_MEM_RECLAIM to alloc_workqueue() to avoid a potential
deadlock.
- Change ampl_snd/rcvlen in struct quic_path_group to u32 to avoid
overflow, and move mtu_info for a better layout.
- Add keepalive_interval to struct quic_path_group to control path
liveness probing, and add version to indicate version negotiation
was performed.
- Pass sk instead of sk_socket to setup_udp_tunnel_sock() and
udp_tunnel_sock_release(), following their parameter type changes.
- Set bit fields paths->disable_saddr_alt and paths->disable_daddr_alt
from p->disable_active_migration using '!!'. - Add QUIC_PMTUD_RAISE_TIMER_FACTOR for later use.
- Change QUIC_PATH_MAX_PMTU from 65536U to 65535U.
v13:
- Drop explicit GFP_KERNEL from kzalloc_obj() in quic_udp_sock_create().
--- net/quic/Makefile | 2 +- net/quic/path.c | 568 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/path.h | 188 +++++++++++++++ net/quic/protocol.c | 14 ++ net/quic/socket.c | 3 + net/quic/socket.h | 7 + 6 files changed, 781 insertions(+), 1 deletion(-) create mode 100644 net/quic/path.c create mode 100644 net/quic/path.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o
net/quic/path.c new file +568 -0
568 lines not on this page · raw message
net/quic/path.h new file +188 -0
188 lines not on this page · raw message
net/quic/protocol.c +14 -0
@@ -21,6 +21,7 @@static unsigned int quic_net_id__read_mostly ;struct percpu_counter quic_sockets_allocated; +struct workqueue_struct *quic_wq;DEFINE_STATIC_KEY_FALSE (quic_alpn_demux_key);
@@ -342,6 +343,15 @@ static __init int quic_init(void)if (err) goto err_hash; +/* Allocate an unbound workqueue for UDP socket destruction and backlog +* packet processing. +*/ + quic_wq =alloc_workqueue ("quic_workqueue" ,WQ_UNBOUND ,0 ); +if (!quic_wq) { + err = -ENOMEM ; + goto err_wq; + } + err =register_pernet_subsys (&quic_net_ops);if (err) goto err_def_ops;
@@ -359,6 +369,8 @@ static __init int quic_init(void) err_protosw:unregister_pernet_subsys (&quic_net_ops); err_def_ops: +destroy_workqueue (quic_wq); +err_wq:quic_hash_tables_destroy (); err_hash:percpu_counter_destroy (&quic_sockets_allocated);
@@ -373,6 +385,8 @@ static __exit void quic_exit(void)#endif quic_protosw_exit ();unregister_pernet_subsys (&quic_net_ops); +flush_workqueue (quic_wq); +destroy_workqueue (quic_wq);quic_hash_tables_destroy ();percpu_counter_destroy (&quic_sockets_allocated);pr_info ("quic: exit\n" );
net/quic/socket.c +3 -0
@@ -60,6 +60,9 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_path_unbind (sk,quic_paths (sk),0 ); +quic_path_unbind (sk,quic_paths (sk),1 ); +quic_conn_id_set_free (quic_source (sk));quic_conn_id_set_free (quic_dest (sk));
net/quic/socket.h +7 -0
@@ -15,6 +15,7 @@#include "family.h" #include "stream.h" #include "connid.h" +#include "path.h" #include "protocol.h"
@@ -39,6 +40,7 @@ struct quic_sock {struct quic_stream_table streams;struct quic_conn_id_set source;struct quic_conn_id_set dest; +struct quic_path_group paths; };struct quic6_sock {
@@ -86,6 +88,11 @@ static inline struct quic_conn_id_set *quic_dest(const struct sock *sk)return &quic_sk (sk)->dest; } +static inline struct quic_path_group *quic_paths (const struct sock *sk) +{ +return &quic_sk (sk)->paths; +} +static inline bool quic_is_serv (const struct sock *sk) {return !!sk->sk_max_ack_backlog;
Signature · 1 line
2.47.1
PATCH v13 9/15 quic: add congestion control
In reply to Xin LongThis patch introduces 'quic_cong' for RTT measurement and congestion control. The 'quic_cong_ops' is added to define the congestion control algorithm.
It implements a congestion control state machine with slow start, congestion avoidance, and recovery phases, and currently introduces the New Reno algorithm only.
The implementation updates RTT estimates when packets are acknowledged, reacts to loss and ECN signals, and adjusts the congestion window accordingly during packet transmission and acknowledgment processing.
- quic_cong_rtt_update(): Performs RTT measurement, invoked when a packet is acknowledged by the largest number in the ACK frame.
- quic_cong_on_packet_acked(): Invoked when a packet is acknowledged.
- quic_cong_on_packet_lost(): Invoked when a packet is marked as lost.
- quic_cong_on_process_ecn(): Invoked when an ACK_ECN frame is received.
- quic_cong_on_packet_sent(): Invoked when a packet is transmitted.
- quic_cong_on_ack_recv(): Invoked when an ACK frame is received.
---
v4:
- Remove the CUBIC congestion algorithm support for this version (suggested by Paolo).
v5:
- Do not update the pacing rate when !cong->smoothed_rtt in quic_cong_pace_update() (suggested by Paolo).
- Change timestamp variables from u32 to u64, as RTT is measured in microseconds and u64 provides sufficient precision for timestamps in microsecond.
v8:
- Add a comment in quic_reno_on_packet_acked() clarifying cong->window is never zero (noted by AI review).
v9:
- Use abs_diff() to simplify RTT variance calculation (noted by AI review).
- Fix a small typo in the comment for struct quic_cong::time (noted by AI review).
- Fix another small typo in quic_cong_check_persistent_congestion().
v10:
- Note for AI reviews: cong->time will always be set before processing the packet on the RX path in the future patch series.
- Add initial_srtt and algo to struct quic_cong to store the initial smoothed RTT and congestion control algorithm, previously kept in quic_sock.config.
v11:
- Note for AI reviews: later patches guarantee cong->time is set before any quic_cong function uses it.
- Note for AI reviews: RFC 9002 section 5.3 does NOT specify that rttvar_sample must use the previous smoothed_rtt value.
- Set maximum line length to 80 characters.
- Change return type of quic_cong_check_persistent_congestion() to bool.
- Add a check for algo in quic_cong_set_algo().
- Extract quic_reno_handle_packet_lost() from quic_reno_on_packet_lost() and quic_reno_on_process_ecn() (noted by AI review).
v12:
- Delete the unnecessary WRITE_ONCE() and READ_ONCE() for
cong->pacing_rate, as it's always used under sock lock.
- Set cong->max_window to S32_MAX / 4 instead of S32_MAX / 2.
- Add pc_start_time in struct quic_cong to track persistent congestion
start time more precisely and improve persistent congestion detection;
move its handling into quic_cong_on_packet_lost() and
quic_cong_on_packet_acked().
---
net/quic/Makefile | 3 +-
net/quic/cong.c | 333 ++++++++++++++++++++++++++++++++++++++++++++++
net/quic/cong.h | 130 ++++++++++++++++++
net/quic/socket.c | 1 +
net/quic/socket.h | 7 +
5 files changed, 473 insertions(+), 1 deletion(-)
create mode 100644 net/quic/cong.c
create mode 100644 net/quic/cong.hnet/quic/Makefile +2 -1
@@ -5,4 +5,5 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ + cong.o
net/quic/cong.c new file +333 -0
333 lines not on this page · raw message
net/quic/cong.h new file +130 -0
130 lines not on this page · raw message
net/quic/socket.c +1 -0
@@ -51,6 +51,7 @@ static int quic_init_sock(struct sock *sk)quic_conn_id_set_init (quic_source (sk), true);quic_conn_id_set_init (quic_dest (sk), false); +quic_cong_init (quic_cong (sk));if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
net/quic/socket.h +7 -0
@@ -16,6 +16,7 @@#include "stream.h" #include "connid.h" #include "path.h" +#include "cong.h" #include "protocol.h"
@@ -41,6 +42,7 @@ struct quic_sock {struct quic_conn_id_set source;struct quic_conn_id_set dest;struct quic_path_group paths; +struct quic_cong cong; };struct quic6_sock {
@@ -98,6 +100,11 @@ static inline bool quic_is_serv(const struct sock *sk)return !!sk->sk_max_ack_backlog; } +static inline struct quic_cong *quic_cong (const struct sock *sk) +{ +return &quic_sk (sk)->cong; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
Re: [PATCH net-next v13 09/15] quic: add congestion control
[sashiko-gemini]
Quoted 5 lines
+ case
QUIC_CONG_CONGESTION_AVOIDANCE:
+ /*cong->windowis never zero; it is initialized by
+ *quic_packet_route()during connect/accept.
+ */
+cong->window+=cong->mss* bytes /cong->window;
Can this arithmetic permanently stall congestion window growth or cause an overflow? Since all variables are 32-bit integers, the division could truncate to 0 as the window grows larger than cong->mss * bytes. Also, if bytes is large due to coalesced ACKs, could the multiplication wrap around U32_MAX?
This looks a legit one, will confirm and fix it.
Thanks.
PATCH v13 10/15 quic: add packet number space
In reply to Xin LongThis patch introduces 'quic_pnspace', which manages per packet number space members.
It maintains the next packet number to assign, tracks the total length of frames currently in flight, and records the time when the next packet may be considered lost. It also keeps track of the largest acknowledged packet number, the time it was acknowledged, and when the most recent ack eliciting packet was sent. These fields are useful for loss detection, RTT estimation, and congestion control.
To support ACK frame generation, quic_pnspace includes a packet number acknowledgment map (pn_ack_map) that tracks received packet numbers. Supporting functions are provided to validate and mark received packet numbers and compute the number of gap blocks needed during ACK frame construction.
- quic_pnspace_check(): Validates a received packet number.
- quic_pnspace_mark(): Marks a received packet number in the ACK map.
- quic_pnspace_num_gabs(): Returns the gap ACK blocks for constructing ACK frames.
Note QUIC uses separate packet number spaces for each encryption level (APP, INITIAL, HANDSHAKE, EARLY) except EARLY and all generations of APP keys use the same packet number space, as describe in rfc9002#section-4.1.
---
v5:
- Change timestamp variables from u32 to u64 and use quic_ktime_get_us() to set max_pn_acked_time, as jiffies_to_usecs() is not accurate enough.
- Reorder some members in quic_pnspace to reduce 32-bit holes (noted by Paolo).
v6:
- Note for AI reviews: it's safe to do cast (u16)(pn - space->base_pn) in quic_pnspace_mark(), as the pn < base_pn + QUIC_PN_MAP_SIZE (4096) validation is always done in quic_pnspace_check(), which will always be called before quic_pnspace_mark() in a later patchset.
- Note for AI reviews: failures in quic_pnspace_init() do not result in a pn_map leak in quic_init_sock(), because quic_destroy_sock() is always called to free it in err path, either via inet/6_create() or through quic_accept() in a later patchset.
v8:
- Replace bitfields with plain u8 in struct quic_pnspace.
v10:
- Fix a grammar error in the comment of quic_pnspace_check().
v11:
- Note for AI reviews: RFC 9000 does not define integer IDs for packet number spaces. In this implementation, App=0, Initial=1, Handshake=2, and Early maps to 0 (3 % 3).
- Set maximum line length to 80 characters.
- clear space->pn_map pointer after free in quic_pnspace_free().
- Change quic_pnspace_grow() to return negative errno on failure or 0 on success.
- Change return type of quic_pnspace_next_gap_ack() and quic_pnspace_set_ecn_count() to bool.
- Return -EINVAL instead of -1 on failure in quic_pnspace_check().
v12:
- Initialize max_pn_acked_seen to -1 in quic_pnspace_init().
- Allow large packet number jumps when processing higher PN values (>= base_pn + QUIC_PN_MAP_SIZE) in quic_pnspace_check(), quic_pnspace_mark(), and quic_pnspace_grow().
- Call quic_pnspace_has_gap() before updating max_pn_seen in quic_pnspace_mark().
- Rename ECN-related helpers:
quic_pnspace_set_ecn_count() -> quic_pnspace_set_ecn_peer(),
quic_pnspace_has_ecn_count() -> quic_pnspace_has_ecn_local(),
quic_pnspace_inc_ecn_count() -> quic_pnspace_inc_ecn_local().
- Add QUIC_ECN_ACKED and introduce quic_pnspace_inc_ecn_acked(),
quic_pnspace_reset_ecn_acked(), and quic_pnspace_validate_ecn() for
validating ECN counts in ACKs.
- Add sack_pending field in struct quic_pnspace for later use in sack
piggybacking.
---
net/quic/Makefile | 2 +-
net/quic/pnspace.c | 253 +++++++++++++++++++++++++++++++++++++++++++++
net/quic/pnspace.h | 201 +++++++++++++++++++++++++++++++++++
net/quic/socket.c | 12 +++
net/quic/socket.h | 7 ++
5 files changed, 474 insertions(+), 1 deletion(-)
create mode 100644 net/quic/pnspace.c
create mode 100644 net/quic/pnspace.hnet/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o + cong.o pnspace.o
net/quic/pnspace.c new file +253 -0
253 lines not on this page · raw message
net/quic/pnspace.h new file +201 -0
201 lines not on this page · raw message
net/quic/socket.c +12 -0
@@ -42,6 +42,8 @@ static void quic_write_space(struct sock *sk)static int quic_init_sock (struct sock *sk) { +u8 i; + sk->sk_write_space = quic_write_space;sock_set_flag (sk,SOCK_USE_WRITE_QUEUE );
@@ -56,11 +58,21 @@ static int quic_init_sock(struct sock *sk)if (quic_stream_init (quic_streams (sk)))return -ENOMEM ; +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++) { +if (quic_pnspace_init (quic_pnspace (sk, i))) +return -ENOMEM ; + } +return 0 ; }static void quic_destroy_sock (struct sock *sk) { +u8 i; + +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++) +quic_pnspace_free (quic_pnspace (sk, i)); +quic_path_unbind (sk,quic_paths (sk),0 );quic_path_unbind (sk,quic_paths (sk),1 );
net/quic/socket.h +7 -0
@@ -12,6 +12,7 @@#include <linux/quic.h> #include "common.h" +#include "pnspace.h" #include "family.h" #include "stream.h" #include "connid.h"
@@ -43,6 +44,7 @@ struct quic_sock {struct quic_conn_id_set dest;struct quic_path_group paths;struct quic_cong cong; +struct quic_pnspace space[QUIC_PNSPACE_MAX ]; };struct quic6_sock {
@@ -105,6 +107,11 @@ static inline struct quic_cong *quic_cong(const struct sock *sk)return &quic_sk (sk)->cong; } +static inline struct quic_pnspace *quic_pnspace (const struct sock *sk,u8 level) +{ +return &quic_sk (sk)->space[level %QUIC_CRYPTO_EARLY ]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v13 11/15 quic: add crypto key derivation and installation
In reply to Xin LongThis patch introduces 'quic_crypto', a component responsible for QUIC encryption key derivation and installation across the various key
levels: Initial, Handshake, 0-RTT (Early), and 1-RTT (Application).
It provides helpers to derive and install initial secrets, set traffic secrets and install the corresponding keys, and perform key updates to enable forward secrecy. Additionally, it implements stateless reset token generation, used to support connection reset without state.
- quic_crypto_initial_keys_install(): Derive and install initial keys.
- quic_crypto_set_cipher(): Allocate all transforms based on the cipher type provided.
- quic_crypto_set_secret(): Set the traffic secret and install derived keys.
- quic_crypto_key_update(): Rekey and install new keys to the !phase side.
- quic_crypto_generate_stateless_reset_token(): Generate token for stateless reset.
These mechanisms are essential for establishing and maintaining secure communication throughout the QUIC connection lifecycle.
---
v3:
- Remove lock from quic_net, since Initial packet decryption for ALPN will be handled serially in a workqueue when ALPN demux is enabled.
v4:
- Use local cipher pointer in quic_crypto_set_secret() to avoid a warning from Smatch.
v5:
- Change the timestamp variables from u32 to u64, which provides sufficient precision for timestamps in microsecond.
v8:
- Remove the redundant err initialization in quic_net_init(), since err is now assigned from quic_crypto_set_cipher().
v10:
- Fix header protection key passed to pr_debug().
- Fix typo: "For example,to ..." -> "For example, to ..." in comment.
- Remove redundant initialization of err in quic_crypto_set_cipher().
v11:
- Note for AI reviews: later patches guarantee all tfms (including secret_tfm) are set before any quic_crypto function uses them.
- Set maximum line length to 80 characters.
- Merge quic_crypto_rx/tx_keys_derive_and_install() to quic_crypto_keys_derive_and_install() with an extra parameter to reduce code duplication (noted by AI review).
- Change flag parameter type to u32 in quic_crypto_set_secret() and quic_crypto_set_cipher().
v12:
- Remove the unused hash parameter from quic_crypto_hkdf_expand() and update all callers.
- Use put_unaligned_be16() instead of open-coding the conversion in quic_crypto_hkdf_expand().
- Pass the key phase to quic_crypto_keys_derive_and_install() and update
its callers; do not modify crypto->key_pending when invoking it from
quic_crypto_key_update(). - Update comments for tx_secret and rx_secret in struct quic_crypto.
- Add async_pending to struct quic_crypto to indicate when no async crypto operations are pending, enabling key updates in a later patch.
- Add quic_sock_destruct() to free crypto resources at the last moment.
- Remove quic_crypto_get_secret(), as userspace is no longer allowed to access secret information.
- Remove the flag parameter from quic_crypto_set_secret() and quic_crypto_set_cipher(); all AEAD TFMs are now allocated in async mode, and crypto_wait will be used for synchronous mode later.
- Remove tag_tfm from struct quic_crypto; use tx/rx_tfm[1] in initial listen socket crypto for token validation instead.
- Implement hkdf_expand() and hkdf_extract() locally, as they are no longer available in the latest kernel crypto API.
- Add key_derived in quic_crypto to prevent repeated key updates on spoofed packets, and check and update it in quic_crypto_key_update().
v13:
- Remove pr_debug() from keys_derive_and_install() as it exposes raw QUIC key material.
- Add comment documenting deferred crypto free in quic_sock_destruct().
--- net/quic/Makefile | 2 +- net/quic/crypto.c | 566 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/crypto.h | 77 ++++++ net/quic/protocol.c | 13 +- net/quic/protocol.h | 2 + net/quic/socket.c | 12 + net/quic/socket.h | 7 + 7 files changed, 677 insertions(+), 2 deletions(-) create mode 100644 net/quic/crypto.c create mode 100644 net/quic/crypto.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o + cong.o pnspace.o crypto.o
net/quic/crypto.c new file +566 -0
566 lines not on this page · raw message
net/quic/crypto.h new file +77 -0
77 lines not on this page · raw message
net/quic/protocol.c +12 -1
@@ -232,15 +232,23 @@ static void quic_protosw_exit(void)static int __net_init quic_net_init (struct net *net) {struct quic_net *qn =quic_net (net); -int err =0 ; +int err; qn->stat = alloc_percpu(struct quic_mib);if (!qn->stat)return -ENOMEM ; + err =quic_crypto_set_cipher (&qn->crypto,TLS_CIPHER_AES_GCM_128 ); +if (err) { +free_percpu (qn->stat); + qn->stat =NULL ; +return err; + } +#if IS_ENABLED (CONFIG_PROC_FS ) err =quic_net_proc_init (net);if (err) { +quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ; }
@@ -255,6 +263,7 @@ static void __net_exit quic_net_exit(struct net *net)#if IS_ENABLED (CONFIG_PROC_FS )quic_net_proc_exit (net);#endif +quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ; }
@@ -335,6 +344,8 @@ static __init int quic_init(void) sysctl_quic_wmem[1 ] =16 *1024 ; sysctl_quic_wmem[2 ] =max (64 *1024 , max_share); +quic_crypto_init (); + err =percpu_counter_init (&quic_sockets_allocated,0 ,GFP_KERNEL );if (err) goto err_percpu_counter;
net/quic/protocol.h +2 -0
@@ -49,6 +49,8 @@ struct quic_net {#if IS_ENABLED (CONFIG_PROC_FS )struct proc_dir_entry *proc_net;/* procfs entry for QUIC stats */ #endif +/* Context for decrypting Initial packets for ALPN */ +struct quic_crypto crypto; };struct quic_net *quic_net (struct net *net);
net/quic/socket.c +12 -0
@@ -40,10 +40,22 @@ static void quic_write_space(struct sock *sk)rcu_read_unlock (); } +static void quic_sock_destruct (struct sock *sk) +{ +u8 i; + +/* Deferred crypto free for async encryption/decryption. */ +for (i =0 ; i <QUIC_CRYPTO_MAX ; i++) +quic_crypto_free (quic_crypto (sk, i)); + +quic_sk_destruct (sk); +} +static int quic_init_sock (struct sock *sk) {u8 i; + sk->sk_destruct = quic_sock_destruct; sk->sk_write_space = quic_write_space;sock_set_flag (sk,SOCK_USE_WRITE_QUEUE );
net/quic/socket.h +7 -0
@@ -16,6 +16,7 @@#include "family.h" #include "stream.h" #include "connid.h" +#include "crypto.h" #include "path.h" #include "cong.h"
@@ -45,6 +46,7 @@ struct quic_sock {struct quic_path_group paths;struct quic_cong cong;struct quic_pnspace space[QUIC_PNSPACE_MAX ]; +struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; };struct quic6_sock {
@@ -112,6 +114,11 @@ static inline struct quic_pnspace *quic_pnspace(const struct sock *sk, u8 level)return &quic_sk (sk)->space[level %QUIC_CRYPTO_EARLY ]; } +static inline struct quic_crypto *quic_crypto (const struct sock *sk,u8 level) +{ +return &quic_sk (sk)->crypto[level]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v13 12/15 quic: add crypto packet encryption and decryption
In reply to Xin LongThis patch adds core support for packet-level encryption and decryption using AEAD, including both payload protection and QUIC header protection. It introduces helpers to encrypt packets before transmission and to remove header protection and decrypt payloads upon reception, in line with QUIC's cryptographic requirements.
- quic_crypto_encrypt(): Perform header protection and payload encryption (TX).
- quic_crypto_decrypt(): Perform header protection removal and payload decryption (RX).
The patch also includes support for Retry token handling. It provides helpers to compute the Retry integrity tag, generate tokens for address validation, and verify tokens received from clients during the handshake phase.
- quic_crypto_get_retry_tag(): Compute tag for Retry packets.
- quic_crypto_generate_token(): Generate retry token.
- quic_crypto_verify_token(): Verify retry token.
These additions establish the cryptographic primitives necessary for secure QUIC packet exchange and address validation.
---
v3:
- quic_crypto_decrypt(): return -EKEYREVOKED to defer key updates to the workqueue when the packet is not marked backlog, since quic_crypto_key_update()/crypto_aead_setkey() must run in process context.
- Only perform header decryption if !cb->number_len to avoid double decryption when a key-update packet (with flipped key_phase) re-enters quic_crypto_decrypt() from the workqueue.
v4:
- skb_dst_force() is already called in in quic_udp_rcv() on recv path, so remove its call from quic_crypto_payload_decrypt(), which may be called without RCU protection.
- Remove the incorrect (void *) cast to quic_crypto_done.
v5:
- Use skb_cb->crypto_ctx for async crypto context freeing, which is
safer than using skb_shinfo(skb)->destructor_arg.
- skb_cb->number_max is removed and number is reused as the largest previously seen and update quic_crypto_get_header() accordingly.
- Change timestamp variables from u32 to u64 and use quic_ktime_get_us() for current timestamps, as jiffies_to_usecs() is not accurate enough.
v6:
- Rename quic_crypto_get_header() to quic_crypto_get_number(), move key_phase parsing out of it, check cb->length when parsing packet number, and update all callers.
- Use hdr->pnl + 1 instead of (*p & QUIC_PN_LEN_BITS_MASK) + 1 to get packet number length, and remove the unnecessary the len variable and QUIC_PN_LEN_BITS_MASK macro from quic_crypto_header_decrypt().
v8:
- Move skb_cow_data() from quic_crypto_payload_decrypt() to quic_crypto_header_decrypt(), as header decryption also writes to the skb and is invoked earlier than payload decryption on RX path.
v10:
- Fix double period at end of the comment for quic_crypto_encrypt().
v11:
- Note for AI review: call quic_crypto_aead_mem_alloc() after skb_cow_data() as it uses the return value for nsg. If the allocation fails, skb is dropped, so no rollback of prior skb modifications is needed.
- Set maximum line length to 80 characters.
- Add a check for skb->len in quic_crypto_get_retry_tag().
- Also reset key_update_send_time when key_pending is cleared in quic_crypto_decrypt().
- Handle -EBUSY returned from crypto_aead_en/decrypt() and return when
err == -EINPROGRESS in quic_crypto_done().
- Extract quic_crypto_token_init() from quic_crypto_generate_token() and quic_crypto_verify_token().
- Merge quic_crypto_header_en/decrypt() to quic_crypto_header_protect() with an extra parameter to reduce code duplication.
- Merge quic_crypto_payload_en/decrypt() to quic_crypto_payload_protect() with an extra parameter to reduce code duplication (noted by AI review).
v12:
- Move ciphers definitions to above the encryption/decryption functions.
- Fix some indentations in quic_crypto_skcipher_mem_alloc() and quic_crypto_header_protect().
- Pass crypto and fetch the key phase only for short header packets in quic_crypto_header_protect() and quic_crypto_payload_protect().
- Increment async_pending[phase] for asynchronous encryption/decryption operations, and pass crypto to quic_crypto_done() to decrement it.
- Update key_phase and key_pending only after successful payload decryption in quic_crypto_decrypt() to comply with RFC9001.
- Take the token flag into account when calling aead_request_set_ad() in quic_crypto_generate_token() and quic_crypto_verify_token().
- Replace quic_crypto_token_init() with quic_crypto_token_protect() to perform AEAD encryption/decryption for the provided token, and update quic_crypto_generate/verify_token() accordingly.
- Reuse TX AEAD (phase 1) from listen socket initial crypto in quic_crypto_token_protect(), and use crypto_wait for sync mode.
- Reuse RX AEAD (phase 1) from listen socket initial crypto in quic_crypto_get_retry_tag(), using crypto_wait for sync mode.
- Check cb->sync in quic_crypto_payload_protect() to enforce sync mode;
set cb->sync in quic_crypto_decrypt() after key update in process
context. - Change the label name 'err:' to 'out:' in quic_crypto_payload_protect() and quic_crypto_header_protect().
- Reset crypto->key_derived if crypo->key_phase is flipped by key_update in quic_crypto_decrypt().
v13:
- Fix the opportunity for kmemdup warning from cocci-check by replacing kzalloc() + memcpy() with kmemdup() in quic_crypto_verify_token().
--- net/quic/crypto.c | 679 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/crypto.h | 12 + 2 files changed, 691 insertions(+)
net/quic/crypto.c +679 -0
@@ -255,6 +255,450 @@ static struct quic_cipher ciphers[QUIC_CIPHER_MAX + 1 - QUIC_CIPHER_MIN] = { "rfc7539(chacha20,poly1305)", "chacha20", "hmac(sha256)"), }; +static bool quic_crypto_is_cipher_ccm (struct quic_crypto *crypto) +{ +return crypto->cipher_type ==TLS_CIPHER_AES_CCM_128 ; +} + +static bool quic_crypto_is_cipher_chacha (struct quic_crypto *crypto) +{ +return crypto->cipher_type ==TLS_CIPHER_CHACHA20_POLY1305 ; +} + +static void *quic_crypto_skcipher_mem_alloc (struct crypto_skcipher *tfm, +u32 mask_size,u8 **iv, +struct skcipher_request **req) +{ +unsigned int iv_size, req_size; +unsigned int len; +u8 *mem; + + iv_size =crypto_skcipher_ivsize (tfm); + req_size =sizeof (**req) +crypto_skcipher_reqsize (tfm); + + len = mask_size; + len += iv_size; + len +=crypto_skcipher_alignmask (tfm) & + ~(crypto_tfm_ctx_alignment () -1 ); + len =ALIGN (len,crypto_tfm_ctx_alignment ()); + len += req_size; + + mem =kzalloc (len,GFP_ATOMIC ); +if (!mem) +return NULL ; + + *iv = (u8 *)PTR_ALIGN (mem + mask_size, +crypto_skcipher_alignmask (tfm) +1 ); + *req = (struct skcipher_request *)PTR_ALIGN (*iv + iv_size, +crypto_tfm_ctx_alignment ()); + +return (void *)mem; +} + +/* Extracts and reconstructs the packet number from an incoming QUIC packet. */ +static int quic_crypto_get_number (struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +s64 number_max = cb->number; +u32 len = cb->length; +u8 *p; + +/* rfc9000#section-17.1: +* +* Once header protection is removed, the packet number is decoded by +* finding the packet number value that is closest to the next expected +* packet. The next expected packet is the highest received packet +* number plus one. +*/ + p = (u8 *)quic_hdr (skb) + cb->number_offset; +if (!quic_get_int (&p, &len, &cb->number, cb->number_len)) +return -EINVAL ; + cb->number =quic_get_num (number_max, cb->number, cb->number_len); +return 0 ; +} + +#define QUIC_SAMPLE_LEN 16 + +#define QUIC_HEADER_FORM_BIT 0x80 +#define QUIC_LONG_HEADER_MASK 0x0f +#define QUIC_SHORT_HEADER_MASK 0x1f + +/* Header Protection. */ +static int quic_crypto_header_protect (struct quic_crypto *crypto, +struct sk_buff *skb,bool enc) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 *mask, *iv, *p, h_mask, chacha; +struct skcipher_request *req; +struct crypto_skcipher *tfm; +struct sk_buff *trailer; +struct scatterlist sg; +int err, i; + + chacha =quic_crypto_is_cipher_chacha (crypto); +if (!enc) { + tfm = crypto->rx_hp_tfm; +if (cb->length <QUIC_PN_MAX_LEN +QUIC_SAMPLE_LEN ) +return -EINVAL ; + + err =skb_cow_data (skb,0 , &trailer); +if (err <0 ) +return err; + }else { + tfm = crypto->tx_hp_tfm; + } + + mask =quic_crypto_skcipher_mem_alloc (tfm,QUIC_SAMPLE_LEN , &iv, &req); +if (!mask) +return -ENOMEM ; + +/* rfc9001#section-5.4.2: Header Protection Sample: +* +* # pn_offset is the start of the Packet Number field. +* sample_offset = pn_offset + 4 +* +* sample = packet[sample_offset..sample_offset+sample_length] +* +* rfc9001#section-5.4.3: AES-Based Header Protection: +* +* header_protection(hp_key, sample): +* mask = AES-ECB(hp_key, sample) +* +* rfc9001#section-5.4.4: ChaCha20-Based Header Protection: +* +* header_protection(hp_key, sample): +* counter = sample[0..3] +* nonce = sample[4..15] +* mask = ChaCha20(hp_key, counter, nonce, {0,0,0,0,0}) +*/ + p = skb->data + cb->number_offset +QUIC_PN_MAX_LEN ; +memcpy ((chacha ? iv : mask), p,QUIC_SAMPLE_LEN ); +sg_init_one (&sg, mask,QUIC_SAMPLE_LEN ); +skcipher_request_set_tfm (req, tfm); +skcipher_request_set_crypt (req, &sg, &sg,QUIC_SAMPLE_LEN , iv); + err =crypto_skcipher_encrypt (req); +if (err) + goto out; + +/* rfc9001#section-5.4.1: +* +* mask = header_protection(hp_key, sample) +* +* pn_length = (packet[0] & 0x03) + 1 +* if (packet[0] & 0x80) == 0x80: +* # Long header: 4 bits masked +* packet[0] ^= mask[0] & 0x0f +* else: +* # Short header: 5 bits masked +* packet[0] ^= mask[0] & 0x1f +* +* # pn_offset is the start of the Packet Number field. +* packet[pn_offset:pn_offset+pn_length] ^= mask[1:1+pn_length] +*/ + p = skb->data; + h_mask = ((*p &QUIC_HEADER_FORM_BIT ) ==QUIC_HEADER_FORM_BIT ) ? +QUIC_LONG_HEADER_MASK :QUIC_SHORT_HEADER_MASK ; + *p = (u8)(*p ^ (mask[0 ] & h_mask)); +if (!enc) { +if (!quic_hdr (skb)->form) + cb->key_phase =quic_hdr (skb)->key; + cb->number_len =quic_hdr (skb)->pnl +1 ; + } + p += cb->number_offset; +for (i =1 ; i <= cb->number_len; i++) + *p++ ^= mask[i]; + +if (!enc) + err =quic_crypto_get_number (skb); +out: +kfree_sensitive (mask); +return err; +} + +static void *quic_crypto_aead_mem_alloc (struct crypto_aead *tfm,u32 ctx_size, +u8 **iv,struct aead_request **req, +struct scatterlist **sg,u32 nsg) +{ +unsigned int iv_size, req_size; +unsigned int len; +u8 *mem; + + iv_size =crypto_aead_ivsize (tfm); + req_size =sizeof (**req) +crypto_aead_reqsize (tfm); + + len = ctx_size; + len += iv_size; + len +=crypto_aead_alignmask (tfm) & ~(crypto_tfm_ctx_alignment () -1 ); + len =ALIGN (len,crypto_tfm_ctx_alignment ()); + len += req_size; + len =ALIGN (len, __alignof__(struct scatterlist )); + len += nsg *sizeof (**sg); + + mem =kzalloc (len,GFP_ATOMIC ); +if (!mem) +return NULL ; + + *iv = (u8 *)PTR_ALIGN (mem + ctx_size,crypto_aead_alignmask (tfm) +1 ); + *req = (struct aead_request *)PTR_ALIGN (*iv + iv_size, +crypto_tfm_ctx_alignment ()); + *sg = (struct scatterlist *)PTR_ALIGN ((u8 *)*req + req_size, + __alignof__(struct scatterlist )); + +return (void *)mem; +} + +static void quic_crypto_done (void *data,int err) +{ +struct sk_buff *skb = data; +struct quic_crypto *crypto; +struct quic_skb_cb *cb; + +if (err == -EINPROGRESS ) +return ; + + cb =QUIC_SKB_CB (skb); + crypto = *(struct quic_crypto **)cb->crypto_ctx; +atomic_dec (&crypto->async_pending[cb->key_phase]); + +kfree_sensitive (cb->crypto_ctx); + cb->crypto_done (skb, err); +} + +/* AEAD Usage. */ +static int quic_crypto_payload_protect (struct quic_crypto *crypto, +struct sk_buff *skb,bool enc) +{ +u8 *base_iv, *iv, i, nonce[QUIC_IV_LEN ], ccm, phase; +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u32 len, hlen, sglen, nsg; +struct aead_request *req; +struct crypto_aead *tfm; +struct sk_buff *trailer; +struct scatterlist *sg; +void *ctx; +__be64 n; +int err; + + ccm =quic_crypto_is_cipher_ccm (crypto); + phase = cb->key_phase; + hlen = cb->number_offset + cb->number_len; +if (enc) { + tfm = crypto->tx_tfm[phase]; + base_iv = crypto->tx_iv[phase]; + len = skb->len; + err =skb_cow_data (skb,QUIC_TAG_LEN , &trailer); +if (err <0 ) +return err; +pskb_put (skb, trailer,QUIC_TAG_LEN ); +if (!quic_hdr (skb)->form) +quic_hdr (skb)->key = phase; + sglen = skb->len; + nsg = (u32 )err; + }else { + tfm = crypto->rx_tfm[phase]; + base_iv = crypto->rx_iv[phase]; + len = cb->length + cb->number_offset; +if (len - hlen <QUIC_TAG_LEN ) +return -EINVAL ; + sglen = len; + nsg =1 ; + } + + ctx =quic_crypto_aead_mem_alloc (tfm,sizeof (void *), &iv, &req, &sg, + nsg); +if (!ctx) +return -ENOMEM ; + +sg_init_table (sg, nsg); + err =skb_to_sgvec (skb, sg,0 , sglen); +if (err <0 ) + goto out; + +/* rfc9001#section-5.3: +* +* The associated data, A, for the AEAD is the contents of the QUIC +* header, starting from the first byte of either the short or long +* header, up to and including the unprotected packet number. +* +* The nonce, N, is formed by combining the packet protection IV with +* the packet number. The 62 bits of the reconstructed QUIC packet +* number in network byte order are left-padded with zeros to the size +* of the IV. The exclusive OR of the padded packet number and the IV +* forms the AEAD nonce. +*/ +memcpy (nonce, base_iv,QUIC_IV_LEN ); + n =cpu_to_be64 (cb->number); +for (i =0 ; i <sizeof (n); i++) + nonce[QUIC_IV_LEN -sizeof (n) + i] ^= ((u8 *)&n)[i]; + +/* For CCM based ciphers, first byte of IV is a constant. */ + iv[0 ] =TLS_AES_CCM_IV_B0_BYTE ; +memcpy (&iv[ccm], nonce,QUIC_IV_LEN ); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, hlen); +aead_request_set_crypt (req, sg, sg, len - hlen, iv); +if (cb->sync) { +DECLARE_CRYPTO_WAIT (wait); + +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &wait); + err = enc ?crypto_aead_encrypt (req) :crypto_aead_decrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) + err =crypto_wait_req (err, &wait); + goto out; + } + +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + quic_crypto_done, skb); + *(struct quic_crypto **)ctx = crypto; + cb->crypto_ctx = ctx;/* Async free context for quic_crypto_done() */ + err = enc ?crypto_aead_encrypt (req) :crypto_aead_decrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) { +atomic_inc (&crypto->async_pending[phase]); +memzero_explicit (nonce,sizeof (nonce)); +return -EINPROGRESS ; + } + +out: +kfree_sensitive (ctx); +memzero_explicit (nonce,sizeof (nonce)); +return err; +} + +/* Encrypts a QUIC packet before transmission. This function performs AEAD +* encryption of the packet payload and applies header protection. It handles +* key phase tracking and key update timing. +* +* Return: 0 on success, or a negative error code. +*/ +int quic_crypto_encrypt (struct quic_crypto *crypto,struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +int err; + + cb->key_phase = crypto->key_phase; +/* Packet payload is already encrypted (e.g., resumed from async), +* proceed to header protection only. +*/ +if (cb->resume) + goto out; + +/* If a key update is pending and this is the first packet using the +* new key, save the current time. Later used to clear old keys after +* some time has passed (see quic_crypto_decrypt()). +*/ +if (crypto->key_pending && !crypto->key_update_send_time) + crypto->key_update_send_time =quic_ktime_get_us (); + + err =quic_crypto_payload_protect (crypto, skb, true); +if (err) +return err; +out: +return quic_crypto_header_protect (crypto, skb, true); +} + +/* Decrypts a QUIC packet after reception. This function removes header +* protection, decrypts the payload, and processes any key updates if the key +* phase bit changes. +* +* Return: 0 on success, or a negative error code. +*/ +int quic_crypto_decrypt (struct quic_crypto *crypto,struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +int err =0 ; +u64 time; +u8 phase; + +/* Payload was decrypted asynchronously. Proceed with parsing packet +* number and key phase. +*/ +if (cb->resume) { + err =quic_crypto_get_number (skb); +if (err) +return err; + goto out; + } +if (!cb->number_len) {/* Packet header not yet decrypted. */ + err =quic_crypto_header_protect (crypto, skb, false); +if (err) { +pr_debug ("%s: hd decrypt err %d\n" , __func__, err); +return err; + } + } + +/* rfc9001#section-6: +* +* The Key Phase bit allows a recipient to detect a change in keying +* material without needing to receive the first packet that triggered +* the change. An endpoint that notices a changed Key Phase bit updates +* keys and decrypts the packet that contains the changed value. +*/ + phase = cb->key_phase; +if (phase != crypto->key_phase && !crypto->key_pending) { +if (!crypto->send_ready)/* Not ready for key update. */ +return -EINVAL ; +if (!cb->backlog)/* Key update requires process context. */ +return -EKEYREVOKED ; +/* Cannot do key update while async crypto is in progress. */ +if (unlikely (atomic_read (&crypto->async_pending[phase]))) +return -EBUSY ; + err =quic_crypto_key_update (crypto);/* Perform key update. */ +if (err) { + cb->errcode =QUIC_TRANSPORT_ERROR_KEY_UPDATE ; +return err; + } + cb->sync =1 ; + cb->key_update =1 ;/* Mark packet as triggering key update. */ + } + + err =quic_crypto_payload_protect (crypto, skb, false); +if (err) { +if (err == -EINPROGRESS ) +return err; +/* When using the old keys can not decrypt the packets, the +* peer might start another key_update. Thus, clear the last +* key_pending so that next packets will trigger the new +* key-update. +*/ +if (crypto->key_pending && phase != crypto->key_phase) { + crypto->key_pending =0 ; + crypto->key_update_time =0 ; + crypto->key_update_send_time =0 ; + } +return err; + } + +out: +/* rfc9001#section-6.2: +* +* If a packet is successfully processed using the next key and IV, +* then the peer has initiated a key update. +*/ +if (cb->key_update) { + crypto->key_pending =1 ; + crypto->key_derived =0 ; + crypto->key_phase = !crypto->key_phase; + } +/* rfc9001#section-6.1: +* +* An endpoint MUST retain old keys until it has successfully +* unprotected a packet sent using the new keys. An endpoint SHOULD +* retain old keys for some time after unprotecting a packet sent using +* the new keys. +*/ +if (crypto->key_pending && cb->key_phase == crypto->key_phase) { + time = crypto->key_update_send_time; +if (time && +quic_ktime_get_us () - time >= crypto->key_update_time) { + crypto->key_pending =0 ; + crypto->key_update_time =0 ; + crypto->key_update_send_time =0 ; + } + } +return err; +} +int quic_crypto_set_cipher (struct quic_crypto *crypto,u32 type) {struct quic_cipher *cipher;
@@ -515,6 +959,241 @@ int quic_crypto_initial_keys_install(struct quic_crypto *crypto,return err; } +#define QUIC_RETRY_KEY_V1 \ + "\xbe\x0c\x69\x0b\x9f\x66\x57\x5a\x1d\x76\x6b\x54\xe3\x68\xc8\x4e" +#define QUIC_RETRY_KEY_V2 \ + "\x8f\xb4\xb0\x1b\x56\xac\x48\xe2\x60\xfb\xcb\xce\xad\x7c\xcc\x92" + +#define QUIC_RETRY_NONCE_V1 "\x46\x15\x99\xd3\x5d\x63\x2b\xf2\x23\x98\x25\xbb" +#define QUIC_RETRY_NONCE_V2 "\xd8\x69\x69\xbc\x2d\x7c\x6d\x99\x90\xef\xb0\x4a" + +/* Retry Packet Integrity. */ +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag) +{ +/* Reuse RX AEAD (phase 1) in Initial crypto. */ +struct crypto_aead *tfm = crypto->rx_tfm[1 ]; +u8 *pseudo_retry, *p, *iv, *key; +DECLARE_CRYPTO_WAIT (wait); +struct aead_request *req; +struct scatterlist *sg; +u32 plen; +int err; + +if (skb->len <QUIC_TAG_LEN ) +return -EINVAL ; + +/* rfc9001#section-5.8: +* +* The Retry Integrity Tag is a 128-bit field that is computed as the +* output of AEAD_AES_128_GCM used with the following inputs: +* +* - The secret key, K, is 128 bits equal to +* 0xbe0c690b9f66575a1d766b54e368c84e. +* - The nonce, N, is 96 bits equal to 0x461599d35d632bf2239825bb. +* - The plaintext, P, is empty. +* - The associated data, A, is the contents of the Retry +* Pseudo-Packet, +* +* The Retry Pseudo-Packet is not sent over the wire. It is computed by +* taking the transmitted Retry packet, removing the Retry Integrity +* Tag, and prepending the two following fields: ODCID Length + +* Original Destination Connection ID (ODCID). +*/ + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) +return err; + key =QUIC_RETRY_KEY_V1 ; +if (version ==QUIC_VERSION_V2 ) + key =QUIC_RETRY_KEY_V2 ; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) +return err; + +/* The caller must ensure skb->len > QUIC_TAG_LEN. */ + plen =1 + odcid->len + skb->len -QUIC_TAG_LEN ; + pseudo_retry =quic_crypto_aead_mem_alloc (tfm, plen +QUIC_TAG_LEN , &iv, + &req, &sg,1 ); +if (!pseudo_retry) +return -ENOMEM ; + + p = pseudo_retry; + p =quic_put_int (p, odcid->len,1 ); + p =quic_put_data (p, odcid->data, odcid->len); + p =quic_put_data (p, skb->data, skb->len -QUIC_TAG_LEN ); +sg_init_one (sg, pseudo_retry, plen +QUIC_TAG_LEN ); + +memcpy (iv,QUIC_RETRY_NONCE_V1 ,QUIC_IV_LEN ); +if (version ==QUIC_VERSION_V2 ) +memcpy (iv,QUIC_RETRY_NONCE_V2 ,QUIC_IV_LEN ); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, plen); +aead_request_set_crypt (req, sg, sg,0 , iv); +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &wait); + err =crypto_aead_encrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) + err =crypto_wait_req (err, &wait); +if (!err) +memcpy (tag, p,QUIC_TAG_LEN ); + +kfree_sensitive (pseudo_retry); +return err; +} + +/* Derives a key and IV using HKDF, configures the AEAD transform and performs +* AEAD encryption/decryption for the provided token. +*/ +static int quic_crypto_token_protect (struct quic_crypto *crypto,u8 *token, +u32 len,u32 adlen,bool enc) +{ +u8 key[TLS_CIPHER_AES_GCM_128_KEY_SIZE ], iv[QUIC_IV_LEN ], *tiv; +/* Reuse TX AEAD (phase 1) in Initial crypto. */ +struct crypto_aead *tfm = crypto->tx_tfm[1 ]; +u32 extra = enc ?QUIC_TAG_LEN :0 ; +struct quic_data srt = {}, k, i; +DECLARE_CRYPTO_WAIT (wait); +struct aead_request *req; +struct scatterlist *sg; +void *ctx =NULL ; +int err; + +quic_data (&srt, quic_random_data,QUIC_RANDOM_DATA_LEN ); +quic_data (&k, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +quic_data (&i, iv,QUIC_IV_LEN ); + err =quic_crypto_keys_derive (crypto->secret_tfm, &srt, &k, &i,NULL , +QUIC_VERSION_V1 ); +if (err) + goto out; + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) + goto out; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) + goto out; + ctx =quic_crypto_aead_mem_alloc (tfm,0 , &tiv, &req, &sg,1 ); +if (!ctx) { + err = -ENOMEM ; + goto out; + } +memcpy (tiv, iv,QUIC_IV_LEN ); + +sg_init_one (sg, token, len); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, adlen); +aead_request_set_crypt (req, sg, sg, len - adlen - extra, tiv); +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &wait); + err = enc ?crypto_aead_encrypt (req) :crypto_aead_decrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) + err =crypto_wait_req (err, &wait); + +out: +memzero_explicit (key,sizeof (key)); +memzero_explicit (iv,sizeof (iv)); +kfree_sensitive (ctx); +return err; +} + +/* Generate a token for Retry or address validation. +* +* Builds a token with the format: [client address][timestamp][original +* DCID][auth tag] +* +* Encrypts the token (excluding the first flag byte) using AES-GCM with a key +* and IV derived via HKDF. The original DCID is stored to be recovered later +* from a Client Initial packet. Ensures the token is bound to the client +* address and time, preventing reuse or tampering. +* +* Returns 0 on success or a negative error code on failure. +*/ +int quic_crypto_generate_token (struct quic_crypto *crypto,void *addr, +u32 addrlen,struct quic_conn_id *conn_id, +u8 *token,u32 *tlen) +{ +u8 *token_buf, *p, flag = *token; +u64 ts =quic_ktime_get_us (); +int err, len; + + len =sizeof (flag) + addrlen +sizeof (ts) + conn_id->len +QUIC_TAG_LEN ; + token_buf =kzalloc (len,GFP_KERNEL ); +if (!token_buf) +return -ENOMEM ; + + p = token_buf; + p =quic_put_int (p, flag,sizeof (flag)); + p =quic_put_data (p, addr, addrlen); + p =quic_put_int (p, ts,sizeof (ts)); +quic_put_data (p, conn_id->data, conn_id->len); + + err =quic_crypto_token_protect (crypto, token_buf, len, +sizeof (flag) + addrlen, true); +if (err) + goto out; + +memcpy (token, token_buf, len); + *tlen = len; +out: +kfree (token_buf); +return err; +} + +/* Validate a Retry or address validation token. +* +* Decrypts the token using derived key and IV. Checks that the decrypted +* address matches the provided address, validates the embedded timestamp +* against current time with a version-specific timeout. If applicable, it +* extracts and returns the original destination connection ID (ODCID) for +* Retry packets. +* +* Returns 0 if the token is valid, -EINVAL if invalid, or another negative +* error code. +*/ +int quic_crypto_verify_token (struct quic_crypto *crypto,void *addr, +u32 addrlen,struct quic_conn_id *conn_id, +u8 *token,u32 len) +{ +u64 t, ts =quic_ktime_get_us (), timeout =QUIC_TOKEN_TIMEOUT_RETRY ; +u8 *token_buf, *p, flag; +int err; + +if (len <sizeof (flag) + addrlen +sizeof (ts) +QUIC_TAG_LEN ) +return -EINVAL ; + token_buf =kmemdup (token, len,GFP_KERNEL ); +if (!token_buf) +return -ENOMEM ; + + err =quic_crypto_token_protect (crypto, token_buf, len, +sizeof (flag) + addrlen, false); +if (err) + goto out; + + err = -EINVAL ; + p = token_buf; + flag = *p++; + len -=sizeof (flag); +if (memcmp (p, addr, addrlen)) + goto out; + + p += addrlen; + len -= addrlen; +if (flag ==QUIC_TOKEN_FLAG_REGULAR ) + timeout =QUIC_TOKEN_TIMEOUT_REGULAR ; +if (!quic_get_int (&p, &len, &t,sizeof (ts)) || t + timeout < ts) + goto out; + + len -=QUIC_TAG_LEN ; +if (len >QUIC_CONN_ID_MAX_LEN ) + goto out; + +if (flag ==QUIC_TOKEN_FLAG_RETRY ) +quic_conn_id_update (conn_id, p, len); + err =0 ; +out: +kfree (token_buf); +return err; +} +/* Generate a derived key using HKDF-Extract and HKDF-Expand with a given * label. */
net/quic/crypto.h +12 -0
@@ -63,6 +63,9 @@ int quic_crypto_set_secret(struct quic_crypto *crypto,int quic_crypto_set_cipher (struct quic_crypto *crypto,u32 type);int quic_crypto_key_update (struct quic_crypto *crypto); +int quic_crypto_encrypt (struct quic_crypto *crypto,struct sk_buff *skb); +int quic_crypto_decrypt (struct quic_crypto *crypto,struct sk_buff *skb); +int quic_crypto_initial_keys_install (struct quic_crypto *crypto,struct quic_conn_id *conn_id,u32 version,bool is_serv);
@@ -73,5 +76,14 @@ int quic_crypto_generate_stateless_reset_token(struct quic_crypto *crypto, void *data, u32 len, u8 *key, u32 key_len); +int quic_crypto_generate_token (struct quic_crypto *crypto,void *addr, +u32 addrlen,struct quic_conn_id *conn_id, +u8 *token,u32 *tlen); +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag); +int quic_crypto_verify_token (struct quic_crypto *crypto,void *addr, +u32 addrlen,struct quic_conn_id *conn_id, +u8 *token,u32 len); +void quic_crypto_free (struct quic_crypto *crypto);void quic_crypto_init (void );
Signature · 1 line
2.47.1
Paolo Abeni
maintainerRe: [PATCH net-next v13 12/15] quic: add crypto packet encryption and decryption
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
quic: add crypto packet encryption and decryption
This patch adds AEAD-based packet encryption/decryption helpers, QUIC header protection, and Retry/address-validation token generation and verification primitives.
Quoted 4 lines
net/quic/crypto.c +0
-0
[ ... ]
Quoted 5 lines
net/quic/crypto.c +5
-0+/* Retry Packet Integrity. */ +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag) +{ +/* Reuse RX AEAD (phase 1) in Initial crypto. */
net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 984
Quoted 10 lines
net/quic/crypto.c +10
-0+struct crypto_aead *tfm = crypto->rx_tfm[1 ]; +u8 *pseudo_retry, *p, *iv, *key; +DECLARE_CRYPTO_WAIT (wait); +struct aead_request *req; +struct scatterlist *sg; +u32 plen; +int err; + +if (skb->len <QUIC_TAG_LEN ) +return -EINVAL ;
[Low]
The guard rejects skb->len < QUIC_TAG_LEN, but a later comment in the same function says:
net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1014
Quoted 2 lines
net/quic/crypto.c +2
-0+/* The caller must ensure skb->len > QUIC_TAG_LEN. */ + plen =1 + odcid->len + skb->len -QUIC_TAG_LEN ;
Should the check be <= QUIC_TAG_LEN, or should the comment say >= to match the strict-less-than test?
In the boundary case where skb->len == QUIC_TAG_LEN, plen becomes 1 + odcid->len, and quic_put_data(p, skb->data, skb->len - QUIC_TAG_LEN) copies zero bytes, so the integrity tag would be computed over a pseudo-packet containing only the ODCID length and ODCID with no actual Retry header bytes. Is that intended?
[ ... ]
Quoted 12 lines
net/quic/crypto.c +12
-0+/* Derives a key and IV using HKDF, configures the AEAD transform and performs +* AEAD encryption/decryption for the provided token. +*/ +static int quic_crypto_token_protect (struct quic_crypto *crypto,u8 *token, +u32 len,u32 adlen,bool enc) +{ +u8 key[TLS_CIPHER_AES_GCM_128_KEY_SIZE ], iv[QUIC_IV_LEN ], *tiv; +/* Reuse TX AEAD (phase 1) in Initial crypto. */ +struct crypto_aead *tfm = crypto->tx_tfm[1 ]; +u32 extra = enc ?QUIC_TAG_LEN :0 ; +struct quic_data srt = {}, k, i; +DECLARE_CRYPTO_WAIT (wait);
net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1065
Quoted 10 lines
net/quic/crypto.c +10
-0+struct aead_request *req; +struct scatterlist *sg; +void *ctx =NULL ; +int err; + +quic_data (&srt, quic_random_data,QUIC_RANDOM_DATA_LEN ); +quic_data (&k, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +quic_data (&i, iv,QUIC_IV_LEN ); + err =quic_crypto_keys_derive (crypto->secret_tfm, &srt, &k, &i,NULL , +QUIC_VERSION_V1 );
[Critical]
Can this lead to AES-GCM nonce reuse across all generated tokens?
quic_random_data is a module-global buffer initialized once in quic_crypto_init() via get_random_bytes() and never refreshed:
static u8 quic_random_data[QUIC_RANDOM_DATA_LEN] __read_mostly;
quic_crypto_keys_derive() runs HKDF-Expand-Label over that constant secret with constant labels "quic key" and "quic iv", so both the derived key and the derived IV are deterministic and identical on every invocation of quic_crypto_token_protect().
Quoted 9 lines
net/quic/crypto.c +9
-0+if (err) + goto out; + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) + goto out; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) + goto out; + ctx =quic_crypto_aead_mem_alloc (tfm,0 , &tiv, &req, &sg,1 );
net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1084
Quoted 10 lines
net/quic/crypto.c +10
-0+if (!ctx) { + err = -ENOMEM ; + goto out; + } +memcpy (tiv, iv,QUIC_IV_LEN ); + +sg_init_one (sg, token, len); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, adlen); +aead_request_set_crypt (req, sg, sg, len - adlen - extra, tiv);
Every call ends up using the same (K, N) pair under AES-GCM, with no per-token random prefix and no packet-number XOR like quic_crypto_payload_protect() does via cb->number.
NIST SP 800-38D forbids reuse of (K, N) under GCM; from two valid ciphertexts an attacker can recover the GHASH authentication subkey H and forge tokens for arbitrary client addresses, which would defeat the address validation in quic_crypto_verify_token() and the anti-amplification protections in RFC 9000 section 8.
Could a unique per-token nonce be derived (for example from a random prefix stored in the token itself), or a nonce-misuse-resistant AEAD be used here instead?
Quoted 12 lines
net/quic/crypto.c +12
-0+aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &wait); + err = enc ?crypto_aead_encrypt (req) :crypto_aead_decrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) + err =crypto_wait_req (err, &wait); + +out: +memzero_explicit (key,sizeof (key)); +memzero_explicit (iv,sizeof (iv)); +kfree_sensitive (ctx); +return err; +}
[ ... ]
Signature · 1 line
This is an AI-generated review.
Re: [PATCH net-next v13 12/15] quic: add crypto packet encryption and decryption
Quoted 43 lines · Paolo Abeni
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
quic: add crypto packet encryption and decryptionThis patch adds AEAD-based packet encryption/decryption helpers, QUIC header protection, and Retry/address-validation token generation and verification primitives.
Quoted 4 lines
net/quic/crypto.c +0
-0[ ... ]
Quoted 5 lines
net/quic/crypto.c +5
-0+/* Retry Packet Integrity. */ +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag) +{ +/* Reuse RX AEAD (phase 1) in Initial crypto. */ net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 984
Quoted 10 lines
net/quic/crypto.c +10
-0+struct crypto_aead *tfm = crypto->rx_tfm[1 ]; +u8 *pseudo_retry, *p, *iv, *key; +DECLARE_CRYPTO_WAIT (wait); +struct aead_request *req; +struct scatterlist *sg; +u32 plen; +int err; + +if (skb->len <QUIC_TAG_LEN ) +return -EINVAL ;[Low]
The guard rejectsskb->len<QUIC_TAG_LEN, but a later comment in the same function says:net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1014
Quoted 2 lines
net/quic/crypto.c +2
-0+/* The caller must ensure skb->len > QUIC_TAG_LEN. */ + plen =1 + odcid->len + skb->len -QUIC_TAG_LEN ;
Quoted 9 lines
Should the check be <=
QUIC_TAG_LEN, or should the comment say >= to match the strict-less-than test?In the boundary case where
skb->len==QUIC_TAG_LEN, plen becomes 1 +odcid->len, andquic_put_data(p, skb->data, skb->len - QUIC_TAG_LEN)copies zero bytes, so the integrity tag would be computed over a pseudo-packet containing only the ODCID length and ODCID with no actual Retry header bytes. Is that intended?
The callers will make sure skb->len > QUIC_TAG_LEN, and the check (skb->len < QUIC_TAG_LEN) was added to make the last AI happy.
I will change (skb->len <= QUIC_TAG_LEN) to match the comment.
Quoted 68 lines
[ ... ]
Quoted 12 lines
net/quic/crypto.c +12
-0+/* Derives a key and IV using HKDF, configures the AEAD transform and performs +* AEAD encryption/decryption for the provided token. +*/ +static int quic_crypto_token_protect (struct quic_crypto *crypto,u8 *token, +u32 len,u32 adlen,bool enc) +{ +u8 key[TLS_CIPHER_AES_GCM_128_KEY_SIZE ], iv[QUIC_IV_LEN ], *tiv; +/* Reuse TX AEAD (phase 1) in Initial crypto. */ +struct crypto_aead *tfm = crypto->tx_tfm[1 ]; +u32 extra = enc ?QUIC_TAG_LEN :0 ; +struct quic_data srt = {}, k, i; +DECLARE_CRYPTO_WAIT (wait);net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1065
Quoted 10 lines
net/quic/crypto.c +10
-0+struct aead_request *req; +struct scatterlist *sg; +void *ctx =NULL ; +int err; + +quic_data (&srt, quic_random_data,QUIC_RANDOM_DATA_LEN ); +quic_data (&k, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +quic_data (&i, iv,QUIC_IV_LEN ); + err =quic_crypto_keys_derive (crypto->secret_tfm, &srt, &k, &i,NULL , +QUIC_VERSION_V1 );[Critical]
Can this lead to AES-GCM nonce reuse across all generated tokens?
quic_random_datais a module-global buffer initialized once inquic_crypto_init()viaget_random_bytes()and never refreshed:static u8 quic_random_data[QUIC_RANDOM_DATA_LEN] __read_mostly;
quic_crypto_keys_derive()runs HKDF-Expand-Label over that constant secret with constant labels "quic key" and "quic iv", so both the derived key and the derived IV are deterministic and identical on every invocation ofquic_crypto_token_protect().Quoted 9 lines
net/quic/crypto.c +9
-0+if (err) + goto out; + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) + goto out; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) + goto out; + ctx =quic_crypto_aead_mem_alloc (tfm,0 , &tiv, &req, &sg,1 );net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1084
Quoted 10 lines
net/quic/crypto.c +10
-0+if (!ctx) { + err = -ENOMEM ; + goto out; + } +memcpy (tiv, iv,QUIC_IV_LEN ); + +sg_init_one (sg, token, len); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, adlen); +aead_request_set_crypt (req, sg, sg, len - adlen - extra, tiv);Every call ends up using the same (K, N) pair under AES-GCM, with no per-token random prefix and no packet-number XOR like
quic_crypto_payload_protect()does viacb->number.NIST SP 800-38D forbids reuse of (K, N) under GCM; from two valid ciphertexts an attacker can recover the GHASH authentication subkey H and forge tokens for arbitrary client addresses, which would defeat the address validation in
quic_crypto_verify_token()and the anti-amplification protections in RFC 9000 section 8.
Quoted 4 lines
Could a unique per-token nonce be derived (for example from a random prefix stored in the token itself), or a nonce-misuse-resistant AEAD be used here instead?
I currently don't have a better solution for this. we can't have it in the socket, as even after the socket closes, this quic_random_data is still needed to validate tokens.
Thanks.
Quoted 17 lines
net/quic/crypto.c int quic_crypto_initial_keys_install(struct quic_crypto *crypto, · line 1096
Quoted 12 lines
net/quic/crypto.c +12
-0+aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , + crypto_req_done, &wait); + err = enc ?crypto_aead_encrypt (req) :crypto_aead_decrypt (req); +if (err == -EINPROGRESS || err == -EBUSY ) + err =crypto_wait_req (err, &wait); + +out: +memzero_explicit (key,sizeof (key)); +memzero_explicit (iv,sizeof (iv)); +kfree_sensitive (ctx); +return err; +}[ ... ]
--
This is an AI-generated review.
PATCH v13 13/15 quic: add timer management
In reply to Xin LongThis patch introduces 'quic_timer' to unify and manage the five main timers used in QUIC: loss detection, delayed ACK, path validation, PMTU probing, and pacing. These timers are critical for driving retransmissions, connection liveness, and flow control.
Each timer type is initialized, started, reset, or stopped using a common set of operations.
- quic_timer_reset(): Reset a timer with type and timeout
- quic_timer_start(): Start a timer with type and timeout
- quic_timer_stop(): Stop a timer with type
Although handler functions for each timer are defined, they are currently placeholders; their logic will be implemented in upcoming patches for packet transmission and outqueue handling.
Deferred timer actions are also integrated through quic_release_cb(), which dispatches to the appropriate handler when timers expire.
---
v5:
- Rename QUIC_TSQ_DEFERRED to QUIC_PACE_DEFERRED.
v11:
- Note for AI reviews: it is safe to avoid synchronous timer shutdown, as the timer holds a socket reference and handlers will not access pnspace/crypto/cong data once sk_state is closed in later patches.
- Note for AI reviews: QUIC_F_MTU_REDUCED_DEFERRED will be used in a later patch; handling in quic_release_cb() will be added then.
- Set maximum line length to 80 characters.
- Add a check for type in quic_timer_reset().
- Extract quic_timer_timeout() from quic_timer_sack/loss/path/pmtu/pace_timeout() (noted by AI review).
v12:
- Remove quic_timer_reset_path() as it is no longer used.
--- net/quic/Makefile | 2 +- net/quic/socket.c | 33 ++++++++++ net/quic/socket.h | 33 ++++++++++ net/quic/timer.c | 154 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/timer.h | 45 ++++++++++++++ 5 files changed, 266 insertions(+), 1 deletion(-) create mode 100644 net/quic/timer.c create mode 100644 net/quic/timer.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o crypto.o + cong.o pnspace.o crypto.o timer.o
net/quic/socket.c +33 -0
@@ -67,6 +67,8 @@ static int quic_init_sock(struct sock *sk)quic_conn_id_set_init (quic_dest (sk), false);quic_cong_init (quic_cong (sk)); +quic_timer_init (sk); +if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
@@ -82,6 +84,8 @@ static void quic_destroy_sock(struct sock *sk) {u8 i; +quic_timer_free (sk); +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++)quic_pnspace_free (quic_pnspace (sk, i));
@@ -213,6 +217,35 @@ static int quic_getsockopt(struct sock *sk, int level, int optname,static void quic_release_cb (struct sock *sk) { +/* Similar to tcp_release_cb(). */ +unsigned long nflags, flags =smp_load_acquire (&sk->sk_tsq_flags); + +do { +if (!(flags &QUIC_DEFERRED_ALL )) +return ; + nflags = flags & ~QUIC_DEFERRED_ALL ; + }while (!try_cmpxchg (&sk->sk_tsq_flags, &flags, nflags)); + +if (flags &QUIC_F_LOSS_DEFERRED ) { +quic_timer_loss_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_SACK_DEFERRED ) { +quic_timer_sack_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_PATH_DEFERRED ) { +quic_timer_path_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_PMTU_DEFERRED ) { +quic_timer_pmtu_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_PACE_DEFERRED ) { +quic_timer_pace_handler (sk); +__sock_put (sk); + } }static int quic_disconnect (struct sock *sk,int flags)
net/quic/socket.h +33 -0
@@ -21,6 +21,7 @@#include "cong.h" #include "protocol.h" +#include "timer.h" extern struct proto quic_prot;extern struct proto quicv6_prot;
@@ -32,6 +33,31 @@ enum quic_state { QUIC_SS_ESTABLISHED = TCP_ESTABLISHED, }; +enum quic_tsq_enum { +QUIC_MTU_REDUCED_DEFERRED , +QUIC_LOSS_DEFERRED , +QUIC_SACK_DEFERRED , +QUIC_PATH_DEFERRED , +QUIC_PMTU_DEFERRED , +QUIC_PACE_DEFERRED , +}; + +enum quic_tsq_flags { +QUIC_F_MTU_REDUCED_DEFERRED =BIT (QUIC_MTU_REDUCED_DEFERRED ), +QUIC_F_LOSS_DEFERRED =BIT (QUIC_LOSS_DEFERRED ), +QUIC_F_SACK_DEFERRED =BIT (QUIC_SACK_DEFERRED ), +QUIC_F_PATH_DEFERRED =BIT (QUIC_PATH_DEFERRED ), +QUIC_F_PMTU_DEFERRED =BIT (QUIC_PMTU_DEFERRED ), +QUIC_F_PACE_DEFERRED =BIT (QUIC_PACE_DEFERRED ), +}; + +#define QUIC_DEFERRED_ALL (QUIC_F_MTU_REDUCED_DEFERRED | \ + QUIC_F_LOSS_DEFERRED | \ + QUIC_F_SACK_DEFERRED | \ + QUIC_F_PATH_DEFERRED | \ + QUIC_F_PMTU_DEFERRED | \ + QUIC_F_PACE_DEFERRED) +struct quic_sock {struct inet_sock inet;struct list_head reqs;
@@ -47,6 +73,8 @@ struct quic_sock {struct quic_cong cong;struct quic_pnspace space[QUIC_PNSPACE_MAX ];struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; + +struct quic_timer timers[QUIC_TIMER_MAX ]; };struct quic6_sock {
@@ -119,6 +147,11 @@ static inline struct quic_crypto *quic_crypto(const struct sock *sk, u8 level)return &quic_sk (sk)->crypto[level]; } +static inline void *quic_timer (const struct sock *sk,u8 type) +{ +return (void *)&quic_sk (sk)->timers[type]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
net/quic/timer.c new file +154 -0
154 lines not on this page · raw message
net/quic/timer.h new file +45 -0
45 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v13 14/15 quic: add packet builder base
In reply to Xin LongThis patch introduces 'quic_packet' to handle packing of QUIC packets on the transmit (TX) path.
It provides functionality for frame packing and packet construction. The packet configuration includes setting the path, calculating overhead, and verifying routing. Frames are appended to the packet before it is created with the queued frames.
Once assembled, the packet is encrypted, bundled, and sent out. There is also support to flush the packet when no additional frames remain. Functions to create application (short) and handshake (long) packets are currently placeholders for future implementation.
- quic_packet_config(): Set the path, compute overhead, and verify routing.
- quic_packet_create_and_xmit(): Create and send the packet with the queued frames.
- quic_packet_flush(): Send the packet if there's nothing left to bundle.
---
v3:
- Adjust global connection and listen socket hashtable operations based on the new hashtable type.
- Introduce quic_packet_backlog_schedule() to enqueue Initial packets to quic_net.backlog_list and defer their decryption for ALPN demux to quic_packet_backlog_work() on quic_net.work, since quic_crypto_initial_keys_install()/crypto_aead_setkey() must run in process context.
v4:
- Update quic_(listen_)sock_lookup() to support lockless socket lookup using hlist_nulls_node APIs.
- Use quic_wq for QUIC packet backlog processing work.
v5:
- Rename quic_packet_create() to quic_packet_create_and_xmit() (suggested by Paolo).
- Move the packet parser base code to a separate patch, keeping only the packet builder base in this patch (suggested by Paolo).
- Change sent_time timestamp from u32 to u64 to improve accuracy.
v8:
- Remove the dependency on struct quic_frame by returning NULL in quic_packet_handshake/app_create() and dropping quic_packet_tail() and struct quic_packet_sent. This effectively strips out patch 14 (suggested by Paolo).
v9:
- Warn on oversized header length in quic_packet_config() (suggested by
Paolo).
- Factor bundle initialization into a common 'init' goto label in quic_packet_bundle() (suggested by Paolo).
- Clarify comment for packet->ipfragok in quic_packet_config().
v10:
- Set MSS to QUIC_MIN_UDP_PAYLOAD in quic_packet_init(); it serves only as a default for procfs dumps before a connection exists.
- Introduce QUIC_PACKET_INVALID as a return value for invalid packet types used in the later patch.
- quic_sock.config.plpmtud_probe_interval has been moved to quic_path_group.plpmtud_interval, so update its usage in quic_packet_route() and quic_packet_config() accordingly.
v11:
- Set maximum line length to 80 characters.
- Change return type of quic_packet_empty() to bool.
- Propagate errors from quic_packet_route() in quic_packet_config() (noted by AI review).
- Use quic_packet_taglen() instead of open-coded logic in quic_packet_mss(), quic_packet_max_payload(), and quic_packet_max_payload_dgram() (noted by AI review).
- Replace some magic numbers with QUIC_PACKET_FORM_SHORT/LONG and QUIC_PACKET_MSS_NORMAL/DGRAM (noted by Paolo).
- Use WARN_ON_ONCE() instead of WARN_ON() in quic_packet_xmit(). skb_set_owner_w/r() cannot be used here because it performs memory accounting, which is not desired in this context (noted by Paolo).
v12:
- Set the minimum PMTU to 1200 in quic_packet_route().
- Increase overhead in struct packet from u8 to u16, update the related cast and remove DEBUG_NET_WARN_ON_ONCE() in quic_packet_config().
- Fix the MSS-based bundling size check and call skb_orphan() before bundling the skb in quic_packet_bundle().
- Remove the quic_packet_xmit() declaration and mark it static.
- Extract quic_packet_overhead() from quic_packet_config().
- Change quic_packet_create_and_xmit() to return 0 on success and an error code on failure.
- Remove errframe, errcode, frame_len, and ack_requested from struct quic_packet as they are no longer used, and update quic_packet_reset() accordingly.
- Move ack_eliciting reset from quic_packet_config() to quic_packet_reset(), as it will only be used on the RX path.
- Add padding as u16 in struct quic_packet to represent total padding bytes appended after frames.
- Add path_validating in struct quic_packet for TX path to indicate whether a path_validating frame is included in the packet, and reset it in quic_packet_config().
- Move version and padding fields up in struct quic_packet for better layout.
- Fix the comment for len, frames, ack_eliciting, non_probing and has_sack in struct quic_packet.
- Include taglen when updating the mss in struct quic_cong.
--- net/quic/Makefile | 2 +- net/quic/packet.c | 279 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/packet.h | 112 +++++++++++++++++++ net/quic/socket.c | 1 + net/quic/socket.h | 8 ++ 5 files changed, 401 insertions(+), 1 deletion(-) create mode 100644 net/quic/packet.c create mode 100644 net/quic/packet.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o crypto.o timer.o + cong.o pnspace.o crypto.o timer.o packet.o
net/quic/packet.c new file +279 -0
279 lines not on this page · raw message
net/quic/packet.h new file +112 -0
112 lines not on this page · raw message
net/quic/socket.c +1 -0
@@ -68,6 +68,7 @@ static int quic_init_sock(struct sock *sk)quic_cong_init (quic_cong (sk));quic_timer_init (sk); +quic_packet_init (sk);if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
net/quic/socket.h +8 -0
@@ -20,6 +20,8 @@#include "path.h" #include "cong.h" +#include "packet.h" +#include "protocol.h" #include "timer.h"
@@ -74,6 +76,7 @@ struct quic_sock {struct quic_pnspace space[QUIC_PNSPACE_MAX ];struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; +struct quic_packet packet;struct quic_timer timers[QUIC_TIMER_MAX ]; };
@@ -147,6 +150,11 @@ static inline struct quic_crypto *quic_crypto(const struct sock *sk, u8 level)return &quic_sk (sk)->crypto[level]; } +static inline struct quic_packet *quic_packet (const struct sock *sk) +{ +return &quic_sk (sk)->packet; +} +static inline void *quic_timer (const struct sock *sk,u8 type) {return (void *)&quic_sk (sk)->timers[type];
Signature · 1 line
2.47.1
PATCH v13 15/15 quic: add packet parser base
In reply to Xin LongThis patch uses 'quic_packet' to handle packing of QUIC packets on the receive (RX) path.
It introduces mechanisms to parse the ALPN from client Initial packets to determine the correct listener socket. Received packets are then routed and processed accordingly. Similar to the TX path, handling for application and handshake packets is not yet implemented.
- quic_packet_parse_alpn()`: Parse the ALPN from a client Initial packet, then locate the appropriate listener using the ALPN.
- quic_packet_rcv(): Locate the appropriate socket to handle the packet via quic_packet_process().
- quic_packet_process()`: Process the received packet.
In addition to packet flow, this patch adds support for ICMP-based MTU updates by locating the relevant socket and updating the stored PMTU accordingly.
- quic_packet_rcv_err_pmtu(): Find the socket and update the PMTU via quic_packet_mss_update().
---
v5:
- In quic_packet_rcv_err(), remove the unnecessary quic_is_listen() check and move quic_get_mtu_info() out of sock lock (suggested by Paolo).
- Replace cancel_work_sync() to disable_work_sync() (suggested by
Paolo).
v6:
- Fix the loop using skb_dequeue() in quic_packet_backlog_work(), and kfree_skb() when sk is not found (reported by AI Reviews).
- Remove skb_pull() from quic_packet_rcv(), since it is now handled
in quic_path_rcv().
- Note for AI reviews: add if (dst) check in quic_packet_rcv_err_pmtu(), although quic_packet_route() >= 0 already guarantees it is not NULL.
- Note for AI reviews: it is safe to do *plen -= QUIC_HLEN in quic_packet_get_version_and_connid(), since quic_packet_get_sock() already checks if (skb->len < QUIC_HLEN).
- Note for AI reviews: cb->length - cb->number_len - QUIC_TAG_LEN cannot underflow, because quic_crypto_header_decrypt() already checks if (cb->length < QUIC_PN_MAX_LEN + QUIC_SAMPLE_LEN).
- Note for AI reviews: the cast length in quic_packet_parse_alpn() is safe, as there is a prior check if (length > (u16)len); len is skb->len, which cannot exceed U16_MAX for UDP packet with QUIC.
- Note for AI reviews: it's correct to do if (flags & QUIC_F_MTU_REDUCED_DEFERRED) in quic_release_cb(), since QUIC_MTU_REDUCED_DEFERRED is the bit used with test_and_set_bit().
- Note for AI reviews: move skb_cb->backlog = 1 before adding skb to backlog, although it's safe to write skb_cb after adding to backlog with sk_lock.slock, as skb dequeue from backlog requires sk_lock.slock.
v7:
- Pass udp sk to quic_packet_rcv(), quic_packet_rcv_err() and
quic_sock_lookup().
- Move the call to skb_linearize() and skb_set_owner_sk_safe() to
.quic_path_rcv()/quic_packet_rcv().v8:
- Replace the global ALPN demultiplexing sysctl with the static key in quic_packet_parse_alpn() (noted by Stefan).
- Refetch skb->data after decrypt in ALPN parsing, as skb_cow_data() may reallocate the skb data buffer (reported by Syzkaller).
- The indirect quic_path_rcv has been removed and call quic_packet_rcv() directly via extern.
- Do not restore skb data when QUIC Initial decryption fails, as the caller will free the skb for this failure anyway.
- With patch 14 removed, define a temporary QUIC_FRAME_CRYPTO ID when parsing the ALPN.
v9:
- Remove local_bh_disable() in quic_packet_get_listen_sock() as it's now using rcu_read_lock instead of spin_sock in quic_listen_sock_lookup() (noted by Paolo).
v10:
- Return QUIC_PACKET_INVALID (instead of -1) for invalid packet types in quic_packet_version_get_type().
- Update the comment to clarify in quic_packet_rcv_err() that ICMP errors embed the original QUIC packet, reversing src/dst addrs when parsed.
- Use qn->backlog_list.lock in quic_packet_backlog_schedule() to
prevent a TOCTOU race between the head->qlen check and its update in
__skb_queue_tail(). - Add check 'len < TLS_CH_RANDOM_LEN + TLS_CH_VERSION_LEN' before parsing ClientHello in quic_packet_get_alpn().
- Add more limits in quic_packet_get_alpn() to improve robustness against malformed TLS ClientHello messages.
- Move skb_queue_purge() to after disable_work_sync() in quic_net_exit() for clarity and to satisfy AI review.
- quic_sock.config.plpmtud_probe_interval has been moved to quic_path_group.plpmtud_interval, so update its usage in quic_packet_rcv_err_pmtu() accordingly.
- Remove quic_packet_select_version() and quic_packet_version_change(); they will be reintroduced later when needed in the next patch series.
v11:
- Note for AI review: refcount increments in quic_listen_sock_lookup() and quic_sock_lookup() are left unchanged due to code complexity.
- Set maximum line length to 80 characters.
- Do not mark backlog packets as sleepable (cb->backlog = 1) in sk_add_backlog path; Replace spin_(un)lock() with spin_(un)lock_bh() in quic_packet_backlog_schedule().
- Return -ENOBUFS instead of -1 in quic_packet_backlog_schedule().
- Change err parameter type from u8 to bool (icmp) in quic_packet_rcv().
- Propagate errors from quic_packet_get_sock() and sk_add_backlog() in
quic_packet_rcv().
- Propagate errors from quic_packet_get_dcid() and quic_packet_parse_alpn() in quic_packet_get_sock() via ERR_PTR().
- Propagate errors from quic_packet_parse_alpn() in quic_packet_get_listen_sock() via ERR_PTR().
- Propagate errors from quic_packet_get_version_and_connid() and quic_packet_get_token() in quic_packet_parse_alpn().
- Do not hold skb when calling quic_packet_backlog_schedule() in quic_packet_parse_alpn(); do not free skb when returning -EINPROGRESS from quic_packet_get_sock() in quic_packet_rcv().
- Move the quic_packet_rcv() declaration from packet.h to path.h, as it's only called in path.c (noted by AI review).
- Merge quic_packet_get_dcid() and quic_packet_get_version_and_connid() into quic_packet_get_long_header() and extract quic_packet_get_connid() (noted by AI review).
v12:
- Check quic_is_closed() in quic_packet_rcv_err_pmtu().
- Remove the ip_sk_accept_pmtu() check from quic_packet_rcv_err_pmtu(), and check quic_sk_accept_pmtu() in quic_packet_rcv_err().
- Call cond_resched() in the loop inside quic_packet_backlog_work().
- Update the comment for the get_nulls_value(node) check in quic_sock_lookup(), and remove the unnecessary get_nulls_value(node) check and add comment for it in quic_listen_sock_lookup().
- Improve matching order: specific address > ANY address (same family) > ANY address (different family) in quic_listen_sock_lookup().
- Defer quic_alpn destruction from quic_destroy_sock() to quic_sock_destruct(), as it may still be accessed in quic_listen_sock_lookup() under rcu_read_lock().
- Initialize dcid/scid variables at declaration in quic_packet_get_sock() and quic_packet_parse_alpn().
- Set packet->level before calling quic_packet_taglen() in
quic_packet_rcv_err_pmtu().
- Set cb->sync to 1 to ensure decryption runs in sync mode.
v13:
- Add comment explaining why ALPN free is deferred in quic_sock_destruct().
- Improve loop boundary check while parsing ALPN extensions in
quic_packet_get_alpn(). --- net/quic/packet.c | 608 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/packet.h | 8 + net/quic/path.c | 4 +- net/quic/path.h | 2 + net/quic/protocol.c | 5 + net/quic/protocol.h | 4 + net/quic/socket.c | 158 +++++++++++- net/quic/socket.h | 7 + 8 files changed, 793 insertions(+), 3 deletions(-)
net/quic/packet.c +608 -0
@@ -14,6 +14,614 @@#define QUIC_HLEN 1 +#define QUIC_LONG_HLEN (dcid, scid) \ + (QUIC_HLEN + QUIC_VERSION_LEN + 1 + (dcid)->len + 1 + (scid)->len) + +#define QUIC_VERSION_NUM 2 + +/* Supported QUIC versions and their compatible versions. Used for Compatible +* Version Negotiation in rfc9368#section-2.3. +*/ +static u32 quic_versions[QUIC_VERSION_NUM ][4 ] = { +/* Version, Compatible Versions */ + {QUIC_VERSION_V1 ,QUIC_VERSION_V2 ,QUIC_VERSION_V1 ,0 }, + {QUIC_VERSION_V2 ,QUIC_VERSION_V2 ,QUIC_VERSION_V1 ,0 }, +}; + +/* Get the compatible version list for a given QUIC version. */ +u32 *quic_packet_compatible_versions (u32 version) +{ +u8 i; + +for (i =0 ; i <QUIC_VERSION_NUM ; i++) +if (version == quic_versions[i][0 ]) +return quic_versions[i]; +return NULL ; +} + +/* Convert version-specific type to internal standard packet type. */ +static u8 quic_packet_version_get_type (u32 version,u8 type) +{ +if (version ==QUIC_VERSION_V1 ) +return type; + +switch (type) { +case QUIC_PACKET_INITIAL_V2 : +return QUIC_PACKET_INITIAL ; +case QUIC_PACKET_0RTT_V2 : +return QUIC_PACKET_0RTT ; +case QUIC_PACKET_HANDSHAKE_V2 : +return QUIC_PACKET_HANDSHAKE ; +case QUIC_PACKET_RETRY_V2 : +return QUIC_PACKET_RETRY ; +default : +return QUIC_PACKET_INVALID ; + } +} + +/* Extracts a QUIC Connection ID from a buffer in the long header packet. */ +static int quic_packet_get_connid (struct quic_conn_id *connid,u8 **pp, +u32 *plen) +{ +u64 len; + +if (!quic_get_int (pp, plen, &len,1 ) || + len > *plen || len >QUIC_CONN_ID_MAX_LEN ) +return -EINVAL ; + +quic_conn_id_update (connid, *pp, len); + *plen -= len; + *pp += len; +return 0 ; +} + +/* Parse QUIC version and connection IDs (DCID and SCID) from a Long header +* packet buffer. +*/ +static int quic_packet_get_long_header (struct quic_conn_id *dcid, +struct quic_conn_id *scid,u32 *version, +u8 **pp,u32 *plen) +{ +int err; +u64 v; + + *pp +=QUIC_HLEN ; + *plen -=QUIC_HLEN ; + +if (!quic_get_int (pp, plen, &v,QUIC_VERSION_LEN )) +return -EINVAL ; +if (version) + *version = v; + + err =quic_packet_get_connid (dcid, pp, plen); +if (err) +return err; +if (!scid) +return 0 ; +return quic_packet_get_connid (scid, pp, plen); +} + +/* Extracts a QUIC token from a buffer in the Client Initial packet. */ +static int quic_packet_get_token (struct quic_data *token,u8 **pp,u32 *plen) +{ +u64 len; + +if (!quic_get_var (pp, plen, &len) || len > *plen) +return -EINVAL ; +quic_data (token, *pp, len); + *plen -= len; + *pp += len; +return 0 ; +} + +/* Process PMTU reduction event on a QUIC socket. */ +void quic_packet_rcv_err_pmtu (struct sock *sk) +{ +struct quic_path_group *paths =quic_paths (sk); +struct quic_packet *packet =quic_packet (sk); +u32 pathmtu, info, taglen; +struct dst_entry *dst; +bool reset_timer; + +if (quic_is_closed (sk)) +return ; + + info =clamp (paths->mtu_info,QUIC_PATH_MIN_PMTU ,QUIC_PATH_MAX_PMTU ); +/* If PLPMTUD is not enabled, update MSS using route and ICMP info. */ +if (!paths->plpmtud_interval) { +if (quic_packet_route (sk)) +return ; + + dst =__sk_dst_get (sk); +if (dst) + dst->ops->update_pmtu (dst, sk,NULL , info, true); +quic_packet_mss_update (sk, info - packet->hlen); +return ; + } +/* PLPMTUD is enabled: adjust to smaller PMTU, subtract headers and +* AEAD tag. Also notify the QUIC path layer for possible state +* changes and probing. +*/ + packet->level =QUIC_CRYPTO_APP ; + taglen =quic_packet_taglen (packet); + info = info - packet->hlen - taglen; + pathmtu =quic_path_pl_toobig (paths, info, &reset_timer); +if (reset_timer) +quic_timer_reset (sk,QUIC_TIMER_PMTU , paths->plpmtud_interval); +if (pathmtu) +quic_packet_mss_update (sk, pathmtu + taglen); +} + +/* Handle ICMP Toobig packet and update QUIC socket path MTU. */ +static int quic_packet_rcv_err (struct sock *sk,struct sk_buff *skb) +{ +union quic_addr daddr, saddr; +u32 info; + +/* ICMP embeds the original outgoing QUIC packet, so saddr/daddr are +* reversed when parsed. Only address-based socket lookup is possible +* in this case. +*/ +quic_get_msg_addrs (skb, &saddr, &daddr); + sk =quic_sock_lookup (skb, &daddr, &saddr, sk,NULL ); +if (!sk) +return -ENOENT ; + +if (quic_get_mtu_info (skb, &info) || !quic_sk_accept_pmtu (sk, skb)) { +sock_put (sk); +return 0 ; + } + +/* Success: update socket path MTU info. */ +bh_lock_sock (sk); +quic_paths (sk)->mtu_info = info; +if (sock_owned_by_user (sk)) { +/* Socket locked by userspace. Defer MTU processing via +* release_cb. Hold socket reference to prevent it being +* freed before deferral. +*/ +if (!test_and_set_bit (QUIC_MTU_REDUCED_DEFERRED , + &sk->sk_tsq_flags)) +sock_hold (sk); + goto out; + } +/* Otherwise, process the MTU reduction now. */ +quic_packet_rcv_err_pmtu (sk); +out: +bh_unlock_sock (sk); +sock_put (sk); +return 1 ; +} + +#define QUIC_PACKET_BACKLOG_MAX 4096 + +/* Queue a packet for later processing when sleeping is allowed. */ +static int quic_packet_backlog_schedule (struct net *net,struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quic_net *qn =quic_net (net); +struct sk_buff_head *head; + +if (cb->backlog) +return 0 ; + + head = &qn->backlog_list; +spin_lock_bh (&head->lock); +if (head->qlen >=QUIC_PACKET_BACKLOG_MAX ) { +spin_unlock_bh (&head->lock); +QUIC_INC_STATS (net,QUIC_MIB_PKT_RCVDROP ); +kfree_skb (skb); +return -ENOBUFS ; + } + cb->backlog =1 ; +__skb_queue_tail (head, skb); +spin_unlock_bh (&head->lock); + +queue_work (quic_wq, &qn->work); +return 1 ; +} + +#define TLS_MT_CLIENT_HELLO 1 +#define TLS_EXT_alpn 16 + +/* TLS Client Hello Msg: +* +* uint16 ProtocolVersion; +* opaque Random[32]; +* uint8 CipherSuite[2]; +* +* struct { +* ExtensionType extension_type; +* opaque extension_data<0..2^16-1>; +* } Extension; +* +* struct { +* ProtocolVersion legacy_version = 0x0303; +* Random rand; +* opaque legacy_session_id<0..32>; +* CipherSuite cipher_suites<2..2^16-2>; +* opaque legacy_compression_methods<1..2^8-1>; +* Extension extensions<8..2^16-1>; +* } ClientHello; +*/ + +#define TLS_CH_RANDOM_LEN 32 +#define TLS_CH_VERSION_LEN 2 +#define TLS_MAX_EXTENSIONS 128 + +/* Extract ALPN data from a TLS ClientHello message. +* +* Parses the TLS ClientHello handshake message to find the ALPN (Application +* Layer Protocol Negotiation) TLS extension. It validates the TLS ClientHello +* structure, including version, random, session ID, cipher suites, compression +* methods, and extensions. Once the ALPN extension is found, the ALPN +* protocols list is extracted and stored in @alpn. +* +* Return: 0 on success or no ALPN found, a negative error code on failed +* parsing. +*/ +static int quic_packet_get_alpn (struct quic_data *alpn,u8 *p,u32 len) +{ +int err = -EINVAL , found =0 , exts =0 ; +u64 length, type; + +/* Verify handshake message type (ClientHello) and its length. */ +if (!quic_get_int (&p, &len, &type,1 ) || type !=TLS_MT_CLIENT_HELLO ) +return err; +if (!quic_get_int (&p, &len, &length,3 ) || + len <TLS_CH_RANDOM_LEN +TLS_CH_VERSION_LEN || + length <TLS_CH_RANDOM_LEN +TLS_CH_VERSION_LEN ) +return err; +if (len > (u32 )length)/* Cap len to handshake msg length. */ + len = length; +/* Skip legacy_version (2 bytes) + random (32 bytes). */ + p +=TLS_CH_RANDOM_LEN +TLS_CH_VERSION_LEN ; + len -=TLS_CH_RANDOM_LEN +TLS_CH_VERSION_LEN ; +/* legacy_session_id_len must be zero (QUIC requirement). */ +if (!quic_get_int (&p, &len, &length,1 ) || length) +return err; + +/* Skip cipher_suites (2 bytes length + variable data). */ +if (!quic_get_int (&p, &len, &length,2 ) || length > (u64 )len) +return err; + len -= length; + p += length; + +/* Skip legacy_compression_methods (1 byte length + variable data). */ +if (!quic_get_int (&p, &len, &length,1 ) || length > (u64 )len) +return err; + len -= length; + p += length; + +/* Read TLS extensions length (2 bytes). */ +if (!quic_get_int (&p, &len, &length,2 )) +return err; +if (len > (u32 )length)/* Limit len to extensions length if larger. */ + len = length; +while (len >=4 ) {/* Scan extensions for ALPN (TLS_EXT_alpn). */ +if (!quic_get_int (&p, &len, &type,2 )) +break ; +if (!quic_get_int (&p, &len, &length,2 )) +break ; +if (len < (u32 )length)/* Incomplete TLS extensions. */ +return 0 ; +if (type == TLS_EXT_alpn) {/* Found ALPN extension. */ +if (length >QUIC_ALPN_MAX_LEN ) +return err; + len = length; + found =1 ; +break ; + } +/* Skip non-ALPN extensions. */ + p += length; + len -= length; +if (exts++ >=TLS_MAX_EXTENSIONS ) +return err; + } +if (!found) {/* No ALPN ext: set alpn->len = 0 and alpn->data = p. */ +quic_data (alpn, p,0 ); +return 0 ; + } + +/* Parse ALPN protocols list length (2 bytes). */ +if (!quic_get_int (&p, &len, &length,2 ) || length > (u64 )len) +return err; +quic_data (alpn, p, length);/* Store ALPN list in alpn->data. */ + len = length; +while (len) {/* Validate ALPN protocols list format. */ +if (!quic_get_int (&p, &len, &length,1 ) || length > (u64 )len) { +/* Bad ALPN: set alpn->len = 0, alpn->data = NULL. */ +quic_data (alpn,NULL ,0 ); +return err; + } + len -= length; + p += length; + } +pr_debug ("%s: alpn_len: %d\n" , __func__, alpn->len); +return 0 ; +} + +#define QUIC_FRAME_CRYPTO 0x06 + +/* Parse ALPN from a QUIC Initial packet. +* +* This function processes a QUIC Initial packet to extract the ALPN from the +* TLS ClientHello message inside the QUIC CRYPTO frame. It verifies packet +* type, version compatibility, decrypts the packet payload, and locates the +* CRYPTO frame to parse the TLS ClientHello. Finally, it calls +* quic_packet_get_alpn() to extract the ALPN extension data. +* +* Return: 0 on success or no ALPN found, a negative error code on failed +* parsing. +*/ +static int quic_packet_parse_alpn (struct sk_buff *skb,struct quic_data *alpn) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quic_conn_id dcid = {}, scid = {}; +struct net *net =sock_net (skb->sk); +u32 len = skb->len, version; +struct quic_crypto *crypto; +u8 *p = skb->data, type; +struct quic_data token; +u64 offset, length; +int err; + +if (!static_branch_unlikely (&quic_alpn_demux_key)) +return 0 ; + err =quic_packet_get_long_header (&dcid, &scid, &version, &p, &len); +if (err) +return err; +if (!quic_packet_compatible_versions (version)) +return 0 ; +/* Only parse Initial packets. */ + type =quic_packet_version_get_type (version,quic_hshdr (skb)->type); +if (type !=QUIC_PACKET_INITIAL ) +return 0 ; + err =quic_packet_get_token (&token, &p, &len); +if (err) +return err; +if (!quic_get_var (&p, &len, &length) || length > (u64 )len) +return -EINVAL ; +if (quic_packet_backlog_schedule (net, skb)) +return -EINPROGRESS ; + cb->length = (u16 )length; + +/* Install initial keys for packet decryption to crypto. */ + crypto = &quic_net (net)->crypto; + err =quic_crypto_initial_keys_install (crypto, &dcid, version,1 ); +if (err) +return err; + cb->number_offset = (u16)(p - skb->data); + cb->sync =1 ; + err =quic_crypto_decrypt (crypto, skb); +if (err) { +QUIC_INC_STATS (net,QUIC_MIB_PKT_DECDROP ); +return err; + } + +QUIC_INC_STATS (net,QUIC_MIB_PKT_DECFASTPATHS ); + cb->resume =1 ;/* Mark this packet as already decrypted. */ + +/* Find the QUIC CRYPTO frame. */ + p = skb->data + cb->number_offset + cb->number_len; + len = cb->length - cb->number_len -QUIC_TAG_LEN ; +for (; len && !(*p); p++, len--)/* Skip the padding frame. */ + ; +if (!len-- || *p++ !=QUIC_FRAME_CRYPTO ) +return 0 ; +if (!quic_get_var (&p, &len, &offset) || offset) +return 0 ; +if (!quic_get_var (&p, &len, &length) || length > (u64 )len) +return 0 ; + +/* Parse the TLS CLIENT_HELLO message. */ +return quic_packet_get_alpn (alpn, p, length); +} + +/* Lookup listening socket for Client Initial packet (in process context). */ +static struct sock *quic_packet_get_listen_sock (struct sk_buff *skb) +{ +union quic_addr daddr, saddr; +struct quic_data alpns = {}; +struct sock *sk; +int err; + +quic_get_msg_addrs (skb, &daddr, &saddr); + + err =quic_packet_parse_alpn (skb, &alpns); +if (err) +return ERR_PTR (err); + + sk =quic_listen_sock_lookup (skb, &daddr, &saddr, &alpns); +if (!sk) +return ERR_PTR (-ENOENT ); +return sk; +} + +/* Determine the QUIC socket associated with an incoming packet. */ +static struct sock *quic_packet_get_sock (struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quic_conn_id dcid = {}, *conn_id; +struct net *net =sock_net (skb->sk); +union quic_addr daddr, saddr; +struct quic_data alpns = {}; +struct sock *sk =NULL ; +u32 len = skb->len; +u8 *p = skb->data; +int err; + +if (skb->len <QUIC_HLEN ) +return ERR_PTR (-EINVAL ); + +if (quic_hdr (skb)->form ==QUIC_PACKET_FORM_SHORT ) { +/* Short header path. */ +if (skb->len <QUIC_HLEN +QUIC_CONN_ID_DEF_LEN ) +return ERR_PTR (-EINVAL ); +/* Fast path: look up QUIC connection by fixed-length DCID +* (Currently, only QUIC_CONN_ID_DEF_LEN-length SCIDs are used). +*/ + conn_id =quic_conn_id_lookup (net, skb->data +QUIC_HLEN , +QUIC_CONN_ID_DEF_LEN ); +if (conn_id) { + cb->seqno =quic_conn_id_number (conn_id); +/* Return associated socket. */ +return quic_conn_id_sk (conn_id); + } + +/* Fallback: listener socket lookup +* (May be used to send a stateless reset from a listen socket). +*/ +quic_get_msg_addrs (skb, &daddr, &saddr); + sk =quic_listen_sock_lookup (skb, &daddr, &saddr, &alpns); +if (sk) +return sk; +/* Final fallback: address-based connection lookup +* (May be used to receive a stateless reset). +*/ + sk =quic_sock_lookup (skb, &daddr, &saddr, skb->sk,NULL ); +if (!sk) +return ERR_PTR (-ENOENT ); +return sk; + } + +/* Long header path. */ + err =quic_packet_get_long_header (&dcid,NULL ,NULL , &p, &len); +if (err) +return ERR_PTR (err); +/* Fast path: look up QUIC connection by parsed DCID. */ + conn_id =quic_conn_id_lookup (net, dcid.data, dcid.len); +if (conn_id) { + cb->seqno =quic_conn_id_number (conn_id); +return quic_conn_id_sk (conn_id);/* Return associated socket. */ + } + +/* Fallback: address + DCID lookup +* (May be used for 0-RTT or a follow-up Client Initial packet). +*/ +quic_get_msg_addrs (skb, &daddr, &saddr); + sk =quic_sock_lookup (skb, &daddr, &saddr, skb->sk, &dcid); +if (sk) +return sk; +/* Final fallback: listener socket lookup +* (Used for receiving the first Client Initial packet). +*/ + err =quic_packet_parse_alpn (skb, &alpns); +if (err) +return ERR_PTR (err); + sk =quic_listen_sock_lookup (skb, &daddr, &saddr, &alpns); +if (!sk) +return ERR_PTR (-ENOENT ); +return sk; +} + +/* Entry point for processing received QUIC packets. */ +int quic_packet_rcv (struct sock *sk,struct sk_buff *skb,bool icmp) +{ +struct net *net =sock_net (sk); +int err; + +if (unlikely (icmp)) +return quic_packet_rcv_err (sk, skb); + +/* Save the UDP socket to skb->sk for later QUIC socket lookup. */ +if (skb_linearize (skb) || !skb_set_owner_sk_safe (skb, sk)) { + err = -EINVAL ; + goto err; + } + +/* Look up socket from socket or connection IDs hash tables. */ + sk =quic_packet_get_sock (skb); +if (IS_ERR (sk)) { + err =PTR_ERR (sk); +if (err == -EINPROGRESS ) +return 0 ; + goto err; + } + +bh_lock_sock (sk); +if (sock_owned_by_user (sk)) { +/* Socket is busy (owned by user context): queue to backlog. */ + err =sk_add_backlog (sk, skb,READ_ONCE (sk->sk_rcvbuf)); +if (err) { +bh_unlock_sock (sk); +sock_put (sk); + goto err; + } +QUIC_INC_STATS (net,QUIC_MIB_PKT_RCVBACKLOGS ); + }else { +/* Socket not busy: process immediately. */ +QUIC_INC_STATS (net,QUIC_MIB_PKT_RCVFASTPATHS ); + sk->sk_backlog_rcv (sk, skb);/* quic_packet_process(). */ + } +bh_unlock_sock (sk); +sock_put (sk); +return 0 ; +err: +pr_debug ("%s: failed, len: %d, err: %d\n" , __func__, skb->len, err); +QUIC_INC_STATS (net,QUIC_MIB_PKT_RCVDROP ); +kfree_skb (skb); +return err; +} + +static int quic_packet_listen_process (struct sock *sk,struct sk_buff *skb) +{ +kfree_skb (skb); +return -EOPNOTSUPP ; +} + +static int quic_packet_handshake_process (struct sock *sk,struct sk_buff *skb) +{ +kfree_skb (skb); +return -EOPNOTSUPP ; +} + +static int quic_packet_app_process (struct sock *sk,struct sk_buff *skb) +{ +kfree_skb (skb); +return -EOPNOTSUPP ; +} + +int quic_packet_process (struct sock *sk,struct sk_buff *skb) +{ +if (quic_is_closed (sk)) { +kfree_skb (skb); +return 0 ; + } + +if (quic_is_listen (sk)) +return quic_packet_listen_process (sk, skb); + +if (quic_hdr (skb)->form ==QUIC_PACKET_FORM_LONG ) +return quic_packet_handshake_process (sk, skb); + +return quic_packet_app_process (sk, skb); +} + +/* Work function to process packets in the backlog queue. */ +void quic_packet_backlog_work (struct work_struct *work) +{ + struct quic_net *qn = container_of(work, struct quic_net, work); +struct sk_buff_head *head = &qn->backlog_list; +struct sk_buff *skb; +struct sock *sk; + +while ((skb =skb_dequeue (head)) !=NULL ) { + sk =quic_packet_get_listen_sock (skb); +if (IS_ERR (sk)) { +QUIC_INC_STATS (sock_net (skb->sk),QUIC_MIB_PKT_RCVDROP ); +kfree_skb (skb); +continue ; + } + +lock_sock (sk); +quic_packet_process (sk, skb); +release_sock (sk); +sock_put (sk); +cond_resched (); + } +} +/* Make these fixed for easy coding. */ #define QUIC_PACKET_NUMBER_LEN QUIC_PN_MAX_LEN#define QUIC_PACKET_LENGTH_LEN 4
net/quic/packet.h +8 -0
@@ -54,6 +54,8 @@ struct quic_packet {#define QUIC_VERSION_LEN 4 +#define QUIC_ALPN_MAX_LEN 128 +#define QUIC_PACKET_MSS_NORMAL 0#define QUIC_PACKET_MSS_DGRAM 1
@@ -101,6 +103,7 @@ static inline void quic_packet_reset(struct quic_packet *packet) packet->ack_immediate =0 ; } +int quic_packet_process (struct sock *sk,struct sk_buff *skb);u16 quic_packet_overhead (struct sock *sk,u8 level,u8 path);int quic_packet_config (struct sock *sk,u8 level,u8 path);
@@ -110,3 +113,8 @@ int quic_packet_route(struct sock *sk);void quic_packet_mss_update (struct sock *sk,u32 mss);void quic_packet_flush (struct sock *sk);void quic_packet_init (struct sock *sk); + +u32 *quic_packet_compatible_versions (u32 version); + +void quic_packet_backlog_work (struct work_struct *work); +void quic_packet_rcv_err_pmtu (struct sock *sk);
net/quic/path.c +2 -2
@@ -27,14 +27,14 @@ static int quic_udp_rcv(struct sock *sk, struct sk_buff *skb)skb_pull (skb,sizeof (struct udphdr ));skb_dst_force (skb); -kfree_skb (skb); +quic_packet_rcv (sk, skb, false);/* .encap_rcv must return 0 if skb was either consumed or dropped. */ return 0 ; }static int quic_udp_err (struct sock *sk,struct sk_buff *skb) { -return 0 ; +return quic_packet_rcv (sk, skb, true); }static void quic_udp_sock_put_work (struct work_struct *work)
net/quic/path.h +2 -0
@@ -167,6 +167,8 @@ quic_path_orig_dcid(struct quic_path_group *paths)return paths->retry ? &paths->retry_dcid : &paths->orig_dcid; } +int quic_packet_rcv (struct sock *sk,struct sk_buff *skb,bool icmp); +bool quic_path_detect_alt (struct quic_path_group *paths,union quic_addr *sa,union quic_addr *da,struct sock *sk);int quic_path_bind (struct sock *sk,struct quic_path_group *paths,u8 path);
net/quic/protocol.c +5 -0
@@ -245,6 +245,9 @@ static int __net_init quic_net_init(struct net *net)return err; } +INIT_WORK (&qn->work, quic_packet_backlog_work); +skb_queue_head_init (&qn->backlog_list); +#if IS_ENABLED (CONFIG_PROC_FS ) err =quic_net_proc_init (net);if (err) {
@@ -263,6 +266,8 @@ static void __net_exit quic_net_exit(struct net *net)#if IS_ENABLED (CONFIG_PROC_FS )quic_net_proc_exit (net);#endif +disable_work_sync (&qn->work); +skb_queue_purge (&qn->backlog_list);quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ;
net/quic/protocol.h +4 -0
@@ -51,6 +51,10 @@ struct quic_net {#endif /* Context for decrypting Initial packets for ALPN */ struct quic_crypto crypto; + +/* Queue of packets deferred for processing in process context */ +struct sk_buff_head backlog_list; +struct work_struct work;/* Work to drain/process backlog_list */ };struct quic_net *quic_net (struct net *net);
net/quic/socket.c +157 -1
194 lines not on this page · raw message
net/quic/socket.h +7 -0
@@ -200,3 +200,10 @@ static inline void quic_set_state(struct sock *sk, int state)inet_sk_set_state (sk, state); sk->sk_state_change (sk); } + +struct sock *quic_listen_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da, +struct quic_data *alpns); +struct sock *quic_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da,struct sock *usk, +struct quic_conn_id *dcid);
Signature · 1 line
2.47.1
Paolo Abeni
maintainerRe: [PATCH net-next v13 15/15] quic: add packet parser base
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
quic: add packet parser base
This patch adds the QUIC packet RX parser, including ALPN extraction from the Client Initial to demux to the right listener, an ICMP-driven PMTU update path, and a per-net backlog/work for deferred parsing.
Quoted 4 lines
net/quic/packet.c +0
-0
[ ... ]
Quoted 5 lines
net/quic/packet.c +5
-0+static int quic_packet_get_alpn (struct quic_data *alpn,u8 *p,u32 len) +{ +int err = -EINVAL , found =0 , exts =0 ; +u64 length, type; +
[ ... ]
net/quic/packet.c line 307
Quoted 7 lines
net/quic/packet.c +7
-0+while (len >=4 ) {/* Scan extensions for ALPN (TLS_EXT_alpn). */ +if (!quic_get_int (&p, &len, &type,2 )) +break ; +if (!quic_get_int (&p, &len, &length,2 )) +break ; +if (len < (u32 )length)/* Incomplete TLS extensions. */ +return 0 ;
[Medium]
Should this branch be treated as a parse failure rather than a success?
The other length-bound checks in this same function return err (-EINVAL) when a declared length exceeds the remaining buffer, but this one returns 0 without populating alpn. The callers initialise alpn as
struct quic_data alpns = {};and quic_listen_sock_lookup() then takes the no-ALPN branch:
if (!alpns->len) { /* No ALPNs or parse failed */
sk_nulls_for_each_rcu(tmp, node, &head->head) {
...
if (... && (!alpns->data || !quic_alpn(tmp)->len)) {Because alpns->data is still NULL, the match collapses to true and any listener bound to the address/port will match, including ones that registered a specific ALPN list. Can a peer reach an ALPN-restricted listener by sending a Client Initial with one extension whose declared length is larger than what is left in the ClientHello?
Would returning err here (or always assigning alpn->data before returning) match the comment in quic_listen_sock_lookup() that distinguishes "TLS parsing succeeded but no ALPN was found" from "parse failed"?
net/quic/packet.c line 319
Quoted 12 lines
net/quic/packet.c +12
-0+if (type == TLS_EXT_alpn) {/* Found ALPN extension. */ +if (length >QUIC_ALPN_MAX_LEN ) +return err; + len = length; + found =1 ; +break ; + } +/* Skip non-ALPN extensions. */ + p += length; + len -= length; +if (exts++ >=TLS_MAX_EXTENSIONS ) +return err;
[Low]
Is the post-increment intended here? With TLS_MAX_EXTENSIONS == 128, the check (exts++ >= 128) first becomes true when exts has already reached 129, so 129 extensions are consumed before bail-out even though the constant name suggests a cap of 128. Would
if (++exts > TLS_MAX_EXTENSIONS) return err;
(or moving the check to the loop top) better reflect the intended limit?
Quoted 1 line
net/quic/packet.c +1
-0+ }
[ ... ]
Quoted 1 line
+static int
quic_packet_parse_alpn(struct sk_buff *skb, struct quic_data *alpn)
[ ... ]
Quoted 4 lines
net/quic/socket.c +0
-0
[ ... ]
Quoted 4 lines
net/quic/socket.c +4
-0+struct sock *quic_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da,struct sock *usk, +struct quic_conn_id *dcid) +{
[ ... ]
Quoted 5 lines
net/quic/socket.c +5
-0+rcu_read_lock (); +begin: +sk_nulls_for_each_rcu (tmp, node, &head->head) { +if (net !=sock_net (tmp)) +continue ;
net/quic/socket.c static void quic_enter_memory_pressure(struct sock *sk) · line 71
Quoted 10 lines
net/quic/socket.c +10
-0+ paths =quic_paths (tmp); + odcid =quic_path_orig_dcid (paths); +if (quic_cmp_sk_addr (tmp,quic_path_saddr (paths,0 ), sa) && +quic_cmp_sk_addr (tmp,quic_path_daddr (paths,0 ), da) && +quic_path_usock (paths,0 ) == usk && + (!dcid || !quic_conn_id_cmp (odcid, dcid))) { + sk = tmp; +break ; + } + }
[High]
Is the sk memory itself RCU-protected here? sk_nulls_for_each_rcu() dereferences fields of tmp (sock_net(tmp), quic_paths(tmp), quic_path_saddr(...), etc.) before any reference is taken. That is only safe when the sk allocation is freed via RCU.
quic_init_sock() does not call sock_set_flag(sk, SOCK_RCU_FREE), and neither quic_prot nor quicv6_prot sets slab_flags to SLAB_TYPESAFE_BY_RCU, so sk_destruct() (and quic_sock_destruct()) runs synchronously on the last sock_put(). Can a parallel close on tmp free the sock between sk_nulls_for_each_rcu() exposing it and the field dereferences above?
The same shape appears in quic_listen_sock_lookup() further down, where quic_alpn(tmp)->len is read inside the RCU walk before refcount_inc_not_zero().
Quoted 5 lines
net/quic/socket.c +5
-0+if (sk &&unlikely (!refcount_inc_not_zero (&sk->sk_refcnt))) + sk =NULL ; +rcu_read_unlock (); +return sk; +}
[ ... ]
Quoted 4 lines
net/quic/socket.c +4
-0+struct sock *quic_listen_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da, +struct quic_data *alpns) +{
[ ... ]
Quoted 3 lines
net/quic/socket.c +3
-0+rcu_read_lock (); +if (!alpns->len) {/* No ALPNs or parse failed */ +sk_nulls_for_each_rcu (tmp, node, &head->head) {
[ ... ]
Quoted 5 lines
net/quic/socket.c +5
-0+ a =quic_path_saddr (quic_paths (tmp),0 ); +if (net ==sock_net (tmp) && +quic_cmp_sk_addr (tmp, a, sa) && +quic_path_usock (quic_paths (tmp),0 ) == skb->sk && + (!alpns->data || !quic_alpn (tmp)->len)) {
[ ... ]
net/quic/socket.c static void quic_sock_destruct(struct sock *sk) · line 201
Quoted 7 lines
net/quic/socket.c +3
-0@@ -48,6 +196,9 @@ static void quic_sock_destruct(struct sock *sk)for (i =0 ; i <QUIC_CRYPTO_MAX ; i++)quic_crypto_free (quic_crypto (sk, i)); +/* Deferred ALPN free for RCU readers in quic_listen_sock_lookup(). */ +quic_data_free (quic_alpn (sk)); +
Without SOCK_RCU_FREE or SLAB_TYPESAFE_BY_RCU on quic_prot/quicv6_prot, does moving the alpn free into the destruct callback actually defer it past an RCU grace period? quic_sock_destruct() is invoked from sk_destruct() on the final sock_put() and is not itself an RCU callback, so the comment's "Deferred ALPN free for RCU readers" assumption seems to rely on a guarantee that is not configured on this protocol. Should this patch also set sock_set_flag(sk, SOCK_RCU_FREE) in quic_init_sock(), or alternatively take refcount_inc_not_zero() in the lookup helpers before touching any fields of tmp?
Quoted 3 lines
net/quic/socket.c +0
-0quic_sk_destruct (sk); }
[ ... ]
Signature · 1 line
This is an AI-generated review.
Re: [PATCH net-next v13 15/15] quic: add packet parser base
Quoted 36 lines · Paolo Abeni
From: AI Reviewer <[email protected]>
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible. Full review at: https://netdev-ai.bots.linux.dev/sashiko/
---
quic: add packet parser baseThis patch adds the QUIC packet RX parser, including ALPN extraction from the Client Initial to demux to the right listener, an ICMP-driven PMTU update path, and a per-net backlog/work for deferred parsing.
Quoted 4 lines
net/quic/packet.c +0
-0[ ... ]
Quoted 5 lines
net/quic/packet.c +5
-0+static int quic_packet_get_alpn (struct quic_data *alpn,u8 *p,u32 len) +{ +int err = -EINVAL , found =0 , exts =0 ; +u64 length, type; +[ ... ]
net/quic/packet.c line 307
Quoted 7 lines
net/quic/packet.c +7
-0+while (len >=4 ) {/* Scan extensions for ALPN (TLS_EXT_alpn). */ +if (!quic_get_int (&p, &len, &type,2 )) +break ; +if (!quic_get_int (&p, &len, &length,2 )) +break ; +if (len < (u32 )length)/* Incomplete TLS extensions. */ +return 0 ;
Quoted 3 lines
[Medium]
Should this branch be treated as a parse failure rather than a success?
The rest of the TLS extensions could be in the CRYPTO frame of the next initial packet.
Returning error will cause packets to be dropped in the callers.
Quoted 3 lines
The other length-bound checks in this same function return err (
-EINVAL) when a declared length exceeds the remaining buffer, but this one returns 0 without populating alpn.
The splitted TLS CLIENT_HELLO messages are very rare.
The ones I saw from some QUIC implementations are splitted from these TLS EXT points. I will improve it when seeing more different split points.
Quoted 17 lines
The callers initialise alpn as
struct quic_data alpns = {};and
quic_listen_sock_lookup()then takes the no-ALPN branch:if (!alpns->len) { /* No ALPNs or parse failed */ sk_nulls_for_each_rcu(tmp, node, &head->head) { ... if (... && (!alpns->data || !quic_alpn(tmp)->len)) {Because
alpns->datais still NULL, the match collapses to true and any listener bound to the address/port will match, including ones that registered a specific ALPN list. Can a peer reach an ALPN-restricted listener by sending a Client Initial with one extension whose declared length is larger than what is left in the ClientHello?
Quoted 5 lines
Would returning err here (or always assigning
alpn->databefore returning) match the comment inquic_listen_sock_lookup()that distinguishes "TLS parsing succeeded but no ALPN was found" from "parse failed"?
ALPN demux is a feature trying its best to dispatch the first initial to the right process. If it goes to the "incorrect" because the peer doesn't provide proper ALPNs, the userspace handshake will reject it.
It's kind of the peer responsibility if it wants to get processed in the right process, send with the right ALPNs then.
Quoted 19 lines
net/quic/packet.c line 319
Quoted 12 lines
net/quic/packet.c +12
-0+if (type == TLS_EXT_alpn) {/* Found ALPN extension. */ +if (length >QUIC_ALPN_MAX_LEN ) +return err; + len = length; + found =1 ; +break ; + } +/* Skip non-ALPN extensions. */ + p += length; + len -= length; +if (exts++ >=TLS_MAX_EXTENSIONS ) +return err;[Low]
Is the post-increment intended here? WithTLS_MAX_EXTENSIONS== 128, the check (exts++ >= 128) first becomes true when exts has already reached 129, so 129 extensions are consumed before bail-out even though the constant name suggests a cap of 128. Would
Quoted 5 lines
if (++exts >
TLS_MAX_EXTENSIONS)
return err;(or moving the check to the loop top) better reflect the intended limit?
will change to ++exts.
Quoted 50 lines
Quoted 1 line
+ }
[ ... ]
Quoted 1 line
+static int
quic_packet_parse_alpn(struct sk_buff *skb, struct quic_data *alpn)[ ... ]
Quoted 4 lines
net/quic/socket.c +0
-0[ ... ]
Quoted 4 lines
net/quic/socket.c +4
-0+struct sock *quic_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da,struct sock *usk, +struct quic_conn_id *dcid) +{[ ... ]
Quoted 5 lines
net/quic/socket.c +5
-0+rcu_read_lock (); +begin: +sk_nulls_for_each_rcu (tmp, node, &head->head) { +if (net !=sock_net (tmp)) +continue ;net/quic/socket.c static void quic_enter_memory_pressure(struct sock *sk) · line 71
Quoted 10 lines
net/quic/socket.c +10
-0+ paths =quic_paths (tmp); + odcid =quic_path_orig_dcid (paths); +if (quic_cmp_sk_addr (tmp,quic_path_saddr (paths,0 ), sa) && +quic_cmp_sk_addr (tmp,quic_path_daddr (paths,0 ), da) && +quic_path_usock (paths,0 ) == usk && + (!dcid || !quic_conn_id_cmp (odcid, dcid))) { + sk = tmp; +break ; + } + }[High]
Is the sk memory itself RCU-protected here?sk_nulls_for_each_rcu()dereferences fields of tmp (sock_net(tmp),quic_paths(tmp),quic_path_saddr(...), etc.) before any reference is taken. That is only safe when the sk allocation is freed via RCU.
quic_init_sock()does not callsock_set_flag(sk, SOCK_RCU_FREE), and neitherquic_protnorquicv6_protsetsslab_flagstoSLAB_TYPESAFE_BY_RCU, sosk_destruct()(andquic_sock_destruct()) runs synchronously on the lastsock_put(). Can a parallel close on tmp free the sock betweensk_nulls_for_each_rcu()exposing it and the field dereferences above?
Quoted 4 lines
The same shape appears in
quic_listen_sock_lookup()further down, where quic_alpn(tmp)->len is read inside the RCU walk beforerefcount_inc_not_zero().
SOCK_RCU_FREE will be set in the patchset-2 via quic_hash().
Quoted 33 lines
Quoted 5 lines
net/quic/socket.c +5
-0+if (sk &&unlikely (!refcount_inc_not_zero (&sk->sk_refcnt))) + sk =NULL ; +rcu_read_unlock (); +return sk; +}[ ... ]
Quoted 4 lines
net/quic/socket.c +4
-0+struct sock *quic_listen_sock_lookup (struct sk_buff *skb,union quic_addr *sa, +union quic_addr *da, +struct quic_data *alpns) +{[ ... ]
Quoted 3 lines
net/quic/socket.c +3
-0+rcu_read_lock (); +if (!alpns->len) {/* No ALPNs or parse failed */ +sk_nulls_for_each_rcu (tmp, node, &head->head) {[ ... ]
Quoted 5 lines
net/quic/socket.c +5
-0+ a =quic_path_saddr (quic_paths (tmp),0 ); +if (net ==sock_net (tmp) && +quic_cmp_sk_addr (tmp, a, sa) && +quic_path_usock (quic_paths (tmp),0 ) == skb->sk && + (!alpns->data || !quic_alpn (tmp)->len)) {[ ... ]
Quoted 4 lines
net/quic/socket.c +0
-0@@ -48,6 +196,9 @@ static void quic_sock_destruct(struct sock *sk)for (i =0 ; i <QUIC_CRYPTO_MAX ; i++)quic_crypto_free (quic_crypto (sk, i));
Quoted 14 lines
net/quic/socket.c static void quic_sock_destruct(struct sock *sk) · line 201
Quoted 3 lines
net/quic/socket.c +3
-0+/* Deferred ALPN free for RCU readers in quic_listen_sock_lookup(). */ +quic_data_free (quic_alpn (sk)); +Without
SOCK_RCU_FREEorSLAB_TYPESAFE_BY_RCUon quic_prot/quicv6_prot, does moving the alpn free into the destruct callback actually defer it past an RCU grace period?quic_sock_destruct()is invoked fromsk_destruct()on the finalsock_put()and is not itself an RCU callback, so the comment's "Deferred ALPN free for RCU readers" assumption seems to rely on a guarantee that is not configured on this protocol. Should this patch also setsock_set_flag(sk, SOCK_RCU_FREE)inquic_init_sock(), or alternatively takerefcount_inc_not_zero()in the lookup helpers before touching any fields of tmp?
SOCK_RCU_FREE will be set in the patchset-2 via quic_hash().
Quoted 8 lines
net/quic/socket.c static void quic_sock_destruct(struct sock *sk) · line 204
Quoted 3 lines
net/quic/socket.c +0
-0quic_sk_destruct (sk); }[ ... ]
--
This is an AI-generated review.
Quoted 423 lines · Xin Long
Introduction
============The QUIC protocol, defined in RFC 9000, is a secure, multiplexed transport built on top of UDP. It enables low-latency connection establishment, stream-based communication with flow control, and supports connection migration across network paths, while ensuring confidentiality, integrity, and availability.
This implementation introduces QUIC support in Linux Kernel, offering several key advantages:
- In-Kernel QUIC Support for Subsystems: Enables kernel subsystems such as SMB and NFS to operate over QUIC with minimal changes. Once the handshake is complete via the net/handshake APIs, data exchange proceeds over standard in-kernel transport interfaces.
- Standard Socket API Semantics: Implements core socket operations (
listen(),accept(),connect(),sendmsg(),recvmsg(),close(),getsockopt(),setsockopt(),getsockname(), andgetpeername()), allowing user space to interact with QUIC sockets in a familiar, POSIX-compliant way.- ALPN-Based Connection Dispatching: Supports in-kernel ALPN (Application-Layer Protocol Negotiation) routing, allowing demultiplexing of QUIC connections across different user-space processes based on the ALPN identifiers.
- Performance Enhancements: Handles all control messages in-kernel to reduce syscall overhead, incorporates zero-copy mechanisms such as
sendfile()to minimize data movement, and is also structured to support future crypto hardware offloads.This implementation offers fundamental support for the following RFCs:
- RFC9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC9001 - Using TLS to Secure QUIC
- RFC9002 - QUIC Loss Detection and Congestion Control
- RFC9221 - An Unreliable Datagram Extension to QUIC
- RFC9287 - Greasing the QUIC Bit
- RFC9368 - Compatible Version Negotiation for QUIC
- RFC9369 - QUIC Version 2The socket APIs for QUIC follow the RFC draft [1]:
- The Sockets API Extensions for In-kernel QUIC Implementations
Implementation
==============The central design is to implement QUIC within the kernel while delegating the handshake to userspace.
Only the processing and creation of raw TLS Handshake Messages are handled in userspace, facilitated by a TLS library like GnuTLS. These messages are exchanged between kernel and userspace via
sendmsg()andrecvmsg(), with cryptographic details conveyed through control messages (cmsg).The entire QUIC protocol, aside from the TLS Handshake Messages processing and creation, is managed in the kernel. Rather than using an Upper Layer Protocol (ULP) layer, this implementation establishes a socket of type
IPPROTO_QUIC(similar toIPPROTO_MPTCP), operating over UDP tunnels.For kernel consumers, they can initiate a handshake request from the kernel to userspace using the existing net/handshake netlink. The userspace component, such as tlshd service [2], then manages the processing of the QUIC handshake request.
- Handshake Architecture:
┌──────┐ ┌──────┐ │ APP1 │ │ APP2 │ ... └──────┘ └──────┘ ┌──────────────────────────────────────────┐ │ {quic_client/server_handshake()} │<─────────────┐ └──────────────────────────────────────────┘ ┌─────────────┐ {send/recvmsg()} {set/getsockopt()} │ tlshd │ [CMSG handshake_info] [SOCKOPT_CRYPTO_SECRET] └─────────────┘ [SOCKOPT_TRANSPORT_PARAM_EXT] │ ^ │ ^ │ ^ │ │ Userspace │ │ │ │ │ │ ──────────────│─│──────────────────│─│──────────────────│───│─────── Kernel │ │ │ │ │ │ v │ v │ v │ ┌──────────────────┬───────────────────────┐ ┌─────────────┐ │ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐ │ handshake │ │ ├───────────────────────┤ │ │netlink APIs │ │ common, family, │ outqueue | inqueue │ │ └─────────────┘ │ ├───────────────────────┤ │ │ │ │ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐ │ ├───────────────────────┤ │ │ │ │ │ │ path, pnspace, │ packet │ │───│ SMB │ │ NFS │... │ ├───────────────────────┤ │ │ │ │ │ │ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘ └──────────────────┴───────────────────────┘ └──────┴───────┘- User Data Architecture:
┌──────┐ ┌──────┐ │ APP1 │ │ APP2 │ ... └──────┘ └──────┘ {send/recvmsg()} {set/getsockopt()} {recvmsg()} [CMSG stream_info] [SOCKOPT_KEY_UPDATE] [EVENT conn update] [SOCKOPT_CONNECTION_MIGRATION] [EVENT stream update] [SOCKOPT_STREAM_OPEN/RESET/STOP] │ ^ │ ^ ^ Userspace │ │ │ │ │ ──────────────│─│───────────────│─│─────────────────────│─────────── Kernel │ │ │ │ │ v │ v │ ┌──────────────────┘ ┌──────────────────┬───────────────────────┐ │ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐{kernel_send/recvmsg()} │ ├───────────────────────┤ │{kernel_set/getsockopt()} │ common, family, │ outqueue | inqueue │ │{kernel_recvmsg()} │ ├───────────────────────┤ │ │ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐ │ ├───────────────────────┤ │ │ │ │ │ │ path, pnspace, │ packet │ │───│ SMB │ │ NFS │... │ ├───────────────────────┤ │ │ │ │ │ │ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘ └──────────────────┴───────────────────────┘ └──────┴───────┘Interface
=========This implementation supports a mapping of QUIC into sockets APIs. Similar to TCP and SCTP, a typical Server and Client use the following system call sequence to communicate:
Client Server
────────────────────────────────────────────────────────────────────── sockfd = socket(IPPROTO_QUIC) listenfd = socket(IPPROTO_QUIC) bind(sockfd) bind(listenfd)listen(listenfd)
connect(sockfd)
quic_client_handshake(sockfd)
sockfd = accept(listenfd)quic_server_handshake(sockfd, cert)sendmsg(sockfd) recvmsg(sockfd)
close(sockfd) close(sockfd)
close(listenfd)Please note that
quic_client_handshake()andquic_server_handshake()functions are currently sourced from libquic [3]. These functions are responsible for receiving and processing the raw TLS handshake messages until the completion of the handshake process.For utilization by kernel consumers, it is essential to have tlshd service [2] installed and running in userspace. This service receives and manages kernel handshake requests for kernel sockets. In the kernel, the APIs closely resemble those used in userspace:
Client Server
──────────────────────────────────────────────────────────────────────── __sock_create(IPPROTO_QUIC, &sock) __sock_create(IPPROTO_QUIC, &sock) kernel_bind(sock) kernel_bind(sock) kernel_listen(sock) kernel_connect(sock) tls_client_hello_x509(args:{sock}) kernel_accept(sock, &newsock) tls_server_hello_x509(args:{newsock})
kernel_sendmsg(sock)kernel_recvmsg(newsock)
sock_release(sock)sock_release(newsock)
sock_release(sock)Please be aware that
tls_client_hello_x509()andtls_server_hello_x509()are APIs fromnet/handshake/. They are used to dispatch the handshake request to the userspace tlshd service and subsequently block until the handshake process is completed.Use Cases
=========- Samba
Stefan Metzmacher has integrated Linux QUIC into Samba for both client and server roles [4].
- tlshd
The tlshd daemon [2] facilitates Linux QUIC handshake requests from kernel sockets. This is essential for enabling protocols like SMB and NFS over QUIC.
- curl
Linux QUIC is being integrated into curl [5] for HTTP/3. Example usage:
# curl --http3-only https://nghttp2.org:4433/ # curl --http3-only https://www.google.com/ # curl --http3-only https://facebook.com/ # curl --http3-only https://outlook.office.com/ # curl --http3-only https://cloudflare-quic.com/- httpd-portable
Moritz Buhl has deployed an HTTP/3 server over Linux QUIC [6] that is accessible via Firefox and curl:
- NetPerfMeter
The latest NetPerfMeter release supports Linux QUIC and can be used to run performance evaluations [10].
Test Coverage
=============The Coverage (gcov) of Functional and Interop Tests:
- Functional Tests
The libquic self-tests (make check) pass on all major architectures:
x86_64, i386, s390x, aarch64, ppc64le.- Interop tests
Interoperability was validated using the QUIC Interop Runner [7] against all major userland QUIC stacks. Results are available at:
- Fuzzing via Syzkaller
Syzkaller has been running kernel fuzzing with QUIC for weeks using tests/syzkaller/ in libquic [3].
- Performance Testing
Performance was benchmarked using iperf [8] over a 100G NIC using various MTUs and packet sizes:
- QUIC vs. kTLS:
UNIT size:1024 size:4096 size:16384 size:65536 Gbits/sec QUIC | kTLS QUIC | kTLS QUIC | kTLS QUIC | kTLS ──────────────────────────────────────────────────────────────────── mtu:1500 2.27 | 3.26 3.02 | 6.97 3.36 | 9.74 3.48 | 10.8 ──────────────────────────────────────────────────────────────────── mtu:9000 3.66 | 3.72 5.87 | 8.92 7.03 | 11.2 8.04 | 11.4-
QUIC(disable_1rtt_encryption)vs. TCP:UNIT size:1024 size:4096 size:16384 size:65536 Gbits/sec QUIC | TCP QUIC | TCP QUIC | TCP QUIC | TCP ──────────────────────────────────────────────────────────────────── mtu:1500 3.09 | 4.59 4.46 | 14.2 5.07 | 21.3 5.18 | 23.9 ──────────────────────────────────────────────────────────────────── mtu:9000 4.60 | 4.65 8.41 | 14.0 11.3 | 28.9 13.5 | 39.2The performance gap between QUIC and kTLS may be attributed to:
- The absence of Generic Segmentation Offload (GSO) for QUIC.
- An additional data copy on the transmission (TX) path.
- Extra encryption required for header protection in QUIC.
- A longer header length for the stream data in QUIC.Patches
=======Note: This implementation is organized into five parts and submitted across two patchsets for review. This patchset includes Parts 1–2, while Parts 3–5 will be submitted in a subsequent patchset. For complete series, see [9].
1. Infrastructure (2):
net: define
IPPROTO_QUICandSOL_QUICconstants
net: build socket infrastructure for QUIC protocol2. Subcomponents (13):
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: providequic.hheader files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add packet builder base
quic: add packet parser base3. Data Processing (8):
quic: add frame encoder and decoder base
quic: implement outqueue transmission and flow control
quic: implement outqueue sack and retransmission
quic: implement inqueue receiving and flow control
quic: implement frame creation functions
quic: implement frame processing functions
quic: implement packet creation functions
quic: implement packet processing functions4. Socket APIs (6):
quic: support bind/listen/connect/accept/close()
quic: supportsendmsg()andrecvmsg()
quic: support socket options related to interaction after handshake
quic: support socket options related to settings prior to handshake
quic: support socket options related to setup during handshake
quic: support socket ioctls and socket dump via procfs5. Documentation and Selftests (3):
Documentation: describe QUIC protocol interface in
quic.rst
quic: create sample test using handshake APIs for kernel consumers
selftests: net: add tests for QUIC protocolNotice: The QUIC module is currently labeled as "EXPERIMENTAL".
All contributors are recognized in the respective patches with the tag of 'Signed-off-by:'. Special thanks to Moritz Buhl and Stefan Metzmacher whose practical use cases and insightful feedback have been instrumental in shaping the design and advancing the development.
References
==========[1] https://datatracker.ietf.org/doc/html/draft-lxin-quic-socket-apis [2] https://github.com/oracle/ktls-utils [3] https://github.com/lxin/quic [4] https://gitlab.com/samba-team/samba/-/merge_requests/4019 [5] https://github.com/moritzbuhl/curl/tree/linux_curl [6] https://github.com/moritzbuhl/httpd-portable [7] https://github.com/quic-interop/quic-interop-runner [8] https://github.com/lxin/iperf [9] https://github.com/lxin/net-next/commits/quic/[10] https://www.nntb.no/~dreibh/netperfmeter/
Changes in v2-v13: See individual patch changelogs for details.
Xin Long (15):
net: defineIPPROTO_QUICandSOL_QUICconstants
net: build socket infrastructure for QUIC protocol
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: providequic.hheader files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add packet builder base
quic: add packet parser baseDocumentation/networking/ip-sysctl.rst | 39 + MAINTAINERS | 9 + include/linux/quic.h | 24 + include/linux/socket.h | 1 + include/uapi/linux/in.h | 2 + include/uapi/linux/quic.h | 241 +++++ net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 35 + net/quic/Makefile | 9 + net/quic/common.c | 559 +++++++++++ net/quic/common.h | 220 +++++ net/quic/cong.c | 333 +++++++ net/quic/cong.h | 130 +++ net/quic/connid.c | 256 +++++ net/quic/connid.h | 182 ++++ net/quic/crypto.c | 1245 ++++++++++++++++++++++++ net/quic/crypto.h | 89 ++ net/quic/family.c | 452 +++++++++ net/quic/family.h | 44 + net/quic/packet.c | 887 +++++++++++++++++ net/quic/packet.h | 120 +++ net/quic/path.c | 568 +++++++++++ net/quic/path.h | 190 ++++ net/quic/pnspace.c | 253 +++++ net/quic/pnspace.h | 201 ++++ net/quic/protocol.c | 418 ++++++++ net/quic/protocol.h | 63 ++ net/quic/socket.c | 477 +++++++++ net/quic/socket.h | 209 ++++ net/quic/stream.c | 416 ++++++++ net/quic/stream.h | 131 +++ net/quic/timer.c | 154 +++ net/quic/timer.h | 45 + usr/include/Makefile | 1 + 35 files changed, 8005 insertions(+) create mode 100644 include/linux/quic.h create mode 100644 include/uapi/linux/quic.h create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/common.c create mode 100644 net/quic/common.h create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.h create mode 100644 net/quic/connid.c create mode 100644 net/quic/connid.h create mode 100644 net/quic/crypto.c create mode 100644 net/quic/crypto.h create mode 100644 net/quic/family.c create mode 100644 net/quic/family.h create mode 100644 net/quic/packet.c create mode 100644 net/quic/packet.h create mode 100644 net/quic/path.c create mode 100644 net/quic/path.h create mode 100644 net/quic/pnspace.c create mode 100644 net/quic/pnspace.h create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.h create mode 100644 net/quic/stream.c create mode 100644 net/quic/stream.h create mode 100644 net/quic/timer.c create mode 100644 net/quic/timer.h
Quoted 3 lines
--
2.47.1
Sorry for the late check for the sashiko reports.
[sashiko-gemini] reported 1 important legit issue. [sashiko-claude] reported 1 important and 4 minor legit issues. (See the comments on the related patches)
will fix them in the next post.