Welcome everybody to SQL injection isn't dead smuggling queries at the protocol level or how i like to call it sql injection lower decks because usually with sql injection you're at the high level like at the bridge where the captain and the high-ranking officers are and they're speaking their query language and their business language but today we're going to do go down to the lower decks where the mechanics are and where they shift around bits and bytes. So, to hook you at the beginning, I have a small teaser. This code snippet is a small HTTP request handler written in Go and it just takes a user ID from the body and uses it in a prepared statement to select the user. And if you think everything's fine here, there's no way for a scale injection, then you should stay because I'm going to prove you wrong. And at a high level in this talk, we're going to look at how applications talk to their databases over the network and how attackers can inject in that connection and what can go wrong and also how prevalent the problem is. A bit about me, I'm Paul. I'm a vulnerability researcher at Sonar's R&D team. And if you don't know Sonar, we're the home of clean code, so we help developers write clean code, which also means secure code. And that's why we look at a lot of code and try to find stuff there. So, for the rough outline, first we're going to look at the idea of all of this research and then we'll go into the main part of the talk, which is attacking the database wire protocols. And we're going to focus on Postgres and MongoDB here. Then we'll put things into perspective by looking at the real world applicability of the research and then give you some ideas for future research and draw some takeaways. So, in short, the idea is to do request smuggling, but for binary protocols. And of course, for this I have to mention James Kettle's HTTP desync attacks, where you basically cause a disagreement between two systems over the end of an HTTP request. For example, between a reverse proxy and an upstream back end. And if they don't agree on where a message ends, or an HTTP request in this case, then the attacker can do some bad things. And the root causes of this were manifold, but some examples are text parsing, where one system would only accept the exact word chunked, and the other one would also allow a tapped character in front. Or they were logical, where one system used the content length header and the other used the transfer encoding, and then things were off again. But what about other protocols? And specifically, what about binary protocols? Where do they have message boundaries? How do they do it? Some of them have delimiters, where, for example, in null terminated strings, the null byte is the delimiter that tells the end of the string. Or you might have length fields, and there's an entire family of protocols that are called TLV, or type length value protocols, because they have a type field, and then a length field, and then the rest of the message is the value. So how could we desync in these protocols? For delimiters, it sounds quite easy. You just have to find a way to put a delimiter where it's not supposed to be, in a value. Of course, it's not that simple, but at least you directly have an idea of what you could do. But for length fields, I was stuck for a moment and thought about, okay, you have a length field, it has a fixed size, it has a fixed location in the message, so what could go wrong there? And then I thought, okay, maybe some endianness issues, or maybe integer overflows, and I wanted to go deeper into that. So for that, I first looked at the modern web application landscape, where our binary protocols used there. So at the center, you always have the application, and it talks to databases, or caches, storages, message queues, structured logging, and so on. And I wanted to focus on the connection between the application and the database. And that was because I thought that if I would find something, it would have a great applicability, because almost every web app has a database. Then there's a big potential severity, because databases are high-value targets, because they either contain interesting data, like personal information, or relevant data to the application, for example, used for authentication. And then also the exploitability should be quite good, because what web app has a database, but doesn't let the user query something from that database, right? So we have kind of guaranteed user input. So let's start in and look at some database wire protocols. And for that, I have a small overview of four popular databases and how their messages and their protocols look like. So for Postgres, this is how a message looks like. You have a type byte, then a four-byte length, and then the value, which in this case is just the string that's an SQL statement. For MySQL, it looks kind of similar. You first have the length, it's only three bytes, but then you have a one-byte sequence, which would allow you to send multiple packets that would be reassembled to one big message at the end. And there, of course, you have the value. For Redis, which is not exactly a binary protocol, but their docs kind of read like this, because they talk about, oh, here they have this byte, so I wanted to include it anyways. There, you first have a type byte, then you have a length, but it's not a fixed size field. It's a decimal integer that has to be parsed. Then you have a delimiter, and then the value, and then another delimiter. And finally, for MongoDB, it's a little bit longer. You first have the message length, again, a four-byte field. Then you have a little bit more metadata. For example, the opcode is like the message type, and then the value is a little bit more of a complicated binary structure called BSON. So let's start with Postgres. Again, this is how a packet looks there. One-byte type identifier, four-byte integer length fields, and then the value. So I thought about, okay, four-byte integer fields. You can fit quite big numbers in there, like two to the power of 32 minus one, which is roughly the size of four gigabytes. But maybe what if we could somehow make a query that's bigger than that? How do actually libraries handle this kind of too-large thing? And for that, I started to look into code of Postgres client libraries, and I found the first bug. This is the code of a library called PGX. It's supposed to encode the content of a message into a larger message buffer. So first, it writes the message type. In this case, it's a B for a bind message. Then it saves the offset, where it should later write the size to. Then it adds all of the actual data of the message. And finally, it writes the size. And to do that, it first slices the message buffer to the exact size of what is included in the length, for example, not the type byte. Then it takes the length of the sliced buffer. And here, the length is of type int, which in most modern systems is a 64-bit integer. But then this is truncated down explicitly to an int32. So we have a problem here, because if the length was bigger than what can be expressed in an int32, we now have a truncation and the number becomes very small. But then the library still sends all of the data after that. So then if the database has to parse this message, it will just see a very small length and only parse a very small message, and then try to parse whatever is coming after that as more messages. But in fact, it's data from the first message. So let's look at this again with example messages. So here we have a very small one. We have a 4-byte value. And then the length becomes 8, because the size of the length field itself is also included in the length. So it's a length of 8. This is how the largest possible message looks like. You can see the length is filled to the brim with hex FFFFF, because the value is just almost 4 gigabytes of ace. But still, everything's good, because the application can express this length in the 4 bytes, and so the database will parse the same size. But if we make it just a little bit larger, we can see that the truncation happens, because the most significant bit is not represented in the length anymore. So the length is just 4, which means this is a tiny message. And then after that, in the connection, there comes some garbage ace that the database can't really understand. But if the attacker chooses not ace, but some bytes that the database can understand, they can craft an injected message here. So let's zoom out again and look at this again. This is the small message, all is good. This is the large message that does not cause a truncation. So both the application and the database see it and parse it the same way. But if we make the size a little bit too big, the application thinks it's writing this big number, but actually, because of the truncation bug, it writes a small number. So when the database parses it, it sees one small message and then garbage. Or if the payload is cleverly crafted, it sees more messages that can contain attacker-controlled SQL statements like this one that adds a new admin user. So the impact is quite high here. You can inject entire SQL statements. You're not limited to union-based or subquery-based SQL injection like with the very classic ones. It's more like if you have stack queries enabled, so you can just finish the first statement that you're injecting into and then have a whole other one that can be an insert, even if the other one was a select, and so on. So this means the attacker can essentially read, write, and delete all the data in the database with the permissions of the application. And if the database is configured insecurely, this can already lead to code execution or you just have all of the data from the database, which is bad enough. The only thing that's a little bit less convenient than with classic SQL injections is that data exfiltration is a little bit less straightforward because if you're injecting more messages into the connection, then the application will still only process the answer for the first message. So you don't directly get the results of your injected message where you maybe select all the password recept tokens of users. So you have to go a different route of maybe doing a subquery and then using an insert to put this data you want to exfiltrate in another table and then use business logic of the application to access the data. So it still works, just a little less convenient. But how does this look in the real world? Some of you might have already noticed that if we control all of these A's that we have in a message, why can't we just directly put any SQL statement in the first place? Why do we need to have the overflow? And you would be correct, because this was just the simplification. So let's look at how this actually looks. This is a two-line code snippet. The ID here is user controlled. In this case, it's a very small one. And then we have our query. You might recognize it from the teaser code snippet that uses the ID to select a user from the database. And the resulting packet or message that's sent over the wire looks like this. We have our type byte, then a small length, and then we have the value with a trailing null byte. All is fine here. But now if the attacker makes the user controlled ID very large, 4 gigabytes, then suddenly the length in the packet is smaller than before, even though we send more data. So we see that the truncation happened. And now when the database tries to parse this packet, it will see, okay, it's a length of 38 bytes. So I'm going to parse until that. And after that, it will try to parse the next message. So the attacker has to put their cleverly crafted payload at that exact offset in this big buffer of A's. But how does the attacker know this offset? The offset depends on the query that they are injecting into, and especially on the injection point in the query and the length of the whole query. So if you know these things, you can just calculate the offset and you're done. But maybe you're lazy and don't want to do the math, or you don't know the query because it's kind of a black box test. So what can you do then? And of course, the naive solution is to brute force the offsets. But unfortunately, now for each try, you have to send 4 gigabytes, which is slow, even on local setups and on production setups, it creates a lot of noise and risks denial of service, because it's a lot of data. So can we make this more reliable? And the first technique I tried out here was to borrow something from binary exploitation from 20 plus years ago, which is called a knob sled. And mapped to this problem, we just use a lot of very small message at the beginning of the buffer, so that when we hit the start of one of these messages, everything's fine, because the message is parsed, and then the next one, and then the next one, and so on, until at the very end, the big message with the actual attacker SQL payload is parsed and executed. But if we hit any other byte, the database will cause a fatal error because it cannot parse there, and it will close the connection between the application and the database. But usually, that's not too bad, because applications have connection pools, and they just reopen connections if they get closed. So let's visualize this. This is the smallest possible message in the PostgreSQL protocol. So we repeat this a lot of times, and in the end, we have our actual payload. So if the offset happens to align with the first or the fifth and so on byte, then we're good. But if it hits one of the other bytes, then there's this fatal parsing error and the connection is closed. So if that happens, we can try again. And now, we just prepend one padding byte, and then if the offset happened to align with the second byte and so on, then now, this attempt would be lucky. Otherwise, we just try again, and again, and again, until we're lucky at the last try. So this means that after a maximum of five attempts, the attack is successful, because each try has a 20% chance of success, and we can repeat the attack. But still, in the worst case, we have to send five times four gigabytes, which can still be a lot. So maybe we can make it even better. And for this, I looked at what was holding us back with the last strategy. And here, it was the length bytes, because those were not valid type bytes, so not a valid start of a message. So maybe we can make them valid type bytes. And I call this technique trampolines. And what we do here is, first, we just use the queue, which is a valid type byte for each byte, because this is also some big length, it's hex 5151, and so on. And we can see down below the whole attacker payload. And we'll see how things are parsed when the offset hits certain bytes here. So if it hits the very beginning, the database parses it like this. First queue is the type byte, and then qqqq is the length of the first message. So the database will parse the following, whatever qqqq means as a number, bytes, and try to run this as a query. And of course, this will cause like a semantic syntax error, but this does not close the connection. So the database will just complain with an error response, but continue parsing the next message. So this is like jumping over this many bytes. So that's the trampoline right there. And where we land after that, we have a pre-constructed message that has the exact size that then does another jump that ends up right at the end of the attacker payload, where the actual SQL statement message is. So if we would have hit any of the other bytes, things look slightly different, but not too different. Here, the length is parsed as qsss. The s is also a very valid type byte. Now it jumps over some more bytes, and it lands at a different pre-constructed message that, again, has the exact size that it does the right jump to land at the end. But does this actually work like we planned to do? And unfortunately, after I tried to implement this, I noticed, well, Postgres has a logical maximum message size next to the actual size that you can possibly fit into four bytes. And this is just under one gigabyte. So the first byte of the length can never be larger than hex 3f. So that's bad, because with a q, that doesn't work. So what if we just use 3f as the type and all of the length bytes then? Also doesn't work, because hex 3f is not a valid type byte, and also none below that, at least not for messages from the application to the database. So I had to use a compromise here, which is an alternating pattern. And with this, now every second byte is a valid type byte, so a valid start of a message. So if we hit any of those bytes, we're good, because everything is parsed okay. And then we can do our trampolines, like I just showed. And if we hit any of the other bytes, like a null byte, then we get the error and the connection is closed. But still, we can try again. So after a maximum of two attempts, we are successful, which is much better than the initial brute force. All right, let's see how many vulnerable libraries there were that we found. And this is just a selection, we looked at more, but these are only the ones that were potentially vulnerable. So for Go, we tested four libraries, and we found all of them to be vulnerable and also exploitable. And I'm going to go into exploitability in a minute. Unfortunately, only one of them fixed the issues we reported, and the others did not. So they are still vulnerable in the latest version. For C Sharp, there was one library we looked at, it was vulnerable and exploitable, but unfortunately, they fixed and also backported it to older branches of the library. So that's great to see. And then for Java and JavaScript, we tested a bunch of libraries, and a lot of them were in theory vulnerable, they had overflows without the right checks, but they were not exploitable. And this was most of the times due to language limitations, where for example, you cannot have large enough strings or buffers that would be more than four gigabytes, so the length would never overflow the four byte length fields. And we're going to look into these language differences later. So short disclosure timeline for transparency, we send out the advisories in February this year, then PGX fixed in March, then PGSQL fixed in May. And for PG and PGDriver, the maintainer first responded to our advisory, but then stopped and didn't implement fixes until now. And for PQ, we couldn't even reach the maintainers, we tried to do it via their GitHub, made an issue or made a pull request with the fix, but they got no attention, unfortunately. So now let's go from vulnerable libraries to exploitable applications. So first, we have a set of applications that use these libraries, or have used libraries in a vulnerable version. And these, for example, include Grafana or Gitty or SyncThing, but we weren't able to confirm if there's an exploitable path here. So there might be, but we haven't proven it yet. And then there's a set of applications that we found to be vulnerable in a non default configuration, for example, Metamost or Gorgs. And then there was also the sweet spot, which is applications that are vulnerable in the default config. And our example here was Harbor. And Harbor is a container registry, it's a CNCF graduate project, which means it's quite mature and people are using it. It's also apparently part of VMware Tanzu Kubernetes, but we didn't look into more of that. So we don't know if it's exploitable in that scenario as well. But in its default version, it's vulnerable in the default configuration, and also pre-authentication, which is quite bad. So they fixed this in version 2.11, which is the latest one, by updating their dependency. So if you have a Harbor instance, you definitely should update to the latest version. And I'm going to try to demo the Harbor exploit now. I'm going to try to do it live. I also have a backup video. But let's see. So first, I will try to log in as the attacker to show that there should be no attacker user. As you can see, the login doesn't work. So now if we start the exploit, and I hope this works over the unstable internet, we have to wait a bit. So there we see the query that the exploit is sending. This is an insert query that will insert the attacker user into the database. So then we could log in. And as we can see, it's sending a lot of bytes, four gigabytes. So it takes some time. And if it works successfully, then we should be able to log in and have administrative privileges in the Harbor application, so that we then could send all mess with the containers in there. So we saw an error, which is expected here. So if I now try to log in again, we should log in successfully, I hope. Okay, it doesn't seem to work. I have to switch to the backup video. And there on the left, now we try to log in again. And there we can see we can now log in and have admin privileges. All right, that was Postgres. Now also, let's look at MongoDB to show that it's not a Postgres and Go-only problem. So to look back, this is what a message in MongoDB looks like. We have a four-byte length field. This time, it's little-endian. Then we have two metadata fields that are not relevant here. And then we have the opcode, which is like the message type. And then the value is a complex binary structure that's called bson, which I think stands for binary JSON. And it's some nested data that's serialized to TLV sections. So they also have lengths again. And to directly look at some code, it's a little bit more, but I'm going to walk you through it. We first have a line here that takes the content bytes. So it takes the query and puts it into this bson representation. Then it computes the total length of the message by adding the header length and so on. And this is saved as a type usize variable. Again, on most modern systems, this is a 64-bit integer. And then again, this is truncated explicitly to an int32, because that's what fits into the field. So the developer had to cut it down here. But of course, this is the same issue as before. If the length was larger than what can be expressed here, we have our truncation and things go wrong the exact same way as it did for Postgres. So for crafting a payload for MongoDB, it's a little bit more involved, because we have to avoid bad bytes. The payload must be valid UTF-8, because the strings are serialized as UTF-8 to the wire. So we cannot create any bytes that are invalid UTF-8. But the problem is, the message type that we need to write in order to craft the right injected message is 0xDD07. And that's always invalid UTF-8. So how can we do that? And also, size fields inside the message could become some byte values that would also be invalid UTF-8. So we have to be careful there as well. And the solution was to just use other metadata of the message we're injecting into to create these byte values. And I have an example for that. So this is a normal MongoDB query. It just queries for a movie based on a few attributes. And this is serialized to the following BSON document. In the beginning, we have in blue, the length of the whole document. Then in red, we have a type identifier that says the next key value pair has a string value. Then in yellow, we have the key, which in this case is title with a trailing null byte. Then in blue again, we have the length of the following string. And then in green, we have the actual string with a terminating null byte. Then we have the next key value pairs and so on. And at the end, we have another null byte that shows the end of the document. So if we want to have the hex sequence 0xDD07 anywhere in here, we cannot use the yellow and green parts because they have to be a valid UTF-8. But what we can do is, for example, we can take the length of a string and just make the string the length that will, when serialized to bytes, will be the exact byte sequence we need. So here we need to subtract one because there's a appended null byte, but then we have the DD07 there. And with this trick, now we can craft the entire injected message. I cannot go into all of this here because we don't have time, but this is the trick you need to be able to do it. So we also looked at libraries here and we found the official Rust MongoDB client library to be vulnerable and exploitable. We sent out our advisory also in February and they fixed in March. So if you use this, especially if you use it in production, which I doubt because it's Rust, but then you should update to 2.8.2. Okay, let's now take a step back. We've seen all the cool bugs and the exploitation, but is this actually applicable to the real world? We've seen the demo, but maybe this was just a lucky punch. So let's talk about constraints and especially about the elephant in the room, which here weighs four gigabytes. Because a lot of you probably are thinking, well, can we actually send four gigabytes into all the applications? Aren't apps limiting input sizes? And you would be right. There's a lot of common protections like default body size limits of your favorite web framework, or maybe JSON and form decode maximum sizes, or you have your reverse proxy that's limiting request size and so on. And I also encountered this and thought about some potential bypasses here. So the first idea is that sometimes endpoints are just unprotected. So maybe your framework doesn't have a default size limit. And also sometimes the developers explicitly disable the limits. This was the case with Harbor, for example, they have an NGINX reverse proxy, which usually has a one megabyte request limit, but they explicitly disabled it, I guess, because they need to receive big docker images. So they need more request size. But this also meant that the whole API is now not limited anymore. And the goal framework that's used under the hood of the server did not limit this, so we could send our big payload. The next trick would be to use compression. This, on the one hand, allows you to send your attacker payload much quicker because you can compress it down and don't have to send four gigabytes over the internet. And also there can be logic bugs where maybe your reverse proxy or your framework first checks the request size, but does a doc decompression after that. So the check is essentially useless because your compressed data will inflate a lot and you can craft a big payload that after decompression still causes the overflow. So for NGINX, for example, this works because NGINX does not look at the body. It doesn't try to decompress it. It just looks at the raw size of the request. So if your backend does decompression, then you could bypass this. And also, for example, the JavaScript Fastify framework does both checks the body size and also does the decompression, but it does it in the wrong order. So you can bypass the limits. Then you might also have WebSockets support on the server of your target. This is cool because WebSockets also, in theory, supports compression. It's not always enabled, but it can help you. But even without that, a single WebSocket request can be super large. I think it's a 64-bit integer, the size field. So you can definitely send four gigabyte messages with that. And maybe the middlewares and filters that are present in your framework don't apply to each individual WebSocket message. So maybe there's no limit there. Then you could also use alternate body types, for example, a multipart form instead of a JSON body. And maybe the limits are different there, or the developer forgot to configure a limit. So this could be another bypass. And then this one, which I like the most, is a little bit more creative and open, which I call server-side creation, which is you just find other means of bringing a big string to the server without sending it in your requests. And one example is SSRF, where you point some functionality of the server to an attacker server, which then returns a very large response. And if this one gets saved into the database or used in a query, it will also cause the overflow. And this, for example, worked in GOGS, where you have a web hooks feature. But beyond the SSRF, you might also have templating or translation that you could use to inflate a string. And this all depends on the business logic and the features of the server. So that's where you can get creative to find bypasses. All right, now that we've seen how we might bypass limitations of frameworks and servers, we also need to look at languages. We've already seen some differences at the vulnerable libraries. So we need to see how well languages handle large payloads, like how big can strings and buffers be. And also, what about integer overflows? Does every language have silent integer overflows, or maybe some languages are safe? So for the large payloads, we can see that Go, Python, and Rust, all of the languages we looked at, have large enough string and buffer sizes that you can send four gigabytes and they can handle it. For Java, you're out of luck. And we also seen this with unexploitable libraries in Java. And that's because strings and buffers here are backed by arrays, which have integer indexes. So you cannot index more than, I think, 2 to the power of 31 here. For C Sharp, the string size is not big enough, but the buffer size is. So if you have multiple strings that you control, then you can still end up with a buffer that becomes bigger than four gigabytes. And for JavaScript, it totally depends on the implementation. For Node, strings are much smaller compared to the other languages, but buffers can be large enough. For integer overflows, we can see that for addition overflows, which just means you add two integers, we can see that in Go, Java, and C Sharp, a silent integer overflow happens, so it will just wrap around. For JavaScript, there will be no overflow. Things will just get more inaccurate because it's JavaScript and they use floats under the hood. And in Python, you have arbitrarily sized integers, so you cannot overflow that. And in Rust, it depends on how you build your project. If you build it in debug mode, the compiler will emit a check that checks for overflows, but in a release build, it will not do that. And for serialization overflows, which basically is the case when you have a standard function in your language that allows you to write an integer to a fixed size field, does this function check for overflows or not? And in all of the type-safe languages, this does not apply because the types that the function can receive cannot overflow the size field or the field that it gets serialized to. But this just means that the developers now have to do the check before casting to this type, and we've seen that this leads to bugs in our Go and Rust examples. In JavaScript, it's again implementation-dependent. I think in Node.js, it does the check, but in Bun or Deno, it might not do it. And in Python, the struct.pack function actually does a check. If you pass a too-large integer, it will throw an error if you try to serialize it to a too-small field. So, to summarize the real-world applicability, we can say that in a lot of times, we can send large payloads past the limits for silent integer overflows or truncations. We've also seen that in many languages, it works, or the developers do the mistake for the language. And we've also seen that you can definitely exploit some real-world applications with this. All right. Now, let's look at what is there more to do in this kind of research for binary protocol smuggling. But first, I have to give a small disclaimer here. Please don't go out and send 4 gigabytes to every API endpoint in your bug bounty scope, because you will crash systems, you will get blocked, and you will ruin a DevOps engineer's day because they have to look at the monitoring alert. So, don't do it, please. But, speaking of this, it would be cool to actually have a non-invasive detection mechanism. In white-box tests, it's okay. You can make your local testing environment and just hammer it with gigabytes of data. But, of course, in black-box tests, that doesn't work. So, if we could find a methodology to find, for example, a fingerprint of a database client library being used, and we would know that this library is vulnerable to these kind of texts, then we could either directly report it or only do the large payload then. And if this would be a tool, it would be great to aid you in pen tests and so on. And, of course, it would be awesome to research a lot of more stuff, more protocols, like there's more databases than the stuff we looked at today, and there's all of the other systems, caches, message queues, and so on, that the application has to talk to. We can also try to find more desync techniques. For example, look into protocols that use delimiters and not size fields. And we can also find more large payload message, which is ways to bypass the filters of a framework, for example, to bypass the request size limits. Or maybe we can find generic ways of making a server craft a very large string. Maybe there's some way to do this. And, of course, all of the stuff we looked at today had 4-byte length fields. But what about 2-byte length fields? This would be much easier to exploit. Sending 65 kilobytes instead of 4 gigabytes is much easier. You don't have the hassle with all the limitations. And I already started to look into this a little bit, so stay tuned for more to come in the future, but feel free to also go out and check this yourself. So, let's wrap things up. I have a few takeaways. And the first one is that I think integer overflows are still relevant in memory-safe languages. Of course, in C, if you have an integer overflow, it's easy to get some memory corruption with it, so that's done. But in memory-safe languages, the worst case that can happen is an array out of bounds or whatever. But with these data attacks in the binary protocols that we've seen today, now we have a new way of exploiting these. And I think developers kind of forgot about integer overflows and maybe researchers as well, at least in the memory-safe languages. Then we've also seen that it's entirely feasible to send large amounts of data, even with protections, because there's many ways how you can bypass these protections. And finally, to get back to the title, SQL injection isn't dead. Of course, it was never dead, at least not in the real world. We've seen a lot of real-world applications with SQL injections. But on paper, you could say developers have the right tools to write secure SQL-based applications. They have parameterized queries, they have query builders, they have ORMs. So if they use all of this, and the application is safe, so if you can't hack it, you just have to go a level deeper. Thank you.