├── .gitignore ├── COPYING ├── ChangeLog.md ├── Makefile.am ├── README.md ├── autogen.sh ├── configure.ac ├── release.mk └── src ├── Makefile.am ├── gdb.c ├── gdb.h ├── kmem.c ├── kmem.h └── kmemd.c /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.o 3 | *.d 4 | /src/kmemd 5 | /kmemd-*.tar* 6 | 7 | # autoconf/automake generated files 8 | .deps 9 | .dirstamp 10 | Makefile 11 | Makefile.in 12 | /aclocal.m4 13 | /autom4te.cache 14 | /compile 15 | /config.* 16 | /configure 17 | /depcomp 18 | /install-sh 19 | /libtool 20 | /ltmain.sh 21 | /m4 22 | /missing 23 | /stamp-h1 24 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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) 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 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to the project are documented in this file. 4 | 5 | ## [1.0.0] - 2022-10-20 6 | 7 | Initial release. 8 | 9 | ### Added 10 | 11 | - Everything 12 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | SUBDIRS = src 2 | doc_DATA = README.md COPYING 3 | EXTRA_DIST = ChangeLog.md README.md 4 | DISTCLEANFILES = *~ *.d 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | kmemd 2 | ----- 3 | 4 | Explore a live Linux kernel's memory using GDB 5 | 6 | For more background, see this [blog 7 | entry](http://wkz.github.io/post/kmemd/) 8 | 9 | ## Building and Installing 10 | 11 | kmem uses Autotools, so the procdure is hopefully familiar to many. 12 | 13 | If you are building from a cloned GIT repo (as opposed to a release 14 | tarball), you have to start by generating the configure script: 15 | 16 | ```sh 17 | ~/kmemd$ ./autogen.sh 18 | ``` 19 | 20 | To build and install with the default settings: 21 | 22 | ```sh 23 | ~/kmemd$ ./configure && make && sudo make install 24 | ``` 25 | 26 | ## Using kmemd 27 | 28 | **BEWARE:** You are about to serve up your kernel's memory over a file 29 | or socket, i.e. basically [Hearbleed](https://heartbleed.com/) as a 30 | service. Anyone with access to that interface will be able to read 31 | _anything_ in there, including crypto keys and whatnot. Consider 32 | yourself warned! 33 | 34 | In is simplest form, kmem can be started without any arguments. As we 35 | are going to completely root the box, we need superuser permissions. 36 | 37 | ```sh 38 | ~$ sudo kmemd 39 | ``` 40 | 41 | Without arguments, kmemd will listen for connections on the named UNIX 42 | socket `/run/kmemd.sock`, which works well in scenarios where you want 43 | to inspect the kernel running on your local machine. 44 | 45 | In cases where GDB is run on a different system than the one being 46 | inspected (which is often the case when debugging embedded systems, 47 | for example), you will most likely want to bind to a TCP socket 48 | instead: 49 | 50 | ```sh 51 | ~$ sudo kmemd -s :1234 52 | ``` 53 | 54 | At this point you should be able to attach to kmemd using GDB's remote 55 | debugging facility in the normal way: 56 | 57 | ```sh 58 | ~/linux$ gdb vmlinux 59 | (gdb) target remote the-system:1234 60 | ``` 61 | 62 | ## KASLR 63 | 64 | If your kernel is running with address layout randomization (KASLR), 65 | the debug symbols in your `vmlinux` won't match the addresses used by 66 | the running kernel. 67 | 68 | You can use this GDB Python extension to compensate for it: 69 | [gdb-linux-kaslr.py](https://gist.github.com/wkz/343f1bf91ae71ed2c140943a4f347c0c). Because 70 | it needs to parse `/proc/kallsyms` to figure out the current base 71 | address, GDB needs to be run as root (which it most likely needs to 72 | connect to the default UNIX socket anyway): 73 | 74 | ```sh 75 | ~/linux$ sudo gdb 76 | (gdb) add-vmlinux vmlinux 77 | (gdb) target remote /run/kmemd.sock 78 | ``` 79 | -------------------------------------------------------------------------------- /autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | autoreconf -W portability -visfm 4 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_PREREQ(2.61) 2 | AC_INIT(kmemd, 1.0.0, https://github.com/wkz/kmemd/issues) 3 | 4 | AC_GNU_SOURCE 5 | AM_INIT_AUTOMAKE(1.11 foreign subdir-objects) 6 | AM_SILENT_RULES(yes) 7 | 8 | AC_CONFIG_HEADER(config.h) 9 | AC_CONFIG_FILES([ 10 | Makefile 11 | src/Makefile 12 | ]) 13 | AC_CONFIG_MACRO_DIRS(m4) 14 | 15 | AC_PROG_CC 16 | AC_PROG_INSTALL 17 | 18 | PKG_CHECK_MODULES([libbpf], [libbpf >= 1.0.0]) 19 | 20 | AC_HEADER_STDC 21 | AC_CHECK_HEADERS(linux/bpf.h) 22 | 23 | AC_OUTPUT 24 | -------------------------------------------------------------------------------- /release.mk: -------------------------------------------------------------------------------- 1 | include Makefile 2 | 3 | git-version := $(shell git describe --tags --always --dirty) 4 | dist-sumtypes := .md5 .sha1 .sha256 5 | dist-sumfiles := $(foreach sum,$(dist-sumtypes),$(DIST_ARCHIVES)$(sum)) 6 | 7 | ifeq ($(git-version),$(PACKAGE_VERSION)) 8 | release: $(dist-sumfiles) 9 | @printf '%s is ready\n' $(PACKAGE_VERSION) 10 | else 11 | release: 12 | @printf 'Working tree does not match the expected version (%s != %s)\n' \ 13 | $(git-version) $(PACKAGE_VERSION) 14 | @exit 1 15 | endif 16 | 17 | $(dist-sumfiles): $(DIST_ARCHIVES) 18 | 19 | %.md5: % 20 | md5sum $< >$@ 21 | %.sha1: % 22 | sha1sum $< >$@ 23 | %.sha256: % 24 | sha256sum $< >$@ 25 | 26 | $(DIST_ARCHIVES): distcheck 27 | -------------------------------------------------------------------------------- /src/Makefile.am: -------------------------------------------------------------------------------- 1 | sbin_PROGRAMS = kmemd 2 | 3 | kmemd_CPPFLAGS = -include $(top_builddir)/config.h 4 | kmemd_CFLAGS = -Wall -Wextra 5 | kmemd_CFLAGS += $(libbpf_CFLAGS) 6 | kmemd_LDADD = $(libbpf_LIBS) 7 | kmemd_SOURCES = gdb.c gdb.h kmem.c kmem.h kmemd.c 8 | -------------------------------------------------------------------------------- /src/gdb.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "gdb.h" 8 | 9 | int gdb_debug = 0; 10 | 11 | static uint8_t gdb_hex2bin_nibble(uint8_t nibble) 12 | { 13 | if ((nibble >= '0') && (nibble <= '9')) 14 | return nibble - '0'; 15 | 16 | return 0xa + nibble - 'a'; 17 | } 18 | 19 | int gdb_hex2bin(void *hex, void *bin, size_t len) 20 | { 21 | uint8_t *h = hex, *b = bin; 22 | 23 | for (; len; len--, b++) { 24 | *b = gdb_hex2bin_nibble(*h++) << 4; 25 | *b |= gdb_hex2bin_nibble(*h++); 26 | } 27 | 28 | return 0; 29 | } 30 | 31 | static uint8_t gdb_bin2hex_nibble(uint8_t nibble) 32 | { 33 | if (nibble <= 0x9) 34 | return '0' + nibble; 35 | 36 | return 'a' + nibble - 0xa; 37 | } 38 | 39 | void gdb_bin2hex(void *bin, void *hex, size_t len) 40 | { 41 | uint8_t *h = hex, *b = bin; 42 | 43 | for (; len; len--, b++) { 44 | *h++ = gdb_bin2hex_nibble((*b) >> 4); 45 | *h++ = gdb_bin2hex_nibble((*b) & 0xf); 46 | } 47 | } 48 | 49 | int gdb_recv(struct gdb_session *s, void *buf, size_t len) 50 | { 51 | uint8_t csum_bin, csum_exp = 0; 52 | char csum_hex[3] = { 0 }; 53 | uint8_t *p = buf; 54 | int c, n, i; 55 | 56 | memset(buf, 0, len); 57 | 58 | /* Wait for STX ($), send NAK (-) if we see unexpected data */ 59 | for (;;) { 60 | c = fgetc(s->rx); 61 | switch (c) { 62 | case '+': 63 | break; 64 | case '$': 65 | goto stx; 66 | case EOF: 67 | return -EBADF; 68 | default: 69 | fputc('-', s->tx); 70 | } 71 | } 72 | 73 | stx: 74 | /* Receive bytes until we see ETX (#) */ 75 | for (n = 0; n < (int)len;) { 76 | c = fgetc(s->rx); 77 | switch (c) { 78 | case '#': 79 | goto etx; 80 | case EOF: 81 | return -EBADF; 82 | default: 83 | *p++ = c; 84 | csum_exp += c; 85 | n++; 86 | } 87 | } 88 | etx: 89 | /* Receive checksum */ 90 | for (i = 0; i < 2; i++) { 91 | c = fgetc(s->rx); 92 | /* printf("csum: %c\n", c); */ 93 | if (c == EOF) 94 | return -EBADF; 95 | 96 | csum_hex[i] = c; 97 | } 98 | 99 | csum_bin = strtoul(csum_hex, NULL, 16); 100 | if (csum_bin != csum_exp) { 101 | printf("csum_bin:%2.2x csum_exp:%2.2x\n", csum_bin, csum_exp); 102 | fputc('-', s->tx); 103 | return -EIO; 104 | } 105 | 106 | fputc('+', s->tx); 107 | fflush(s->tx); 108 | 109 | if (gdb_debug) 110 | fprintf(stderr, "RECV:\"%s\"\n", (char *)buf); 111 | return n; 112 | } 113 | 114 | int gdb_send_iter(struct gdb_session *s, int (*next)(void *ctx), void *ctx) 115 | { 116 | uint8_t csum_bin = 0, csum_hex[2]; 117 | int c; 118 | 119 | if (gdb_debug) 120 | fprintf(stderr, "SEND:\""); 121 | 122 | fputc('$', s->tx); 123 | 124 | while ((c = next(ctx)) >= 0) { 125 | fputc(c, s->tx); 126 | csum_bin += c; 127 | 128 | if (gdb_debug) 129 | fputc(c, stderr); 130 | 131 | } 132 | 133 | fputc('#', s->tx); 134 | 135 | if (gdb_debug) 136 | fprintf(stderr, "\"\n"); 137 | 138 | if (c != EOF) 139 | /* Something went wrong, make sure to generate an 140 | * incorrect checksum */ 141 | csum_bin++; 142 | 143 | gdb_bin2hex(&csum_bin, csum_hex, 1); 144 | fwrite(csum_hex, sizeof(csum_hex), 1, s->tx); 145 | fflush(s->tx); 146 | 147 | c = fgetc(s->rx); 148 | if (c == '+') 149 | return 0; 150 | 151 | if (gdb_debug) 152 | fprintf(stderr, "Expected ACK (+), but received '%c'\n", c); 153 | 154 | return -EIO; 155 | } 156 | 157 | struct gdb_send_ctx { 158 | uint8_t *buf; 159 | size_t len; 160 | }; 161 | 162 | static int gdb_send_next(void *_ctx) 163 | { 164 | struct gdb_send_ctx *ctx = _ctx; 165 | 166 | if (ctx->len--) 167 | return *(ctx->buf++); 168 | 169 | return EOF; 170 | } 171 | 172 | int gdb_send(struct gdb_session *s, void *buf, size_t len) 173 | { 174 | struct gdb_send_ctx ctx = { 175 | .buf = buf, 176 | .len = len, 177 | }; 178 | 179 | return gdb_send_iter(s, gdb_send_next, &ctx); 180 | } 181 | -------------------------------------------------------------------------------- /src/gdb.h: -------------------------------------------------------------------------------- 1 | #ifndef _GDB_H 2 | #define _GDB_H 3 | 4 | struct FILE; 5 | 6 | struct gdb_session { 7 | FILE *rx; 8 | FILE *tx; 9 | }; 10 | 11 | extern int gdb_debug; 12 | 13 | int gdb_hex2bin(void *hex, void *bin, size_t len); 14 | void gdb_bin2hex(void *bin, void *hex, size_t len); 15 | 16 | int gdb_recv(struct gdb_session *s, void *buf, size_t len); 17 | int gdb_send(struct gdb_session *s, void *buf, size_t len); 18 | 19 | int gdb_send_iter(struct gdb_session *s, int (*next)(void *ctx), void *ctx); 20 | 21 | #endif /* _GDB_H */ 22 | -------------------------------------------------------------------------------- /src/kmem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include 10 | 11 | #include "kmem.h" 12 | 13 | static char kern_log[BPF_LOG_BUF_SIZE]; 14 | 15 | #define kmem_bufsiz(_idx) ((unsigned)(16 << ((_idx) << 2))) 16 | #define KMEM_BUFMAX kmem_bufsiz(3) 17 | 18 | struct kmem_args { 19 | uint64_t addr; 20 | uint16_t size; 21 | }; 22 | 23 | static const struct bpf_insn kmem_prog[] = { 24 | #define jgt(_size, _off) \ 25 | { \ 26 | BPF_JMP | BPF_JGT | BPF_K, BPF_REG_2, \ 27 | 0, _off, _size \ 28 | } 29 | 30 | #define ja(_off) \ 31 | { BPF_JMP | BPF_JA | BPF_K, 0, 0, _off, 0 } 32 | 33 | #define ldmap(_idx) \ 34 | { \ 35 | BPF_LD | BPF_IMM | BPF_DW, BPF_REG_1, \ 36 | BPF_PSEUDO_MAP_IDX_VALUE, 0, _idx \ 37 | }, \ 38 | { 0, 0, 0, 0, 0 } 39 | 40 | #define maybe_ldmap(_idx) \ 41 | jgt(kmem_bufsiz(_idx), 3), \ 42 | ldmap(_idx), \ 43 | ja((2 - (_idx)) * 4 + 2) 44 | 45 | /* Load arguments from ctx in R1 */ 46 | { 47 | BPF_LDX | BPF_MEM | BPF_DW, BPF_REG_3, 48 | BPF_REG_1, offsetof(struct kmem_args, addr), 0 49 | }, 50 | { 51 | BPF_LDX | BPF_MEM | BPF_H, BPF_REG_2, 52 | BPF_REG_1, offsetof(struct kmem_args, size), 0 53 | }, 54 | 55 | /* Select destination map based on size, to minimize copy size */ 56 | maybe_ldmap(0), 57 | maybe_ldmap(1), 58 | maybe_ldmap(2), 59 | ldmap(3), 60 | 61 | /* Copy requested region to the selected map */ 62 | { BPF_JMP | BPF_CALL | BPF_K, 0, 0, 0, BPF_FUNC_probe_read_kernel }, 63 | { BPF_JMP | BPF_EXIT | BPF_K, 0, 0, 0, 0 } 64 | 65 | #undef maybe_ldmap 66 | #undef ldmap 67 | #undef ja 68 | #undef jgt 69 | }; 70 | 71 | static int kmem_read_chunk(struct kmem *kmem, uint64_t addr, void *buf, size_t size) 72 | { 73 | struct kmem_args args = { 74 | .addr = addr, 75 | .size = size, 76 | }; 77 | struct bpf_test_run_opts runopts = { 78 | .sz = sizeof(runopts), 79 | .ctx_in = &args, 80 | .ctx_size_in = sizeof(args), 81 | }; 82 | const uint32_t idx = 0; 83 | int err, i; 84 | 85 | err = bpf_prog_test_run_opts(kmem->progfd, &runopts); 86 | if (err) 87 | return err; 88 | 89 | err = -1; 90 | for (i = 0; i < 4; i++) { 91 | if (size > kmem_bufsiz(i)) 92 | continue; 93 | 94 | err = bpf_map_lookup_elem(kmem->mapfd[i], &idx, kmem->buf); 95 | break; 96 | } 97 | 98 | memcpy(buf, kmem->buf, size); 99 | return err; 100 | } 101 | 102 | int kmem_read(struct kmem *kmem, uint64_t addr, void *buf, size_t size) 103 | { 104 | int err; 105 | 106 | for (err = 0; !err && (size > KMEM_BUFMAX); 107 | addr += KMEM_BUFMAX, buf += KMEM_BUFMAX, size -= KMEM_BUFMAX) 108 | err = kmem_read_chunk(kmem, addr, buf, KMEM_BUFMAX); 109 | 110 | return err ? : kmem_read_chunk(kmem, addr, buf, size); 111 | } 112 | 113 | int kmem_open(struct kmem *kmem) 114 | { 115 | struct bpf_prog_load_opts progopts = { 116 | .sz = sizeof(progopts), 117 | .kern_version = LINUX_VERSION_CODE, 118 | .fd_array = kmem->mapfd, 119 | 120 | .log_level = 7, 121 | .log_size = sizeof(kern_log), 122 | .log_buf = kern_log, 123 | }; 124 | int err, i; 125 | 126 | kmem->buf = malloc(KMEM_BUFMAX); 127 | if (!kmem->buf) { 128 | errno = ENOMEM; 129 | err = 1; 130 | goto err; 131 | } 132 | 133 | for (i = 0; i < 4; i++) { 134 | kmem->mapfd[i] = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, 135 | sizeof(uint32_t), 136 | kmem_bufsiz(i), 1, NULL); 137 | if (kmem->mapfd[i] < 0) { 138 | err = kmem->mapfd[i]; 139 | i--; 140 | goto err_close_maps; 141 | } 142 | } 143 | 144 | kmem->progfd = bpf_prog_load(BPF_PROG_TYPE_RAW_TRACEPOINT, NULL, "GPL", 145 | kmem_prog, 146 | sizeof(kmem_prog) / sizeof(kmem_prog[0]), 147 | &progopts); 148 | if (kmem->progfd < 0) { 149 | err = kmem->progfd; 150 | goto err_close_maps; 151 | } 152 | 153 | return 0; 154 | 155 | err_close_maps: 156 | for (; i >= 0; i--) 157 | close(kmem->mapfd[i]); 158 | 159 | free(kmem->buf); 160 | err: 161 | return err; 162 | } 163 | 164 | void kmem_close(struct kmem *kmem) 165 | { 166 | int i; 167 | 168 | close(kmem->progfd); 169 | 170 | for (i = 0; i < 4; i++) 171 | close(kmem->mapfd[i]); 172 | 173 | free(kmem->buf); 174 | } 175 | -------------------------------------------------------------------------------- /src/kmem.h: -------------------------------------------------------------------------------- 1 | #ifndef _KMEM_H 2 | #define _KMEM_H 3 | 4 | #include 5 | 6 | struct kmem { 7 | int progfd; 8 | int mapfd[4]; 9 | void *buf; 10 | }; 11 | 12 | int kmem_read(struct kmem *kmem, uint64_t addr, void *buf, size_t size); 13 | 14 | int kmem_open(struct kmem *kmem); 15 | void kmem_close(struct kmem *kmem); 16 | 17 | #endif /* _KMEM_H */ 18 | -------------------------------------------------------------------------------- /src/kmemd.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | #include "gdb.h" 19 | #include "kmem.h" 20 | 21 | /* 22 | * To lie convincingly enough to GDB that it is, in fact, talking to a 23 | * real debug stub, we have to respond to the 'g' packet with our 24 | * current register state. We fill these with all zeroes, but the 25 | * length must still match what GDB expects, based on the architecture 26 | * we're running on. 27 | * 28 | * The following is a list of the expected lengths for some common 29 | * platforms, mostly scraped from arch/$ARCH/include/asm/kgdb.h in the 30 | * kernel and by trail-and-error. On other systems, the user can 31 | * supply the information manually using the -g option. 32 | */ 33 | #if defined(__x86_64__) 34 | size_t gsize = 560; 35 | #elif defined(__i386__) 36 | size_t gsize = 312; 37 | #elif defined(__aarch64__) 38 | size_t gsize = 788; 39 | #elif defined(__arm__) 40 | size_t gsize = 168; 41 | #elif defined(__powerpc64__) 42 | size_t gsize = 1076; 43 | #elif defined(__powerpc__) 44 | size_t gsize = 932; 45 | #elif defined(__riscv_xlen) && __riscv_xlen == 64 46 | size_t gsize = 264; 47 | #elif defined(__riscv_xlen) && __riscv_xlen == 32 48 | size_t gsize = 132; 49 | #else 50 | size_t gsize = 0; 51 | #endif 52 | 53 | struct kmem kmem; 54 | 55 | struct serve_m_ctx { 56 | uint8_t *buf; 57 | size_t len; 58 | 59 | bool nibble; 60 | uint8_t hex[2]; 61 | }; 62 | 63 | int serve_m_next(void *_ctx) 64 | { 65 | struct serve_m_ctx *ctx = _ctx; 66 | 67 | if (ctx->nibble) { 68 | ctx->nibble = false; 69 | return ctx->hex[1]; 70 | } 71 | 72 | if (!ctx->len--) 73 | return EOF; 74 | 75 | gdb_bin2hex(ctx->buf++, ctx->hex, 1); 76 | ctx->nibble = true; 77 | 78 | return ctx->hex[0]; 79 | } 80 | 81 | int serve_m(struct gdb_session *session, uint8_t *pkt) 82 | { 83 | struct serve_m_ctx ctx = {}; 84 | unsigned long long addr; 85 | char *delim; 86 | void *buf; 87 | int err; 88 | 89 | addr = strtoull((char *)&pkt[1], &delim, 16); 90 | if (*delim != ',') 91 | return -EINVAL; 92 | 93 | delim++; 94 | 95 | ctx.len = strtoul(delim, NULL, 16); 96 | if (ctx.len == ULONG_MAX) 97 | return -EINVAL; 98 | 99 | buf = malloc(ctx.len); 100 | if (!buf) 101 | return -ENOMEM; 102 | 103 | err = kmem_read(&kmem, addr, buf, ctx.len); 104 | if (err) { 105 | free(buf); 106 | gdb_send(session, NULL, 0); 107 | return err; 108 | } 109 | 110 | ctx.buf = buf; 111 | err = gdb_send_iter(session, serve_m_next, &ctx); 112 | 113 | free(buf); 114 | return err; 115 | } 116 | 117 | int serve_g_next(void *_left) 118 | { 119 | size_t *left = _left; 120 | if ((*left)--) 121 | return '0'; 122 | 123 | return EOF; 124 | } 125 | 126 | int serve_g(struct gdb_session *session) 127 | { 128 | /* Two ASCII hex digits per byte */ 129 | size_t left = gsize * 2; 130 | 131 | return gdb_send_iter(session, serve_g_next, &left); 132 | } 133 | 134 | void serve(struct gdb_session *session) 135 | { 136 | uint8_t pkt[0x100]; 137 | int len, err = 0; 138 | 139 | if (gdb_debug) 140 | fprintf(stderr, "Session started\n"); 141 | 142 | while (!err && (len = gdb_recv(session, pkt, sizeof(pkt))) >= 0) { 143 | switch (pkt[0]) { 144 | case '?': 145 | err = gdb_send(session, "S05", 3); 146 | break; 147 | case 'g': 148 | err = serve_g(session); 149 | break; 150 | case 'm': 151 | err = serve_m(session, pkt); 152 | break; 153 | default: 154 | err = gdb_send(session, NULL, 0); 155 | } 156 | } 157 | 158 | if (gdb_debug) 159 | fprintf(stderr, "Session ended (len:%d err:%d)\n", len, err); 160 | } 161 | 162 | 163 | int serve_file(const char *path) 164 | { 165 | struct gdb_session session; 166 | 167 | session.rx = session.tx = fopen(path, "a+"); 168 | if (!session.rx) { 169 | fprintf(stderr, "Unable to open \"%s\": %m\n", path); 170 | return 1; 171 | } 172 | 173 | fprintf(stderr, "Opened %s\n", path); 174 | serve(&session); 175 | fclose(session.rx); 176 | return 0; 177 | } 178 | 179 | int bind_unix(const char *path) 180 | { 181 | struct sockaddr_un sa = { 182 | .sun_family = AF_UNIX, 183 | }; 184 | struct stat st; 185 | int err, sk; 186 | 187 | strcpy(sa.sun_path, path); 188 | 189 | sk = socket(AF_UNIX, SOCK_STREAM, 0); 190 | if (sk < 0) { 191 | perror("socket(unix)"); 192 | return sk; 193 | } 194 | 195 | err = stat(path, &st); 196 | if (!err && ((st.st_mode & S_IFMT) == S_IFSOCK)) 197 | unlink(sa.sun_path); 198 | 199 | err = bind(sk, (const struct sockaddr *) &sa, sizeof(sa)); 200 | if (err) { 201 | perror("bind(unix)"); 202 | return err; 203 | } 204 | 205 | return sk; 206 | } 207 | 208 | int bind_inet(const char *addr) 209 | { 210 | static const struct addrinfo hints = { 211 | .ai_flags = AI_PASSIVE | AI_V4MAPPED | AI_ADDRCONFIG, 212 | .ai_family = AF_UNSPEC, 213 | .ai_socktype = SOCK_STREAM, 214 | }; 215 | static const int enable = 1; 216 | 217 | struct addrinfo *ai, *ais; 218 | char *addr2, *host, *port; 219 | int err, sk; 220 | 221 | host = addr2 = strdup(addr); 222 | 223 | /* Port must be specified, so remove that first */ 224 | port = rindex(host, ':'); 225 | *(port++) = '\0'; 226 | 227 | switch (*host) { 228 | case '\0': 229 | /* : */ 230 | host = NULL; 231 | break; 232 | case '[': 233 | /* []: (RFC5952, section 6) */ 234 | if (host[strlen(host) - 1] == ']') { 235 | host[strlen(host) - 1] = '\0'; 236 | host++; 237 | } 238 | break; 239 | } 240 | 241 | err = getaddrinfo(host, port, &hints, &ais); 242 | free(addr2); 243 | if (err) { 244 | fprintf(stderr, "Unable to resolve %s\n", addr); 245 | return -1; 246 | } 247 | 248 | for (ai = ais; ai; ai = ai->ai_next) { 249 | sk = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); 250 | if (sk < 0) 251 | continue; 252 | 253 | err = setsockopt(sk, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, 254 | &enable, sizeof(enable)); 255 | if (err) 256 | goto try_next; 257 | 258 | err = bind(sk, ai->ai_addr, ai->ai_addrlen); 259 | if (err) 260 | goto try_next; 261 | 262 | freeaddrinfo(ais); 263 | return sk; 264 | 265 | try_next: 266 | close(sk); 267 | } 268 | 269 | freeaddrinfo(ais); 270 | 271 | fprintf(stderr, "Unable to bind to %s\n", addr); 272 | return -1; 273 | } 274 | 275 | int serve_sock(const char *addr) 276 | { 277 | struct gdb_session session; 278 | int err, sk, fd; 279 | 280 | if (strchr(addr, ':')) 281 | sk = bind_inet(addr); 282 | else 283 | sk = bind_unix(addr); 284 | 285 | if (sk < 0) 286 | return 1; 287 | 288 | err = listen(sk, 1); 289 | if (err) { 290 | perror("listen"); 291 | return 1; 292 | } 293 | 294 | fprintf(stderr, "Listening on %s\n", addr); 295 | 296 | for (;;) { 297 | fd = accept(sk, NULL, NULL); 298 | if (fd < 0) { 299 | perror("accept"); 300 | break; 301 | } 302 | 303 | session.rx = fdopen(dup(fd), "r"); 304 | session.tx = fdopen(dup(fd), "w"); 305 | if (!session.rx || !session.tx) { 306 | perror("fdopen"); 307 | break; 308 | } 309 | 310 | serve(&session); 311 | 312 | fclose(session.tx); 313 | fclose(session.rx); 314 | close(fd); 315 | } 316 | 317 | return 0; 318 | } 319 | 320 | static void usage() 321 | { 322 | fputs("kmemd - Serve live kernel memory over GDB RSP\n" 323 | "\n" 324 | "Usage:\n" 325 | " kmemd [options] [-s ] -- Listen on UNIX socket\n" 326 | " kmemd [options] -s []: -- Listen on TCP socket\n" 327 | " kmemd [options] -f -- Communicate using file\n" 328 | "\n" 329 | " By default, kmemd listens on the named UNIX domain\n" 330 | " socket /run/kmemd.sock\n" 331 | "\n" 332 | "Options:\n" 333 | " -d Enable debug output.\n" 334 | " -f PATH Use file for communicating with GDB.\n" 335 | " -g SIZE Reply size of 'g' messages (0 - 4k).\n" 336 | " -h Print usage message and exit.\n" 337 | " -s ADDRESS Listen for GDB connections on UNIX or TCP socket.\n" 338 | " -v Print version information.\n", 339 | stderr); 340 | } 341 | 342 | static const char *sopts = "df:g:hs:v"; 343 | static struct option lopts[] = { 344 | { "debug", no_argument, 0, 'd' }, 345 | { "file", required_argument, 0, 'f' }, 346 | { "g-size", required_argument, 0, 'g' }, 347 | { "help", no_argument, 0, 'h' }, 348 | { "socket", required_argument, 0, 's' }, 349 | { "version", no_argument, 0, 'v' }, 350 | 351 | { NULL } 352 | }; 353 | 354 | int main(int argc, char **argv) 355 | { 356 | char *file = NULL, *sock = "/run/kmemd.sock"; 357 | int err, opt; 358 | unsigned long g; 359 | 360 | while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) > 0) { 361 | switch (opt) { 362 | case 'd': 363 | gdb_debug++; 364 | break; 365 | case 'f': 366 | file = optarg; 367 | break; 368 | case 'g': 369 | g = strtoul(optarg, NULL, 0); 370 | if (g > (4 << 10)) { 371 | fprintf(stderr, "Invalid g size '%s'\n\n", optarg); 372 | usage(); 373 | exit(1); 374 | } 375 | 376 | gsize = g; 377 | break; 378 | case 'h': 379 | usage(); 380 | return 0; 381 | case 's': 382 | sock = optarg; 383 | break; 384 | case 'v': 385 | puts(PACKAGE_STRING); 386 | return 0; 387 | 388 | default: 389 | fprintf(stderr, "Unknown option '%c'\n\n", opt); 390 | usage(); 391 | return 1; 392 | } 393 | } 394 | 395 | if (!gsize) { 396 | fprintf(stderr, 397 | "Size of 'g' packet is not known, " 398 | "please supply via -g option\n"); 399 | usage(); 400 | return 1; 401 | } else if (gdb_debug) { 402 | fprintf(stderr, "Using 'g' size of %zu bytes\n", gsize); 403 | } 404 | 405 | err = kmem_open(&kmem); 406 | if (err) { 407 | fprintf(stderr, "Unable to create kernel memory reader: %m\n"); 408 | return 1; 409 | } 410 | 411 | return file ? serve_file(file) : serve_sock(sock); 412 | } 413 | --------------------------------------------------------------------------------