├── LICENSE ├── README.md └── tool └── webshell-detector ├── .gitignore ├── README.md ├── bin ├── detector.go └── static │ ├── config │ ├── rules.conf │ └── statState.json │ └── model-latest │ ├── OpSerial.model │ ├── Processor.model │ ├── SampleHash.txt │ ├── Words.model │ └── hashState.json ├── php ├── .gitignore ├── Makefile ├── patches │ ├── 0001-eliminate-libresolv.patch │ ├── 0002-eliminate-libnsl.patch │ ├── 0003-eliminate-libdl.patch │ ├── 0004-eliminate-librt.patch │ ├── 0005-expose-phar_open_from_fp-as-PHP_PHAR_API.patch │ ├── 0006-integrate-github.com-nikic-php-ast.patch │ ├── 0007-use-alias-in-opened_path-for-phar-stream-wrapper.patch │ └── 0008-expose-an-API-that-increment-refcount-of-phar_archiv.patch ├── payload │ └── index.php ├── php.c └── php.go ├── src ├── Ast.go ├── AstNode.go ├── Ast_test.go ├── BinData.go ├── BinData_test.go ├── Detector.go ├── Detector_test.go ├── OpSerial.go ├── OpSerial_test.go ├── PhpAstGen.go ├── PhpAstGen_test.go ├── Processor.go ├── Processor_test.go ├── RegMatcher.go ├── RegMatcher_test.go ├── SampleMatcher.go ├── SampleMatcher_test.go ├── Stat.go ├── Stat_test.go ├── Words.go ├── Words_test.go ├── genOpSerialData_test.go ├── genProcessorData_test.go ├── genWordsData_test.go └── main_test.go └── static ├── output-cli.png └── webshell-test-html.png /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 | CloudWalker Cloud Workload Protection Platform 635 | Copyright (C) 2018 Chaitin Tech 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 | CloudWalker Copyright (C) 2018 Chaitin Tech 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 | **本项目停止更新,感谢一直以来的支持。** 2 | 3 | **长亭科技已发布[牧云企业版](https://www.chaitin.cn/zh/cloudwalker),敬请关注。** 4 | 5 | **牧云企业版的全新 webshell 检测能力可以在 [Xray 社区](https://stack.chaitin.com/security-challenge/webshell/index) 体验,批量检测 API 可以通过[百川云平台](https://rivers.chaitin.cn/) 接入。** 6 | 7 | # CloudWalker(牧云)开源计划 8 | 9 | CloudWalker(牧云)是长亭推出的一款开源服务器安全管理平台。根据项目计划会逐步覆盖服务器资产管理、威胁扫描、Webshell 查杀、基线检测等各项功能。 10 | 11 | 本次开源作为开源计划的第一步,仅包含 Webshell 检测引擎部分,重点调优 Webshell 检测效果。目前放出的是一个可执行的命令行版本 Webshell 检测工具。 12 | 13 | # 下载地址 14 | 15 | 工具打包形式为单个可执行文件,下载之后添加可执行权限即可执行。 16 | 17 | [Release 页面](https://github.com/chaitin/cloudwalker/releases) 18 | 19 | # 使用方式 20 | 21 | ``` 22 | $ ./webshell-detector /path/to/your-web-root/ /var/www/html /path/to/some-file 23 | ``` 24 | 25 | ![output-cli.png](tool/webshell-detector/static/output-cli.png) 26 | 27 | ## 输出 HTML 报告 28 | 29 | ``` 30 | $ ./webshell-detector -html -output result.html /path/to/web-root/ 31 | ``` 32 | 33 | 输出报告样例如下: 34 | 35 | ![webshell-output-html.png](tool/webshell-detector/static/webshell-test-html.png) 36 | 37 | ## 输出结果描述 38 | 39 | 目前检测结果分为 5 个级别,级别越高说明检测出 Webshell 的可能性越高,如果没有级别说明不存在 Webshell 风险。 40 | 41 | ## 线上测试 Demo 地址 42 | 43 | 线上测试 Demo 地址:https://webshellchop.chaitin.cn/ 44 | 45 | (注意:线上 Demo 代码检测效果可能有微弱差异) 46 | 47 | ## 支持系统与版本 48 | 49 | - 主流 Linux 发行版(内核不能太老,至少 2.6.32,否则会由于 Go 语言不支持直接打印 FATAL: kernel too old) 50 | - MacOS 可自行编译 51 | - Windows 暂不支持 52 | 53 | # Roadmap and TODO List 54 | 55 | - 整理完成产品框架代码并开源 56 | - 实现统一插件管理与通信机制 57 | - 提供插件 SDK 58 | - 文档、Demo 等 59 | 60 | # License 61 | 62 | [GPLv3](LICENSE) 63 | 64 | -------------------------------------------------------------------------------- /tool/webshell-detector/.gitignore: -------------------------------------------------------------------------------- 1 | # GoLand cache dir 2 | .idea/ 3 | 4 | # VSCode config 5 | .vscode/ 6 | 7 | # Mac OS X file 8 | .DS_Store 9 | 10 | # Binaries for programs and plugins 11 | *.exe 12 | *.exe~ 13 | *.dll 14 | *.so 15 | *.dylib 16 | 17 | # Test binary, build with `go test -c` 18 | *.test 19 | 20 | # Output of the go coverage tool, specifically when used with LiteIDE 21 | *.out 22 | -------------------------------------------------------------------------------- /tool/webshell-detector/README.md: -------------------------------------------------------------------------------- 1 | # Webshell detector 2 | 3 | ## Installation 4 | 5 | Standalone binary can be downloaded at . 6 | 7 | ## Usage 8 | 9 | ``` 10 | ./webshell-detector-linux-amd64 -h 11 | Chaitin CloudWalker Webshell Detector 12 | [version 1.0.0] 13 | 14 | usage: ./webshell-detector-linux-amd64 [options] name ... 15 | 16 | -html 17 | Show result as HTML 18 | -output string 19 | Export result to output file 20 | ``` 21 | 22 | ## Build 23 | 24 | ### Dependencies 25 | 26 | For Ubuntu and Debian users: 27 | 28 | ``` 29 | apt-get install autoconf bzip2 patch vim 30 | ``` 31 | 32 | ### Build the detector 33 | 34 | ``` 35 | make -C php 36 | go get -d ./src 37 | go build -o webshell-detector ./bin 38 | ``` 39 | -------------------------------------------------------------------------------- /tool/webshell-detector/bin/detector.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "strings" 11 | "time" 12 | 13 | "../php" 14 | "../src" 15 | ) 16 | 17 | var outputPtr *string 18 | var htmlPtr *bool 19 | var detector *WebshellDetector.Detector 20 | var countRisk = 0 21 | var countRisk1 = 0 22 | var countRisk2 = 0 23 | var countRisk3 = 0 24 | var countRisk4 = 0 25 | var countRisk5 = 0 26 | var countFile = 0 27 | var t0 = time.Now() 28 | var err error 29 | 30 | func walk(path string, info os.FileInfo, _ error) error { 31 | 32 | countFile++ 33 | 34 | if strings.ToLower(filepath.Ext(path)) != ".php" && 35 | strings.ToLower(filepath.Ext(path)) != ".phpt" && 36 | strings.ToLower(filepath.Ext(path)) != ".php3" && 37 | strings.ToLower(filepath.Ext(path)) != ".php4" && 38 | strings.ToLower(filepath.Ext(path)) != ".php5" && 39 | strings.ToLower(filepath.Ext(path)) != ".txt" && 40 | strings.ToLower(filepath.Ext(path)) != ".bak" { 41 | return nil 42 | } 43 | src, err := ioutil.ReadFile(path) 44 | if err != nil { 45 | log.Fatal(err) 46 | } 47 | score, err := detector.Predict(src) 48 | // if err != nil { 49 | // log.Fatal(err) 50 | // } 51 | for i := 0; i < 128; i++ { 52 | fmt.Printf("\b") 53 | } 54 | fmt.Printf("\rTesting %-50s / %d risks / Runtime %v", info.Name(), countRisk, time.Since(t0)) 55 | if score > 0 { 56 | countRisk++ 57 | var risk int 58 | switch score { 59 | case 1, 2: 60 | risk = 1 61 | countRisk1++ 62 | case 3: 63 | risk = 2 64 | countRisk2++ 65 | case 4: 66 | risk = 3 67 | countRisk3++ 68 | case 5: 69 | risk = 4 70 | countRisk4++ 71 | case 6, 7: 72 | risk = 5 73 | countRisk5++ 74 | default: 75 | risk = 0 76 | } 77 | printResult(countFile, path, risk) 78 | } 79 | return nil 80 | } 81 | 82 | func multiTest(detectPath string) { 83 | if err != nil { 84 | log.Fatal(err) 85 | } 86 | filepath.Walk(detectPath, walk) 87 | } 88 | 89 | func singleTest(path string) { 90 | 91 | countFile++ 92 | 93 | if err != nil { 94 | log.Fatal(err) 95 | } 96 | src, err := ioutil.ReadFile(path) 97 | if err != nil { 98 | log.Fatal(err) 99 | } 100 | score, err := detector.Predict(src) 101 | if err != nil { 102 | log.Fatal(err) 103 | } 104 | if score > 0 { 105 | var risk int 106 | switch score { 107 | case 1, 2: 108 | risk = 1 109 | countRisk1++ 110 | case 3: 111 | risk = 2 112 | countRisk2++ 113 | case 4: 114 | risk = 3 115 | countRisk3++ 116 | case 5: 117 | risk = 4 118 | countRisk4++ 119 | case 6, 7: 120 | risk = 5 121 | countRisk5++ 122 | default: 123 | risk = 0 124 | } 125 | printResult(countFile, path, risk) 126 | } 127 | } 128 | 129 | func printResult(fileIndex int, filePath string, fileRisk int) { 130 | var res string 131 | if len(filePath) > 80 && !*htmlPtr { 132 | filePath = "..." + filePath[len(filePath)-77:len(filePath)] 133 | } 134 | if *htmlPtr { 135 | res = fmt.Sprintf("%08d%s%d\n", fileIndex, filePath, fileRisk) 136 | } else { 137 | res = fmt.Sprintf("[+] %08d %-80s Risk:%d\n", fileIndex, filePath, fileRisk) 138 | } 139 | if *outputPtr != "" { 140 | outputFile, err := os.OpenFile(*outputPtr, os.O_WRONLY|os.O_APPEND, 0600) 141 | if err != nil { 142 | log.Fatal(err) 143 | } 144 | outputFile.WriteString(res) 145 | outputFile.Close() 146 | } else { 147 | for i := 0; i < 128; i++ { 148 | fmt.Printf("\b") 149 | } 150 | fmt.Print(res) 151 | } 152 | } 153 | 154 | func work(files []string) { 155 | for _, v := range files { 156 | info, err := os.Stat(v) 157 | if err != nil { 158 | log.Fatal(err) 159 | } 160 | if info.IsDir() { 161 | log.Printf("Testing %s...", v) 162 | truePath, err := filepath.EvalSymlinks(v) 163 | if err != nil { 164 | log.Fatal(err) 165 | } 166 | multiTest(truePath) 167 | } else { 168 | singleTest(v) 169 | } 170 | } 171 | } 172 | 173 | func main() { 174 | version := "1.0.0" 175 | flag.Usage = func() { 176 | fmt.Fprintf(flag.CommandLine.Output(), "Chaitin CloudWalker Webshell Detector\n[version %s]\n\nusage: %s [options] name ...\n\n", version, os.Args[0]) 177 | flag.PrintDefaults() 178 | } 179 | outputPtr = flag.String("output", "", "Export result to output file") 180 | htmlPtr = flag.Bool("html", false, "Show result as HTML") 181 | flag.Parse() 182 | if len(flag.Args()) == 0 { 183 | flag.Usage() 184 | } 185 | files := flag.Args() 186 | php.Start() 187 | detector, err = WebshellDetector.NewDefaultDetector(php.Stdin, php.Stdout) 188 | if err != nil { 189 | log.Println("Detector kernel cannot load.") 190 | } 191 | if *outputPtr != "" { 192 | outputFile, err := os.OpenFile(*outputPtr, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600) 193 | if err != nil { 194 | log.Fatal(err) 195 | } 196 | if *htmlPtr { 197 | nowStr := time.Now().Format("2006-01-02 15:04:05") 198 | outputFile.WriteString(` 199 | 200 | 201 | 202 | Report - Chaitin CloudWalker 203 | 204 | 259 | 260 |
261 |

   Chaitin CloudWalker Webshell Detector

262 |
263 |
264 |

Report

265 |

Time: ` + nowStr + `

266 | 267 | 268 | 269 | 270 | 277 | 278 | 279 | 286 |

Tested 271 | Risk:1 272 | Risk:2 273 | Risk:3 274 | Risk:4 275 | Risk:5 276 |
Waiting 280 | Waiting 281 | Waiting 282 | Waiting 283 | Waiting 284 | Waiting 285 |
287 | 288 | 289 | 290 | 291 | 295 | `) 296 | outputFile.Close() 297 | } 298 | work(files) 299 | outputFile, err = os.OpenFile(*outputPtr, os.O_WRONLY|os.O_APPEND, 0600) 300 | if err != nil { 301 | log.Fatal(err) 302 | } 303 | if *htmlPtr { 304 | outputFile.WriteString(fmt.Sprintf(`

Index 292 | File 293 | Risk 294 |
`, countFile, countRisk1, countRisk2, countRisk3, countRisk4, countRisk5)) 312 | outputFile.Close() 313 | } 314 | } else { 315 | fmt.Println(" _____ _ ___ __ _ _") 316 | fmt.Println(" / ____| | | \\ \\ / / | | |") 317 | fmt.Println("| | | | ___ _ _ __| |\\ \\ /\\ / /_ _| | | _____ _ __ __ ___ ") 318 | fmt.Println("| | | |/ _ \\| | | |/ _` | \\ \\/ \\/ / _` | | |/ / _ \\ '__| /_ | / _ \\ ") 319 | fmt.Println("| |____| | (_) | |_| | (_| | \\ /\\ / (_| | | < __/ | | | ||_||") 320 | fmt.Println(" \\_____|_|\\___/ \\__,_|\\__,_| \\/ \\/ \\__,_|_|_|\\_\\___|_| |_(_)___/ \n") 321 | log.Println("Detector started.") 322 | 323 | work(files) 324 | 325 | for i := 0; i < 256; i++ { 326 | fmt.Printf("\b") 327 | } 328 | fmt.Print("\n\n") 329 | log.Printf("Risk (level1): %d files", countRisk1) 330 | log.Printf("Risk (level2): %d files", countRisk2) 331 | log.Printf("Risk (level3): %d files", countRisk3) 332 | log.Printf("Risk (level4): %d files", countRisk4) 333 | log.Printf("Risk (level5): %d files", countRisk5) 334 | log.Printf("Tested: %d files", countFile) 335 | 336 | fmt.Print("\n\n") 337 | log.Printf("Detector done (%v).\n", time.Since(t0)) 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /tool/webshell-detector/bin/static/config/statState.json: -------------------------------------------------------------------------------- 1 | { 2 | "MinStat": { 3 | "LVC": 0.1, 4 | "SR": 10, 5 | "SPL": 0.001 6 | }, 7 | "MaxStat": { 8 | "LM": 2048, 9 | "WM": 1024 10 | } 11 | } -------------------------------------------------------------------------------- /tool/webshell-detector/bin/static/model-latest/Words.model: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaitin/cloudwalker/d0a30200a3c498df03db1e527548a2c90baa1bd2/tool/webshell-detector/bin/static/model-latest/Words.model -------------------------------------------------------------------------------- /tool/webshell-detector/php/.gitignore: -------------------------------------------------------------------------------- 1 | # macOS Finder metadata 2 | .DS_Store 3 | 4 | # build 5 | /bin/ 6 | /include/ 7 | /lib/ 8 | /payload-phar.c 9 | /payload.phar 10 | /php-* 11 | /php/ 12 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/Makefile: -------------------------------------------------------------------------------- 1 | PHP_RELEASE := 7.2.10 2 | PHP_MIRROR := http://php.net 3 | 4 | PHP_MAJOR := $(firstword $(subst ., ,$(PHP_RELEASE))) 5 | PHP_SRC := php-$(PHP_RELEASE).tar.bz2 6 | PHP_DIR := php-$(PHP_RELEASE) 7 | PHP := bin/php 8 | PHP_INC := include/php 9 | PHP_LIB := lib/libphp$(PHP_MAJOR).a 10 | 11 | # these flags are not exported and will not affect PHP build 12 | CFLAGS := -g -Wall -Wextra -Werror -Iinclude/php -I$(PHP_INC)/Zend -I$(PHP_INC)/TSRM -I$(PHP_INC)/main 13 | LDFLAGS := -lm 14 | 15 | all: $(PHP_LIB) payload-phar.c 16 | 17 | .PHONY: all clean distclean 18 | 19 | clean: 20 | $(RM) -r $(PHP_DIR) bin include lib payload.phar payload-phar.c 21 | 22 | distclean: clean 23 | $(RM) $(PHP_SRC) 24 | 25 | $(PHP_SRC): 26 | wget --no-verbose $(PHP_MIRROR)/distributions/$(PHP_SRC) 27 | 28 | $(PHP): $(PHP_SRC) 29 | tar --extract --file $(PHP_SRC) 30 | cd $(PHP_DIR) && for PATCHFILE in ../patches/*.patch; do echo "applying $${PATCHFILE}" && patch -p1 <"$${PATCHFILE}"; done 31 | cd $(PHP_DIR) && ./buildconf --force && CFLAGS=-O2 ./configure --prefix='$(realpath .)' --enable-embed=static --disable-phpdbg --disable-cgi --disable-all --enable-ast --enable-ctype --enable-filter --enable-json --enable-tokenizer --enable-phar --without-pear --enable-debug 32 | $(MAKE) -C $(PHP_DIR) install-cli install-headers install-sapi 33 | 34 | # dummy rule 35 | $(PHP_LIB): $(PHP) 36 | 37 | # FIXME: incomplete dependency 38 | payload.phar: $(PHP) 39 | $(PHP) --define phar.readonly=0 --run '$$phar = new Phar("payload.phar"); $$phar->buildFromDirectory(dirname(__FILE__) . "/payload"); $$phar->setStub($$phar->createDefaultStub("index.php"));' 40 | 41 | payload-phar.c: payload.phar 42 | xxd -i $< >$@ 43 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0001-eliminate-libresolv.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Wed, 27 Jun 2018 16:15:11 +0800 4 | Subject: [PATCH] eliminate libresolv 5 | 6 | --- 7 | ext/standard/config.m4 | 13 ++++++------- 8 | 1 file changed, 6 insertions(+), 7 deletions(-) 9 | 10 | diff --git a/ext/standard/config.m4 b/ext/standard/config.m4 11 | index b800aaa1..9833898a 100644 12 | --- a/ext/standard/config.m4 13 | +++ b/ext/standard/config.m4 14 | @@ -339,17 +339,16 @@ dnl 15 | dnl Detect library functions needed by php dns_xxx functions 16 | dnl ext/standard/php_dns.h will collect these in a single define: HAVE_FULL_DNS_FUNCS 17 | dnl 18 | -PHP_CHECK_FUNC(res_nsearch, resolv, bind, socket) 19 | -PHP_CHECK_FUNC(res_ndestroy, resolv, bind, socket) 20 | -PHP_CHECK_FUNC(dns_search, resolv, bind, socket) 21 | -PHP_CHECK_FUNC(dn_expand, resolv, bind, socket) 22 | -PHP_CHECK_FUNC(dn_skipname, resolv, bind, socket) 23 | +#PHP_CHECK_FUNC(res_nsearch, resolv, bind, socket) 24 | +#PHP_CHECK_FUNC(res_ndestroy, resolv, bind, socket) 25 | +#PHP_CHECK_FUNC(dns_search, resolv, bind, socket) 26 | +#PHP_CHECK_FUNC(dn_expand, resolv, bind, socket) 27 | +#PHP_CHECK_FUNC(dn_skipname, resolv, bind, socket) 28 | 29 | dnl 30 | dnl These are old deprecated functions 31 | dnl 32 | - 33 | -PHP_CHECK_FUNC(res_search, resolv, bind, socket) 34 | +#PHP_CHECK_FUNC(res_search, resolv, bind, socket) 35 | 36 | dnl 37 | dnl Check for strptime() 38 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0002-eliminate-libnsl.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Sat, 29 Sep 2018 22:31:10 +0800 4 | Subject: [PATCH] eliminate libnsl 5 | 6 | --- 7 | TSRM/tsrm.m4 | 4 ++-- 8 | configure.ac | 12 +++++------- 9 | ext/standard/dns.c | 6 +++--- 10 | ext/standard/filestat.c | 4 ++-- 11 | main/fopen_wrappers.c | 2 +- 12 | main/main.c | 2 +- 13 | main/network.c | 2 +- 14 | 7 files changed, 15 insertions(+), 17 deletions(-) 15 | 16 | diff --git a/TSRM/tsrm.m4 b/TSRM/tsrm.m4 17 | index 98aa2b8c..7d3f7852 100644 18 | --- a/TSRM/tsrm.m4 19 | +++ b/TSRM/tsrm.m4 20 | @@ -1,4 +1,4 @@ 21 | -m4_include([TSRM/m4/gethostbyname.m4]) 22 | +#m4_include([TSRM/m4/gethostbyname.m4]) 23 | 24 | dnl TSRM_CHECK_GCC_ARG(ARG, ACTION-IF-FOUND, ACTION-IF-NOT_FOUND) 25 | AC_DEFUN([TSRM_CHECK_GCC_ARG],[ 26 | @@ -33,7 +33,7 @@ AC_CHECK_HEADERS(stdarg.h) 27 | 28 | AC_CHECK_FUNCS(sigprocmask) 29 | 30 | -AX_FUNC_WHICH_GETHOSTBYNAME_R() 31 | +#AX_FUNC_WHICH_GETHOSTBYNAME_R() 32 | 33 | ]) 34 | 35 | diff --git a/configure.ac b/configure.ac 36 | index 974c7b08..ff48a4df 100644 37 | --- a/configure.ac 38 | +++ b/configure.ac 39 | @@ -418,9 +418,9 @@ dnl Also, uClibc will bark at linking with glibc's libnsl. 40 | PHP_CHECK_FUNC(socket, socket) 41 | PHP_CHECK_FUNC(socketpair, socket) 42 | PHP_CHECK_FUNC(htonl, socket) 43 | -PHP_CHECK_FUNC(gethostname, nsl) 44 | -PHP_CHECK_FUNC(gethostbyaddr, nsl) 45 | -PHP_CHECK_FUNC(yp_get_default_domain, nsl) 46 | +#PHP_CHECK_FUNC(gethostname, nsl) 47 | +#PHP_CHECK_FUNC(gethostbyaddr, nsl) 48 | +#PHP_CHECK_FUNC(yp_get_default_domain, nsl) 49 | 50 | PHP_CHECK_FUNC(dlopen, dl) 51 | if test "$ac_cv_func_dlopen" = "yes"; then 52 | @@ -610,10 +610,6 @@ gai_strerror \ 53 | gcvt \ 54 | getloadavg \ 55 | getlogin \ 56 | -getprotobyname \ 57 | -getprotobynumber \ 58 | -getservbyname \ 59 | -getservbyport \ 60 | gethostname \ 61 | getrusage \ 62 | gettimeofday \ 63 | @@ -684,6 +680,7 @@ nanosleep \ 64 | dnl Some systems (like OpenSolaris) do not have nanosleep in libc 65 | PHP_CHECK_FUNC_LIB(nanosleep, rt) 66 | 67 | +if false; then 68 | dnl Check for getaddrinfo, should be a better way, but... 69 | dnl Also check for working getaddrinfo 70 | AC_CACHE_CHECK([for getaddrinfo], ac_cv_func_getaddrinfo, 71 | @@ -730,6 +727,7 @@ ac_cv_func_getaddrinfo=no)]) 72 | if test "$ac_cv_func_getaddrinfo" = yes; then 73 | AC_DEFINE(HAVE_GETADDRINFO,1,[Define if you have the getaddrinfo function]) 74 | fi 75 | +fi 76 | 77 | dnl Check for the __sync_fetch_and_add builtin 78 | AC_CACHE_CHECK([for __sync_fetch_and_add], ac_cv_func_sync_fetch_and_add, 79 | diff --git a/ext/standard/dns.c b/ext/standard/dns.c 80 | index fb21d6dd..13af9727 100644 81 | --- a/ext/standard/dns.c 82 | +++ b/ext/standard/dns.c 83 | @@ -184,9 +184,9 @@ static zend_string *php_gethostbyaddr(char *ip) 84 | 85 | #if HAVE_IPV6 && HAVE_INET_PTON 86 | if (inet_pton(AF_INET6, ip, &addr6)) { 87 | - hp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6); 88 | + hp = NULL; 89 | } else if (inet_pton(AF_INET, ip, &addr)) { 90 | - hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); 91 | + hp = NULL; 92 | } else { 93 | return NULL; 94 | } 95 | @@ -197,7 +197,7 @@ static zend_string *php_gethostbyaddr(char *ip) 96 | return NULL; 97 | } 98 | 99 | - hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET); 100 | + hp = NULL; 101 | #endif 102 | 103 | if (!hp || hp->h_name == NULL || hp->h_name[0] == '\0') { 104 | diff --git a/ext/standard/filestat.c b/ext/standard/filestat.c 105 | index e730b5ae..a4839585 100644 106 | --- a/ext/standard/filestat.c 107 | +++ b/ext/standard/filestat.c 108 | @@ -315,7 +315,7 @@ PHPAPI int php_get_gid_by_name(const char *name, gid_t *gid) 109 | efree(grbuf); 110 | *gid = gr.gr_gid; 111 | #else 112 | - struct group *gr = getgrnam(name); 113 | + struct group *gr = NULL; 114 | 115 | if (!gr) { 116 | return FAILURE; 117 | @@ -451,7 +451,7 @@ PHPAPI uid_t php_get_uid_by_name(const char *name, uid_t *uid) 118 | efree(pwbuf); 119 | *uid = pw.pw_uid; 120 | #else 121 | - struct passwd *pw = getpwnam(name); 122 | + struct passwd *pw = NULL; 123 | 124 | if (!pw) { 125 | return FAILURE; 126 | diff --git a/main/fopen_wrappers.c b/main/fopen_wrappers.c 127 | index 520edfad..03feb87c 100644 128 | --- a/main/fopen_wrappers.c 129 | +++ b/main/fopen_wrappers.c 130 | @@ -389,7 +389,7 @@ PHPAPI int php_fopen_primary_script(zend_file_handle *file_handle) 131 | return FAILURE; 132 | } 133 | #else 134 | - pw = getpwnam(user); 135 | + pw = NULL; 136 | #endif 137 | if (pw && pw->pw_dir) { 138 | spprintf(&filename, 0, "%s%c%s%c%s", pw->pw_dir, PHP_DIR_SEPARATOR, PG(user_dir), PHP_DIR_SEPARATOR, s + 1); /* Safe */ 139 | diff --git a/main/main.c b/main/main.c 140 | index ee92bcc7..4049f4d1 100644 141 | --- a/main/main.c 142 | +++ b/main/main.c 143 | @@ -1329,7 +1329,7 @@ PHPAPI char *php_get_current_user(void) 144 | } 145 | pwd = &_pw; 146 | #else 147 | - if ((pwd=getpwuid(pstat->st_uid))==NULL) { 148 | + if (1) { 149 | return ""; 150 | } 151 | #endif 152 | diff --git a/main/network.c b/main/network.c 153 | index 30e22003..002861fb 100644 154 | --- a/main/network.c 155 | +++ b/main/network.c 156 | @@ -1340,7 +1340,7 @@ struct hostent * gethostname_re (const char *host,struct hostent *hostbuf,char * 157 | 158 | PHPAPI struct hostent* php_network_gethostbyname(char *name) { 159 | #if !defined(HAVE_GETHOSTBYNAME_R) 160 | - return gethostbyname(name); 161 | + return NULL; 162 | #else 163 | if (FG(tmp_host_buf)) { 164 | free(FG(tmp_host_buf)); 165 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0003-eliminate-libdl.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Wed, 27 Jun 2018 17:08:57 +0800 4 | Subject: [PATCH] eliminate libdl 5 | 6 | --- 7 | Zend/Zend.m4 | 2 ++ 8 | Zend/zend_portability.h | 2 +- 9 | configure.ac | 2 ++ 10 | 3 files changed, 5 insertions(+), 1 deletion(-) 11 | 12 | diff --git a/Zend/Zend.m4 b/Zend/Zend.m4 13 | index 7a01c0b0..8a4a5a11 100644 14 | --- a/Zend/Zend.m4 15 | +++ b/Zend/Zend.m4 16 | @@ -66,8 +66,10 @@ AC_TYPE_SIZE_T 17 | AC_TYPE_SIGNAL 18 | 19 | AC_DEFUN([LIBZEND_LIBDL_CHECKS],[ 20 | +if false; then 21 | AC_CHECK_LIB(dl, dlopen, [LIBS="-ldl $LIBS"]) 22 | AC_CHECK_FUNC(dlopen,[AC_DEFINE(HAVE_LIBDL, 1,[ ])]) 23 | +fi 24 | ]) 25 | 26 | AC_DEFUN([LIBZEND_DLSYM_CHECK],[ 27 | diff --git a/Zend/zend_portability.h b/Zend/zend_portability.h 28 | index 79632f65..6e581e7c 100644 29 | --- a/Zend/zend_portability.h 30 | +++ b/Zend/zend_portability.h 31 | @@ -159,7 +159,7 @@ 32 | # define DL_ERROR dlerror 33 | # define DL_HANDLE void * 34 | # define ZEND_EXTENSIONS_SUPPORT 1 35 | -#elif defined(ZEND_WIN32) 36 | +#elif 0 37 | # define DL_LOAD(libname) LoadLibrary(libname) 38 | # define DL_FETCH_SYMBOL GetProcAddress 39 | # define DL_UNLOAD FreeLibrary 40 | diff --git a/configure.ac b/configure.ac 41 | index ff48a4df..8df71f77 100644 42 | --- a/configure.ac 43 | +++ b/configure.ac 44 | @@ -422,10 +422,12 @@ PHP_CHECK_FUNC(htonl, socket) 45 | #PHP_CHECK_FUNC(gethostbyaddr, nsl) 46 | #PHP_CHECK_FUNC(yp_get_default_domain, nsl) 47 | 48 | +if false; then 49 | PHP_CHECK_FUNC(dlopen, dl) 50 | if test "$ac_cv_func_dlopen" = "yes"; then 51 | AC_DEFINE(HAVE_LIBDL, 1, [ ]) 52 | fi 53 | +fi 54 | AC_CHECK_LIB(m, sin) 55 | 56 | dnl Check for inet_aton 57 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0004-eliminate-librt.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Fri, 29 Jun 2018 16:23:08 +0800 4 | Subject: [PATCH] eliminate librt 5 | 6 | --- 7 | configure.ac | 2 +- 8 | 1 file changed, 1 insertion(+), 1 deletion(-) 9 | 10 | diff --git a/configure.ac b/configure.ac 11 | index 8df71f77..2fd8fc9f 100644 12 | --- a/configure.ac 13 | +++ b/configure.ac 14 | @@ -680,7 +680,7 @@ nanosleep \ 15 | ) 16 | 17 | dnl Some systems (like OpenSolaris) do not have nanosleep in libc 18 | -PHP_CHECK_FUNC_LIB(nanosleep, rt) 19 | +PHP_CHECK_FUNC(nanosleep) 20 | 21 | if false; then 22 | dnl Check for getaddrinfo, should be a better way, but... 23 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0005-expose-phar_open_from_fp-as-PHP_PHAR_API.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Tue, 25 Sep 2018 15:06:40 +0800 4 | Subject: [PATCH] expose phar_open_from_fp as PHP_PHAR_API 5 | 6 | --- 7 | ext/phar/phar.c | 2 +- 8 | ext/phar/phar_internal.h | 2 -- 9 | ext/phar/php_phar.h | 4 +++- 10 | 3 files changed, 4 insertions(+), 4 deletions(-) 11 | 12 | diff --git a/ext/phar/phar.c b/ext/phar/phar.c 13 | index c1c57120..5633164c 100644 14 | --- a/ext/phar/phar.c 15 | +++ b/ext/phar/phar.c 16 | @@ -1553,7 +1553,7 @@ static inline char *phar_strnstr(const char *buf, int buf_len, const char *searc 17 | * that the manifest is proper, then pass it to phar_parse_pharfile(). SUCCESS 18 | * or FAILURE is returned and pphar is set to a pointer to the phar's manifest 19 | */ 20 | -static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error) /* {{{ */ 21 | +PHP_PHAR_API int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error) /* {{{ */ 22 | { 23 | const char token[] = "__HALT_COMPILER();"; 24 | const char zip_magic[] = "PK\x03\x04"; 25 | diff --git a/ext/phar/phar_internal.h b/ext/phar/phar_internal.h 26 | index c23e6f51..8c82b5c0 100644 27 | --- a/ext/phar/phar_internal.h 28 | +++ b/ext/phar/phar_internal.h 29 | @@ -131,7 +131,6 @@ 30 | #define PHAR_MUNG_SCRIPT_FILENAME (1<<3) 31 | 32 | typedef struct _phar_entry_fp phar_entry_fp; 33 | -typedef struct _phar_archive_data phar_archive_data; 34 | 35 | ZEND_BEGIN_MODULE_GLOBALS(phar) 36 | /* a list of phar_archive_data objects that reference a cached phar, so 37 | @@ -575,7 +574,6 @@ int phar_open_or_create_zip(char *fname, int fname_len, char *alias, int alias_l 38 | int phar_zip_flush(phar_archive_data *archive, char *user_stub, zend_long len, int defaultstub, char **error); 39 | 40 | #ifdef PHAR_MAIN 41 | -static int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error); 42 | extern php_stream_wrapper php_stream_phar_wrapper; 43 | #else 44 | extern HashTable cached_phars; 45 | diff --git a/ext/phar/php_phar.h b/ext/phar/php_phar.h 46 | index efaacc57..9013f88d 100644 47 | --- a/ext/phar/php_phar.h 48 | +++ b/ext/phar/php_phar.h 49 | @@ -34,8 +34,10 @@ extern zend_module_entry phar_module_entry; 50 | #define PHP_PHAR_API PHPAPI 51 | #endif 52 | 53 | -PHP_PHAR_API int phar_resolve_alias(char *alias, int alias_len, char **filename, int *filename_len); 54 | +typedef struct _phar_archive_data phar_archive_data; 55 | 56 | +PHP_PHAR_API int phar_resolve_alias(char *alias, int alias_len, char **filename, int *filename_len); 57 | +PHP_PHAR_API int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error); 58 | #endif /* PHP_PHAR_H */ 59 | 60 | 61 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0007-use-alias-in-opened_path-for-phar-stream-wrapper.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Tue, 25 Sep 2018 17:44:59 +0800 4 | Subject: [PATCH] use alias in opened_path for phar:// stream wrapper 5 | 6 | --- 7 | ext/phar/stream.c | 4 ++-- 8 | 1 file changed, 2 insertions(+), 2 deletions(-) 9 | 10 | diff --git a/ext/phar/stream.c b/ext/phar/stream.c 11 | index 0936681a..feb48e95 100644 12 | --- a/ext/phar/stream.c 13 | +++ b/ext/phar/stream.c 14 | @@ -233,7 +233,7 @@ static php_stream * phar_wrapper_open_url(php_stream_wrapper *wrapper, const cha 15 | } 16 | } 17 | if (opened_path) { 18 | - *opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->fname, idata->internal_file->filename); 19 | + *opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->alias, idata->internal_file->filename); 20 | } 21 | return fpf; 22 | } else { 23 | @@ -334,7 +334,7 @@ idata_error: 24 | } 25 | } 26 | if (opened_path) { 27 | - *opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->fname, idata->internal_file->filename); 28 | + *opened_path = strpprintf(MAXPATHLEN, "phar://%s/%s", idata->phar->alias, idata->internal_file->filename); 29 | } 30 | efree(internal_file); 31 | phar_stub: 32 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/patches/0008-expose-an-API-that-increment-refcount-of-phar_archiv.patch: -------------------------------------------------------------------------------- 1 | From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 2 | From: =?UTF-8?q?=E5=BC=A0=E9=85=89=E5=A4=AB?= 3 | Date: Tue, 25 Sep 2018 18:53:23 +0800 4 | Subject: [PATCH] expose an API that increment refcount of phar_archive_data 5 | 6 | --- 7 | ext/phar/phar.c | 6 ++++++ 8 | ext/phar/php_phar.h | 1 + 9 | 2 files changed, 7 insertions(+) 10 | 11 | diff --git a/ext/phar/phar.c b/ext/phar/phar.c 12 | index 5633164c..00b1b0a7 100644 13 | --- a/ext/phar/phar.c 14 | +++ b/ext/phar/phar.c 15 | @@ -264,6 +264,12 @@ void phar_destroy_phar_data(phar_archive_data *phar) /* {{{ */ 16 | } 17 | /* }}}*/ 18 | 19 | +PHP_PHAR_API void phar_archive_addref(phar_archive_data *phar) 20 | +{ 21 | + if (phar->is_persistent) { return; } 22 | + ++phar->refcount; 23 | +} 24 | + 25 | /** 26 | * Delete refcount and destruct if needed. On destruct return 1 else 0. 27 | */ 28 | diff --git a/ext/phar/php_phar.h b/ext/phar/php_phar.h 29 | index 9013f88d..e44d44c9 100644 30 | --- a/ext/phar/php_phar.h 31 | +++ b/ext/phar/php_phar.h 32 | @@ -38,6 +38,7 @@ typedef struct _phar_archive_data phar_archive_data; 33 | 34 | PHP_PHAR_API int phar_resolve_alias(char *alias, int alias_len, char **filename, int *filename_len); 35 | PHP_PHAR_API int phar_open_from_fp(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, int options, phar_archive_data** pphar, int is_data, char **error); 36 | +PHP_PHAR_API void phar_archive_addref(phar_archive_data *phar); 37 | #endif /* PHP_PHAR_H */ 38 | 39 | 40 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/payload/index.php: -------------------------------------------------------------------------------- 1 | getMessage(); 55 | 56 | return json_encode( 57 | array( 58 | "status" => "failed", 59 | "reason" => $err_msg 60 | ), 61 | JSON_PARTIAL_OUTPUT_ON_ERROR 62 | ); 63 | } 64 | 65 | $json = json_encode( 66 | array( 67 | "status" => "successed", 68 | "ast" => $ast 69 | ), 70 | JSON_PARTIAL_OUTPUT_ON_ERROR, 71 | 4096 72 | ); 73 | 74 | if($json === false) { 75 | return json_encode( 76 | array( 77 | "status" => "failed", 78 | "reason" => "json encode error: ".json_last_error_msg() 79 | ) 80 | ); 81 | } 82 | 83 | return $json; 84 | 85 | } 86 | 87 | /** 88 | * php ast server : socket communication 89 | */ 90 | class PhpAstServer { 91 | 92 | /** 93 | * get header data 94 | * @return length of data 95 | */ 96 | function getHeader() : int { 97 | fscanf(STDIN, "%d%*c", $length); 98 | if (!$length) { 99 | throw new Exception('message header must be number'); 100 | } 101 | return $length; 102 | } 103 | 104 | /** 105 | * get body data 106 | * @param body_length:int could given by getHeader() 107 | */ 108 | function getBody(int $body_length) : string { 109 | $receive_length = 0; 110 | $receive_buffer = ""; 111 | while($receive_length < $body_length) { 112 | $receive_buffer .= fread(STDIN, $body_length - $receive_length); 113 | $receive_length = strlen($receive_buffer); 114 | } 115 | return $receive_buffer; 116 | } 117 | 118 | /** 119 | * write data to client 120 | */ 121 | public function write(string $msg) { 122 | $msg = $msg."\n"; 123 | $len_str = strval(strlen($msg))."\n"; 124 | fwrite(STDOUT, $len_str); 125 | fwrite(STDOUT, $msg); 126 | } 127 | 128 | /** 129 | * loop to deal with request 130 | */ 131 | public function loop() { 132 | while (!feof(STDIN)) { 133 | try { 134 | $total_length = $this->getHeader(); 135 | $src = $this->getBody($total_length); 136 | $talk_back = parseToJson($src); 137 | $this->write($talk_back); 138 | } 139 | catch(Exception $exception) { 140 | $this->write(json_encode( 141 | array( 142 | "status" => "failed", 143 | "reason" => $exception->getMessage() 144 | ) 145 | )); 146 | } 147 | }; 148 | } 149 | } 150 | 151 | function main() { 152 | $server = new PhpAstServer(); 153 | $server->loop(); 154 | } 155 | 156 | main(); 157 | 158 | ?> 159 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/php.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #ifdef _WIN32 5 | #include 6 | #include 7 | #include 8 | #else 9 | #include 10 | #endif 11 | 12 | #include "sapi/embed/php_embed.h" 13 | #include "Zend/zend_exceptions.h" 14 | #include "ext/phar/php_phar.h" 15 | 16 | extern unsigned char payload_phar[]; 17 | extern unsigned int payload_phar_len; 18 | 19 | static const size_t memory_limit = 1024 * 1024 * 1024; // 1 GB 20 | static const size_t stack_limit = 64 * 1024 * 1024; // 64 MB 21 | 22 | static int eval(const char *str, size_t len, zval *retval) { 23 | zval script; 24 | ZVAL_STRINGL(&script, str, len); 25 | 26 | zend_op_array *op_array; 27 | op_array = zend_compile_string(&script, "script"); 28 | zval_dtor(&script); 29 | if (!op_array) { 30 | return 1; 31 | } 32 | 33 | int failed = 0; 34 | zend_first_try { 35 | zend_execute(op_array, retval); 36 | if (EG(exception)) { 37 | failed = 1; 38 | } 39 | } zend_catch { 40 | failed = 1; 41 | } zend_end_try(); 42 | 43 | destroy_op_array(op_array); 44 | efree(op_array); 45 | 46 | return failed; 47 | } 48 | 49 | static char *get_error_message(void) { 50 | if (EG(exception)) { 51 | zval exception_object, rv, *message; 52 | zend_class_entry *exception_ce = NULL; 53 | 54 | ZVAL_OBJ(&exception_object, EG(exception)); 55 | if (instanceof_function(Z_OBJCE(exception_object), zend_ce_exception)) { 56 | exception_ce = zend_ce_exception; 57 | } else if (instanceof_function(Z_OBJCE(exception_object), zend_ce_error)) { 58 | exception_ce = zend_ce_error; 59 | } 60 | 61 | if (exception_ce) { 62 | message = zend_read_property_ex(exception_ce, &exception_object, ZSTR_KNOWN(ZEND_STR_MESSAGE), 1, &rv); 63 | if (Z_TYPE(*message) == IS_STRING) { 64 | return Z_STRVAL(*message); 65 | } 66 | } 67 | } 68 | return "unknown error"; 69 | } 70 | 71 | static int init_php_stdio(int fd_in, int fd_out) { 72 | int fd_err = 2; 73 | 74 | php_stream *s_in, *s_out, *s_err; 75 | s_in = php_stream_fopen_from_fd(fd_in, "rb", NULL); 76 | s_out = php_stream_fopen_from_fd(fd_out, "wb", NULL); 77 | s_err = php_stream_fopen_from_fd(fd_err, "wb", NULL); 78 | 79 | if (!s_in || !s_out || !s_err) { 80 | if (s_in) { php_stream_close(s_in); } 81 | if (s_out) { php_stream_close(s_out); } 82 | if (s_err) { php_stream_close(s_err); } 83 | return 1; 84 | } 85 | 86 | s_in->flags |= PHP_STREAM_FLAG_NO_BUFFER; 87 | s_out->flags |= PHP_STREAM_FLAG_NO_BUFFER; 88 | s_err->flags |= PHP_STREAM_FLAG_NO_BUFFER; 89 | 90 | // php only checks S_ISFIFO, which is not enough (e.g. tty) 91 | s_in->flags |= PHP_STREAM_FLAG_NO_SEEK; 92 | s_out->flags |= PHP_STREAM_FLAG_NO_SEEK; 93 | s_err->flags |= PHP_STREAM_FLAG_NO_SEEK; 94 | 95 | zend_constant ic, oc, ec; 96 | php_stream_to_zval(s_in, &ic.value); 97 | php_stream_to_zval(s_out, &oc.value); 98 | php_stream_to_zval(s_err, &ec.value); 99 | 100 | ic.flags = CONST_CS; 101 | ic.name = zend_string_init("STDIN", sizeof("STDIN")-1, 1); 102 | ic.module_number = 0; 103 | zend_register_constant(&ic); 104 | 105 | oc.flags = CONST_CS; 106 | oc.name = zend_string_init("STDOUT", sizeof("STDOUT")-1, 1); 107 | oc.module_number = 0; 108 | zend_register_constant(&oc); 109 | 110 | ec.flags = CONST_CS; 111 | ec.name = zend_string_init("STDERR", sizeof("STDERR")-1, 1); 112 | ec.module_number = 0; 113 | zend_register_constant(&ec); 114 | 115 | return 0; 116 | } 117 | 118 | static int load_phar(void) { 119 | php_stream *fp = php_stream_memory_open(TEMP_STREAM_READONLY, (char *)payload_phar, payload_phar_len); 120 | 121 | static const char fname[] = "payload.phar"; 122 | static const char alias[] = "payload"; 123 | phar_archive_data *pphar; 124 | if (phar_open_from_fp(fp, (char*)fname, sizeof fname - 1, (char*)alias, sizeof alias - 1, 0, &pphar, 0, NULL) != SUCCESS) { 125 | return 1; 126 | } 127 | phar_archive_addref(pphar); 128 | 129 | return 0; 130 | } 131 | 132 | int init(intptr_t fd_in, intptr_t fd_out) { 133 | php_embed_module.php_ini_ignore = 1; 134 | if (php_embed_init(0, NULL) != SUCCESS) { return 1; } 135 | 136 | EG(error_handling) = EH_THROW; 137 | 138 | PG(memory_limit) = memory_limit; 139 | if (zend_set_memory_limit(memory_limit) != SUCCESS) { return 1; } 140 | 141 | #ifdef _WIN32 142 | // duplicate Windows file handle and convert to msvcrt file descriptor 143 | HANDLE hProcess = GetCurrentProcess(); 144 | 145 | if (!DuplicateHandle(hProcess, fd_in, hProcess, &fd_in, 0, FALSE, DUPLICATE_SAME_ACCESS)) { 146 | return 1; 147 | } 148 | fd_in = _open_osfhandle(fd_in, _O_RDONLY | _O_NOINHERIT | _O_BINARY); 149 | if (fd_in == -1) { 150 | CloseHandle(fd_in); 151 | return 1; 152 | } 153 | 154 | if (!DuplicateHandle(hProcess, fd_out, hProcess, &fd_out, 0, FALSE, DUPLICATE_SAME_ACCESS)) { 155 | _close(fd_in); 156 | return 1; 157 | } 158 | fd_out = _open_osfhandle(fd_out, _O_WRONLY | _O_NOINHERIT | _O_BINARY); 159 | if (fd_out == -1) { 160 | CloseHandle(fd_out); 161 | _close(fd_in); 162 | return 1; 163 | } 164 | #else 165 | fd_in = dup(fd_in); 166 | if (fd_in == -1) { 167 | return 1; 168 | } 169 | 170 | fd_out = dup(fd_out); 171 | if (fd_out == -1) { 172 | close(fd_in); 173 | return 1; 174 | } 175 | #endif 176 | 177 | if (init_php_stdio(fd_in, fd_out)) { 178 | return 1; 179 | } 180 | 181 | if (load_phar()) { 182 | return 1; 183 | } 184 | 185 | return 0; 186 | } 187 | 188 | static void* _execute(void* arg) { 189 | static const char entry_php[] = "require 'phar://payload/';"; 190 | if (eval(entry_php, sizeof entry_php - 1, NULL)) { 191 | fputs(get_error_message(), stderr); 192 | } 193 | return NULL; 194 | } 195 | 196 | int execute(void) { 197 | #ifdef WIN32 198 | _execute(); 199 | #else 200 | pthread_t thread; 201 | pthread_attr_t attr; 202 | 203 | if (pthread_attr_init(&attr) || 204 | pthread_attr_setstacksize(&attr, stack_limit) || 205 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) || 206 | pthread_create(&thread, &attr, _execute, NULL) 207 | ) { 208 | return 1; 209 | } 210 | #endif 211 | return 0; 212 | } 213 | -------------------------------------------------------------------------------- /tool/webshell-detector/php/php.go: -------------------------------------------------------------------------------- 1 | package php 2 | 3 | /* 4 | #cgo CFLAGS: -Wall -Wextra -Werror -Wno-unused-parameter -I${SRCDIR}/include/php -I${SRCDIR}/include/php/Zend -I${SRCDIR}/include/php/TSRM -I${SRCDIR}/include/php/main 5 | #cgo LDFLAGS: ${SRCDIR}/lib/libphp7.a -lm 6 | 7 | #include 8 | 9 | int init(intptr_t fd_in, intptr_t fd_out); 10 | int execute(void); 11 | */ 12 | import "C" 13 | 14 | import ( 15 | "errors" 16 | "os" 17 | ) 18 | 19 | var Stdin, Stdout *os.File 20 | 21 | func init() { 22 | var err error 23 | var stdin, stdout *os.File 24 | stdin, Stdin, err = os.Pipe() 25 | if err != nil { panic(err) } 26 | Stdout, stdout, err = os.Pipe() 27 | if err != nil { panic(err) } 28 | 29 | if ret := C.init(C.intptr_t(stdin.Fd()), C.intptr_t(stdout.Fd())); ret != 0 { 30 | panic("cannot initialize PHP runtime") 31 | } 32 | } 33 | 34 | func Start() error { 35 | if (C.execute() != 0) { 36 | return errors.New("cannot start PHP runtime") 37 | } 38 | return nil 39 | } 40 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Ast.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "os" 7 | "sort" 8 | "strings" 9 | ) 10 | 11 | /* 12 | WebshellDetector - Refactor version 1 13 | Date 0814 14 | Author Twice 15 | Intro operations for PHP AST 16 | */ 17 | 18 | type ast struct { 19 | root interface{} 20 | } 21 | 22 | func newAst(data []byte) (*ast, error) { 23 | var astData interface{} 24 | if err := json.Unmarshal(data, &astData); err != nil { 25 | return nil, err 26 | } 27 | 28 | if astMap, ok := astData.(map[string]interface{}); ok { 29 | if astNode, ok := astMap["ast"]; ok { 30 | return &ast{transformAstNode(astNode)}, nil 31 | } else if reason, ok := astMap["reason"]; ok { 32 | if reasonStr, ok := reason.(string); ok { 33 | return nil, errors.New(reasonStr) 34 | } 35 | } 36 | } 37 | 38 | return &ast{nil}, nil 39 | } 40 | 41 | func transformAstNode(ast interface{}) (result interface{}) { 42 | switch value := ast.(type) { 43 | case float64: 44 | result = value 45 | case string: 46 | result = value 47 | case nil: 48 | result = value 49 | case []interface{}: 50 | resArray := make([]interface{}, 0) 51 | for _, v := range value { 52 | resArray = append(resArray, transformAstNode(v)) 53 | } 54 | result = resArray 55 | case map[string]interface{}: 56 | if _, ok := value["kind"]; ok { 57 | result = astNode{ 58 | int(value["kind"].(float64)), 59 | int(value["flags"].(float64)), 60 | int(value["lineno"].(float64)), 61 | transformAstNode(value["children"])} 62 | } else { 63 | resMap := make(map[string]interface{}) 64 | for k, v := range value { 65 | resMap[k] = transformAstNode(v) 66 | } 67 | result = resMap 68 | } 69 | } 70 | 71 | return 72 | } 73 | 74 | func newAstFromGenerator(src []byte, stdin *os.File, stdout *os.File) (*ast, error) { 75 | server := newPhpAstGenerator(stdin, stdout) 76 | data, err := server.GetData(src) 77 | if err != nil { 78 | return nil, err 79 | } 80 | return newAst(data) 81 | } 82 | 83 | type opQueueNode struct { 84 | Key string 85 | Value interface{} 86 | Layer int 87 | Father *astNode 88 | } 89 | 90 | func getOpSerial(ast interface{}) (result [][]int) { 91 | 92 | var queue []opQueueNode 93 | 94 | nowSerial := make([]int, 0) 95 | 96 | queue = append(queue, opQueueNode{"root", ast, 0, nil}) 97 | 98 | for len(queue) != 0 { 99 | node := queue[0] 100 | switch value := node.Value.(type) { 101 | case astNode: 102 | nowSerial = append(nowSerial, value.Kind) 103 | //fmt.Printf("kind:%4v(%4v)\t", value.Kind, node.Layer) 104 | queue = append(queue, opQueueNode{"children", value.Children, node.Layer, &value}) 105 | case string: 106 | case float64: 107 | case nil: 108 | if node.Key == "separator" { 109 | if len(nowSerial) != 0 { 110 | //fmt.Printf("\n") 111 | finishSerial := make([]int, 1) 112 | finishSerial[0] = node.Father.Kind 113 | finishSerial = append(finishSerial, nowSerial...) 114 | 115 | result = append(result, finishSerial) 116 | nowSerial = make([]int, 0) 117 | } 118 | } 119 | case []interface{}: 120 | for i, v := range value { 121 | queue = append(queue, opQueueNode{string(i), v, node.Layer + 1, node.Father}) 122 | } 123 | if node.Key == "children" { 124 | queue = append(queue, opQueueNode{"separator", nil, node.Layer + 1, node.Father}) 125 | } 126 | case map[string]interface{}: 127 | keys := make([]string, 0) 128 | for key, _ := range value { 129 | keys = append(keys, key) 130 | } 131 | sort.Strings(keys) 132 | 133 | for _, k := range keys { 134 | queue = append(queue, opQueueNode{k, value[k], node.Layer + 1, node.Father}) 135 | } 136 | if node.Key == "children" { 137 | queue = append(queue, opQueueNode{"separator", nil, node.Layer + 1, node.Father}) 138 | } 139 | } 140 | queue = queue[1:] 141 | } 142 | 143 | return 144 | } 145 | 146 | func cleanOpSerial(data [][]int, maxLen int) [][]int { 147 | 148 | blockCompare := func(data []int, i int, length int) bool { 149 | if i+2*length > len(data) { 150 | return false 151 | } 152 | for k := 0; k < length; k++ { 153 | if data[i+k] != data[i+length+k] { 154 | return false 155 | } 156 | } 157 | return true 158 | } 159 | 160 | var result [][]int 161 | 162 | for _, v := range data { 163 | tmp := v 164 | for i := maxLen; i >= 1; i-- { 165 | for j := 0; j < len(tmp); { 166 | if blockCompare(tmp, j, i) { 167 | tmp = append(tmp[:j], tmp[j+i:]...) 168 | } else { 169 | j++ 170 | } 171 | } 172 | } 173 | result = append(result, tmp) 174 | } 175 | 176 | return result 177 | } 178 | 179 | func cleanOpSerialRepeatedly(serials *[][]int, cleanTimes, cleanLength int) { 180 | for i := 1; i <= cleanTimes; i++ { 181 | *serials = cleanOpSerial(*serials, cleanLength) 182 | } 183 | } 184 | 185 | type arrayHashState struct { 186 | Table map[string]int 187 | DeTable map[int]string 188 | } 189 | 190 | func newArrayHashState() arrayHashState { 191 | return arrayHashState{make(map[string]int), make(map[int]string)} 192 | } 193 | 194 | func serialToString(serial []int) string { 195 | builder := strings.Builder{} 196 | for _, value := range serial { 197 | builder.WriteByte(byte(value / 100)) 198 | builder.WriteByte(byte(value % 100)) 199 | } 200 | 201 | return builder.String() 202 | } 203 | 204 | func stringToSerial(str string) (result []int) { 205 | for i := 0; i < len(str); i += 2 { 206 | result = append(result, int([]byte(str)[i])*100+int([]byte(str)[i+1])) 207 | } 208 | 209 | return 210 | } 211 | 212 | func (state *arrayHashState) Hash(span []int) int { 213 | if value, ok := state.Table[serialToString(span)]; ok { 214 | return value 215 | } else { 216 | return -1 217 | } 218 | } 219 | 220 | func (state *arrayHashState) Find(hash int) []int { 221 | return stringToSerial(state.DeTable[hash]) 222 | } 223 | 224 | func (state *arrayHashState) Load(bytes []byte) error { 225 | return json.Unmarshal(bytes, state) 226 | } 227 | 228 | func (ast ast) GetOpSerial(state *arrayHashState) opSerial { 229 | serials := getOpSerial(ast.root) 230 | cleanOpSerialRepeatedly(&serials, 10, 5) 231 | 232 | vector := make([]float64, len(state.Table)) 233 | for _, s := range serials { 234 | hash := state.Hash(s) 235 | if hash != -1 { 236 | vector[hash]++ 237 | } 238 | } 239 | 240 | return opSerial{vector} 241 | } 242 | 243 | type iterateAstState struct { 244 | Key string 245 | KindPredict func(int) bool 246 | FlagsPredict func(int) bool 247 | ChildrenPredict func(interface{}) bool 248 | } 249 | 250 | func predictTrue(int) bool { 251 | return true 252 | } 253 | 254 | func predictTrueInterface(interface{}) bool { 255 | return true 256 | } 257 | 258 | func (state iterateAstState) Iterate(ast interface{}) (count int) { 259 | count = 0 260 | 261 | switch value := ast.(type) { 262 | case astNode: 263 | if state.KindPredict(value.Kind) && state.FlagsPredict(value.Flag) && state.ChildrenPredict(value.Children) { 264 | count += 1 265 | } 266 | count += state.Iterate(value.Children) 267 | case float64: 268 | case string: 269 | case []interface{}: 270 | for i, v := range value { 271 | state.Key = string(i) 272 | count += state.Iterate(v) 273 | } 274 | case map[string]interface{}: 275 | for k, v := range value { 276 | state.Key = k 277 | count += state.Iterate(v) 278 | } 279 | } 280 | 281 | return 282 | } 283 | 284 | func checkNameAndKind(ast interface{}, nameChecker func(string) bool, kindChecker func(int) bool) int { 285 | state := iterateAstState{ 286 | "", 287 | kindChecker, 288 | predictTrue, 289 | func(ast interface{}) bool { 290 | if nameMap, ok := ast.(map[string]interface{}); ok { 291 | if name, ok := nameMap["name"]; ok { 292 | if nameStr, ok := name.(string); ok { 293 | return nameChecker(nameStr) 294 | } 295 | } 296 | } 297 | return false 298 | }} 299 | 300 | return state.Iterate(ast) 301 | } 302 | 303 | func (ast ast) GetWordsAndCallable() (words, bool) { 304 | result := false 305 | vector := make([]string, 0) 306 | checkNameAndKind(ast.root, func(s string) bool { 307 | vector = append(vector, s) 308 | return true 309 | }, func(k int) bool { 310 | if k == 269 || k == 265 || k == 515 || k == 768 || k == 769 { 311 | result = true 312 | } 313 | return true 314 | }) 315 | 316 | return words{vector}, result 317 | } 318 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/AstNode.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | /* 4 | WebshellDetector - Refactor version 1 5 | Date 0814 6 | Author Twice 7 | Intro A node structure in PHP AST 8 | */ 9 | 10 | type astNode struct { 11 | Kind int 12 | Flag int 13 | LineNo int 14 | Children interface{} 15 | } 16 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Ast_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_Ast_New(t *testing.T) { 8 | ast, err := newAstFromGenerator([]byte(``), stdin, stdout) 9 | if err != nil { 10 | t.Error(err.Error()) 11 | t.Log(ast) 12 | } 13 | } 14 | 15 | func Test_Ast_GetOpSerial(t *testing.T) { 16 | ast, err := newAstFromGenerator([]byte(``), stdin, stdout) 17 | if err != nil { 18 | t.Error(err.Error()) 19 | } 20 | 21 | det, err := NewDefaultDetector(stdin, stdout) 22 | if err != nil { 23 | t.Error(err.Error()) 24 | } 25 | 26 | vec1 := ast.GetOpSerial(&det.hashState).data 27 | 28 | vec2 := make([]float64, len(vec1)) 29 | vec2[0] = 3 30 | vec2[2] = 1 31 | vec2[6] = 1 32 | vec2[20] = 2 33 | vec2[26] = 1 34 | vec2[45] = 1 35 | vec2[195] = 1 36 | 37 | for i := 0; i < len(vec1); i++ { 38 | if vec1[i] != vec2[i] { 39 | t.Error("vec1 != vec2") 40 | } 41 | } 42 | } 43 | 44 | func Test_Ast_GetWords(t *testing.T) { 45 | 46 | ast, err := newAstFromGenerator([]byte(``), stdin, stdout) 47 | if err != nil { 48 | return 49 | } 50 | res, _ := ast.GetWordsAndCallable() 51 | vec := res.data 52 | 53 | t.Log(len(vec)) 54 | 55 | for i := 0; i < len(vec); i++ { 56 | if vec[i] != "f" && vec[i] != "g" { 57 | t.Error("vec1 != vec2") 58 | } 59 | } 60 | 61 | } 62 | 63 | func Test_Ast_IsCallable(t *testing.T) { 64 | ast1, err := newAstFromGenerator([]byte(``), stdin, stdout) 65 | if err != nil { 66 | return 67 | } 68 | _, res1 := ast1.GetWordsAndCallable() 69 | if res1 != true { 70 | t.Error("Missing Callable") 71 | } 72 | 73 | ast2, err := newAstFromGenerator([]byte(``), stdin, stdout) 74 | if err != nil { 75 | return 76 | } 77 | _, res2 := ast2.GetWordsAndCallable() 78 | if res2 != false { 79 | t.Error("Misjudge Callable") 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/BinData_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_BinData_opSerialStream(t *testing.T) { 8 | _, err := Asset("static/model-latest/OpSerial.model") 9 | if err != nil { 10 | t.Log(err) 11 | t.Error("FAILED - Test_BinData - opSerialStream") 12 | } 13 | } 14 | func Test_BinData_processorStream(t *testing.T) { 15 | _, err := Asset("static/model-latest/Processor.model") 16 | if err != nil { 17 | t.Log(err) 18 | t.Error("FAILED - Test_BinData - processorStream") 19 | } 20 | } 21 | func Test_BinData_wordStream(t *testing.T) { 22 | _, err := Asset("static/model-latest/Words.model") 23 | if err != nil { 24 | t.Log(err) 25 | t.Error("FAILED - Test_BinData - wordStream") 26 | } 27 | } 28 | func Test_BinData_hashStateBytes(t *testing.T) { 29 | _, err := Asset("static/model-latest/hashState.json") 30 | if err != nil { 31 | t.Log(err) 32 | t.Error("FAILED - Test_BinData - hashStateBytes") 33 | } 34 | } 35 | func Test_BinData_statStateBytes(t *testing.T) { 36 | _, err := Asset("static/config/statState.json") 37 | if err != nil { 38 | t.Log(err) 39 | t.Error("FAILED - Test_BinData - statStateBytes") 40 | } 41 | } 42 | func Test_BinData_regMatcherStream(t *testing.T) { 43 | _, err := Asset("static/config/rules.conf") 44 | if err != nil { 45 | t.Log(err) 46 | t.Error("FAILED - Test_BinData - regMatcherStream") 47 | } 48 | } 49 | func Test_BinData_sampleMatcherStream(t *testing.T) { 50 | _, err := Asset("static/model-latest/SampleHash.txt") 51 | if err != nil { 52 | t.Log(err) 53 | t.Error("FAILED - Test_BinData - sampleMatcherStream") 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Detector.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/CyrusF/go-bayesian" 7 | "github.com/CyrusF/libsvm-go" 8 | 9 | "bytes" 10 | "os" 11 | "regexp" 12 | 13 | "github.com/glaslos/ssdeep" 14 | ) 15 | 16 | /* 17 | WebshellDetector - Refactor version 1 18 | Date 0814 19 | Author Cyrus, Twice 20 | Intro Read model from file 21 | Give an interface for predict 22 | */ 23 | 24 | type DetectorConfig struct { 25 | modelPath string 26 | configPath string 27 | enableProcessor bool 28 | enableRegMatcher bool 29 | enableSampleMather bool 30 | enableStatCheck bool 31 | } 32 | 33 | func NewDetectorConfig() (*DetectorConfig, error) { 34 | return &DetectorConfig{"", "", true, true, true, true}, nil 35 | } 36 | 37 | type Detector struct { 38 | opSerialModel *libSvm.Model 39 | processModel *libSvm.Model 40 | wordsModel *bayesian.Classifier 41 | regMatcher *regMatcher 42 | sampleMatcher *sampleMatcher 43 | hashState arrayHashState 44 | statState arrayStatState 45 | stdin *os.File 46 | stdout *os.File 47 | config *DetectorConfig 48 | } 49 | 50 | func NewDetectorWithConfig(config *DetectorConfig, opSerialStream []byte, processorStream []byte, wordStream []byte, hashStateBytes []byte, statStateBytes []byte, regMatcherStream []byte, sampleMatcherStream []byte, stdin *os.File, stdout *os.File) (*Detector, error) { 51 | var self Detector 52 | var err error 53 | 54 | self.config = config 55 | opSerialStreamReader := bytes.NewReader(opSerialStream) 56 | self.opSerialModel = libSvm.NewModelFromFileStream(opSerialStreamReader) 57 | processorStreamReader := bytes.NewReader(processorStream) 58 | self.processModel = libSvm.NewModelFromFileStream(processorStreamReader) 59 | 60 | wordStreamReader := bytes.NewReader(wordStream) 61 | tmpWordsModel, _ := bayesian.NewClassifierFromFileStream(wordStreamReader) 62 | self.wordsModel = &tmpWordsModel // make all struct element to be pointer 63 | 64 | self.hashState = newArrayHashState() 65 | self.hashState.Load(hashStateBytes) 66 | 67 | self.statState = newArrayStatState() 68 | err = self.statState.Load(statStateBytes) 69 | if err != nil { 70 | return nil, err 71 | } 72 | 73 | regMatcherStreamReader := bytes.NewReader(regMatcherStream) 74 | self.regMatcher, err = newRegMatcher(regMatcherStreamReader) 75 | if err != nil { 76 | return nil, err 77 | } 78 | 79 | sampleMatcherStreamReader := bytes.NewReader(sampleMatcherStream) 80 | self.sampleMatcher, err = newSampleMatcher(sampleMatcherStreamReader) 81 | if err != nil { 82 | return nil, err 83 | } 84 | 85 | self.stdin = stdin 86 | self.stdout = stdout 87 | return &self, nil 88 | } 89 | 90 | func NewDetector(opSerialStream []byte, processorStream []byte, wordStream []byte, hashStateBytes []byte, statStateBytes []byte, regMatcherStream []byte, sampleMatcherStream []byte, stdin *os.File, stdout *os.File) (*Detector, error) { 91 | if config, err := NewDetectorConfig(); err == nil { 92 | return NewDetectorWithConfig(config, opSerialStream, processorStream, wordStream, hashStateBytes, statStateBytes, regMatcherStream, sampleMatcherStream, stdin, stdout) 93 | } else { 94 | return nil, err 95 | } 96 | } 97 | 98 | func NewDefaultDetector(stdin *os.File, stdout *os.File) (*Detector, error) { 99 | opSerialStream, err := Asset("static/model-latest/OpSerial.model") 100 | if err != nil { 101 | log.Fatal(err) 102 | } 103 | processorStream, err := Asset("static/model-latest/Processor.model") 104 | if err != nil { 105 | log.Fatal(err) 106 | } 107 | wordStream, err := Asset("static/model-latest/Words.model") 108 | if err != nil { 109 | log.Fatal(err) 110 | } 111 | hashStateBytes, err := Asset("static/model-latest/hashState.json") 112 | if err != nil { 113 | log.Fatal(err) 114 | } 115 | statStateBytes, err := Asset("static/config/statState.json") 116 | if err != nil { 117 | log.Fatal(err) 118 | } 119 | regMatcherStream, err := Asset("static/config/rules.conf") 120 | if err != nil { 121 | log.Fatal(err) 122 | } 123 | sampleMatcherStream, err := Asset("static/model-latest/SampleHash.txt") 124 | if err != nil { 125 | log.Fatal(err) 126 | } 127 | 128 | return NewDetector(opSerialStream, processorStream, wordStream, hashStateBytes, statStateBytes, regMatcherStream, sampleMatcherStream, stdin, stdout) 129 | } 130 | 131 | func (self Detector) Predict(src []byte) (int, error) { 132 | 133 | isPhpCode := func(src []byte) bool { 134 | return bytes.Contains(src, []byte("`).Match(src) 135 | } 136 | 137 | var err error 138 | 139 | processor, err := newProcessorFromSrc(&self, src, self.stdin, self.stdout) 140 | if err != nil { 141 | return -999, err 142 | } 143 | 144 | if !isPhpCode(src) { 145 | return -1, nil 146 | } 147 | 148 | result := 0 149 | 150 | if self.config.enableRegMatcher && self.regMatcher.IsMatched(src) > 0 { 151 | result += 1 152 | } 153 | 154 | if self.config.enableStatCheck && processor.stat.IsAbnormal(self.statState) && processor.callable { 155 | result += 2 156 | } 157 | 158 | isMatchedBySample := false 159 | if self.config.enableSampleMather { 160 | isMatchedBySample, err = self.sampleMatcher.Match(src) 161 | if err != nil && err != ssdeep.ErrFileTooSmall { 162 | return -1, err 163 | } 164 | } 165 | 166 | if (self.config.enableProcessor && processor.Predict() < 0) || (self.config.enableSampleMather && isMatchedBySample) { 167 | result += 4 168 | } 169 | 170 | return result, nil 171 | } 172 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Detector_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func Test_Detector_NewDetector(t *testing.T) { 9 | detector, err := NewDefaultDetector(stdin, stdout) 10 | if err != nil { 11 | t.Error(err.Error()) 12 | } 13 | if detector.opSerialModel.NrClass() == 0 { 14 | t.Error("FAILED - Test_Detector_NewDetector - opSerialModel") 15 | } 16 | if len(detector.wordsModel.LearningResults) == 0 { 17 | t.Error("FAILED - Test_Detector_NewDetector - wordsModel") 18 | } 19 | if detector.processModel.NrClass() == 0 { 20 | t.Error("FAILED - Test_Detector_NewDetector - processModel") 21 | } 22 | if len(detector.regMatcher.regData) == 0 { 23 | t.Error("FAILED - Test_Detector_NewDetector - regMatcher") 24 | } 25 | if len(detector.hashState.Table) == 0 { 26 | t.Error("FAILED - Test_Detector_NewDetector - hashState") 27 | } 28 | if fmt.Sprintf("%v", detector.statState) != "{{NaN 0.1 NaN NaN 10 NaN 0.001 NaN} {2048 NaN 1024 NaN NaN NaN NaN NaN}}" { 29 | t.Logf("%v", detector.statState) 30 | t.Error("FAILED - Test_Detector_NewDetector - statState") 31 | } 32 | } 33 | 34 | func Test_Detector_Predict(t *testing.T) { 35 | detector, _ := NewDefaultDetector(stdin, stdout) 36 | src := []byte(``) 37 | result, err := detector.Predict(src) 38 | if err != nil { 39 | t.Error(err.Error()) 40 | } 41 | if result < 0 { 42 | t.Error("FAILED - Test_Detector_Predict") 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/OpSerial.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "github.com/CyrusF/libsvm-go" 5 | ) 6 | 7 | /* 8 | WebshellDetector - Refactor version 1 9 | Date 0814 10 | Author Cyrus 11 | Intro Use operation serial array 12 | Convert array to map for model prediction 13 | */ 14 | 15 | type opSerial struct { 16 | data []float64 17 | } 18 | 19 | func (self opSerial) Predict(model *libSvm.Model) float64 { 20 | var inputData = make(map[int]float64) 21 | for k, v := range self.data { 22 | if v != 0 { 23 | inputData[k+1] = v // model start at 1 24 | } 25 | } 26 | _, result := model.PredictValues(inputData) 27 | return result[0] 28 | } 29 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/OpSerial_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_OpSerial_Predict(t *testing.T) { 8 | detector, _ := NewDefaultDetector(stdin, stdout) 9 | opserial1 := opSerial{[]float64{1, 2, 3}} 10 | result1 := opserial1.Predict(detector.opSerialModel) 11 | if result1 > 0 { 12 | t.Log(result1) 13 | t.Error("FAILED - Test_OpSerial_Predict - data1") 14 | } 15 | opserial2 := opSerial{[]float64{1, 2, 3, 4}} 16 | result2 := opserial2.Predict(detector.opSerialModel) 17 | if result2 > 0 { 18 | t.Log(result2) 19 | t.Error("FAILED - Test_OpSerial_Predict - data2") 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/PhpAstGen.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "bufio" 5 | "log" 6 | "os" 7 | "strconv" 8 | ) 9 | 10 | /* 11 | WebshellDetector - Refactor version 2 12 | Date 0929 13 | Author Cyrus 14 | Intro Create a PHP-Ast generator for build Ast, from STDIO. 15 | */ 16 | 17 | type phpAstServer struct { 18 | stdin *os.File 19 | stdout *os.File 20 | } 21 | 22 | func newPhpAstGenerator(stdin *os.File, stdout *os.File) phpAstServer { 23 | return phpAstServer{stdin, stdout} 24 | } 25 | 26 | func (self *phpAstServer) GetData(src []byte) ([]byte, error) { 27 | srcLen := len(src) 28 | if n, err := self.stdin.WriteString(strconv.Itoa(srcLen) + "\n"); err != nil || n <= 1 { 29 | log.Fatal("Write stdin failed") 30 | } 31 | if _, err := self.stdin.Write(src); err != nil { 32 | log.Fatal("Write stdin failed") 33 | } 34 | 35 | connReader := bufio.NewReaderSize(self.stdout, 4096) // Get recv data length from server 36 | resultLenStr, _, err := connReader.ReadLine() 37 | if err != nil { 38 | return nil, err 39 | } 40 | 41 | resultLen, err := strconv.Atoi(string(resultLenStr)) // convert []byte to int 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | var resultTextByte = make([]byte, resultLen) 47 | var buf byte 48 | for i := 0; i < resultLen; i++ { 49 | buf, err = connReader.ReadByte() 50 | if err != nil { 51 | return nil, err 52 | } 53 | resultTextByte[i] = buf 54 | } 55 | 56 | return resultTextByte, nil 57 | } 58 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/PhpAstGen_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | ) 7 | 8 | func Test_PhpAstGen_GetData(t *testing.T) { 9 | phpAstGen := newPhpAstGenerator(stdin, stdout) 10 | src := []byte(``) 11 | std := []byte(`{"status":"successed","ast":{"kind":132,"flags":0,"lineno":1,"children":[{"kind":282,"flags":0,"lineno":1,"children":{"expr":"hello world"}}]}}` + "\n") 12 | result, err := phpAstGen.GetData(src) 13 | if bytes.Compare(result, std) != 0 || err != nil { 14 | t.Log(bytes.Compare(result, std)) 15 | t.Log(err) 16 | t.Log(string(result)) 17 | t.Log(string(std)) 18 | t.Error("FAILED - Test_PhpAstServer_GetData") 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Processor.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import "os" 4 | 5 | /* 6 | WebshellDetector - Refactor version 1 7 | Date 0814 8 | Author Cyrus, Twice 9 | Intro Process 8 textStat vectors and 2 ML vectors, final score 10 | */ 11 | 12 | type processor struct { 13 | detector *Detector 14 | opSerial *opSerial 15 | words *words 16 | stat *textStat 17 | callable bool 18 | } 19 | 20 | func newProcessor(detector *Detector, ast *ast, stat *textStat) *processor { 21 | opSerial := ast.GetOpSerial(&detector.hashState) 22 | words, callable := ast.GetWordsAndCallable() 23 | 24 | var self processor 25 | self.detector = detector 26 | self.opSerial = &opSerial 27 | self.words = &words 28 | self.stat = stat 29 | self.callable = callable 30 | 31 | return &self 32 | } 33 | 34 | func newProcessorFromSrc(detector *Detector, src []byte, stdin *os.File, stdout *os.File) (*processor, error) { 35 | ast, err := newAstFromGenerator(src, stdin, stdout) 36 | if err != nil { 37 | return nil, err 38 | } 39 | stat := newTextStat(src) 40 | return newProcessor(detector, ast, &stat), nil 41 | } 42 | 43 | func (self processor) Predict() float64 { 44 | var inputData = make(map[int]float64, 11) 45 | for k, v := range self.stat.GetVector() { 46 | inputData[k+1] = v // model start at 1 47 | } 48 | inputData[9] = self.opSerial.Predict(self.detector.opSerialModel) 49 | inputData[10] = self.words.Predict(self.detector.wordsModel) 50 | _, result := self.detector.processModel.PredictValues(inputData) 51 | return result[0] 52 | } 53 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Processor_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "testing" 5 | 6 | "../php" 7 | ) 8 | 9 | func Test_Processor_NewProcessor(t *testing.T) { 10 | detector, _ := NewDefaultDetector(stdin, stdout) 11 | src := []byte(``) 12 | ast, err := newAstFromGenerator(src, stdin, stdout) 13 | if err != nil { 14 | t.Error("FAILED - Test_Processor_NewProcessor - AST") 15 | } 16 | stat := newTextStat(src) 17 | processor := newProcessor(detector, ast, &stat) 18 | if &processor == nil { 19 | t.Error("FAILED - Test_Processor_NewProcessor") 20 | } 21 | } 22 | 23 | func Test_Processor_NewProcessorFromSrc(t *testing.T) { 24 | detector, _ := NewDefaultDetector(stdin, stdout) 25 | src := []byte(``) 26 | var err error 27 | stdin := php.Stdin 28 | stdout := php.Stdout 29 | processor, err := newProcessorFromSrc(detector, src, stdin, stdout) 30 | if err != nil || &processor == nil { 31 | t.Error("FAILED - Test_Processor_NewProcessorFromSrc") 32 | } 33 | } 34 | func Test_Processor_Predict(t *testing.T) { 35 | detector, _ := NewDefaultDetector(stdin, stdout) 36 | src := []byte(``) 37 | stdin := php.Stdin 38 | stdout := php.Stdout 39 | processor, _ := newProcessorFromSrc(detector, src, stdin, stdout) 40 | result := processor.Predict() 41 | if &result == nil { 42 | t.Error("FAILED - Test_Processor_NewProcessor - Predict") 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/RegMatcher.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "regexp" 10 | "strings" 11 | "unicode" 12 | ) 13 | 14 | /* 15 | WebshellDetector - Refactor version 1 16 | Date 0814 17 | Author Cyrus 18 | Intro Some regular expression match for PHP file 19 | */ 20 | 21 | type regItem struct { 22 | ordered bool 23 | regItem []*regexp.Regexp 24 | strItem [][]byte 25 | } 26 | 27 | type regMatcher struct { 28 | regData []regItem 29 | } 30 | 31 | var presets = []regItem{ 32 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`function\_exists\s*\(\s*[\'|\"](popen|exec|proc\_open|system|passthru)+[\'|\"]\s*\)`)}, [][]byte{}}, 33 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`(exec|shell\_exec|system|passthru)+\s*\(\s*\$\_(\w+)\[(.*)\]\s*\)`)}, [][]byte{}}, 34 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`((udp|tcp)\:\/\/(.*)\;)+`)}, [][]byte{}}, 35 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`preg\_replace\s*\((.*)\/e(.*)\,\s*\$\_(.*)\,(.*)\)`)}, [][]byte{}}, 36 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`preg\_replace\s*\((.*)\(base64\_decode\(\$`)}, [][]byte{}}, 37 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*(base64\_decode|str\_rot13|gz(\w+)|file\_(\w+)\_contents|(.*)php\:\/\/input)+`)}, [][]byte{}}, 38 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`(eval|assert|include|require|include\_once|require\_once|array\_map|array\_walk)+\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER|SESSION)+\[(.*)\]\s*\)`)}, [][]byte{}}, 39 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`eval\s*\(\s*\(\s*\$\$(\w+)`)}, [][]byte{}}, 40 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`(include|require|include\_once|require\_once)+\s*\(\s*[\'|\"](\w+)\.(jpg|gif|ico|bmp|png|txt|zip|rar|htm|css|js)+[\'|\"]\s*\)`)}, [][]byte{}}, 41 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$\_(\w+)(.*)(eval|assert|include|require|include\_once|require\_once)+\s*\(\s*\$(\w+)\s*\)`)}, [][]byte{}}, 42 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\(\s*\$\_FILES\[(.*)\]\[(.*)\]\s*\,\s*\$\_(GET|POST|REQUEST|FILES)+\[(.*)\]\[(.*)\]\s*\)`)}, [][]byte{}}, 43 | // regItem{false, []*regexp.Regexp{regexp.MustCompile(`(fopen|fwrite|fputs|file\_put\_contents)+\s*\((.*)\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\](.*)\)`)}, [][]byte{}}, 44 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`echo\s*curl\_exec\s*\(\s*\$(\w+)\s*\)`)}, [][]byte{}}, 45 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`new com\s*\(\s*[\'|\"]shell(.*)[\'|\"]\s*\)`)}, [][]byte{}}, 46 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$(.*)\s*\((.*)\/e(.*)\,\s*\$\_(.*)\,(.*)\)`)}, [][]byte{}}, 47 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$\_\=(.*)\$\_`)}, [][]byte{}}, 48 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\(\s*\$(.*)\)`)}, [][]byte{}}, 49 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$(\w+)\s*\(\s*\$\_(GET|POST|REQUEST|COOKIE|SERVER)+\[(.*)\]\s*\)`)}, [][]byte{}}, 50 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$(\w+)\s*\(\s*\$\{(.*)\}`)}, [][]byte{}}, 51 | regItem{false, []*regexp.Regexp{regexp.MustCompile(`\$(\w+)\s*\(\s*chr\(\d+\)`)}, [][]byte{}}, 52 | } 53 | 54 | func defaultRegMatcher() *regMatcher { 55 | var self regMatcher 56 | self.regData = presets 57 | return &self 58 | } 59 | 60 | func newRegMatcher(file io.Reader) (*regMatcher, error) { 61 | reader := bufio.NewReader(file) 62 | var self regMatcher 63 | self.regData = presets 64 | errNum := 0 65 | var regGroup []*regexp.Regexp 66 | var strGroup [][]byte 67 | inGroup := false 68 | oederedGroup := false 69 | lineCount := 0 70 | for line, _, err := reader.ReadLine(); err == nil; line, _, err = reader.ReadLine() { 71 | lineCount++ 72 | str := strings.Trim(string(line), " ") 73 | if str == "" || (strings.Index(str, "##") == 0) { 74 | continue 75 | } 76 | if strings.Index(strings.ToLower(str), "#start#") == 0 { 77 | if inGroup { 78 | errStr := fmt.Sprintf("RegMatcher Error: except #End but found #Start in %s (Line %d)", "bindata", lineCount) 79 | return nil, errors.New(errStr) 80 | } 81 | inGroup = true 82 | oederedGroup = false 83 | regGroup = make([]*regexp.Regexp, 0) 84 | strGroup = make([][]byte, 0) 85 | continue 86 | } 87 | if strings.Index(strings.ToLower(str), "#end#") == 0 { 88 | if !inGroup { 89 | errStr := fmt.Sprintf("RegMatcher Error: except #Start but found #End in %s (Line %d)", "bindata", lineCount) 90 | return nil, errors.New(errStr) 91 | } 92 | inGroup = false 93 | self.regData = append(self.regData, regItem{oederedGroup, regGroup, strGroup}) 94 | continue 95 | } 96 | if strings.Index(strings.ToLower(str), "#ordered#") == 0 { 97 | if !inGroup { 98 | errStr := fmt.Sprintf("RegMatcher Error: [Ordered] label need regexp group, found #ordered# in %s (Line %d)", "bindata", lineCount) 99 | return nil, errors.New(errStr) 100 | } 101 | oederedGroup = true 102 | continue 103 | } 104 | if inGroup { 105 | if strings.Index(strings.ToLower(str), "#pre#") == 0 { 106 | preStr := []byte(strings.TrimSpace(str[5:len(str)])) 107 | strGroup = append(strGroup, preStr) 108 | } else { 109 | if reg, err := regexp.Compile(str); err == nil { 110 | regGroup = append(regGroup, reg) 111 | } else { 112 | errNum++ 113 | fmt.Printf("%v\n", str) 114 | } 115 | } 116 | } else { 117 | if strings.Index(strings.ToLower(str), "#pre#") == 0 { 118 | preStr := []byte(strings.TrimSpace(str[5:len(str)])) 119 | self.regData = append(self.regData, regItem{false, []*regexp.Regexp{}, [][]byte{preStr}}) 120 | } else { 121 | if reg, err := regexp.Compile(str); err == nil { 122 | self.regData = append(self.regData, regItem{false, []*regexp.Regexp{reg}, [][]byte{}}) 123 | } else { 124 | errNum++ 125 | fmt.Printf("%v\n", str) 126 | } 127 | } 128 | } 129 | } 130 | if inGroup { 131 | errStr := fmt.Sprintf("RegMatcher Error: could not find #End in %s", "bindata") 132 | return nil, errors.New(errStr) 133 | } 134 | if errNum > 0 { 135 | fmt.Printf("RegExp compiler: %d failed, ignored\n", errNum) 136 | } 137 | return &self, nil 138 | } 139 | 140 | func pretreat(src []byte) []byte { 141 | 142 | getFirstNChars := func(src []byte, k int, n int) string { 143 | if n < 0 { 144 | if k+n > 0 { 145 | return fmt.Sprintf("%s", src[k+n:k]) 146 | } else { 147 | return fmt.Sprintf("%s", src[0:k]) 148 | } 149 | } else { 150 | if k+n <= len(src) { 151 | return fmt.Sprintf("%s", src[k:k+n]) 152 | } else { 153 | return fmt.Sprintf("%s", src[k:len(src)]) 154 | } 155 | } 156 | } 157 | 158 | buf := bytes.NewBufferString("") 159 | sgnPhp := false 160 | sgnValue := false 161 | sgnStr := false 162 | sgnList := false 163 | sgnArray := false 164 | sgnCommentLine := false 165 | sgnCommentBlock := false 166 | tmpValue := bytes.NewBufferString("") 167 | listLevel := 0 168 | arrayLevel := 0 169 | 170 | for k, v := range src { 171 | 172 | if getFirstNChars(src, k, 2) == "" || v == '\n') && sgnCommentLine { 182 | sgnCommentLine = false 183 | } 184 | if getFirstNChars(src, k, 2) == "/*" && !sgnStr { 185 | sgnCommentBlock = true 186 | } 187 | if (getFirstNChars(src, k, 2) == "?>" || getFirstNChars(src, k, 2) == "*/") && !sgnStr { 188 | sgnCommentBlock = false 189 | } 190 | if sgnCommentLine || sgnCommentBlock { 191 | continue 192 | } 193 | if v == '$' && !sgnStr && !sgnList { 194 | sgnValue = true 195 | tmpValue.Reset() 196 | buf.WriteByte(v) 197 | continue 198 | } 199 | if sgnValue { 200 | if (src[k-1] == '$' && 201 | (unicode.IsUpper(rune(v)) || 202 | unicode.IsLower(rune(v)) || 203 | v == '_')) || 204 | (src[k-1] != '$' && 205 | (unicode.IsUpper(rune(v)) || 206 | unicode.IsLower(rune(v)) || 207 | v == '_' || 208 | unicode.IsDigit(rune(v)))) { 209 | tmpValue.WriteByte(v) 210 | } else { 211 | if tmpValue.Len() > 0 { 212 | tmpValueByte, _ := tmpValue.ReadBytes(byte(0)) 213 | tmpValueStr := fmt.Sprintf("%s", tmpValueByte) 214 | if tmpValueStr != "_SERVER" && 215 | tmpValueStr != "_GET" && 216 | tmpValueStr != "_POST" && 217 | tmpValueStr != "_COOKIE" && 218 | tmpValueStr != "_FILES" && 219 | tmpValueStr != "_ENV" && 220 | tmpValueStr != "_REQUEST" && 221 | tmpValueStr != "_SESSION" && 222 | tmpValueStr != "GLOBALS" { 223 | buf.WriteByte(byte('v')) 224 | } else { 225 | buf.Write(tmpValueByte) 226 | } 227 | } 228 | sgnValue = false 229 | } 230 | } 231 | 232 | if v == '"' && !sgnStr { 233 | sgnStr = true 234 | if !sgnList { 235 | buf.WriteByte(v) 236 | } 237 | continue 238 | } 239 | if v == '"' && src[k-1] != '\\' && sgnStr { 240 | sgnStr = false 241 | if !sgnList { 242 | buf.WriteByte(v) 243 | } 244 | continue 245 | } 246 | if sgnStr && !sgnList { 247 | continue 248 | } 249 | if v == '[' && !sgnList && !sgnStr { 250 | sgnList = true 251 | listLevel = 1 252 | buf.WriteByte(v) 253 | continue 254 | } 255 | if v == '[' && sgnList && !sgnStr { 256 | listLevel++ 257 | continue 258 | } 259 | if v == ']' && sgnList && !sgnStr { 260 | listLevel-- 261 | if listLevel == 0 { 262 | sgnList = false 263 | buf.WriteByte(v) 264 | continue 265 | } 266 | } 267 | if v == '(' && !sgnStr && !sgnList { 268 | sgnArray = true 269 | arrayLevel++ 270 | buf.WriteByte(v) 271 | continue 272 | } 273 | if v == ')' && !sgnStr && !sgnList { 274 | arrayLevel-- 275 | if arrayLevel == 0 { 276 | sgnArray = false 277 | buf.WriteByte(v) 278 | continue 279 | } else { 280 | buf.WriteByte(v) 281 | continue 282 | } 283 | } 284 | if sgnArray { 285 | if v == ',' { 286 | buf.WriteByte(v) 287 | } 288 | continue 289 | } 290 | if getFirstNChars(src, k, -2) == "?>" { 291 | sgnPhp = false 292 | sgnValue = false 293 | sgnStr = false 294 | sgnList = false 295 | sgnArray = false 296 | sgnCommentLine = false 297 | sgnCommentBlock = false 298 | if v == '\n' { 299 | buf.WriteByte(v) 300 | } 301 | continue 302 | } 303 | if !sgnValue && !sgnList { 304 | if v != ' ' || getFirstNChars(src, k, -5) == " 0 { 30 | t.Error("FAILED - Test_RegMatcher_IsMatched - misjudge") 31 | } 32 | if regMatcher.IsMatched([]byte("eval($_GET[\"A\"])")) == 0 { 33 | t.Error("FAILED - Test_RegMatcher_IsMatched - missing") 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/SampleMatcher.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | 7 | "github.com/glaslos/ssdeep" 8 | ) 9 | 10 | /* 11 | WebshellDetector - Refactor version 1 12 | Date 0822 13 | Author Twice 14 | Intro Match some PHP code from webshell samples using ssdeep 15 | */ 16 | 17 | type sampleMatcher struct { 18 | hashes []string 19 | } 20 | 21 | func newSampleMatcher(sampleHashFile io.Reader) (*sampleMatcher, error) { 22 | 23 | matcher := sampleMatcher{nil} 24 | reader := bufio.NewReader(sampleHashFile) 25 | for line, _, err := reader.ReadLine(); err == nil; line, _, err = reader.ReadLine() { 26 | matcher.hashes = append(matcher.hashes, string(line)) 27 | } 28 | 29 | return &matcher, nil 30 | } 31 | 32 | func (matcher *sampleMatcher) Match(src []byte) (bool, error) { 33 | hash, err := ssdeep.FuzzyBytes(src) 34 | if err != nil { 35 | return false, err 36 | } 37 | 38 | for _, h := range matcher.hashes { 39 | score, err := ssdeep.Distance(hash, h) 40 | if err != nil { 41 | return false, err 42 | } 43 | if score > 90 { 44 | return true, nil 45 | } 46 | } 47 | 48 | return false, nil 49 | } 50 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/SampleMatcher_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "bytes" 5 | "log" 6 | "testing" 7 | ) 8 | 9 | func Test_SampleMatcher_New(t *testing.T) { 10 | sampleMatcherStream, err := Asset("static/model-latest/SampleHash.txt") 11 | if err != nil { 12 | log.Fatal(err) 13 | } 14 | sampleMatcherStreamReader := bytes.NewReader(sampleMatcherStream) 15 | _, err = newSampleMatcher(sampleMatcherStreamReader) 16 | if err != nil { 17 | t.Error(err.Error()) 18 | } 19 | } 20 | 21 | func Test_SampleMatcher_Match(t *testing.T) { 22 | sampleMatcherStream, err := Asset("static/model-latest/SampleHash.txt") 23 | if err != nil { 24 | log.Fatal(err) 25 | } 26 | sampleMatcherStreamReader := bytes.NewReader(sampleMatcherStream) 27 | matcher, err := newSampleMatcher(sampleMatcherStreamReader) 28 | isMatched, err := matcher.Match([]byte{10, 60, 33, 45, 45, 10, 10, 47, 43, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 43, 92, 10, 32, 124, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 75, 65, 95, 117, 83, 104, 101, 108, 108, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 124, 10, 32, 124, 32, 32, 32, 32, 60, 75, 65, 100, 111, 116, 32, 85, 110, 105, 118, 101, 114, 115, 97, 108, 32, 83, 104, 101, 108, 108, 62, 32, 32, 32, 32, 32, 124, 10, 32, 124, 32, 32, 32, 32, 32, 32, 32, 32, 32, 86, 101, 114, 115, 105, 111, 110, 32, 48, 46, 49, 46, 54, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 124, 10, 32, 124, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 49, 51, 46, 48, 51, 46, 48, 52, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 124, 10, 32, 124, 32, 32, 65, 117, 116, 104, 111, 114, 58, 32, 75, 65, 100, 111, 116, 32, 60, 75, 65, 100, 111, 116, 64, 110, 103, 115, 46, 114, 117, 62, 32, 32, 124, 10, 32, 124, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 124, 10, 92, 43, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 43, 47, 10, 10, 45, 45, 62, 10, 60, 104, 116, 109, 108, 62, 10, 60, 104, 101, 97, 100, 62, 10, 60, 116, 105, 116, 108, 101, 62, 75, 65, 95, 117, 83, 104, 101, 108, 108, 32, 48, 46, 49, 46, 54, 60, 47, 116, 105, 116, 108, 101, 62, 10, 60, 115, 116, 121, 108, 101, 32, 116, 121, 112, 101, 61, 34, 116, 101, 120, 116, 47, 99, 115, 115, 34, 62, 10, 60, 33, 45, 45, 10, 98, 111, 100, 121, 44, 32, 116, 97, 98, 108, 101, 123, 102, 111, 110, 116, 45, 102, 97, 109, 105, 108, 121, 58, 86, 101, 114, 100, 97, 110, 97, 59, 32, 102, 111, 110, 116, 45, 115, 105, 122, 101, 58, 49, 50, 112, 120, 59, 125, 10, 116, 97, 98, 108, 101, 32, 123, 98, 97, 99, 107, 103, 114, 111, 117, 110, 100, 45, 99, 111, 108, 111, 114, 58, 35, 69, 65, 69, 65, 69, 65, 59, 32, 98, 111, 114, 100, 101, 114, 45, 119, 105, 100, 116, 104, 58, 48, 112, 120, 59, 125, 10, 98, 32, 123, 102, 111, 110, 116, 45, 102, 97, 109, 105, 108, 121, 58, 65, 114, 105, 97, 108, 59, 32, 102, 111, 110, 116, 45, 115, 105, 122, 101, 58, 49, 53, 112, 120, 59, 125, 10, 97, 123, 116, 101, 120, 116, 45, 100, 101, 99, 111, 114, 97, 116, 105, 111, 110, 58, 110, 111, 110, 101, 59, 125, 10, 45, 45, 62, 10, 60, 47, 115, 116, 121, 108, 101, 62, 10, 60, 47, 104, 101, 97, 100, 62, 10, 60, 98, 111, 100, 121, 62, 10, 10, 60, 63, 112, 104, 112, 10, 36, 115, 101, 108, 102, 32, 61, 32, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 83, 69, 76, 70, 39, 93, 59, 10, 36, 100, 111, 99, 114, 32, 61, 32, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 68, 79, 67, 85, 77, 69, 78, 84, 95, 82, 79, 79, 84, 39, 93, 59, 10, 36, 115, 101, 114, 110, 32, 61, 32, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 83, 69, 82, 86, 69, 82, 95, 78, 65, 77, 69, 39, 93, 59, 10, 36, 116, 101, 110, 100, 32, 61, 32, 34, 60, 47, 116, 114, 62, 60, 47, 102, 111, 114, 109, 62, 60, 47, 116, 97, 98, 108, 101, 62, 60, 98, 114, 62, 60, 98, 114, 62, 60, 98, 114, 62, 60, 98, 114, 62, 34, 59, 10, 10, 47, 47, 32, 67, 111, 110, 102, 105, 103, 117, 114, 97, 116, 105, 111, 110, 10, 36, 108, 111, 103, 105, 110, 32, 61, 32, 34, 110, 111, 116, 32, 97, 100, 109, 105, 110, 34, 59, 10, 36, 112, 97, 115, 115, 32, 61, 32, 34, 110, 111, 116, 32, 49, 50, 51, 34, 59, 10, 10, 10, 47, 42, 47, 32, 65, 117, 116, 104, 101, 110, 116, 105, 99, 97, 116, 105, 111, 110, 10, 105, 102, 32, 40, 33, 105, 115, 115, 101, 116, 40, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 65, 85, 84, 72, 95, 85, 83, 69, 82, 39, 93, 41, 41, 32, 123, 10, 104, 101, 97, 100, 101, 114, 40, 39, 87, 87, 87, 45, 65, 117, 116, 104, 101, 110, 116, 105, 99, 97, 116, 101, 58, 32, 66, 97, 115, 105, 99, 32, 114, 101, 97, 108, 109, 61, 34, 75, 65, 95, 117, 83, 104, 101, 108, 108, 34, 39, 41, 59, 10, 104, 101, 97, 100, 101, 114, 40, 39, 72, 84, 84, 80, 47, 49, 46, 48, 32, 52, 48, 49, 32, 85, 110, 97, 117, 116, 104, 111, 114, 105, 122, 101, 100, 39, 41, 59, 10, 101, 120, 105, 116, 59, 125, 10, 10, 101, 108, 115, 101, 32, 123, 10, 105, 102, 40, 101, 109, 112, 116, 121, 40, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 65, 85, 84, 72, 95, 80, 87, 39, 93, 41, 32, 124, 124, 32, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 65, 85, 84, 72, 95, 80, 87, 39, 93, 60, 62, 36, 112, 97, 115, 115, 32, 124, 124, 32, 101, 109, 112, 116, 121, 40, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 65, 85, 84, 72, 95, 85, 83, 69, 82, 39, 93, 41, 32, 124, 124, 32, 36, 95, 83, 69, 82, 86, 69, 82, 91, 39, 80, 72, 80, 95, 65, 85, 84, 72, 95, 85, 83, 69, 82, 39, 93, 60, 62, 36, 108, 111, 103, 105, 110, 41, 10, 123, 32, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 63, 34, 59, 32, 101, 120, 105, 116, 59, 125, 10, 125, 10, 42, 47, 10, 10, 10, 10, 105, 102, 32, 40, 33, 101, 109, 112, 116, 121, 40, 36, 95, 71, 69, 84, 91, 39, 97, 99, 39, 93, 41, 41, 32, 123, 36, 97, 99, 32, 61, 32, 36, 95, 71, 69, 84, 91, 39, 97, 99, 39, 93, 59, 125, 10, 101, 108, 115, 101, 105, 102, 32, 40, 33, 101, 109, 112, 116, 121, 40, 36, 95, 80, 79, 83, 84, 91, 39, 97, 99, 39, 93, 41, 41, 32, 123, 36, 97, 99, 32, 61, 32, 36, 95, 80, 79, 83, 84, 91, 39, 97, 99, 39, 93, 59, 125, 10, 101, 108, 115, 101, 32, 123, 36, 97, 99, 32, 61, 32, 34, 115, 104, 101, 108, 108, 34, 59, 125, 10, 10, 47, 47, 32, 77, 101, 110, 117, 10, 101, 99, 104, 111, 32, 34, 10, 124, 60, 97, 32, 104, 114, 101, 102, 61, 36, 115, 101, 108, 102, 63, 97, 99, 61, 115, 104, 101, 108, 108, 62, 83, 104, 101, 108, 108, 60, 47, 97, 62, 124, 10, 124, 60, 97, 32, 104, 114, 101, 102, 61, 36, 115, 101, 108, 102, 63, 97, 99, 61, 117, 112, 108, 111, 97, 100, 62, 70, 105, 108, 101, 32, 85, 112, 108, 111, 97, 100, 60, 47, 97, 62, 124, 10, 124, 60, 97, 32, 104, 114, 101, 102, 61, 36, 115, 101, 108, 102, 63, 97, 99, 61, 116, 111, 111, 108, 115, 62, 84, 111, 111, 108, 115, 60, 47, 97, 62, 124, 10, 124, 60, 97, 32, 104, 114, 101, 102, 61, 36, 115, 101, 108, 102, 63, 97, 99, 61, 101, 118, 97, 108, 62, 80, 72, 80, 32, 69, 118, 97, 108, 32, 67, 111, 100, 101, 60, 47, 97, 62, 124, 10, 124, 60, 97, 32, 104, 114, 101, 102, 61, 36, 115, 101, 108, 102, 63, 97, 99, 61, 119, 104, 111, 105, 115, 62, 87, 104, 111, 105, 115, 60, 47, 97, 62, 124, 10, 60, 98, 114, 62, 60, 98, 114, 62, 60, 98, 114, 62, 60, 112, 114, 101, 62, 34, 59, 10, 10, 10, 115, 119, 105, 116, 99, 104, 40, 36, 97, 99, 41, 32, 123, 10, 10, 47, 47, 32, 83, 104, 101, 108, 108, 10, 99, 97, 115, 101, 32, 34, 115, 104, 101, 108, 108, 34, 58, 10, 10, 101, 99, 104, 111, 32, 60, 60, 60, 72, 84, 77, 76, 10, 60, 98, 62, 83, 104, 101, 108, 108, 60, 47, 98, 62, 10, 60, 116, 97, 98, 108, 101, 62, 10, 60, 102, 111, 114, 109, 32, 97, 99, 116, 105, 111, 110, 61, 34, 36, 115, 101, 108, 102, 34, 32, 109, 101, 116, 104, 111, 100, 61, 34, 80, 79, 83, 84, 34, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 104, 105, 100, 100, 101, 110, 34, 32, 110, 97, 109, 101, 61, 34, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 115, 104, 101, 108, 108, 34, 62, 10, 60, 116, 114, 62, 60, 116, 100, 62, 10, 36, 36, 115, 101, 114, 110, 32, 60, 105, 110, 112, 117, 116, 32, 115, 105, 122, 101, 61, 34, 53, 48, 34, 32, 116, 121, 112, 101, 61, 34, 116, 101, 120, 116, 34, 32, 110, 97, 109, 101, 61, 34, 99, 34, 62, 60, 105, 110, 112, 117, 116, 32, 97, 108, 105, 103, 110, 61, 34, 114, 105, 103, 104, 116, 34, 32, 116, 121, 112, 101, 61, 34, 115, 117, 98, 109, 105, 116, 34, 32, 118, 97, 108, 117, 101, 61, 34, 69, 110, 116, 101, 114, 34, 62, 10, 60, 47, 116, 100, 62, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 60, 116, 100, 62, 10, 60, 116, 101, 120, 116, 97, 114, 101, 97, 32, 99, 111, 108, 115, 61, 34, 49, 48, 48, 34, 32, 114, 111, 119, 115, 61, 34, 50, 53, 34, 62, 10, 72, 84, 77, 76, 59, 10, 10, 105, 102, 32, 40, 33, 101, 109, 112, 116, 121, 40, 36, 95, 80, 79, 83, 84, 91, 39, 99, 39, 93, 41, 41, 123, 10, 112, 97, 115, 115, 116, 104, 114, 117, 40, 36, 95, 80, 79, 83, 84, 91, 39, 99, 39, 93, 41, 59, 10, 125, 10, 101, 99, 104, 111, 32, 34, 60, 47, 116, 101, 120, 116, 97, 114, 101, 97, 62, 60, 47, 116, 100, 62, 36, 116, 101, 110, 100, 34, 59, 10, 98, 114, 101, 97, 107, 59, 10, 10, 10, 47, 47, 80, 72, 80, 32, 69, 118, 97, 108, 32, 67, 111, 100, 101, 32, 101, 120, 101, 99, 117, 116, 105, 111, 110, 10, 99, 97, 115, 101, 32, 34, 101, 118, 97, 108, 34, 58, 10, 10, 101, 99, 104, 111, 32, 60, 60, 60, 72, 84, 77, 76, 10, 60, 98, 62, 80, 72, 80, 32, 69, 118, 97, 108, 32, 67, 111, 100, 101, 60, 47, 98, 62, 10, 60, 116, 97, 98, 108, 101, 62, 10, 60, 102, 111, 114, 109, 32, 109, 101, 116, 104, 111, 100, 61, 34, 80, 79, 83, 84, 34, 32, 97, 99, 116, 105, 111, 110, 61, 34, 36, 115, 101, 108, 102, 34, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 104, 105, 100, 100, 101, 110, 34, 32, 110, 97, 109, 101, 61, 34, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 101, 118, 97, 108, 34, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 60, 116, 101, 120, 116, 97, 114, 101, 97, 32, 110, 97, 109, 101, 61, 34, 101, 112, 104, 112, 34, 32, 114, 111, 119, 115, 61, 34, 49, 48, 34, 32, 99, 111, 108, 115, 61, 34, 54, 48, 34, 62, 60, 47, 116, 101, 120, 116, 97, 114, 101, 97, 62, 60, 47, 116, 100, 62, 10, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 115, 117, 98, 109, 105, 116, 34, 32, 118, 97, 108, 117, 101, 61, 34, 69, 110, 116, 101, 114, 34, 62, 60, 47, 116, 100, 62, 10, 36, 116, 101, 110, 100, 10, 72, 84, 77, 76, 59, 10, 10, 105, 102, 32, 40, 105, 115, 115, 101, 116, 40, 36, 95, 80, 79, 83, 84, 91, 39, 101, 112, 104, 112, 39, 93, 41, 41, 123, 10, 101, 118, 97, 108, 40, 36, 95, 80, 79, 83, 84, 91, 39, 101, 112, 104, 112, 39, 93, 41, 59, 10, 125, 10, 98, 114, 101, 97, 107, 59, 10, 10, 10, 47, 47, 84, 101, 120, 116, 32, 116, 111, 111, 108, 115, 10, 99, 97, 115, 101, 32, 34, 116, 111, 111, 108, 115, 34, 58, 10, 10, 101, 99, 104, 111, 32, 60, 60, 60, 72, 84, 77, 76, 10, 60, 98, 62, 84, 111, 111, 108, 115, 60, 47, 98, 62, 10, 60, 116, 97, 98, 108, 101, 62, 10, 60, 102, 111, 114, 109, 32, 109, 101, 116, 104, 111, 100, 61, 34, 80, 79, 83, 84, 34, 32, 97, 99, 116, 105, 111, 110, 61, 34, 36, 115, 101, 108, 102, 34, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 104, 105, 100, 100, 101, 110, 34, 32, 110, 97, 109, 101, 61, 34, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 116, 111, 111, 108, 115, 34, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 114, 97, 100, 105, 111, 34, 32, 110, 97, 109, 101, 61, 34, 116, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 49, 34, 62, 66, 54, 52, 32, 68, 101, 99, 111, 100, 101, 60, 98, 114, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 114, 97, 100, 105, 111, 34, 32, 110, 97, 109, 101, 61, 34, 116, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 50, 34, 62, 66, 54, 52, 32, 69, 110, 99, 111, 100, 101, 60, 98, 114, 62, 60, 104, 114, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 114, 97, 100, 105, 111, 34, 32, 110, 97, 109, 101, 61, 34, 116, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 51, 34, 62, 109, 100, 53, 32, 72, 97, 115, 104, 10, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 116, 101, 120, 116, 97, 114, 101, 97, 32, 110, 97, 109, 101, 61, 34, 116, 111, 116, 34, 32, 114, 111, 119, 115, 61, 34, 53, 34, 32, 99, 111, 108, 115, 61, 34, 52, 50, 34, 62, 60, 47, 116, 101, 120, 116, 97, 114, 101, 97, 62, 60, 47, 116, 100, 62, 10, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 32, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 115, 117, 98, 109, 105, 116, 34, 32, 118, 97, 108, 117, 101, 61, 34, 69, 110, 116, 101, 114, 34, 62, 60, 47, 116, 100, 62, 10, 36, 116, 101, 110, 100, 10, 72, 84, 77, 76, 59, 10, 10, 105, 102, 32, 40, 33, 101, 109, 112, 116, 121, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 111, 116, 39, 93, 41, 32, 38, 38, 32, 33, 101, 109, 112, 116, 121, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 97, 99, 39, 93, 41, 41, 32, 123, 10, 10, 115, 119, 105, 116, 99, 104, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 97, 99, 39, 93, 41, 32, 123, 10, 10, 99, 97, 115, 101, 32, 34, 49, 34, 58, 10, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 98, 62, 34, 32, 46, 98, 97, 115, 101, 54, 52, 95, 100, 101, 99, 111, 100, 101, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 111, 116, 39, 93, 41, 46, 32, 34, 60, 47, 98, 62, 34, 59, 10, 98, 114, 101, 97, 107, 59, 10, 10, 99, 97, 115, 101, 32, 34, 50, 34, 58, 10, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 98, 62, 34, 32, 46, 98, 97, 115, 101, 54, 52, 95, 101, 110, 99, 111, 100, 101, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 111, 116, 39, 93, 41, 46, 32, 34, 60, 47, 98, 62, 34, 59, 10, 98, 114, 101, 97, 107, 59, 10, 10, 99, 97, 115, 101, 32, 34, 51, 34, 58, 10, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 98, 62, 34, 32, 46, 109, 100, 53, 40, 36, 95, 80, 79, 83, 84, 91, 39, 116, 111, 116, 39, 93, 41, 46, 32, 34, 60, 47, 98, 62, 34, 59, 10, 98, 114, 101, 97, 107, 59, 10, 125, 125, 10, 98, 114, 101, 97, 107, 59, 10, 10, 10, 47, 47, 32, 85, 112, 108, 111, 97, 100, 105, 110, 103, 10, 99, 97, 115, 101, 32, 34, 117, 112, 108, 111, 97, 100, 34, 58, 10, 10, 101, 99, 104, 111, 32, 60, 60, 60, 72, 84, 77, 76, 10, 60, 98, 62, 70, 105, 108, 101, 32, 85, 112, 108, 111, 97, 100, 60, 47, 98, 62, 10, 60, 116, 97, 98, 108, 101, 62, 10, 60, 102, 111, 114, 109, 32, 101, 110, 99, 116, 121, 112, 101, 61, 34, 109, 117, 108, 116, 105, 112, 97, 114, 116, 47, 102, 111, 114, 109, 45, 100, 97, 116, 97, 34, 32, 97, 99, 116, 105, 111, 110, 61, 34, 36, 115, 101, 108, 102, 34, 32, 109, 101, 116, 104, 111, 100, 61, 34, 80, 79, 83, 84, 34, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 104, 105, 100, 100, 101, 110, 34, 32, 110, 97, 109, 101, 61, 34, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 117, 112, 108, 111, 97, 100, 34, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 115, 105, 122, 101, 61, 34, 52, 56, 34, 32, 110, 97, 109, 101, 61, 34, 102, 105, 108, 101, 34, 32, 116, 121, 112, 101, 61, 34, 102, 105, 108, 101, 34, 62, 60, 47, 116, 100, 62, 10, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 115, 105, 122, 101, 61, 34, 52, 56, 34, 32, 118, 97, 108, 117, 101, 61, 34, 36, 100, 111, 99, 114, 47, 34, 32, 110, 97, 109, 101, 61, 34, 112, 97, 116, 104, 34, 32, 116, 121, 112, 101, 61, 34, 116, 101, 120, 116, 34, 62, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 115, 117, 98, 109, 105, 116, 34, 32, 118, 97, 108, 117, 101, 61, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 34, 62, 60, 47, 116, 100, 62, 10, 36, 116, 101, 110, 100, 10, 72, 84, 77, 76, 59, 10, 10, 105, 102, 32, 40, 105, 115, 115, 101, 116, 40, 36, 95, 80, 79, 83, 84, 91, 39, 112, 97, 116, 104, 39, 93, 41, 41, 123, 10, 10, 36, 117, 112, 108, 111, 97, 100, 102, 105, 108, 101, 32, 61, 32, 36, 95, 80, 79, 83, 84, 91, 39, 112, 97, 116, 104, 39, 93, 46, 36, 95, 70, 73, 76, 69, 83, 91, 39, 102, 105, 108, 101, 39, 93, 91, 39, 110, 97, 109, 101, 39, 93, 59, 10, 105, 102, 32, 40, 36, 95, 80, 79, 83, 84, 91, 39, 112, 97, 116, 104, 39, 93, 61, 61, 34, 34, 41, 123, 36, 117, 112, 108, 111, 97, 100, 102, 105, 108, 101, 32, 61, 32, 36, 95, 70, 73, 76, 69, 83, 91, 39, 102, 105, 108, 101, 39, 93, 91, 39, 110, 97, 109, 101, 39, 93, 59, 125, 10, 10, 105, 102, 32, 40, 99, 111, 112, 121, 40, 36, 95, 70, 73, 76, 69, 83, 91, 39, 102, 105, 108, 101, 39, 93, 91, 39, 116, 109, 112, 95, 110, 97, 109, 101, 39, 93, 44, 32, 36, 117, 112, 108, 111, 97, 100, 102, 105, 108, 101, 41, 41, 32, 123, 10, 32, 32, 32, 32, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 36, 117, 112, 108, 111, 97, 100, 102, 105, 108, 101, 92, 110, 34, 59, 10, 32, 32, 32, 32, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 34, 32, 46, 36, 95, 70, 73, 76, 69, 83, 91, 39, 102, 105, 108, 101, 39, 93, 91, 39, 110, 97, 109, 101, 39, 93, 46, 32, 34, 92, 110, 34, 59, 10, 32, 32, 32, 32, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 34, 32, 46, 36, 95, 70, 73, 76, 69, 83, 91, 39, 102, 105, 108, 101, 39, 93, 91, 39, 115, 105, 122, 101, 39, 93, 46, 32, 34, 92, 110, 34, 59, 10, 10, 125, 32, 101, 108, 115, 101, 32, 123, 10, 32, 32, 32, 32, 112, 114, 105, 110, 116, 32, 34, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 46, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 92, 110, 34, 59, 10, 32, 32, 32, 32, 112, 114, 105, 110, 116, 95, 114, 40, 36, 95, 70, 73, 76, 69, 83, 41, 59, 10, 125, 10, 125, 10, 98, 114, 101, 97, 107, 59, 10, 10, 10, 47, 47, 32, 87, 104, 111, 105, 115, 10, 99, 97, 115, 101, 32, 34, 119, 104, 111, 105, 115, 34, 58, 10, 101, 99, 104, 111, 32, 60, 60, 60, 72, 84, 77, 76, 10, 60, 98, 62, 87, 104, 111, 105, 115, 60, 47, 98, 62, 10, 60, 116, 97, 98, 108, 101, 62, 10, 60, 102, 111, 114, 109, 32, 97, 99, 116, 105, 111, 110, 61, 34, 36, 115, 101, 108, 102, 34, 32, 109, 101, 116, 104, 111, 100, 61, 34, 80, 79, 83, 84, 34, 62, 10, 60, 105, 110, 112, 117, 116, 32, 116, 121, 112, 101, 61, 34, 104, 105, 100, 100, 101, 110, 34, 32, 110, 97, 109, 101, 61, 34, 97, 99, 34, 32, 118, 97, 108, 117, 101, 61, 34, 119, 104, 111, 105, 115, 34, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 115, 105, 122, 101, 61, 34, 52, 48, 34, 32, 116, 121, 112, 101, 61, 34, 116, 101, 120, 116, 34, 32, 110, 97, 109, 101, 61, 34, 119, 113, 34, 62, 60, 47, 116, 100, 62, 10, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 10, 60, 116, 100, 62, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 58, 60, 47, 116, 100, 62, 10, 60, 116, 100, 62, 60, 105, 110, 112, 117, 116, 32, 115, 105, 122, 101, 61, 34, 52, 48, 34, 32, 116, 121, 112, 101, 61, 34, 116, 101, 120, 116, 34, 32, 110, 97, 109, 101, 61, 34, 119, 115, 101, 114, 34, 32, 118, 97, 108, 117, 101, 61, 34, 119, 104, 111, 105, 115, 46, 114, 105, 112, 101, 46, 110, 101, 116, 34, 62, 60, 47, 116, 100, 62, 10, 60, 47, 116, 114, 62, 10, 60, 116, 114, 62, 60, 116, 100, 62, 10, 60, 105, 110, 112, 117, 116, 32, 97, 108, 105, 103, 110, 61, 34, 114, 105, 103, 104, 116, 34, 32, 116, 121, 112, 101, 61, 34, 115, 117, 98, 109, 105, 116, 34, 32, 118, 97, 108, 117, 101, 61, 34, 69, 110, 116, 101, 114, 34, 62, 10, 60, 47, 116, 100, 62, 60, 47, 116, 114, 62, 10, 36, 116, 101, 110, 100, 10, 72, 84, 77, 76, 59, 10, 10, 105, 102, 32, 40, 105, 115, 115, 101, 116, 40, 36, 95, 80, 79, 83, 84, 91, 39, 119, 113, 39, 93, 41, 32, 38, 38, 32, 36, 95, 80, 79, 83, 84, 91, 39, 119, 113, 39, 93, 60, 62, 34, 34, 41, 32, 123, 10, 10, 105, 102, 32, 40, 101, 109, 112, 116, 121, 40, 36, 95, 80, 79, 83, 84, 91, 39, 119, 115, 101, 114, 39, 93, 41, 41, 32, 123, 36, 119, 115, 101, 114, 32, 61, 32, 34, 119, 104, 111, 105, 115, 46, 114, 105, 112, 101, 46, 110, 101, 116, 34, 59, 125, 32, 101, 108, 115, 101, 32, 36, 119, 115, 101, 114, 32, 61, 32, 36, 95, 80, 79, 83, 84, 91, 39, 119, 115, 101, 114, 39, 93, 59, 10, 10, 36, 113, 117, 101, 114, 116, 121, 32, 61, 32, 36, 95, 80, 79, 83, 84, 91, 39, 119, 113, 39, 93, 46, 34, 92, 114, 92, 110, 34, 59, 10, 36, 102, 112, 32, 61, 32, 102, 115, 111, 99, 107, 111, 112, 101, 110, 40, 36, 119, 115, 101, 114, 44, 32, 52, 51, 41, 59, 10, 10, 105, 102, 32, 40, 33, 36, 102, 112, 41, 32, 123, 101, 99, 104, 111, 32, 34, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 32, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 239, 191, 189, 34, 59, 125, 32, 101, 108, 115, 101, 32, 123, 10, 102, 112, 117, 116, 115, 40, 36, 102, 112, 44, 32, 36, 113, 117, 101, 114, 116, 121, 41, 59, 10, 119, 104, 105, 108, 101, 40, 33, 102, 101, 111, 102, 40, 36, 102, 112, 41, 41, 123, 101, 99, 104, 111, 32, 102, 103, 101, 116, 115, 40, 36, 102, 112, 44, 32, 52, 48, 48, 48, 41, 59, 125, 10, 102, 99, 108, 111, 115, 101, 40, 36, 102, 112, 41, 59, 10, 125, 125, 10, 98, 114, 101, 97, 107, 59, 10, 10, 10, 125, 10, 63, 62, 10, 60, 47, 112, 114, 101, 62, 10, 60, 47, 98, 111, 100, 121, 62, 10, 60, 47, 104, 116, 109, 108, 62, 10}) 29 | if err != nil { 30 | t.Error(err.Error()) 31 | return 32 | } 33 | if !isMatched { 34 | t.Error("not matched") 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Stat.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "encoding/json" 5 | "math" 6 | "regexp" 7 | "strings" 8 | 9 | "github.com/grd/stat" 10 | ) 11 | 12 | /* 13 | WebshellDetector - Refactor version 1 14 | Date 0814 15 | Author Cyrus 16 | Intro Statastic model for PHP file 17 | */ 18 | 19 | type textStat struct { 20 | LM float64 // int64 in fact 21 | LVC float64 22 | WM float64 // int64 in fact 23 | WVC float64 24 | SR float64 25 | TR float64 26 | SPL float64 27 | IE float64 28 | } 29 | 30 | type arrayStatState struct { 31 | MinStat textStat 32 | MaxStat textStat 33 | } 34 | 35 | var nan = math.NaN() 36 | var nanStat = textStat{nan, nan, nan, nan, nan, nan, nan, nan} 37 | 38 | func newArrayStatState() arrayStatState { 39 | 40 | return arrayStatState{nanStat, nanStat} 41 | } 42 | 43 | func (self *arrayStatState) Load(bytes []byte) error { 44 | return json.Unmarshal(bytes, self) 45 | } 46 | 47 | func outOfRange(x float64, min float64, max float64) bool { 48 | if min != math.NaN() { 49 | if x < min { 50 | return true 51 | } 52 | } 53 | if max != math.NaN() { 54 | if x > max { 55 | return true 56 | } 57 | } 58 | return false 59 | } 60 | 61 | func statLines(src string) []int64 { 62 | // get all lines 63 | var result []int64 64 | splitResult := strings.Split(src, "\n") 65 | for _, v := range splitResult { 66 | result = append(result, int64(len(v))) 67 | } 68 | return result 69 | } 70 | 71 | func lineMax(src string) int64 { 72 | lines := stat.IntSlice(statLines(src)) 73 | if len(lines) > 0 { 74 | result, _ := stat.Max(lines) 75 | return int64(result) 76 | } else { 77 | return 0 78 | } 79 | 80 | } 81 | 82 | func lineVariationCoefficient(src string) float64 { 83 | lines := stat.IntSlice(statLines(src)) 84 | return math.Sqrt(stat.Variance(lines)) / stat.Mean(lines) 85 | } 86 | 87 | func statWords(src string) []int64 { 88 | var result []int64 89 | l := int64(0) 90 | for _, c := range src { 91 | if (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) { 92 | l++ 93 | } else if l != 0 { 94 | result = append(result, l) 95 | l = 0 96 | } 97 | } 98 | 99 | if l != 0 { 100 | result = append(result, l) 101 | } 102 | 103 | return result 104 | } 105 | 106 | func wordMax(src string) int64 { 107 | words := stat.IntSlice(statWords(src)) 108 | if len(words) > 0 { 109 | result, _ := stat.Max(words) 110 | return int64(result) 111 | } else { 112 | return 0 113 | } 114 | } 115 | 116 | func wordVariationCoefficient(src string) float64 { 117 | words := stat.IntSlice(statWords(src)) 118 | return math.Sqrt(stat.Variance(words)) / stat.Mean(words) * 100 119 | } 120 | 121 | func symbolRatio(src string) float64 { 122 | symbolReg, _ := regexp.Compile(`[^a-zA-Z0-9]`) 123 | symbolNumber := len(symbolReg.FindAllString(src, -1)) 124 | if len(src) > 0 { 125 | return float64(symbolNumber) / float64(len(src)) * 100 126 | } else { 127 | return 1 128 | } 129 | } 130 | 131 | func tagRatio(src string) float64 { 132 | tagReg, _ := regexp.Compile(`<[\x00-\xFF]*?>`) 133 | tagNumber := len(tagReg.FindAllString(src, -1)) 134 | lenWords := len(statWords(src)) 135 | if lenWords > 0 { 136 | return float64(tagNumber) / float64(lenWords) * 100 137 | } else { 138 | return 0 139 | } 140 | } 141 | 142 | func statementPerLine(src string) float64 { 143 | statementReg, _ := regexp.Compile(`;`) 144 | statementNumber := len(statementReg.FindAllString(src, -1)) 145 | lenLines := len(statLines(src)) 146 | if lenLines > 0 { 147 | return float64(statementNumber) / float64(lenLines) 148 | } else { 149 | return 0 150 | } 151 | } 152 | 153 | func infomationEntropy(src string) float64 { 154 | var lst []float64 155 | chrs := 0.00 156 | for i := 0; i < 256; i++ { 157 | lst = append(lst, 0) 158 | } 159 | for _, chr := range src { 160 | if 0 <= chr && chr < 256 && chr != '\n' { 161 | lst[chr]++ 162 | chrs++ 163 | } 164 | } 165 | var result float64 166 | for i := 0; i < 256; i++ { 167 | if lst[i] > 0 { 168 | result -= lst[i] / chrs * math.Log2(lst[i]/chrs) 169 | } 170 | } 171 | return result 172 | } 173 | 174 | func newTextStat(src []byte) textStat { 175 | var self textStat 176 | str_src := string(src) 177 | self.LM = float64(lineMax(str_src)) 178 | self.LVC = lineVariationCoefficient(str_src) 179 | self.WM = float64(wordMax(str_src)) 180 | self.WVC = wordVariationCoefficient(str_src) 181 | self.SR = symbolRatio(str_src) 182 | self.TR = tagRatio(str_src) 183 | self.SPL = statementPerLine(str_src) 184 | self.IE = infomationEntropy(str_src) 185 | return self 186 | } 187 | 188 | func (self textStat) GetVector() []float64 { 189 | return []float64{self.LM, self.LVC, self.WM, self.WVC, self.SR, self.TR, self.SPL, self.IE} 190 | } 191 | 192 | func (self textStat) IsAbnormal(std arrayStatState) bool { 193 | return outOfRange(self.LM, std.MinStat.LM, std.MaxStat.LM) || 194 | outOfRange(self.LVC, std.MinStat.LVC, std.MaxStat.LVC) || 195 | outOfRange(self.WM, std.MinStat.WM, std.MaxStat.WM) || 196 | outOfRange(self.WVC, std.MinStat.WVC, std.MaxStat.WVC) || 197 | outOfRange(self.SR, std.MinStat.SR, std.MaxStat.SR) || 198 | outOfRange(self.TR, std.MinStat.TR, std.MaxStat.TR) || 199 | outOfRange(self.SPL, std.MinStat.SPL, std.MaxStat.SPL) || 200 | outOfRange(self.IE, std.MinStat.IE, std.MaxStat.IE) 201 | } 202 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Stat_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test_Stat_NewStat(t *testing.T) { 8 | src := []byte("") 9 | stat := newTextStat(src) 10 | std := textStat{19, 0.8724939396583133, 5, 57.94256397693845, 48.64864864864865, 16.666666666666664, 0.5, 4.0796786498829745} 11 | if stat != std { 12 | t.Error("FAILED - Test_Stat_NewStat") 13 | } 14 | } 15 | 16 | func Test_Stat_GetVector(t *testing.T) { 17 | src := []byte("") 18 | statVector := newTextStat(src).GetVector() 19 | std := []float64{19, 0.8724939396583133, 5, 57.94256397693845, 48.64864864864865, 16.666666666666664, 0.5, 4.0796786498829745} 20 | for i, _ := range statVector { 21 | if statVector[i] != std[i] { 22 | t.Error("FAILED - Test_Stat_NewStat") 23 | } 24 | } 25 | } 26 | 27 | func Test_Stat_IsAbnormal(t *testing.T) { 28 | detector, _ := NewDefaultDetector(stdin, stdout) 29 | 30 | src1 := []byte("") 31 | statResult1 := newTextStat(src1).IsAbnormal(detector.statState) 32 | if statResult1 != false { 33 | t.Error("FAILED - Test_Stat_IsAbnormal - data1") 34 | } 35 | 36 | src2 := []byte("aaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaa") 37 | statResult2 := newTextStat(src2).IsAbnormal(detector.statState) 38 | if statResult2 != true { 39 | t.Error("FAILED - Test_Stat_IsAbnormal - data2") 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Words.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import "github.com/CyrusF/go-bayesian" 4 | 5 | /* 6 | WebshellDetector - Refactor version 1 7 | Date 0814 8 | Author Twice 9 | Intro predict webshell by words using Naive Bayes 10 | */ 11 | 12 | type words struct { 13 | data []string 14 | } 15 | 16 | func (words words) Predict(model *bayesian.Classifier) float64 { 17 | score, _, _ := model.Classify(words.data...) 18 | return score["webshell"] / (score["webshell"] + score["normal"]) 19 | } 20 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/Words_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import "testing" 4 | 5 | func Test_Words_Predict(t *testing.T) { 6 | detector, _ := NewDefaultDetector(stdin, stdout) 7 | words1 := words{[]string{"f", "g", "hello", "world"}} 8 | result1 := words1.Predict(detector.wordsModel) 9 | if result1 >= 0.5 { 10 | t.Log(result1) 11 | t.Error("data1") 12 | } 13 | words2 := words{[]string{"create_function", "assert"}} 14 | result2 := words2.Predict(detector.wordsModel) 15 | if result2 <= 0.5 { 16 | t.Log(result2) 17 | t.Error("data2") 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/genOpSerialData_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | // import ( 4 | // "fmt" 5 | // "io/ioutil" 6 | // "os" 7 | // "path/filepath" 8 | // "strings" 9 | // "testing" 10 | // ) 11 | 12 | // var detO *Detector 13 | 14 | // var isWebshellO = 0 15 | // var resultO = strings.Builder{} 16 | 17 | // func walkFunc_genOpSerialData(path string, info os.FileInfo, _ error) error { 18 | 19 | // if filepath.Ext(path) != ".php" { 20 | // return nil 21 | // } 22 | 23 | // fmt.Printf("%-50v [%v]\n", info.Name(), path) 24 | // src, _ := ioutil.ReadFile(path) 25 | // ast, err := newAstFromServer(src) 26 | // if err != nil { 27 | // fmt.Println(err.Error()) 28 | // return nil 29 | // } 30 | 31 | // resultO.WriteString(fmt.Sprint(isWebshellO, " ")) 32 | // for i, e := range ast.GetOpSerial(&detO.hashState).data { 33 | // if e != 0 { 34 | // resultO.WriteString(fmt.Sprintf("%v:%v ", i+1, e)) 35 | // } 36 | // } 37 | // resultO.WriteString("\n") 38 | 39 | // return nil 40 | // } 41 | 42 | // func Test_genOpSerialData(t *testing.T) { 43 | // detO, _ = NewDefaultDetector(stdin, stdout) 44 | // isWebshellO = 0 45 | // filepath.Walk("../sample/frame", walkFunc_genOpSerialData) 46 | // isWebshellO = 1 47 | // filepath.Walk("../sample/webshell", walkFunc_genOpSerialData) 48 | // isWebshellO = 0 49 | // filepath.Walk("../sample/predict/frame", walkFunc_genOpSerialData) 50 | // isWebshellO = 1 51 | // filepath.Walk("../sample/predict/webshell", walkFunc_genOpSerialData) 52 | 53 | // ioutil.WriteFile("../tools/cross-validation tool/MetaData/opSerialData.txt", []byte(resultO.String()), 0600) 54 | // } 55 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/genProcessorData_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | // import ( 4 | // "fmt" 5 | // "io/ioutil" 6 | // "os" 7 | // "path/filepath" 8 | // "strings" 9 | // "testing" 10 | // ) 11 | 12 | // var detP *Detector 13 | 14 | // var isWebshellP = 0 15 | // var resultP = strings.Builder{} 16 | 17 | // func walkFunc_genProcessorData(path string, info os.FileInfo, _ error) error { 18 | 19 | // if filepath.Ext(path) != ".php" { 20 | // return nil 21 | // } 22 | 23 | // fmt.Printf("%-50v [%v]\n", info.Name(), path) 24 | // src, _ := ioutil.ReadFile(path) 25 | // proc, err := newProcessorFromSrc(detP, src) 26 | // if err != nil { 27 | // fmt.Println(err.Error()) 28 | // return nil 29 | // } 30 | 31 | // resultP.WriteString(fmt.Sprint(isWebshellP, " ")) 32 | // for i, e := range proc.stat.GetVector() { 33 | // resultP.WriteString(fmt.Sprintf("%v:%v ", i+1, e)) 34 | // } 35 | // resultP.WriteString(fmt.Sprintf("9:%v ", proc.opSerial.Predict(proc.detector.opSerialModel))) 36 | // resultP.WriteString(fmt.Sprintf("10:%v ", proc.words.Predict(proc.detector.wordsModel))) 37 | // resultP.WriteString("\n") 38 | 39 | // return nil 40 | // } 41 | 42 | // func Test_genProcessorData(t *testing.T) { 43 | // detP, _ = NewDefaultDetector(stdin, stdout) 44 | // isWebshellP = 0 45 | // filepath.Walk("../sample/frame", walkFunc_genProcessorData) 46 | // isWebshellP = 1 47 | // filepath.Walk("../sample/webshell", walkFunc_genProcessorData) 48 | // isWebshellP = 0 49 | // filepath.Walk("../sample/predict/frame", walkFunc_genProcessorData) 50 | // isWebshellP = 1 51 | // filepath.Walk("../sample/predict/webshell", walkFunc_genProcessorData) 52 | 53 | // ioutil.WriteFile("../tools/cross-validation tool/MetaData/processorData.txt", []byte(resultP.String()), 0600) 54 | // } 55 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/genWordsData_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | // import ( 4 | // "encoding/json" 5 | // "fmt" 6 | // "io/ioutil" 7 | // "os" 8 | // "path/filepath" 9 | // "testing" 10 | // ) 11 | 12 | // var isWebshellW = 0 13 | // var resultW struct { 14 | // Data [][]string 15 | // Expect []int 16 | // } 17 | 18 | // func walkFunc_genWordsData(path string, info os.FileInfo, _ error) error { 19 | 20 | // if filepath.Ext(path) != ".php" { 21 | // return nil 22 | // } 23 | 24 | // fmt.Printf("%-50v [%v]\n", info.Name(), path) 25 | // src, _ := ioutil.ReadFile(path) 26 | // ast, err := newAstFromServer(src) 27 | // if err != nil { 28 | // fmt.Println(err.Error()) 29 | // return nil 30 | // } 31 | 32 | // words := ast.GetWords() 33 | // resultW.Data = append(resultW.Data, words.data) 34 | // resultW.Expect = append(resultW.Expect, isWebshellW) 35 | 36 | // return nil 37 | // } 38 | 39 | // func Test_genWordsData(t *testing.T) { 40 | // isWebshellW = 0 41 | // filepath.Walk("../sample/frame", walkFunc_genWordsData) 42 | // isWebshellW = 1 43 | // filepath.Walk("../sample/webshell", walkFunc_genWordsData) 44 | // isWebshellW = 0 45 | // filepath.Walk("../sample/predict/frame", walkFunc_genWordsData) 46 | // isWebshellW = 1 47 | // filepath.Walk("../sample/predict/webshell", walkFunc_genWordsData) 48 | 49 | // data, err := json.Marshal(resultW) 50 | // if err != nil { 51 | // fmt.Println(err.Error()) 52 | // return 53 | // } 54 | 55 | // ioutil.WriteFile("../tools/cross-validation tool/MetaData/wordsData.txt", data, 0600) 56 | // } 57 | -------------------------------------------------------------------------------- /tool/webshell-detector/src/main_test.go: -------------------------------------------------------------------------------- 1 | package WebshellDetector 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "../php" 8 | ) 9 | 10 | var stdin *os.File 11 | var stdout *os.File 12 | 13 | func TestMain(m *testing.M) { 14 | php.Start() 15 | stdin = php.Stdin 16 | stdout = php.Stdout 17 | 18 | code := m.Run() 19 | 20 | os.Exit(code) 21 | } 22 | -------------------------------------------------------------------------------- /tool/webshell-detector/static/output-cli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaitin/cloudwalker/d0a30200a3c498df03db1e527548a2c90baa1bd2/tool/webshell-detector/static/output-cli.png -------------------------------------------------------------------------------- /tool/webshell-detector/static/webshell-test-html.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chaitin/cloudwalker/d0a30200a3c498df03db1e527548a2c90baa1bd2/tool/webshell-detector/static/webshell-test-html.png --------------------------------------------------------------------------------