[CVE-2022-34918] A crack in the Linux firewall
A heap buffer overflow in the Linux kernel's netfilter subsystem allowed an attacker to corrupt kernel memory and escalate privileges to root on Ubuntu 22.04. The flaw arose because the size of a data copy was taken from one object while the destination buffer was sized using a different value.
Published on randorisec.fr
In our previous article Yet another bug into Netfilter, I presented a vulnerability found within the netfilter subsystem of the Linux kernel. During my investigation, I found a weird comparison that does not fully protect a copy within a buffer.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This write-up follows a vulnerability in the netfilter subsystem of the Linux kernel, found during research on the nft_set structure defined in /include/net/netfilter/nf_tables.h. The previous article in the series had already reached an out-of-bound within nft_set. Because that structure holds a lot of data, other fields could offer a better write primitive, so the research turned to the length fields udlen, klen and dlen, which looked useful for performing overflows.
struct nft_set {
struct list_head list;
struct list_head bindings;
struct nft_table *table;
possible_net_t net;
char *name;
u64 handle;
u32 ktype;
u32 dtype;
u32 objtype;
u32 size;
u8 field_len[NFT_REG32_COUNT];
u8 field_count;
u32 use;
atomic_t nelems;
u32 ndeact;
u64 timeout;
u32 gc_int;
u16 policy;
u16 udlen;
unsigned char *udata;
/* runtime data below here */
const struct nft_set_ops *ops ____cacheline_aligned;
u16 flags:14,
genmask:2;
u8 klen;
u8 dlen;
u8 num_exprs;
struct nft_expr *exprs[NFT_SET_EXPR_MAX];
struct list_head catchall_list;
unsigned char data[]
__attribute__((aligned(__alignof__(u64))));
};
The target is Ubuntu 22.04, and the outcome of the exploitation is root privileges on that system.
Setup
The research was carried out against the Linux kernel, reading the netfilter source. The exploit was developed against Ubuntu 22.04.
Finding it
Exploring the different accesses to the field dlen, a call to memcpy in nft_set_elem_init (/net/netfilter/nf_tables_api.c) stood out.
void *nft_set_elem_init(const struct nft_set *set,
const struct nft_set_ext_tmpl *tmpl,
const u32 *key, const u32 *key_end,
const u32 *data, u64 timeout, u64 expiration, gfp_t gfp)
{
struct nft_set_ext *ext;
void *elem;
elem = kzalloc(set->ops->elemsize + tmpl->len, gfp); <===== (0)
if (elem == NULL)
return NULL;
ext = nft_set_elem_ext(set, elem);
nft_set_ext_init(ext, tmpl);
if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY))
memcpy(nft_set_ext_key(ext), key, set->klen);
if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
memcpy(nft_set_ext_key_end(ext), key_end, set->klen);
if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
memcpy(nft_set_ext_data(ext), data, set->dlen); <===== (1)
...
return elem;
}
The call is suspicious because two different objects are involved. The destination buffer lives inside an nft_set_ext object, ext, while the size of the copy is taken from an nft_set object. The ext object is dynamically allocated at (0) together with elem, and the space reserved for it is tmpl->len. The question was whether the value stored in set->dlen is used to compute the value stored in tmpl->len.
The wrong place
nft_set_elem_init is called at (5) inside nft_add_set_elem (/net/netfilter/nf_tables_api.c), the function responsible for adding an element to a netfilter set.
static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
const struct nlattr *attr, u32 nlmsg_flags)
{
struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
struct nft_set_ext_tmpl tmpl;
struct nft_set_elem elem; <===== (2)
struct nft_data_desc desc;
...
if (nla[NFTA_SET_ELEM_DATA] != NULL) {
err = nft_setelem_parse_data(ctx, set, &desc, &elem.data.val, <===== (3)
nla[NFTA_SET_ELEM_DATA]);
if (err < 0)
goto err_parse_key_end;
...
nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, desc.len); <===== (4)
}
...
err = -ENOMEM;
elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, <===== (5)
elem.key_end.val.data, elem.data.val.data,
timeout, expiration, GFP_KERNEL);
if (elem.priv == NULL)
goto err_parse_data;
...
set->dlen is not used to reserve the space for the data associated with the id NFT_SET_EXT_DATA; the space is reserved with desc.len at (4). desc is initialised in nft_setelem_parse_data (/net/netfilter/nf_tables_api.c), called at (3).
static int nft_setelem_parse_data(struct nft_ctx *ctx, struct nft_set *set,
struct nft_data_desc *desc,
struct nft_data *data,
struct nlattr *attr)
{
int err;
err = nft_data_init(ctx, data, NFT_DATA_VALUE_MAXLEN, desc, attr); <===== (6)
if (err < 0)
return err;
if (desc->type != NFT_DATA_VERDICT && desc->len != set->dlen) { <===== (7)
nft_data_release(data, desc->type);
return -EINVAL;
}
return 0;
}
data and desc are filled in nft_data_init (/net/netfilter/nf_tables_api.c) according to data provided by the user at (6). The critical part is the check between desc->len and set->dlen at (7): it only runs when the data associated with the added element has a type different from NFT_DATA_VERDICT.
set->dlen is controlled by the user when a new set is created. The only restriction is that set->dlen should be lower than 64 bytes and the data type should be different from NFT_DATA_VERDICT. When desc->type is equal to NFT_DATA_VERDICT, desc->len is equal to 16 bytes.
Adding an element of type NFT_DATA_VERDICT to a set with data type NFT_DATA_VALUE usually leads to desc->len being different from set->dlen. That makes it possible to perform a heap buffer overflow in nft_set_elem_init at (1), and the overflow can be extended up to 48 bytes long.
Exploitation
Step 1: understanding the overflow data
This is not a standard buffer overflow where the user directly controls the overflowing data. Random data is copied out of the allocated buffer. Looking at the call to nft_set_elem_init at (5), the copied data comes from a local variable elem, which is an nft_set_elem object.
struct nft_set_elem elem; <===== (2)
...
elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, <===== (5)
elem.key_end.val.data, elem.data.val.data,
timeout, expiration, GFP_KERNEL);
nft_set_elem (/net/netfilter/nf_tables.h) stores information about new elements during their creation.
#define NFT_DATA_VALUE_MAXLEN 64
struct nft_verdict {
u32 code;
struct nft_chain *chain;
};
struct nft_data {
union {
u32 data[4];
struct nft_verdict verdict;
};
} __attribute__((aligned(__alignof__(u64))));
struct nft_set_elem {
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} key;
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} key_end;
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} data;
void *priv;
};
64 bytes are reserved to temporarily store data associated with the new element, but only 16 bytes at most are written into elem.data when the buffer overflow is triggered. Random bytes are therefore used in the overflow.
Step 2: turning random into controlled
At this point the buffer overflow exists but the data used for the corruption is uncontrolled, which makes building an exploit a real challenge. elem.data used in the overflow is not initialised at (2), and that can be used to control the overflow.
Looking at the caller, nft_add_set_elem is called in nf_tables_newsetelem (/net/netfilter/nf_tables_api.c) for each element the user wants to add to the set.
static int nf_tables_newsetelem(struct sk_buff *skb,
const struct nfnl_info *info,
const struct nlattr * const nla[])
{
...
nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
err = nft_add_set_elem(&ctx, set, attr, info->nlh->nlmsg_flags);
if (err < 0) {
NL_SET_BAD_ATTR(extack, attr);
return err;
}
}
}
nla_for_each_nested iterates over attributes sent by the user, so the user controls the number of iterations. Because nla_for_each_nested only uses macros and inline functions, a call to nft_add_set_elem can be directly followed by another call to nft_add_set_elem. That allows data of a previous element to be used in the overflow, since elem.data is not initialised, and it also ignores the randomisation of the stack layout. The way to control the overflow is therefore independent of the kernel compilation.
The following schema summarises the different stages of elem.data within the stack to produce a controlled overflow.

