├── LICENSE ├── README.md ├── VERSION ├── images ├── packet-strider-ssh tcpdump.pcap stream 0 - Data Movement.png ├── packet-strider-ssh tcpdump.pcap stream 0 - Keystrokes.png ├── packet-strider-ssh tcpdump.pcap stream 0 - Packet Size Histogram.png ├── screen output.png ├── screen output_2.png ├── strider_200w.png ├── strider_400w.png ├── strider_640w.png ├── strider_800w.png └── strider_orig.png ├── python └── packetStrider-ssh.py └── zeek ├── README.md ├── packetSrider_AgentForwarding.zeek ├── packetSrider_R_option.zeek ├── packetStrider_reverse_init.zeek ├── packetStrider_reverse_login_FAILED.zeek └── packetStrider_reverse_login_SUCCESS.zeek /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Packet Strider (v0.21) 2 | ![alt text](https://github.com/benjeems/packetStrider/blob/master/images/strider_400w.png "strider logo") 3 | 4 | 5 | ## Summary 6 | packetStrider for SSH is a packet forensics tool that aims to provide valuable insight into the nature of SSH traffic, shining a light into the corners of SSH network traffic where golden nuggets of information previously lay in the dark. 7 | 8 | ## The problem that packet strider aims to help with (AKA Why?) 9 | SSH is obviously encrypted, yet valuable contextual information still exists within the network traffic that can go towards TTP's, intent, success and magnitude of actions on objectives. There may even exist situations where valuable context is not available or deleted from hosts, and so having an immutable and un-alterable passive network capture gives additional forensic context. "Packets don't lie". 10 | 11 | Separately to the forensic context, packet strider predictions could also be used in an active fashion, for example to shun/RST forward connections if a tunneled reverse SSH session initiation feature is predicted within, even before reverse authentication is offered. 12 | 13 | ## The broad techniques of packet strider (AKA How?) 14 | - Builds a rich feature set in the form of pandas dataframes. Over 40 features are engineered from packet metadata such as SSH Protocol message content, normalized statistics, direction, size, latency and sliding window features. 15 | - Strides through this feature set numerous times using sliding windows (Inspired by Convolutional Neural networks) to predict: 16 | - The use -R option in the forward session - this is what *enables* a Reverse connection to be made later in the session. This artefact is discovered very early in the session, directly after the forward session is authenticated. This is the first available warning sign that Reverse sessions are possible. 17 | - Initiation of the Reverse SSH session, this can occur at any point (early, or late) in the forward session. This is discovered prior to the Reverse session being authenticated successfully. This is the second warning sign, in that a reverse session has just been requested and setup for authentication. 18 | - Success and/or Failure of the Reverse session authentication. This is the third and final warning sign, after this point you know someone is on your host, inside a reverse session. 19 | - The use of the -A option (SSH Agent Forwarding), which enables the client to share it's local SSH private keys with the server. This functionality is generally considered dangerous. 20 | References: 21 | https://matrix.org/blog/2019/05/08/post-mortem-and-remediations-for-apr-11-security-incident 22 | https://skylightcyber.com/2019/09/26/all-your-cloud-are-belong-to-us-cve-2019-12491/ 23 | https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-12491 24 | - All predictions and metadata reports on a stream by stream basis. 25 | - Human or scripted, based on timing deltas. 26 | - Is the server already known to the client? or was it the first time a connection between the two has been made. This is done through packet deltas associated with known_hosts. 27 | - Whether a client certificate or password auth was used, and if length of password is 8 chars or less. 28 | - keystrokes, delete key press, enter key presses (cut and paste and up/down is YMMV/experimental). 29 | - exfil/infil data movement predictions in both Forward and Reverse sessions. 30 | - Works on interactive sessions as well as file based ssh file transfer apps (eg scp, putty, cyberduck etc). 31 | 32 | ## Getting started 33 | Python3 has been used, and you will need the following modules (YMMV on python2) 34 | 35 | `pip3 install pandas matplotlib pyshark` 36 | 37 | Usage: 38 | 39 | `python3 packetStrider-ssh.py -h` 40 | 41 | Output: 42 | 43 | ``` 44 | usage: packetStrider-ssh.py [-h] [-f FILE] [-n NSTREAM] [-m] [-k] [-p] 45 | [-z ZOOM] [-d DIRECTION] [-o OUTPUT_DIR] 46 | [-w WINDOW] [-s STRIDE] 47 | 48 | packetStrider-ssh is a packet forensics tool for SSH. It creates a rich 49 | feature set from packet metadata such SSH Protocol message content, direction, 50 | size, latency and sequencing. It performs pattern matching on these features, 51 | using statistical analysis, and sliding windows to predict session initiation, 52 | keystrokes, human/script behavior, password length, use of client 53 | certificates, context into the historic nature of client/server contact and 54 | exfil/infil data movement characteristics in both Forward and Reverse sessions 55 | 56 | optional arguments: 57 | -h, --help show this help message and exit 58 | -f FILE, --file FILE pcap file to analyze 59 | -n NSTREAM, --nstream NSTREAM 60 | Perform analysis only on stream n 61 | -m, --metaonly Display stream metadata only 62 | -k, --keystrokes Perform keystroke prediction 63 | -p, --predict_plot Plot data movement and keystrokes 64 | -z ZOOM, --zoom ZOOM Narrow down/zoom the analysis and plotting to only 65 | packets "x-y" 66 | -d DIRECTION, --direction DIRECTION 67 | Perform analysis on SSH direction : "forward", 68 | "reverse" OR "both" 69 | -o OUTPUT_DIR, --output_dir OUTPUT_DIR 70 | Directory to output plots 71 | -w WINDOW, --window WINDOW 72 | Sliding window size, # of packets to side of window 73 | center packet, default is 2 74 | -s STRIDE, --stride STRIDE 75 | Stride between sliding windows, default is 1 76 | ``` 77 | 78 | 79 | ## Example 80 | The pcap "forward_reverse.pcap" is from a common TTP of a Reverse SSH shell, a favorite of red teams everywhere. Specifically the following commands were used, to highlight the capabilities of packet strider in a simple way: 81 | - Forward connection from victim 82 | - The command for the forward session was `ssh user@1.2.3.4 -R 31337:localhost:22` which binds local port 31337 ready for the reverse SSH connection back to the victim PC. This connection can be effected in many ways including manually, by an RCE, SSRF, or some form of persistence. For the purpose of this demo, it is a manual standard forward session. 83 | - This was NOT the first time the client has seen the server , we see this because the delta for related packets was very small , the server's key fingerprint was already in the client's known_hosts, so the user was not prompted to add it - which would increase the latency of packets. 84 | - Two consecutive failed password logins by a human, followed by a successful login with an 8+ character password. 85 | - `ls` is typed in forward session, in this sequence: **'l'** 'w' 'w' 'back-space' 'back-space' **'s'** and then enter. The total size of data over the wire that is transmitted (as the output of ls) is classified as infiltration, given that is inbound. 86 | 87 | - Now on the attacker's machine (the server), a reverse shell is initiated back to the victim: 88 | - `ssh victim@localhost -p 31337`. At this point, which is even *before authentication process begins*, packet strider has identified the Reverse session SSH initiation, at packet 72 89 | - Now the attacker has a reverse shell on the victim host. From here they can turn off history settings, and run whatever lateral movement or ransacking highinks they desire. The simple examples in this demo are initial user recon. 90 | - `last` is run in the form of keystrokes **'l' 'a' 's'** 'r' 'delete' **'t'** 'enter' 91 | - `who`is run in the form of **'w' 'h' 'o'** 'enter' 92 | - `exit`is run in the form of **'e' 'x' 'i' 't'** 93 | - Then finally with the Forward session the session is closed, just to demonstrate that the forward SSH feature detection still works. 94 | - `exit` 95 | 96 | Network traffic from this activity is saved to tcpdump.pcap and now it's time to run Packet Strider. 97 | 98 | `python3 packetStrider-ssh.py -f tcpdump.pcap -k -p -o out` 99 | 100 | ![alt text](https://github.com/benjeems/packetStrider/blob/master/images/screen%20output_2.png "Screen Output") 101 | 102 | This plot shows a timeline of key predictions (image has been annotated here) 103 | ![alt text](https://github.com/benjeems/packetStrider/blob/master/images/packet-strider-ssh%20tcpdump.pcap%20stream%200%20-%20Keystrokes.png "Keystroke timeline") 104 | 105 | This plot shows some window statistics, useful for a deep dive and experimenting with features. 106 | ![alt text](https://github.com/benjeems/packetStrider/blob/master/images/packet-strider-ssh%20tcpdump.pcap%20stream%200%20-%20Data%20Movement.png "Data movement packet stats") 107 | 108 | This plot shows a simple histogram 109 | ![alt text](https://github.com/benjeems/packetStrider/blob/master/images/packet-strider-ssh%20tcpdump.pcap%20stream%200%20-%20Packet%20Size%20Histogram.png "Simple packet histogram") 110 | 111 | ## Inspiration 112 | This project was done as a personal Proof of Concept, as a way for me to practice with some data science libraries in Python, it was heavily inspired by my Coursera studies in Machine Learning and Data Science, in particular the pandas library and the way in which Convolutional Neural Networks (CNN) "stride" through image pixel sets using sliding windows to detect certain features within. 113 | 114 | ## Tips 115 | Packet Strider does a vast amount of "striding" in full capacity mode. This can result in some substantial resource usage if the pcap is large, or more precisely if there are many packets in the pcap. Here are some speed up tips, these are particularly useful as an initial run for example just to see if there was reverse SSH activity predicted, and then adding functionality if you desire. 116 | - Ensure you are running with the latest patches of modules that do some heavy lifting, eg pyshark/tshark, pandas and matplotlib. 117 | - The -p --predict_plot option is the most intensive operation. Think about just running with the output to terminal, and then see if you'd like this plotted. 118 | - Use the -m --metaonly option. This only retrieves the high level metadata such as Protocol names and HASSH data. This can be useful to quickly determine if you are dealing with an interactive session using OpenSSH, or with a file transfer client like Cyberduck. 119 | - Pre filter the pcap to the ssh traffic. 120 | - Pre filter the pcap to the stream you want, which you may have learned by previously running with the speedy -m --metaonly option. You can examine only stream "NSTREAM" with the "-n NSTREAM" option, or you can pre filter with wireshark etc. 121 | - There may be times when you identify something interesting in a subset of a very large packet set. Here you can use the zoom feature to only examine and plot the packets in the region you are interested in. Use -z ZOOM, --zoom ZOOM for this. eg -z 100-500 122 | - Most times you will be interested in understanding keystroke activity, so while not using the -k option will save processing speed, it also means you won't get this valuable insight. 123 | 124 | ## TODO 125 | - More protocols! 126 | - Look at Multi threading and see where this can help processing speed. 127 | - Improve efficiency of script, particularly plotting times. 128 | - Improve the Pasting indicator 129 | - Improve the 'up/down' key indicator 130 | - Annotate plots with imagemagick or similar 131 | - Improve the reporting function, write out to disk. 132 | - The Reverse key indicator is conservative because of packet encapsulation can potentially report two keystrokes. This issue does not exist for forward keystrokes, as the packet order has been treated in case they come in out of order. Examine options here. 133 | - Port to golang for speed 134 | - Real time mode 135 | - Examine the effect of additional tunneling local ports over the forward connection. 136 | 137 | ## Disclaimer 138 | Use at your own risk. See License terms. 139 | 140 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | Version 0.21 (29 September 2019) 2 | - Added support for when key sharing via Agent Forwarding. eg https://developer.github.com/v3/guides/using-ssh-agent-forwarding/ 3 | 4 | Version 0.2 (2 September 2019) 5 | - Added support for when -R is used in forward connection commandline 6 | 7 | Version 0.1 8 | - Initial Release 9 | 10 | -------------------------------------------------------------------------------- /images/packet-strider-ssh tcpdump.pcap stream 0 - Data Movement.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/packet-strider-ssh tcpdump.pcap stream 0 - Data Movement.png -------------------------------------------------------------------------------- /images/packet-strider-ssh tcpdump.pcap stream 0 - Keystrokes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/packet-strider-ssh tcpdump.pcap stream 0 - Keystrokes.png -------------------------------------------------------------------------------- /images/packet-strider-ssh tcpdump.pcap stream 0 - Packet Size Histogram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/packet-strider-ssh tcpdump.pcap stream 0 - Packet Size Histogram.png -------------------------------------------------------------------------------- /images/screen output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/screen output.png -------------------------------------------------------------------------------- /images/screen output_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/screen output_2.png -------------------------------------------------------------------------------- /images/strider_200w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/strider_200w.png -------------------------------------------------------------------------------- /images/strider_400w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/strider_400w.png -------------------------------------------------------------------------------- /images/strider_640w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/strider_640w.png -------------------------------------------------------------------------------- /images/strider_800w.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/strider_800w.png -------------------------------------------------------------------------------- /images/strider_orig.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/benjeems/packetStrider/94bee15e3351cd1c057a77182d166cf61140a3fb/images/strider_orig.png -------------------------------------------------------------------------------- /python/packetStrider-ssh.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import shutil 4 | import argparse 5 | from hashlib import md5 6 | import matplotlib.pyplot as plt 7 | import pandas as pd 8 | import pyshark 9 | import time 10 | 11 | __author__ = 'Ben Reardon' 12 | __contact__ = 'benjeems@gmail.com @benreardon' 13 | __version__ = '0.21' 14 | __license__ = 'GNU General Public License v3.0' 15 | 16 | 17 | 18 | def parse_command_args(): 19 | """Parse command line arguments""" 20 | desc = """packet-strider-ssh is a packet forensics tool for SSH. 21 | It creates a rich feature set from packet metadata such SSH Protocol message content, direction, size, latency and sequencing. 22 | It performs pattern matching on these features, using statistical analysis, and sliding windows to predict session initiation, 23 | keystrokes, human/script behaviour, password length, use of client certificates, 24 | context into the historic nature of client/server contact and exfil/infil data movement characteristics 25 | in both Forward and Reverse sessions""" 26 | parser = argparse.ArgumentParser(description=desc) 27 | helptxt = 'pcap file to analyze' 28 | parser.add_argument('-f', '--file', type=str, help=helptxt) 29 | helptxt = 'Perform analysis only on stream n' 30 | parser.add_argument('-n', '--nstream', default=-1, type=int, help=helptxt) 31 | helptxt = 'Display stream metadata only' 32 | parser.add_argument('-m', '--metaonly', help=helptxt, action='store_true') 33 | helptxt = 'Perform keystroke prediction' 34 | parser.add_argument('-k', '--keystrokes', help=helptxt, action='store_true') 35 | helptxt = 'Plot data movement and keystrokes' 36 | parser.add_argument('-p', '--predict_plot', help=helptxt, action='store_true') 37 | helptxt = 'Narrow down/zoom the analysis and plotting to only packets "x-y"' 38 | parser.add_argument('-z', '--zoom', help=helptxt, default='0', type=str) 39 | helptxt = 'Perform analysis on SSH direction : "forward", "reverse" OR "both"' 40 | parser.add_argument('-d', '--direction', help=helptxt, default='both', type=str) 41 | helptxt = 'Directory to output plots' 42 | parser.add_argument('-o', '--output_dir', type=str, help=helptxt) 43 | helptxt = 'Sliding window size, # of packets to side of window center packet, default is 2' 44 | parser.add_argument('-w', '--window', default=2, type=int, help=helptxt) 45 | helptxt = 'Stride between sliding windows, default is 1' 46 | parser.add_argument('-s', '--stride', default=1, type=int, help=helptxt) 47 | 48 | return parser.parse_args() 49 | 50 | 51 | def construct_matrix(pcap): 52 | """Returns a matrix containing packet of index, stream and size 53 | Each packet has a row in the matrix""" 54 | matrix = [] 55 | index = 0 56 | for packet in pcap: 57 | # status = '\r... Carving basic features out of packet {0}'.format(index) 58 | # sys.stdout.write(status) 59 | # sys.stdout.flush() 60 | # get the packet length 61 | length = int(packet.tcp.len) 62 | # To save memory, let server packets have a negative size 63 | # This best effort port check is required if the session init for this stream is not in the pcap 64 | if int(packet.tcp.dstport) > int(packet.tcp.srcport): 65 | length = -length 66 | # Update the matrix with details 67 | matrix = matrix + [length] 68 | index = index + 1 69 | return matrix 70 | 71 | 72 | def find_meta_size(pcap, num_packets, stream): 73 | """Finds the sizes of "tell" packets which appear just after New keys packet 74 | These relate the size for reverse and forward keystrokes and login prompt""" 75 | meta_size = [stream, 0, 0, 0, 0, 0] 76 | for i in range(0, num_packets - 4): 77 | if i == 50: 78 | break 79 | if 'message_code' in dir(pcap[i].ssh): 80 | # look for 'New Keys' code packet 21 81 | if int(pcap[i].ssh.message_code) == 21 and 'message_code' not in dir(pcap[i + 1].ssh): 82 | # Session init size_newkeys_next is the packet straight after 'New Keys') 83 | size_newkeys_next = int(pcap[i + 1].tcp.len) 84 | if int(pcap[i + 1].tcp.dstport) > int(pcap[i + 1].tcp.srcport): 85 | size_newkeys_next = -size_newkeys_next 86 | # Session init size_newkeys_next2 (should be same size as size_newkeys_next) 87 | size_newkeys_next2 = int(pcap[i + 2].tcp.len) 88 | if int(pcap[i + 2].tcp.dstport) > int(pcap[i + 2].tcp.srcport): 89 | size_newkeys_next2 = -size_newkeys_next2 90 | # Session init size_newkeys_next3 91 | size_newkeys_next3 = int(pcap[i + 3].tcp.len) 92 | if int(pcap[i + 3].tcp.dstport) > int(pcap[i + 3].tcp.srcport): 93 | size_newkeys_next3 = -size_newkeys_next3 94 | # The Forward password prompt size 95 | size_login_prompt = int(pcap[i + 4].tcp.len) 96 | if int(pcap[i + 4].tcp.dstport) > int(pcap[i + 4].tcp.srcport): 97 | size_login_prompt = -size_login_prompt 98 | # Magical observation below 99 | reverse_keystroke_size = -(size_newkeys_next - 8 + 40) 100 | 101 | meta_size = [stream, reverse_keystroke_size, 102 | size_newkeys_next, size_newkeys_next2, size_newkeys_next3, size_login_prompt] 103 | break 104 | #debug 105 | #print(meta_size) 106 | return meta_size 107 | 108 | 109 | def find_meta_hassh(pcap, num_packets, stream): 110 | """Finds the hassh parameters of each stream""" 111 | protocol_client = 'not contained in pcap' 112 | protocol_server = 'not contained in pcap' 113 | hassh = 'not contained in pcap' 114 | hassh_server = 'not contained in pcap' 115 | hassh_client_found = hassh_server_found = 0 116 | sport = dport = sip = dip = 0 117 | # Step through each packet until we find the hassh components 118 | for i in range(0, num_packets - 1): 119 | # If not in the first 50 packets, break 120 | if i == 50 or (hassh_client_found == 1 and hassh_server_found == 1): 121 | break 122 | packet = pcap[i] 123 | sip = packet.ip.src 124 | sport = int(packet.tcp.srcport) 125 | dip = packet.ip.dst 126 | dport = int(packet.tcp.dstport) 127 | 128 | # Get the Protocol names for client and server 129 | if 'protocol' in packet.ssh.field_names: 130 | if sport > dport: 131 | protocol_client = packet.ssh.protocol 132 | elif dport > sport: 133 | protocol_server = packet.ssh.protocol 134 | # Find packets with Message code 20 (kexinit components) 135 | # but discard spurious packets 136 | if 'message_code' in dir(packet.ssh): 137 | if int(packet.ssh.message_code) == 20 and \ 138 | 'spurious' not in str(packet.tcp.field_names): 139 | # If Client kexinit packet then build hassh 140 | if sport > dport: 141 | ckex = ceacts = cmacts = ccacts = '' 142 | if 'kex_algorithms' in packet.ssh.field_names: 143 | ckex = packet.ssh.kex_algorithms 144 | if 'encryption_algorithms_client_to_server' in packet.ssh.field_names: 145 | ceacts = packet.ssh.encryption_algorithms_client_to_server 146 | if 'mac_algorithms_client_to_server' in packet.ssh.field_names: 147 | cmacts = packet.ssh.mac_algorithms_client_to_server 148 | if 'compression_algorithms_client_to_server' in packet.ssh.field_names: 149 | ccacts = packet.ssh.compression_algorithms_client_to_server 150 | hassh_algos = ';'.join( 151 | [ckex, ceacts, cmacts, ccacts]) 152 | hassh = md5( 153 | hassh_algos.encode()).hexdigest() 154 | hassh_client_found = 1 155 | 156 | # If Server kexinit packet then build hassh_server 157 | if dport > sport: 158 | skex = seastc = smastc = scastc = '' 159 | if 'kex_algorithms' in packet.ssh.field_names: 160 | skex = packet.ssh.kex_algorithms 161 | if 'encryption_algorithms_server_to_client' in packet.ssh.field_names: 162 | seastc = packet.ssh.encryption_algorithms_server_to_client 163 | if 'mac_algorithms_server_to_client' in packet.ssh.field_names: 164 | smastc = packet.ssh.mac_algorithms_server_to_client 165 | if 'compression_algorithms_server_to_client' in packet.ssh.field_names: 166 | scastc = packet.ssh.compression_algorithms_server_to_client 167 | hassh_server_algos = ';'.join( 168 | [skex, seastc, smastc, scastc]) 169 | hassh_server = md5( 170 | hassh_server_algos.encode()).hexdigest() 171 | hassh_server_found = 1 172 | 173 | # sometimes server and client kex packet arrive out of order, so we must fix this. 174 | if sport < dport: 175 | # Store as temp variable 176 | sip_temp = sip 177 | sport_temp = sport 178 | dip_temp = dip 179 | dport_temp = dport 180 | # Assign the correct values 181 | dip = sip_temp 182 | sip = dip_temp 183 | sport = dport_temp 184 | dport = sport_temp 185 | 186 | meta_hassh = [stream, protocol_client, hassh, 187 | protocol_server, hassh_server, sip, sport, dip, dport] 188 | 189 | return meta_hassh 190 | 191 | 192 | def analyze(matrix, meta_size, pcap, window, stride, do_direction, do_windowing_and_plots, keystrokes, meta_hassh): 193 | 194 | # Initialialize with the first packet of the pcap 195 | # TODO this assumes that the pcap contains the entire init. 196 | results = [['packet0', 'packet0 ', 0, 0, int(pcap[0].tcp.len), 1, 0]] 197 | results_f_keystroke = [] 198 | 199 | window_matrix = [] 200 | stream = meta_size[0] 201 | reverse_init_start = results_r_logins = [] 202 | 203 | # Order the keystroke packets in this stream so they appear in realtime order 204 | print('\n ... Ordering the keystroke packets') 205 | matrix = order_keystrokes(matrix, meta_size) 206 | 207 | # only do the rest of the analysis if we have metadata. 208 | if meta_size[1] != 0: 209 | if do_direction == 'forward': 210 | print(' ... Scanning for Reverse Option being present in forward session init') 211 | results_f_R_flag_used = scan_for_reverse_session_R_option(pcap, matrix, meta_size) 212 | print(' ... Scanning for Forward login attempts') 213 | results_f_logins, fwd_logged_in_at_packet = scan_for_forward_login_attempts(matrix, meta_size, pcap) 214 | print(' ... Scanning for Forward key accepts') 215 | results_f_key_accepts = scan_for_forward_host_key_accepts(pcap, fwd_logged_in_at_packet) 216 | print(' ... Scanning for Forward login prompts') 217 | results_f_login_prompts = scan_for_forward_login_prompts(matrix, meta_size, pcap, fwd_logged_in_at_packet) 218 | print(' ... Scanning for Agent forwarding') 219 | results_f_agentForwarding = scan_for_forward_AgentForwarding(matrix, pcap, meta_hassh) 220 | # print('fwd_logged_in_at_packet={}'.format(fwd_logged_in_at_packet)) 221 | if keystrokes and fwd_logged_in_at_packet > 0: 222 | print(' ... Scanning for Forward keystrokes and enters') 223 | results_f_keystroke = scan_for_forward_keystrokes(matrix, meta_size, pcap, fwd_logged_in_at_packet) 224 | results = (results + results_f_R_flag_used + results_f_key_accepts + results_f_login_prompts + 225 | results_f_logins + results_f_agentForwarding + results_f_keystroke) 226 | else: 227 | results = results + results_f_R_flag_used + results_f_key_accepts + results_f_login_prompts + results_f_logins + results_f_agentForwarding 228 | 229 | elif do_direction == 'reverse': 230 | print(' ... Scanning for Reverse Option being present in forward session init') 231 | results_f_R_flag_used = scan_for_reverse_session_R_option(pcap, matrix, meta_size) 232 | print(' ... Scanning for Reverse Session initiation') 233 | results_r_init, reverse_init_start = scan_for_reverse_session_initiation( 234 | matrix, meta_size, pcap) 235 | if reverse_init_start != 0: 236 | print(' ... Scanning for Reverse Session logins') 237 | results_r_logins = scan_for_reverse_login_attempts(matrix, meta_size, pcap, reverse_init_start) 238 | 239 | # TODO only look for keystrokes after reverse_init_start, or do we support multi reverse sessions? 240 | if keystrokes: 241 | print(' ... Scanning for Reverse keystrokes and enters') 242 | results_r_keystroke = scan_for_reverse_keystrokes(matrix, meta_size, pcap, reverse_init_start) 243 | results = results + results_f_R_flag_used + results_r_keystroke + results_r_init + results_r_logins 244 | else: 245 | results = results + results_f_R_flag_used + results_r_init + results_r_logins 246 | elif do_direction == 'both': 247 | print(' ... Scanning for Reverse Option being present in forward session init') 248 | results_f_R_flag_used = scan_for_reverse_session_R_option(pcap, matrix, meta_size) 249 | print(' ... Scanning for Forward login attempts') 250 | results_f_logins, fwd_logged_in_at_packet = scan_for_forward_login_attempts(matrix, meta_size, pcap) 251 | print(' ... Scanning for Forward key accepts') 252 | results_f_key_accepts = scan_for_forward_host_key_accepts(pcap, fwd_logged_in_at_packet) 253 | print(' ... Scanning for Forward login prompts') 254 | results_f_login_prompts = scan_for_forward_login_prompts(matrix, meta_size, pcap, fwd_logged_in_at_packet) 255 | print(' ... Scanning for Agent forwarding') 256 | results_f_agentForwarding = scan_for_forward_AgentForwarding(matrix, pcap, meta_hassh) 257 | 258 | if keystrokes and fwd_logged_in_at_packet > 0: 259 | print(' ... Scanning for Forward keystrokes and enters') 260 | results_f_keystroke = scan_for_forward_keystrokes(matrix, meta_size, pcap, fwd_logged_in_at_packet) 261 | print(' ... Scanning for Reverse Session initiation') 262 | results_r_init, reverse_init_start = scan_for_reverse_session_initiation( 263 | matrix, meta_size, pcap) 264 | if reverse_init_start != 0: 265 | print(' ... Scanning for Reverse Session logins') 266 | results_r_logins = scan_for_reverse_login_attempts(matrix, meta_size, pcap, reverse_init_start) 267 | if keystrokes and fwd_logged_in_at_packet > 0: 268 | print(' ... Scanning for Reverse keystrokes and enters') 269 | results_r_keystroke = scan_for_reverse_keystrokes(matrix, meta_size, pcap, reverse_init_start) 270 | results = (results + results_f_R_flag_used + results_f_key_accepts + results_f_login_prompts + results_f_logins 271 | + results_f_agentForwarding + results_f_keystroke + results_r_init + results_r_logins + results_r_keystroke) 272 | else: 273 | results = (results + results_f_R_flag_used + results_f_key_accepts + results_f_login_prompts + results_f_logins + 274 | results_f_agentForwarding + results_r_init + results_r_logins) 275 | if do_windowing_and_plots: 276 | window_matrix = construct_window_matrix(pcap, matrix, stream, window, stride, meta_size, reverse_init_start, 277 | results) 278 | 279 | results = sorted(results, key=lambda x: x[2]) 280 | # window_matrix = sorted(window_matrix, key=lambda x: x[1]) 281 | results = enrich_results_time_delta(results) 282 | results = enrich_results_notes_field(results) 283 | return results, window_matrix, matrix 284 | 285 | 286 | def enrich_results_notes_field(results): 287 | """ Enriches the results with notes field""" 288 | result_enriched = [] 289 | fwd_login_time = 0 290 | for result in results: 291 | note_field = '' 292 | delta = result[7] 293 | direction = result[0] 294 | indicator = result[1] 295 | packet_size = (result[4]) 296 | if 'forward' in direction and 'login success' in indicator: 297 | fwd_login_time=result[6] 298 | 299 | # If the size of the login failure or login success is > 350 (372 in testing) then likely it is certificate auth 300 | if 'forward' in direction and ('login success' in indicator or 'login failure' in indicator): 301 | if packet_size > 350: 302 | if delta < .100: 303 | note_field = 'Delta suggests Certificate Auth, pwd to cert null or non interactive' 304 | else: 305 | note_field = 'Delta suggests Certificate Auth, pwd to cert entered interactively' 306 | 307 | else: 308 | if delta < .100: 309 | if 0 < packet_size <= 84: 310 | note_field = '< 8 char Password, NOT entered interactively by human' 311 | elif 84 < packet_size <= 148: 312 | note_field = '8+ char Password, NOT entered interactively by human' 313 | 314 | else: 315 | if 0 < packet_size <= 84: 316 | note_field = '< 8 char Password, entered interactively by human' 317 | elif 84 < packet_size <= 148: 318 | note_field = '8+char Password, entered interactively by human' 319 | 320 | # If the time delta between key offered and key accepted in small (say 50ms) likely the server is 321 | # in the known_hosts already, and the user was not prompted interactively to accept the server's key. 322 | # another explanation is that host checking is being ignored. 323 | if 'forward' in direction and 'key accepted' in indicator: 324 | if delta < .050: 325 | note_field = 'Delta suggests hostkey was already in known_hosts or ignored' 326 | else: 327 | note_field = 'Delta suggests hostkey was NOT in known_hosts, user manually accepted it' 328 | 329 | if 'reverse' in direction and ('login success' in indicator or 'login failure' in indicator): 330 | if delta < 1: 331 | note_field = 'Delta suggests creds NOT entered interactively by human' 332 | else: 333 | note_field = 'Delta suggests creds were entered interactively by human' 334 | if 'reverse' in direction and ('-R ' in indicator): 335 | note_field = '!! -R option used by forward session. This enables reverse SSH' 336 | 337 | if 'reverse' in direction and ('session init' in indicator): 338 | reverse_setup_delta = result[6] - fwd_login_time 339 | if reverse_setup_delta < 2: 340 | note_field = "Delta (<2s) suggests this may be automated (eg implant/RCE/SSRF)" 341 | else: 342 | note_field = "Delta (>2s) suggests this may be manual, by human" 343 | if 'forward' in direction and 'agent fwding' in indicator: 344 | note_field = "!! -A option used. Client private key sharing via SSH Agent Forwarding" 345 | 346 | enriched_row = [result[0], result[1], result[2], 347 | result[3], result[4], result[5], 348 | result[6], result[7], note_field] 349 | result_enriched.append(enriched_row) 350 | 351 | 352 | return result_enriched 353 | 354 | 355 | def enrich_results_time_delta(results): 356 | """ Calculates and enriches time deltas between events""" 357 | result_enriched = [] 358 | 359 | result_count = 0 360 | for result in results: 361 | if result_count == 0: 362 | delta_this_event = 0 363 | else: 364 | time_this_event = result[6] 365 | time_last_event = results[result_count - 1][6] 366 | delta_this_event = time_this_event - time_last_event 367 | enriched_row = [result[0], result[1], result[2], 368 | result[3], result[4], result[5], 369 | result[6], delta_this_event] 370 | result_enriched.append(enriched_row) 371 | result_count = result_count + 1 372 | 373 | return result_enriched 374 | 375 | 376 | def order_keystrokes(matrix_unordered, meta_size): 377 | """ Attempts to put forward keystroke packets in order of occurrence in real world""" 378 | forward_keystroke_size = meta_size[2] - 8 379 | ordered = [] 380 | keystone = 0 381 | looking_for_match = 1 382 | while len(matrix_unordered) > 1: 383 | size_keystone = matrix_unordered[keystone] 384 | # If non keystroke packet, then just add to ordered matrix 385 | if size_keystone != forward_keystroke_size: 386 | ordered = ordered + [matrix_unordered[keystone]] 387 | matrix_unordered.remove(matrix_unordered[keystone]) 388 | looking_for_match = 0 389 | 390 | # Must be the start of a keystroke block 391 | else: 392 | # Add the keystone to the ordered list 393 | ordered = ordered + [matrix_unordered[keystone]] 394 | matrix_unordered.remove(matrix_unordered[keystone]) 395 | looking_for_match = 1 396 | 397 | if looking_for_match == 0: 398 | ordered = ordered + [matrix_unordered[keystone]] 399 | # Then look ahead for matches 400 | else: 401 | mark = keystone 402 | count = 0 403 | while looking_for_match == 1 and mark < len(matrix_unordered): 404 | size_mark = matrix_unordered[mark] 405 | # Check if this packet is the servers return packet, but only look ahead 10 packets 406 | if count == 10: 407 | ordered = ordered + [matrix_unordered[mark]] 408 | matrix_unordered.remove(matrix_unordered[mark]) 409 | looking_for_match = 0 410 | break 411 | 412 | if size_mark == -forward_keystroke_size: 413 | ordered = ordered + [matrix_unordered[mark]] 414 | matrix_unordered.remove(matrix_unordered[mark]) 415 | looking_for_match = 0 416 | elif size_mark <= -(forward_keystroke_size + 8): 417 | ordered = ordered + [matrix_unordered[mark]] 418 | matrix_unordered.remove(matrix_unordered[mark]) 419 | looking_for_match = 0 420 | else: 421 | mark = mark + 1 422 | count = count + 1 423 | 424 | # Add any leftover packets onto the end of the ordered list 425 | ordered = ordered + matrix_unordered 426 | 427 | return ordered 428 | 429 | 430 | def scan_for_forward_host_key_accepts(pcap, fwd_logged_in_at_packet): 431 | """Looks for the client's acceptance of the servers SSH host key 432 | which is when the public key is in known_hosts""" 433 | 434 | results_f_key_accepts = [] 435 | if fwd_logged_in_at_packet == 0: 436 | stop_at = 100 437 | else: 438 | stop_at = fwd_logged_in_at_packet 439 | 440 | timestamp_first = float(pcap[0].sniff_timestamp) 441 | for i in range(0, len(pcap) - 4): 442 | if i == stop_at: 443 | break 444 | if 'message_code' in dir(pcap[i].ssh): 445 | # look for 'New Keys' code packet 21, this indicates acceptance of servers key 446 | if int(pcap[i].ssh.message_code) == 21 and 'message_code' not in dir(pcap[i + 1].ssh): 447 | # The packet prior to this is the server sending it's key fingerprint 448 | relative_timestamp = float(pcap[i - 1].sniff_timestamp) - timestamp_first 449 | results_f_key_accepts = [['forward', 'key offered ', 450 | i-1, i-1, 451 | int(pcap[i - 1].tcp.len), 1, relative_timestamp]] 452 | 453 | # This packet occurs only once the client has accepted entry of key into known_hosts 454 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 455 | results_f_key_accepts = results_f_key_accepts + [['forward', 'key accepted ', 456 | i, i, int(pcap[i].tcp.len), 457 | 1, relative_timestamp]] 458 | break 459 | return results_f_key_accepts 460 | 461 | 462 | def scan_for_forward_login_prompts(matrix, meta_size, pcap, fwd_logged_in_at_packet): 463 | """Looks for the server's login prompt""" 464 | 465 | results_f_login_prompts = [] 466 | size_login_prompt = meta_size[5] 467 | timestamp_first = float(pcap[0].sniff_timestamp) 468 | if fwd_logged_in_at_packet == 0: 469 | stop_at = 300 470 | 471 | else: 472 | stop_at = fwd_logged_in_at_packet + 2 473 | for i in range(0, min(len(matrix), stop_at)): 474 | if matrix[i] == size_login_prompt: 475 | relative_timestamp = (float(pcap[i].sniff_timestamp) - timestamp_first) 476 | results_f_login_prompts = results_f_login_prompts + [['forward', 'login prompt ', 477 | i, i, int(pcap[i].tcp.len), 478 | 1, relative_timestamp]] 479 | 480 | return results_f_login_prompts 481 | 482 | 483 | def scan_for_forward_AgentForwarding(matrix, pcap, meta_hassh): 484 | """Looks for packet sizing suggesting Agent forwarding has been configured""" 485 | timestamp_first = float(pcap[0].sniff_timestamp) 486 | results_f_agentForwarding = [] 487 | # Strike represents a counter, the game starts at srike -1 and a match is made when strike = 5 488 | strike = -1 489 | # The tell-tale client packet normally lies around packet 18 to 22, so stop at (say) packet 40 490 | stop_at = 40 491 | for i in range(0, min(stop_at, len(pcap) - 1)): 492 | # Keep track of any strikes made on this packet. 493 | this_ball = 1 494 | # Only start looking after the new keys packet 495 | if 'message_code' in dir(pcap[i].ssh): 496 | # look for 'New Keys' code packet 21 497 | if int(pcap[i].ssh.message_code) == 21 and 'message_code' not in dir(pcap[i + 1].ssh): 498 | # Batter up 499 | strike = 0 500 | # Tell tale packet is always surrounded by 2 Server packets before and 2 Server packets after 501 | # Use these 4 server packets to ensure no FPs 502 | # Server packet 503 | if strike == 0 and this_ball: 504 | if matrix[i] < 0: 505 | strike = 1 506 | this_ball = 0 507 | else: 508 | # Reset the strike counter afresh if a mismatch is made. 509 | strike = 0 510 | # Server packet 511 | if strike == 1 and this_ball: 512 | if matrix[i] < 0: 513 | strike = 2 514 | this_ball = 0 515 | else: 516 | strike = 0 517 | # Now look for the tell-tale packet found in testing. 518 | # testing shows (with openssh) client packet < 500 == no forwarding, > 500 == forwarding. 519 | # testing shows (with Putty) client packet 176 (< 200) == no forwarding, 256 (> 200) == forwarding. 520 | # TODO dig deeper on these size observations, found out what this packet represents exactly and tune further 521 | if strike == 2 and this_ball: 522 | if 'putty' in meta_hassh[1].lower(): 523 | if 200 < matrix[i] < 650: 524 | strike = 3 525 | this_ball = 0 526 | else: 527 | strike = 0 528 | elif 500 < matrix[i] < 650: 529 | strike = 3 530 | this_ball = 0 531 | else: 532 | strike = 0 533 | if strike == 3 and this_ball: 534 | # Server packet 535 | if matrix[i] < 0: 536 | strike = 4 537 | this_ball = 0 538 | else: 539 | strike = 0 540 | # Server packet 541 | if strike == 4 and this_ball: 542 | if matrix[i] < 0: 543 | # Steeeeee-rike, you're outta here 544 | strike = 5 545 | relative_timestamp = (float(pcap[i - 2].sniff_timestamp) - timestamp_first) 546 | results_f_agentForwarding = results_f_agentForwarding + [['forward', 'agent fwding ', 547 | i, i, int(pcap[i - 2].tcp.len), 548 | 1, relative_timestamp]] 549 | else: 550 | strike = 0 551 | return results_f_agentForwarding 552 | 553 | def scan_for_forward_login_attempts(matrix, meta_size, pcap): 554 | """Looks for successful and unsuccessful forward SSH logins""" 555 | fwd_logged_in_at_packet = 0 556 | results_f_logins = [] 557 | size_login_prompt = meta_size[5] 558 | timestamp_first = float(pcap[0].sniff_timestamp) 559 | # Start at packet 8 , to make sure we are out of negotiation phase 560 | # Only check the first 300 packets for login attempts 561 | 562 | for i in range(8, (min(len(matrix) - 2, 300))): 563 | 564 | if matrix[i] == size_login_prompt and \ 565 | matrix[i + 1] > 0 and \ 566 | matrix[i + 2] == size_login_prompt: 567 | relative_timestamp = float(pcap[i + 1].sniff_timestamp) - timestamp_first 568 | results_f_logins = results_f_logins + [['forward', 'login failure', 569 | i, i + 1, 570 | abs(matrix[i + 1]), 2, relative_timestamp]] 571 | 572 | if matrix[i] == size_login_prompt and \ 573 | matrix[i + 1] > 0 and \ 574 | matrix[i + 2] < 0 and \ 575 | matrix[i + 2] != size_login_prompt: 576 | relative_timestamp = float(pcap[i + 1].sniff_timestamp) - timestamp_first 577 | results_f_logins = results_f_logins + [['forward', 'login success', 578 | i, i + 1, 579 | abs(matrix[i + 1]), 2, relative_timestamp]] 580 | # This is used later as a stop point on scans for password prompts and key accepts 581 | fwd_logged_in_at_packet = i 582 | # Stop looking when the log in has been seen 583 | break 584 | return results_f_logins, fwd_logged_in_at_packet 585 | 586 | 587 | def scan_for_reverse_login_attempts(matrix, meta_size, pcap, reverse_init_start): 588 | """Looks for successful and unsuccessful forward SSH logins""" 589 | 590 | results_r_logins = [] 591 | size_reverse_login_prompt = -meta_size[5] + 40 + 8 592 | timestamp_first = float(pcap[0].sniff_timestamp) 593 | # only look at the 300 packets after the first reverse session initiation 594 | # TODO what if there are mutiple reverse sessions within the single fwd ? 595 | for i in range(reverse_init_start, min((len(matrix) - 4), 300)): 596 | if matrix[i] == size_reverse_login_prompt and \ 597 | matrix[i + 1] < -size_reverse_login_prompt and \ 598 | matrix[i + 2] > size_reverse_login_prompt and \ 599 | matrix[i + 3] < -size_reverse_login_prompt and \ 600 | matrix[i + 4] == size_reverse_login_prompt: 601 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 602 | results_r_logins = results_r_logins + [['reverse', 'login prompt ', 603 | i, i + 4, 604 | abs(matrix[i]), 4, relative_timestamp]] 605 | # The packet directly after the login prompt is when the password is entered 606 | relative_timestamp = float(pcap[i + 1].sniff_timestamp) - timestamp_first 607 | results_r_logins = results_r_logins + [['reverse', 'login failure', 608 | i, i + 4, 609 | abs(matrix[i + 1]), 4, relative_timestamp]] 610 | if matrix[i] == size_reverse_login_prompt and \ 611 | matrix[i + 1] < -size_reverse_login_prompt and \ 612 | 0 < matrix[i + 2] < size_reverse_login_prompt and \ 613 | matrix[i + 3] < -size_reverse_login_prompt and \ 614 | 0 < matrix[i + 4] < size_reverse_login_prompt: 615 | 616 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 617 | results_r_logins = results_r_logins + [['reverse', 'login prompt ', 618 | i, i + 4, 619 | abs(matrix[i]), 4, relative_timestamp]] 620 | # The packet directly after the login prompt is when the password is entered 621 | relative_timestamp = float(pcap[i + 1].sniff_timestamp) - timestamp_first 622 | results_r_logins = results_r_logins + [['reverse', 'login success', 623 | i, i + 4, 624 | abs(matrix[i + 1]), 4, relative_timestamp]] 625 | # Stop looking once reverse is logged in 626 | break 627 | return results_r_logins 628 | 629 | 630 | def scan_for_forward_keystrokes(matrix, meta_size, pcap, fwd_logged_in_at_packet): 631 | """ Looks for forward key strokes """ 632 | results_f_keystroke = [] 633 | forward_keystroke_size = meta_size[2] - 8 634 | packets_infiltrated = 0 635 | bytes_infiltated = 0 636 | keystrokes = 0 637 | 638 | timestamp_first = float(pcap[0].sniff_timestamp) 639 | # Skip over packets prior to successful login as there are no keylogs there 640 | i = fwd_logged_in_at_packet 641 | 642 | while i < len(matrix) - 2: 643 | size_this = matrix[i] 644 | size_next = matrix[i + 1] 645 | size_next_next = matrix[i + 2] 646 | if size_this == forward_keystroke_size: 647 | 648 | if size_next == -forward_keystroke_size and size_next_next == forward_keystroke_size: 649 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 650 | keystrokes = keystrokes + 1 651 | results_f_keystroke = results_f_keystroke + [['forward', 'keystroke ', 652 | i, i + 1, 653 | abs(size_this), 2, relative_timestamp]] 654 | i = i + 2 655 | elif size_next == -(forward_keystroke_size + 8) and size_next_next == forward_keystroke_size: 656 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 657 | keystrokes = keystrokes + 1 658 | results_f_keystroke = results_f_keystroke + [['forward', '< delete/ac ', 659 | i, i + 1, 660 | abs(size_this), 2, relative_timestamp]] 661 | i = i + 2 662 | # If packet is server packet, and bigger than forward size (i.e not a keepalive), lets report the enter key 663 | # YMMV on tab completion see TODO. comment this out if appropriate 664 | elif size_next < -(forward_keystroke_size + 8) and size_next_next == forward_keystroke_size: 665 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 666 | keystrokes = keystrokes + 1 667 | results_f_keystroke = results_f_keystroke + [['forward', 'tab complete ', 668 | i, i + 1, 669 | abs(size_this), 2, relative_timestamp]] 670 | i = i + 1 671 | 672 | elif size_next <= -forward_keystroke_size and size_next_next <= -forward_keystroke_size and keystrokes > 0: 673 | i_enterkey_pressed = i 674 | finish = i + 2 675 | # Look forward past the return and calculate the number of bytes in subsequent Server packets 676 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 677 | while finish < len(matrix): 678 | # A client packet signifies the end of a contiguous server block of packets 679 | if matrix[finish] > 0: 680 | i = finish 681 | break 682 | packets_infiltrated = packets_infiltrated + 1 683 | bytes_infiltated = bytes_infiltated + abs(matrix[finish]) 684 | finish = finish + 1 685 | i = i + 1 686 | results_f_keystroke = results_f_keystroke + [['forward', '_\u2503 ENTER ', 687 | i_enterkey_pressed, i, 688 | bytes_infiltated, packets_infiltrated, 689 | relative_timestamp]] 690 | packets_infiltrated = 0 691 | bytes_infiltated = 0 692 | keystrokes = 0 693 | else: 694 | i = i + 1 695 | 696 | # This component seems to FP on some file transfers. uncomment this if you like though. YMMV 697 | # elif (size_this == (forward_keystroke_size + 8) and size_next <= -(forward_keystroke_size + 8)) or \ 698 | # ((forward_keystroke_size + 40) > size_this > forward_keystroke_size and 699 | # size_next == -size_this): 700 | # relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 701 | # results_f_keystroke = results_f_keystroke + [['forward', 'UP/DOWN/Paste', 702 | # i, i + 1, 703 | # abs(size_this), 2, relative_timestamp]] 704 | # keystrokes = keystrokes + 1 705 | # i = i + 2 706 | 707 | else: 708 | i = i + 1 709 | 710 | return results_f_keystroke 711 | 712 | 713 | def scan_for_reverse_session_R_option(pcap, matrix,meta_size): 714 | """Looks for evidence of the -R option being used during the initial forward connection 715 | This indicates that the forward session has explicitly been created to support reverse SSH""" 716 | results_f_R_flag_used = [] 717 | num_packets = len(matrix) 718 | timestamp_first = float(pcap[0].sniff_timestamp) 719 | stop_at = min((num_packets - 10), 100) 720 | size_login_prompt = meta_size[5] 721 | 722 | for i in range(0, stop_at): 723 | if i == stop_at: 724 | break 725 | if 'message_code' in dir(pcap[i].ssh): 726 | # look for 'New Keys' code packet 21 727 | if int(pcap[i].ssh.message_code) == 21 and 'message_code' not in dir(pcap[i + 1].ssh): 728 | # We have found the newkeys packets and can count from here to detect -R anomaly 729 | 730 | offset = 4 731 | # look ahead for the login prompt size, the first one should be at +4 packets from here 732 | # Only look forward 20 packets as an offset, this should be plenty enough to cater for failed passwords 733 | # debug print('i={}'.format(i)) 734 | # debug print(matrix[i]) 735 | while ((i + offset + 7) < stop_at) and offset < 20 : 736 | #debug print('offset={}'.format(offset)) 737 | #debug print(i + offset + 7) 738 | #debug print(matrix[i + offset + 3]) 739 | if (matrix[i + offset]) == size_login_prompt: 740 | if matrix[i + offset + 2] != size_login_prompt: 741 | # check for behaviour often but not always exhibited by mac clients when -R is used 742 | if (matrix[i + offset + 3] > 0 and 743 | matrix[i + offset + 4] < 0 and 744 | matrix[i + offset + 4] != size_login_prompt and 745 | matrix[i + offset + 5] > 0 and 746 | matrix[i + offset + 6] < 0 and 747 | matrix[i + offset + 6] != size_login_prompt and 748 | abs(matrix[i + offset + 6]) < abs(matrix[i + offset + 5])): 749 | relative_timestamp = float(pcap[i + 10].sniff_timestamp) - timestamp_first 750 | results_f_R_flag_used = (results_f_R_flag_used + [['reverse', '-R used ', 751 | (i + offset + 7), (i + offset + 7), abs(matrix[i + offset + 7]), 3, relative_timestamp]]) 752 | # print('found a type 1 style -R') 753 | break 754 | # check for behaviour often exhibited by ubuntu clients when -R is used 755 | elif (matrix[i + offset + 3] > 0 and 756 | matrix[i + offset + 4] > 0 and 757 | matrix[i + offset + 5] < 0 and 758 | matrix[i + offset + 5] != size_login_prompt and 759 | matrix[i + offset + 6] < 0 and 760 | matrix[i + offset + 6] != size_login_prompt and 761 | abs(matrix[i + offset + 6]) < abs(matrix[i + offset + 5]) and 762 | matrix[i + offset + 7] > 0): 763 | 764 | relative_timestamp = float(pcap[i + 10].sniff_timestamp) - timestamp_first 765 | results_f_R_flag_used = (results_f_R_flag_used + [['reverse', '-R used ', 766 | (i + offset + 7), (i + offset + 7), abs(matrix[i + offset + 7]), 3, relative_timestamp]]) 767 | # print('found a type 2 style -R') 768 | break 769 | offset = offset + 1 770 | 771 | 772 | return results_f_R_flag_used 773 | 774 | 775 | def scan_for_reverse_session_initiation(matrix, meta_size, pcap): 776 | """Looks for when a Reverse sesssion is initiated by watching for reverse meta""" 777 | reverse_init_start = 0 778 | results_r_init = [] 779 | size_newkeys_next = meta_size[2] 780 | size_newkeys_next2 = meta_size[3] 781 | timestamp_first = float(pcap[0].sniff_timestamp) 782 | 783 | for i in range(0, len(matrix) - 3): 784 | if matrix[i + 1] == -(size_newkeys_next + 40) and \ 785 | matrix[i + 2] == -(size_newkeys_next2 - 40) and \ 786 | matrix[i + 3] < 0 and \ 787 | abs(matrix[i + 3]) >= (matrix[i + 2]): 788 | relative_timestamp = float(pcap[i + 1].sniff_timestamp) - timestamp_first 789 | reverse_init_start = i 790 | finish = i + 3 791 | results_r_init = (results_r_init + [['reverse', 'session init ', 792 | reverse_init_start, finish, 793 | abs(matrix[i + 1]), 3, relative_timestamp]]) 794 | return results_r_init, reverse_init_start 795 | 796 | 797 | def scan_for_reverse_keystrokes(matrix, meta_size, pcap, reverse_init_start): 798 | """ Looks for reverse key strokes """ 799 | results_r_keystroke = [] 800 | reverse_keystroke_size = meta_size[1] 801 | packets_exfiltrated = 0 802 | bytes_exfiltated = 0 803 | keystrokes = 0 804 | timestamp_first = float(pcap[0].sniff_timestamp) 805 | # Skip over all packets prior to reverse_init_start as there are no reverse keystrokes here 806 | i = reverse_init_start - 1 807 | 808 | while i < len(matrix) - 2: 809 | size_this = matrix[i] 810 | size_next = matrix[i + 1] 811 | size_next_next = matrix[i + 2] 812 | if size_this == reverse_keystroke_size: 813 | 814 | if size_next == -reverse_keystroke_size and size_next_next == reverse_keystroke_size: 815 | keystrokes = keystrokes + 1 816 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 817 | results_r_keystroke = results_r_keystroke + [['reverse', 'keystroke ', 818 | i, i + 1, 819 | abs(size_this), 2, relative_timestamp]] 820 | i = i + 2 821 | # debug changed +8 to -8 822 | elif size_next == -(reverse_keystroke_size - 8) and size_next_next == reverse_keystroke_size: 823 | 824 | keystrokes = keystrokes + 1 825 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 826 | results_r_keystroke = results_r_keystroke + [['reverse', '< delete ', 827 | i, i + 1, 828 | abs(size_this), 2, relative_timestamp]] 829 | i = i + 2 830 | 831 | # If packet is client packet, but is not the delete key size, lets report the enter key 832 | # debug changed +8 to -8 833 | elif size_next == -reverse_keystroke_size and \ 834 | size_next_next > -(reverse_keystroke_size - 8) and keystrokes > 0: 835 | relative_timestamp = float(pcap[i].sniff_timestamp) - timestamp_first 836 | i_enterkey_pressed = i 837 | finish = i + 2 838 | # Look forward past the return and calculate the number of bytes in subsequent Client packets 839 | while finish < len(matrix): 840 | # A server packet signifies the end of a contiguous server block of packets 841 | if matrix[finish] < 0: 842 | i = finish 843 | break 844 | packets_exfiltrated = packets_exfiltrated + 1 845 | bytes_exfiltated = bytes_exfiltated + abs(matrix[finish]) 846 | finish = finish + 1 847 | i = i + 1 848 | 849 | results_r_keystroke = results_r_keystroke + [['reverse', '_\u2503 ENTER ', 850 | i_enterkey_pressed, i, 851 | bytes_exfiltated, packets_exfiltrated, 852 | relative_timestamp]] 853 | packets_exfiltrated = 0 854 | bytes_exfiltated = 0 855 | keystrokes = 0 856 | else: 857 | i = i + 1 858 | 859 | else: 860 | i = i + 1 861 | return results_r_keystroke 862 | 863 | 864 | def construct_window_matrix(pcap, matrix, stream, window, stride, meta_size, reverse_init_start, results): 865 | """Returns window_matrix containing features of window analysis 866 | Each packet has a row of features in window_matrix""" 867 | # Splay defined as amount of packets to the left (and right) 868 | # of the midpoint of the window 869 | splay = int((window - int(window % 2))) / 2 870 | # Set the initial mid point (datum) of the first window 871 | max_client_packet_size = max_server_packet_size = 0 872 | 873 | datum = int(splay) 874 | window_matrix = [] 875 | 876 | # calculate time ranges in order to use in min-max feature normalization of timestamps 877 | print(' ... Building features with window size = {}, stride = {}'.format(window, stride)) 878 | print(' ... Calculating first packet timestamp') 879 | time_first_packet = float(pcap[0].sniff_timestamp) 880 | print(' ... Calculating last packet timestamp') 881 | time_last_packet = pcap[len(matrix) - 1].sniff_timestamp 882 | time_last_packet = float(time_last_packet) 883 | time_range = time_last_packet - time_first_packet 884 | sniff_timestamp_last = time_first_packet 885 | # calculate time Delta range in order to use in min-max feature normalization of time deltas 886 | delta_max = 0 887 | print(' ... Calculating Max Packet delta') 888 | for i in range(0, len(matrix)): 889 | sniff_timestamp = float(pcap[i].sniff_timestamp) 890 | delta = round(sniff_timestamp - sniff_timestamp_last, 3) 891 | if delta > delta_max: 892 | delta_max = delta 893 | sniff_timestamp_last = sniff_timestamp 894 | # Reset the initial sniff_timestamp_last after calculating feature scaling params 895 | sniff_timestamp_last = time_first_packet 896 | # The "datum" is the center packet of the window 897 | print(' ... Striding through windows of size {}'.format(window)) 898 | while datum < (len(matrix) - splay) \ 899 | and window < (len(matrix) - 1): 900 | datum_packet_size = matrix[datum] 901 | server_packets = 0 902 | server_packets_size = 0 903 | client_packets = 0 904 | client_packets_size = 0 905 | client_packets_list = [] 906 | server_packets_list = [] 907 | packet_size = 0 908 | 909 | for i in range(int(datum - splay), int(datum + splay + 1)): 910 | packet_size = matrix[i] 911 | if packet_size < 0: 912 | if abs(packet_size) > max_server_packet_size: 913 | max_server_packet_size = abs(packet_size) 914 | server_packets = server_packets + 1 915 | server_packets_size = server_packets_size + packet_size 916 | server_packets_list.append(int(packet_size)) 917 | else: 918 | if packet_size > max_client_packet_size: 919 | max_client_packet_size = abs(packet_size) 920 | client_packets = client_packets + 1 921 | client_packets_size = client_packets_size + packet_size 922 | client_packets_list.append(int(packet_size)) 923 | 924 | # If there were client packets in the window, calculate the stats 925 | if client_packets_list: 926 | client_packet_variability = round( 927 | (len(set(client_packets_list))) / len(client_packets_list), 3) 928 | normalized_client_datum_packet_size = round( 929 | abs(datum_packet_size / max_client_packet_size), 3) 930 | else: 931 | client_packet_variability = 0 932 | normalized_client_datum_packet_size = 0 933 | # If there were server packets in the window, calculate the stats 934 | if server_packets_list: 935 | server_packet_variability = round( 936 | (len(set(server_packets_list))) / len(server_packets_list), 3) 937 | normalized_server_datum_packet_size = round( 938 | abs(datum_packet_size / max_server_packet_size), 3) 939 | else: 940 | server_packet_variability = 0 941 | normalized_server_datum_packet_size = 0 942 | 943 | ratio_packets = round( 944 | (client_packets / (client_packets + server_packets)), 3) 945 | ratio_size = round( 946 | client_packets_size / (client_packets_size + abs(server_packets_size)), 3) 947 | 948 | new_window_row = [datum, stream, window, stride, 949 | normalized_client_datum_packet_size, client_packets, 950 | client_packets_size, client_packet_variability, 951 | normalized_server_datum_packet_size, server_packets, 952 | abs(server_packets_size), server_packet_variability, 953 | ratio_packets, ratio_size, packet_size, datum_packet_size] 954 | # Determine if the window size charactericts indicate exfil 955 | predict_exfiltration = predict_exfil(new_window_row, meta_size, reverse_init_start) 956 | predict_infiltration = predict_infil(new_window_row, meta_size, reverse_init_start) 957 | # Also we want to populate the matrix with atomic Enter key exfils/infils 958 | enter_child_forward, enter_child_reverse = tag_enter_child_packets(new_window_row, results) 959 | 960 | sniff_timestamp = round(float(pcap[datum].sniff_timestamp), 3) 961 | delta_normal = round((sniff_timestamp - sniff_timestamp_last) / delta_max, 3) 962 | this_time_elapsed_normal = round((sniff_timestamp - time_first_packet) / time_range, 3) 963 | 964 | sniff_timestamp_last = sniff_timestamp 965 | 966 | if predict_infiltration or enter_child_forward: 967 | predict_infiltration_aggregate = 1 968 | else: 969 | predict_infiltration_aggregate = 0 970 | 971 | if predict_exfiltration or enter_child_reverse: 972 | predict_exfiltration_aggregate = 1 973 | else: 974 | predict_exfiltration_aggregate = 0 975 | 976 | # Add these predictions and time deltas to the end of new_window_row 977 | new_window_row = [datum, stream, window, stride, 978 | normalized_client_datum_packet_size, client_packets, 979 | client_packets_size, client_packet_variability, 980 | normalized_server_datum_packet_size, server_packets, 981 | abs(server_packets_size), server_packet_variability, 982 | ratio_packets, ratio_size, predict_exfiltration, 983 | predict_infiltration, 984 | this_time_elapsed_normal, delta_normal, datum_packet_size, 985 | enter_child_forward, enter_child_reverse, 986 | predict_infiltration_aggregate, predict_exfiltration_aggregate] 987 | window_matrix.append(new_window_row) 988 | # Advance to the next datum by "stride" packets 989 | datum = datum + stride 990 | return window_matrix 991 | 992 | 993 | def tag_enter_child_packets(new_window_row, results): 994 | """tags packets that occur in contiguous blocks after an enter key has been pressed. 995 | This is useful to augment exfil/infil predictions based on separate window analysis""" 996 | enter_child_forward = 0 997 | enter_child_reverse = 0 998 | i = new_window_row[0] 999 | for result in results: 1000 | if 'ENTER' in result[1]: 1001 | start = result[2] 1002 | finish = result[3] 1003 | if start < i < finish: 1004 | if 'forward' in result[0]: 1005 | enter_child_forward = 1 1006 | elif 'reverse' in result[0]: 1007 | enter_child_reverse = 1 1008 | 1009 | return enter_child_forward, enter_child_reverse 1010 | 1011 | 1012 | def predict_exfil(new_window_row, meta_size, reverse_init_start): 1013 | ratio_packets = new_window_row[12] 1014 | ratio_size = new_window_row[13] 1015 | datum_packet_size = new_window_row[15] 1016 | max_keystroke_size = abs(meta_size[1]) 1017 | 1018 | predict_exfil = 0 1019 | 1020 | # to prevent FPs, Skip the first 35 packets, as these can contain legit contiguous session init packets from client 1021 | # Also skip the 35 packets after/before reverse_init_start as these also contain legit contiguous client packets 1022 | if new_window_row[0] > 35 and not \ 1023 | ((reverse_init_start - 35) < new_window_row[0] < (reverse_init_start + 35)): 1024 | # new_window_row[0] > reverse_init_start and new_window_row[0] < (reverse_init_start + 35)): 1025 | # This stems from reverse interactive command line driven exfil 1026 | if (ratio_packets == 1 and ratio_size == 1) and abs(datum_packet_size) > (1.2 * abs(max_keystroke_size)): # and 1027 | # (client_packet_variability >= round((2 / window), 3)) and 1028 | # client_packet_normalized_size > 0.3 and client_packet_normalized_size < 1.0): 1029 | predict_exfil = 1 1030 | return predict_exfil 1031 | 1032 | 1033 | def predict_infil(new_window_row, meta_size, reverse_init_start): 1034 | """Returns prediction on forward inbound file transfers""" 1035 | ratio_packets = new_window_row[12] 1036 | ratio_size = new_window_row[13] 1037 | predict_infil = 0 1038 | datum_packet_size = new_window_row[15] 1039 | max_keystroke_size = abs(meta_size[1]) 1040 | 1041 | # to prevent FPs Skip the first 35 packets, as these can contain many contiguous session init packets from server 1042 | # Also skip the 30 packets prior to the reverse_init_start as these also contain server packets 1043 | 1044 | if new_window_row[0] > 35 and not ( 1045 | (reverse_init_start - 30) < new_window_row[0] < reverse_init_start and new_window_row[0]): 1046 | if (ratio_packets == 0 and ratio_size == 0) and abs(datum_packet_size) > (1.2 * abs(max_keystroke_size)): 1047 | predict_infil = 1 1048 | return predict_infil 1049 | 1050 | 1051 | def zooms(zoom, num_packets): 1052 | if zoom == '0': 1053 | zleft = 0 1054 | zright = num_packets 1055 | return zleft, zright 1056 | 1057 | if '-' in zoom: 1058 | zleft = int(zoom.split("-")[0]) 1059 | zright = int(zoom.split("-")[1]) 1060 | if zright < zleft or zleft < 0 or zright < 0 or zleft > num_packets or zright > num_packets: 1061 | print('... ignoring out of bounds packet zooms, max zoom out is -z 0-{}'.format(num_packets)) 1062 | zleft = 0 1063 | zright = num_packets 1064 | return zleft, zright 1065 | else: 1066 | print('... ignoring invalid packet zooms, the max zoom out is -z 0-{}'.format(num_packets)) 1067 | zleft = 0 1068 | zright = num_packets 1069 | return zleft, zright 1070 | 1071 | 1072 | def plot_window_stat_predictions(stream, window_matrix, window, stride, file, out_plot_predictions, zleft, zright): 1073 | """Plots the window analysis including the exfil prediction 1074 | which does not rely of stream meta being known""" 1075 | df_stream = pd.DataFrame(window_matrix, 1076 | columns=['Packet number (datum)', 1077 | 'stream', 'window', 'stride', 'Client packet size (normalized)', 1078 | 'client_packets', 'client_packets_size', 'Client size variance', 1079 | 'Server packet size (normalized)', 'server_packets', 1080 | 'server_packets_size', 'Server Size variance', 1081 | 'Client:Server packet ratio', 'Client:Server size ratio', 1082 | 'Window Exfiltration prediction', 1083 | 'Window Infiltration prediction', 1084 | 'Time elapsed normalized', 'Packet Time delta normalized', 1085 | 'Datum packet size', 'Is forward enter child', 'Is reverse enter child', 1086 | 'Infiltration prediction aggregate', 'Exfiltration prediction aggregate']) 1087 | # Slice the dataframe so as to only get the zoomed selection 1088 | df_stream = df_stream.loc[zleft:zright] 1089 | 1090 | title = ("Strider - protocol:SSH" + '\n' + "Data Movement Predictions for pcap '" + file + "'\n" + 'Stream' + 1091 | str(stream) + ' - showing packets ' + str(zleft) + ' to ' + str(zright) + '\n' + 'windowsize ' + str( 1092 | window) + ' stride:' + str(stride)) 1093 | df_stream.plot(kind='bar', y=[16, 17, 12, 13, 7, 4, 11, 8, 14, 15], grid=True, ylim=[0, 1.05], 1094 | yticks=[.2, .4, .6, .8, 1.0], subplots=True, 1095 | title=[title, '', '', '', '', '', '', '', '', ''], figsize=[15, 20], 1096 | color=['#FFA500', '#FFA500', 'b', 'b', '#13ee00', '#13ee00', 'm', 'm', 'r', 'c', 'c']) 1097 | 1098 | plt.xlabel('Packet number in Stream {}'.format(stream)) 1099 | plt.ylabel('Normalized value') 1100 | plt.legend(loc='upper left') 1101 | 1102 | packets_to_plot = zright - zleft 1103 | 1104 | plt.xticks([i for i in range(0, packets_to_plot, int(packets_to_plot / 10))], 1105 | [i for i in range(0, packets_to_plot, int(packets_to_plot / 10))]) 1106 | plt.xlim(zleft, zright) 1107 | # print('time debug - plt.savefig(out_plot_predictions)') 1108 | plt.savefig(out_plot_predictions) 1109 | # print('time debug - closing plot after saving') 1110 | plt.close(out_plot_predictions) 1111 | plt.close('all') 1112 | 1113 | 1114 | def plot_packet_size_histogram(stream, matrix, output_dir, base_file, zleft, zright): 1115 | """Plots the packet size histogram 1116 | which does not rely of stream meta being known""" 1117 | out_plot_packet_size_histogram = str('./' + output_dir + '/' + 'packet-strider-ssh ' + base_file + 1118 | ' stream ' + str(stream) + ' - Packet Size Histogram.png') 1119 | m = [] 1120 | # Construct size matrix m and then dataframe df_m 1121 | for size in matrix: 1122 | if size > 0: 1123 | m = m + [[size, 0]] 1124 | else: 1125 | m = m + [[0, size]] 1126 | 1127 | df_m = pd.DataFrame(m, columns=['Client bytes sent', 'Server bytes sent']) 1128 | # Slice the dataframe so as to only get the zoomed selection, this makes plotting much faster 1129 | df_m = df_m.loc[zleft:zright] 1130 | 1131 | title = ("Strider - protocol:SSH" + '\n' + "Packet size histogram for '" + str(base_file) + "'\n" + 'Stream' + str( 1132 | stream) + ' - showing packets ' + str(zleft) + ' to ' + str(zright)) 1133 | df_m.plot(kind='bar', y=[0, 1], grid=False, title=title, figsize=[12, 6.5], 1134 | color=['b', 'r']) 1135 | plt.xlabel('Packet numbers in Stream {}'.format(stream)) 1136 | plt.ylabel('Bytes sent') 1137 | plt.legend(loc='best') 1138 | packets_to_plot = zright - zleft 1139 | plt.xticks([i for i in range(0, packets_to_plot, int(packets_to_plot / 10))], 1140 | [i for i in range(0, packets_to_plot, int(packets_to_plot / 10))]) 1141 | plt.xlim(zleft, zright) 1142 | plt.savefig(out_plot_packet_size_histogram) 1143 | plt.close(out_plot_packet_size_histogram) 1144 | plt.close('all') 1145 | 1146 | 1147 | def plot_keystroke_timeline(stream, results, window_matrix, file, out_plot_keystroke_timeline, df_stream_meta, zleft, 1148 | zright): 1149 | """Plots the keystroke data, mapping them to time elapsed 1150 | from the first packet in the stream""" 1151 | indicators = [] 1152 | client_protocol = str(df_stream_meta.loc[0, 'Client Proto']) 1153 | server_protocol = str(df_stream_meta.loc[0, 'Server Proto']) 1154 | sip = str(df_stream_meta.loc[0, 'sip']) 1155 | sport = str(df_stream_meta.loc[0, 'sport']) 1156 | dip = str(df_stream_meta.loc[0, 'dip']) 1157 | dport = str(df_stream_meta.loc[0, 'dport']) 1158 | 1159 | for result in results: 1160 | index = result[2] 1161 | r_initiation = r_login_prompt = 0 1162 | r_login_success = r_login_failure = 0 1163 | r_keystroke = r_delete = r_exfil = r_up_down_paste = 0 1164 | bytes_r_exfiled = 0 1165 | 1166 | f_key_offer = f_key_accept = f_login_prompt = 0 1167 | f_login_success = f_login_failure = f_keystroke = f_delete = f_exfil = f_up_down_paste = 0 1168 | # First do Reverse indicators 1169 | if 'reverse' in result[0]: 1170 | if ' init' in result[1]: 1171 | r_initiation = 1 1172 | elif 'prompt' in result[1]: 1173 | r_login_prompt = 0 1174 | elif 'login success' in result[1]: 1175 | r_login_success = 1 1176 | elif 'login failure' in result[1]: 1177 | r_login_failure = 1 1178 | elif 'keystroke' in result[1]: 1179 | r_keystroke = 1 1180 | elif 'delete' in result[1]: 1181 | r_delete = 1 1182 | elif 'ENTER' in result[1]: 1183 | r_exfil = 1 1184 | bytes_r_exfiled = bytes_r_exfiled + int(result[5]) 1185 | elif 'UP/DOWN/Paste' in result[1]: 1186 | r_up_down_paste = 1 1187 | # Then do Forward indicators 1188 | else: 1189 | if 'key offered' in result[1]: 1190 | f_key_offer = 1 1191 | elif 'key accepted' in result[1]: 1192 | f_key_accept = 1 1193 | elif 'login prompt' in result[1]: 1194 | f_login_prompt = 1 1195 | elif 'login success' in result[1]: 1196 | f_login_success = 1 1197 | elif 'login failure' in result[1]: 1198 | f_login_failure = 1 1199 | elif 'keystroke' in result[1]: 1200 | f_keystroke = 1 1201 | elif 'delete' in result[1]: 1202 | f_delete = 1 1203 | elif 'ENTER' in result[1]: 1204 | f_exfil = 1 1205 | elif 'UP/DOWN/Paste' in result[1]: 1206 | f_up_down_paste = 1 1207 | 1208 | indicators = indicators + [ 1209 | [index, r_initiation, r_login_prompt, r_login_success, r_login_failure, r_keystroke, r_delete, 1210 | r_exfil, r_up_down_paste, bytes_r_exfiled, f_key_offer, f_key_accept, f_login_prompt, 1211 | f_login_success, f_login_failure, f_keystroke, f_delete, f_exfil, f_up_down_paste]] 1212 | df_indicators = pd.DataFrame(indicators, columns=['index', 'REVERSE session initiation', 'REVERSE login prompt', 1213 | 'REVERSE login success', 'REVERSE login failure', 1214 | 'REVERSE keystroke', 'REVERSE delete', 1215 | 'REVERSE Enter', 'Reverse UP/DOWN/Paste', 1216 | 'Bytes exfiled when Reverse Enter key pressed', 1217 | 'Forward key offer', 'Forward key accept', 'Forward login prompt', 1218 | 'Forward login success', 'Forward login failure', 1219 | 'Forward keystroke', 'Forward delete', 'Forward Enter key', 1220 | 'Forward UP/DOWN/Paste' 1221 | ]) 1222 | df_indicators = df_indicators.loc[zleft:zright] 1223 | 1224 | df_stream = pd.DataFrame(window_matrix, 1225 | columns=['Packet number (datum)', 1226 | 'stream', 'window', 'stride', 'Client packet size (normalized)', 1227 | 'client_packets', 'client_packets_size', 'Client size variance', 1228 | 'Server packet size (normalized)', 'server_packets', 1229 | 'server_packets_size', 'Server Size variance', 1230 | 'Client:Server packet ratio', 'Client:Server size ratio', 1231 | 'Exfil prediction', 1232 | 'Infil prediction', 'Time elapsed normalized', 'Time delta normalized', 1233 | 'Datum packet size', 'Is forward Enter child', 'Is reverse Enter child', 1234 | 'Infiltration prediction aggregate', 'Exfiltration prediction aggregate' 1235 | ]) 1236 | df_stream = df_stream.loc[zleft:zright] 1237 | 1238 | df_stream_merged_results = df_stream.merge(df_indicators, how='outer', left_on='Packet number (datum)', 1239 | right_on='index').fillna(0) 1240 | 1241 | df_stream_merged_results = df_stream_merged_results.loc[zleft:zright] 1242 | 1243 | title = ("Strider - protocol:SSH Keystroke predictions timeline" + "\n" + 1244 | file + ' Stream ' + str(stream) + ' - showing packets ' + str(zleft) + ' to ' + str(zright) + 1245 | "\nClient:" + client_protocol + 1246 | "'\nServer:" + server_protocol + 1247 | "\n" + sip + ":" + sport + " -> " + dip + ":" + dport) 1248 | resolution = 2000 1249 | width = max(1, (zright-zleft)/resolution) 1250 | 1251 | df_stream_merged_results.plot(kind='bar', width=width, sharex='True', grid=True, subplots=True, 1252 | y=[36, 38, 39, 40, 21, 24, 26, 28, 29, 30, 22], 1253 | fontsize=16, 1254 | title=[title, '', '', '', '', '', '', '', '', '', ''], 1255 | color=['c', 'c', 'c', 'b', 'k', 'm', 'm', 'm', 'm', 1256 | 'r', 'k'], 1257 | figsize=[20, 20], ylim=[0, 1], yticks=[0, 1] 1258 | ) 1259 | 1260 | plt.xlabel('Packet number in Stream {}'.format(stream)) 1261 | plt.ylabel('Indicator') 1262 | 1263 | packets_to_plot = zright - zleft 1264 | 1265 | plt.xticks([i for i in range(0, packets_to_plot, int(packets_to_plot / 10))], 1266 | [i for i in range(0, packets_to_plot, int(packets_to_plot / 10))]) 1267 | plt.xlim(zleft, zright) 1268 | 1269 | plt.savefig(out_plot_keystroke_timeline) 1270 | plt.close(out_plot_keystroke_timeline) 1271 | plt.close('all') 1272 | 1273 | 1274 | def report(results, file, matrix, window_matrix, window, stride, output_dir, df_stream_meta, do_direction, 1275 | meta_only, do_plots, time_first_packet_gmt, num_packets, zoom): 1276 | row = 0 1277 | stream = df_stream_meta.loc[row, 'stream'] 1278 | client_protocol = df_stream_meta.loc[row, 'Client Proto'] 1279 | server_protocol = df_stream_meta.loc[row, 'Server Proto'] 1280 | hassh = df_stream_meta.loc[row, 'hassh'] 1281 | hassh_server = df_stream_meta.loc[row, 'hassh_server'] 1282 | sip = df_stream_meta.loc[row, 'sip'] 1283 | sport = df_stream_meta.loc[row, 'sport'] 1284 | dip = df_stream_meta.loc[row, 'dip'] 1285 | dport = df_stream_meta.loc[row, 'dport'] 1286 | # Prepare filenames for results 1287 | if output_dir != None: 1288 | base_file = os.path.basename(file) 1289 | output_dir = output_dir # +'/'+base_file 1290 | string_file = str('./' + output_dir + '/' + 'packet-strider-ssh ' + base_file + 1291 | ' stream ' + str(stream) + ' - Summary.txt') 1292 | out_plot_predictions = str('./' + output_dir + '/' + 'packet-strider-ssh ' + base_file + 1293 | ' stream ' + str(stream) + ' - Data Movement.png') 1294 | out_plot_keystroke_timeline = str('./' + output_dir + '/' + 'packet-strider-ssh ' + base_file + 1295 | ' stream ' + str(stream) + ' - Keystrokes.png') 1296 | 1297 | print('\n\u250F\u2501\u2501\u2501\u2501 Reporting results for stream {}'.format(stream)) 1298 | 1299 | num_f_init_events = num_f_keystroke_events = 0 1300 | num_r_init_events = num_r_keystroke_events = 0 1301 | bytes_f_infiled = bytes_r_exfiled = 0 1302 | num_predict_exfiltrations = 0 1303 | predict_exfiltrations_bytes = 0 1304 | num_predict_infiltrations = 0 1305 | predict_infiltrations_bytes = 0 1306 | 1307 | for row in window_matrix: 1308 | if row[21] == 1: 1309 | num_predict_exfiltrations += 1 1310 | predict_exfiltrations_bytes = predict_exfiltrations_bytes + matrix[row[0]] 1311 | 1312 | if row[22] == 1: 1313 | num_predict_infiltrations += 1 1314 | predict_infiltrations_bytes = predict_infiltrations_bytes + matrix[row[0]] 1315 | 1316 | # Aggregate the Indicator numbers 1317 | for result in results: 1318 | # First do Forward indicators 1319 | if 'forward' in result[0]: 1320 | if 'login' in result[1] or 'key ' in result[1]: 1321 | num_f_init_events += 1 1322 | elif 'ENTER' in result[1]: 1323 | num_f_keystroke_events += 1 1324 | bytes_f_infiled = bytes_f_infiled + int(result[4]) 1325 | else: 1326 | num_f_keystroke_events += 1 1327 | # Then do Reverse indicators 1328 | elif 'reverse' in result[0]: 1329 | if 'init' in result[1] or 'login' in result[1] or '-R' in result[1]: 1330 | num_r_init_events += 1 1331 | elif 'ENTER' in result[1]: 1332 | num_r_keystroke_events += 1 1333 | bytes_r_exfiled = bytes_r_exfiled + int(result[4]) 1334 | else: 1335 | num_r_keystroke_events += 1 1336 | # TODO simplify this block of reporting code 1337 | print('\u2503') 1338 | print('\u2503 Stream \033[0;33;40m{}\033[0m of pcap \'{}\''.format(stream, file)) 1339 | print('\u2503 {} packets in total, first at {}'.format(num_packets, time_first_packet_gmt)) 1340 | print('\u2503 \033[0;36;40m{}:{}\033[0m -> \033[0;31;40m {}:{}\033[0m'.format(sip, sport, dip, dport)) 1341 | print('\u2503 Client Proto : \033[0;33;40m{}\033[0m'.format(client_protocol)) 1342 | print('\u2503 hassh : \033[0;33;40m{}\033[0m'.format(hassh)) 1343 | print('\u2503 Server Proto : \033[0;33;40m{}\033[0m'.format(server_protocol)) 1344 | print('\u2503 hasshServer : \033[0;33;40m{}\033[0m'.format(hassh_server)) 1345 | print('\u2503 Summary of findings:') 1346 | if (do_direction == 'forward' or do_direction == 'both') and not meta_only: 1347 | if num_f_init_events > 0: 1348 | print('\u2503 \033[0;36;40m {} Forward SSH login/init events\033[0m'.format(num_f_init_events)) 1349 | if num_f_keystroke_events > 0: 1350 | print('\u2503 \033[0;36;40m {} Forward keystroke related events\033[0m'. 1351 | format(num_f_keystroke_events)) 1352 | # TODO fix this, calculate aggregate and report on this rather than separate techniques. 1353 | # if bytes_f_infiled > 0: 1354 | # print('\u2503 \033[0;36;40m Estimated {} Bytes infiled\033[0m'.format(bytes_f_infiled)) 1355 | 1356 | if (do_direction == 'reverse' or do_direction == 'both') and not meta_only: 1357 | if num_r_init_events > 0: 1358 | print('\u2503 \033[1;31;40m {} Reverse SSH login/init events\033[0m'.format(num_r_init_events)) 1359 | if num_r_keystroke_events > 0: 1360 | print('\u2503 \033[1;31;40m {} Reverse keystroke related events\033[0m'. 1361 | format(num_r_keystroke_events)) 1362 | # TODO fix this, calculate aggregate and report on this rather than separate techniques. 1363 | #if bytes_r_exfiled > 0: 1364 | # print('\u2503 \033[1;31;40m Estimated {} Bytes exfiled\033[0m'.format(bytes_r_exfiled)) 1365 | 1366 | # if num_predict_exfiltrations > 0 and not meta_only: 1367 | # print('\u2503\033[0;2;40m {} POSITIVE outbound exfiltation predictions from Window modeling ({} MB - lower bound)\033[0m'. 1368 | # format(num_predict_exfiltrations, round((abs(predict_exfiltrations_bytes) / 1024 / 1024), 3))) 1369 | # if num_predict_infiltrations > 0 and not meta_only: 1370 | # print('\u2503\033[0;2;40m {} POSITIVE inbound transfer predictions from Window modeling ({} MB - lower bound)\033[0m' 1371 | # .format(num_predict_infiltrations, round((abs(predict_infiltrations_bytes) / 1024 / 1024), 3))) 1372 | if results: 1373 | pretty_print(results) 1374 | if window_matrix and not meta_only and do_plots: 1375 | zleft, zright = zooms(zoom, num_packets) 1376 | if len(matrix) > 10: 1377 | print('\u2503 Plotting packets {}-{} size histogram to \'{}\''.format(zleft, zright, 1378 | out_plot_predictions)) 1379 | 1380 | plot_packet_size_histogram(stream, matrix, output_dir, base_file, zleft, zright) 1381 | 1382 | print('\u2503 Plotting packets {}-{} Data Movement predictions to \'{}\''.format(zleft, zright, 1383 | out_plot_predictions)) 1384 | 1385 | plot_window_stat_predictions(stream, window_matrix, window, stride, file, out_plot_predictions, zleft, zright) 1386 | if results: 1387 | print('\u2503 Plotting packets {}-{} keystroke timeline to \'{}\''.format(zleft, zright, 1388 | out_plot_keystroke_timeline)) 1389 | 1390 | # Now plot the keystroke timeline 1391 | plot_keystroke_timeline(stream, results, window_matrix, file, out_plot_keystroke_timeline, 1392 | df_stream_meta, zleft, zright) 1393 | else: 1394 | print('\u2503 No keystrokes found') 1395 | 1396 | print('\u2503') 1397 | print('\u2517\u2501\u2501\u2501\u2501 End of Analysis for stream {}'.format(stream)) 1398 | 1399 | 1400 | def pretty_print(results): 1401 | """Prints colorized table of results to terminal""" 1402 | 1403 | print('\u2503 Detailed Events:') 1404 | print('\u2503 packet time(s) delta(s) Direction Indicator Bytes Notes') 1405 | print('\u2503 -----------------------------------------------------------------------') 1406 | for result in results: 1407 | # print(result) 1408 | if result[0] == 'forward': 1409 | print('\u2503 \033[1;36;40m{:<10}{:<10}{:<10}{:<10}{:^10}{:^10}{:^10}\033[0m'. 1410 | format(result[3], round(result[6], 3), round(result[7], 3), result[0], result[1], result[4], result[8])) 1411 | elif result[0] == 'reverse': 1412 | print('\u2503 \033[1;31;40m{:<10}{:<10}{:<10}{:<10}{:^10}{:^10}{:^10}\033[0m'. 1413 | format(result[3], round(result[6], 3), round(result[7], 3), result[0], result[1], result[4], result[8])) 1414 | else: 1415 | print('\u2503 {:<10}{:<10}{:<10}{:<10}{:^10}{:^10}{:^10}'. 1416 | format(result[3], round(result[6], 3), round(result[7], 3), result[0], result[1], result[4], result[8])) 1417 | print('\u2503') 1418 | 1419 | 1420 | def get_streams(fullpcap): 1421 | """ Walks through fullpcap and makes a list (streams) of streams within 1422 | """ 1423 | streams = [] 1424 | for packet in fullpcap: 1425 | stream = int(packet.tcp.stream) 1426 | if stream not in streams: 1427 | print(' ...found stream {}'.format(stream)) 1428 | streams.append(stream) 1429 | fullpcap.close() 1430 | return streams 1431 | 1432 | 1433 | def main(): 1434 | """packet-strider-ssh is a packet forensics tool for SSH. 1435 | It creates a rich feature set from packet metadata such SSH Protocol message content, direction, size, latency and sequencing. 1436 | It performs pattern matching on these features, using statistical analysis, and sliding windows to predict session initiation, 1437 | keystrokes, human/script behaviour, password length, use of client certificates, 1438 | context into the historic nature of client/server contact and exfil/infil data movement characteristics 1439 | in both Forward and Reverse sessions""" 1440 | 1441 | command_args = parse_command_args() 1442 | 1443 | if command_args.file: 1444 | file = command_args.file 1445 | base_file = os.path.basename(file) 1446 | output_dir = command_args.output_dir 1447 | only_stream = command_args.nstream 1448 | window = int(command_args.window) 1449 | stride = int(command_args.stride) 1450 | keystrokes = command_args.keystrokes 1451 | do_direction = command_args.direction 1452 | meta_only = command_args.metaonly 1453 | do_windowing_and_plots = command_args.predict_plot 1454 | zoom = command_args.zoom 1455 | if output_dir != None: 1456 | # print('output_dir=_{}_'.format(output_dir)) 1457 | # TODO Can remove this later, is just to clean dir for debugging 1458 | # shutil.rmtree(output_dir) 1459 | if output_dir and not os.path.exists(output_dir): 1460 | os.makedirs(output_dir) 1461 | else: 1462 | print('no output directory') 1463 | print('\n... Loading full pcap : {}'.format(file)) 1464 | if only_stream >= 0: 1465 | string = 'ssh && !tcp.analysis.spurious_retransmission && !tcp.analysis.retransmission && !tcp.analysis.fast_retransmission && tcp.stream==' + str( 1466 | only_stream) 1467 | try: 1468 | fullpcap = pyshark.FileCapture(file, display_filter=string) 1469 | # TODO is this needed at all ? This was a test access to the data, to ensure that an exception occurs if the data is empty 1470 | # fullpcap[0] 1471 | streams = [only_stream] 1472 | except: 1473 | print('There is no stream {} in {}, try another'.format(only_stream, file)) 1474 | streams = [] 1475 | # fullpcap.close() 1476 | else: 1477 | fullpcap = pyshark.FileCapture(file, display_filter='ssh && !tcp.analysis.spurious_retransmission && \ 1478 | !tcp.analysis.retransmission && \ 1479 | !tcp.analysis.fast_retransmission') 1480 | print('... Getting streams from pcap:') 1481 | streams = get_streams(fullpcap) 1482 | 1483 | for stream in streams: 1484 | string = 'ssh && !tcp.analysis.spurious_retransmission && !tcp.analysis.retransmission && !tcp.analysis.fast_retransmission && tcp.stream== ' + str( 1485 | stream) 1486 | try: 1487 | print('... Loading stream {}'.format(stream)) 1488 | pcap = pyshark.FileCapture(file, display_filter=string) 1489 | pcap.load_packets() 1490 | num_packets = len(pcap) 1491 | if num_packets > 10: 1492 | 1493 | print('... Finding meta') 1494 | meta_size = find_meta_size(pcap, num_packets, stream) 1495 | df_meta_size = pd.DataFrame([meta_size], columns=[ 1496 | 'stream', 'Reverse keystoke size', 'size_newkeys_next', 'size_newkeys_next2', 1497 | 'size_newkeys_next3', 'size_login_prompt']) 1498 | 1499 | print('... Finding hassh elements') 1500 | meta_hassh = find_meta_hassh(pcap, num_packets, stream) 1501 | df_meta_hassh = pd.DataFrame([meta_hassh], columns=[ 1502 | 'stream', 'Client Proto', 'hassh', 'Server Proto', 'hassh_server', 1503 | 'sip', 'sport', 'dip', 'dport']) 1504 | 1505 | if len(df_meta_hassh) > 0 and len(df_meta_size) > 0: 1506 | df_stream_meta = df_meta_size.merge(df_meta_hassh, left_on='stream', right_on='stream') 1507 | else: 1508 | df_stream_meta = [] 1509 | 1510 | if meta_only: 1511 | matrix = [] 1512 | window_matrix = [] 1513 | results = [] 1514 | else: 1515 | print('... Building size matrix') 1516 | # Note this returns the raw, unordered matrix 1517 | matrix = construct_matrix(pcap) 1518 | # Note the matrix is reordered inside the anaylze function to account for any of order 1519 | # keystroke packets Hence appearing on both side of the function call 1520 | results, window_matrix, matrix = analyze(matrix, meta_size, pcap, window, stride, do_direction, 1521 | do_windowing_and_plots, keystrokes, meta_hassh) 1522 | time_first_packet = float(pcap[0].sniff_timestamp) 1523 | time_first_packet_gmt = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time_first_packet)) 1524 | pcap.close() 1525 | report(results, file, matrix, window_matrix, window, stride, output_dir, df_stream_meta, 1526 | do_direction, meta_only, do_windowing_and_plots, time_first_packet_gmt, num_packets, zoom) 1527 | else: 1528 | print(' ... < 10 packets in stream {}, quiting this stream'.format(stream)) 1529 | except Exception as error: 1530 | print('Error: ({})'.format(error)) 1531 | print("\n... packet-strider-ssh complete\n") 1532 | 1533 | 1534 | if __name__ == '__main__': 1535 | main() 1536 | -------------------------------------------------------------------------------- /zeek/README.md: -------------------------------------------------------------------------------- 1 | # Zeek implimenations 2 | This is a small collection of Zeek scripts containing logic ported from the original Python implementation. 3 | 4 | ## Agent Forwarding, the -A option 5 | The use of the -A option (SSH Agent Forwarding), which enables the client to share it's local SSH private keys with the server is generally considered dangerous - it has been the root of incidents and vulnerabilities. 6 | References: 7 | https://matrix.org/blog/2019/05/08/post-mortem-and-remediations-for-apr-11-security-incident 8 | https://skylightcyber.com/2019/09/26/all-your-cloud-are-belong-to-us-cve-2019-12491/ 9 | https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-12491 10 | https://developer.github.com/v3/guides/using-ssh-agent-forwarding/ 11 | 12 | ## -R Option 13 | The use -R option in the forward session - this is what *enables* a Reverse connection to be made later in the session. This artefact is discovered very early in the session, directly after the the forward session is authenticated. This is the first available warning sign that Reverse sessions are possible. 14 | 15 | ## Reverse session initiation 16 | Initiation of the Reverse SSH session, this can occur at any point (early, or late) in the forward session. This is discovered prior to the Reverse session being authenticated successfully. This is the second warning sign, in that a reverse session has just been requested and setup for authentication. 17 | 18 | ## Reverse session Success 19 | Success and/or Failure of the Reverse session authentication. TODO bundle these 2 scripts into one. 20 | This is the third and final warning sign, after this point you know someone is on your host, inside a reverse session. For richer visibibilty you can now use the main Python script in this package to explore the nature of activity (eg keystrokes and exfiltration) conducted within the Reverse session. 21 | -------------------------------------------------------------------------------- /zeek/packetSrider_AgentForwarding.zeek: -------------------------------------------------------------------------------- 1 | # __author__ = 'Ben Reardon' 2 | # __contact__ = 'benjeems@gmail.com @benreardon' 3 | # __version__ = '0.2' 4 | # __license__ = 'GNU General Public License v3.0' 5 | # packetSrider_AgentForwarding 6 | # This is a port of the pattern logic within the packetStrider 7 | # function "scan_for_forward_AgentForwarding" 8 | # https://github.com/benjeems/packetStrider/blob/master/python/packetStrider-ssh.py 9 | # This is a zeek script that looks for specific patterns in the size and 10 | # sequence of packets that are unique to cases where the Agent Forwarding is configured 11 | # example https://developer.github.com/v3/guides/using-ssh-agent-forwarding/ 12 | # Logic from python script has been ported to zeek 13 | 14 | redef SSH::disable_analyzer_after_detection = F; 15 | # Strike represents a counter, the game starts at srike 0 and a match is made when strike = 5 16 | global strike = 0; 17 | global index = 1; 18 | global has_been_found = 0; 19 | global client_protocol_string = ""; 20 | 21 | redef enum Notice::Type += { 22 | SSH_F_ForwardAgent 23 | }; 24 | 25 | event ssh_client_version(c: connection, version: string) { 26 | client_protocol_string = to_lower(version); 27 | } 28 | 29 | 30 | event ssh_encrypted_packet(c:connection, orig:bool, len:count) 31 | { 32 | #print fmt("!!!strike = %d len = %d", strike, len); print(" "); 33 | if (has_been_found == 1 || index > 40) { 34 | # print fmt("BAILING : has_been_found = %d index = %d", has_been_found, index); print(" "); 35 | return; 36 | } 37 | 38 | # Only start looking after packet 7 , approx location of new keys packet. TODO properly 39 | if (index < 8) { 40 | index = index + 1; 41 | return; 42 | } 43 | # Tell tale packet is always surrounded by 2 Server packets before and 2 Server packets after 44 | # Use these 4 server packets to ensure no FPs 45 | 46 | # Server packet 47 | if (strike == 0 && orig == F) { 48 | strike = 1; 49 | index = index + 1; 50 | #print fmt("strike = %d orig = %s len = %d", strike, orig, len); print(" "); 51 | return; 52 | } 53 | 54 | # Server packet 55 | if (strike == 1 && orig == F) { 56 | strike = 2; 57 | index = index + 1; 58 | #print fmt("strike = %d orig = %s len = %d", strike, orig, len); print(" "); 59 | return; 60 | } 61 | 62 | # Now look for the tell-tale packet found in testing. 63 | # testing shows (with openssh) client packet < 500 == no forwarding, > 500 == forwarding. 64 | # testing shows (with Putty) client packet 176 (< 200) == no forwarding, 256 (> 200) == forwarding. 65 | if (strike == 2 && orig == T && 500 < len && len < 650 && "putty" !in client_protocol_string) { 66 | strike = 3; 67 | index = index + 1; 68 | #print fmt("strike = %d orig = %s len = %d", strike, orig, len); print(" "); 69 | return; 70 | } 71 | if (strike == 2 && orig == T && 200 < len && len < 650 && "putty" in client_protocol_string) { 72 | strike = 3; 73 | index = index + 1; 74 | #print fmt("strike = %d orig = %s len = %d", strike, orig, len); print(" "); 75 | return; 76 | } 77 | 78 | # Server packet 79 | if (strike == 3 && orig == F) { 80 | strike = 4; 81 | index = index + 1; 82 | #print fmt("strike = %d len = %d", strike, len); print(" "); 83 | return; 84 | } 85 | 86 | # The final Server packet 87 | if (strike == 4 && orig == F) { 88 | strike = 5; 89 | #print fmt("strike = %d orig = %s len = %d", strike, orig, len); print(" "); 90 | #print fmt("###### Found Agent Forwarding"); 91 | NOTICE([$note=SSH_F_ForwardAgent, 92 | $msg = fmt("Agent Forwarding is in use (-A option). Client %s has requested to share it's private SSH key with Server %s",c$id$orig_h,c$id$resp_h), 93 | $sub = fmt("Agent Forwarding is in use")]); 94 | has_been_found = 1; 95 | return; 96 | } 97 | 98 | # If none of the above matches were made, the run is over and we must strike back to zero. 99 | # print fmt("setting strike to zero"); 100 | strike = 0; 101 | index = index + 1; 102 | 103 | } 104 | -------------------------------------------------------------------------------- /zeek/packetSrider_R_option.zeek: -------------------------------------------------------------------------------- 1 | # __author__ = 'Ben Reardon' 2 | # __contact__ = 'benjeems@gmail.com @benreardon' 3 | # __version__ = '0.1' 4 | # __license__ = 'GNU General Public License v3.0' 5 | # packetSrider_R_option.zeek 6 | # This is a port of the pattern logic within the packetStrider 7 | # function "scan_for_reverse_session_R_option" 8 | # https://github.com/benjeems/packetStrider/blob/master/python/packetStrider-ssh.py 9 | # This is a zeek script that looks for specific patterns in the size and 10 | # sequence of packets that are unique to cases where the -R 11 | # option is present in the commandline of the forward session. 12 | # An example of a forward commandline that would trigger 13 | # this script would be when this is run on the victim host : 14 | # `ssh attacker@attacker.com -R 31337:localhost:22` 15 | # This -R option is required to support a reverse SSH session 16 | # from attacker back to the victim at a later stage. 17 | # Logic from python script has been ported to zeek 18 | 19 | redef SSH::disable_analyzer_after_detection = F; 20 | global base = 0; 21 | global index = 0; 22 | global packet_count = 0; 23 | global len_base_4 = 0; 24 | global login_prompt_size = 0; 25 | global reverseType = 0; 26 | global R_has_been_found = 0; 27 | 28 | redef enum Notice::Type += { 29 | SSH_R_Reverse 30 | }; 31 | 32 | event ssh_encrypted_packet(c:connection, orig:bool, len:count) 33 | { 34 | 35 | if (R_has_been_found == 1 || index > 50) { 36 | break; 37 | } 38 | 39 | # The forth packet (index = 3) is the size of the servers login prompt. 40 | # This is important to know when failed attempts occur, as a packet of this size 41 | # replays directly after a failed Client auth packet. 42 | if (index == 3 && orig == F && !login_prompt_size) { 43 | login_prompt_size = len; 44 | #print fmt("Found login prompt size of %d", login_prompt_size); print(" "); 45 | base = 1; 46 | index += 1; 47 | packet_count = 1; 48 | return; 49 | } 50 | 51 | # Packets relating to setting up reverse tunnels start at packet count 3 after the login prompt 52 | if (packet_count == 3 && base == 1 && orig == T) { 53 | base = 2; 54 | #print fmt("At base %d of 5", base); print(" "); 55 | packet_count = packet_count + 1; 56 | return; 57 | } 58 | 59 | # TYPE 1 check 60 | if (packet_count == 4 && base == 2 && orig == F && len != login_prompt_size) { 61 | base = 3; 62 | reverseType = 1; 63 | #print fmt("At base %d of 5", base); print(" "); 64 | packet_count = packet_count + 1; 65 | return; 66 | } 67 | if (reverseType == 1 && packet_count == 5 && base == 3 && orig == T) { 68 | base = 4; 69 | len_base_4 = len; 70 | #print fmt("At base %d of 5", base); print(" "); 71 | packet_count = packet_count + 1; 72 | return; 73 | } 74 | if (reverseType == 1 && packet_count == 6 && base == 4 && orig == F && len != login_prompt_size && len < len_base_4) { 75 | base = 5; 76 | #print fmt("At base %d of 5", base); print(" "); 77 | #print fmt("###### Found a Type 1 -R"); 78 | NOTICE([$note=SSH_R_Reverse, 79 | $msg = fmt("The -R option was used by the forward connection from %s to %s. This option enables reverse SSH to occur ",c$id$orig_h,c$id$resp_h), 80 | $sub = fmt("-R option was used (type 1 detected)")]); 81 | R_has_been_found = 1; 82 | return; 83 | } 84 | 85 | 86 | # TYPE 2 check 87 | if (packet_count == 4 && base == 2 && orig == T) { 88 | base = 3; 89 | reverseType = 0; 90 | #print fmt("At base %d of 5", base); print(" "); 91 | packet_count = packet_count + 1; 92 | return; 93 | } 94 | if (reverseType == 2 && packet_count == 5 && base == 3 && orig == F && len != login_prompt_size) { 95 | base = 4; 96 | len_base_4 = len; 97 | #print fmt("At base %d of 5", base); print(" "); 98 | packet_count = packet_count + 1; 99 | return; 100 | } 101 | if (reverseType == 2 && packet_count == 6 && base == 4 && orig == F && len != login_prompt_size && len < len_base_4) { 102 | base = 5; 103 | #print fmt("###### Found a Type 2 -R"); 104 | NOTICE([$note=SSH_R_Reverse, 105 | $msg = fmt("The -R option was used by the forward connection from %s to %s. This option enables reverse SSH to occur ",c$id$orig_h,c$id$resp_h), 106 | $sub = fmt("-R option was used (type 2 detected)")]); 107 | R_has_been_found = 1; 108 | return; 109 | } 110 | 111 | # If none of the above packets were seen but the size is that of login_prompt_size 112 | # A failed auth attempt must have occured, so reset the packet_count and base 113 | if (orig == F && len == login_prompt_size) { 114 | #print fmt("Found a re-login prompt size of %d", login_prompt_size);print(" "); 115 | packet_count = 1; 116 | base = 1; 117 | reverseType = 0; 118 | return; 119 | } 120 | 121 | index += 1; 122 | packet_count += 1; 123 | 124 | } 125 | -------------------------------------------------------------------------------- /zeek/packetStrider_reverse_init.zeek: -------------------------------------------------------------------------------- 1 | # __author__ = 'Ben Reardon' 2 | # __contact__ = 'benjeems@gmail.com @benreardon' 3 | # __version__ = '0.1' 4 | # __license__ = 'GNU General Public License v3.0' 5 | # 6 | # This is a port of the pattern logic within the packetStrider 7 | # function "scan_for_reverse_session_initiation" 8 | # https://github.com/benjeems/packetStrider/blob/master/python/packetStrider-ssh.py 9 | # This is a Zeek script that looks for initiation of reverse SSH session. 10 | # This script will fire as soon as the session in 'negotiated', 11 | # i.e prior to any authentication back to the victim host. 12 | # Tested in zeek 2.6.0, 2.6.1, 2.6.3 13 | 14 | 15 | redef SSH::disable_analyzer_after_detection = F; 16 | global base = 0; 17 | global index = 0; 18 | global reverse_init_found = 0; 19 | global size_newkeys_next_found = 0; 20 | global orig_newkeys_next = F; 21 | global size_newkeys_next = 0; 22 | global len_base_2 = 1500; 23 | 24 | redef enum Notice::Type += { 25 | SSH_R_Reverse 26 | }; 27 | 28 | event ssh_encrypted_packet(c:connection, orig:bool, len:count) 29 | { 30 | if (reverse_init_found == 1 && size_newkeys_next_found == 1) { 31 | return; 32 | } 33 | 34 | if (size_newkeys_next_found == 0) { 35 | if (index == 0) { 36 | orig_newkeys_next = orig; 37 | size_newkeys_next = len; 38 | index = 1; 39 | } 40 | if (index == 1) { 41 | if (orig != orig_newkeys_next && len == size_newkeys_next) { 42 | size_newkeys_next_found = 1; 43 | return; 44 | } 45 | } 46 | } 47 | 48 | if (base == 0 && orig == F && len == (size_newkeys_next + 40)) { 49 | base = 1; 50 | return; 51 | } 52 | if (base == 1 && orig == T && len == (size_newkeys_next + 40)) { 53 | base = 2; 54 | len_base_2 = len; 55 | return; 56 | } 57 | if (base == 1 && (orig == F || len != (size_newkeys_next + 40))) { 58 | base = 0; 59 | len_base_2 = 1500; 60 | return; 61 | } 62 | 63 | if (base == 2 && orig == F && len >= len_base_2) { 64 | base = 3; 65 | reverse_init_found = 1; 66 | NOTICE([$note=SSH_R_Reverse, 67 | $msg = fmt("Reverse Shell was initiated from %s to %s",c$id$resp_h,c$id$orig_h), 68 | $sub = fmt("Reverse Shell was initiated")]); 69 | return; 70 | } 71 | if (base == 2 && (orig == T || len < len_base_2)) { 72 | base = 0; 73 | return; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /zeek/packetStrider_reverse_login_FAILED.zeek: -------------------------------------------------------------------------------- 1 | # __author__ = 'Ben Reardon' 2 | # __contact__ = 'benjeems@gmail.com @benreardon' 3 | # __version__ = '0.1' 4 | # __license__ = 'GNU General Public License v3.0' 5 | # 6 | # This is a port of the pattern logic within the packetStrider 7 | # function "scan_for_reverse_login_attempts" FAILED reverse logins 8 | # https://github.com/benjeems/packetStrider/blob/master/python/packetStrider-ssh.py 9 | # This is a Zeek script that looks for failed and successfull reverse SSH logins. 10 | # Tested in zeek 2.6.0, 2.6.1, 2.6.3 11 | 12 | 13 | redef SSH::disable_analyzer_after_detection = F; 14 | global base = 0; 15 | global index = 0; 16 | global reverse_login_found = 0; 17 | global size_newkeys_next_found = 0; 18 | global orig_newkeys_next = F; 19 | global size_newkeys_next = 0; 20 | global size_reverse_login_prompt =0; 21 | 22 | 23 | redef enum Notice::Type += { 24 | SSH_R_Reverse 25 | }; 26 | 27 | event ssh_encrypted_packet(c:connection, orig:bool, len:count) 28 | { 29 | if (reverse_login_found == 1) { 30 | return; 31 | } 32 | 33 | #print fmt("%d %d %s %d", index, base, orig, len); 34 | # The forth packet (index = 3) is the size of the servers login prompt. 35 | # This is important to know when failed attempts occur, as a packet of this size 36 | # replays directly after a failed Client auth packet. 37 | if (index == 3 && orig == F && !size_reverse_login_prompt) { 38 | size_reverse_login_prompt = len + 40 + 8; 39 | #print fmt("Found size_reverse_login_prompt prompt size of %d", size_reverse_login_prompt); print(" "); 40 | index += 1; 41 | return; 42 | } 43 | 44 | if (base == 0 && orig == T && len == size_reverse_login_prompt) { 45 | base = 1; 46 | #print fmt("At base %d of 5", base); print(" "); 47 | index += 1; 48 | return; 49 | } 50 | if (base == 0 && !(orig == T && len == size_reverse_login_prompt)) { 51 | base = 0; 52 | index += 1; 53 | return; 54 | } 55 | 56 | 57 | if (base == 1 && orig == F && len > size_reverse_login_prompt) { 58 | base = 2; 59 | #print fmt("At base %d of 5", base); print(" "); 60 | index += 1; 61 | return; 62 | } 63 | if (base == 1 && !(orig == F && len > size_reverse_login_prompt)) { 64 | base = 0; 65 | index += 1; 66 | return; 67 | } 68 | 69 | 70 | if (base == 2 && (orig == T || len > size_reverse_login_prompt)) { 71 | base = 3; 72 | #print fmt("At base %d of 5", base); print(" "); 73 | index += 1; 74 | return; 75 | } 76 | if (base == 2 && !(orig == T || len > size_reverse_login_prompt)) { 77 | base = 0; 78 | index += 1; 79 | return; 80 | } 81 | 82 | 83 | if (base == 3 && orig == F && len > size_reverse_login_prompt) { 84 | base = 4; 85 | #print fmt("At base %d of 5", base); print(" "); 86 | index += 1; 87 | return; 88 | } 89 | if (base == 3 && !(orig == F && len > size_reverse_login_prompt)) { 90 | base = 0; 91 | index += 1; 92 | return; 93 | } 94 | 95 | if (base == 4 && orig == T && len == size_reverse_login_prompt) { 96 | base = 5; 97 | #print fmt("*******At base %d of 5", base); print(" "); 98 | NOTICE([$note=SSH_R_Reverse, 99 | $msg = fmt("Reverse Shell failed logon from %s to %s",c$id$orig_h,c$id$resp_h), 100 | $sub = fmt("Reverse Shell failed logon")]); 101 | reverse_login_found == 1; 102 | return; 103 | } 104 | if (base == 4 && !(orig == T && len == size_reverse_login_prompt)) { 105 | base = 0; 106 | index += 1; 107 | return; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /zeek/packetStrider_reverse_login_SUCCESS.zeek: -------------------------------------------------------------------------------- 1 | # __author__ = 'Ben Reardon' 2 | # __contact__ = 'benjeems@gmail.com @benreardon' 3 | # __version__ = '0.1' 4 | # __license__ = 'GNU General Public License v3.0' 5 | # 6 | # This is a port of the pattern logic within the packetStrider 7 | # function "scan_for_reverse_login_attempts" SUCCESSFULL reverse logins 8 | # https://github.com/benjeems/packetStrider/blob/master/python/packetStrider-ssh.py 9 | # This is a Zeek script that looks for failed and successfull reverse SSH logins. 10 | # Tested in zeek 2.6.0, 2.6.1, 2.6.3 11 | 12 | 13 | redef SSH::disable_analyzer_after_detection = F; 14 | global base = 0; 15 | global index = 0; 16 | global reverse_login_found = 0; 17 | global size_newkeys_next_found = 0; 18 | global orig_newkeys_next = F; 19 | global size_newkeys_next = 0; 20 | global size_reverse_login_prompt =0; 21 | 22 | 23 | redef enum Notice::Type += { 24 | SSH_R_Reverse 25 | }; 26 | 27 | event ssh_encrypted_packet(c:connection, orig:bool, len:count) 28 | { 29 | if (reverse_login_found == 1) { 30 | return; 31 | } 32 | 33 | #print fmt("%d %d %s %d", index, base, orig, len); 34 | # The forth packet (index = 3) is the size of the servers login prompt. 35 | # This is important to know when failed attempts occur, as a packet of this size 36 | # replays directly after a failed Client auth packet. 37 | if (index == 3 && orig == F && !size_reverse_login_prompt) { 38 | size_reverse_login_prompt = len + 40 + 8; 39 | #print fmt("Found size_reverse_login_prompt prompt size of %d", size_reverse_login_prompt); print(" "); 40 | index += 1; 41 | return; 42 | } 43 | 44 | if (base == 0 && orig == T && len == size_reverse_login_prompt) { 45 | base = 1; 46 | #print fmt("At base %d of 5", base); print(" "); 47 | index += 1; 48 | return; 49 | } 50 | if (base == 0 && !(orig == T && len == size_reverse_login_prompt)) { 51 | base = 0; 52 | index += 1; 53 | return; 54 | } 55 | 56 | 57 | if (base == 1 && orig == F && len > size_reverse_login_prompt) { 58 | base = 2; 59 | #print fmt("At base %d of 5", base); print(" "); 60 | index += 1; 61 | return; 62 | } 63 | if (base == 1 && !(orig == F && len > size_reverse_login_prompt)) { 64 | base = 0; 65 | index += 1; 66 | return; 67 | } 68 | 69 | 70 | if (base == 2 && (orig == T || len > size_reverse_login_prompt)) { 71 | base = 3; 72 | #print fmt("At base %d of 5", base); print(" "); 73 | index += 1; 74 | return; 75 | } 76 | if (base == 2 && !(orig == T || len > size_reverse_login_prompt)) { 77 | base = 0; 78 | index += 1; 79 | return; 80 | } 81 | 82 | 83 | if (base == 3 && orig == F && len > size_reverse_login_prompt) { 84 | base = 4; 85 | #print fmt("At base %d of 5", base); print(" "); 86 | index += 1; 87 | return; 88 | } 89 | if (base == 3 && !(orig == F && len > size_reverse_login_prompt)) { 90 | base = 0; 91 | index += 1; 92 | return; 93 | } 94 | 95 | if (base == 4 && orig == T && len < size_reverse_login_prompt) { 96 | base = 5; 97 | #print fmt("*******At base %d of 5", base); print(" "); 98 | NOTICE([$note=SSH_R_Reverse, 99 | $msg = fmt("Reverse Shell successfull login from %s to %s",c$id$resp_h,c$id$orig_h), 100 | $sub = fmt("Reverse Shell successfull login")]); 101 | reverse_login_found = 1; 102 | return; 103 | } 104 | if (base == 4 && !(orig == T && len < size_reverse_login_prompt)) { 105 | base = 0; 106 | index += 1; 107 | return; 108 | } 109 | 110 | } 111 | --------------------------------------------------------------------------------