To help you see what's changed in the code, we first perform a diff(1) of this (deliberately) bad driver code with our previous (good) version, yielding the differences, of course (in the following snippet, we curtail the output to only what's most relevant):
// in ch1/bad_miscdrv
$ diff -u ../miscdrv_rdwr/miscdrv_rdwr.c bad_miscdrv.c
[ ... ]
+#include <linux/cred.h> // access to struct cred
#include "../../convenient.h"
[ ... ]
static ssize_t read_miscdrv_rdwr(struct file *filp, char __user *ubuf,
[ ... ]
+ void *kbuf = NULL;
+ void *new_dest = NULL;
[ ... ]
+#define READ_BUG
+//#undef READ_BUG
+#ifdef READ_BUG
[ ... ]
+ new_dest = ubuf+(512*1024);
+#else
+ new_dest = ubuf;
+#endif
[ ... ]
+ if (copy_to_user(new_dest, ctx->oursecret, secret_len)) {
[ ... ]
So, it should be quite clear: in our 'bad' driver's read method, if the READ_BUG macro is defined, we alter the user space destination pointer to point to an illegal location (512 KB beyond the location we should actually copy the data to!). This demonstrates the point here: we can do arbitrary stuff like this because we are running with kernel privileges. That it will cause issues and bugs is a separate matter.
Let's try it: first, do ensure that you've built and loaded the bad_miscdrv kernel module (you can use our lkm convenience script to do so). Our trial run, issuing a read(2) system call via our ch1/bad_miscdrv/rdwr_test_hackit user-mode app, results in failure (see the following screenshot):
Ah, this is interesting; our test application's (rdwr_test_hackit) read(2) system call does indeed fail, with the perror(3) routine indicating the cause of failure as Bad address. But why? Why didn't the driver, running with kernel privileges, actually write to the destination address (here, 0x5597245d46b0 , the wrong one; as we know, it's attempting to write 512 KB ahead of the correct destination address. We deliberately wrote the driver's read method code to do so).
This is because kernel ensures that the copy_[from|to]_user() routines will (ideally) fail when attempting to read or write illegal addresses! Internally, several checks are done: access_ok() is a simple one merely ensuring that I/O is performed within the expected segment (user or kernel). Modern Linux kernels have superior checking; besides the simple access_ok() check, the kernel then wades through – if enabled – the KASAN (Kernel Address Sanitizer, a compiler instrumentation feature; KASAN is indeed very useful, a must-do during development and test!), checks on object sizes (including overflow checks), and only then does it invoke the worker routine that performs the actual copy, raw_copy_[from|to]_user().
Okay, that's good; now, let's move on to the more interesting case, the buggy write, which we shall arrange (in a contrived manner though) to make into an attack! Read on...