Random data is stored within the stack; adding a new element with NFT_DATA_VALUE data leads to user-controlled data within the stack; finally, adding a second element with NFT_DATA_VERDICT data triggers the buffer overflow and the data residue of the last element is copied during the overflow.
Step 3: choosing the cache
elem, allocated at (0), depends on the options selected by the user, and its size may vary. Several options can be used to increase it, such as NFT_SET_ELEM_KEY and NFT_SET_ELEM_KEY_END, which reserve two buffers with a length up to 64 bytes in elem. The overflow can therefore happen in several caches. On Ubuntu 22.04 elem is allocated with the flag GFP_KERNEL, so the concerned caches are kmalloc-{64,96,128,192}.
The remaining task is to align elem on the cache object size to perform the best overflow. The next schema represents the construction of elem to align it on 64 bytes.

The construction used to target the kmalloc-64 cache is:
- 20 bytes for the object header
- 28 bytes of padding via
NFT_SET_ELEM_KEY - 16 bytes to store the element data of type
NFT_DATA_VERDICT.
Step 4: leaking the KASLR base
With controlled overflowing data, the next step is to retrieve the KASLR base. The overflow only occurs in kmalloc-x caches, so the classical msg_msg objects cannot be used for the information leak, because they are allocated within the kmalloc-cg-x caches.
user_key_payload (/include/keys/user-type.h) objects, normally used to store sensitive user information in kernel land, are a good alternative. They are similar to msg_msg objects in structure: a header with the object size, then a buffer with user data.
struct user_key_payload {
struct rcu_head rcu; /* RCU destructor */
unsigned short datalen; /* length of this data */
char data[] __aligned(__alignof__(u64)); /* actual data */
};
These objects are allocated in user_preparse (/security/keys/user_defined.c).
int user_preparse(struct key_preparsed_payload *prep)
{
struct user_key_payload *upayload;
size_t datalen = prep->datalen;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); <===== (6)
if (!upayload)
return -ENOMEM;
/* attach the data */
prep->quotalen = datalen;
prep->payload.data[0] = upayload;
upayload->datalen = datalen;
memcpy(upayload->data, prep->data, datalen); <===== (7)
return 0;
}
The allocation at (6) takes into account the length of the data provided by the user, and the data is stored just after the header with the memcpy at (7). The header of user_key_payload objects is 24 bytes long, so they can spray several caches, from kmalloc-32 to kmalloc-8k.
As with msg_msg objects, the goal is to overwrite the datalen field with a bigger value than the initial one. When the stored information is retrieved, the corrupted object returns more data than initially provided by the user.
There is an important drawback with this spray: the number of allocated objects is restricted. The sysctl variable kernel.keys.maxkeys defines the limit on the number of allowed keys within a user keyring, and kernel.keys.maxbytes restricts the number of stored bytes within a keyring. The default values of these variables are very low. They are shown below for Ubuntu 22.04.
kernel.keys.maxbytes = 20000
kernel.keys.maxkeys = 200
Step 5: leaking something useful
Working within the kmalloc-64 cache seemed the best option, since it is the cache with the smallest objects where the overflow can occur, and consequently a higher number of objects can leak.
percpu_ref_data (/include/linux/percpu-refcount.h) objects are also allocated in this cache. They are interesting targets because they contain two useful kinds of pointers.
struct percpu_ref_data {
atomic_long_t count;
percpu_ref_func_t *release;
percpu_ref_func_t *confirm_switch;
bool force_atomic:1;
bool allow_reinit:1;
struct rcu_head rcu;
struct percpu_ref *ref;
};
These objects store pointers to functions (fields release and confirm_switch) that can be used to compute the KASLR base or module bases when they are leaked, and also a pointer to a dynamically allocated object (field ref) useful to compute the physmap base.
Such objects are allocated during a call to percpu_ref_init (/lib/percpu-refcount.c).
int percpu_ref_init(struct percpu_ref *ref, percpu_ref_func_t *release,
unsigned int flags, gfp_t gfp)
{
struct percpu_ref_data *data;
...
data = kzalloc(sizeof(*ref->data), gfp);
...
data->release = release;
data->confirm_switch = NULL;
data->ref = ref;
ref->data = data;
return 0;
}
The simplest way to allocate percpu_ref_data objects is to use the io_uring_setup syscall (/fs/io_uring.c), and a simple call to the close syscall is enough to program the release of such an object.
The allocation of a percpu_ref_data object is done during the initialisation of an io_ring_ctx object (/fs/io_uring.c) within io_ring_ctx_alloc (/fs/io_uring.c).
static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
{
struct io_ring_ctx *ctx;
...
if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
goto err;
...
}
As io_uring is integrated into the Linux core, leaking io_ring_ctx_ref_free (/fs/io_uring.c) allows the KASLR base to be computed.
During the investigation, some unexpected percpu_ref_data objects appeared in the leak with the address of the function io_rsrc_node_ref_zero (/fs/io_uring.c) in the release field. After analysing the origin of these objects, they were found to also come from the io_uring_setup syscall. This side effect of io_uring_setup improved the leak within the exploit.
Step 6: the write primitive
With a useful information leak available, a good write primitive is needed for privilege escalation. Lam Jun Rong from Starlabs released an article describing a new way to exploit CVE-2021-41073: the unlinking attack. It is based on the list_del operation. After corrupting a list_head object with two addresses, one address gets stored at the other.
As in that article, the target for the list_head corruption in this exploit is a simple_xattr object.
struct simple_xattr {
struct list_head list;
char *name;
size_t size;
char value[];
};
To work, this technique requires knowing which object has been corrupted. Otherwise, removing random items from the list leads surely to a fault in the list traversal. The items in the list are identified with their names.
To identify the corrupted object, a trick is performed on the name field: allocating name with a length high enough to have 256 bytes reserved makes the least significant byte of the returned address null. On little endian architectures such as x86_64, it is enough to erase the least significant byte of name after the two pointers in the list_head. It is therefore possible to prepare the list field for the write primitive and at the same time identify the corrupted object by truncating its name. The only requirement is that all the names have the same end.
The following schema summarises the construction of the name for a spray with simple_xattr objects.

