xref: /linux/Documentation/networking/tls-offload.rst (revision 20bed0d6ff62d985fe8222958825504b8aad4e88)
1.. SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2
3==================
4Kernel TLS offload
5==================
6
7Kernel TLS operation
8====================
9
10Linux kernel provides TLS connection offload infrastructure. Once a TCP
11connection is in ``ESTABLISHED`` state user space can enable the TLS Upper
12Layer Protocol (ULP) and install the cryptographic connection state.
13For details regarding the user-facing interface refer to the TLS
14documentation in :ref:`Documentation/networking/tls.rst <kernel_tls>`.
15
16``ktls`` can operate in two modes:
17
18 * Software crypto mode (``TLS_SW``) - CPU handles the cryptography.
19   In most basic cases only crypto operations synchronous with the CPU
20   can be used, but depending on calling context CPU may utilize
21   asynchronous crypto accelerators. The use of accelerators introduces extra
22   latency on socket reads (decryption only starts when a read syscall
23   is made) and additional I/O load on the system.
24 * Packet-based NIC offload mode (``TLS_HW``) - the NIC handles crypto
25   on a packet by packet basis, provided the packets arrive in order.
26   This mode integrates best with the kernel stack and is described in detail
27   in the remaining part of this document
28   (``ethtool`` flags ``tls-hw-tx-offload`` and ``tls-hw-rx-offload``).
29
30The operation mode is selected automatically based on device configuration,
31offload opt-in or opt-out on per-connection basis is not currently supported.
32
33TX
34--
35
36At a high level user write requests are turned into a scatter list, the TLS ULP
37intercepts them, inserts record framing, performs encryption (in ``TLS_SW``
38mode) and then hands the modified scatter list to the TCP layer. From this
39point on the TCP stack proceeds as normal.
40
41In ``TLS_HW`` mode the encryption is not performed in the TLS ULP.
42Instead packets reach a device driver, the driver will mark the packets
43for crypto offload based on the socket the packet is attached to,
44and send them to the device for encryption and transmission.
45
46RX
47--
48
49On the receive side, if the device handled decryption and authentication
50successfully, the driver will set the decrypted bit in the associated
51:c:type:`struct sk_buff <sk_buff>`. The packets reach the TCP stack and
52are handled normally. ``ktls`` is informed when data is queued to the socket
53and the ``strparser`` mechanism is used to delineate the records. Upon read
54request, records are retrieved from the socket and passed to decryption routine.
55If device decrypted all the segments of the record the decryption is skipped,
56otherwise software path handles decryption.
57
58.. kernel-figure::  tls-offload-layers.svg
59   :alt:	TLS offload layers
60   :align:	center
61   :figwidth:	28em
62
63   Layers of Kernel TLS stack
64
65Device configuration
66====================
67
68During driver initialization device sets the ``NETIF_F_HW_TLS_RX`` and
69``NETIF_F_HW_TLS_TX`` features and installs its
70:c:type:`struct tlsdev_ops <tlsdev_ops>`
71pointer in the :c:member:`tlsdev_ops` member of the
72:c:type:`struct net_device <net_device>`.
73
74TLS cryptographic connection state is installed separately for RX and TX
75on a ``ktls`` socket. For each direction, the kernel checks if the underlying
76network device is offload-capable and attempts the offload. If offload fails,
77that direction is handled in software as if offload had never been tried.
78
79Both hardware directions share one device binding. Once one direction is
80offloaded, the other direction must use the same device. If a route change
81selects a different device, or ``NETDEV_DOWN`` has cleared the binding,
82hardware offload of the other direction is declined and it uses software
83instead.
84
85Offload request is performed via the :c:member:`tls_dev_add` callback of
86:c:type:`struct tlsdev_ops <tlsdev_ops>`:
87
88.. code-block:: c
89
90	int (*tls_dev_add)(struct net_device *netdev, struct sock *sk,
91			   enum tls_offload_ctx_dir direction,
92			   struct tls_crypto_info *crypto_info,
93			   u32 start_offload_tcp_sn);
94
95``direction`` indicates whether the cryptographic information is for
96the received or transmitted packets. Driver uses the ``sk`` parameter
97to retrieve the connection 5-tuple and socket family (IPv4 vs IPv6).
98Cryptographic information in ``crypto_info`` includes the key, iv, salt
99as well as TLS record sequence number. ``start_offload_tcp_sn`` indicates
100which TCP sequence number corresponds to the beginning of the record with
101sequence number from ``crypto_info``. The driver can add its state
102at the end of kernel structures (see :c:member:`driver_state` members
103in ``include/net/tls.h``) to avoid additional allocations and pointer
104dereferences.
105
106When the offloaded connection is destroyed the core calls
107the :c:member:`tls_dev_del` callback so the driver can release per-direction
108state:
109
110.. code-block:: c
111
112	void (*tls_dev_del)(struct net_device *netdev,
113			    struct tls_context *ctx,
114			    enum tls_offload_ctx_dir direction);
115
116``tls_dev_del`` is mandatory whenever ``tls_dev_add`` is provided.
117
118The third TLS device callback is :c:member:`tls_dev_resync`, called by the core
119to synchronize the TCP stream with the record boundaries:
120
121.. code-block:: c
122
123	int (*tls_dev_resync)(struct net_device *netdev,
124			      struct sock *sk, u32 seq, u8 *rcd_sn,
125			      enum tls_offload_ctx_dir direction);
126
127See the `Resync handling`_ section for details.
128
129TX
130--
131
132After TX state is installed, the stack guarantees that the first segment
133of the stream will start exactly at the ``start_offload_tcp_sn`` sequence
134number, simplifying TCP sequence number matching.
135
136TX offload being fully initialized does not imply that all segments passing
137through the driver and which belong to the offloaded socket will be after
138the expected sequence number and will have kernel record information.
139In particular, already encrypted data may have been queued to the socket
140before installing the connection state in the kernel.
141
142RX
143--
144
145In the RX direction, the local networking stack has little control over
146segmentation, so the initial records' TCP sequence number may be anywhere
147inside the segment.
148
149Normal operation
150================
151
152At the minimum the device maintains the following state for each connection, in
153each direction:
154
155 * crypto secrets (key, iv, salt)
156 * crypto processing state (partial blocks, partial authentication tag, etc.)
157 * record metadata (sequence number, processing offset and length)
158 * expected TCP sequence number
159
160There are no guarantees on record length or record segmentation. In particular
161segments may start at any point of a record and contain any number of records.
162Assuming segments are received in order, the device should be able to perform
163crypto operations and authentication regardless of segmentation. For this
164to be possible, the device has to keep a small amount of segment-to-segment
165state. This includes at least:
166
167 * partial headers (if a segment carried only a part of the TLS header)
168 * partial data block
169 * partial authentication tag (all data had been seen but part of the
170   authentication tag has to be written or read from the subsequent segment)
171
172Record reassembly is not necessary for TLS offload. If the packets arrive
173in order the device should be able to handle them separately and make
174forward progress.
175
176TX
177--
178
179The kernel stack performs record framing reserving space for the authentication
180tag and populating all other TLS header and tailer fields.
181
182Both the device and the driver maintain expected TCP sequence numbers
183due to the possibility of retransmissions and the lack of software fallback
184once the packet reaches the device.
185For segments passed in order, the driver marks the packets with
186a connection identifier (note that a 5-tuple lookup is insufficient to identify
187packets requiring HW offload, see the :ref:`5tuple_problems` section)
188and hands them to the device. The device identifies the packet as requiring
189TLS handling and confirms the sequence number matches its expectation.
190The device performs encryption and authentication of the record data.
191It replaces the authentication tag and TCP checksum with correct values.
192
193RX
194--
195
196Before a packet is DMAed to the host (but after NIC's embedded switching
197and packet transformation functions) the device validates the Layer 4
198checksum and performs a 5-tuple lookup to find any TLS connection the packet
199may belong to (technically a 4-tuple
200lookup is sufficient - IP addresses and TCP port numbers, as the protocol
201is always TCP). If the packet is matched to a connection, the device confirms
202if the TCP sequence number is the expected one and proceeds to TLS handling
203(record delineation, decryption, authentication for each record in the packet).
204The device leaves the record framing unmodified, the stack takes care of record
205decapsulation. Device indicates successful handling of TLS offload in the
206per-packet context (descriptor) passed to the host.
207
208Upon reception of a TLS offloaded packet, the driver sets
209the :c:member:`decrypted` mark in :c:type:`struct sk_buff <sk_buff>`
210corresponding to the segment. Networking stack makes sure decrypted
211and non-decrypted segments do not get coalesced (e.g. by GRO or socket layer)
212and takes care of partial decryption.
213
214Resync handling
215===============
216
217In presence of packet drops or network packet reordering, the device may lose
218synchronization with the TLS stream, and require a resync with the kernel's
219TCP stack.
220
221Note that resync is only attempted for connections which were successfully
222added to the device table and are in TLS_HW mode. For example,
223if the table was full when cryptographic state was installed in the kernel,
224such connection will never get offloaded. Therefore the resync request
225does not carry any cryptographic connection state.
226
227TX
228--
229
230Segments transmitted from an offloaded socket can get out of sync
231in similar ways to the receive side-retransmissions - local drops
232are possible, though network reorders are not. There are currently
233two mechanisms for dealing with out of order segments.
234
235Crypto state rebuilding
236~~~~~~~~~~~~~~~~~~~~~~~
237
238Whenever an out of order segment is transmitted the driver provides
239the device with enough information to perform cryptographic operations.
240This means most likely that the part of the record preceding the current
241segment has to be passed to the device as part of the packet context,
242together with its TCP sequence number and TLS record number. The device
243can then initialize its crypto state, process and discard the preceding
244data (to be able to insert the authentication tag) and move onto handling
245the actual packet.
246
247In this mode depending on the implementation the driver can either ask
248for a continuation with the crypto state and the new sequence number
249(next expected segment is the one after the out of order one), or continue
250with the previous stream state - assuming that the out of order segment
251was just a retransmission. The former is simpler, and does not require
252retransmission detection therefore it is the recommended method until
253such time it is proven inefficient.
254
255Next record sync
256~~~~~~~~~~~~~~~~
257
258Whenever an out of order segment is detected the driver requests
259that the ``ktls`` software fallback code encrypt it. If the segment's
260sequence number is lower than expected the driver assumes retransmission
261and doesn't change device state. If the segment is in the future, it
262may imply a local drop, the driver asks the stack to sync the device
263to the next record state and falls back to software.
264
265Resync request is indicated with:
266
267.. code-block:: c
268
269  void tls_offload_tx_resync_request(struct sock *sk, u32 got_seq, u32 exp_seq)
270
271Until resync is complete driver should not access its expected TCP
272sequence number (as it will be updated from a different context).
273Following helper should be used to test if resync is complete:
274
275.. code-block:: c
276
277  bool tls_offload_tx_resync_pending(struct sock *sk)
278
279Next time ``ktls`` pushes a record it will first send its TCP sequence number
280and TLS record number to the driver via the ``tls_dev_resync`` callback.
281The stack will also make sure that the new record will start on a segment
282boundary (like it does when the connection is initially added).
283
284RX
285--
286
287A small amount of RX reorder events may not require a full resynchronization.
288In particular the device should not lose synchronization
289when record boundary can be recovered:
290
291.. kernel-figure::  tls-offload-reorder-good.svg
292   :alt:	reorder of non-header segment
293   :align:	center
294
295   Reorder of non-header segment
296
297Green segments are successfully decrypted, blue ones are passed
298as received on wire, red stripes mark start of new records.
299
300In above case segment 1 is received and decrypted successfully.
301Segment 2 was dropped so 3 arrives out of order. The device knows
302the next record starts inside 3, based on record length in segment 1.
303Segment 3 is passed untouched, because due to lack of data from segment 2
304the remainder of the previous record inside segment 3 cannot be handled.
305The device can, however, collect the authentication algorithm's state
306and partial block from the new record in segment 3 and when 4 and 5
307arrive continue decryption. Finally when 2 arrives it's completely outside
308of expected window of the device so it's passed as is without special
309handling. ``ktls`` software fallback handles the decryption of record
310spanning segments 1, 2 and 3. The device did not get out of sync,
311even though two segments did not get decrypted.
312
313Kernel synchronization may be necessary if the lost segment contained
314a record header and arrived after the next record header has already passed:
315
316.. kernel-figure::  tls-offload-reorder-bad.svg
317   :alt:	reorder of header segment
318   :align:	center
319
320   Reorder of segment with a TLS header
321
322In this example segment 2 gets dropped, and it contains a record header.
323Device can only detect that segment 4 also contains a TLS header
324if it knows the length of the previous record from segment 2. In this case
325the device will lose synchronization with the stream.
326
327Stream scan resynchronization
328~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
329
330When the device gets out of sync and the stream reaches TCP sequence
331numbers more than a max size record past the expected TCP sequence number,
332the device starts scanning for a known header pattern. For example
333for TLS 1.2 and TLS 1.3 subsequent bytes of value ``0x03 0x03`` occur
334in the SSL/TLS version field of the header. Once pattern is matched
335the device continues attempting parsing headers at expected locations
336(based on the length fields at guessed locations).
337Whenever the expected location does not contain a valid header the scan
338is restarted.
339
340When the header is matched the device sends a confirmation request
341to the kernel, asking if the guessed location is correct (if a TLS record
342really starts there), and which record sequence number the given header had.
343
344The asynchronous resync process is coordinated on the kernel side using
345struct tls_offload_resync_async, which tracks and manages the resync request.
346
347Helper functions to manage struct tls_offload_resync_async:
348
349``tls_offload_rx_resync_async_request_start()``
350Initializes an asynchronous resync attempt by specifying the sequence range to
351monitor and resetting internal state in the struct.
352
353``tls_offload_rx_resync_async_request_end()``
354Retains the device's guessed TCP sequence number for comparison with current or
355future logged ones. It also clears the RESYNC_REQ_ASYNC flag from the resync
356request, indicating that the device has submitted its guessed sequence number.
357
358``tls_offload_rx_resync_async_request_cancel()``
359Cancels any in-progress resync attempt, clearing the request state.
360
361When the kernel processes an RX segment that begins a new TLS record, it
362examines the current status of the asynchronous resynchronization request.
363
364If the device is still waiting to provide its guessed TCP sequence number
365(the async state), the kernel records the sequence number of this segment so
366that it can later be compared once the device's guess becomes available.
367
368If the device has already submitted its guessed sequence number (the non-async
369state), the kernel now tries to match that guess against the sequence numbers of
370all TLS record headers that have been logged since the resync request
371started.
372
373The kernel confirms the guessed location was correct and tells the device
374the record sequence number via the ``tls_dev_resync`` callback. Meanwhile,
375the device had been parsing and counting all records since the just-confirmed
376one, it adds the number of records it had seen to the record number provided
377by the kernel.
378At this point the device is in sync and can resume decryption at next
379segment boundary.
380
381In a pathological case the device may latch onto a sequence of matching
382headers and never hear back from the kernel (there is no negative
383confirmation from the kernel). The implementation may choose to periodically
384restart scan. Given how unlikely falsely-matching stream is, however,
385periodic restart is not deemed necessary.
386
387Special care has to be taken if the confirmation request is passed
388asynchronously to the packet stream and record may get processed
389by the kernel before the confirmation request.
390
391Stack-driven resynchronization
392~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393
394The driver may also request the stack to perform resynchronization
395whenever it sees the records are no longer getting decrypted.
396If the connection is configured in this mode the stack automatically
397schedules resynchronization after it has received two completely encrypted
398records.
399
400The stack waits for the socket to drain and informs the device about
401the next expected record number and its TCP sequence number via the
402``tls_dev_resync`` callback. If the
403records continue to be received fully encrypted stack retries the
404synchronization with an exponential back off (first after 2 encrypted
405records, then after 4 records, after 8, after 16... up until every
406128 records).
407
408Rekey
409=====
410
411Offload does not currently support TLS 1.3, therefore key rotation
412is not a concern for offloaded connections at this point.
413
414Error handling
415==============
416
417TX
418--
419
420Packets may be redirected or rerouted by the stack to a different
421device than the selected TLS offload device. The stack will handle
422such condition using the :c:func:`sk_validate_xmit_skb` helper
423(TLS offload code installs :c:func:`tls_validate_xmit_skb` at this hook).
424Offload maintains information about all records until the data is
425fully acknowledged, so if skbs reach the wrong device they can be handled
426by software fallback.
427
428Any device TLS offload handling error on the transmission side must result
429in the packet being dropped. For example if a packet got out of order
430due to a bug in the stack or the device, reached the device and can't
431be encrypted such packet must be dropped.
432
433RX
434--
435
436If the device encounters any problems with TLS offload on the receive
437side it should pass the packet to the host's networking stack as it was
438received on the wire.
439
440For example authentication failure for any record in the segment should
441result in passing the unmodified packet to the software fallback. This means
442packets should not be modified "in place". Splitting segments to handle partial
443decryption is not advised. In other words either all records in the packet
444had been handled successfully and authenticated or the packet has to be passed
445to the host's stack as it was on the wire (recovering original packet in the
446driver if device provides precise error is sufficient).
447
448The Linux networking stack does not provide a way of reporting per-packet
449decryption and authentication errors, packets with errors must simply not
450have the :c:member:`decrypted` mark set.
451
452A packet should also not be handled by the TLS offload if it contains
453incorrect checksums.
454
455Performance metrics
456===================
457
458TLS offload can be characterized by the following basic metrics:
459
460 * max connection count
461 * connection installation rate
462 * connection installation latency
463 * total cryptographic performance
464
465Note that each TCP connection requires a TLS session in both directions,
466the performance may be reported treating each direction separately.
467
468Max connection count
469--------------------
470
471The number of connections device can support can be exposed via
472``devlink resource`` API.
473
474Total cryptographic performance
475-------------------------------
476
477Offload performance may depend on segment and record size.
478
479Overload of the cryptographic subsystem of the device should not have
480significant performance impact on non-offloaded streams.
481
482Statistics
483==========
484
485Following minimum set of TLS-related statistics should be reported
486by the driver:
487
488 * ``rx_tls_decrypted_packets`` - number of successfully decrypted RX packets
489   which were part of a TLS stream.
490 * ``rx_tls_decrypted_bytes`` - number of TLS payload bytes in RX packets
491   which were successfully decrypted.
492 * ``rx_tls_ctx`` - number of TLS RX HW offload contexts added to device for
493   decryption.
494 * ``rx_tls_del`` - number of TLS RX HW offload contexts deleted from device
495   (connection has finished).
496 * ``rx_tls_resync_req_pkt`` - number of received TLS packets with a resync
497    request.
498 * ``rx_tls_resync_req_start`` - number of times the TLS async resync request
499    was started.
500 * ``rx_tls_resync_req_end`` - number of times the TLS async resync request
501    properly ended with providing the HW tracked tcp-seq.
502 * ``rx_tls_resync_req_skip`` - number of times the TLS async resync request
503    procedure was started but not properly ended.
504 * ``rx_tls_resync_res_ok`` - number of times the TLS resync response call to
505    the driver was successfully handled.
506 * ``rx_tls_resync_res_skip`` - number of times the TLS resync response call to
507    the driver was terminated unsuccessfully.
508 * ``rx_tls_err`` - number of RX packets which were part of a TLS stream
509   but were not decrypted due to unexpected error in the state machine.
510 * ``tx_tls_encrypted_packets`` - number of TX packets passed to the device
511   for encryption of their TLS payload.
512 * ``tx_tls_encrypted_bytes`` - number of TLS payload bytes in TX packets
513   passed to the device for encryption.
514 * ``tx_tls_ctx`` - number of TLS TX HW offload contexts added to device for
515   encryption.
516 * ``tx_tls_ooo`` - number of TX packets which were part of a TLS stream
517   but did not arrive in the expected order.
518 * ``tx_tls_skip_no_sync_data`` - number of TX packets which were part of
519   a TLS stream and arrived out-of-order, but skipped the HW offload routine
520   and went to the regular transmit flow as they were retransmissions of the
521   connection handshake.
522 * ``tx_tls_drop_no_sync_data`` - number of TX packets which were part of
523   a TLS stream dropped, because they arrived out of order and associated
524   record could not be found.
525 * ``tx_tls_drop_bypass_req`` - number of TX packets which were part of a TLS
526   stream dropped, because they contain both data that has been encrypted by
527   software and data that expects hardware crypto offload.
528
529Notable corner cases, exceptions and additional requirements
530============================================================
531
532.. _5tuple_problems:
533
5345-tuple matching limitations
535----------------------------
536
537The device can only recognize received packets based on the 5-tuple
538of the socket. Current ``ktls`` implementation will not offload sockets
539routed through software interfaces such as those used for tunneling
540or virtual networking. However, many packet transformations performed
541by the networking stack (most notably any BPF logic) do not require
542any intermediate software device, therefore a 5-tuple match may
543consistently miss at the device level. In such cases the device
544should still be able to perform TX offload (encryption) and should
545fallback cleanly to software decryption (RX).
546
547Out of order
548------------
549
550Introducing extra processing in NICs should not cause packets to be
551transmitted or received out of order, for example pure ACK packets
552should not be reordered with respect to data segments.
553
554Ingress reorder
555---------------
556
557A device is permitted to perform packet reordering for consecutive
558TCP segments (i.e. placing packets in the correct order) but any form
559of additional buffering is disallowed.
560
561Coexistence with standard networking offload features
562-----------------------------------------------------
563
564Offloaded ``ktls`` sockets should support standard TCP stack features
565transparently. Enabling device TLS offload should not cause any difference
566in packets as seen on the wire.
567
568Transport layer transparency
569----------------------------
570
571For the purpose of simplifying TLS offload, the device should not modify any
572packet headers.
573
574The device should not depend on any packet headers beyond what is strictly
575necessary for TLS offload.
576
577Segment drops
578-------------
579
580Dropping packets is acceptable only in the event of catastrophic
581system errors and should never be used as an error handling mechanism
582in cases arising from normal operation. In other words, reliance
583on TCP retransmissions to handle corner cases is not acceptable.
584
585TLS device features
586-------------------
587
588Drivers should ignore the changes to the TLS device feature flags.
589These flags will be acted upon accordingly by the core ``ktls`` code.
590TLS device feature flags only control adding of new TLS connection
591offloads, old connections will remain active after flags are cleared.
592
593TLS encryption cannot be offloaded to devices without checksum calculation
594offload. Hence, TLS TX device feature flag requires TX csum offload being set.
595Disabling the latter implies clearing the former. Disabling TX checksum offload
596should not affect old connections, and drivers should make sure checksum
597calculation does not break for them.
598Similarly, device-offloaded TLS decryption implies doing RXCSUM. If the user
599does not want to enable RX csum offload, TLS RX device feature is disabled
600as well.
601