And with no further ado, please continue. Hello, everyone, and welcome to my talk, Clash, Burn, and Exploit Manipulated Filters to Pwn Kernel CTF. I'm HexRabbit from Taiwan, currently working as a security researcher at DefCon. I specialize in binary exploit, especially in Linux kernel exploitation. I found some vulnerabilities in Linux kernel components like ksmbd, nstables, and others. Today, I will start from introducing kernel CTF and nstables. After that, we will dive into the nstable internals and talk about three vulnerabilities we discovered in nstables. And in between these three vulnerabilities, I will also share some story behind the scene during my kernel CTF journey. So, let's first talk about kernel CTF. Kernel CTF is part of Google VRP, and the way it works is quite similar to a CTF challenge. For about every two weeks, there will be a new kernel version released, and attendees will be given an unprivileged show. And you will need to exploit the Linux kernel to get flagged and submit it to Google to earn a bounty. There are three instances that can be pawned. LTS and CLS both use newer and quite similar kernel config, while the mitigation one uses an older kernel config with custom security patch to accept more one-day exploits. But the most important thing is, Google offers pretty big bounty reward. With some simple math calculation, we can quickly find for a zero-day LTS exploit, the bounty can easily surpass $50,000. And with the same vulnerability, you can earn both $21,000 maximum in both mitigation and CLS instance, which is quite appealing for the bounty hunter like me. So, why am I targeting nftables? First, nftable config is enabled in kernel CTF. And as you can see on the right, there are multiple vulnerabilities discovered just after kernel CTF is announced. So, for kernel CTF newbie like me, I think it's the right place to start. Okay, so first we take a brief intro to nftables. What exactly is nftables? nftable is a package filtering framework inside Linux kernel. It's used to replace the legacy IP, ARP, EB tables, merge them into a single entry point. It uses a simple VM design to implement its functionality and support new syntax for CY interface. As you can see on the right, instead of doing things one by one, new syntax can now allow config multiple things all at once. And these capabilities come from its design, which we will revisit later. nftable is constructed by a tree-like structure. It contains five core modules, table, chain, rule, expression, and set. Table is the top-level container for the below structures. It's used for the measurement purpose. Each table will only belong to a specific neural family, and any object contained by the table will follow the same family. Chain in nftables will hook at predefined hooking point provided by net filter infrastructure to do the packet filtering. When any packet flows through the hooking point, the chain will execute the expressions in the row it managed to accept or to block or to modify the packets. So what is the rule and what is the expression? As I mentioned earlier, nftable implement its functionality by a simple virtual machine. So you can think a rule as a small function that can contain multiple expressions, and the expression is the instruction for nftables. There are different types of expressions that can be used to manipulate VN registers, and the others can be used to load or to read or write data within packets. And thus, set is used to store a group of some type, like IP address, port, or any binary data. It can also be used as a map to map some type A to another type B, and these data stored in the set can be queried by the expressions during packet filtering. Okay, so after having some basic understanding of nftables, I will now introduce the first vulnerability I discovered. At the time, I'm not so familiar with nftables. However, I spotted something weird in the code base. These three functions are all used to delete objects in nftables. The nftable deleteRuleDeactivate will be called during rule deletion, nftFlush will be called during full config flush, and nftSetElementCatchAllDeactivate will be called during set element deletion. However, the pattern here is a bit different. The first two use nftIsActiveNext to check if the object is active. But the last one, nftSetElementCatchAllDeactivate use nftIsActive to check. So what's the difference? Actually, these two functions are used for object lifetime management in nftables. In order to understand how it works, we will need to first talk about the batch request mechanism. For a query request, for example, the getRule operation above, Netlink API will internally use netlinkReceiveXKB to get the raw information loglessly. However, if it's some operation that will modify the control plan, like new table or delete chain, nftables will use nfnetlinkReceiveBatch instead of the logless one to serve the request. The difference between them is that batch one can process a request which contains multiple operations, and they will be processed sequentially. And also because of this design, the COR interface can copy multiple things all at once. So it sounds great, but the thing becomes more complicated when any operation fails in the middle of a batch request. And what nftables do is to split batch request handling into multiple phases. There are three phases during the handling of the batch request. Prepare phase, commit phase, and abort phase. During the prepare phase, if every operation finished successfully in the batch request, it will go to the commit phase and commit the changes. However, if something went wrong, after every operation is processed, it will go to abort phase and revert all the changes. Here's the lifetime management's consign. Any object in nftables has two state variables, current generation and next generation. Only the object activated in current generation can affect the runtime behavior. And you can think the next generation as a temporary state for the prepare phase. Every operation modify the control plan, like new or delete operations, will only make changes on the next generation state in the prepare phase. So without affecting the current generation state. Then, during the commit phase, it will commit the modification. So the current generation will finally be set as the next generation, and the next generation state will be reset to a clean state. But in the case if something went wrong during the abort phase, it only needs to clean the next generation state. Let's go through some examples to know how it works. After a batch request is received, it goes into the prepare phase. The first operation is delete set C. Okay, so the set C's next generation state will be set to deactivated. Next, it continues to process a set D operation. So the set D will be added into hash table with next generation in activated state. If nothing went wrong, we will go to the commit phase, and at this phase, current generation will be set as the next generation. So the set D will be available in both runtime and query operations, and also the set C will be free. If something went wrong, we will enter the abort phase, and at this phase, all operations done in the prepare phase will be reverted in a reverse order. So the add set D will be undue, and also the delete set C will be undue. So okay, back to the check. So what's the problem here? As we can see, during the NFT set element catch all deactivate, it used NFT is active to check if the element is still alive. However, NFT is active checks current generation, but the function actually runs in the prepare state, which will only modify the next generation state of an object. So the check here will always pass, and by request multiple delete operations, we can free the element multiple times in the commit phase. So the batch request to trigger double free will look at this, since the lifetime check will always pass if the element exists during the prepare phase, two delete set element of operation will both execute successfully. And so when you get to the commit phase, the same element will be free twice, and we get a set catch all element double free. Great, so I found my first bug for current CTF. But the next day, I found the maintainer also find the same bug and send a patch to kernel mailing list. I mean, why? So, okay, this means my zero day is officially turns into a one day, and according to kernel CTF rules, my bounty will decrease by 20,000 USD. Ouch. Also, one day vulnerability means that everyone will know how to trigger the vulnerability, and they may also come up with some exploit. So I definitely need to exploit it before next kernel CTF slot opens. So after we get the double free primitive, we reuse the exploit method for CVE-2023-4004 to overlap the MFT table user data and MFT object to leak address and control IP. Due to a time limit of this talk, I won't expand the detail of it, but kudos to Lonely and Calm who discovered this technique and shared it on kernel CTF repository. So now we develop the exploits and wait for the slot to reopen. Fast forward to two hours before the competition starts. I nervously check if there's any kernel updates related to NF tables, and guess what? The patch previously posted on the mailing list has been merged into the kernel, and it added one line on it. It says reported by Lonely and Calm, which this means is the patch may actually come from a zero day kernel CTF submission, and since the reporter is Lonely and Calm whose exploit I just used, this is indeed the case. So just before I have the chance to exploit an official instance, I found it's a collision. So yes, I still found the instance and report the flag, but too bad for me, the first bug do collide with an old kernel CTF submission. That's how I look after the competition. Okay, so I take some break, and after three weeks later, I found the second bug. During the research, I came across an interesting commit. NF table validate family when identifying table by handle. The commit is added after the mitigation instance kernel version, so it can be used upon the mitigation instance as a one day. It added a check on NFC table lookup by handle function, which is used for searching a register table by the provided handle. Without the commit, during the table lookup, we can provide a family different from the one which table belongs to, but what can we do with this inconsistency? Let's trace where the family parameter comes from and where it goes. NF table lookup by handle is only code from NF table delete table, and this function is used to delete user-specified table from NF tables. The family variable is directly get from user-provided input and is saved into context family and passed to NFT flush table function. In NFT flush table, context argument is passed into every function handling object deletion. For me, trace which function use the context family is quite annoying, so instead of just tracing into each function, I take the shortcut to trace where it is used. So I just grab the whole code base to find where the context family is used. Grabbing context family gives us a lot of result, most of which comes from the NF table expressions, like count limit, net, T proxy, and et cetera. However, most of them cannot be used for the exploit, but I finally found one that can be exploited. It is in the NFT log expression. The trigger path I found starts from the NFT log destroy. This function takes context family as an argument and code to NF log output. Now it's becoming the PF argument and used as an index to de-reference the loggers array. The value range of our input context family and also the PF here is zero to 255. But if we check the size of loggers array, we can find it only has 13 elements in the first dimension. So we get the global array out of bound access here. But what can we do with it? After taking the logger out, it de-referenced the me field and feed it into the module put. The module put will again de-reference and decrease the refcon value in the module object. With this vulnerability, logger can be any pointer store adjacent to a loggers array. So we may cause some type confusion here and decrease some variable by one. However, we are dealing with an awkward situation here. In order to utilize this bug, we have to find a pointer store on global and can be de-referenced twice. The first is to take our logger me and the second is to take our module refcon. To sum up what we have by now, first, the maximum value of PF value we can control is 255 and we can trigger an out of bound reference count decrement by using a PF value larger than 12, which will execute like the code here. To exploit this, the first thing we need to do is to find a global pointer placed near the loggers array. So what do we have on the global? By inspect the marrying GDB, we quickly find there's an NFCT expect hash placed near the loggers array. And it's a hash table. So in this case, it seems to be a good target since the pointer point to an array of pointers. Therefore, it can be de-referenced twice. So let's check how the code normally works. First, it gets the me field at offset 1x and then get the refcon at offset 340x. Now let's check the out of bound access case. First, we set PF to 19 to get a hash table pointer, NFCT expect hash. The first de-reference we got is the index tree entry of the hash table. The entry points to the HNO field of a contract expect object. So after one more de-reference, it will access offset 340x down below the expect object. But since the expect object only has a D at size, it will access out of bounds. Fortunately, all NF contract expect object allocated in a dedicated Cayman cache. So the memory space below will also contain NF contract expect objects. So it will access to an RCU field and decrease the next pointer in the structure. But what does this next pointer use for? As we know, after RCU objects free, Linux kernel will not instantly free the object. Instead, it will hold the object for a grace period to wait for all other RCU readers to finish. So the next pointer in the RCU hash structure is used for temporary storing them and waiting for the RCU thread to process, to free them. So after the contract expect object are free, they will be like this, trained by the next pointer. And since we can decrease the next pointer in RCU head, we can make it point to another field inside the contract expect object. And to exploit it, we choose to land it on a user controllable field, which contains a union of IPv4 and IPv6 address. So when RCU callback triggered, it will read the fake function pointer we set, and we can control the IP. However, to actually exploit the vulnerability, we came across some roadblocks. First, we need the index tree of the hash table point to some expect object, so we can use it to do the out-of-bound write. But unfortunately, the hash value is unpredictable. Next, the out-of-bound written expect object needs to be in the grace period, so we can decrease its next pointer. But the next period is a small time window, and how to control when the kernel actually frees the object. Well, so long story short, we eventually found a way to exploit it by brute force and race. So to exploit this, first we use a tight loop to create a lot of expect objects. And at some point, the expect count exceeded the value max expected and start to evict the oldest expect object. So the oldest expect object will be placed into the RCU free list. And so on, and so on. And at some point, RCU thread gets scheduled by the kernel and starting to process objects. At this point, we add another thread to trigger out-of-bound decrement in a batch request and keep this system running for a bit. So we hope for a race scenario like this to emerge. First, the expect object allocated into index three of the hash table, and then the expect object we want to out-of-bound write is freed into the RCU free list. Then it continues to free another expect object. After that, we trigger the vulnerability 28 times in a batch request to make the next pointer point to a user-controllable value. And finally, the RCU start to process these free object and runs our set callback function. Great. Let's try it on local build. And we successful successfully control the IP to form, form, form, form. So what about remote? Let's try. And we got an error message while trying to add the lock expression. Since I have no idea what happened on the remote environment, I decided to download the official busy image to debug it locally. So I open the GDB and set some breakpoint on the functions, but when I set the break on nft-lock-destroy function, GDB complained that it was not defined. What's wrong here? I later found that it's because the kernel config I used is different from the one used in the official environment. So the log expression I used to exploit the vulnerability not even compiled into the official image, but I'm using the official build script to view the local test image. Why on earth there can be any difference? I mean, why? Eventually, I found it is caused by the official build script. The mitigation instance is built by COS kernel config plus the Google custom security security patch. And the official mitigation instance use COS config 6.1.55. The nftable expression are enabled in COS config after the version 6.1.64. However, the build script will always fetch the latest COS config, so the mitigation kernel I built has the nftable expression enabled, but in the official image, they're actually disabled. So, well, I think next time I should definitely check out the config first. Okay, so after my second failure, I revisit some old patch and I found a new bug. The patch I was looking at is a patch which introduced the first bug. The title says nftable, a set backend to use GC transaction API. So what does the GC mean? Here it means the set garbage collection. There are some set implementation support user to set a timeout on any set element. And there are two types of GC to clean the expired element. The first one, the synchronous one will be called in the commit phase, and the asynchronous one will be triggered periodically in the background. But here we only focus on the asynchronous one. So back to the patch. In the commit message, it says use GC transaction API to replace the old and buggy GC API and the busy mark approach. So what is the difference between the new and the old one? Let's take a look of the old GC design. In the old design, the synchronous GC will run loglessly and can be triggered at any time. So in order to protect GC threads from raising with the landing API, both of them will check a busy mark set on the element before delete it to prevent double free. But sometimes the developer might forget to check against it. In this case, there's a new function called NFT map deactivate forgot to check a busy mark. And this leads to a double free vulnerability. So in order to avoid this kind of issues, NFT developer decided to replace it with a new design. In the new GC design, it introduced the GC sequence. The GC sequence is a per net variable and it will be increased before and after any modification to the control plan. So it will increase at the beginning and at the end of both the commit and the abort phase. During a GC procedure, GC thread will record and check it to prevent raise. Even though the GC thread still run loglessly, during the check, it will now quad the commit mutex lock. The new GC design look like this. During batch request handling, GC sequence will increase both before and after the commit and abort phase. And in the GC thread, it will first run locklessly to store the GC sequence and collect all the expired elements. After that, it will quad the lock and check if the current GC sequence match the safe one. If they are the same, then the elements will be released. For this normal case, since GC thread does not raise with the batch request, the GC sequence will be the same. And the element can be freed by the GC thread. Next, we check if it still works in the raise case. If during the prepare phase, GC thread triggered and stored the global GC sequence into transfer objects, it will continue to run loglessly to find all the expired elements and wait for the mutex lock. At the same time, the main thread stepped into the commit phase, and some of the elements in the set can be released in this phase. The GC thread will need to wait until the main thread releases the mutex lock, so it can finally check the safe GC sequence and delete the element. But in this case, since GC sequence is recorded in the prepare phase, and we check it after the batch request is done, the GC sequence will be different. So, the element deletion will be skipped to avoid double free. Next, let's check the case if GC sequence is recorded in the commit phase. In this case, since GC sequence increased after the commit phase, the GC thread can only check GC sequence after the commit mutex unlocked. This raise will also be detected. So, to sum up, the new GC design requires both the batch request and the GC sequence check to hold the lock. This ensures that even there's a raise while collecting the expired element, the check will always happen after the GC sequence has increased. But does the batch request always lock mean there's no raise? Actually, if you look closely, we will find, well, it's not always locked. To find where it release the lock, let's first talk about the module autoload. During the prepare phase, if there's some expression type in the request is not found during the type resolution, it will instantly abort and try to load the type module during the end of the abort phase. After that, it will retry the whole batch request again. However, maybe there's some efficiency consideration or to just only prevent that lock before the function tries to load the request module, the mutex lock will be released. But could it cause any problem? Back to the diagram. Now there's a little time window in the abort phase that it will not hold the mutex lock. So there's a chance during the abort phase, the GC check kicks in, recalls the expired element and do a GC sequence check. In this case, however, the check will be bypassed. And the GC thread can delete arbitrary expired elements. Okay, so now the question is, how do we actually exploit the race? Our exploit plan is first, we add a set element with a short timeout. And then we trigger module autoload to force it to revert the commit and free the element we just added. And at the same time, we trigger GC to collect that element. Next, module autoload will release the mutex and we hope that the GC thread will grab it and bypass the check. So as a result, the element we just added will be double free. But in order to trigger double free, there are two time windows we need to enlarge. The first time window is from the abort phase start to the set element released. So the GC thread can recall the expired element before they get a link by the revert procedure. The second time window is from the load module to its end. So the GC thread can grab the lock and bypass the check. For the first one, since the abort phase will revert the operations in reverse order, we add a bunch of requests after the add set element request to delay the link operation. For the second one, we just request multiple unknown type to make module autoload runs longer. And here's the demo. Okay. So first we boot our machine and check the UID is a normal user and then we run the exploit. So here we will first measure the execution time to set up timing parameter for the race. And after that, we set up the environment to enlarge the race time windows. Then we trigger double free to leak address and control IP. And we got the root shell. Thank you, guys. Great. So now I write the exploit and submit it to kernel CTF. And this is my kernel CTF submission. I exploited the LTS instance on kernel version 6.1.81. But as you can see, it is marked with a dupe in that line. It is because for every LTS slot, only the first zero day or one day exploit will be accepted. And there's someone who also submitted a LTS exploit which beat me by nine seconds. That's too bad. So we have to wait for the slot to reopen. So, yes, just wait for about two weeks and the slot will reopen. Right? Wait until it starts to reopen. Yep. But do you know the F table will be disabled for April 1st? What? Actually, there's an announcement on kernel CTF. It says they are going to disable NF tables along with the switch to kernel version 6.6. It starts from March 15th but actually they delay the switch so it's from April 1st. Okay. So what's the date today? It's actually March 22nd. And the kernel CTF slot opens about every two weeks on average which means I won't be able to exploit before they disable the NF tables. So on my third kernel CTF attempt, I still could not get a bounty which is pretty sad. To sum up my journey, first I have hope and then I found bug one, a lifetime issue. And it collides with another submission. Then I found the bug two, a hard to use one day. But I used the wrong config so it's unusable. Then I found the bug three, a locking issue. But I lose the submission race and NF table will be disabled so it's killed. However, there's a final plot twist. A few days after, I found there's some changes in the kernel CTF spreadsheet. The person who previously got ahead of me is disqualified due to a bug collision. And so this time, I finally take over the slot and report it to Google. And this month, I got my kernel CTF bounty from Google which is my first Google VIP bounty. I'm so proud of myself. Thanks. So, well, I think this concludes my kernel CTF journey. And thank you, guys. Is there any questions? Yeah, if there's any questions, you can come up here to this microphone. Thank you.