Step 7: root shell
Using this write primitive, it is possible to edit the modprobe_path with a path in the /tmp/ folder. It allows any program to be executed with root privileges, and to enjoy a root shell.

Remarks
This exploitation method is based on the hypothesis that a specific address is mapped in kernel land, which is not always the case. The exploit is therefore not fully reliable, but it still has a good success rate. The second drawback of the unlinking attack is the kernel panic that comes when the exploit is finished. This could be avoided by finding objects that can stay in the kernel memory at the end of the exploit process.
Root cause
The mistake is a mismatch between the size used to reserve space and the size used to copy. In nft_add_set_elem, the space for NFT_SET_EXT_DATA is reserved with desc.len at (4), while nft_set_elem_init copies set->dlen bytes at (1). The consistency check between desc->len and set->dlen at (7) is skipped whenever the element data has type NFT_DATA_VERDICT, and in that case desc->len is 16 bytes. A set created with data type NFT_DATA_VALUE and a set->dlen lower than 64 bytes can therefore receive an element of type NFT_DATA_VERDICT, and the copy overflows the buffer reserved for the data by up to 48 bytes.
Impact
The heap buffer overflow can be exploited to escalate privileges to root on Ubuntu 22.04. The exploit is not fully reliable because it depends on a specific address being mapped in kernel land, and it ends with a kernel panic when the exploit is finished.
Fix
The vulnerability was reported to the Linux security team and CVE-2022-34918 was assigned. They proposed a patch that was tested and reviewed, and it was released in the upstream tree within commit [redacted].
Variants to test
- Create a set with a data type of
NFT_DATA_VALUEand aset->dlenbelow 64 bytes, then add an element of typeNFT_DATA_VERDICT. A positive result is a copy of 16 bytes into a buffer reserved withdesc.len, overflowing by up to 48 bytes. - Vary the options that grow
elem, such asNFT_SET_ELEM_KEYandNFT_SET_ELEM_KEY_END, to move the allocation across thekmalloc-{64,96,128,192}caches. A positive result is a controlled overflow in the chosen cache. - Send several elements in one
NFTA_SET_ELEM_LIST_ELEMENTSlist, first anNFT_DATA_VALUEelement and then anNFT_DATA_VERDICTelement. A positive result is that the residue of the first element's data is copied during the overflow. - Spray
user_key_payloadobjects and overwritedatalenwith a larger value. A positive result is that reading the key returns more data than was provided. - Spray
percpu_ref_dataobjects throughio_uring_setupand leak thereleasefield. A positive result is a kernel text pointer such asio_ring_ctx_ref_freeorio_rsrc_node_ref_zero, from which the KASLR base can be computed. - Corrupt a
simple_xattrlist_headand truncate the least significant byte ofnameto identify the corrupted object. A positive result is a workinglist_delwrite primitive that can editmodprobe_path.
What happened, in plain words
A security researcher found a bug in the Linux kernel, the core program that sits underneath everything on a Linux computer and controls memory, hardware and permissions. The bug lives in a part of the kernel called netfilter, which is the built-in firewall: the piece of software that decides which network traffic is allowed in and out. Netfilter is configured through a feature called nftables, where you create named collections (called sets) of addresses, ports or other values, and attach rules to them.
The bug is a heap buffer overflow. Imagine a row of small numbered boxes in a storage room, each box rented for exactly one item. A buffer overflow is what happens when a program is told to put a larger item into a box than the box was rented for: the extra part spills into the neighbouring boxes and overwrites whatever was stored there. The heap is the kernel's general-purpose storage area where such boxes are handed out. Because the spilled data lands in memory the program did not intend to touch, an attacker can sometimes use it to change how the kernel behaves.
In this case the researcher worked out how to control what spills over, how to read secret values back out of the kernel, and finally how to make the kernel run a program of his choosing with the highest privileges. The end result is a root shell: a command prompt with full administrator power over the machine. The target was Ubuntu 22.04, a common desktop and server version of Linux. The bug was reported and received the identifier CVE-2022-34918; the Linux security team proposed a patch. CVE stands for Common Vulnerabilities and Exposures: a public catalogue number given to each known security flaw so people can track it.
A small jump in the past
The researcher had already published an earlier article about a related bug in the same area. That earlier work reached an out-of-bound inside a kernel data structure called nft_set. Out-of-bound means reading or writing just outside the area a program is supposed to use. The nft_set structure is the kernel's internal description of one nftables set. A structure (or struct) is a bundle of named fields stored together in memory, like a form with several boxes on it.
struct nft_set {
struct list_head list;
struct list_head bindings;
struct nft_table *table;
possible_net_t net;
char *name;
u64 handle;
u32 ktype;
u32 dtype;
u32 objtype;
u32 size;
u8 field_len[NFT_REG32_COUNT];
u8 field_count;
u32 use;
atomic_t nelems;
u32 ndeact;
u64 timeout;
u32 gc_int;
u16 policy;
u16 udlen;
unsigned char *udata;
/* runtime data below here */
const struct nft_set_ops *ops ____cacheline_aligned;
u16 flags:14,
genmask:2;
u8 klen;
u8 dlen;
u8 num_exprs;
struct nft_expr *exprs[NFT_SET_EXPR_MAX];
struct list_head catchall_list;
unsigned char data[]
__attribute__((aligned(__alignof__(u64))));
};
Line by line, in plain words:
struct nft_set {opens the description of the set. Everything between the braces is one field of the set.struct list_head list;andstruct list_head bindings;are links that let the kernel chain this set into lists with other sets. A list is like a chain of paper clips: each clip holds a pointer to the next.struct nft_table *table;points back to the table this set belongs to. The asterisk means pointer: a field that stores the memory address of something else rather than the thing itself.possible_net_t net;records which network namespace the set belongs to. A namespace is an isolated view of the system, so two containers can each have their own network without seeing each other's.char *name;is the set's name, stored elsewhere in memory and pointed to here.u64 handle;is a numeric identifier.u64means an unsigned 64-bit integer, a whole number that cannot be negative.u32 ktype;,u32 dtype;,u32 objtype;describe what kind of key, data and object the set holds.u32is a 32-bit unsigned number.u32 size;is the set's size.u8 field_len[NFT_REG32_COUNT];is a small array of byte values. An array is a numbered row of identical slots.u8 field_count;counts those fields.u32 use;tracks how many times the set is used.atomic_t nelems;counts the elements in the set in a way that is safe when several CPU cores touch it at once.u32 ndeact;counts deactivated elements.u64 timeout;andu32 gc_int;control when elements expire and how often the kernel cleans them up.u16 policy;stores a policy setting.u16 udlen;is the length of user data attached to the set.unsigned char *udata;points to that user data.- The comment
/* runtime data below here */marks fields that are only meaningful while the set is in use. const struct nft_set_ops *ops ____cacheline_aligned;points to a table of operations (functions) for this kind of set.____cacheline_alignedasks the compiler to place it on a fresh cache line, a small block of memory the CPU reads in one go for speed.u16 flags:14, genmask:2;packs two small values into one 16-bit field. The:14and:2say how many bits each one gets.u8 klen;is the key length,u8 dlen;the data length,u8 num_exprs;the number of expressions (extra rules) attached.struct nft_expr *exprs[NFT_SET_EXPR_MAX];is an array of pointers to those expressions.struct list_head catchall_list;is a list of catch-all entries.unsigned char data[] __attribute__((aligned(__alignof__(u64))));is a flexible array: a tail of bytes whose length is decided when the structure is created, aligned so 64-bit values can be read from it cleanly.
Because this structure holds so much data, other fields might offer a better way to write into memory than the earlier bug did. A write primitive is simply a reliable way to make the kernel write a value of your choosing to an address of your choosing. The researcher therefore looked at the length fields udlen, klen and dlen, because a length decides how many bytes get copied, and a wrong length is exactly what produces an overflow.
Research for Code and Anomalies
Searching for every place the kernel reads the dlen field, one call to memcpy inside the function nft_set_elem_init caught his attention. memcpy is a standard function that copies a given number of bytes from one memory location to another; its third argument is the count.
void *nft_set_elem_init(const struct nft_set *set,
const struct nft_set_ext_tmpl *tmpl,
const u32 *key, const u32 *key_end,
const u32 *data, u64 timeout, u64 expiration, gfp_t gfp)
{
struct nft_set_ext *ext;
void *elem;
elem = kzalloc(set->ops->elemsize + tmpl->len, gfp); <===== (0)
if (elem == NULL)
return NULL;
ext = nft_set_elem_ext(set, elem);
nft_set_ext_init(ext, tmpl);
if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY))
memcpy(nft_set_ext_key(ext), key, set->klen);
if (nft_set_ext_exists(ext, NFT_SET_EXT_KEY_END))
memcpy(nft_set_ext_key_end(ext), key_end, set->klen);
if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
memcpy(nft_set_ext_data(ext), data, set->dlen); <===== (1)
...
return elem;
}
Line by line:
- The function signature lists what it receives: the set, a template describing which optional parts the element has, the key, the end of the key, the data, timeout values, and an allocation flag.
gfp_t gfptells the memory allocator how it may behave, for example whether it is allowed to wait for free memory. struct nft_set_ext *ext;andvoid *elem;declare two pointers, one to the element's extension area and one to the element itself.elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);at(0)allocates one block of memory big enough for the element plus the extension, and zeroes it.kzallocis "allocate and clear to zero". The size comes fromtmpl->len, the template's length.if (elem == NULL) return NULL;handles the case where memory ran out.ext = nft_set_elem_ext(set, elem);finds where inside that block the extension begins.nft_set_ext_init(ext, tmpl);fills the extension's bookkeeping from the template.- The three
ifblocks copy the key, the end of the key and the data into the extension, but only if the template says that part exists. Each copy uses a length taken from the set:set->klenfor keys, andset->dlenfor data at(1). return elem;hands the new element back to the caller.
The suspicious part is that two different objects are involved. The destination buffer lives inside the ext object, but the number of bytes to copy is read from the set object. The ext object was allocated at (0) together with elem, and the space reserved for it is tmpl->len. The question was whether the value in set->dlen is used to compute tmpl->len. If it is not, the copy can be larger than the space reserved, and that is the overflow.
The wrong place
nft_set_elem_init is called at (5) inside nft_add_set_elem, the function that adds one element to a netfilter set.
static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
const struct nlattr *attr, u32 nlmsg_flags)
{
struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
struct nft_set_ext_tmpl tmpl;
struct nft_set_elem elem; <===== (2)
struct nft_data_desc desc;
...
if (nla[NFTA_SET_ELEM_DATA] != NULL) {
err = nft_setelem_parse_data(ctx, set, &desc, &elem.data.val, <===== (3)
nla[NFTA_SET_ELEM_DATA]);
if (err < 0)
goto err_parse_key_end;
...
nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, desc.len); <===== (4)
}
...
err = -ENOMEM;
elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, <===== (5)
elem.key_end.val.data, elem.data.val.data,
timeout, expiration, GFP_KERNEL);
if (elem.priv == NULL)
goto err_parse_data;
...
Line by line:
- The function receives a context, the set, the attribute describing the element, and message flags. An attribute here is one labelled piece of a message, like one field in a form.
struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];is an array of pointers, one slot per possible attribute, used to look them up by number.struct nft_set_ext_tmpl tmpl;is the template that will describe the layout of the new element.struct nft_set_elem elem;at(2)is a local variable holding the element while it is being built. Local means it lives on the stack, the small scratch area each running function gets.struct nft_data_desc desc;describes the data: its type and its length.if (nla[NFTA_SET_ELEM_DATA] != NULL) {runs the following block only if the user supplied a data attribute.nft_setelem_parse_data(ctx, set, &desc, &elem.data.val, nla[NFTA_SET_ELEM_DATA]);at(3)reads the user's data intoelem.data.valand fills indesc.if (err < 0) goto err_parse_key_end;jumps to cleanup if parsing failed.nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, desc.len);at(4)reserves room in the template for the data, usingdesc.lenas the size.elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, elem.key_end.val.data, elem.data.val.data, timeout, expiration, GFP_KERNEL);at(5)creates the real kernel element, passing the template and the local data.if (elem.priv == NULL) goto err_parse_data;cleans up if allocation failed.
So the space for the data part is reserved with desc.len at (4), not with set->dlen. desc is filled in by nft_setelem_parse_data, called at (3).
static int nft_setelem_parse_data(struct nft_ctx *ctx, struct nft_set *set,
struct nft_data_desc *desc,
struct nft_data *data,
struct nlattr *attr)
{
int err;
err = nft_data_init(ctx, data, NFT_DATA_VALUE_MAXLEN, desc, attr); <===== (6)
if (err < 0)
return err;
if (desc->type != NFT_DATA_VERDICT && desc->len != set->dlen) { <===== (7)
nft_data_release(data, desc->type);
return -EINVAL;
}
return 0;
}
Line by line:
- The function receives the context, the set, a place to write the description, a place to write the data, and the user's attribute.
err = nft_data_init(ctx, data, NFT_DATA_VALUE_MAXLEN, desc, attr);at(6)copies the user's data intodataand fillsdescwith its type and length.NFT_DATA_VALUE_MAXLENis the maximum allowed length, 64 bytes.if (err < 0) return err;stops if that failed.if (desc->type != NFT_DATA_VERDICT && desc->len != set->dlen) {at(7)is the consistency check. It only complains when the data is not a verdict and its length differs from the set's data length. The&&means both conditions must hold.nft_data_release(data, desc->type); return -EINVAL;frees the data and returns an invalid-argument error.return 0;means success.
data and desc are filled from what the user sent at (6). The critical part is the check at (7): it only runs when the element's data type is not NFT_DATA_VERDICT. A verdict is a special kind of data that tells netfilter what to do with a packet, such as accept or drop it; it is not a plain value.
set->dlen is chosen by the user when creating a set. The only restrictions are that it must be below 64 bytes and that the set's data type must not be NFT_DATA_VERDICT. When the element's data type is NFT_DATA_VERDICT, its length is 16 bytes.
Adding an element of type NFT_DATA_VERDICT to a set whose data type is NFT_DATA_VALUE normally means the two lengths differ. Because the check at (7) is skipped for verdicts, the mismatch is never caught, and the copy at (1) writes more bytes than were reserved. That is the heap buffer overflow, and it can reach up to 48 bytes beyond the reserved space.
Stay here ! I will be back soon !
This is not the easy kind of overflow where the attacker types the exact bytes that spill over. Here, random data gets copied out of the allocated buffer. Looking again at the call at (5), the copied data comes from the local variable elem, which is an nft_set_elem object.
struct nft_set_elem elem; <===== (2)
...
elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, <===== (5)
elem.key_end.val.data, elem.data.val.data,
timeout, expiration, GFP_KERNEL);
Line by line:
struct nft_set_elem elem;at(2)declares the local element on the stack.- The call at
(5)passes three pieces of that local variable to the initialiser: the key data, the key-end data and the element data. The initialiser then copies from those places using the set's lengths.
nft_set_elem is the structure used to hold information about a new element while it is being created.
#define NFT_DATA_VALUE_MAXLEN 64
struct nft_verdict {
u32 code;
struct nft_chain *chain;
};
struct nft_data {
union {
u32 data[4];
struct nft_verdict verdict;
};
} __attribute__((aligned(__alignof__(u64))));
struct nft_set_elem {
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} key;
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} key_end;
union {
u32 buf[NFT_DATA_VALUE_MAXLEN / sizeof(u32)];
struct nft_data val;
} data;
void *priv;
};
Line by line:
#define NFT_DATA_VALUE_MAXLEN 64defines a constant: the maximum length of a data value is 64 bytes.struct nft_verdict { u32 code; struct nft_chain *chain; };describes a verdict: a numeric code and a pointer to the chain it refers to. A chain is a list of firewall rules.struct nft_data { union { u32 data[4]; struct nft_verdict verdict; }; }describes a piece of data that can be seen either as four 32-bit numbers (16 bytes) or as a verdict. A union means the two views share the same memory; only one is in use at a time.struct nft_set_elem { ... };holds three such slots, namedkey,key_endanddata, plusvoid *priv;, a pointer the kernel uses internally.- Each slot is itself a union of a 64-byte byte buffer (
buf) and the 16-byteval. So 64 bytes are reserved per slot, but only 16 bytes are meaningful when a verdict is stored.
64 bytes are reserved to hold the element's data temporarily, but at most 16 bytes are written into elem.data when the overflow is triggered. The remaining bytes are whatever happened to be on the stack before, which is why the overflow data looks random.
Finally, not so random
At this point there is an overflow, but the data used to corrupt memory is uncontrolled, and building an exploit on uncontrolled data is a real challenge. However, elem.data is not initialised at (2), and that can be turned into an advantage.
Looking at the caller, nft_add_set_elem is called from nf_tables_newsetelem once for each element the user wants to add to the set.
static int nf_tables_newsetelem(struct sk_buff *skb,
const struct nfnl_info *info,
const struct nlattr * const nla[])
{
...
nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
err = nft_add_set_elem(&ctx, set, attr, info->nlh->nlmsg_flags);
if (err < 0) {
NL_SET_BAD_ATTR(extack, attr);
return err;
}
}
}
Line by line:
- The function receives the incoming message (
skb, a socket buffer holding network data), information about the request, and the parsed attributes. nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {is a loop over a list of elements nested inside one attribute.remtracks how much of the list is left. Because the user decides how many elements to send, the user decides how many times the loop runs.err = nft_add_set_elem(&ctx, set, attr, info->nlh->nlmsg_flags);adds one element.if (err < 0) { NL_SET_BAD_ATTR(extack, attr); return err; }records which attribute was bad and stops on error.
nla_for_each_nested is built only from macros and inline functions. A macro is a piece of text the compiler substitutes in place; an inline function is one the compiler may paste directly into the caller. Neither creates a separate function call frame, so one call to nft_add_set_elem can be followed immediately by another with the same stack area reused. That is very useful: because elem.data is not initialised, the bytes left behind by the previous element are still there, and the next element's overflow copies them. It also sidesteps stack randomisation, the defence that shuffles the layout of the stack to make addresses unpredictable. The way to control the overflow is therefore independent of how the kernel was compiled.
The following schema summarises the different stages of elem.data within the stack to produce a controlled overflow.

The diagram shows the sequence: random data sits on the stack; adding a new element with NFT_DATA_VALUE data leaves user-controlled bytes there; then adding a second element with NFT_DATA_VERDICT data triggers the overflow, and the leftover bytes from the previous element are what gets copied.
Cache selection
The last thing to settle before writing the exploit is which cache the overflow lands in. A cache here is a pool of fixed-size memory blocks that the kernel hands out quickly; asking for a block of a given size gets you one from the matching pool. elem, allocated at (0), depends on the options the user picks, so its size varies. Several options can make it bigger, such as NFT_SET_ELEM_KEY and NFT_SET_ELEM_KEY_END, which reserve two buffers of up to 64 bytes each inside elem. The overflow can therefore happen in several caches. On Ubuntu 22.04, elem is allocated with the flag GFP_KERNEL, so the relevant caches are kmalloc-{64,96,128,192}: pools whose blocks are 64, 96, 128 and 192 bytes.
The remaining task is to line elem up with the size of the cache block so the overflow does the most good. The next schema shows how elem is built to line up on 64 bytes.

The construction used to target the kmalloc-64 cache is:
- 20 bytes for the object header
- 28 bytes of padding via
NFT_SET_ELEM_KEY - 16 bytes to store the element data of type
NFT_DATA_VERDICT.
Padding means deliberately adding filler so the total reaches a chosen size. Here the filler pushes the element to exactly 64 bytes, so it sits neatly in a 64-byte block and the overflow spills into the next block.
Gimme a leak
With controlled overflowing data in hand, the next step is to find the KASLR base. KASLR stands for Kernel Address Space Layout Randomisation: at each boot the kernel loads itself at a random address, so an attacker cannot know where kernel functions live. Leaking one real kernel address reveals the offset, and from that the base can be calculated. A leak means getting the kernel to hand back memory contents it should not.
The overflow only happens in kmalloc-x caches, so the classic msg_msg objects cannot be used for the leak: they are allocated in the separate kmalloc-cg-x caches. msg_msg is the kernel's internal object for a message in a queue, a common building block in exploits.
user_key_payload objects, normally used to store sensitive user information in kernel land, are a good alternative. They resemble msg_msg: a header holding the object's size, then a buffer holding the user's data.
struct user_key_payload {
struct rcu_head rcu; /* RCU destructor */
unsigned short datalen; /* length of this data */
char data[] __aligned(__alignof__(u64)); /* actual data */
};
Line by line:
struct rcu_head rcu;is bookkeeping used by RCU, a kernel mechanism for freeing memory safely while other code may still be reading it.unsigned short datalen;is the length of the stored data, a 16-bit number.char data[] __aligned(__alignof__(u64));is the flexible tail holding the actual bytes, aligned for 64-bit access.
These objects are allocated in user_preparse.
int user_preparse(struct key_preparsed_payload *prep)
{
struct user_key_payload *upayload;
size_t datalen = prep->datalen;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL); <===== (6)
if (!upayload)
return -ENOMEM;
/* attach the data */
prep->quotalen = datalen;
prep->payload.data[0] = upayload;
upayload->datalen = datalen;
memcpy(upayload->data, prep->data, datalen); <===== (7)
return 0;
}
Line by line:
- The function receives a prepared payload, which holds the user's data and its length.
size_t datalen = prep->datalen;copies the length into a local variable.if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL;rejects empty data, data longer than 32767 bytes, or a missing data pointer.upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);at(6)allocates a block sized as the header plus the user's data.if (!upayload) return -ENOMEM;handles allocation failure.prep->quotalen = datalen;records the length for quota accounting.prep->payload.data[0] = upayload;stores the new object in the payload.upayload->datalen = datalen;writes the length into the header.memcpy(upayload->data, prep->data, datalen);at(7)copies the user's bytes just after the header.return 0;means success.
The allocation at (6) takes the user's data length into account, and the data is stored right after the header at (7). The header is 24 bytes, so these objects can fill several caches, from kmalloc-32 up to kmalloc-8k.
As with msg_msg, the goal is to overwrite the datalen field with a larger value than the original. When the stored information is read back, the corrupted object returns more data than the user supplied, and that extra data is neighbouring kernel memory: the leak.
There is an important drawback to this spray. Spraying means allocating many objects of the same kind so that one of them lands next to the target. The number of objects is limited: the sysctl variable kernel.keys.maxkeys caps how many keys a user keyring may hold, and kernel.keys.maxbytes caps how many bytes may be stored. A sysctl is a kernel setting adjustable at runtime. The defaults on Ubuntu 22.04 are very low.
kernel.keys.maxbytes = 20000
kernel.keys.maxkeys = 200
With these defaults, at most 200 keys and 20000 bytes in total, which limits how wide the spray can be.
Leaking is good, leaking useful is better
Finding a way to leak is one thing; leaking something useful is another. Working in the kmalloc-64 cache seemed best, because it is the smallest cache where the overflow can happen, so more objects fit and more can leak.
percpu_ref_data objects are also allocated in that cache. They are interesting because they contain two useful kinds of pointer.
struct percpu_ref_data {
atomic_long_t count;
percpu_ref_func_t *release;
percpu_ref_func_t *confirm_switch;
bool force_atomic:1;
bool allow_reinit:1;
struct rcu_head rcu;
struct percpu_ref *ref;
};
Line by line:
atomic_long_t count;is a reference count, safe to update from several cores at once.percpu_ref_func_t *release;andpercpu_ref_func_t *confirm_switch;are pointers to functions that run when the reference is released or switched. A function pointer is the address of code, so leaking one reveals where the kernel's code sits in memory.bool force_atomic:1;andbool allow_reinit:1;are two single-bit flags packed together.struct rcu_head rcu;is RCU bookkeeping.struct percpu_ref *ref;points back to the object being counted, which is dynamically allocated, so leaking it helps compute the physmap base. The physmap is the kernel's direct mapping of physical memory.
Such objects are allocated during a call to percpu_ref_init.
int percpu_ref_init(struct percpu_ref *ref, percpu_ref_func_t *release,
unsigned int flags, gfp_t gfp)
{
struct percpu_ref_data *data;
...
data = kzalloc(sizeof(*ref->data), gfp);
...
data->release = release;
data->confirm_switch = NULL;
data->ref = ref;
ref->data = data;
return 0;
}
Line by line:
- The function receives the reference object, the release function, flags and allocation flags.
data = kzalloc(sizeof(*ref->data), gfp);allocates and zeroes the bookkeeping object.data->release = release;stores the release function pointer, which is the value worth leaking.data->confirm_switch = NULL;clears the switch pointer.data->ref = ref;stores the back-pointer.ref->data = data;links the bookkeeping object to the reference.return 0;means success.
The simplest way to allocate percpu_ref_data objects is the io_uring_setup syscall. A syscall is a request a program makes to the kernel, for example to open a file or create a queue. io_uring is a Linux feature for submitting many input/output operations efficiently. A simple call to close is enough to schedule the release of such an object.
The allocation happens while an io_ring_ctx object, the context for one io_uring instance, is being initialised inside io_ring_ctx_alloc.
static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
{
struct io_ring_ctx *ctx;
...
if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
goto err;
...
}
Line by line:
- The function receives the parameters for the new io_uring instance.
__coldis a compiler hint that this code runs rarely. struct io_ring_ctx *ctx;declares the context pointer.if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free, PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) goto err;initialises the reference count and passesio_ring_ctx_ref_freeas the release function. That function pointer is what ends up in the object.goto err;jumps to error handling if initialisation fails.
Because io_uring is part of the Linux core, leaking io_ring_ctx_ref_free lets the KASLR base be computed.
During the investigation, some unexpected percpu_ref_data objects showed up in the leak with the address of io_rsrc_node_ref_zero in the release field. After analysing where they came from, they too turned out to come from the io_uring_setup syscall. This side effect improved the leak in the exploit.
I am (G)root
With a useful leak in hand, a good write primitive is needed to escalate privileges. A few weeks earlier, Lam Jun Rong from Starlabs published an article describing a new way to exploit CVE-2021-41073: the unlinking attack. It is based on the list_del operation. A list in the kernel is made of nodes, each holding two pointers: one to the previous node and one to the next. list_del removes a node by writing the next pointer into the previous node and the previous pointer into the next node. If an attacker controls those two pointers, the kernel writes one chosen address at another chosen address: a write primitive.
As in that article, the target for the list_head corruption here is a simple_xattr object. An extended attribute (xattr) is a small named value attached to a file, used for extra metadata.
struct simple_xattr {
struct list_head list;
char *name;
size_t size;
char value[];
};
Line by line:
struct list_head list;holds the previous and next pointers that chain this attribute into a list.char *name;points to the attribute's name.size_t size;is the length of the value.char value[];is the flexible tail holding the value itself.
For this technique to work, the attacker must know which object was corrupted. Otherwise, removing random items from the list will surely crash during the list traversal. The items are identified by their names.
To identify the corrupted object, a trick is used on the name field. Allocating name with a length large enough to reserve 256 bytes makes the least significant byte of the returned address zero. The least significant byte is the last byte of the address in memory order. On little-endian architectures such as x86_64, numbers are stored with their smallest part first, so that byte sits right after the two pointers in the list_head. Erasing it is enough to prepare the list field for the write primitive and, at the same time, to identify the corrupted object by truncating its name. The only requirement is that all names end the same way.
The following schema summarises how the name is built for a spray of simple_xattr objects.

