├── .gitignore ├── Dockerfile ├── LICENSE ├── NetCap-output ├── benign │ ├── chrome │ │ ├── TLSClientHello.csv │ │ └── TLSServerHello.csv │ └── firefox │ │ └── TLSHandshakes.7z └── malware │ ├── TLSClientHello.csv │ └── TLSServerHello.csv ├── README.md ├── anomaly-detect.py ├── feature-reduction-tests ├── features.py ├── graph_data.py └── reduce_features.py ├── format-data ├── check_ip.py ├── extract_data_csv.py ├── ja3_fingerprints.csv └── requirements.txt ├── graph └── SAVE MODEL GRAPHS HERE ├── models ├── ADD TRAINED MODEL HERE ├── ae.h5 ├── oc-svm.pkl ├── svm.pkl └── win-pkl-ver │ ├── oc-svm.pkl │ └── svm.pkl ├── requirements.txt └── test-train-data └── test_train_data.7z /.gitignore: -------------------------------------------------------------------------------- 1 | # Cache files 2 | __pycache__/ 3 | *.vscode 4 | validate_data_new-all.csv 5 | format-data/TLSClientHello.csv 6 | format-data/TLSServerHello.csv 7 | NetCap-output/benign/validate/TLSClientHello.csv 8 | NetCap-output/benign/validate/TLSServerHello.csv 9 | test-train-data/test_train_data.csv 10 | .ipynb_checkpoints -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM tensorflow/tensorflow 2 | 3 | COPY requirements.txt /tmp/requirements.txt 4 | RUN pip install -r /tmp/requirements.txt 5 | 6 | RUN mkdir -p /detect/data && \ 7 | mkdir -p /detect/models && \ 8 | mkdir -p /detect/graph 9 | 10 | COPY ./anomaly-detect.py /detect/anomaly-detect.py 11 | COPY ./test-train-data/test_train_data.csv /detect/data/test_train_data.csv 12 | COPY ./models/* /detect/models/ 13 | 14 | ENV RUNNING_IN_DOCKER=True 15 | 16 | WORKDIR /detect 17 | 18 | ENTRYPOINT [ "python3", "/detect/anomaly-detect.py", "--export" ] 19 | 20 | CMD [ "-h" ] 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /NetCap-output/benign/firefox/TLSHandshakes.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/NetCap-output/benign/firefox/TLSHandshakes.7z -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TLS Mal Detect 2 | Using machine learning to detect malware in encrypted TLS traffic metadata 3 | 4 | [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) 5 | ![Linux](https://img.shields.io/badge/Supports-Linux-green.svg) 6 | ![Windows](https://img.shields.io/badge/Supports-Windows-green.svg) 7 | ![Docker](https://img.shields.io/badge/Supports-Docker-red.svg) 8 | ![Python: v3.8](https://img.shields.io/badge/Python-3.8-blue.svg) 9 | [![Python: Reference](https://img.shields.io/badge/Python-Reference-blue.svg)](https://docs.python.org/3.8/) 10 | --- 11 | 12 | The purpose of this repository is to evaluate multiple machine learning algorithms and demonstrate their ability to accurately classify malicious traffic. Three models were used in this research, a One-Class Support Vector Machine, a Support Vector Machine, and an Autoencoder Neural Network. This repository is supplied as a part of a research assignment in support of my Master's of Science in Information Security Engineering from SANS Technology Institute entitled *Malware Detection in Encrypted TLS Traffic Through Machine Learning*. 13 | 14 | Visit the accompanying Jupyter Notebook Repo to step through a basic demonstration of some of the data analysis and one of the ML models used in this research. 15 | 16 | [TLS-Mal-Detect Jupyter Repository](https://github.com/1computerguy/tls-mal-detect-jupyter) 17 | 18 | [TLS-Mal-Detect Jupyter Notebook Binder](https://notebooks.gesis.org/binder/v2/gh/1computerguy/tls-mal-detect-jupyter/HEAD?filepath=anomaly-detect.ipynb) 19 | 20 | --- 21 | 22 | > NOTE: If you decide to use this program with Windows, there are issues with pathlib. It works best if you convert the pathlib paths to raw strings. 23 | 24 | ## Run from Docker 25 | 26 | The easiest way to use this is to use Docker. 27 | 1. Download repository (git clone https://github.com/1computerguy/tls-mal-detect) 28 | 2. cd to tls-mal-detect directory 29 | 3. Unzip the file `test-train-data/test_train_data.7z` 30 | 4. Build the container with Docker: 31 | - Change directory to the tls-mal-detect repo directory 32 | - Run the docker build command 33 | - Run the docker container 34 | 35 | ``` 36 | docker build . --tag tls-mal-detect:latest 37 | docker run --rm -it tls-mal-detect 38 | ``` 39 | 40 | The `docker run` command above will provide the script help documentation below: 41 | ``` 42 | usage: anomaly-detect.py [-h] -d DATA_SIZE [-m MALWARE_SIZE] [-t TEST_SIZE] 43 | [-o ML_MODEL] [-s] [-l] [-f FILE] [-r] [-g GRAPH] 44 | [-p] [-e] [-c CSV_FILE] 45 | 46 | Run an ML model to analyse TLS data for malicious activity. 47 | 48 | optional arguments: 49 | -h, --help show this help message and exit 50 | -d DATA_SIZE, --data DATA_SIZE 51 | Data sample size to analyze 52 | -m MALWARE_SIZE, --malware MALWARE_SIZE 53 | Percentage of dataset that is Malware 54 | -t TEST_SIZE, --test TEST_SIZE 55 | Percentage of dataset to use for validation 56 | -o ML_MODEL, --model ML_MODEL 57 | Machine Learning model to use. Acceptable values are: 58 | - ae = Autoencoder 59 | - svm = Support Vector Machine 60 | - oc-svm = One-Class SVM 61 | -s, --save Save the trained model - REQUIRES the -f/--file option 62 | -l, --load Evaluate data against a trained model - REQUIRES the -f/--file option 63 | -f FILE, --file FILE Save/Load file path 64 | -r, --scores Print 10-fold cross-validated Accuracy, Recall, Precision, and F2 scores 65 | -g GRAPH, --graph GRAPH 66 | Visualize the modeled dataset. Acceptable values are: 67 | SVM and OC-SVM graphs: 68 | - confusion 69 | - margin (SVM only) 70 | - boundary (SVM only) 71 | - auc 72 | Autoencoder graphs: 73 | - confusion 74 | - loss 75 | - mae 76 | - thresh 77 | - scatter 78 | -p, --print Print dataset 79 | -e, --export This will save the graph to a file - REQUIRED if running in a container 80 | -c CSV_FILE, --csv CSV_FILE 81 | Location of the CSV Data file 82 | ``` 83 | 84 | --- 85 | 86 | #### Examples running the script from Docker 87 | 88 | 89 | Train the One-Class SVM with a 25,000 sample dataset, a 1% malware distribution, a 20% Validation dataset, and print the cross-validated accuracy, precision, recall, and F2-scores 90 | 91 | ``` 92 | docker run --rm -it tls-mal-detect -d 25000 -m 1 --model oc-svm --scores 93 | ``` 94 | 95 | Run the SVM using the pre-saved model 96 | 97 | ``` 98 | docker run --rm -it tls-mal-detect -d 5000 -m 20 --model svm --scores --load --file /detect/models/svm.pkl 99 | ``` 100 | 101 | Run the Autoencoder and export the Confusion Matrix graph as a .png file to the current working directory of the host or VM 102 | 103 | ``` 104 | docker run --rm -it -v $(pwd):/detect/graph tls-mal-detect -d 25000 -m 5 --model ae --graph confusion 105 | ``` 106 | 107 | --- 108 | 109 | ## Run from Host (or VM) - *Linux recommended* 110 | 1. Download repository (git clone https://github.com/1computerguy/tls-mal-detect) 111 | 2. cd to tls-mal-detect directory 112 | 3. Unzip the file `test-train-data/test_train_data.7z` 113 | 4. Install Python3 and requirements 114 | - Install python3 according to your Operating System's requirements 115 | - Install pip 116 | - Use pip to install additional requirements `pip install -r requirements.txt` 117 | - Run the program 118 | 119 | Print script help: 120 | 121 | ``` 122 | python3 anomaly-detect.py -h 123 | ``` 124 | 125 | Train the One-Class SVM with a 25,000 sample dataset, a 1% malware distribution, a 20% Validation dataset, and print the cross-validated accuracy, precision, recall, and F2-scores 126 | 127 | ``` 128 | python3 anomaly-detect.py -d 25000 -m 1 --model oc-svm --scores 129 | ``` 130 | 131 | Run the SVM using the pre-saved model 132 | 133 | ``` 134 | python3 anomaly-detect.py -d 50000 -m 20 --model svm --scores --load --file ./models/svm.pkl 135 | ``` 136 | 137 | Run the Autoencoder and open the Confusion Matrix graph 138 | 139 | ``` 140 | python3 anomaly-detect.py -d 25000 -m 5 --model ae --graph confusion 141 | ``` 142 | 143 | Run the SVM and save the margin graph to disk 144 | 145 | ``` 146 | python3 anomaly-detect.py -d 25000 -m 20 --model svm --graph margin --export 147 | ``` 148 | -------------------------------------------------------------------------------- /anomaly-detect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import pandas as pd 4 | import matplotlib.pyplot as plt 5 | import seaborn as sns 6 | import numpy as np 7 | import joblib 8 | import os 9 | 10 | from argparse import ArgumentParser, RawTextHelpFormatter 11 | from pathlib import Path 12 | from sklearn.preprocessing import MinMaxScaler 13 | from sklearn.decomposition import PCA 14 | from sklearn.model_selection import train_test_split, cross_val_score 15 | from sklearn.svm import SVC, OneClassSVM 16 | from sklearn.metrics import confusion_matrix, roc_curve, auc, roc_auc_score 17 | from sklearn.metrics import fbeta_score, accuracy_score, precision_score, recall_score 18 | from mlxtend.plotting import plot_decision_regions 19 | from tensorflow.keras.layers import Input, Dense 20 | from tensorflow.keras.models import Sequential, load_model, Model 21 | from tensorflow.keras import regularizers 22 | from tensorflow.random import set_seed 23 | from numpy.random import seed 24 | 25 | def create_graph(x_data, y_data, graph, model=None, ae=False, occ=False, label_data=None, export=False, graph_file=Path('./graph/graph.png')): 26 | ''' 27 | Graph an ML model's training or analysis output to visualize its efficacy and functionality 28 | - ae and label_data arguments are used to signify Autoencoder graphs 29 | ''' 30 | # Generate confusion matrix for output data 31 | if graph == 'confusion': 32 | if ae: 33 | pred_x = [1 if e > y_data else 0 for e in x_data['Loss_mae'].values] 34 | conf_matrix = confusion_matrix(label_data, pred_x) 35 | else: 36 | if occ: 37 | ben = 0 38 | mal = 1 39 | x_data[x_data == 1] = ben 40 | x_data[x_data == -1] = mal 41 | y_data = y_data.values 42 | y_data[y_data == 1] = ben 43 | y_data[y_data == -1] = mal 44 | 45 | conf_matrix = confusion_matrix(y_data, x_data) 46 | 47 | plt.figure(figsize=(8, 6)) 48 | sns.heatmap(conf_matrix, 49 | xticklabels=['Benign', 'Malware'], 50 | yticklabels=['Benign', 'Malware'], 51 | annot=True, fmt='d') 52 | 53 | plt.title('Confusion Matrix') 54 | plt.ylabel('True class') 55 | plt.xlabel('Predicted class') 56 | # Create an SVM margin graph to visualize the Maximal Margin 57 | elif graph == 'margin': 58 | x_data = np.array(x_data) 59 | 60 | plt.scatter(x_data[:, 0], x_data[:, 1], c=y_data.values, s=30, cmap=plt.cm.winter, alpha=0.5) 61 | ax = plt.gca() 62 | xlim = [-8, 6] 63 | ylim = [-3, 3] 64 | xx = np.linspace(xlim[0], xlim[1], 30) 65 | yy = np.linspace(ylim[0], ylim[1], 30) 66 | XX, YY = np.meshgrid(yy, xx) 67 | xy = np.vstack([XX.ravel(), YY.ravel()]).T 68 | Z = model.decision_function(xy).reshape(XX.shape) 69 | 70 | ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--']) 71 | ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], 72 | s=100, linewidth=1, facecolors='none', edgecolors='k') 73 | # Create a colored Margin graph 74 | elif graph == 'boundary': 75 | x_data = np.array(x_data) if isinstance(x_data, pd.DataFrame) else x_data 76 | y_data = np.array(y_data).astype(np.integer) 77 | plot_decision_regions(X=x_data, y=y_data, clf=model, legend=2) 78 | plt.xlabel("Component 1", size=12) 79 | plt.ylabel("Component 2", size=12) 80 | # Graph the AUC 81 | elif graph == 'auc': 82 | fpr, tpr, _ = roc_curve(y_data, x_data) 83 | auc = roc_auc_score(y_data, x_data) 84 | plt.plot([0,1], [0,1], color='navy', lw=2, linestyle='--') 85 | plt.xlim([-0.05, 1.0]) 86 | plt.ylim([0.0, 1.05]) 87 | plt.xlabel('False Positive Rate') 88 | plt.ylabel('True Positive Rate') 89 | plt.plot(fpr, tpr, label='ROC Curve (area = {})'.format(str(auc)), color='darkorange') 90 | plt.title('Receiver Operating Characteristic (ROC curve)') 91 | plt.legend(loc='lower right') 92 | ################################################### 93 | # Below graphs are specifically for the Autoencoder 94 | # Graph the AE loss curve 95 | elif graph == 'loss': 96 | plt.plot(x_data, 97 | 'b', 98 | label='Training loss') 99 | plt.plot(y_data, 100 | 'r', 101 | label='Validation loss') 102 | plt.legend(loc='upper right') 103 | plt.xlabel('Epochs') 104 | plt.ylabel('Loss, [mse]') 105 | plt.ylim([0,.014]) 106 | # Show the Mean Absolute Error graph (used for the threshold) 107 | # to determine the number of standard deviations above the peak of the 108 | # curve that the learning reaches "0" 109 | elif graph == 'mae': 110 | X_pred = model.predict(np.array(x_data)) 111 | X_pred = pd.DataFrame(X_pred, columns=x_data.columns) 112 | X_pred.index = x_data.index 113 | 114 | pred = pd.DataFrame(index=x_data.index) 115 | pred['Loss_mae'] = np.mean(np.abs(X_pred - x_data), axis = 1) 116 | plt.figure() 117 | sns.distplot(pred['Loss_mae'], 118 | bins = 10, 119 | kde= True, 120 | color = 'blue') 121 | plt.xlim([0.0,.02]) 122 | # Simple time-based plot of threshold and data points 123 | elif graph == 'thresh': 124 | x_data.plot(logy=True, figsize = (10,6), ylim = [1e-2,1e0], color = ['blue','red']) 125 | # Scatter chart offering clearer, easier to understand malicious vs. benign data 126 | # representation with threshold marker 127 | elif graph == 'scatter': 128 | sns.scatterplot( x=x_data.index, y='Loss_mae', data=x_data, palette='plasma', hue='Anomaly') 129 | plt.axhline(y=y_data) 130 | 131 | if export: 132 | plt.savefig(graph_file) 133 | else: 134 | plt.show() 135 | 136 | def f_beta(beta, precision, recall): 137 | ''' 138 | Calculate the F score indicating the beta value to use 0.5, 1, or 2 139 | ''' 140 | return (beta*beta + 1) * precision * recall / (beta * beta * precision + recall) 141 | 142 | def save_model(model, filename, ae=False): 143 | ''' 144 | Save a model to disk for later analysis 145 | ''' 146 | model_output_path = os.path.split(os.path.abspath(filename))[0] 147 | if not os.path.exists(model_output_path): 148 | os.mkdir(model_output_path) 149 | 150 | if ae: 151 | model.save(filename) 152 | else: 153 | joblib.dump(model, filename) 154 | 155 | def import_model(filename, ae=False): 156 | ''' 157 | Import a pre-trained model for analysis 158 | ''' 159 | if os.path.exists(filename): 160 | if ae: 161 | loaded_model = load_model(filename) 162 | else: 163 | loaded_model = joblib.load(filename) 164 | else: 165 | loaded_model = 'The file path {} does not exist...'.format(filename) 166 | 167 | return loaded_model 168 | 169 | def AE_threshold(train_dist, pred_dist, extreme=False): 170 | ''' 171 | Calculate the Autoencoder threshold 172 | - Above the threshold marks anomalous/malicious data 173 | - Below the threshold marks normal/benign data 174 | ''' 175 | k = 4. if extreme else 3. 176 | train_thresh = np.mean(np.mean(np.abs(train_dist), axis = 1)) 177 | pred_thresh = np.mean(np.mean(np.abs(pred_dist), axis = 1)) 178 | threshold = np.abs(pred_thresh - train_thresh) * k 179 | 180 | return threshold 181 | 182 | def svm(data, scores=False, save=False, load=False, filename=Path('./models/svm.pkl'), graph=None, graph_file=None): 183 | ''' 184 | Use a Support Vector Machine to classify malware and benign TLS traffic based on metadata 185 | gathered during the client/server handshake. 186 | ''' 187 | label = 'malware_label' 188 | tt_features = data.drop(label, axis=1) 189 | tt_labels = data[label] 190 | 191 | # Feature reduction to 2 components required for margin and boundary graphs 192 | if graph == 'margin' or graph == 'boundary': 193 | pca = PCA(n_components=2).fit_transform(tt_features) 194 | tt_features = pd.DataFrame(pca) 195 | 196 | # Laod model from file 197 | if load: 198 | svclassifier = import_model(filename.absolute()) 199 | feature_test = tt_features 200 | label_test = tt_labels 201 | 202 | # Train model 203 | else: 204 | feature_train, feature_test, label_train, label_test = train_test_split(tt_features, tt_labels, test_size=0.20) 205 | svclassifier = SVC(kernel='rbf', C=100, gamma=0.1, probability=True, random_state=42) 206 | svclassifier.fit(feature_train, label_train) 207 | 208 | # Save model to file 209 | if save: 210 | save_model(svclassifier, filename) 211 | 212 | # Perform n-fold cross validation and calculate the mean score across the cv=## folds 213 | if scores: 214 | print('\nCalculating SVM scores...') 215 | for val in ['accuracy', 'precision', 'recall']: 216 | score = cross_val_score(svclassifier, feature_test, label_test, cv=10, scoring=val).mean() 217 | print("{}: {}".format(val, score)) 218 | if val == 'precision': 219 | prec = score 220 | elif val == 'recall': 221 | rec = score 222 | print("F2 Score: {}".format(f_beta(2.0, prec, rec))) 223 | 224 | svm_pred = svclassifier.predict(feature_test) 225 | 226 | export = True if graph_file else False 227 | 228 | if graph == 'margin' or graph == 'boundary': 229 | create_graph(tt_features, tt_labels, graph, svclassifier, export=export, graph_file=graph_file) 230 | elif graph == 'loss' or graph == 'scatter' or graph == 'mae': 231 | print('These graphs do not apply to this ML model. Try the Autoencoder to view them.') 232 | elif graph: 233 | create_graph(svm_pred, label_test, graph, export=export, graph_file=graph_file) 234 | 235 | def oc_svm(data, mal_percent, scores=False, save=False, load=False, filename=Path('./models/oc-svm.pkl'), graph=None, graph_file=None): 236 | ''' 237 | Use a One-Class Support Vector Machine to classify malware and benign TLS traffic based 238 | on metadata gathered during the client/server handshake. 239 | ''' 240 | # Set nu and gamma hyperparameters and test percentage 241 | test_percent = 0.20 242 | nu_value = (mal_percent / 100) * test_percent 243 | gamma_val = 0.1 244 | label = 'malware_label' 245 | 246 | #if graph == 'margin' or graph == 'boundary': 247 | # Feature reduction to 2 components required for margin and boundary graphs 248 | # OC-SVM does not graph well using any of the attempted feature reduction techniques. 249 | # I attempted PCA, Autoencoder, T-SNE, UMAP, Factor Analysis, Random Forest. The PCA 250 | # and AE are left below merely for reference. 251 | 252 | #label_data = data.malware_label 253 | #feature_data = data.drop(label, axis=1) 254 | 255 | #pca = PCA(n_components=2).fit_transform(feature_data) 256 | #data = pd.DataFrame(pca) 257 | #data = pd.concat([data, label_data], axis=1) 258 | 259 | #ae = Sequential() 260 | #ae.add(Dense(100, activation='elu', 261 | # kernel_initializer='glorot_uniform', 262 | # input_shape=(feature_data.shape[1],), 263 | # kernel_regularizer=regularizers.l2(0.0))) 264 | #ae.add(Dense(2, activation='elu', name='bottleneck', kernel_initializer='glorot_uniform')) 265 | #ae.add(Dense(100, activation='elu', kernel_initializer='glorot_uniform')) 266 | #ae.add(Dense(feature_data.shape[1], activation='sigmoid', kernel_initializer='glorot_uniform')) 267 | #ae.compile(loss='mse',optimizer='adam') 268 | #ae.fit(np.array(feature_data), np.array(feature_data), batch_size=64, epochs=20, verbose=0) 269 | #encoder = Model(ae.input, ae.get_layer('bottleneck').output) 270 | #ae_data = encoder.predict(feature_data) 271 | #data = pd.DataFrame(ae_data) 272 | #data = pd.concat([data, label_data], axis=1) 273 | 274 | # Laod model from file 275 | if load: 276 | svclassifier = import_model(filename) 277 | oc_test = data.drop(label, axis=1) 278 | oc_test_label = data[label] 279 | 280 | # Train model 281 | else: 282 | oc_benign = data[data.malware_label == 1] 283 | oc_malware = data[data.malware_label == -1] 284 | 285 | oc_b_train, oc_b_test = train_test_split(oc_benign, test_size=test_percent, random_state=1) 286 | oc_b_train = oc_b_train.drop(label, axis=1) 287 | 288 | oc_test = oc_b_test.append(oc_malware) 289 | oc_test_label = oc_test.malware_label 290 | oc_test = oc_test.drop(label, axis=1) 291 | 292 | svclassifier = OneClassSVM(nu=nu_value, kernel='rbf', gamma=gamma_val) 293 | svclassifier.fit(oc_b_train) 294 | 295 | # Save model to file 296 | if save: 297 | save_model(svclassifier, filename) 298 | 299 | # Perform n-fold cross validation and calculate the mean score across the cv=## folds 300 | if scores: 301 | print('\nCalculating OC-SVM scores...') 302 | for val in ['accuracy', 'precision', 'recall']: 303 | score = cross_val_score(svclassifier, oc_test, oc_test_label, cv=2, scoring=val).mean() 304 | print("{}: {}".format(val, score)) 305 | if val == 'precision': 306 | prec = score 307 | elif val == 'recall': 308 | rec = score 309 | print("F2 Score: {}".format(f_beta(2.0, prec, rec))) 310 | 311 | oc_pred = svclassifier.predict(oc_test) 312 | 313 | export = True if graph_file else False 314 | 315 | # You can uncomment the below if statement (and change the second if graph to an elif graph) 316 | # ONLY if you enable one of the feature reduction techniques above - either PCA or the AE 317 | #if graph == 'margin' or graph == 'boundary': 318 | # create_graph(oc_test, oc_test_label, graph, svclassifier, export, graph_file) 319 | if graph == 'confusion' or graph == 'auc': 320 | create_graph(oc_pred, oc_test_label, graph, svclassifier, export=export, graph_file=graph_file, occ=True) 321 | elif graph == 'margin' or graph == 'boundary': 322 | print('You need to uncomment one of the feature reduction techniques in this function to use that graph type...') 323 | elif graph == 'loss' or graph == 'scatter' or graph == 'mae': 324 | print('These graphs do not apply to this ML model. Try the Autoencoder to view them.') 325 | 326 | def ae(data, scores=False, save=False, load=False, filename=Path('./models/ae.h5'), graph=None, graph_file=None): 327 | ''' 328 | Use an Autoencoder Neural Network to classify malware and benign TLS traffic based 329 | on metadata gathered during the client/server handshake. 330 | ''' 331 | seed(1) 332 | set_seed(2) 333 | NUM_EPOCHS=200 334 | BATCH_SIZE=32 335 | label = 'malware_label' 336 | act_func = 'elu' 337 | label_data = data.malware_label 338 | 339 | # Laod model from file 340 | if load: 341 | data = data.drop(label, axis=1) 342 | 343 | model = import_model(filename, True) 344 | predictions = model.predict(np.array(data)) 345 | predictions = pd.DataFrame(predictions, columns=data.columns) 346 | predictions.index = data.index 347 | 348 | # Calculate threshold and provide anomaly output predictions as a dataframe 349 | threshold = AE_threshold(data, predictions) 350 | scored = pd.DataFrame(index=data.index) 351 | scored['Loss_mae'] = np.mean(np.abs(predictions-data), axis=1) 352 | scored['Threshold'] = threshold 353 | scored['Anomaly'] = scored['Loss_mae'] > scored['Threshold'] 354 | 355 | # Train model 356 | else: 357 | x_train = data[data.malware_label == 0] 358 | x_train = x_train.drop(label, axis=1) 359 | x_test = data[data.malware_label == 1] 360 | x_test = x_test.drop(label, axis=1) 361 | 362 | begin_end_length = x_train.shape[1] 363 | stage_two_length = 300 364 | stage_three_length = 100 365 | stage_four_length = 2 366 | 367 | # Build AE network 368 | model = Sequential() 369 | 370 | model.add(Dense(stage_two_length, activation=act_func, 371 | kernel_initializer='glorot_uniform', 372 | kernel_regularizer=regularizers.l2(0.0), 373 | input_shape=(begin_end_length,) 374 | ) 375 | ) 376 | 377 | model.add(Dense(stage_three_length , activation=act_func, 378 | kernel_initializer='glorot_uniform')) 379 | model.add(Dense(stage_four_length , activation=act_func, 380 | kernel_initializer='glorot_uniform')) 381 | model.add(Dense(stage_three_length , activation=act_func, 382 | kernel_initializer='glorot_uniform')) 383 | 384 | model.add(Dense(stage_two_length , activation=act_func, 385 | kernel_initializer='glorot_uniform')) 386 | 387 | model.add(Dense(begin_end_length, 388 | kernel_initializer='glorot_uniform')) 389 | 390 | model.compile(loss='mse',optimizer='adam') 391 | 392 | history = model.fit(np.array(x_train), np.array(x_train), 393 | batch_size=BATCH_SIZE, 394 | epochs=NUM_EPOCHS, 395 | validation_split=0.05, 396 | verbose = 1) 397 | 398 | # Save model to file 399 | if save: 400 | save_model(model, filename, True) 401 | 402 | predictions = model.predict(np.array(x_test)) 403 | predictions = pd.DataFrame(predictions, 404 | columns=x_test.columns) 405 | predictions.index = x_test.index 406 | 407 | # Calculate scores if conducting training and validation 408 | # - First set of measurements are for benign traffic 409 | # - Second set of measurements are for predictions based on first set 410 | # and for detecting malware 411 | scored = pd.DataFrame(index=x_test.index) 412 | threshold = AE_threshold(x_train, predictions, True) 413 | scored['Loss_mae'] = np.mean(np.abs(predictions-x_test), axis = 1) 414 | scored['Threshold'] = threshold 415 | scored['Anomaly'] = scored['Loss_mae'] > scored['Threshold'] 416 | 417 | predictions_train = model.predict(np.array(x_train)) 418 | predictions_train = pd.DataFrame(predictions_train, 419 | columns=x_train.columns) 420 | predictions_train.index = x_train.index 421 | 422 | scored_train = pd.DataFrame(index=x_train.index) 423 | scored_train['Loss_mae'] = np.mean(np.abs(predictions_train-x_train), axis = 1) 424 | scored_train['Threshold'] = threshold 425 | scored_train['Anomaly'] = scored_train['Loss_mae'] > scored_train['Threshold'] 426 | scored = pd.concat([scored_train, scored]).sort_index() 427 | 428 | # Cross_val_score does not support AE model, so we calculate scores individually 429 | # Did not find a suitable method of N-fold cross validation... 430 | if scores: 431 | print('\nPrinting Autoencoder scores...') 432 | print('Accuracy: {}'.format(accuracy_score(label_data, scored['Anomaly']))) 433 | print('Precision: {}'.format(precision_score(label_data, scored['Anomaly']))) 434 | print('Recall: {}'.format(recall_score(label_data, scored['Anomaly']))) 435 | print('F2 Score: {}'.format(fbeta_score(label_data, scored['Anomaly'], beta=2.0))) 436 | 437 | export = True if graph_file else False 438 | 439 | if graph == 'loss': 440 | create_graph(history.history['loss'], history.history['val_loss'], graph, export=export, graph_file=graph_file) 441 | elif graph == 'scatter': 442 | create_graph(scored, threshold, graph, model, export=export, graph_file=graph_file) 443 | elif graph == 'confusion': 444 | create_graph(scored, threshold, graph, export=export, graph_file=graph_file, ae=True, label_data=label_data) 445 | elif graph == 'mae': 446 | create_graph(x_train, label_data, graph, model, export=export, graph_file=graph_file) 447 | elif graph: 448 | create_graph(scored, label_data, graph, model, export=export, graph_file=graph_file) 449 | 450 | def get_data(csv_data_file, sample_size, mal_percent=20, test_percent=20, occ=False): 451 | rand_state_val = 42 452 | full_dataset = pd.read_csv(csv_data_file) 453 | 454 | # Scale data to 0-1 value for more efficient ML analysis 455 | mm_data = MinMaxScaler().fit_transform(full_dataset) 456 | full_dataset = pd.DataFrame(mm_data, columns=full_dataset.columns) 457 | 458 | # If model is OC-SVM convert label values to 1 and -1 (this is how OC-SVM 459 | # outputs predictions, so validation requires these values 460 | if occ: 461 | label = 'malware_label' 462 | ben = 1 463 | mal = -1 464 | full_dataset.loc[full_dataset[label] == 1, label] = mal 465 | full_dataset.loc[full_dataset[label] == 0, label] = ben 466 | 467 | benign = full_dataset[full_dataset.malware_label == ben] 468 | malware = full_dataset[full_dataset.malware_label == mal] 469 | 470 | test_size = int((test_percent / 100) * sample_size) 471 | mal_size = int((mal_percent / 100) * test_size) 472 | 473 | # Prevent malware sample size from being larger than actual sample size 474 | if mal_size > malware.shape[0]: 475 | mal_size = malware.shape[0] 476 | 477 | malware = malware.sample(n=mal_size, random_state=rand_state_val) 478 | 479 | # Prevent total sample size from being larger than actual sample size 480 | total_sample_size = sample_size - mal_size 481 | if total_sample_size > benign.shape[0]: 482 | total_sample_size = benign.shape[0] 483 | 484 | benign = benign.sample(n=total_sample_size, random_state=rand_state_val) 485 | sampled_data = benign.append(malware).reset_index(drop=True) 486 | # If not OC-SVM then provide desitnated testing and malware distributions 487 | else: 488 | ben = 0 489 | mal = 1 490 | 491 | benign = full_dataset[full_dataset.malware_label == ben] 492 | malware = full_dataset[full_dataset.malware_label == mal] 493 | 494 | mal_size = int((mal_percent / 100) * sample_size) 495 | 496 | # Prevent malware sample size from being larger than actual sample size 497 | if mal_size > malware.shape[0]: 498 | mal_size = malware.shape[0] 499 | 500 | malware = malware.sample(n=mal_size, random_state=rand_state_val) 501 | 502 | # Prevent total sample size from being larger than actual sample size 503 | total_sample_size = sample_size - mal_size 504 | if total_sample_size > benign.shape[0]: 505 | total_sample_size = benign.shape[0] 506 | 507 | benign = benign.sample(n=total_sample_size, random_state=rand_state_val) 508 | sampled_data = benign.append(malware).reset_index(drop=True) 509 | 510 | sampled_data = sampled_data.sample(frac=1).reset_index(drop=True) 511 | 512 | return sampled_data 513 | 514 | def main(): 515 | ''' 516 | Execute above functions and run through the various ML models outlined in the paper: 517 | Malware Detection in Encrypted TLS Traffic Through Machine Learning 518 | ''' 519 | 520 | parser = ArgumentParser(description='Run an ML model to analyse TLS data for malicious activity.', 521 | formatter_class=RawTextHelpFormatter) 522 | parser.add_argument('-d', '--data', action='store', dest='data_size', default=0, 523 | help='Data sample size to analyze', type=int, required=True) 524 | parser.add_argument('-m', '--malware', action='store', dest='malware_size', default=20, 525 | help='Percentage of dataset that is Malware', type=float, required=False) 526 | parser.add_argument('-t', '--test', action='store', dest='test_size', default=20, 527 | help='Percentage of dataset to use for validation', type=float, required=False) 528 | parser.add_argument('-o', '--model', action='store', dest='ml_model', 529 | help='''Machine Learning model to use. Acceptable values are: 530 | - ae = Autoencoder 531 | - svm = Support Vector Machine 532 | - oc-svm = One-Class SVM''', 533 | required=False) 534 | parser.add_argument('-s', '--save', action='store_true', dest='save_model', default=False, 535 | help='Save the trained model - REQUIRES the -f/--file option', required=False) 536 | parser.add_argument('-l', '--load', action='store_true', dest='load_model', default=False, 537 | help='Evaluate data against a trained model - REQUIRES the -f/--file option', required=False) 538 | parser.add_argument('-f', '--file', action='store', dest='file', default=None, 539 | help='Save/Load file path', required=False) 540 | parser.add_argument('-r', '--scores', action='store_true', dest='scores', default=False, 541 | help='Print 10-fold cross-validated Accuracy, Recall, Precision, and F2 scores', required=False) 542 | parser.add_argument('-g', '--graph', action='store', dest='graph', default=None, 543 | help='''Visualize the modeled dataset. Acceptable values are: 544 | SVM and OC-SVM graphs: 545 | - confusion 546 | - margin (SVM only) 547 | - boundary (SVM only) 548 | - auc 549 | Autoencoder graphs: 550 | - confusion 551 | - loss 552 | - mae 553 | - thresh 554 | - scatter''', 555 | required=False) 556 | parser.add_argument('-p', '--print', action='store_true', dest='print_data', default=False, 557 | help='Print dataset', required=False) 558 | parser.add_argument('-e', '--export', action='store_true', dest='export', default=False, 559 | help='This will save the graph to a file - REQUIRED if running in a container', required=False) 560 | parser.add_argument('-c', '--csv', action='store', dest='csv_file', 561 | help='Location of the CSV Data file', required=False) 562 | 563 | options = parser.parse_args() 564 | 565 | if (options.save_model or options.load_model) and not options.file: 566 | print('If you want to save or load a model, you must also use the -f or\n--file option and provide the location of the file.') 567 | quit() 568 | 569 | data_size = options.data_size 570 | malware_size = options.malware_size 571 | test_size = options.test_size 572 | save = options.save_model 573 | load = options.load_model 574 | scores = options.scores 575 | graph = options.graph 576 | print_data = options.print_data 577 | model = options.ml_model 578 | export_graph = options.export 579 | csv_file = options.csv_file 580 | 581 | occ = True if model == 'oc-svm' else False 582 | filename = Path(options.file) if options.file else None 583 | 584 | docker = bool(os.environ.get('RUNNING_IN_DOCKER', False)) 585 | 586 | if docker: 587 | graph_file = Path('/detect/graph/{}-{}.png'.format(model, graph)) if export_graph else None 588 | csv_file = Path('/detect/data/test_train_data.csv') if not csv_file else csv_file 589 | else: 590 | graph_file = Path('./graph/{}-{}.png'.format(model, graph)) if export_graph else None 591 | csv_file = Path('./test-train-data/test_train_data.csv') if not csv_file else csv_file 592 | 593 | if load and not filename.exists(): 594 | print('\n The file {} cannot be found... Please check your spelling and try again'.format(filename)) 595 | quit() 596 | 597 | dataset = get_data(csv_file, data_size, malware_size, test_size, occ) 598 | 599 | if print_data: 600 | print(dataset) 601 | 602 | if model == 'ae': 603 | ae(dataset, scores, save, load, filename, graph, graph_file) 604 | elif model == 'svm': 605 | svm(dataset, scores, save, load, filename, graph, graph_file) 606 | elif model == 'oc-svm': 607 | oc_svm(dataset, malware_size, scores, save, load, filename, graph, graph_file) 608 | elif model: 609 | print('\nPlease choose a model of type ae, svm, or oc-svm... To get help using this script use the -h or --help option') 610 | quit() 611 | 612 | if __name__ == '__main__': 613 | main() 614 | 615 | -------------------------------------------------------------------------------- /feature-reduction-tests/features.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import seaborn as sns 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | import tensorflow as tf 6 | import pingouin as pg 7 | import matplotlib.patches as mpatches 8 | 9 | from scipy.stats import bartlett, levene 10 | from tensorflow.keras.layers import Input, Dense 11 | from tensorflow.keras.models import Model 12 | from tensorflow.keras import regularizers 13 | from tensorflow.random import set_seed 14 | from statsmodels.stats.outliers_influence import variance_inflation_factor 15 | from sklearn.preprocessing import MinMaxScaler, StandardScaler 16 | from sklearn.decomposition import PCA 17 | from sklearn.model_selection import train_test_split 18 | from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard 19 | from sklearn.metrics import confusion_matrix, precision_recall_curve, auc, roc_curve 20 | from numpy.random import seed 21 | from sklearn.ensemble import RandomForestClassifier 22 | 23 | 24 | def malware_distribution(data, label): 25 | ''' 26 | Generate a bar chart showing malware to benign data ratio 27 | ''' 28 | # Specify data column to calculate 29 | target = data[label] 30 | # Get dataset length for percentage calculation 31 | total = len(data) 32 | # Define graph area and title 33 | plt.figure(figsize = (6, 6)) 34 | plt.title("Malware Dataset Distribution") 35 | 36 | # Generate count plot and turn into bar graph for display 37 | ax = sns.countplot(target) 38 | for p in ax.patches: 39 | percentage = '{:.0f}%'.format(p.get_height() / total * 100) 40 | x = p.get_x() + p.get_width() / 2 41 | y = p.get_height() + 5 42 | ax.annotate(percentage, (x, y), ha = 'center') 43 | 44 | plt.show() 45 | 46 | def dataset_heatmap (data, label, annotate=False): 47 | ''' 48 | Analyze all features together in a large heatmap. This is nearly impossible to interpret using all 519 features. 49 | ''' 50 | #Gausidan distrabution of dataset 51 | data_features = data.drop(label, axis=1) 52 | data_standard_dev = (data_features - data_features.mean()) / data_features.std() 53 | gaussian_data = pd.concat([data[label], data_standard_dev], axis=1) 54 | 55 | # Define plot area 56 | plt.figure(figsize = (10, 8)) 57 | plt.title("Correlation Heatmap") 58 | correlation = gaussian_data.corr() 59 | if annotate: 60 | sns.heatmap(correlation, annot = annotate, fmt = '.2f', cmap = 'coolwarm') 61 | else: 62 | sns.heatmap(correlation, annot = annotate, cmap = 'coolwarm') 63 | 64 | plt.show() 65 | 66 | def calculate_vif (data, label): 67 | ''' 68 | Method to calculate Variance Inflation Factor (VIF) to determine multi-collinearity of data. Had difficulty 69 | interpreting this output... 70 | ''' 71 | data = data.drop(label, axis=1) 72 | vif_data = pd.DataFrame() 73 | vif_data['feature'] = data.columns 74 | vif_data['VIF'] = [variance_inflation_factor(data.values, i) for i in range(len(data.columns))] 75 | 76 | for feature in vif_data: 77 | print(feature) 78 | 79 | def mal_ben_hist (data, label, graph_set, benign_percent): 80 | ''' 81 | Generate a feature for feature histogram comparing the importance of various features in distinguishing between 82 | malware and benign traffic. 83 | ''' 84 | malware_label = data.malware_label 85 | # Remove malware label 86 | data = data.drop(label, axis=1) 87 | #std_data = StandardScaler().fit_transform(data) 88 | #norm_data = normalize(data) 89 | mm_data = MinMaxScaler().fit_transform(data) 90 | data = pd.DataFrame(mm_data, columns = data.columns) 91 | _, axes = plt.subplots(10, 3, figsize=(12, 9)) # 3 columns containing 10 figures 92 | 93 | begin = graph_set * 30 94 | end = begin + 30 95 | data_to_graph = data.iloc[:, begin:end] 96 | 97 | data_to_graph = pd.concat([data_to_graph, malware_label], axis=1) 98 | malware = data_to_graph[data_to_graph.malware_label == 1] 99 | benign = data_to_graph[data_to_graph.malware_label == 0] 100 | # Get a percentage of the benign data set to balance measurements for analysis 101 | # This can be changed to view graphs differently, but is very helpful to truly 102 | # see the differences between benign and malicious traffic side by side 103 | percent = int(len(benign) * (benign_percent / 100)) 104 | benign = benign.sample(n=percent) 105 | ax = axes.ravel() 106 | for i in range(data_to_graph.shape[1] - 1): 107 | _, bins = np.histogram(data_to_graph.iloc[:, i], bins=40) 108 | ax[i].hist(malware.iloc[:, i], bins=bins, color='r', alpha=.5) # Red for malware 109 | ax[i].hist(benign.iloc[:, i], bins=bins, color='g', alpha=0.3) # Green for benign 110 | ax[i].set_title(data_to_graph.columns[i], fontsize=9) 111 | ax[i].axes.get_xaxis().set_visible(False) # Just want to see separation not measurements 112 | ax[i].set_yticks(()) 113 | 114 | ax[0].legend(['malware', 'benign'], loc='best', fontsize=8) 115 | plt.tight_layout() 116 | plt.show() 117 | 118 | 119 | def calculate_pca (data, label, components=10, fit=False, graph=None): 120 | ''' 121 | Used to generate a desired number of "Principle Components" from the input data and return the calculated 122 | output components as a pandas dataframe 123 | ''' 124 | features = data.columns 125 | # Remove features from data 126 | data_vals = data.loc[:, features].values 127 | # Define the target/label 128 | data_label = data.loc[:, [label]].values 129 | # Normalize the dataset 130 | std_data = MinMaxScaler().fit_transform(data_vals) 131 | 132 | # Calculate the 10 most important components 133 | #pca = PCA(n_components = components) 134 | if fit: 135 | data_pca_vals = PCA().fit(std_data.data) 136 | else: 137 | data_pca_vals = PCA().fit_transform(std_data) 138 | #pca_dataframe = pd.DataFrame(data = data_pca_vals) 139 | #final_pca_dataframe = pd.concat([pca_dataframe, data[[label]]], axis=1) 140 | 141 | if graph == 'heatmap': 142 | correlation = final_pca_dataframe.corr() 143 | sns.heatmap(correlation, annot=True, fmt='.2f', cmap = 'coolwarm') 144 | plt.show() 145 | elif graph == 'pairplot': 146 | sns.pairplot(final_pca_dataframe, kind='scatter', hue=label, markers=['o', 's'], palette='Set2') 147 | plt.show() 148 | elif graph == 'scatter': 149 | colors = {'0': 'darkblue', '1': 'darkorange'} 150 | plt.scatter(data_pca_vals[:, 0], data_pca_vals[:, 1], 151 | c=pd.Series(data['malware_label']).astype(str).map(colors), edgecolor='none', 152 | alpha=0.5, cmap='viridis') 153 | m = mpatches.Patch(color='darkblue', label='Benign') 154 | b = mpatches.Patch(color='darkorange', label='Malware') 155 | plt.legend(handles=[m, b]) 156 | plt.show() 157 | elif graph == 'comp_curve': 158 | plt.plot(np.cumsum(data_pca_vals.explained_variance_ratio_)) 159 | plt.xlabel('number of componsents') 160 | plt.ylabel('cumulative explained variance') 161 | plt.show() 162 | 163 | #return pd.DataFrame(final_pca_dataframe) 164 | 165 | def random_forest(data, label, estimators, graph=None): 166 | ''' 167 | Use a Random Forest to determine feature importance. Can also be used to return the top number of 168 | features determined by the "IF" statement of val_tuple[1] value. This is the threshold determined by 169 | the Random Forest regressor and can be determiend by generating and analyzing the bar chart. 170 | 171 | This proved to be between 65%-80% successful in classifing malicious traffic by itself, however, the SVM 172 | used in tls-mal-detect.py was more successful due to its robust ability to deal with outliers. 173 | ''' 174 | seed(1) 175 | set_seed(2) 176 | SEED = 123 177 | DATA_SPLIT_PCT = 0.3 178 | data_label = data.malware_label 179 | data = data.drop(label, axis=1) 180 | features = data.columns 181 | 182 | # Standardize the dataset 183 | std_data = MinMaxScaler().fit_transform(data) 184 | 185 | x_train, x_test, train_labels, test_labels = train_test_split(std_data, data_label, random_state=SEED, test_size=DATA_SPLIT_PCT) 186 | 187 | regressor = RandomForestClassifier(n_estimators=estimators, random_state=SEED) 188 | regressor.fit(x_train, train_labels) 189 | predictions = regressor.predict(x_test) 190 | feat_series = regressor.feature_importances_ 191 | 192 | if graph == 'bar': 193 | pd.Series(feat_series, index=features).nlargest(50).plot(kind='barh').invert_yaxis() 194 | plt.show() 195 | 196 | feature_list = [(feature, round(importance, 2)) for feature, importance in zip(list(features), list(feat_series))] 197 | top_10_feature_list = [] 198 | for val_tuple in feature_list: 199 | if val_tuple[1] >= 0.03: 200 | top_10_feature_list.append(val_tuple[0]) 201 | 202 | final_data = data[top_10_feature_list] 203 | final_data = pd.DataFrame(MinMaxScaler().fit_transform(final_data), columns=top_10_feature_list) 204 | final_data = pd.concat([data_label, final_data], axis=1) 205 | return final_data 206 | 207 | def autoencoded_features (data, label, final_features, graph=None): 208 | ''' 209 | Attempt to analyze and interpret data using a Sparse, Stacked Autoencoder. Was not too successful, 210 | but leaving here for potential, future analysis in feature reduction in lieu of Random Forest or 211 | PCA. Read some interesting research where that was successful. 212 | ''' 213 | # Balance dataset based on percentage passed to function 214 | output_vals = [] 215 | seed(1) 216 | set_seed(2) 217 | SEED = 123 218 | DATA_SPLIT_PCT = 0.2 219 | 220 | # Split into training and testing datasets 221 | x_train, x_test = train_test_split(data, test_size=DATA_SPLIT_PCT, random_state=SEED) 222 | x_train, x_valid = train_test_split(x_train, test_size=DATA_SPLIT_PCT, random_state=SEED) 223 | 224 | x_train_0 = x_train.loc[data[label] == 0] 225 | x_train_1 = x_train.loc[data[label] == 1] 226 | x_train_0_x = x_train_0.drop([label], axis=1) 227 | x_train_1_x = x_train_1.drop([label], axis=1) 228 | 229 | x_valid_0 = x_valid.loc[data[label] == 0] 230 | x_valid_1 = x_valid.loc[data[label] == 1] 231 | x_valid_0_x = x_valid_0.drop([label], axis=1) 232 | x_valid_1_x = x_valid_1.drop([label], axis=1) 233 | 234 | x_test_0 = x_test.loc[data[label] == 0] 235 | x_test_1 = x_test.loc[data[label] == 1] 236 | x_test_0_x = x_test_0.drop([label], axis=1) 237 | x_test_1_x = x_test_1.drop([label], axis=1) 238 | 239 | scaler = StandardScaler().fit(x_train_0_x) 240 | x_train_0_x_rescaled = scaler.transform(x_train_0_x) 241 | x_valid_0_x_rescaled = scaler.transform(x_valid_0_x) 242 | x_valid_x_rescaled = scaler.transform(x_valid.drop([label], axis=1)) 243 | 244 | x_test_0_x_rescaled = scaler.transform(x_test_0_x) 245 | x_test_x_rescaled = scaler.transform(x_test.drop([label], axis=1)) 246 | 247 | # Autoencoder values 248 | learning_epochs = 200 249 | batch_size = 128 250 | input_dim = x_train_0_x_rescaled.shape[1] 251 | #input_dim = x_train_1.shape[1] 252 | encoding_dim = int(input_dim / 2) 253 | hidden_dim_1 = int(encoding_dim / 2) 254 | hidden_dim_2 = int(hidden_dim_1 / 2) 255 | final_hidden_dim = final_features 256 | learning_rate = 1e-6 257 | 258 | input_layer = Input(shape=(input_dim, )) 259 | encoder = Dense(encoding_dim, activation='relu', activity_regularizer=regularizers.l1(learning_rate))(input_layer) 260 | encoder = Dense(hidden_dim_1, activation='relu')(encoder) 261 | encoder = Dense(hidden_dim_2, activation='relu')(encoder) 262 | encoder = Dense(final_hidden_dim, activation='relu')(encoder) 263 | decoder = Dense(final_hidden_dim, activation='relu')(encoder) 264 | decoder = Dense(hidden_dim_2, activation='relu')(decoder) 265 | decoder = Dense(hidden_dim_1, activation='relu')(decoder) 266 | decoder = Dense(encoding_dim, activation='relu')(decoder) 267 | decoder = Dense(input_dim, activation='linear')(decoder) 268 | autoencoder = Model(inputs=input_layer, outputs=decoder) 269 | autoencoder.summary() 270 | 271 | autoencoder.compile(metrics=['accuracy'], loss='mean_squared_error', optimizer='adam') 272 | write_model = ModelCheckpoint(filepath=r'C:\Users\bryan\Desktop\ae_data\model\ae_calssifier.h5', save_best_only=True, verbose=0) 273 | write_logs = TensorBoard(log_dir=r'C:\Users\bryan\Desktop\ae_data\logs', histogram_freq=0, write_graph=True, write_images=True) 274 | history = autoencoder.fit(x_train_0_x_rescaled, x_train_0_x_rescaled, 275 | epochs=learning_epochs, 276 | batch_size=batch_size, 277 | validation_data=(x_valid_0_x_rescaled, x_valid_0_x_rescaled), 278 | verbose=1, 279 | callbacks=[write_model, write_logs]).history 280 | 281 | valid_x_predictions = autoencoder.predict(x_valid_x_rescaled) 282 | mse = np.mean(np.power(x_valid_x_rescaled - valid_x_predictions, 2), axis=1) 283 | 284 | error_df = pd.DataFrame({'Reconstruction_error': mse, 'True_class': x_valid[label]}) 285 | false_pos_rate, true_pos_rate, thresholds = roc_curve(error_df['True_class'], error_df['Reconstruction_error']) 286 | threshold = np.mean(thresholds) 287 | threshold_fixed = float("{:0.4f}".format(threshold)) 288 | roc_auc = auc(false_pos_rate, true_pos_rate,) 289 | 290 | output_vals.append('MSE: {}'.format(mse)) 291 | output_vals.append('Threshold mean: {}'.format(threshold)) 292 | output_vals.append('AUC: {}'.foramt(auc(false_pos_rate, true_pos_rate))) 293 | 294 | if graph == 'loss': 295 | plt.plot(history['loss']) 296 | plt.plot(history['val_loss']) 297 | plt.title('model_loss') 298 | plt.ylabel('loss') 299 | plt.xlabel('epoch') 300 | plt.legend(['train', 'test'], loc='upper left') 301 | plt.show() 302 | elif graph == 'pre_call': 303 | precision_rt, recall_rt, threshold_rt = precision_recall_curve(error_df.True_class, error_df.Reconstruction_error) 304 | plt.plot(threshold_rt, precision_rt[1:], label='Precision', linewidth=5) 305 | plt.plot(threshold_rt, recall_rt[1:], label='Recall', linewidth=5) 306 | plt.title('Precision and recall for different threshold values') 307 | plt.xlabel('Threshold') 308 | plt.ylabel('Precision/Recall') 309 | plt.legend() 310 | plt.show() 311 | elif graph == 're_error': 312 | groups = error_df.groupby('True_class') 313 | fig, ax = plt.subplots() 314 | for name, group in groups: 315 | ax.plot(group.index, group.Reconstruction_error, marker='o', ms=3.5, linestyle='', label='Malware Estimation' if name == 1 else 'Benign Estimate') 316 | ax.hlines(threshold_fixed, ax.get_xlim()[0], ax.get_xlim()[1], colors='r', zorder=100, label='Threshold') 317 | ax.legend() 318 | plt.title('Reconstruction error for malicious/benign traffic') 319 | plt.ylabel('Reconstruction error') 320 | plt.xlabel('Data point index') 321 | plt.show() 322 | elif graph == 'heatmap': 323 | pred_y = [1 if e > threshold_fixed else 0 for e in error_df['Reconstruction_error'].values] 324 | conf_matrix = confusion_matrix(error_df['True_class'], pred_y) 325 | plt.figure(figsize=(8, 6)) 326 | sns.heatmap(conf_matrix, 327 | xticklabels=['Benign', 'Malware'], 328 | yticklabels=['Benign', 'Malware'], 329 | annot=True, fmt='d') 330 | plt.title('Confusion Matrix') 331 | plt.ylabel('True class') 332 | plt.xlabel('Predicted class') 333 | plt.show() 334 | elif graph == 'roc': 335 | plt.plot(false_pos_rate, true_pos_rate, linewidth=5, label='AUC = %0.3f'% roc_auc) 336 | plt.plot([0,1],[0,1], linewidth=5) 337 | plt.xlim([-0.01, 1]) 338 | plt.ylim([0, 1.01]) 339 | plt.legend(loc='lower right') 340 | plt.title('Reciever operating charactistic curve (ROC)') 341 | plt.ylabel('True Positive Rating') 342 | plt.xlabel('False Positive Rate') 343 | plt.show() 344 | 345 | return output_vals 346 | 347 | def factor_analysis(data, label, eq_var=True): 348 | ''' 349 | Method to perform factor analysis to determine the most important features and calculate 350 | the ability to distinguish between malware and benign traffic using varying numbers of "important" 351 | features. 352 | ''' 353 | np.seterr(divide='raise') 354 | for feature in data.columns: 355 | try: 356 | bart_vals = pg.homoscedasticity(data, dv=feature, group='malware_label', method='bartlett') 357 | lev_vals = pg.homoscedasticity(data, dv=feature, group='malware_label') 358 | if bart_vals['equal_var'].values[0] == eq_var: 359 | print("Bartlett Value feature: {}\nT Value: {}\nP Value: {}".format(feature, bart_vals['T'].values[0], bart_vals['pval'].values[0])) 360 | elif lev_vals['equal_var'].values[0] == eq_var: 361 | print("Levene Value feature: {}\nT Value: {}\nP Value: {}".format(feature, bart_vals['T'].values[0], bart_vals['pval'].values[0])) 362 | except Exception as e: 363 | pass 364 | 365 | #if __name__ == '__main__': 366 | #def load_input (csv_data_file): 367 | csv_data_file = r'test-train-data\test\test_train_data-all.csv' 368 | csv_data_file_new = r'test-train-data\validate\validate_data_new-all.csv' 369 | dataset = pd.read_csv(csv_data_file) 370 | new_dataset = pd.read_csv(csv_data_file_new) 371 | 372 | full_data = pd.concat([dataset, new_dataset], axis=0) 373 | full_data = full_data.reset_index() 374 | # Remove columns filled with all 0 value (these will be statistically insignifant and will cause 375 | # issues when using correlation methods of analysis) 376 | data_no_z_cols = dataset.loc[:, (dataset != 0).any(axis=0)] 377 | 378 | # NOTE TO SELF 379 | # To import as module for testing: 380 | # from importlib import import_module, reload 381 | # a = import_module('features') 382 | # Use this when you make changes 383 | # reload(a) 384 | # 385 | # Call methods using below syntax: 386 | # a.random_forest(a.dataset, 'labelname', 100, 'bar') -------------------------------------------------------------------------------- /feature-reduction-tests/graph_data.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import seaborn as sns 4 | import matplotlib.pyplot as plt 5 | from sklearn.preprocessing import MinMaxScaler 6 | 7 | #csv_data_file = r'test-train-data\test\test_train_data-all.csv' 8 | #new_csv_data_file = r'test-train-data\validate\validate_data_new-all.csv' 9 | csv_data_file = r'test-train-data\test_train_data.csv' 10 | 11 | #all_data = pd.concat([pd.read_csv(csv_data_file), pd.read_csv(new_csv_data_file)], axis=0) 12 | all_data = pd.read_csv(csv_data_file) 13 | all_data_nz = all_data.loc[:, (all_data != 0).any(axis=0)] 14 | 15 | mal = all_data_nz[all_data_nz.malware_label == 1] 16 | #mal = pd.DataFrame(pd.DataFrame(MinMaxScaler().fit_transform(mal), columns=mal.columns).mean(), columns=['Malware']) 17 | ben = all_data_nz[all_data_nz.malware_label == 0] 18 | #ben = pd.DataFrame(pd.DataFrame(MinMaxScaler().fit_transform(ben), columns=ben.columns).mean(), columns=['Benign']) 19 | 20 | ####################### 21 | # CS Number of CS's used 22 | #sns.barplot(data=cs_sum, x=cs_sum.index) 23 | #mal_cs_nz = len(mal_cs_data.loc[:, (mal_cs_data != 0).any(axis=0)].columns) 24 | #ben_cs_nz = len(ben_cs_data.loc[:, (ben_cs_data != 0).any(axis=0)].columns) 25 | 26 | # Add labels above bars 27 | #cs_count = pd.DataFrame({'Label': ['Benign Signature Algorithms', 'Malware Signature Algorithms'], 'Count': [ben_cs_nz, mal_cs_nz]}) 28 | #ax = sns.barplot(data=cs_count, y='Count', x='Label') 29 | #for bar in ax.patches: 30 | # ax.annotate(format(bar.get_height(), ''), 31 | # (bar.get_x() + bar.get_width() / 2, 32 | # bar.get_height()), ha='center', va='center', 33 | # size=15, xytext=(0, 8), 34 | # textcoords='offset points') 35 | 36 | ################ 37 | # CS top 30 Utilization comparison 38 | mal_cs_data = mal.filter(regex='grp_') 39 | #mal_cs_data = mal_cs_data.drop(['cs_len'], axis=1) 40 | #mal_cs_data = mal_cs_data.loc[:, (mal_cs_data != 0).any(axis=0)] 41 | #mal_cs_data = pd.concat([mal_cs_data, mal.malware_label], axis=1) 42 | 43 | ben_cs_data = ben.filter(regex='grp_') 44 | #ben_cs_data = ben_cs_data.drop(['cs_len'], axis=1) 45 | #ben_cs_data = ben_cs_data.loc[:, (ben_cs_data != 0).any(axis=0)] 46 | #ben_cs_data = pd.concat([ben_cs_data, ben.malware_label], axis=1) 47 | 48 | #cs_sum = pd.concat([ben_cs_data.sum(), mal_cs_data.sum()], axis=1) 49 | cs_sum = pd.DataFrame({"Benign": ben_cs_data.sum(), "Malware": mal_cs_data.sum()}, index=ben_cs_data.sum().sort_values().index) 50 | #cs_sum = cs_sum.loc[:, (cs_sum != 0).any(axis=0)] 51 | #cs_sum = pd.DataFrame({"Benign": ben_cs_data.sum().sort_values()}, index=ben_cs_data.sum().sort_values().index) 52 | #cs_sum = pd.DataFrame({"Malware": mal_cs_data.sum().sort_values()}, index=mal_cs_data.sum().sort_values().index) 53 | 54 | ################### 55 | # Length Fields 56 | #mal_len_data = mal.filter(regex='_len') 57 | #mal_len_data = mal_len_data.loc[:, (mal_len_data != 0).any(axis=0)] 58 | 59 | #ben_len_data = ben.filter(regex='_len') 60 | #ben_len_data = ben_len_data.loc[:, (ben_len_data != 0).any(axis=0)] 61 | 62 | #cs_sum = pd.concat([pd.DataFrame(ben_len_data.mean(), columns=['Benign']), pd.DataFrame(mal_len_data.mean(), columns=['Malware'])], axis=1) 63 | 64 | ################# 65 | # Svr features 66 | #mal_svr_data = mal.filter(regex='handshake_') 67 | #mal_svr_data = mal[['dom_in_tranco_1m', 'dom_dga_prob', 'otx_status', 'otx_age', 'urlhaus_status','urlhaus_age']] 68 | #mal_svr_data = mal_svr_data.drop(['svr_tls_ver', 'svr_supported_ver'], axis=1) 69 | #mal_svr_data = pd.DataFrame(pd.DataFrame(MinMaxScaler().fit_transform(mal_svr_data), columns=mal_svr_data.columns).mean(), columns=['Malware']) 70 | 71 | #ben_svr_data = ben.filter(regex='handshake_') 72 | #ben_svr_data = ben[['dom_in_tranco_1m', 'dom_dga_prob', 'otx_status', 'otx_age', 'urlhaus_status','urlhaus_age']] 73 | #ben_svr_data = ben_svr_data.drop(['svr_tls_ver', 'svr_supported_ver'], axis=1) 74 | #ben_svr_data = pd.DataFrame(pd.DataFrame(MinMaxScaler().fit_transform(ben_svr_data), columns=ben_svr_data.columns).mean(), columns=['Benign']) 75 | 76 | #cs_sum = pd.concat([ben_svr_data, mal_svr_data], axis=1).sort_values(by='Malware') 77 | 78 | ################ 79 | # Ports 80 | #mal_prt = mal[['src_port', 'dst_port']] 81 | #ben_prt = ben[['src_port', 'dst_port']] 82 | #ben_percent = ben_prt.dst_port.unique().shape[0] / ben_prt.dst_port.shape[0] 83 | #mal_percent = mal_prt.dst_port.unique().shape[0] / mal_prt.dst_port.shape[0] 84 | #cs_sum = pd.DataFrame({'Label': ['Benign Unique Dst Ports', 'Malware Unique Dst Ports'], 'Count': [ ben_percent, mal_percent ]}) 85 | #cs_sum = pd.DataFrame(ben_prt.dst_port.value_counts()).sort_values(by='dst_port').tail(10) 86 | #cs_sum = cs_sum[cs_sum.index <= 30000] 87 | #cs_sum = pd.concat([ben_cs_data, mal_cs_data], axis=1).sort_values(by='Malware').tail(40) 88 | #mal_cs_nz = len(mal_cs_data.loc[:, (mal_cs_data != 0).any(axis=0)].columns) 89 | #ben_cs_nz = len(ben_cs_data.loc[:, (ben_cs_data != 0).any(axis=0)].columns) 90 | 91 | # Add labels above bars 92 | #cs_count = pd.DataFrame({'Label': ['Benign Cipher Suites', 'Malware Cipher Suites'], 'Count': [ben_cs_nz, mal_cs_nz]}) 93 | 94 | #ax = sns.barplot(data=cs_count, y='Count', x='Label', orient='v') 95 | 96 | #ax.set_xticklabels(ax.get_xticklabels(), rotation=0) 97 | #for bar in ax.patches: 98 | # ax.annotate(format(bar.get_height(), ''), 99 | # (bar.get_x() + bar.get_width() / 2, 100 | # bar.get_height()), ha='center', va='center', 101 | # size=8, xytext=(0, 8), 102 | # textcoords='offset points') 103 | #ax.set(xlabel='Label', ylabel='Count') 104 | cs_sum.plot.barh(rot=0) 105 | plt.show() -------------------------------------------------------------------------------- /feature-reduction-tests/reduce_features.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | from tensorflow.keras.layers import Input, Dense 4 | from tensorflow.keras.models import Model 5 | from tensorflow.keras import regularizers 6 | from tensorflow.random import set_seed 7 | from sklearn.preprocessing import MinMaxScaler 8 | from sklearn.decomposition import PCA 9 | from numpy.random import seed 10 | from sklearn.ensemble import RandomForestClassifier 11 | 12 | def pca_output (data, label, components=10): 13 | ''' 14 | Used to generate a desired number of "Principle Components" from the input data and return the calculated 15 | output components as a pandas dataframe 16 | ''' 17 | data_label = data[[label]] 18 | data = data.drop([label], axis=1) 19 | std_data = MinMaxScaler().fit_transform(data.values) 20 | 21 | # Calculate the 10 most important components 22 | pca = PCA(n_components = components) 23 | data_pca_vals = pca.fit_transform(std_data) 24 | pca_dataframe = pd.DataFrame(data = data_pca_vals) 25 | final_pca_dataframe = pd.concat([pca_dataframe, data_label], axis=1) 26 | 27 | return pd.DataFrame(final_pca_dataframe) 28 | 29 | 30 | def random_forest(data, label, estimators): 31 | ''' 32 | Use a Random Forest to determine feature importance. Can also be used to return the top number of 33 | features determined by the "IF" statement of val_tuple[1] value. This is the threshold determined by 34 | the Random Forest regressor and can be determiend by generating and analyzing the bar chart. 35 | 36 | This proved to be between 65%-80% successful in classifing malicious traffic by itself, however, the SVM 37 | used in svm-testing.py was more successful due to its robust ability to deal with outliers. 38 | ''' 39 | seed(1) 40 | set_seed(2) 41 | SEED = 123 42 | data_label = data.malware_label 43 | data = data.drop([label], axis=1) 44 | features = data.columns 45 | 46 | # Standardize the dataset 47 | std_data = MinMaxScaler().fit_transform(data) 48 | 49 | regressor = RandomForestClassifier(n_estimators=estimators, random_state=SEED) 50 | regressor.fit(std_data, data_label) 51 | feat_series = regressor.feature_importances_ 52 | 53 | feature_list = [(feature, round(importance, 2)) for feature, importance in zip(list(features), list(feat_series))] 54 | top_x_feature_list = [] 55 | for val_tuple in feature_list: 56 | if val_tuple[1] >= 0.03: 57 | top_x_feature_list.append(val_tuple[0]) 58 | 59 | final_data = pd.DataFrame(MinMaxScaler().fit_transform(data[top_x_feature_list])) 60 | final_data = pd.concat([final_data, data_label], axis=1) 61 | 62 | # Return dataframe of N most important features based on feature_list importances and 63 | # val_tuple[0] measure value 64 | return final_data 65 | 66 | def autoencoded_features (data, label, feature_count): 67 | ''' 68 | Attempt to analyze and interpret data using a Sparse, Stacked Autoencoder. Was not too successful, 69 | but leaving here for potential, future analysis in feature reduction in lieu of Random Forest or 70 | PCA. Read some interesting research where that was successful. 71 | ''' 72 | # Balance dataset based on percentage passed to function 73 | seed(1) 74 | set_seed(2) 75 | data_label = data.malware_label 76 | data = data.drop([label], axis=1) 77 | std_data = MinMaxScaler().fit_transform(data) 78 | 79 | # Autoencoder values 80 | input_dim = data.shape[1] 81 | encoding_dim = int(input_dim / 2) 82 | hidden_dim_1 = int(encoding_dim / 2) 83 | hidden_dim_2 = int(hidden_dim_1 / 2) 84 | final_hidden_dim = feature_count 85 | learning_rate = 1e-6 86 | 87 | input_layer = Input(shape=(input_dim, )) 88 | encoder = Dense(encoding_dim, activation='relu', activity_regularizer=regularizers.l1(learning_rate))(input_layer) 89 | encoder = Dense(hidden_dim_1, activation='relu')(encoder) 90 | encoder = Dense(hidden_dim_2, activation='relu')(encoder) 91 | encoder = Dense(final_hidden_dim, activation='relu')(encoder) 92 | 93 | autoencoder_model = Model(inputs=input_layer, outputs=encoder) 94 | autoencoder_feature_output = pd.DataFrame(autoencoder_model.predict(std_data)) 95 | autoencoder_feature_output = pd.concat([autoencoder_feature_output, data_label], axis=1) 96 | 97 | return autoencoder_feature_output 98 | 99 | if __name__ == '__main__': 100 | #def load_input (csv_data_file): 101 | csv_data_file = 'test_train_data-all.csv' 102 | dataset = pd.read_csv(csv_data_file) 103 | # Remove columns filled with all 0 value (these will be statistically insignifant and will cause 104 | # issues when using correlation methods of analysis) 105 | data_no_z_cols = dataset.loc[:, (dataset != 0).any(axis=0)] 106 | 107 | # NOTE TO SELF 108 | # To import as module for testing: 109 | # from importlib import import_module, reload 110 | # a = import_module('features') 111 | # Use this when you make changes 112 | # reload(a) 113 | # 114 | # Call methods using below syntax: 115 | # a.random_forest(a.dataset, 'labelname', 100, 'bar') -------------------------------------------------------------------------------- /format-data/check_ip.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # This script tells if a File, IP, Domain or URL may be malicious according to the data in a couple of 4 | # OSINT sources 5 | import IndicatorTypes 6 | import json 7 | import socket 8 | import requests 9 | import os 10 | import time 11 | import logging 12 | import csv 13 | import ipaddress 14 | 15 | from datetime import date, datetime, timedelta 16 | from dateutil.parser import parse 17 | from OTXv2 import OTXv2 18 | from tranco import Tranco 19 | 20 | # Define logger for cross appliction logging consistency 21 | logger = logging.getLogger(__name__) 22 | 23 | def getValue(results, keys): 24 | ''' 25 | Get a nested key from a dict, without having to do loads of ifs 26 | ''' 27 | 28 | if type(keys) is list and len(keys) > 0: 29 | if type(results) is dict: 30 | key = keys.pop(0) 31 | if key in results: 32 | return getValue(results[key], keys) 33 | else: 34 | return None 35 | else: 36 | if type(results) is list and len(results) > 0: 37 | return getValue(results[0], keys) 38 | else: 39 | return results 40 | else: 41 | return results 42 | 43 | def date_range(start_date, end_date): 44 | ''' 45 | Return a list of the dates from start to end date 46 | ''' 47 | try: 48 | dates = [] 49 | for day in range (int ((end_date - start_date).days) + 1): 50 | dates.append(start_date + timedelta(day)) 51 | except Exception as e: 52 | logging.exception("There was a problem generating dates... {}".format(e)) 53 | exit(1) 54 | 55 | return dates 56 | 57 | def is_ipv4(string): 58 | try: 59 | ipaddress.IPv4Network(string) 60 | return True 61 | except ValueError: 62 | return False 63 | 64 | def ip(api_key, ip): 65 | ''' 66 | Query AlienVault OTX for malicious IP checking 67 | ''' 68 | alerts = {} 69 | full_url_list = [] 70 | report_age = 0 71 | url_status = 0 72 | 73 | if ipaddress.ip_address(ip).is_private: 74 | alerts = {'url_status': 0, 'report_age': 0} 75 | else: 76 | # Set URLs and instantiate OTX object 77 | OTX_SERVER = 'https://otx.alienvault.com/' 78 | otx = OTXv2(api_key, server=OTX_SERVER) 79 | 80 | try: 81 | result = otx.get_indicator_details_full(IndicatorTypes.IPv4, ip) 82 | pulses = getValue(result['general'], ['pulse_info', 'pulses']) 83 | if pulses: 84 | full_url_list = getValue(result['passive_dns'], ['passive_dns']) 85 | if full_url_list: 86 | first_reported = datetime.strptime(full_url_list[-1]['first'], "%Y-%m-%dT%H:%M:%S") 87 | last_reported = datetime.strptime(full_url_list[0]['last'], "%Y-%m-%dT%H:%M:%S") 88 | report_age = int(((last_reported - first_reported).total_seconds() / 86400)) 89 | else: 90 | report_age = 0 91 | url_status = 1 92 | 93 | except (RetryError): 94 | url_status = 1 95 | report_age = 0 96 | except Exception as e: 97 | logger.exception(" : You received this error with the OTX API Data... {}".format(e)) 98 | 99 | # Build alerts dictionary from variables 100 | alerts = {'url_status': url_status, 'report_age': report_age} 101 | 102 | return alerts 103 | 104 | def hostname(host, ip_addr, query_two=False): 105 | ''' 106 | Query urlhaus.abuse.ch for malicious URL checking (if no URL found, check IP as some malicious domains are the unresolved IP) 107 | ''' 108 | alerts = {} 109 | report_age = 0 110 | url_status = 0 111 | query_results = '' 112 | __version__ = '0.0.2' 113 | 114 | # URL haus API URL 115 | urlhaus_api = "https://urlhaus-api.abuse.ch/v1/" 116 | 117 | if is_ipv4(ip_addr) and ipaddress.ip_address(ip_addr).is_private: 118 | query_two = True 119 | 120 | try: 121 | query_urlhaus = requests.post("{}host/".format(urlhaus_api), headers={"User-Agent" : "urlhaus-python-client-{}".format(__version__)}, data={"host": host}) 122 | if query_urlhaus.ok: 123 | query_results = query_urlhaus.json() 124 | if query_results['query_status'] == "no_results" and not query_two: 125 | hostname(ip_addr, host, True) 126 | 127 | elif query_results['query_status'] == "no_results" and query_two: 128 | url_status = 0 129 | report_age = 0 130 | 131 | else: 132 | if not query_urlhaus.json()['urls']: 133 | url_status = 0.5 134 | report_age = 0 135 | elif query_urlhaus.json()['urls'][0]['url_status'] == 'online': 136 | first_seen = datetime.strptime(query_urlhaus.json()['firstseen'], "%Y-%m-%d %H:%M:%S UTC") 137 | last_seen = datetime.now() 138 | report_age = int(((last_seen - first_seen).total_seconds() / 86400)) 139 | url_status = 1 140 | else: 141 | url_status = 0.5 142 | report_age = 0 143 | 144 | else: 145 | logger.error(" : Unable to read response as json") 146 | 147 | except Exception as e: 148 | logger.exception(" : Unable to connect to URLHaus API. Recieved the following error {} - {} - {}".format(e, host, ip_addr)) 149 | 150 | # Build alerts dictionary from variables 151 | alerts = {'url_status': url_status, 'report_age': report_age} 152 | return alerts 153 | 154 | def update_csv(csv_file): 155 | ''' 156 | Method to update ja3 csv file from sslbl.urlhaus.ch 157 | ''' 158 | with open(csv_file, 'wb') as write_ja3_csv: 159 | csv_data = requests.get('https://sslbl.abuse.ch/blacklist/ja3_fingerprints.csv') 160 | write_ja3_csv.write(csv_data.content) 161 | 162 | def ja3_sslbl_check(fingerprint): 163 | ''' 164 | Method to check JA3 database for existence of connection 165 | ''' 166 | ja3_malware_check = {} 167 | csv_filename = r'C:\Users\bryan\Desktop\ja3_fingerprints.csv' 168 | days = 1 169 | report_age = 0 170 | ja3_check = 0 171 | 172 | if not os.path.exists(csv_filename): 173 | update_csv(csv_filename) 174 | else: 175 | file_modify_date = os.path.getmtime(csv_filename) 176 | file_older_than_days = ((time.time() - file_modify_date) / 3600 > 24 * days) 177 | if file_older_than_days: 178 | update_csv(csv_filename) 179 | 180 | with open(csv_filename, 'r') as ja3_csv_file: 181 | # Add csv file to variable and ignore comments 182 | read_ja3 = csv.reader(filter(lambda row: row[0] != '#', ja3_csv_file)) 183 | # Locate value in csv (if exists) 184 | for ja3_fingerprint in read_ja3: 185 | if fingerprint == ja3_fingerprint[0]: 186 | ja3_check = 1 187 | first_seen = datetime.strptime(ja3_fingerprint[1], "%Y-%d-%m %H:%M:%S") 188 | last_seen = datetime.strptime(ja3_fingerprint[2], "%Y-%d-%m %H:%M:%S") 189 | report_age = int((last_seen - first_seen).total_seconds() / 86400) 190 | break 191 | 192 | ja3_malware_check = {'ja3_check': ja3_check, 'ja3_record_age': report_age} 193 | 194 | return ja3_malware_check 195 | 196 | def dns_tranco_check(cache_dir, domain_name, number_of_days): 197 | ''' 198 | Analyze DNS domains for Tranco 1 million over the last 30 days and return percentage existence 199 | ''' 200 | # Set variables 201 | tranco_result = float() 202 | begin_date = date.today() - timedelta(number_of_days) 203 | # Must set time delta to not consider the last 2 days. This prevents errors when the latest 204 | # records have not been released during the evaluation timeframe 205 | end_date = date.today() - timedelta(2) 206 | date_check_range = date_range(begin_date, end_date) 207 | tranco_data = Tranco(cache=True, cache_dir=cache_dir) 208 | occurence_count = 0 209 | 210 | # Iterate over date range and increase count for each occurence of the domain 211 | try: 212 | for single_day in date_check_range: 213 | tranco_1M = set(tranco_data.list(single_day.strftime("%Y-%m-%d")).top(1000000)) 214 | if domain_name in tranco_1M: 215 | occurence_count += 1 216 | else: 217 | occurence_count += 0 218 | except (ValueError, AttributeError): 219 | occurence_count += 0 220 | except Exception as e: 221 | logging.exception("There was a problem in Tranco analysis... {}".format(e)) 222 | #exit(1) 223 | 224 | # Convert occurence value to float for ML analysis 225 | tranco_result = occurence_count / number_of_days 226 | 227 | return tranco_result 228 | 229 | def main(): 230 | ''' 231 | Run some automated tests for ip and hostname methods 232 | ''' 233 | api_key = os.environ.get('API_KEY') 234 | ip_addr = '4.4.4.4' 235 | host = 'google.com' 236 | 237 | print("IP Query output: {}".format(ip(api_key, ip_addr))) 238 | print("Hostname Query output: {}".format(hostname(host, ip_addr))) 239 | 240 | if __name__ == "__main__": 241 | try: 242 | exit(main()) 243 | except Exception: 244 | logging.exception("Exception in main()") 245 | exit(1) -------------------------------------------------------------------------------- /format-data/extract_data_csv.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import csv 4 | import logging 5 | import os 6 | import argparse 7 | 8 | from check_ip import ip, hostname, ja3_sslbl_check, dns_tranco_check 9 | from dgaintel import get_prob 10 | from concurrent.futures import ProcessPoolExecutor 11 | from functools import partial 12 | 13 | # Define logger for cross appliction logging consistency 14 | logger = logging.getLogger(__name__) 15 | 16 | ip_domain_dict = {} 17 | 18 | csv_header = ['dom_in_tranco_1m', 'dom_dga_prob', 'otx_status', 'otx_age', 'urlhaus_status', 19 | 'urlhaus_age', 'ja3_urlhaus_status', 'ja3_urlhaus_age', 'tls_record_type', 'client_tls_ver', 20 | 'message_len', 'handshake_type', 'handshake_version', 'handshake_len', 21 | 'cs_len', 'ext_len', 'src_port', 'dst_port', 'cs_0000', 'cs_0001', 'cs_0002', 22 | 'cs_0003', 'cs_0004', 'cs_0005', 'cs_0006', 'cs_0007', 'cs_0008','cs_0009', 23 | 'cs_000a', 'cs_000b', 'cs_000c', 'cs_000d', 'cs_000e', 'cs_000f', 'cs_0010', 24 | 'cs_0011', 'cs_0012','cs_0013', 'cs_0014', 'cs_0015', 'cs_0016', 'cs_0017', 'cs_0018', 25 | 'cs_0019', 'cs_001a', 'cs_001b', 'cs_001e', 'cs_001f', 'cs_0020', 'cs_0021', 'cs_0022', 26 | 'cs_0023', 'cs_0024', 'cs_0025', 'cs_0026', 'cs_0027', 'cs_0028', 'cs_0029', 27 | 'cs_002a', 'cs_002b', 'cs_002c', 'cs_002d', 'cs_002e', 'cs_002f', 'cs_0030', 28 | 'cs_0031', 'cs_0032', 'cs_0033', 'cs_0034', 'cs_0035', 'cs_0036', 'cs_0037', 29 | 'cs_0038', 'cs_0039', 'cs_003a', 'cs_003b', 'cs_003c', 'cs_003d', 'cs_003e', 30 | 'cs_003f', 'cs_0040', 'cs_0041', 'cs_0042', 'cs_0043', 'cs_0044', 'cs_0045', 31 | 'cs_0046', 'cs_0067', 'cs_0068', 'cs_0069', 'cs_006a', 'cs_006b', 'cs_006c', 32 | 'cs_006d', 'cs_0084', 'cs_0085', 'cs_0086', 'cs_0087', 'cs_0088', 'cs_0089', 33 | 'cs_008a', 'cs_008b', 'cs_008c', 'cs_008d', 'cs_008e', 'cs_008f', 'cs_0090', 34 | 'cs_0091', 'cs_0092', 'cs_0093', 'cs_0094', 'cs_0095', 'cs_0096', 'cs_0097', 35 | 'cs_0098', 'cs_0099', 'cs_009a', 'cs_009b', 'cs_009c', 'cs_009d', 'cs_009e', 36 | 'cs_009f', 'cs_00a0', 'cs_00a1', 'cs_00a2', 'cs_00a3', 'cs_00a4', 'cs_00a5', 37 | 'cs_00a6', 'cs_00a7', 'cs_00a8', 'cs_00a9', 'cs_00aa', 'cs_00ab', 'cs_00ac', 38 | 'cs_00ad', 'cs_00ae', 'cs_00af', 'cs_00b0', 'cs_00b1', 'cs_00b2', 'cs_00b3', 39 | 'cs_00b4', 'cs_00b5', 'cs_00b6', 'cs_00b7', 'cs_00b8', 'cs_00b9', 'cs_00ba', 40 | 'cs_00bb', 'cs_00bc', 'cs_00bd', 'cs_00be', 'cs_00bf', 'cs_00c0', 'cs_00c1', 41 | 'cs_00c2', 'cs_00c3', 'cs_00c4', 'cs_00c5', 'cs_00c6', 'cs_00c7', 'cs_00ff', 42 | 'cs_1301', 'cs_1302', 'cs_1303', 'cs_1304', 'cs_1305', 'cs_5600', 'cs_c001', 43 | 'cs_c002', 'cs_c003', 'cs_c004', 'cs_c005', 'cs_c006', 'cs_c007', 'cs_c008', 44 | 'cs_c009', 'cs_c00a', 'cs_c00b', 'cs_c00c', 'cs_c00d', 'cs_c00e', 'cs_c00f', 45 | 'cs_c010', 'cs_c011', 'cs_c012', 'cs_c013', 'cs_c014', 'cs_c015', 'cs_c016', 46 | 'cs_c017', 'cs_c018', 'cs_c019', 'cs_c01a', 'cs_c01b', 'cs_c01c', 'cs_c01d', 47 | 'cs_c01e', 'cs_c01f', 'cs_c020', 'cs_c021', 'cs_c022', 'cs_c023', 'cs_c024', 48 | 'cs_c025', 'cs_c026', 'cs_c027', 'cs_c028', 'cs_c029', 'cs_c02a', 'cs_c02b', 49 | 'cs_c02c', 'cs_c02d', 'cs_c02e', 'cs_c02f', 'cs_c030', 'cs_c031', 'cs_c032', 50 | 'cs_c033', 'cs_c034', 'cs_c035', 'cs_c036', 'cs_c037', 'cs_c038', 'cs_c039', 51 | 'cs_c03a', 'cs_c03b', 'cs_c03c', 'cs_c03d', 'cs_c03e', 'cs_c03f', 'cs_c040', 52 | 'cs_c041', 'cs_c042', 'cs_c043', 'cs_c044', 'cs_c045', 'cs_c046', 'cs_c047', 53 | 'cs_c048', 'cs_c049', 'cs_c04a', 'cs_c04b', 'cs_c04c', 'cs_c04d', 'cs_c04e', 54 | 'cs_c04f', 'cs_c050', 'cs_c051', 'cs_c052', 'cs_c053', 'cs_c054', 'cs_c055', 55 | 'cs_c056', 'cs_c057', 'cs_c058', 'cs_c059', 'cs_c05a', 'cs_c05b', 'cs_c05c', 56 | 'cs_c05d', 'cs_c05e', 'cs_c05f', 'cs_c060', 'cs_c061', 'cs_c062', 'cs_c063', 57 | 'cs_c064', 'cs_c065', 'cs_c066', 'cs_c067', 'cs_c068', 'cs_c069', 'cs_c06a', 58 | 'cs_c06b', 'cs_c06c', 'cs_c06d', 'cs_c06e', 'cs_c06f', 'cs_c070', 'cs_c071', 59 | 'cs_c072', 'cs_c073', 'cs_c074', 'cs_c075', 'cs_c076', 'cs_c077', 'cs_c078', 60 | 'cs_c079', 'cs_c07a', 'cs_c07b', 'cs_c07c', 'cs_c07d', 'cs_c07e', 'cs_c07f', 61 | 'cs_c080', 'cs_c081', 'cs_c082', 'cs_c083', 'cs_c084', 'cs_c085', 'cs_c086', 62 | 'cs_c087', 'cs_c088', 'cs_c089', 'cs_c08a', 'cs_c08b', 'cs_c08c', 'cs_c08d', 63 | 'cs_c08e', 'cs_c08f', 'cs_c090', 'cs_c091', 'cs_c092', 'cs_c093', 'cs_c094', 64 | 'cs_c095', 'cs_c096', 'cs_c097', 'cs_c098', 'cs_c099', 'cs_c09a', 'cs_c09b', 65 | 'cs_c09c', 'cs_c09d', 'cs_c09e', 'cs_c09f', 'cs_c0a0', 'cs_c0a1', 'cs_c0a2', 66 | 'cs_c0a3', 'cs_c0a4', 'cs_c0a5', 'cs_c0a6', 'cs_c0a7', 'cs_c0a8', 'cs_c0a9', 67 | 'cs_c0aa', 'cs_c0ab', 'cs_c0ac', 'cs_c0ad', 'cs_c0ae', 'cs_c0af', 'cs_c0b0', 68 | 'cs_c0b1', 'cs_c0b2', 'cs_c0b3', 'cs_c0b4', 'cs_c0b5', 'cs_c100', 'cs_c101', 69 | 'cs_c102', 'cs_c103', 'cs_c104', 'cs_c105', 'cs_c106', 'cs_cca8', 'cs_cca9', 70 | 'cs_ccaa', 'cs_ccab', 'cs_ccac', 'cs_ccad', 'cs_ccae', 'cs_d001', 'cs_d002', 71 | 'cs_d003', 'cs_d005', 'cs_unknown', 'sig_0201', 'sig_0203', 'sig_0401', 'sig_0403', 'sig_0420', 72 | 'sig_0501', 'sig_0503', 'sig_0520', 'sig_0601', 'sig_0603', 'sig_0620', 'sig_0704', 73 | 'sig_0705', 'sig_0706', 'sig_0707', 'sig_0708', 'sig_0709', 'sig_070A', 'sig_070B', 74 | 'sig_070C', 'sig_070D', 'sig_070E', 'sig_070F', 'sig_0804', 'sig_0805', 'sig_0806', 75 | 'sig_0807', 'sig_0808', 'sig_0809', 'sig_080a', 'sig_080b', 'sig_081a', 'sig_081b', 76 | 'sig_081c', 'sig_grease', 'sig_empty', 'grp_01', 'grp_02', 'grp_03', 'grp_04', 'grp_05', 77 | 'grp_06', 'grp_07', 'grp_08', 'grp_09', 'grp_10', 'grp_11', 'grp_12', 'grp_13', 'grp_14', 78 | 'grp_15', 'grp_16', 'grp_17', 'grp_18', 'grp_19', 'grp_20', 'grp_21', 'grp_22', 79 | 'grp_23', 'grp_24', 'grp_25', 'grp_26', 'grp_27', 'grp_28', 'grp_29', 'grp_30', 80 | 'grp_31', 'grp_32', 'grp_33', 'grp_34', 'grp_35', 'grp_36', 'grp_37', 'grp_38', 81 | 'grp_39', 'grp_40', 'grp_41', 'grp_256', 'grp_257', 'grp_258', 'grp_259', 'grp_260', 82 | 'grp_65281', 'grp_65282', 'grp_grease', 'pts_00', 'pts_01', 'pts_02', 'svr_ext_00', 'svr_ext_01', 83 | 'svr_ext_02','svr_ext_03', 'svr_ext_04', 'svr_ext_05', 'svr_ext_06', 'svr_ext_07', 'svr_ext_08', 84 | 'svr_ext_09', 'svr_ext_10', 'svr_ext_11', 'svr_ext_12', 'svr_ext_13', 'svr_ext_14', 85 | 'svr_ext_15', 'svr_ext_16', 'svr_ext_17', 'svr_ext_18', 'svr_ext_19', 'svr_ext_20', 86 | 'svr_ext_21', 'svr_ext_22', 'svr_ext_23', 'svr_ext_24', 'svr_ext_25', 'svr_ext_26', 87 | 'svr_ext_27', 'svr_ext_28', 'svr_ext_29', 'svr_ext_30', 'svr_ext_31', 'svr_ext_32', 88 | 'svr_ext_33', 'svr_ext_34', 'svr_ext_35', 'svr_ext_36', 'svr_ext_37', 'svr_ext_38', 89 | 'svr_ext_39', 'svr_ext_40', 'svr_ext_41', 'svr_ext_42', 'svr_ext_43', 'svr_ext_44', 90 | 'svr_ext_45', 'svr_ext_46', 'svr_ext_47', 'svr_ext_48', 'svr_ext_49', 'svr_ext_50', 91 | 'svr_ext_51', 'svr_ext_52', 'svr_ext_53', 'svr_ext_55', 'svr_ext_56', 'svr_ext_65281', 92 | 'svr_ext_unassigned', 'svr_ocsp_staple', 'svr_tls_ver', 'svr_supported_ver', 'malware_label'] 93 | 94 | # Create custom logging class for exceptions 95 | class OneLineExceptionFormatter(logging.Formatter): 96 | def formatException(self, exc_info): 97 | result = super().formatException(exc_info) 98 | return repr(result) 99 | 100 | def format(self, record): 101 | result = super().format(record) 102 | if record.exc_text: 103 | result = result.replace("\n", "") 104 | return result 105 | 106 | def write_csv_file(filename, data, header=False): 107 | ''' 108 | Write data to csv 109 | ''' 110 | if header: 111 | try: 112 | with open(filename, "w", newline='') as outfile: 113 | write_csv = csv.DictWriter(outfile, fieldnames=csv_header) 114 | write_csv.writeheader() 115 | except Exception as e: 116 | logging.exception("There was a problem in the CSV file write process... {}".format(e)) 117 | exit(1) 118 | else: 119 | try: 120 | with open(filename, "a", newline='') as outfile: 121 | write_csv = csv.DictWriter(outfile, fieldnames=csv_header) 122 | write_csv.writerow(data) 123 | except Exception as e: 124 | logging.exception("There was a problem in the CSV file write process... {}".format(e)) 125 | exit(1) 126 | 127 | def correlate_data(csv_filename, tls_server_list, malware_label, API_KEY, out_dir, tls_client_entry): 128 | ''' 129 | Reads in data from netcap TLS files and returns dictionary to insert into CSV file 130 | ''' 131 | test_train_data = {} 132 | global ip_domain_dict 133 | ip_domain_value = "" 134 | tls_osint_list = [] 135 | tranco_cache_dir = os.path.join(out_dir, '.tranco') 136 | 137 | # Pre-generate test_train_data_dict with 0 values 138 | for val in csv_header: 139 | test_train_data[val] = 0 140 | 141 | test_train_data['malware_label'] = malware_label 142 | 143 | for tls_server_data in tls_server_list: 144 | if tls_server_data['SrcIP'] == tls_client_entry['DstIP'] and tls_server_data['DstIP'] == tls_client_entry['SrcIP'] and tls_server_data['DstPort'] == tls_client_entry['SrcPort'] and tls_server_data['SrcPort'] == tls_client_entry['DstPort']: 145 | tls_server_entry = tls_server_data 146 | # Drop entries from list for search efficiency and to reduce invalid duplicates 147 | tls_server_list.remove(tls_server_entry) 148 | ip_domain_value = "{}:{}".format(tls_client_entry['DstIP'], tls_client_entry['SNI']) 149 | break 150 | 151 | # Check to see if key is in the ip_domain_dict (meaning it is an existing entry) 152 | # If it is, then skip check_ip, otherwise, we'll run it and add the values to the dict 153 | if ip_domain_value in ip_domain_dict.keys(): 154 | tls_osint_list.append(ip_domain_dict[ip_domain_value][0]) 155 | tls_osint_list.append(ip_domain_dict[ip_domain_value][1]) 156 | tls_osint_list.append(ip_domain_dict[ip_domain_value][2]) 157 | tls_osint_list.append(ip_domain_dict[ip_domain_value][3]) 158 | tls_osint_list.append(ip_domain_dict[ip_domain_value][4]) 159 | else: 160 | dst_ip = tls_client_entry['DstIP'] 161 | sni = tls_client_entry['SNI'] 162 | tls_osint_list.append(ip(API_KEY, dst_ip)) 163 | tls_osint_list.append(hostname(sni, dst_ip)) 164 | tls_osint_list.append(ja3_sslbl_check(tls_client_entry['Ja3'])) 165 | 166 | # Tranco and dgaintel fail when domain name is empty 167 | if not sni == '': 168 | tls_osint_list.append(dns_tranco_check(tranco_cache_dir, sni, 15)) 169 | tls_osint_list.append(get_prob(sni)) 170 | else: 171 | tls_osint_list.append(0) 172 | tls_osint_list.append(0) 173 | 174 | ip_domain_dict[ip_domain_value] = tls_osint_list 175 | 176 | # OSINT OTX and urlhaus analysis 177 | test_train_data['otx_status'] = tls_osint_list[0]['url_status'] 178 | test_train_data['otx_age'] = tls_osint_list[0]['report_age'] 179 | test_train_data['urlhaus_status'] = tls_osint_list[1]['url_status'] 180 | test_train_data['urlhaus_age'] = tls_osint_list[1]['report_age'] 181 | test_train_data['ja3_urlhaus_status'] = tls_osint_list[2]['ja3_check'] 182 | test_train_data['ja3_urlhaus_age'] = tls_osint_list[2]['ja3_record_age'] 183 | test_train_data['dom_in_tranco_1m'] = tls_osint_list[3] 184 | test_train_data['dom_dga_prob'] = tls_osint_list[4] 185 | 186 | # Set TLS Client static data fields in test_train_data dict 187 | test_train_data['tls_record_type'] = tls_client_entry['Type'] 188 | test_train_data['client_tls_ver'] = tls_client_entry['Version'] 189 | test_train_data['message_len'] = tls_client_entry['MessageLen'] 190 | test_train_data['handshake_type'] = tls_client_entry['HandshakeType'] 191 | test_train_data['handshake_version'] = tls_client_entry['HandshakeVersion'] 192 | test_train_data['handshake_len'] = tls_client_entry['HandshakeLen'] 193 | test_train_data['cs_len'] = tls_client_entry['CipherSuiteLen'] 194 | test_train_data['ext_len'] = tls_client_entry['ExtensionLen'] 195 | test_train_data['src_port'] = tls_client_entry['SrcPort'] 196 | test_train_data['dst_port'] = tls_client_entry['DstPort'] 197 | 198 | # Set TLS Server static data fields in test_train_data dict 199 | test_train_data['svr_tls_ver'] = tls_server_entry['Version'] 200 | test_train_data['svr_supported_ver'] = tls_server_entry['SupportedVersion'] 201 | if tls_server_entry['OCSPStapling'] == 'false': 202 | test_train_data['svr_ocsp_staple'] = 0 203 | else: 204 | test_train_data['svr_ocsp_staple'] = 1 205 | 206 | svr_selected_group = "{:02}".format(int(tls_server_entry['SelectedGroup'])) 207 | server_cs_used = "{:04x}".format(int(tls_server_entry['CipherSuite'])) 208 | 209 | try: 210 | # Cipher Suites 211 | tls_client_entry['CipherSuites'] = tls_client_entry['CipherSuites'][1:-1].split('-') 212 | for cs_val in tls_client_entry['CipherSuites']: 213 | entry_hex = "{:04x}".format(int(cs_val)) 214 | 215 | cs_entry = "cs_{}".format(entry_hex) 216 | 217 | if cs_entry in test_train_data: 218 | test_train_data[cs_entry] += 0.5 219 | else: 220 | test_train_data['cs_unknown'] += 0.5 221 | 222 | if entry_hex == server_cs_used: 223 | test_train_data[cs_entry] += 0.5 224 | 225 | # Signature Algorithms 226 | tls_client_entry['SignatureAlgs'] = tls_client_entry['SignatureAlgs'][1:-1].split('-') 227 | 228 | if not tls_client_entry['SignatureAlgs'][0]: 229 | tls_client_entry['SignatureAlgs'] = ['0'] 230 | 231 | sig_reserved_count = 1 232 | for sig_data in tls_client_entry['SignatureAlgs']: 233 | sig_entry = "sig_{:04x}".format(int(sig_data)) 234 | 235 | if sig_entry in test_train_data: 236 | test_train_data[sig_entry] = 0.5 237 | elif sig_entry == 'sig_0000': 238 | test_train_data['sig_empty'] = 0.5 239 | else: 240 | test_train_data['sig_grease'] = sig_reserved_count 241 | sig_reserved_count += 0.5 242 | 243 | # Supported Groups 244 | tls_client_entry['SupportedGroups'] = tls_client_entry['SupportedGroups'][1:-1].split('-') 245 | for grp_data in tls_client_entry['SupportedGroups']: 246 | grp_val = "{:02}".format(int(grp_data)) 247 | 248 | grp_entry = "grp_{}".format(grp_val) 249 | 250 | if grp_entry in test_train_data: 251 | test_train_data[grp_entry] = 0.5 252 | else: 253 | grp_entry = 'grp_grease' 254 | test_train_data[grp_entry] += 0.5 255 | 256 | if grp_val == svr_selected_group: 257 | test_train_data[grp_entry] += 0.5 258 | 259 | # Supported Points 260 | if tls_client_entry['SupportedPoints'][0] == '(': 261 | tls_client_entry['SupportedPoints'] = tls_client_entry['SupportedPoints'][1:-1].split('-') 262 | else: 263 | tls_client_entry['SupportedPoints'] = [tls_client_entry['SupportedPoints']] 264 | 265 | for pts_data in tls_client_entry['SupportedPoints']: 266 | pts_entry = "pts_{:02}".format(int(pts_data)) 267 | test_train_data[pts_entry] = 0.5 268 | 269 | # Server Extensions 270 | if tls_server_entry['Extensions'][0] == '(': 271 | tls_server_entry['Extensions'] = tls_server_entry['Extensions'][1:-1].split('-') 272 | elif not type(tls_server_entry['Extensions']) is list and not tls_server_entry['Extensions'][0] == '': 273 | tls_server_entry['Extensions'] = [tls_server_entry['Extensions'][1:]] 274 | elif tls_server_entry['Extensions'][0] == '': 275 | tls_server_entry['Extensions'] = ['0'] 276 | 277 | for svr_ext_data in tls_server_entry['Extensions']: 278 | svr_ext_entry = "svr_ext_{:02}".format(int(svr_ext_data)) 279 | 280 | if svr_ext_entry in test_train_data: 281 | test_train_data[svr_ext_entry] = 0.5 282 | else: 283 | test_train_data['svr_ext_unassigned'] += 0.5 284 | 285 | except Exception as e: 286 | print("The problem is with a loop... - {}".format(e)) 287 | 288 | write_csv_file(csv_filename, test_train_data) 289 | 290 | def main(): 291 | ''' 292 | Gather and format data from the TLSClientHello and TLSServerHello CSV files generated from NetCap 293 | ''' 294 | # Get a label value for known data 295 | parser = argparse.ArgumentParser(description='Get label input for data analysis') 296 | parser.add_argument('-l', '--label', action='store', dest='label', default=0, help='Is this data known malicious or not?', required=False) 297 | parser.add_argument('-o', '--outfile', action='store', dest='out_file', default='test_train_data.csv', 298 | help='Name of the output file', required=False) 299 | parser.add_argument('-c', '--client-file', action='store', dest='client_file', default='TLSClientHello.csv', 300 | help='Name of the TLS Client Hello (TLSClientHello.csv) file created with NetCap', required=False) 301 | parser.add_argument('-s', '--server-file', action='store', dest='server_file', default='TLSServerHello.csv', 302 | help='Name of the TLS Server Hello (TLSServerHello.csv) file created with NetCap', required=False) 303 | parser.add_argument('-a', '--api-key', action='store', dest='api', default='', 304 | help='API Key value required for Alienvault OTX', required=False) 305 | 306 | options = parser.parse_args() 307 | 308 | base_log_dir = os.getcwd() 309 | out_dir = r'C:\Users\bryan\Desktop' 310 | csv_filename = os.path.join(out_dir, options.out_file) 311 | tls_client_file = os.path.join(base_log_dir, options.client_file) 312 | tls_server_file = os.path.join(base_log_dir, options.server_file) 313 | tls_server_list = [] 314 | malicious_label = options.label 315 | #API_KEY = os.environ.get('API_KEY') 316 | API_KEY = options.api 317 | 318 | if not os.path.exists(csv_filename): 319 | write_csv_file(csv_filename, csv_header, True) 320 | 321 | with open(tls_server_file, 'r', newline='') as tls_server_data: 322 | tls_server_csv = csv.DictReader(tls_server_data) 323 | for line in tls_server_csv: 324 | tls_server_list.append(line) 325 | 326 | with ProcessPoolExecutor() as executor: 327 | fn = partial(correlate_data, csv_filename, tls_server_list, malicious_label, API_KEY, out_dir) 328 | with open(tls_client_file, 'r', newline='') as tls_client_data: 329 | tls_client_csv = csv.DictReader(tls_client_data) 330 | executor.map(fn, tls_client_csv, timeout=86400) 331 | 332 | if __name__ == '__main__': 333 | try: 334 | exit(main()) 335 | except Exception: 336 | logging.exception("Exception in main()") 337 | exit(1) -------------------------------------------------------------------------------- /format-data/ja3_fingerprints.csv: -------------------------------------------------------------------------------- 1 | ################################################################ 2 | # abuse.ch Suricata JA3 Fingerprint Blacklist (CSV) # 3 | # For Suricata 4.1.0 or newer # 4 | # Last updated: 2020-04-09 06:48:14 UTC # 5 | # # 6 | # Terms Of Use: https://sslbl.abuse.ch/blacklist/ # 7 | # For questions please contact sslbl [at] abuse.ch # 8 | ################################################################ 9 | # 10 | # ja3_md5,Firstseen,Lastseen,Listingreason 11 | b386946a5a44d1ddcc843bc75336dfce,2017-07-14 18:08:15,2019-07-27 20:42:54,Dridex 12 | 8991a387e4cc841740f25d6f5139f92d,2017-07-14 19:02:03,2019-07-28 00:34:38,Adware 13 | cb98a24ee4b9134448ffb5714fd870ac,2017-07-14 19:48:28,2019-05-22 03:22:38,Dridex 14 | 1aa7bf8b97e540ca5edd75f7b8384bfa,2017-07-14 20:23:38,2019-07-28 01:38:22,TrickBot 15 | 3d89c0dfb1fa44911b8fa7523ef8dedb,2017-07-15 04:23:45,2020-12-06 17:43:38,Adware 16 | bc6c386f480ee97b9d9e52d472b772d8,2017-07-15 10:57:38,2020-12-06 09:52:14,Adware 17 | 8f52d1ce303fb4a6515836aec3cc16b1,2017-07-15 19:05:11,2019-07-27 20:00:57,TrickBot 18 | d6f04b5a910115f4b50ecec09d40a1df,2017-07-15 19:42:24,2018-10-14 08:12:51,Dridex 19 | 35c0a31c481927f022a3b530255ac080,2017-07-15 19:43:19,2020-10-31 18:36:39,Tofsee 20 | d551fafc4f40f1dec2bb45980bfa9492,2017-07-15 19:59:29,2020-11-16 13:06:20,Adware 21 | e330bca99c8a5256ae126a55c4c725c5,2017-07-15 19:59:29,2020-11-01 17:49:10,Adware 22 | b8f81673c0e1d29908346f3bab892b9b,2017-07-16 01:32:03,2018-12-17 06:08:03,Adware 23 | 83e04bc58d402f9633983cbf22724b02,2017-07-16 01:32:03,2019-04-30 15:04:48,Adware 24 | 70722097d1fe1d78d8c2164640ab6df4,2017-07-16 02:39:08,2020-12-07 11:17:16,Tofsee 25 | 9c2589e1c0e9f533a022c6205f9719e1,2017-07-16 08:37:17,2020-12-01 17:48:11,Adware 26 | 849b04bdbd1d2b983f6e8a457e0632a8,2017-07-16 08:37:17,2020-12-01 17:48:11,Adware 27 | 16efcf0e00504ddfedde13bfea997952,2017-07-16 19:45:45,2020-08-21 18:01:27,Adware 28 | 4d7a28d6f2263ed61de88ca66eb011e3,2017-07-16 21:20:29,2020-12-07 09:31:52,Tofsee 29 | 550dce18de1bb143e69d6dd9413b8355,2017-07-16 22:17:20,2018-12-21 07:04:50,Adware 30 | c50f6a8b9173676b47ba6085bd0c6cee,2017-07-16 22:38:41,2019-05-21 09:42:17,TrickBot 31 | 20dd18bdd3209ea718989030a6f93364,2017-07-18 10:22:58,2019-04-28 09:23:31,Adware 32 | 8498fe4268764dbf926a38283e9d3d8f,2017-07-18 10:22:58,2019-04-28 09:23:31,Adware 33 | 590a232d04d56409fab72e752a8a2634,2017-07-18 18:53:24,2020-10-11 20:48:33,Tofsee 34 | 51a7ad14509fd614c7bb3a50c4982b8c,2017-07-19 07:28:19,2019-07-14 11:58:32,JBifrost 35 | 96eba628dcb2b47607192ba74a3b55ba,2017-07-19 18:53:48,2020-11-13 17:37:05,Tofsee 36 | df5c30e670dba99f9270ed36060cf054,2017-07-20 17:44:07,2018-04-11 15:57:59,Tofsee 37 | 098f55e27d8c4b0a590102cbdb3a5f3a,2017-07-21 09:52:01,2019-04-08 01:09:54,Adware 38 | 46efd49abcca8ea9baa932da68fdb529,2017-07-22 14:07:36,2020-12-06 21:06:38,Adware 39 | 29085f03f8e8a03f0b399c5c7cf0b0b8,2017-07-22 14:07:36,2020-12-07 03:30:34,Adware 40 | d7150af4514b868defb854db0f62a441,2017-07-23 09:39:24,2018-07-24 01:04:58,Tofsee 41 | 03e186a7f83285e93341de478334006e,2017-07-24 18:17:14,2020-10-31 18:36:38,Tofsee 42 | 3cda52da4ade09f1f781ad2e82dcfa20,2017-07-30 18:41:36,2019-05-21 17:34:18,Quakbot 43 | b13d01846ad7a14a70bf030a16775c78,2017-08-08 07:12:49,2020-12-06 21:22:44,Adware 44 | 1543a7c46633acf71e8401baccbd0568,2017-08-08 21:32:28,2020-11-10 05:30:17,Tofsee 45 | 1d095e68489d3c535297cd8dffb06cb9,2017-08-12 19:56:28,2020-10-28 11:06:23,Tofsee 46 | 93d056782d649deb51cda44ecb714bb0,2017-08-28 12:20:47,2019-04-15 23:47:27,Adware 47 | 698e36219f3979420fa2581b21dac7ec,2017-08-28 12:20:47,2019-04-28 09:23:31,Adware 48 | 1712287800ac91b34cadd5884ce85568,2017-08-28 16:01:59,2020-12-04 20:11:58,TorrentLocker 49 | 5e573c9c9f8ba720ef9b18e9fce2e2f7,2017-08-30 13:44:56,2020-12-05 20:27:10,Adware 50 | f6fd83a21f9f3c5f9ff7b5c63bbc179d,2017-10-20 08:03:21,2018-11-06 06:42:12,Adware 51 | 92579701f145605e9edc0b01a901c6d5,2017-10-23 00:10:48,2020-12-06 01:11:23,Adware 52 | a61299f9b501adcf680b9275d79d4ac6,2017-11-04 18:03:59,2020-04-21 17:08:24,Tofsee 53 | b2b61db7b9490a60d270ccb20b462826,2017-11-14 20:12:03,2020-12-06 01:08:46,Adware 54 | 7dcce5b76c8b17472d024758970a406b,2017-11-22 12:42:46,2020-10-24 19:47:51,Tofsee 55 | 534ce2dbc413c68e908363b5df0ae5e0,2017-12-22 09:36:21,2019-07-27 15:22:33,TrickBot 56 | fb00055a1196aeea8d1bc609885ba953,2018-01-01 22:49:25,2019-04-09 06:58:58,TrickBot 57 | a50a861119aceb0ccc74902e8fddb618,2018-01-02 08:16:23,2018-07-05 02:33:08,Tofsee 58 | e7643725fcff971e3051fe0e47fc2c71,2018-01-31 08:06:13,2020-03-25 16:19:48,Tofsee 59 | 7c410ce832e848a3321432c9a82e972b,2018-01-31 20:04:25,2020-12-07 11:17:17,Tofsee 60 | da949afd9bd6df820730f8f171584a71,2018-02-03 05:19:37,2020-12-06 09:52:14,Tofsee 61 | 906004246f3ba5e755b043c057254a29,2018-03-11 08:25:38,2018-04-14 00:59:16,Tofsee 62 | fd80fa9c6120cdeea8520510f3c644ac,2018-03-11 09:34:30,2020-12-07 11:09:14,Tofsee 63 | b90bdbe961a648f0427db21aaa6ccb59,2018-03-11 10:37:43,2020-05-29 23:39:01,Tofsee 64 | 1fe4c7a3544eb27afec2adfb3a3dbf60,2018-03-11 19:23:08,2020-12-07 11:17:17,Tofsee 65 | c201b92f8b483fa388be174d6689f534,2018-03-12 13:43:52,2020-08-17 16:56:42,Gozi 66 | 9f62c4f26b90d3d757bea609e82f2eaf,2018-03-13 06:23:41,2020-11-15 11:42:42,Tofsee 67 | 1be3ecebe5aa9d3654e6e703d81f6928,2018-03-13 11:50:02,2020-11-29 16:18:00,Ransomware.Troldesh 68 | e3b2ab1f9a56f2fb4c9248f2f41631fa,2018-03-15 01:06:34,2020-12-07 11:17:17,Tofsee 69 | dff8a0aa1c904aaea76c5bf624e88333,2018-03-18 09:41:15,2020-10-27 09:50:24,Tofsee 70 | 17fd49722f8d11f3d76dce84f8e099a7,2018-03-19 23:02:27,2020-12-06 15:29:30,Tofsee 71 | 911479ac8a0813ed1241b3686ccdade9,2018-03-19 23:24:59,2020-03-30 04:09:18,Tofsee 72 | c5deb9465d47232dd48772f9c4d14679,2018-03-22 15:42:48,2020-11-26 18:49:34,Tofsee 73 | f22bdd57e3a52de86cda40da2d84e83b,2018-03-27 13:40:19,2019-01-20 14:31:39,Tofsee 74 | d18a4da84af59e1108862a39bae7c9d4,2018-04-03 00:40:51,2020-11-11 00:58:38,Tofsee 75 | 2d8794cb7b52b777bee2695e79c15760,2018-04-04 06:56:37,2020-12-06 20:44:32,Ransomware 76 | 40adfd923eb82b89d8836ba37a19bca1,2018-04-15 15:49:08,2020-12-07 00:23:55,CoinMiner 77 | 1aee0238942d453d679fc1e37a303387,2018-05-13 01:59:49,2020-12-04 09:02:41,Tofsee 78 | 2092e1fffb45d7e4a19a57f9bc5e203a,2018-05-16 21:59:36,2018-09-05 01:58:33,Adware 79 | bffa4501966196d3d6e90cee1f88fc89,2018-06-07 15:08:04,2020-03-16 00:03:44,Tofsee 80 | 807fca46d9d0cf63adf4e5e80e414bbe,2018-06-07 16:51:03,2020-12-06 19:46:37,Tofsee 81 | fb58831f892190644fe44e25bc830b45,2018-06-08 12:07:59,2019-05-31 21:02:37,Adware 82 | 0cc1e84568e471aa1d62ad4158ade6b5,2018-06-24 10:50:47,2020-11-24 14:41:00,Tofsee 83 | d2935c58fe676744fecc8614ee5356c7,2018-08-14 21:48:41,2020-12-07 09:31:53,Adwind 84 | 8916410db85077a5460817142dcbc8de,2018-08-21 12:32:28,2020-12-07 03:30:34,TrickBot 85 | c5235d3a8b9934b7fbbd204d50bc058d,2018-08-23 17:36:08,2019-10-13 05:11:09,Gootkit 86 | 57f3642b4e37e28f5cbe3020c9331b4c,2018-08-28 15:54:53,2020-12-07 04:22:05,Gozi 87 | e62a5f4d538cbf169c2af71bec2399b4,2018-08-30 15:45:40,2020-12-06 21:59:37,TrickBot 88 | 51c64c77e60f3980eea90869b68c58a8,2018-08-30 21:04:57,2020-12-07 05:41:18,Dridex 89 | 7691297bcb20a41233fd0a0baa0a3628,2018-09-17 02:50:05,2020-12-07 09:00:41,Adware 90 | 7dd50e112cd23734a310b90f6f44a7cd,2018-09-17 17:54:58,2020-12-06 23:16:28,Quakbot 91 | 52c7396a501e4fecbdfa99c5408334ac,2018-09-18 00:29:04,2019-12-03 17:24:02,Tofsee 92 | f735bbc6b69723b9df7b0e7ef27872af,2018-10-02 18:04:16,2020-12-06 01:47:38,TrickBot 93 | 49ed2ef3f1321e5f044f1e71b0e6fdd5,2018-10-02 18:04:17,2020-12-06 01:47:38,TrickBot 94 | d76ee64fb7273733cbe455ac81c292e6,2018-11-16 13:26:39,2018-11-18 19:19:36,Tofsee 95 | 8f6c918dcb585ebbea05e2cc94530e3d,2018-11-16 13:26:41,2020-05-06 15:45:21,Tofsee 96 | 34f14a69ad7009ca5863379218af17f3,2018-11-17 05:17:22,2018-12-29 01:46:46,Tofsee 97 | c2b4710c6888a5d47befe865c8e6fb19,2018-11-29 20:46:04,2020-12-06 20:41:48,Tofsee 98 | decfb48a53789ebe081b88aabb58ee34,2018-12-21 09:06:16,2020-10-08 10:41:00,Adwind 99 | 08a8a4e85b25ac42e1490bc85cfdb5ce,2019-01-30 02:48:34,2020-10-27 09:50:19,Tofsee 100 | c0220cd64849a629397a9cb68f78a0ea,2019-03-24 00:12:32,2020-12-07 11:17:17,Tofsee 101 | 7a29c223fb122ec64d10f0a159e07996,2019-06-09 22:55:29,2020-10-27 09:50:26,Tofsee 102 | 44dab16d680ef93487bc16ad23b3ffb1,2019-06-09 22:55:29,2020-10-27 09:50:25,Tofsee 103 | 70a04365be5bbd4653698bebeb43ce68,2019-07-02 06:26:56,2020-05-30 04:19:00,Tofsee 104 | d81d654effb94714a4086734fa0adad9,2019-07-16 23:29:02,2020-10-27 09:50:21,Tofsee 105 | 25d74b7b4b779eb1efd4b31d26d651c6,2019-08-03 20:15:33,2020-07-14 21:43:25,Tofsee 106 | fc2299d5b2964cd242c5a2c8c531a5f0,2019-08-09 23:56:32,2020-12-07 11:17:17,Tofsee 107 | 32926ca3e59f0413d0b98725454594f5,2019-09-12 06:56:10,2020-10-27 21:49:31,Tofsee 108 | ffefafdb86336d057eda5fdf02b3d5ce,2019-10-26 07:31:49,2020-07-25 00:14:09,Tofsee 109 | # END (98) entries -------------------------------------------------------------------------------- /format-data/requirements.txt: -------------------------------------------------------------------------------- 1 | tranco==0.5 2 | dgaintel==2.3 3 | OTXv2==1.5.10 -------------------------------------------------------------------------------- /graph/SAVE MODEL GRAPHS HERE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/graph/SAVE MODEL GRAPHS HERE -------------------------------------------------------------------------------- /models/ADD TRAINED MODEL HERE: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/ADD TRAINED MODEL HERE -------------------------------------------------------------------------------- /models/ae.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/ae.h5 -------------------------------------------------------------------------------- /models/oc-svm.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/oc-svm.pkl -------------------------------------------------------------------------------- /models/svm.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/svm.pkl -------------------------------------------------------------------------------- /models/win-pkl-ver/oc-svm.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/win-pkl-ver/oc-svm.pkl -------------------------------------------------------------------------------- /models/win-pkl-ver/svm.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/models/win-pkl-ver/svm.pkl -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | sklearn 2 | numpy==1.18.5 3 | pandas==0.25.3 4 | tensorflow==2.3.2 5 | seaborn 6 | matplotlib 7 | mlxtend -------------------------------------------------------------------------------- /test-train-data/test_train_data.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/1computerguy/tls-mal-detect/d93b287529bbc53871b5c9e6623af1301b7dc920/test-train-data/test_train_data.7z --------------------------------------------------------------------------------