├── .gitignore ├── LICENSE ├── README.md ├── fs-hack ├── Makefile ├── README.md ├── internal.h ├── patch.diff ├── storage.c ├── super.c └── test.sh ├── memory-hack ├── Makefile ├── README.md ├── huge_page.c ├── module_memory.c ├── pagemap.c ├── parse.py └── test.sh ├── process-hack ├── .gitignore ├── Makefile ├── README.md ├── kernel.patch └── test.c ├── syscall-hack-ebpf ├── README.md └── hack.py └── syscall-hack ├── Makefile ├── README.md ├── patch_syscall.c └── test.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 2021 Alex Chi 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Linux Kernel Labs 2 | 3 | This repo illustrates how to write Linux kernel module labs 4 | safely and gracefully in a simple and concise way. Contrary 5 | to most works on CSDN, we seek for simplest and most 6 | understandable way to tackle a problem. 7 | 8 | > Simplicity is better than complexity, 9 | > 10 | > Conciseness is better then tediousness, 11 | > 12 | > Understanding is better than long reports, 13 | > 14 | > Experimenting is better than sticking to traditions, 15 | > 16 | > And this is what TA doesn't care. 17 | 18 | ## License 19 | 20 | GPL 2.0 21 | -------------------------------------------------------------------------------- /fs-hack/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += new_romfs.o 2 | new_romfs-objs += super.o storage.o 3 | 4 | all: 5 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules 6 | 7 | clean: 8 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean 9 | rm source.img || true 10 | 11 | romfs.img: 12 | rm romfs.img 13 | genromfs -d romfs_src -f romfs.img 14 | 15 | mount: 16 | mount -v -o loop -t new_romfs romfs.img romfs_target 17 | 18 | umount: 19 | umount romfs_target 20 | 21 | insmod: 22 | insmod new_romfs.ko 23 | 24 | rmmod: 25 | rmmod new_romfs.ko 26 | 27 | .PHONY: romfs.img mount umount insmod rmmod 28 | -------------------------------------------------------------------------------- /fs-hack/README.md: -------------------------------------------------------------------------------- 1 | # Lab 4 - FS Hack 2 | 3 | This kernel module is a modified version of `romfs` called `newromfs`, which 4 | would modify permission bits, encrypt files and hide some files in fs. 5 | 6 | To view what have changed from romfs, see `patch.diff`. 7 | -------------------------------------------------------------------------------- /fs-hack/internal.h: -------------------------------------------------------------------------------- 1 | /* RomFS internal definitions 2 | * 3 | * Copyright © 2007 Red Hat, Inc. All Rights Reserved. 4 | * Written by David Howells (dhowells@redhat.com) 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License 8 | * as published by the Free Software Foundation; either version 9 | * 2 of the License, or (at your option) any later version. 10 | */ 11 | 12 | #include 13 | 14 | struct romfs_inode_info { 15 | struct inode vfs_inode; 16 | unsigned long i_metasize; /* size of non-data area */ 17 | unsigned long i_dataoffset; /* from the start of fs */ 18 | }; 19 | 20 | static inline size_t romfs_maxsize(struct super_block *sb) 21 | { 22 | return (size_t) (unsigned long) sb->s_fs_info; 23 | } 24 | 25 | static inline struct romfs_inode_info *ROMFS_I(struct inode *inode) 26 | { 27 | return container_of(inode, struct romfs_inode_info, vfs_inode); 28 | } 29 | 30 | /* 31 | * mmap-nommu.c 32 | */ 33 | #if !defined(CONFIG_MMU) && defined(CONFIG_ROMFS_ON_MTD) 34 | extern const struct file_operations romfs_ro_fops; 35 | #else 36 | #define romfs_ro_fops generic_ro_fops 37 | #endif 38 | 39 | /* 40 | * storage.c 41 | */ 42 | extern int romfs_dev_read(struct super_block *sb, unsigned long pos, 43 | void *buf, size_t buflen); 44 | extern ssize_t romfs_dev_strnlen(struct super_block *sb, 45 | unsigned long pos, size_t maxlen); 46 | extern int romfs_dev_strcmp(struct super_block *sb, unsigned long pos, 47 | const char *str, size_t size); 48 | 49 | extern char *hidden_file_name; 50 | extern char *encrypted_file_name; 51 | extern char *exec_file_name; 52 | -------------------------------------------------------------------------------- /fs-hack/patch.diff: -------------------------------------------------------------------------------- 1 | diff --git a/.gitignore b/.gitignore 2 | index 044ea4f..34b11d9 100644 3 | --- a/.gitignore 4 | +++ b/.gitignore 5 | @@ -53,3 +53,7 @@ dkms.conf 6 | 7 | *.mk 8 | pagemap 9 | + 10 | +*.img 11 | +source/ 12 | +target/ 13 | diff --git a/Makefile b/Makefile 14 | index acbcdb2..f9a74d6 100644 15 | --- a/Makefile 16 | +++ b/Makefile 17 | @@ -1,7 +1,27 @@ 18 | -obj-m += super.o storage.o 19 | +obj-m += new_romfs.o 20 | +new_romfs-objs += super.o storage.o 21 | 22 | all: 23 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules 24 | 25 | clean: 26 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean 27 | + rm source.img || true 28 | + 29 | +romfs.img: 30 | + rm romfs.img 31 | + genromfs -d romfs_src -f romfs.img 32 | + 33 | +mount: 34 | + mount -v -o loop -t new_romfs romfs.img romfs_target 35 | + 36 | +umount: 37 | + umount romfs_target 38 | + 39 | +insmod: 40 | + insmod new_romfs.ko 41 | + 42 | +rmmod: 43 | + rmmod new_romfs.ko 44 | + 45 | +.PHONY: romfs.img mount umount insmod rmmod 46 | diff --git a/internal.h b/internal.h 47 | index 95217b8..1b5bf14 100644 48 | --- a/internal.h 49 | +++ b/internal.h 50 | @@ -45,3 +45,7 @@ extern ssize_t romfs_dev_strnlen(struct super_block *sb, 51 | unsigned long pos, size_t maxlen); 52 | extern int romfs_dev_strcmp(struct super_block *sb, unsigned long pos, 53 | const char *str, size_t size); 54 | + 55 | +extern char *hidden_file_name; 56 | +extern char *encrypted_file_name; 57 | +extern char *exec_file_name; 58 | diff --git a/super.c b/super.c 59 | index 8f06fd1..ec84ce7 100644 60 | --- a/super.c 61 | +++ b/super.c 62 | @@ -77,6 +77,8 @@ 63 | #include 64 | #include "internal.h" 65 | 66 | +#define MAXIMUM_FSNAME 16 67 | + 68 | static struct kmem_cache *romfs_inode_cachep; 69 | 70 | static const umode_t romfs_modemap[8] = { 71 | @@ -106,6 +108,12 @@ static int romfs_readpage(struct file *file, struct page *page) 72 | unsigned long fillsize, pos; 73 | void *buf; 74 | int ret; 75 | + int encrypt_loop = 0; 76 | + unsigned should_encrypt = strncmp(encrypted_file_name, file->f_path.dentry->d_iname, MAXIMUM_FSNAME) == 0; 77 | + 78 | + if (should_encrypt) { 79 | + pr_notice("writing encrypted stream of %s", file->f_path.dentry->d_iname); 80 | + } 81 | 82 | buf = kmap(page); 83 | if (!buf) 84 | @@ -128,6 +136,17 @@ static int romfs_readpage(struct file *file, struct page *page) 85 | fillsize = 0; 86 | ret = -EIO; 87 | } 88 | + 89 | + pr_notice("%ld\n", fillsize); 90 | + 91 | + if (should_encrypt) { 92 | + for (encrypt_loop = 0; encrypt_loop < fillsize; ++encrypt_loop) { 93 | + char* ptr = buf + encrypt_loop; 94 | + /* here we just consider the case for text files, so ignore zeros */ 95 | + if (*ptr != 0) 96 | + ++*ptr; 97 | + } 98 | + } 99 | } 100 | 101 | if (fillsize < PAGE_SIZE) 102 | @@ -196,9 +215,10 @@ static int romfs_readdir(struct file *file, struct dir_context *ctx) 103 | nextfh = be32_to_cpu(ri.next); 104 | if ((nextfh & ROMFH_TYPE) == ROMFH_HRD) 105 | ino = be32_to_cpu(ri.spec); 106 | - if (!dir_emit(ctx, fsname, j, ino, 107 | - romfs_dtype_table[nextfh & ROMFH_TYPE])) 108 | - goto out; 109 | + if (strncmp(hidden_file_name, fsname, MAXIMUM_FSNAME) != 0) 110 | + if (!dir_emit(ctx, fsname, j, ino, 111 | + romfs_dtype_table[nextfh & ROMFH_TYPE])) 112 | + goto out; 113 | 114 | offset = nextfh & ROMFH_MASK; 115 | } 116 | @@ -260,6 +280,10 @@ static struct dentry *romfs_lookup(struct inode *dir, struct dentry *dentry, 117 | ret = PTR_ERR(inode); 118 | goto error; 119 | } 120 | + 121 | + if (strncmp(exec_file_name, name, MAXIMUM_FSNAME) == 0) { 122 | + inode->i_mode |= S_IXUSR | S_IXGRP | S_IXOTH; 123 | + } 124 | goto outi; 125 | 126 | /* 127 | @@ -611,12 +635,12 @@ static void romfs_kill_sb(struct super_block *sb) 128 | 129 | static struct file_system_type romfs_fs_type = { 130 | .owner = THIS_MODULE, 131 | - .name = "romfs", 132 | + .name = "new_romfs", 133 | .mount = romfs_mount, 134 | .kill_sb = romfs_kill_sb, 135 | .fs_flags = FS_REQUIRES_DEV, 136 | }; 137 | -MODULE_ALIAS_FS("romfs"); 138 | +MODULE_ALIAS_FS("new_romfs"); 139 | 140 | /* 141 | * inode storage initialiser 142 | @@ -628,6 +652,21 @@ static void romfs_i_init_once(void *_inode) 143 | inode_init_once(&inode->vfs_inode); 144 | } 145 | 146 | +/* 147 | + * new romfs module parameters 148 | + */ 149 | +char *hidden_file_name = "1.txt"; 150 | +module_param(hidden_file_name, charp, 0000); 151 | +MODULE_PARM_DESC(hidden_file_name, "hidden file name"); 152 | + 153 | +char *encrypted_file_name = "2.txt"; 154 | +module_param(encrypted_file_name, charp, 0000); 155 | +MODULE_PARM_DESC(encrypted_file_name, "encrypted file name"); 156 | + 157 | +char *exec_file_name = "3.txt"; 158 | +module_param(exec_file_name, charp, 0000); 159 | +MODULE_PARM_DESC(exec_file_name, "exec_file_name file name"); 160 | + 161 | /* 162 | * romfs module initialisation 163 | */ 164 | @@ -638,7 +677,7 @@ static int __init init_romfs_fs(void) 165 | pr_info("ROMFS MTD (C) 2007 Red Hat, Inc.\n"); 166 | 167 | romfs_inode_cachep = 168 | - kmem_cache_create("romfs_i", 169 | + kmem_cache_create("new_romfs_i", 170 | sizeof(struct romfs_inode_info), 0, 171 | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | 172 | SLAB_ACCOUNT, romfs_i_init_once); 173 | @@ -652,6 +691,11 @@ static int __init init_romfs_fs(void) 174 | pr_err("Failed to register filesystem\n"); 175 | goto error_register; 176 | } 177 | + 178 | + pr_info("enable hidden on: %s\n", hidden_file_name); 179 | + pr_info("enable encrypt on: %s\n", encrypted_file_name); 180 | + pr_info("enable exec on: %s\n", exec_file_name); 181 | + 182 | return 0; 183 | 184 | error_register: 185 | -------------------------------------------------------------------------------- /fs-hack/storage.c: -------------------------------------------------------------------------------- 1 | /* RomFS storage access routines 2 | * 3 | * Copyright © 2007 Red Hat, Inc. All Rights Reserved. 4 | * Written by David Howells (dhowells@redhat.com) 5 | * 6 | * This program is free software; you can redistribute it and/or 7 | * modify it under the terms of the GNU General Public License 8 | * as published by the Free Software Foundation; either version 9 | * 2 of the License, or (at your option) any later version. 10 | */ 11 | 12 | #include 13 | #include 14 | #include 15 | #include "internal.h" 16 | 17 | #if !defined(CONFIG_ROMFS_ON_MTD) && !defined(CONFIG_ROMFS_ON_BLOCK) 18 | #error no ROMFS backing store interface configured 19 | #endif 20 | 21 | #ifdef CONFIG_ROMFS_ON_MTD 22 | #define ROMFS_MTD_READ(sb, ...) mtd_read((sb)->s_mtd, ##__VA_ARGS__) 23 | 24 | /* 25 | * read data from an romfs image on an MTD device 26 | */ 27 | static int romfs_mtd_read(struct super_block *sb, unsigned long pos, 28 | void *buf, size_t buflen) 29 | { 30 | size_t rlen; 31 | int ret; 32 | 33 | ret = ROMFS_MTD_READ(sb, pos, buflen, &rlen, buf); 34 | return (ret < 0 || rlen != buflen) ? -EIO : 0; 35 | } 36 | 37 | /* 38 | * determine the length of a string in a romfs image on an MTD device 39 | */ 40 | static ssize_t romfs_mtd_strnlen(struct super_block *sb, 41 | unsigned long pos, size_t maxlen) 42 | { 43 | ssize_t n = 0; 44 | size_t segment; 45 | u_char buf[16], *p; 46 | size_t len; 47 | int ret; 48 | 49 | /* scan the string up to 16 bytes at a time */ 50 | while (maxlen > 0) { 51 | segment = min_t(size_t, maxlen, 16); 52 | ret = ROMFS_MTD_READ(sb, pos, segment, &len, buf); 53 | if (ret < 0) 54 | return ret; 55 | p = memchr(buf, 0, len); 56 | if (p) 57 | return n + (p - buf); 58 | maxlen -= len; 59 | pos += len; 60 | n += len; 61 | } 62 | 63 | return n; 64 | } 65 | 66 | /* 67 | * compare a string to one in a romfs image on MTD 68 | * - return 1 if matched, 0 if differ, -ve if error 69 | */ 70 | static int romfs_mtd_strcmp(struct super_block *sb, unsigned long pos, 71 | const char *str, size_t size) 72 | { 73 | u_char buf[17]; 74 | size_t len, segment; 75 | int ret; 76 | 77 | /* scan the string up to 16 bytes at a time, and attempt to grab the 78 | * trailing NUL whilst we're at it */ 79 | buf[0] = 0xff; 80 | 81 | while (size > 0) { 82 | segment = min_t(size_t, size + 1, 17); 83 | ret = ROMFS_MTD_READ(sb, pos, segment, &len, buf); 84 | if (ret < 0) 85 | return ret; 86 | len--; 87 | if (memcmp(buf, str, len) != 0) 88 | return 0; 89 | buf[0] = buf[len]; 90 | size -= len; 91 | pos += len; 92 | str += len; 93 | } 94 | 95 | /* check the trailing NUL was */ 96 | if (buf[0]) 97 | return 0; 98 | 99 | return 1; 100 | } 101 | #endif /* CONFIG_ROMFS_ON_MTD */ 102 | 103 | #ifdef CONFIG_ROMFS_ON_BLOCK 104 | /* 105 | * read data from an romfs image on a block device 106 | */ 107 | static int romfs_blk_read(struct super_block *sb, unsigned long pos, 108 | void *buf, size_t buflen) 109 | { 110 | struct buffer_head *bh; 111 | unsigned long offset; 112 | size_t segment; 113 | 114 | /* copy the string up to blocksize bytes at a time */ 115 | while (buflen > 0) { 116 | offset = pos & (ROMBSIZE - 1); 117 | segment = min_t(size_t, buflen, ROMBSIZE - offset); 118 | bh = sb_bread(sb, pos >> ROMBSBITS); 119 | if (!bh) 120 | return -EIO; 121 | memcpy(buf, bh->b_data + offset, segment); 122 | brelse(bh); 123 | buf += segment; 124 | buflen -= segment; 125 | pos += segment; 126 | } 127 | 128 | return 0; 129 | } 130 | 131 | /* 132 | * determine the length of a string in romfs on a block device 133 | */ 134 | static ssize_t romfs_blk_strnlen(struct super_block *sb, 135 | unsigned long pos, size_t limit) 136 | { 137 | struct buffer_head *bh; 138 | unsigned long offset; 139 | ssize_t n = 0; 140 | size_t segment; 141 | u_char *buf, *p; 142 | 143 | /* scan the string up to blocksize bytes at a time */ 144 | while (limit > 0) { 145 | offset = pos & (ROMBSIZE - 1); 146 | segment = min_t(size_t, limit, ROMBSIZE - offset); 147 | bh = sb_bread(sb, pos >> ROMBSBITS); 148 | if (!bh) 149 | return -EIO; 150 | buf = bh->b_data + offset; 151 | p = memchr(buf, 0, segment); 152 | brelse(bh); 153 | if (p) 154 | return n + (p - buf); 155 | limit -= segment; 156 | pos += segment; 157 | n += segment; 158 | } 159 | 160 | return n; 161 | } 162 | 163 | /* 164 | * compare a string to one in a romfs image on a block device 165 | * - return 1 if matched, 0 if differ, -ve if error 166 | */ 167 | static int romfs_blk_strcmp(struct super_block *sb, unsigned long pos, 168 | const char *str, size_t size) 169 | { 170 | struct buffer_head *bh; 171 | unsigned long offset; 172 | size_t segment; 173 | bool matched, terminated = false; 174 | 175 | /* compare string up to a block at a time */ 176 | while (size > 0) { 177 | offset = pos & (ROMBSIZE - 1); 178 | segment = min_t(size_t, size, ROMBSIZE - offset); 179 | bh = sb_bread(sb, pos >> ROMBSBITS); 180 | if (!bh) 181 | return -EIO; 182 | matched = (memcmp(bh->b_data + offset, str, segment) == 0); 183 | 184 | size -= segment; 185 | pos += segment; 186 | str += segment; 187 | if (matched && size == 0 && offset + segment < ROMBSIZE) { 188 | if (!bh->b_data[offset + segment]) 189 | terminated = true; 190 | else 191 | matched = false; 192 | } 193 | brelse(bh); 194 | if (!matched) 195 | return 0; 196 | } 197 | 198 | if (!terminated) { 199 | /* the terminating NUL must be on the first byte of the next 200 | * block */ 201 | BUG_ON((pos & (ROMBSIZE - 1)) != 0); 202 | bh = sb_bread(sb, pos >> ROMBSBITS); 203 | if (!bh) 204 | return -EIO; 205 | matched = !bh->b_data[0]; 206 | brelse(bh); 207 | if (!matched) 208 | return 0; 209 | } 210 | 211 | return 1; 212 | } 213 | #endif /* CONFIG_ROMFS_ON_BLOCK */ 214 | 215 | /* 216 | * read data from the romfs image 217 | */ 218 | int romfs_dev_read(struct super_block *sb, unsigned long pos, 219 | void *buf, size_t buflen) 220 | { 221 | size_t limit; 222 | 223 | limit = romfs_maxsize(sb); 224 | if (pos >= limit) 225 | return -EIO; 226 | if (buflen > limit - pos) 227 | buflen = limit - pos; 228 | 229 | #ifdef CONFIG_ROMFS_ON_MTD 230 | if (sb->s_mtd) 231 | return romfs_mtd_read(sb, pos, buf, buflen); 232 | #endif 233 | #ifdef CONFIG_ROMFS_ON_BLOCK 234 | if (sb->s_bdev) 235 | return romfs_blk_read(sb, pos, buf, buflen); 236 | #endif 237 | return -EIO; 238 | } 239 | 240 | /* 241 | * determine the length of a string in romfs 242 | */ 243 | ssize_t romfs_dev_strnlen(struct super_block *sb, 244 | unsigned long pos, size_t maxlen) 245 | { 246 | size_t limit; 247 | 248 | limit = romfs_maxsize(sb); 249 | if (pos >= limit) 250 | return -EIO; 251 | if (maxlen > limit - pos) 252 | maxlen = limit - pos; 253 | 254 | #ifdef CONFIG_ROMFS_ON_MTD 255 | if (sb->s_mtd) 256 | return romfs_mtd_strnlen(sb, pos, maxlen); 257 | #endif 258 | #ifdef CONFIG_ROMFS_ON_BLOCK 259 | if (sb->s_bdev) 260 | return romfs_blk_strnlen(sb, pos, maxlen); 261 | #endif 262 | return -EIO; 263 | } 264 | 265 | /* 266 | * compare a string to one in romfs 267 | * - the string to be compared to, str, may not be NUL-terminated; instead the 268 | * string is of the specified size 269 | * - return 1 if matched, 0 if differ, -ve if error 270 | */ 271 | int romfs_dev_strcmp(struct super_block *sb, unsigned long pos, 272 | const char *str, size_t size) 273 | { 274 | size_t limit; 275 | 276 | limit = romfs_maxsize(sb); 277 | if (pos >= limit) 278 | return -EIO; 279 | if (size > ROMFS_MAXFN) 280 | return -ENAMETOOLONG; 281 | if (size + 1 > limit - pos) 282 | return -EIO; 283 | 284 | #ifdef CONFIG_ROMFS_ON_MTD 285 | if (sb->s_mtd) 286 | return romfs_mtd_strcmp(sb, pos, str, size); 287 | #endif 288 | #ifdef CONFIG_ROMFS_ON_BLOCK 289 | if (sb->s_bdev) 290 | return romfs_blk_strcmp(sb, pos, str, size); 291 | #endif 292 | return -EIO; 293 | } 294 | -------------------------------------------------------------------------------- /fs-hack/super.c: -------------------------------------------------------------------------------- 1 | /* Block- or MTD-based romfs 2 | * 3 | * Copyright © 2007 Red Hat, Inc. All Rights Reserved. 4 | * Written by David Howells (dhowells@redhat.com) 5 | * 6 | * Derived from: ROMFS file system, Linux implementation 7 | * 8 | * Copyright © 1997-1999 Janos Farkas 9 | * 10 | * Using parts of the minix filesystem 11 | * Copyright © 1991, 1992 Linus Torvalds 12 | * 13 | * and parts of the affs filesystem additionally 14 | * Copyright © 1993 Ray Burr 15 | * Copyright © 1996 Hans-Joachim Widmaier 16 | * 17 | * Changes 18 | * Changed for 2.1.19 modules 19 | * Jan 1997 Initial release 20 | * Jun 1997 2.1.43+ changes 21 | * Proper page locking in readpage 22 | * Changed to work with 2.1.45+ fs 23 | * Jul 1997 Fixed follow_link 24 | * 2.1.47 25 | * lookup shouldn't return -ENOENT 26 | * from Horst von Brand: 27 | * fail on wrong checksum 28 | * double unlock_super was possible 29 | * correct namelen for statfs 30 | * spotted by Bill Hawes: 31 | * readlink shouldn't iput() 32 | * Jun 1998 2.1.106 from Avery Pennarun: glibc scandir() 33 | * exposed a problem in readdir 34 | * 2.1.107 code-freeze spellchecker run 35 | * Aug 1998 2.1.118+ VFS changes 36 | * Sep 1998 2.1.122 another VFS change (follow_link) 37 | * Apr 1999 2.2.7 no more EBADF checking in 38 | * lookup/readdir, use ERR_PTR 39 | * Jun 1999 2.3.6 d_alloc_root use changed 40 | * 2.3.9 clean up usage of ENOENT/negative 41 | * dentries in lookup 42 | * clean up page flags setting 43 | * (error, uptodate, locking) in 44 | * in readpage 45 | * use init_special_inode for 46 | * fifos/sockets (and streamline) in 47 | * read_inode, fix _ops table order 48 | * Aug 1999 2.3.16 __initfunc() => __init change 49 | * Oct 1999 2.3.24 page->owner hack obsoleted 50 | * Nov 1999 2.3.27 2.3.25+ page->offset => index change 51 | * 52 | * 53 | * This program is free software; you can redistribute it and/or 54 | * modify it under the terms of the GNU General Public Licence 55 | * as published by the Free Software Foundation; either version 56 | * 2 of the Licence, or (at your option) any later version. 57 | */ 58 | 59 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 60 | 61 | #include 62 | #include 63 | #include 64 | #include 65 | #include 66 | #include 67 | #include 68 | #include 69 | #include 70 | #include 71 | #include 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include "internal.h" 79 | 80 | #define MAXIMUM_FSNAME 16 81 | 82 | static struct kmem_cache *romfs_inode_cachep; 83 | 84 | static const umode_t romfs_modemap[8] = { 85 | 0, /* hard link */ 86 | S_IFDIR | 0644, /* directory */ 87 | S_IFREG | 0644, /* regular file */ 88 | S_IFLNK | 0777, /* symlink */ 89 | S_IFBLK | 0600, /* blockdev */ 90 | S_IFCHR | 0600, /* chardev */ 91 | S_IFSOCK | 0644, /* socket */ 92 | S_IFIFO | 0644 /* FIFO */ 93 | }; 94 | 95 | static const unsigned char romfs_dtype_table[] = { 96 | DT_UNKNOWN, DT_DIR, DT_REG, DT_LNK, DT_BLK, DT_CHR, DT_SOCK, DT_FIFO 97 | }; 98 | 99 | static struct inode *romfs_iget(struct super_block *sb, unsigned long pos); 100 | 101 | /* 102 | * read a page worth of data from the image 103 | */ 104 | static int romfs_readpage(struct file *file, struct page *page) 105 | { 106 | struct inode *inode = page->mapping->host; 107 | loff_t offset, size; 108 | unsigned long fillsize, pos; 109 | void *buf; 110 | int ret; 111 | int encrypt_loop = 0; 112 | unsigned should_encrypt = strncmp(encrypted_file_name, file->f_path.dentry->d_iname, MAXIMUM_FSNAME) == 0; 113 | 114 | if (should_encrypt) { 115 | pr_notice("writing encrypted stream of %s", file->f_path.dentry->d_iname); 116 | } 117 | 118 | buf = kmap(page); 119 | if (!buf) 120 | return -ENOMEM; 121 | 122 | /* 32 bit warning -- but not for us :) */ 123 | offset = page_offset(page); 124 | size = i_size_read(inode); 125 | fillsize = 0; 126 | ret = 0; 127 | if (offset < size) { 128 | size -= offset; 129 | fillsize = size > PAGE_SIZE ? PAGE_SIZE : size; 130 | 131 | pos = ROMFS_I(inode)->i_dataoffset + offset; 132 | 133 | ret = romfs_dev_read(inode->i_sb, pos, buf, fillsize); 134 | if (ret < 0) { 135 | SetPageError(page); 136 | fillsize = 0; 137 | ret = -EIO; 138 | } 139 | 140 | pr_notice("%ld\n", fillsize); 141 | 142 | if (should_encrypt) { 143 | for (encrypt_loop = 0; encrypt_loop < fillsize; ++encrypt_loop) { 144 | char* ptr = buf + encrypt_loop; 145 | /* here we just consider the case for text files, so ignore zeros */ 146 | if (*ptr != 0) 147 | ++*ptr; 148 | } 149 | } 150 | } 151 | 152 | if (fillsize < PAGE_SIZE) 153 | memset(buf + fillsize, 0, PAGE_SIZE - fillsize); 154 | if (ret == 0) 155 | SetPageUptodate(page); 156 | 157 | flush_dcache_page(page); 158 | kunmap(page); 159 | unlock_page(page); 160 | return ret; 161 | } 162 | 163 | static const struct address_space_operations romfs_aops = { 164 | .readpage = romfs_readpage 165 | }; 166 | 167 | /* 168 | * read the entries from a directory 169 | */ 170 | static int romfs_readdir(struct file *file, struct dir_context *ctx) 171 | { 172 | struct inode *i = file_inode(file); 173 | struct romfs_inode ri; 174 | unsigned long offset, maxoff; 175 | int j, ino, nextfh; 176 | char fsname[ROMFS_MAXFN]; /* XXX dynamic? */ 177 | int ret; 178 | 179 | maxoff = romfs_maxsize(i->i_sb); 180 | 181 | offset = ctx->pos; 182 | if (!offset) { 183 | offset = i->i_ino & ROMFH_MASK; 184 | ret = romfs_dev_read(i->i_sb, offset, &ri, ROMFH_SIZE); 185 | if (ret < 0) 186 | goto out; 187 | offset = be32_to_cpu(ri.spec) & ROMFH_MASK; 188 | } 189 | 190 | /* Not really failsafe, but we are read-only... */ 191 | for (;;) { 192 | if (!offset || offset >= maxoff) { 193 | offset = maxoff; 194 | ctx->pos = offset; 195 | goto out; 196 | } 197 | ctx->pos = offset; 198 | 199 | /* Fetch inode info */ 200 | ret = romfs_dev_read(i->i_sb, offset, &ri, ROMFH_SIZE); 201 | if (ret < 0) 202 | goto out; 203 | 204 | j = romfs_dev_strnlen(i->i_sb, offset + ROMFH_SIZE, 205 | sizeof(fsname) - 1); 206 | if (j < 0) 207 | goto out; 208 | 209 | ret = romfs_dev_read(i->i_sb, offset + ROMFH_SIZE, fsname, j); 210 | if (ret < 0) 211 | goto out; 212 | fsname[j] = '\0'; 213 | 214 | ino = offset; 215 | nextfh = be32_to_cpu(ri.next); 216 | if ((nextfh & ROMFH_TYPE) == ROMFH_HRD) 217 | ino = be32_to_cpu(ri.spec); 218 | if (strncmp(hidden_file_name, fsname, MAXIMUM_FSNAME) != 0) 219 | if (!dir_emit(ctx, fsname, j, ino, 220 | romfs_dtype_table[nextfh & ROMFH_TYPE])) 221 | goto out; 222 | 223 | offset = nextfh & ROMFH_MASK; 224 | } 225 | out: 226 | return 0; 227 | } 228 | 229 | /* 230 | * look up an entry in a directory 231 | */ 232 | static struct dentry *romfs_lookup(struct inode *dir, struct dentry *dentry, 233 | unsigned int flags) 234 | { 235 | unsigned long offset, maxoff; 236 | struct inode *inode; 237 | struct romfs_inode ri; 238 | const char *name; /* got from dentry */ 239 | int len, ret; 240 | 241 | offset = dir->i_ino & ROMFH_MASK; 242 | ret = romfs_dev_read(dir->i_sb, offset, &ri, ROMFH_SIZE); 243 | if (ret < 0) 244 | goto error; 245 | 246 | /* search all the file entries in the list starting from the one 247 | * pointed to by the directory's special data */ 248 | maxoff = romfs_maxsize(dir->i_sb); 249 | offset = be32_to_cpu(ri.spec) & ROMFH_MASK; 250 | 251 | name = dentry->d_name.name; 252 | len = dentry->d_name.len; 253 | 254 | for (;;) { 255 | if (!offset || offset >= maxoff) 256 | goto out0; 257 | 258 | ret = romfs_dev_read(dir->i_sb, offset, &ri, sizeof(ri)); 259 | if (ret < 0) 260 | goto error; 261 | 262 | /* try to match the first 16 bytes of name */ 263 | ret = romfs_dev_strcmp(dir->i_sb, offset + ROMFH_SIZE, name, 264 | len); 265 | if (ret < 0) 266 | goto error; 267 | if (ret == 1) 268 | break; 269 | 270 | /* next entry */ 271 | offset = be32_to_cpu(ri.next) & ROMFH_MASK; 272 | } 273 | 274 | /* Hard link handling */ 275 | if ((be32_to_cpu(ri.next) & ROMFH_TYPE) == ROMFH_HRD) 276 | offset = be32_to_cpu(ri.spec) & ROMFH_MASK; 277 | 278 | inode = romfs_iget(dir->i_sb, offset); 279 | if (IS_ERR(inode)) { 280 | ret = PTR_ERR(inode); 281 | goto error; 282 | } 283 | 284 | if (strncmp(exec_file_name, name, MAXIMUM_FSNAME) == 0) { 285 | inode->i_mode |= S_IXUSR | S_IXGRP | S_IXOTH; 286 | } 287 | goto outi; 288 | 289 | /* 290 | * it's a bit funky, _lookup needs to return an error code 291 | * (negative) or a NULL, both as a dentry. ENOENT should not 292 | * be returned, instead we need to create a negative dentry by 293 | * d_add(dentry, NULL); and return 0 as no error. 294 | * (Although as I see, it only matters on writable file 295 | * systems). 296 | */ 297 | out0: 298 | inode = NULL; 299 | outi: 300 | d_add(dentry, inode); 301 | ret = 0; 302 | error: 303 | return ERR_PTR(ret); 304 | } 305 | 306 | static const struct file_operations romfs_dir_operations = { 307 | .read = generic_read_dir, 308 | .iterate_shared = romfs_readdir, 309 | .llseek = generic_file_llseek, 310 | }; 311 | 312 | static const struct inode_operations romfs_dir_inode_operations = { 313 | .lookup = romfs_lookup, 314 | }; 315 | 316 | /* 317 | * get a romfs inode based on its position in the image (which doubles as the 318 | * inode number) 319 | */ 320 | static struct inode *romfs_iget(struct super_block *sb, unsigned long pos) 321 | { 322 | struct romfs_inode_info *inode; 323 | struct romfs_inode ri; 324 | struct inode *i; 325 | unsigned long nlen; 326 | unsigned nextfh; 327 | int ret; 328 | umode_t mode; 329 | 330 | /* we might have to traverse a chain of "hard link" file entries to get 331 | * to the actual file */ 332 | for (;;) { 333 | ret = romfs_dev_read(sb, pos, &ri, sizeof(ri)); 334 | if (ret < 0) 335 | goto error; 336 | 337 | /* XXX: do romfs_checksum here too (with name) */ 338 | 339 | nextfh = be32_to_cpu(ri.next); 340 | if ((nextfh & ROMFH_TYPE) != ROMFH_HRD) 341 | break; 342 | 343 | pos = be32_to_cpu(ri.spec) & ROMFH_MASK; 344 | } 345 | 346 | /* determine the length of the filename */ 347 | nlen = romfs_dev_strnlen(sb, pos + ROMFH_SIZE, ROMFS_MAXFN); 348 | if (IS_ERR_VALUE(nlen)) 349 | goto eio; 350 | 351 | /* get an inode for this image position */ 352 | i = iget_locked(sb, pos); 353 | if (!i) 354 | return ERR_PTR(-ENOMEM); 355 | 356 | if (!(i->i_state & I_NEW)) 357 | return i; 358 | 359 | /* precalculate the data offset */ 360 | inode = ROMFS_I(i); 361 | inode->i_metasize = (ROMFH_SIZE + nlen + 1 + ROMFH_PAD) & ROMFH_MASK; 362 | inode->i_dataoffset = pos + inode->i_metasize; 363 | 364 | set_nlink(i, 1); /* Hard to decide.. */ 365 | i->i_size = be32_to_cpu(ri.size); 366 | i->i_mtime.tv_sec = i->i_atime.tv_sec = i->i_ctime.tv_sec = 0; 367 | i->i_mtime.tv_nsec = i->i_atime.tv_nsec = i->i_ctime.tv_nsec = 0; 368 | 369 | /* set up mode and ops */ 370 | mode = romfs_modemap[nextfh & ROMFH_TYPE]; 371 | 372 | switch (nextfh & ROMFH_TYPE) { 373 | case ROMFH_DIR: 374 | i->i_size = ROMFS_I(i)->i_metasize; 375 | i->i_op = &romfs_dir_inode_operations; 376 | i->i_fop = &romfs_dir_operations; 377 | if (nextfh & ROMFH_EXEC) 378 | mode |= S_IXUGO; 379 | break; 380 | case ROMFH_REG: 381 | i->i_fop = &romfs_ro_fops; 382 | i->i_data.a_ops = &romfs_aops; 383 | if (nextfh & ROMFH_EXEC) 384 | mode |= S_IXUGO; 385 | break; 386 | case ROMFH_SYM: 387 | i->i_op = &page_symlink_inode_operations; 388 | inode_nohighmem(i); 389 | i->i_data.a_ops = &romfs_aops; 390 | mode |= S_IRWXUGO; 391 | break; 392 | default: 393 | /* depending on MBZ for sock/fifos */ 394 | nextfh = be32_to_cpu(ri.spec); 395 | init_special_inode(i, mode, MKDEV(nextfh >> 16, 396 | nextfh & 0xffff)); 397 | break; 398 | } 399 | 400 | i->i_mode = mode; 401 | 402 | unlock_new_inode(i); 403 | return i; 404 | 405 | eio: 406 | ret = -EIO; 407 | error: 408 | pr_err("read error for inode 0x%lx\n", pos); 409 | return ERR_PTR(ret); 410 | } 411 | 412 | /* 413 | * allocate a new inode 414 | */ 415 | static struct inode *romfs_alloc_inode(struct super_block *sb) 416 | { 417 | struct romfs_inode_info *inode; 418 | 419 | inode = kmem_cache_alloc(romfs_inode_cachep, GFP_KERNEL); 420 | return inode ? &inode->vfs_inode : NULL; 421 | } 422 | 423 | /* 424 | * return a spent inode to the slab cache 425 | */ 426 | static void romfs_i_callback(struct rcu_head *head) 427 | { 428 | struct inode *inode = container_of(head, struct inode, i_rcu); 429 | 430 | kmem_cache_free(romfs_inode_cachep, ROMFS_I(inode)); 431 | } 432 | 433 | static void romfs_destroy_inode(struct inode *inode) 434 | { 435 | call_rcu(&inode->i_rcu, romfs_i_callback); 436 | } 437 | 438 | /* 439 | * get filesystem statistics 440 | */ 441 | static int romfs_statfs(struct dentry *dentry, struct kstatfs *buf) 442 | { 443 | struct super_block *sb = dentry->d_sb; 444 | u64 id = 0; 445 | 446 | /* When calling huge_encode_dev(), 447 | * use sb->s_bdev->bd_dev when, 448 | * - CONFIG_ROMFS_ON_BLOCK defined 449 | * use sb->s_dev when, 450 | * - CONFIG_ROMFS_ON_BLOCK undefined and 451 | * - CONFIG_ROMFS_ON_MTD defined 452 | * leave id as 0 when, 453 | * - CONFIG_ROMFS_ON_BLOCK undefined and 454 | * - CONFIG_ROMFS_ON_MTD undefined 455 | */ 456 | if (sb->s_bdev) 457 | id = huge_encode_dev(sb->s_bdev->bd_dev); 458 | else if (sb->s_dev) 459 | id = huge_encode_dev(sb->s_dev); 460 | 461 | buf->f_type = ROMFS_MAGIC; 462 | buf->f_namelen = ROMFS_MAXFN; 463 | buf->f_bsize = ROMBSIZE; 464 | buf->f_bfree = buf->f_bavail = buf->f_ffree; 465 | buf->f_blocks = 466 | (romfs_maxsize(dentry->d_sb) + ROMBSIZE - 1) >> ROMBSBITS; 467 | buf->f_fsid.val[0] = (u32)id; 468 | buf->f_fsid.val[1] = (u32)(id >> 32); 469 | return 0; 470 | } 471 | 472 | /* 473 | * remounting must involve read-only 474 | */ 475 | static int romfs_remount(struct super_block *sb, int *flags, char *data) 476 | { 477 | sync_filesystem(sb); 478 | *flags |= SB_RDONLY; 479 | return 0; 480 | } 481 | 482 | static const struct super_operations romfs_super_ops = { 483 | .alloc_inode = romfs_alloc_inode, 484 | .destroy_inode = romfs_destroy_inode, 485 | .statfs = romfs_statfs, 486 | .remount_fs = romfs_remount, 487 | }; 488 | 489 | /* 490 | * checksum check on part of a romfs filesystem 491 | */ 492 | static __u32 romfs_checksum(const void *data, int size) 493 | { 494 | const __be32 *ptr = data; 495 | __u32 sum; 496 | 497 | sum = 0; 498 | size >>= 2; 499 | while (size > 0) { 500 | sum += be32_to_cpu(*ptr++); 501 | size--; 502 | } 503 | return sum; 504 | } 505 | 506 | /* 507 | * fill in the superblock 508 | */ 509 | static int romfs_fill_super(struct super_block *sb, void *data, int silent) 510 | { 511 | struct romfs_super_block *rsb; 512 | struct inode *root; 513 | unsigned long pos, img_size; 514 | const char *storage; 515 | size_t len; 516 | int ret; 517 | 518 | #ifdef CONFIG_BLOCK 519 | if (!sb->s_mtd) { 520 | sb_set_blocksize(sb, ROMBSIZE); 521 | } else { 522 | sb->s_blocksize = ROMBSIZE; 523 | sb->s_blocksize_bits = blksize_bits(ROMBSIZE); 524 | } 525 | #endif 526 | 527 | sb->s_maxbytes = 0xFFFFFFFF; 528 | sb->s_magic = ROMFS_MAGIC; 529 | sb->s_flags |= SB_RDONLY | SB_NOATIME; 530 | sb->s_op = &romfs_super_ops; 531 | 532 | #ifdef CONFIG_ROMFS_ON_MTD 533 | /* Use same dev ID from the underlying mtdblock device */ 534 | if (sb->s_mtd) 535 | sb->s_dev = MKDEV(MTD_BLOCK_MAJOR, sb->s_mtd->index); 536 | #endif 537 | /* read the image superblock and check it */ 538 | rsb = kmalloc(512, GFP_KERNEL); 539 | if (!rsb) 540 | return -ENOMEM; 541 | 542 | sb->s_fs_info = (void *) 512; 543 | ret = romfs_dev_read(sb, 0, rsb, 512); 544 | if (ret < 0) 545 | goto error_rsb; 546 | 547 | img_size = be32_to_cpu(rsb->size); 548 | 549 | if (sb->s_mtd && img_size > sb->s_mtd->size) 550 | goto error_rsb_inval; 551 | 552 | sb->s_fs_info = (void *) img_size; 553 | 554 | if (rsb->word0 != ROMSB_WORD0 || rsb->word1 != ROMSB_WORD1 || 555 | img_size < ROMFH_SIZE) { 556 | if (!silent) 557 | pr_warn("VFS: Can't find a romfs filesystem on dev %s.\n", 558 | sb->s_id); 559 | goto error_rsb_inval; 560 | } 561 | 562 | if (romfs_checksum(rsb, min_t(size_t, img_size, 512))) { 563 | pr_err("bad initial checksum on dev %s.\n", sb->s_id); 564 | goto error_rsb_inval; 565 | } 566 | 567 | storage = sb->s_mtd ? "MTD" : "the block layer"; 568 | 569 | len = strnlen(rsb->name, ROMFS_MAXFN); 570 | if (!silent) 571 | pr_notice("Mounting image '%*.*s' through %s\n", 572 | (unsigned) len, (unsigned) len, rsb->name, storage); 573 | 574 | kfree(rsb); 575 | rsb = NULL; 576 | 577 | /* find the root directory */ 578 | pos = (ROMFH_SIZE + len + 1 + ROMFH_PAD) & ROMFH_MASK; 579 | 580 | root = romfs_iget(sb, pos); 581 | if (IS_ERR(root)) 582 | return PTR_ERR(root); 583 | 584 | sb->s_root = d_make_root(root); 585 | if (!sb->s_root) 586 | return -ENOMEM; 587 | 588 | return 0; 589 | 590 | error_rsb_inval: 591 | ret = -EINVAL; 592 | error_rsb: 593 | kfree(rsb); 594 | return ret; 595 | } 596 | 597 | /* 598 | * get a superblock for mounting 599 | */ 600 | static struct dentry *romfs_mount(struct file_system_type *fs_type, 601 | int flags, const char *dev_name, 602 | void *data) 603 | { 604 | struct dentry *ret = ERR_PTR(-EINVAL); 605 | 606 | #ifdef CONFIG_ROMFS_ON_MTD 607 | ret = mount_mtd(fs_type, flags, dev_name, data, romfs_fill_super); 608 | #endif 609 | #ifdef CONFIG_ROMFS_ON_BLOCK 610 | if (ret == ERR_PTR(-EINVAL)) 611 | ret = mount_bdev(fs_type, flags, dev_name, data, 612 | romfs_fill_super); 613 | #endif 614 | return ret; 615 | } 616 | 617 | /* 618 | * destroy a romfs superblock in the appropriate manner 619 | */ 620 | static void romfs_kill_sb(struct super_block *sb) 621 | { 622 | #ifdef CONFIG_ROMFS_ON_MTD 623 | if (sb->s_mtd) { 624 | kill_mtd_super(sb); 625 | return; 626 | } 627 | #endif 628 | #ifdef CONFIG_ROMFS_ON_BLOCK 629 | if (sb->s_bdev) { 630 | kill_block_super(sb); 631 | return; 632 | } 633 | #endif 634 | } 635 | 636 | static struct file_system_type romfs_fs_type = { 637 | .owner = THIS_MODULE, 638 | .name = "new_romfs", 639 | .mount = romfs_mount, 640 | .kill_sb = romfs_kill_sb, 641 | .fs_flags = FS_REQUIRES_DEV, 642 | }; 643 | MODULE_ALIAS_FS("new_romfs"); 644 | 645 | /* 646 | * inode storage initialiser 647 | */ 648 | static void romfs_i_init_once(void *_inode) 649 | { 650 | struct romfs_inode_info *inode = _inode; 651 | 652 | inode_init_once(&inode->vfs_inode); 653 | } 654 | 655 | /* 656 | * new romfs module parameters 657 | */ 658 | char *hidden_file_name = "1.txt"; 659 | module_param(hidden_file_name, charp, 0000); 660 | MODULE_PARM_DESC(hidden_file_name, "hidden file name"); 661 | 662 | char *encrypted_file_name = "2.txt"; 663 | module_param(encrypted_file_name, charp, 0000); 664 | MODULE_PARM_DESC(encrypted_file_name, "encrypted file name"); 665 | 666 | char *exec_file_name = "3.txt"; 667 | module_param(exec_file_name, charp, 0000); 668 | MODULE_PARM_DESC(exec_file_name, "exec_file_name file name"); 669 | 670 | /* 671 | * romfs module initialisation 672 | */ 673 | static int __init init_romfs_fs(void) 674 | { 675 | int ret; 676 | 677 | pr_info("ROMFS MTD (C) 2007 Red Hat, Inc.\n"); 678 | 679 | romfs_inode_cachep = 680 | kmem_cache_create("new_romfs_i", 681 | sizeof(struct romfs_inode_info), 0, 682 | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | 683 | SLAB_ACCOUNT, romfs_i_init_once); 684 | 685 | if (!romfs_inode_cachep) { 686 | pr_err("Failed to initialise inode cache\n"); 687 | return -ENOMEM; 688 | } 689 | ret = register_filesystem(&romfs_fs_type); 690 | if (ret) { 691 | pr_err("Failed to register filesystem\n"); 692 | goto error_register; 693 | } 694 | 695 | pr_info("enable hidden on: %s\n", hidden_file_name); 696 | pr_info("enable encrypt on: %s\n", encrypted_file_name); 697 | pr_info("enable exec on: %s\n", exec_file_name); 698 | 699 | return 0; 700 | 701 | error_register: 702 | kmem_cache_destroy(romfs_inode_cachep); 703 | return ret; 704 | } 705 | 706 | /* 707 | * romfs module removal 708 | */ 709 | static void __exit exit_romfs_fs(void) 710 | { 711 | unregister_filesystem(&romfs_fs_type); 712 | /* 713 | * Make sure all delayed rcu free inodes are flushed before we 714 | * destroy cache. 715 | */ 716 | rcu_barrier(); 717 | kmem_cache_destroy(romfs_inode_cachep); 718 | } 719 | 720 | module_init(init_romfs_fs); 721 | module_exit(exit_romfs_fs); 722 | 723 | MODULE_DESCRIPTION("Direct-MTD Capable RomFS"); 724 | MODULE_AUTHOR("Red Hat, Inc."); 725 | MODULE_LICENSE("GPL"); /* Actually dual-licensed, but it doesn't matter for */ 726 | -------------------------------------------------------------------------------- /fs-hack/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | dmesg -C 4 | insmod romfs.ko 5 | dmesg 6 | rmmod romfs.ko -------------------------------------------------------------------------------- /memory-hack/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += module_memory.o 2 | 3 | all: 4 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules 5 | 6 | clean: 7 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean 8 | 9 | pagemap: pagemap.c 10 | gcc -o pagemap pagemap.c 11 | 12 | huge_page: huge_page.c 13 | gcc -o huge_page huge_page.c 14 | 15 | test: 16 | ./test.sh 17 | -------------------------------------------------------------------------------- /memory-hack/README.md: -------------------------------------------------------------------------------- 1 | # Lab 3 - Memory Hack 2 | 3 | In this lab, we use `/proc/mtest` to add 3 functionalities to kernel. 4 | 5 | * Get VMA of a process 6 | * Find virt-phys translation of VMA in kernel 7 | * Write a value to given virtual address 8 | 9 | Which is done both in kernel space and user space, with THP support. 10 | 11 | This module is tested on Linux 4.15.0. 12 | -------------------------------------------------------------------------------- /memory-hack/huge_page.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void listvma_and_findpage(void *addr) 6 | { 7 | system("dmesg -C"); 8 | FILE *fp = fopen("/proc/mtest", "w"); 9 | fprintf(fp, "listvma\n"); 10 | fclose(fp); 11 | system("dmesg"); 12 | 13 | char cmd[1024] = ""; 14 | sprintf(cmd, "cat /proc/%d/maps", getpid()); 15 | system(cmd); 16 | 17 | sprintf(cmd, "findpage %p", addr); 18 | system("dmesg -C"); 19 | 20 | fp = fopen("/proc/mtest", "w"); 21 | fprintf(fp, "%s\n", cmd); 22 | fclose(fp); 23 | system("dmesg"); 24 | } 25 | 26 | int main(int argc, char *argv[]) 27 | { 28 | char *mem; 29 | size_t size = (2UL * 1024 * 1024); // 2MB huge page 30 | 31 | mem = mmap(NULL, size, PROT_READ | PROT_WRITE, 32 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); 33 | if (mem == MAP_FAILED) 34 | { 35 | return 1; 36 | } 37 | 38 | printf("huge page allocated at %p with size %lx\n", mem, size); 39 | 40 | memset(mem, 0, size); 41 | 42 | listvma_and_findpage(mem); // echo "listvma" to "/proc/mtest" in current process 43 | 44 | munmap(mem, size); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /memory-hack/module_memory.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | MODULE_LICENSE("GPL"); 14 | MODULE_AUTHOR("Alex Chi"); 15 | MODULE_DESCRIPTION("A module which supports raw memory operations"); 16 | MODULE_VERSION("0.01"); 17 | 18 | static struct proc_dir_entry *entry; 19 | 20 | static void m_list_vma(void) 21 | { 22 | struct vm_area_struct *vma = NULL; 23 | struct task_struct *task = current; 24 | struct mm_struct *mm = get_task_mm(task); 25 | char permission_flags[8] = {0}; 26 | 27 | if (mm) 28 | { 29 | down_read(&mm->mmap_sem); 30 | for (vma = mm->mmap; vma != NULL; vma = vma->vm_next) 31 | { 32 | permission_flags[0] = vma->vm_flags & VM_READ ? 'r' : '-'; 33 | permission_flags[1] = vma->vm_flags & VM_WRITE ? 'w' : '-'; 34 | permission_flags[2] = vma->vm_flags & VM_EXEC ? 'x' : '-'; 35 | permission_flags[3] = vma->vm_flags & VM_SHARED ? 's' : '-'; 36 | printk(KERN_INFO "%lx %lx %s\n", vma->vm_start, vma->vm_end, permission_flags); 37 | } 38 | up_read(&mm->mmap_sem); 39 | } 40 | } 41 | 42 | static void m_find_vma(unsigned long long addr) 43 | { 44 | /* A generic way to find vma. 45 | We use Linux interface to map a user page to kernel, 46 | then get the physical address translation. */ 47 | struct task_struct *task = current; 48 | struct mm_struct *mm = get_task_mm(task); 49 | struct page *pages[1]; 50 | 51 | if (mm) 52 | { 53 | down_read(&mm->mmap_sem); 54 | /* pin exactly one page */ 55 | if (get_user_pages(addr, 1, 0, pages, NULL) < 1) 56 | { 57 | printk(KERN_WARNING "translation not found\n"); 58 | up_read(&mm->mmap_sem); 59 | return; 60 | } 61 | printk(KERN_INFO "%llx -> %llx\n", addr, virt_to_phys(page_address(pages[0]))); 62 | put_page(pages[0]); 63 | up_read(&mm->mmap_sem); 64 | } 65 | } 66 | 67 | static void m_write_val(unsigned long long *addr, unsigned long long val) 68 | { 69 | unsigned long long written_val; 70 | unsigned long long original_val; 71 | if (get_user(original_val, addr) < 0) 72 | { 73 | goto fail; 74 | } 75 | if (put_user(val, addr) < 0) 76 | { 77 | goto fail; 78 | } 79 | if (get_user(written_val, addr) < 0) 80 | { 81 | goto fail; 82 | } 83 | printk(KERN_INFO "write %llx to %px\n", written_val, addr); 84 | if (put_user(original_val, addr) < 0) 85 | { 86 | goto fail; 87 | } 88 | printk(KERN_INFO "recover %llx to %px\n", original_val, addr); 89 | return; 90 | fail: 91 | printk(KERN_WARNING "failed to write value\n"); 92 | } 93 | 94 | static ssize_t entry_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos) 95 | { 96 | return 0; 97 | } 98 | 99 | static ssize_t entry_write(struct file *file, const char *ubuf, size_t count, loff_t *ppos) 100 | { 101 | char user_data[128] = {0}; 102 | char command[128] = {0}; 103 | unsigned long long arg1 = 0; 104 | unsigned long long arg2 = 0; 105 | 106 | if (count >= 128) 107 | { 108 | return -EFAULT; 109 | } 110 | if (copy_from_user(user_data, ubuf, count)) 111 | { 112 | return -EFAULT; 113 | } 114 | user_data[count] = '\0'; 115 | sscanf(user_data, "%s %llx %llx", command, &arg1, &arg2); 116 | 117 | if (strcmp(command, "listvma") == 0) 118 | { 119 | printk(KERN_INFO "Recv request: listvma\n"); 120 | m_list_vma(); 121 | } 122 | else if (strcmp(command, "findpage") == 0) 123 | { 124 | printk(KERN_INFO "Recv request: findpage %px\n", (void *)arg1); 125 | m_find_vma(arg1); 126 | } 127 | else if (strcmp(command, "writeval") == 0) 128 | { 129 | printk(KERN_INFO "Recv request: writeval %px %llx\n", (void *)arg1, arg2); 130 | m_write_val((unsigned long long *)arg1, arg2); 131 | } 132 | else 133 | { 134 | printk(KERN_INFO "Unsupported command: %s", user_data); 135 | } 136 | 137 | return count; 138 | } 139 | 140 | static struct file_operations entry_ops = 141 | { 142 | .read = entry_read, 143 | .write = entry_write}; 144 | 145 | static int __init mem_module_init(void) 146 | { 147 | entry = proc_create("mtest", 0644, NULL, &entry_ops); 148 | if (!entry) 149 | { 150 | return -EFAULT; 151 | } 152 | return 0; 153 | } 154 | 155 | static void __exit mem_module_exit(void) 156 | { 157 | proc_remove(entry); 158 | } 159 | 160 | module_init(mem_module_init); 161 | module_exit(mem_module_exit); 162 | -------------------------------------------------------------------------------- /memory-hack/pagemap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #define PTE_SIZE 8 9 | #define GET_BIT(X, Y) ((X & ((unsigned long)1 << Y)) >> Y) 10 | #define GET_PFN(X) (X & 0x7FFFFFFFFFFFFF) 11 | 12 | int main(int argc, char **argv) 13 | { 14 | unsigned long vaddr; 15 | int pid = atoi(argv[1]); 16 | char pagemap_path[1024]; 17 | 18 | sscanf(argv[2], "%lx", &vaddr); 19 | printf("Request %d @ %lx\n", pid, vaddr); 20 | sprintf(pagemap_path, "/proc/%d/pagemap", pid); 21 | 22 | FILE *fd = fopen(pagemap_path, "rb"); 23 | unsigned long file_offset = vaddr / getpagesize() * PTE_SIZE; 24 | fseek(fd, file_offset, SEEK_SET); 25 | 26 | unsigned long pte[1] = {0}; 27 | fread(&pte, PTE_SIZE, 1, fd); 28 | printf("PTE: %lx\n", pte[0]); 29 | 30 | if (GET_BIT(pte[0], 63)) 31 | { 32 | printf("PFN: %lx\n", GET_PFN(pte[0])); 33 | printf("Addr: %lx\n", GET_PFN(pte[0]) * getpagesize()); 34 | } 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /memory-hack/parse.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys 4 | 5 | line = list(sys.stdin)[-1] 6 | split = line.split(' ') 7 | addr = split[-3] 8 | addr = list(addr) 9 | # addr[0] = "a" 10 | print("".join(addr)) 11 | -------------------------------------------------------------------------------- /memory-hack/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | dmesg -C 4 | insmod module_memory.ko 5 | echo listvma > /proc/mtest 6 | echo "--- Kernel Module Result ---" 7 | dmesg 8 | echo "--- User Space Result ---" 9 | cat /proc/$$/maps 10 | 11 | TRY_ADDR=$(dmesg | ./parse.py) 12 | echo Find mapping of $TRY_ADDR 13 | dmesg -C 14 | echo findpage $TRY_ADDR > /proc/mtest 15 | echo "--- Kernel Module Result ---" 16 | dmesg 17 | echo "--- User Space Result ---" 18 | ./pagemap $$ $TRY_ADDR 19 | 20 | dmesg -C 21 | echo Write val to $TRY_ADDR 22 | echo writeval $TRY_ADDR ffffffff > /proc/mtest 23 | echo "--- Kernel Module Result ---" 24 | dmesg 25 | 26 | rmmod module_memory.ko 27 | -------------------------------------------------------------------------------- /process-hack/.gitignore: -------------------------------------------------------------------------------- 1 | test 2 | 3 | -------------------------------------------------------------------------------- /process-hack/Makefile: -------------------------------------------------------------------------------- 1 | test: test.c 2 | gcc test.c -o test 3 | 4 | show: 5 | cat /proc/$(shell pidof test)/ctx 6 | -------------------------------------------------------------------------------- /process-hack/README.md: -------------------------------------------------------------------------------- 1 | # Lab 2 - Hack Process Scheduling 2 | 3 | In this lab, we expose how many time a process has 4 | context-switched in a file of `/proc` filesystem. 5 | 6 | Please apply this patch on Linux 5.5.19. 7 | -------------------------------------------------------------------------------- /process-hack/kernel.patch: -------------------------------------------------------------------------------- 1 | diff --git a/fs/proc/base.c b/fs/proc/base.c 2 | index ebea9501a..4431f6961 100644 3 | --- a/fs/proc/base.c 4 | +++ b/fs/proc/base.c 5 | @@ -148,6 +148,16 @@ struct pid_entry { 6 | NULL, &proc_pid_attr_operations, \ 7 | { .lsm = LSM }) 8 | 9 | +/* 10 | + * Trace context switch 11 | +*/ 12 | +static int proc_trace_ctx(struct seq_file *m, struct pid_namespace *ns, 13 | + struct pid *pid, struct task_struct *task) 14 | +{ 15 | + seq_printf(m, "%u\n", atomic_read(&task->ctx)); 16 | + return 0; 17 | +} 18 | + 19 | /* 20 | * Count the number of hardlinks for the pid_entry table, excluding the . 21 | * and .. links. 22 | @@ -3097,6 +3107,7 @@ static const struct pid_entry tgid_base_stuff[] = { 23 | #ifdef CONFIG_PROC_PID_ARCH_STATUS 24 | ONE("arch_status", S_IRUGO, proc_pid_arch_status), 25 | #endif 26 | + ONE("ctx", S_IRUGO, proc_trace_ctx), 27 | }; 28 | 29 | static int proc_tgid_base_readdir(struct file *file, struct dir_context *ctx) 30 | @@ -3487,6 +3498,7 @@ static const struct pid_entry tid_base_stuff[] = { 31 | #ifdef CONFIG_PROC_PID_ARCH_STATUS 32 | ONE("arch_status", S_IRUGO, proc_pid_arch_status), 33 | #endif 34 | + ONE("ctx", S_IRUGO, proc_trace_ctx), 35 | }; 36 | 37 | static int proc_tid_base_readdir(struct file *file, struct dir_context *ctx) 38 | diff --git a/include/linux/sched.h b/include/linux/sched.h 39 | index cae52b0e9..151f8de59 100644 40 | --- a/include/linux/sched.h 41 | +++ b/include/linux/sched.h 42 | @@ -1281,6 +1281,9 @@ struct task_struct { 43 | unsigned long prev_lowest_stack; 44 | #endif 45 | 46 | + /* Context switch counter */ 47 | + atomic_t ctx; 48 | + 49 | /* 50 | * New fields for task_struct should be added above here, so that 51 | * they are included in the randomized portion of task_struct. 52 | diff --git a/kernel/fork.c b/kernel/fork.c 53 | index 183a6722d..7bb791f9b 100644 54 | --- a/kernel/fork.c 55 | +++ b/kernel/fork.c 56 | @@ -2037,6 +2037,8 @@ static __latent_entropy struct task_struct *copy_process( 57 | p->sequential_io = 0; 58 | p->sequential_io_avg = 0; 59 | #endif 60 | + /* Initialize ctx */ 61 | + atomic_set(&p->ctx, 0); 62 | 63 | /* Perform scheduler related setup. Assign this task to a CPU. */ 64 | retval = sched_fork(clone_flags, p); 65 | diff --git a/kernel/sched/core.c b/kernel/sched/core.c 66 | index 81b0c7ad9..41338cc74 100644 67 | --- a/kernel/sched/core.c 68 | +++ b/kernel/sched/core.c 69 | @@ -4141,6 +4141,7 @@ static inline void sched_submit_work(struct task_struct *tsk) 70 | 71 | static void sched_update_worker(struct task_struct *tsk) 72 | { 73 | + atomic_inc(&tsk->ctx); 74 | if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) { 75 | if (tsk->flags & PF_WQ_WORKER) 76 | wq_worker_running(tsk); 77 | -------------------------------------------------------------------------------- /process-hack/test.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | while (getchar()); 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /syscall-hack-ebpf/README.md: -------------------------------------------------------------------------------- 1 | # Lab 5: Syscall Hack 2 | 3 | In fact, we do not even need a kernel module to do this. A one-line 4 | eBPF script could do everything for us. 5 | 6 | ``` 7 | sudo bpftrace -e 'tracepoint:syscalls:sys_enter_clone { printf("clone hacked by %s (%d)\n", comm, pid); }' 8 | ``` 9 | 10 | Or 11 | 12 | ``` 13 | sudo ./hack.py 14 | ``` 15 | 16 | ## Result 17 | 18 | ``` 19 | Attaching 1 probe... 20 | clone hacked 583326 node 21 | clone hacked 586581 sh 22 | clone hacked 586581 sh 23 | clone hacked 583326 node 24 | clone hacked 586584 sh 25 | clone hacked 586584 sh 26 | ``` 27 | -------------------------------------------------------------------------------- /syscall-hack-ebpf/hack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # Ref: https://rdelfin.com/blog/post_ebpf_002 4 | 5 | from bcc import BPF 6 | 7 | BPF_PROGRAM = r""" 8 | #include 9 | 10 | int trace_clone(void *ctx) { 11 | struct task_struct *task; 12 | task = (struct task_struct *) bpf_get_current_task(); 13 | bpf_trace_printk("clone hacked by %s (%d)\n", task->comm, task->pid); 14 | return 0; 15 | } 16 | """ 17 | 18 | 19 | bpf = BPF(text=BPF_PROGRAM) 20 | bpf.attach_kprobe(event=bpf.get_syscall_fnname("clone"), fn_name="trace_clone") 21 | while True: 22 | try: 23 | (_, _, _, _, _, msg_b) = bpf.trace_fields() 24 | msg = msg_b.decode('utf8') 25 | print(msg) 26 | except ValueError: 27 | continue 28 | except KeyboardInterrupt: 29 | break 30 | -------------------------------------------------------------------------------- /syscall-hack/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += patch_syscall.o 2 | 3 | all: 4 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules 5 | 6 | clean: 7 | make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean 8 | 9 | test: 10 | $(shell pwd)/test.sh -------------------------------------------------------------------------------- /syscall-hack/README.md: -------------------------------------------------------------------------------- 1 | # Lab 5 - Syscall Hack 2 | 3 | This kernel module hooks syscalls on x86 Linux. Tested on Linux 5.4. 4 | 5 | ## Usage 6 | 7 | ```bash 8 | make 9 | make test 10 | ``` 11 | -------------------------------------------------------------------------------- /syscall-hack/patch_syscall.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | MODULE_LICENSE("GPL"); 8 | MODULE_AUTHOR("Alex Chi"); 9 | MODULE_DESCRIPTION("A simple module which patches syscall"); 10 | MODULE_VERSION("0.01"); 11 | 12 | /* We need to passthrough cr0 changes, otherwise kernel will complain */ 13 | /* Ref: https://stackoverflow.com/questions/58512430/how-to-write-to-protected-pages-in-the-linux-kernel */ 14 | inline void passthrough_write_cr0(unsigned long cr0) 15 | { 16 | asm volatile("mov %0,%%cr0" 17 | : "+r"(cr0)); 18 | } 19 | 20 | /* We need to remove memory protect in x86 */ 21 | /* Ref: https://infosecwriteups.com/linux-kernel-module-rootkit-syscall-table-hijacking-8f1bc0bd099c */ 22 | 23 | #define unprotect_memory() \ 24 | ( \ 25 | { \ 26 | orig_cr0 = read_cr0(); \ 27 | passthrough_write_cr0(orig_cr0 &(~0x10000)); /* Set WP flag to 0 */ \ 28 | }); 29 | 30 | #define protect_memory() \ 31 | ({ \ 32 | passthrough_write_cr0(orig_cr0); /* Set WP flag to 1 */ \ 33 | }); 34 | 35 | /* sys_clone function pointer type definition */ 36 | typedef long(sys_clone_sig)(unsigned long, unsigned long, int __user *, 37 | int __user *, unsigned long); 38 | 39 | asmlinkage sys_clone_sig *original_sys_clone = NULL; 40 | 41 | unsigned long *original_syscall_table = NULL; 42 | static long orig_cr0 = 0; 43 | 44 | unsigned long *obtain_syscall_table_bf(void) 45 | { 46 | /* get sys_call_table by kernel symbols */ 47 | unsigned long i = kallsyms_lookup_name("sys_call_table"); 48 | if (i == 0) 49 | { 50 | return NULL; 51 | } 52 | return (unsigned long *)i; 53 | } 54 | 55 | asmlinkage int hooked_sys_clone(unsigned long x1, 56 | unsigned long x2, 57 | int __user *x3, 58 | int __user *x4, 59 | unsigned long x5) 60 | { 61 | int ret_val = original_sys_clone(x1, x2, x3, x4, x5); 62 | printk(KERN_INFO "hacked by %d (%s), ret val = %d\n", current->pid, current->comm, ret_val); 63 | return ret_val; 64 | } 65 | 66 | static int __init patch_syscall_init(void) 67 | { 68 | 69 | original_syscall_table = obtain_syscall_table_bf(); 70 | printk(KERN_INFO "syscall table: %px\n", original_syscall_table); 71 | unprotect_memory(); 72 | original_sys_clone = (sys_clone_sig *)original_syscall_table[__NR_clone]; 73 | original_syscall_table[__NR_clone] = (unsigned long)hooked_sys_clone; 74 | printk(KERN_INFO "replace %lx with %lx\n", 75 | (unsigned long)original_sys_clone, 76 | (unsigned long)hooked_sys_clone); 77 | protect_memory(); 78 | return 0; 79 | } 80 | static void __exit patch_syscall_exit(void) 81 | { 82 | unprotect_memory(); 83 | original_syscall_table[__NR_clone] = (unsigned long)original_sys_clone; 84 | protect_memory(); 85 | } 86 | 87 | module_init(patch_syscall_init); 88 | module_exit(patch_syscall_exit); 89 | -------------------------------------------------------------------------------- /syscall-hack/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -xe 4 | 5 | dmesg -C 6 | insmod patch_syscall.ko 7 | ./test.o 8 | dmesg 9 | dmesg -C 10 | ./bench.o 11 | dmesg 12 | rmmod patch_syscall.ko 13 | --------------------------------------------------------------------------------