Root shell
Using this write primitive, it is possible to edit modprobe_path with a path in the /tmp/ folder. modprobe_path is a kernel setting holding the program the kernel runs when it needs to load a module, a piece of code that can be added to the kernel at runtime. Pointing it at a program of the attacker's choosing means that program runs with root privileges, which gives a root shell.

Remarks
This exploitation method assumes that a specific address is mapped in kernel land, which is not always the case. The exploit is therefore not fully reliable, though it still has a good success rate. The second drawback of the unlinking attack is the kernel panic that comes when the exploit finishes. A kernel panic is the kernel's emergency stop when it detects an unrecoverable fault. This could be avoided by finding objects that can stay in kernel memory at the end of the exploit process.
The end of the story
The vulnerability was reported to the Linux security team and CVE-2022-34918 was assigned. They proposed a patch, which the researcher tested and reviewed, and it was released in the upstream tree within commit [redacted]. A commit is one recorded change in a source code repository; the upstream tree is the main Linux source that distributions copy from.
Conclusion
To sum up, a heap buffer overflow was found in the Netfilter subsystem of the Linux kernel. It could be exploited to escalate privileges on Ubuntu 22.04. The source code of the exploit is available on GitHub.
The researcher acknowledges RandoriSec for the opportunity to do vulnerability research inside the Linux kernel during an internship, and the research team for their advice.
Glossary
- API: Application Programming Interface, a defined set of requests one program can make to another; here, the kernel interfaces a program calls to ask for things.
- Array: A numbered row of identical slots in memory.
- Attribute: One labelled piece of a message, like one field in a form.
- Buffer: A reserved area of memory used to hold data temporarily.
- Buffer overflow: Writing more data into a buffer than it was reserved for, so the extra spills into neighbouring memory.
- Cache (kmalloc): A pool of fixed-size memory blocks the kernel hands out quickly;
kmalloc-64holds 64-byte blocks. - Chain (netfilter): A list of firewall rules that packets are checked against.
- Commit: One recorded change in a source code repository.
- CVE: Common Vulnerabilities and Exposures, a public catalogue number for a known security flaw.
- Flexible array: A tail of bytes at the end of a structure whose length is decided when the object is created.
- Function pointer: A value holding the address of code, so leaking it reveals where code sits in memory.
- Heap: The kernel's general-purpose storage area where memory blocks are allocated and freed.
- Inline function: A function the compiler may paste directly into the caller instead of calling separately.
- io_uring: A Linux feature for submitting many input/output operations efficiently.
- KASLR: Kernel Address Space Layout Randomisation, which loads the kernel at a random address each boot.
- Kernel: The core program underneath a Linux system that controls memory, hardware and permissions.
- Kernel panic: The kernel's emergency stop when it detects an unrecoverable fault.
- Leak: Getting the kernel to hand back memory contents it should not.
- Little-endian: A byte order where the smallest part of a number is stored first.
- Local variable: A variable that lives on the stack inside one running function.
- Macro: A piece of text the compiler substitutes in place before compiling.
- memcpy: A standard function that copies a given number of bytes from one place to another.
- Module: A piece of code that can be added to the kernel at runtime.
- Namespace: An isolated view of the system, so separate containers do not see each other's resources.
- Netfilter: The Linux kernel's built-in firewall subsystem.
- nftables: The feature used to configure netfilter, with tables, sets and rules.
- Out-of-bound: Reading or writing just outside the area a program is supposed to use.
- Padding: Deliberate filler added so an object reaches a chosen size.
- Patch: A change to source code that fixes a bug.
- Pointer: A value that stores the memory address of something else.
- Privilege escalation: Gaining more power on a system than you were given, here reaching root.
- RCU: A kernel mechanism for freeing memory safely while other code may still be reading it.
- Root: The administrator account on Linux, with full power over the machine.
- Root shell: A command prompt running with root privileges.
- Set (nftables): A named collection of values, such as addresses or ports, used by firewall rules.
- Spray: Allocating many objects of the same kind so one lands next to the target.
- Stack: The small scratch area each running function gets for its local variables.
- Struct (structure): A bundle of named fields stored together in memory.
- Syscall: A request a program makes to the kernel, such as opening a file or creating a queue.
- sysctl: A kernel setting adjustable at runtime.
- Union: A structure whose members share the same memory, with only one in use at a time.
- Upstream tree: The main Linux source repository that distributions copy from.
- Verdict: A special kind of netfilter data telling it what to do with a packet, such as accept or drop.
- Write primitive: A reliable way to make the kernel write a chosen value to a chosen address.
- xattr: Extended attribute, a small named value attached to a file for extra metadata.