├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ ├── critical_report.md │ ├── enhancement_request.md │ └── question.md └── PULL_REQUEST_TEMPLATE.MD ├── .gitignore ├── LICENSE ├── README.md ├── dbx_mysql.pl ├── dbx_postgres.pl ├── docs ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── SECURITY.md ├── SUPPORT.md └── VERSIONING.md ├── lib └── OAuth.pm ├── report-parser.conf.pub └── report-parser.pl /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Something isn't working 4 | title: "[Bug]: " 5 | labels: bug 6 | assignees: userjack6880 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Software Version** 27 | [] Version 0 Alpha 5 28 | [] Version 0 Alpha 4 29 | [] Version 0 Alpha 3 30 | [] Version 0 Alpha 2 31 | 32 | **Server (please complete the following information):** 33 | - Server OS [e.g. CentOS 7.3] 34 | - Perl Version [e.g. 5.32] 35 | - SQL Variant and Version [e.g. MariaDB 10.2] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/critical_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Critical Bug Report 3 | about: Something is critically broken 4 | title: "[Critical Bug]: " 5 | labels: critical, bug 6 | assignees: userjack6880 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Software Version** 27 | [] Version 0 Alpha 5 28 | [] Version 0 Alpha 4 29 | [] Version 0 Alpha 3 30 | [] Version 0 Alpha 2 31 | [] Other 32 | 33 | **Server (please complete the following information):** 34 | - Server OS [e.g. CentOS 7.3] 35 | - Perl Version [e.g. 5.32] 36 | - SQL Variant and Version [e.g. MariaDB 10.2] 37 | 38 | **Additional context** 39 | Add any other context about the problem here. -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/enhancement_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Enhancement Request 3 | about: New feature or request 4 | title: "[Request]: " 5 | labels: enhancement 6 | assignees: userjack6880 7 | 8 | --- 9 | 10 | **Describe the enhancement request** 11 | A clear and concise description of what you want us to consider. 12 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Further information is requested 4 | title: "[Question]: " 5 | labels: question, help wanted 6 | assignees: userjack6880 7 | 8 | --- 9 | 10 | **Posit your question!** 11 | What do you need help with? 12 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.MD: -------------------------------------------------------------------------------- 1 | # Pull Request Template 2 | 3 | ## Description 4 | 5 | Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. 6 | 7 | Fixes # (issue) 8 | 9 | ## Type of change 10 | 11 | Please delete options that are not relevant. 12 | 13 | - [ ] Bug fix (non-breaking change which fixes an issue) 14 | - [ ] New feature (non-breaking change which adds functionality) 15 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 16 | - [ ] This change requires a documentation update 17 | 18 | ## How Has This Been Tested? 19 | 20 | Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration 21 | 22 | **Test Configuration**: 23 | * OS: 24 | * OS Kernel Version: 25 | * Perl Version: 26 | * SQL Variant: 27 | * SQL Version: 28 | 29 | ## Checklist: 30 | 31 | - [ ] My code follows the style guidelines of this project 32 | - [ ] I have performed a self-review of my own code 33 | - [ ] I have commented my code, particularly in hard-to-understand areas 34 | - [ ] I have made corresponding changes to the documentation 35 | - [ ] My changes generate no new warnings 36 | - [ ] I have added tests that prove my fix is effective or that my feature works 37 | - [ ] New and existing unit tests pass locally with my changes 38 | - [ ] Any dependent changes have been merged and published in downstream modules 39 | - [ ] I have checked my code and corrected any misspellings -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /report-parser.conf 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Open Report Parser 2 | 3 | A Perl based tool to parse DMARC reports, based on John Levine's [rddmarc](http://www.taugh.com/rddmarc/), but extended by the following features: 4 | - Allow to read messages from an IMAP server and not only from the local filesystem. 5 | - Store much more XML values into the database (for example the missing SPF and DKIM results from the policy_evaluated section) and also the entire XML for later reference. 6 | - Needed database tables and columns are created automatically, user only needs to provide a database. The database schema is compatible to the one used by rddmarc, but extends it by additional fields. Users can switch from rddmarc to dmarcts-report-parser without having to do any changes to the database by themselves. 7 | - Support for MySQL and PostgreSQL 8 | 9 | Open Report Parser is a fork of [techsneeze's dmarcts-report-parser](https://github.com/techsneeze/dmarcts-report-parser), and was forked to more closely match the needs of [Open DMARC Analyzer](https://github.com/userjack6880/Open-DMARC-Analyzer). 10 | 11 | Open Report Parser Version 0 Alpha 5 (0-α5) is an [Anomaly \](https://systemanomaly.com/codebase) project by John Bradley (john@systemanomaly.com). 12 | 13 | # Minimum Requirements 14 | 15 | - Perl 5 16 | - MariaDB 10.5 or equivalent 17 | - PostgreSQL 13.9 18 | 19 | # Dependencies 20 | 21 | ## on Debian 22 | 23 | ``` 24 | apt-get install libfile-mimeinfo-perl libmail-imapclient-perl libmime-tools-perl libxml-simple-perl \ 25 | libio-socket-inet6-perl libio-socket-ip-perl libperlio-gzip-perl \ 26 | libmail-mbox-messageparser-perl libwww-perl unzip 27 | ``` 28 | 29 | - For MySQL: `libdbd-mysql-perl` 30 | - For PostgreSQL: `libdbd-pg-perl` 31 | - For Oauth2: `liblwp-protocol-https-perl libencode-perl libtime-piece-mysql-perl` 32 | 33 | ## on Fedora (Fedora 23) 34 | 35 | ``` 36 | sudo dnf install perl-File-MimeInfo perl-Mail-IMAPClient perl-MIME-tools perl-XML-Simple perl-DBI \ 37 | perl-Socket6 perl-PerlIO-gzip perl-libwww-perl unzip 38 | ``` 39 | 40 | - For MySQL: `perl-DBD-MySQL` 41 | - For PostgreSQL: `perl-DBD-Pg` 42 | - For Oauth2: `perl-LWP-Protocol-https perl-Encode perl-Time-Piece-MySQL` 43 | 44 | ## on CentOS (CentOS 7) 45 | 46 | ``` 47 | yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm 48 | yum install perl-File-MimeInfo perl-Mail-IMAPClient perl-MIME-tools perl-XML-Simple perl-DBI \ 49 | perl-Socket6 perl-PerlIO-gzip perl-libwww-perl unzip perl-Mail-Mbox-MessageParser 50 | ``` 51 | 52 | - For MySQL: `perl-DBD-MySQL` 53 | - For PostgreSQL: `perl-DBD-Pg` 54 | - For Oauth2: `perl-LWP-Protocol-https perl-Encode perl-Time-Piece-MySQL` 55 | 56 | ## on FreeBSD (FreeBSD 11.4) 57 | 58 | ``` 59 | sudo pkg install p5-File-MimeInfo p5-Mail-IMAPClient p5-MIME-tools p5-XML-Simple p5-DBI p5-Socket6 p5-PerlIO-gzip p5-Mail-Mbox-MessageParser p5-libwww unzip 60 | ``` 61 | 62 | - For MySQL: `p5-DBD-MySQL` 63 | - For PostgreSQL: `p5-DBD-Pg` 64 | - For Oauth2: `p5-LWP-Protocol-https p5-Encode p5-Time-Piece-MySQL` 65 | 66 | ## on macOS (macOS 10.13) 67 | 68 | ``` 69 | brew install mysql shared-mime-info 70 | update-mime-database /usr/local/share/mime 71 | perl -MCPAN -e 'install Mail::IMAPClient' 72 | perl -MCPAN -e 'install Mail::Mbox::MessageParser' 73 | perl -MCPAN -e 'install File::MimeInfo' 74 | perl -MCPAN -e 'install LWP::UserAgent 75 | ``` 76 | 77 | - For MySQL: `perl -MCPAN -e 'install DBD::mysql'` 78 | - For PostgreSQL: `perl -MCPAN -e 'install DBD::pg'` 79 | - For Oauth2: 80 | ``` 81 | perl -MCPAN -e 'install LWP::Protocol::https' 82 | perl -MCPAN -e 'install Encode' 83 | perl -MCPAN -e 'install Time::Piece' 84 | ``` 85 | 86 | # Setting up Open Report Parser 87 | 88 | Optaining Open Report Parser through `git` is probably the easiest way, in addition to doing occasional pulls to get up-to-date versions. 89 | 90 | ``` 91 | git clone https://github.com/userjack6880/Open-Report-Parser.git 92 | ``` 93 | 94 | Optionally, a [zip file of the latest release](https://github.com/userjack6880/Open-Report-Parser/releases) can be downloaded. 95 | 96 | Rename `repoart-parser.conf.pub` to `report-parser.conf` and edit the configuration for your environment (see the next section on **Configuration Options** for details). Finally, some condierations need to be taken in account due to limitations in stock configurations of MySQL/MariaSQL on some distros, it may be necessary to add the following to your configuration (i.e. in /etc/mysql/mariadb.conf.d/50-server.cnf): 97 | 98 | ``` 99 | innodb_large_prefix = on 100 | innodb_file_format = barracuda 101 | innodb_file_per_table = true 102 | ``` 103 | 104 | # Configuration Options 105 | 106 | **Script Options** 107 | 108 | ```perl 109 | $debug = 0; 110 | $delete_reports = 0; 111 | #$dmarc_only = 0; 112 | # if set to 1, do not process tls reports, if set to -1 do not process 113 | # dmarc reports - defaults to 1 for legacy support 114 | # this is ignored for all methods except IMAP, use --tls to process 115 | # TLS reports for other methods 116 | ``` 117 | 118 | **Database Options** 119 | 120 | ```perl 121 | #$dbtype = 'mysql'; # Supported types - mysql, postgres - defaults to mysql if unset 122 | $dbname = 'dmarc'; 123 | $dbuser = 'dmarc'; 124 | $dbpass = 'password'; 125 | #$dbhost = 'dbhost'; # Set the hostname if we can't connect to the local socket. 126 | $dbport = '3306'; 127 | ``` 128 | 129 | **IMAP Options** 130 | 131 | ```perl 132 | $imapserver = 'imap.server'; 133 | $imapuser = 'username'; 134 | $imappass = 'password'; 135 | $imapport = '143'; 136 | $imapssl = '0'; # If set to 1, remember to change server port to 993 and disable imaptls. 137 | $imaptls = '0'; 138 | $tlsverify = '0'; 139 | $imapignoreerror = '0'; # recommended if you use MS Exchange 2007, ... 140 | #$imapauth = 'simple'; # supported - simple, oauth2 - defaults to simple if unset 141 | 142 | # see documentation for detailed setup 143 | #$oauthclientid = ''; 144 | #$oauthuri = ''; 145 | 146 | $imapdmarcfolder = 'dmarc'; 147 | $imaptlsfolder = 'tls'; 148 | 149 | # If $imapxxxproc is set, processed IMAP messages will be moved (overruled by 150 | # the --delete option!) 151 | # $imapdmarcproc = 'dmarc.Processed'; 152 | # $imaptlsproc = 'tls.Processed'; 153 | 154 | # If $imapxxxerr is set, IMAP messages that fail will be moved. If unset, failed messages 155 | # will move to $imapdmarcproc (if it is set). Overruled by the --delete option! 156 | # $imapdmarcerr = 'dmarc.notProcessed'; 157 | # $imaptlserr = 'tls.notProcessed'; 158 | ``` 159 | 160 | These settings are ignored when using the -m flag. When using SSL, TLS needs to be disabled and the port used should be changed to 993. TLS Verify is ignored. 161 | 162 | Setting `$imapauth` to 'oauth2' enables OAuth2 authentication, and requires an initial dance to verify the application with your provider. Once this is done, it should be able to renew the token automatically on subsequent runs. Currently, only OAuth2 with M365 has been tested. 163 | 164 | **XML Storage Options** 165 | 166 | ```perl 167 | # maximum size of XML/JSON files to store in database, long files can cause transaction aborts 168 | $maxsize_xml = 50000; 169 | $maxsize_json = 50000; 170 | 171 | # store XML/JSON as base64 encopded gzip in database (save space, harder usable) 172 | $compress_xml = 0; 173 | $compress_json = 0; 174 | ``` 175 | 176 | **Processing Failure Action** 177 | 178 | ```perl 179 | # if there was an error during file processing (message does not contain XML or ZIP parts, 180 | # or a database error) the parser reports an error and does not delete the file, even if 181 | # delete_reports is set (or --delete is given). Deletion can be enforced by delete_failed, 182 | # however not for database errors. 183 | $delete_failed = 0; 184 | ``` 185 | 186 | The script is looking for `report-parser.conf` in the current working directory. If not found it will look by the calling path. If neither is found than it will abort. 187 | 188 | Note: Be sure to use the proper hierarchy separator for your server in all folder specs, and if your IMAP server flattens the hierarchy (i.e. Cyrus IMAP with "altnamespace: yes") then leave "Inbox" off of the beginning of such specs. 189 | 190 | # Usage 191 | 192 | ``` 193 | ./report-parser.pl [OPTIONS] [PATH] 194 | ``` 195 | 196 | PATH can be the filename of a single file or a list of files - wildcard expression are allowed. 197 | 198 | **Remember**: This script needs a configurations file called in the current working directory, which defines a database server with credentials and (if used) an IMAP server with credentials. 199 | 200 | One of the following source options must be provided: 201 | 202 | ``` 203 | -i : Read reports from messages on IMAP server as defined in the 204 | config file. 205 | -m : Read reports from mbox file(s) provided in PATH. 206 | -e : Read reports from MIME email file(s) provided in PATH. 207 | -x : Read reports from xml file(s) provided in PATH. 208 | -j : Read reports from json files(s) provided in PATH. 209 | -z : Read reports from zip file(s) provided in PATH. 210 | ``` 211 | 212 | The following options are always allowed: 213 | 214 | ``` 215 | -d : Print debug info. 216 | -r : Replace existing reports rather than skipping them. 217 | --delete : Delete processed message files (the XML is stored in the 218 | database for later reference). 219 | --info : Print out number of XML files or emails processed. 220 | --tls : Force TLS-Only Mode. 221 | ``` 222 | 223 | Currently, processing of both DMARC and TLS reports during the same run is only supported from IMAP. All other sources will *always* default to DMARC reports unless the `--tls` flag is provided at runtime. 224 | 225 | # Latest Changes 226 | 227 | ## 0-α5 228 | - Fixed an issue with undefined variables discovered with Issue #12. 229 | - Fixed an issue with mimecast improperly setting mime type outlined in Issue #12. 230 | 231 | # Tested System Configurations 232 | | OS | Perl | SQL | Source | 233 | | ----------- | --------- | --------------- | ------------------------------- | 234 | | Debian 11.6 | Perl 5.32 | MariaDB 10.5.18 | Postfix/Dovecot IMAP Basic Auth | 235 | | Debian 11.6 | Perl 5.32 | PostgreSQL 13.9 | Postfix/Dovecot IMAP Basic Auth | 236 | 237 | # Release Cycle and Versioning 238 | 239 | This project regular release cycle is not yet determined. Versioning is under the Anomaly Versioning Scheme (2022), as outlined in `VERSIONING` under `docs`. 240 | 241 | # Support 242 | 243 | Support will be provided as outlined in the following schedule. For more details, see `SUPPORT`. 244 | 245 | | Version | Support Level | Released | End of Support | End of Life | 246 | | ----------------------------------- | ---------------- | ---------------- | ---------------- | ---------------- | 247 | | Version 1 Alpha 5 | Full Support | 10 July 2023 | TBD | TBD | 248 | | Version 1 Alpha 4 | Critical Support | 8 June 2023 | 10 July 2023 | TBD | 249 | | Version 1 Alpha 3 | End of Life | 25 May 2023 | 8 June 2023 | 10 July 2023 | 250 | 251 | # Contributing 252 | 253 | Public contributions are encouraged. Please review `CONTRIBUTING` under `docs` for contributing procedures. Additionally, please take a look at our `CODE_OF_CONDUCT`. By participating in this project you agree to abide by the Code of Conduct. 254 | 255 | # Contributors 256 | 257 | Primary Contributors 258 | - John Bieling - Initial Work 259 | - TechZneeze.com - Expansion of Initial Work 260 | - John Bradley - This Fork 261 | 262 | Thanks to [all who contributed](https://github.com/userjack6880/Open-Report-Parser/graphs/contributors) ([and here](https://github.com/techsneeze/dmarcts-report-parser/graphs/contributors)) and [have given feedback](https://github.com/userjack6880/Open-Report-Parser/issues?q=is%3Aissue). 263 | 264 | # Licenses and Copyrights 265 | 266 | Copyright © 2023 John Bradley (userjack6880), Copyright © 2016 TechSneeze.com, Copyright © 2012 John Bieling. Open Report Parser is released under GNU GPLv3. See `LICENSE`. -------------------------------------------------------------------------------- /dbx_mysql.pl: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # 3 | # Open Report Parser - Open Source report parser 4 | # Copyright (C) 2023 John Bradley (userjack6880) 5 | # Copyright (C) 2016 TechSneeze.com 6 | # Copyright (C) 2012 John Bieling 7 | # 8 | # dbx_mysql.pl 9 | # mysql db module 10 | # 11 | # Available at: https://github.com/userjack6880/Open-Report-Parser 12 | # 13 | # ----------------------------------------------------------------------------- 14 | # 15 | # This file is part of Open Report Parser. 16 | # 17 | # Open Report Parser is free software: you can redistribute it and/or modify it under 18 | # the terms of the GNU General Public License as published by the Free Software 19 | # Foundation, either version 3 of the License, or (at your option) any later 20 | # version. 21 | # 22 | # This program is distributed in the hope that it will be useful, but WITHOUT ANY 23 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | # PARTICULAR PURPOSE. See the GNU General Public License for more details. 25 | # 26 | # You should have received a copy of the GNU General Public License along with 27 | # this program. If not, see . 28 | # 29 | # ----------------------------------------------------------------------------- 30 | 31 | %dbx = ( 32 | epoch_to_timestamp_fn => 'FROM_UNIXTIME', 33 | 34 | to_hex_string => sub { 35 | my ($bin) = @_; 36 | return "X'" . unpack("H*", $bin) . "'"; 37 | }, 38 | 39 | column_info_type_col => 'mysql_type_name', 40 | 41 | tables => { 42 | "report" => { 43 | column_definitions => [ 44 | "serial" , "int" , "unsigned NOT NULL AUTO_INCREMENT", 45 | "mindate" , "timestamp" , "NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", 46 | "maxdate" , "timestamp" , "NULL", 47 | "domain" , "varchar(255)" , "NOT NULL", 48 | "org" , "varchar(255)" , "NOT NULL", 49 | "reportid" , "varchar(255)" , "NOT NULL", 50 | "email" , "varchar(255)" , "NULL", 51 | "extra_contact_info" , "varchar(255)" , "NULL", 52 | "policy_adkim" , "varchar(20)" , "NULL", 53 | "policy_aspf" , "varchar(20)" , "NULL", 54 | "policy_p" , "varchar(20)" , "NULL", 55 | "policy_sp" , "varchar(20)" , "NULL", 56 | "policy_pct" , "tinyint" , "unsigned", 57 | "raw_xml" , "mediumtext" , "", 58 | ], 59 | additional_definitions => "PRIMARY KEY (serial), UNIQUE KEY domain (domain, reportid)", 60 | table_options => "ROW_FORMAT=COMPRESSED", 61 | indexes => [], 62 | }, 63 | "rptrecord" => { 64 | column_definitions => [ 65 | "id" , "int" , "unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY", 66 | "serial" , "int" , "unsigned NOT NULL", 67 | "ip" , "int" , "unsigned", 68 | "ip6" , "binary(16)" , "", 69 | "rcount" , "int" , "unsigned NOT NULL", 70 | "disposition" , "enum('" . join("','", ALLOWED_DISPOSITION) . "')" , "", 71 | "reason" , "varchar(255)" , "", 72 | "dkimdomain" , "varchar(255)" , "", 73 | "dkimresult" , "enum('" . join("','", ALLOWED_DKIMRESULT) . "')" , "", 74 | "spfdomain" , "varchar(255)" , "", 75 | "spfresult" , "enum('" . join("','", ALLOWED_SPFRESULT) . "')" , "", 76 | "spf_align" , "enum('" . join("','", ALLOWED_SPF_ALIGN) . "')" , "NOT NULL", 77 | "dkim_align" , "enum('" . join("','", ALLOWED_DKIM_ALIGN) . "')" , "NOT NULL", 78 | "identifier_hfrom" , "varchar(255)" , "" 79 | ], 80 | additional_definitions => "KEY serial (serial, ip), KEY serial6 (serial, ip6)", 81 | table_options => "", 82 | indexes => [], 83 | }, 84 | "tls" => { 85 | column_definitions => [ 86 | "serial" , "int" , "unsigned NOT NULL AUTO_INCREMENT", 87 | "mindate" , "timestamp" , "NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", 88 | "maxdate" , "timestamp" , "NULL", 89 | "domain" , "varchar(255)" , "NOT NULL", 90 | "org" , "varchar(255)" , "NOT NULL", 91 | "reportid" , "varchar(255)" , "NOT NULL", 92 | "email" , "varchar(255)" , "NULL", 93 | "policy_mode" , "varchar(20)" , "NULL", 94 | "summary_success" , "int" , "NULL", 95 | "summary_failure" , "int" , "NULL", 96 | "raw_json" , "mediumtext" , "", 97 | ], 98 | additional_definitions => "PRIMARY KEY (serial), UNIQUE KEY domain(domain, reportid)", 99 | table_options => "ROW_FORMAT=COMPRESSED", 100 | indexes => [], 101 | }, 102 | "tlsrecord" => { 103 | column_definitions => [ 104 | "id" , "int" , "unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY", 105 | "serial" , "int" , "unsigned NOT NULL", 106 | "send_ip" , "int" , "unsigned", 107 | "send_ip6" , "binary(16)" , "", 108 | "recv_ip" , "int" , "unsigned", 109 | "recv_ip6" , "binary(16)" , "", 110 | "recv_mx" , "varchar(255)" , "", 111 | "type" , "varchar(255)" , "", 112 | "count" , "int" , "unsigned NOT NULL", 113 | ], 114 | additional_definitions => "KEY serial (serial, send_ip), KEY serial6 (serial, send_ip6)", 115 | table_options => "", 116 | indexes => [], 117 | }, 118 | "oauth" => { 119 | column_definitions => [ 120 | "id" , "int" , "unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY", 121 | "access_token" , "varchar(4096)" , "", 122 | "refresh_token" , "varchar(1024)" , "", 123 | "expire" , "timestamp" , "NOT NULL", 124 | "valid" , "int" , "unsigned NOT NULL", 125 | ], 126 | additional_definitions => "", 127 | table_options => "", 128 | indexes => [], 129 | } 130 | }, 131 | 132 | add_column => sub { 133 | my ($table, $col_name, $col_type, $col_opts, $after_col) = @_; 134 | 135 | my $insert_pos = "FIRST"; 136 | if ($after_col) { 137 | $insert_pos = "AFTER $after_col"; 138 | } 139 | return "ALTER TABLE $table ADD $col_name $col_type $col_opts $insert_pos;" 140 | }, 141 | 142 | modify_column => sub { 143 | my ($table, $col_name, $col_type, $col_opts) = @_; 144 | return "ALTER TABLE $table MODIFY COLUMN $col_name $col_type $col_opts;" 145 | }, 146 | ); 147 | 148 | 1; 149 | -------------------------------------------------------------------------------- /dbx_postgres.pl: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # 3 | # Open Report Parser - Open Source DMARC report parser 4 | # Copyright (C) 2023 John Bradley (userjack6880) 5 | # Copyright (C) 2016 TechSneeze.com 6 | # Copyright (C) 2012 John Bieling 7 | # 8 | # dbx_postgres.pl 9 | # postgres db module 10 | # 11 | # Available at: https://github.com/userjack6880/Open-Report-Parser 12 | # 13 | # ----------------------------------------------------------------------------- 14 | # 15 | # This file is part of Open Report Parser. 16 | # 17 | # Open Report Parser is free software: you can redistribute it and/or modify it under 18 | # the terms of the GNU General Public License as published by the Free Software 19 | # Foundation, either version 3 of the License, or (at your option) any later 20 | # version. 21 | # 22 | # This program is distributed in the hope that it will be useful, but WITHOUT ANY 23 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | # PARTICULAR PURPOSE. See the GNU General Public License for more details. 25 | # 26 | # You should have received a copy of the GNU General Public License along with 27 | # this program. If not, see . 28 | # 29 | # ----------------------------------------------------------------------------- 30 | 31 | %dbx = ( 32 | epoch_to_timestamp_fn => 'TO_TIMESTAMP', 33 | 34 | to_hex_string => sub { 35 | my ($bin) = @_; 36 | return "'\\x" . unpack("H*", $bin) . "'"; 37 | }, 38 | 39 | column_info_type_col => 'pg_type', 40 | 41 | tables => { 42 | "report" => { 43 | column_definitions => [ 44 | "serial" , "bigint" , "GENERATED ALWAYS AS IDENTITY", 45 | "mindate" , "timestamp without time zone" , "NOT NULL", 46 | "maxdate" , "timestamp without time zone" , "NULL", 47 | "domain" , "character varying(255)" , "NOT NULL", 48 | "org" , "character varying(255)" , "NOT NULL", 49 | "reportid" , "character varying(255)" , "NOT NULL", 50 | "email" , "character varying(255)" , "NULL", 51 | "extra_contact_info" , "character varying(255)" , "NULL", 52 | "policy_adkim" , "character varying(20)" , "NULL", 53 | "policy_aspf" , "character varying(20)" , "NULL", 54 | "policy_p" , "character varying(20)" , "NULL", 55 | "policy_sp" , "character varying(20)" , "NULL", 56 | "policy_pct" , "smallint" , "", 57 | "raw_xml" , "text" , "", 58 | ], 59 | additional_definitions => "PRIMARY KEY (serial)", 60 | table_options => "", 61 | indexes => [ 62 | "CREATE UNIQUE INDEX report_uidx_domain ON report (domain, reportid);" 63 | ], 64 | }, 65 | "rptrecord" => { 66 | column_definitions => [ 67 | "id" , "bigint" , "GENERATED ALWAYS AS IDENTITY", 68 | "serial" , "bigint" , "NOT NULL", 69 | "ip" , "bigint" , "", 70 | "ip6" , "bytea" , "", 71 | "rcount" , "integer" , "NOT NULL", 72 | "disposition" , "character varying(20)" , "", 73 | "reason" , "character varying(255)" , "", 74 | "dkimdomain" , "character varying(255)" , "", 75 | "dkimresult" , "character varying(20)" , "", 76 | "spfdomain" , "character varying(255)" , "", 77 | "spfresult" , "character varying(20)" , "", 78 | "spf_align" , "character varying(20)" , "NOT NULL", 79 | "dkim_align" , "character varying(20)" , "NOT NULL", 80 | "identifier_hfrom" , "character varying(255)" , "" 81 | ], 82 | additional_definitions => "PRIMARY KEY (id)", 83 | table_options => "", 84 | indexes => [ 85 | "CREATE INDEX rptrecord_idx_serial ON rptrecord (serial, ip);", 86 | "CREATE INDEX rptrecord_idx_serial6 ON rptrecord (serial, ip6);", 87 | ], 88 | }, 89 | "tls" => { 90 | column_definitions => [ 91 | "serial" , "bigint" , "GENERATED ALWAYS AS IDENTITY", 92 | "mindate" , "timestamp without time zone" , "NOT NULL", 93 | "maxdate" , "timestamp without time zone" , "NULL", 94 | "domain" , "character varying(255)" , "NOT NULL", 95 | "org" , "character varying(255)" , "NOT NULL", 96 | "reportid" , "character varying(255)" , "NOT NULL", 97 | "email" , "character varying(255)" , "NULL", 98 | "policy_mode" , "character varying(20)" , "NULL", 99 | "summary_success" , "integer" , "NULL", 100 | "summary_failure" , "integer" , "NULL", 101 | "raw_json" , "text" , "", 102 | ], 103 | additional_definitions => "PRIMARY KEY (serial)", 104 | table_options => "", 105 | indexes => [ 106 | "CREATE UNIQUE INDEX tls_uidx_domain ON tls (domain, reportid);" 107 | ], 108 | }, 109 | "tlsrecord" => { 110 | column_definitions => [ 111 | "id" , "bigint" , "GENERATED ALWAYS AS IDENTITY", 112 | "serial" , "bigint" , "NOT NULL", 113 | "send_ip" , "bigint" , "", 114 | "send_ip6" , "bytea" , "", 115 | "recv_ip" , "bigint" , "", 116 | "recv_ip6" , "bytea" , "", 117 | "recv_mx" , "character varying(255)" , "", 118 | "type" , "character varying(255)" , "", 119 | "count" , "integer" , "NOT NULL", 120 | ], 121 | additional_definitions => "PRIMARY KEY (id)", 122 | table_options => "", 123 | indexes => [ 124 | "CREATE INDEX tlsrecord_idx_serial ON tlsrecord (serial, send_ip);", 125 | "CREATE INDEX tlsrecord_idx_serial6 ON tlsrecord (serial, send_ip6);", 126 | ], 127 | } 128 | }, 129 | 130 | add_column => sub { 131 | my ($table, $col_name, $col_type, $col_opts, $after_col) = @_; 132 | 133 | # Postgres only allows adding columns at the end, so $after_col is ignored 134 | return "ALTER TABLE $table ADD COLUMN $col_name $col_type $col_opts;" 135 | }, 136 | 137 | modify_column => sub { 138 | my ($table, $col_name, $col_type, $col_opts) = @_; 139 | return "ALTER TABLE $table ALTER COLUMN $col_name TYPE $col_type;" 140 | }, 141 | ); 142 | 143 | 1; -------------------------------------------------------------------------------- /docs/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0-α5 4 | - Fixed an issue with undefined variables discovered with Issue #12. 5 | - Fixed an issue with mimecast improperly setting mime type outlined in Issue #12. 6 | 7 | ## 0-α4 8 | - Fixed Issue #8 again - some errornous code was introduced at some point that skips DB checks if not using Oauth2. 9 | - Updated documentation to fix minimum requirements regarding MariaDB vs MySQL (initially discovered with Open Report Analyzer). 10 | 11 | ## 0-α3 12 | - Postgres fixes (and validation). Fixes Issue #8. 13 | - Initial Oauth2 Support code (untested). 14 | 15 | ## 0-α2 16 | - Fixed errors in previous release incorporating postgres support related to table creation. 17 | - Added MTA-TLS report support. 18 | - More useful debug output. 19 | - Code consolodation (eg, subroutine repetative code). 20 | 21 | ## 0-α1 22 | - Fork renamed 23 | - Incorporate changes made to original repository after fork ([commit 51ba1de](https://github.com/userjack6880/Open-Report-Parser/commit/51ba1de8521559647ebe4b8a1db291c26b572de4)) -------------------------------------------------------------------------------- /docs/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | The Internet is a vast space with a diverse community of professionals and enthusaists with an equally vast set of interests and opinions. From this deep well of diversity comes a wellspring of fresh and bold ideas that can further humanity as a whole. But it is this same diversity that can lead to communication failures and discontent. 4 | 5 | This document, the Code of Conduct, serves as a general guideline on how the community revolving around this project, and all projects directly under my control, including those here on GitHub, the [System Anomaly](https://systemanomaly.com) website and web persona, personal and public social channels, and any other channels of communication spawned from these. These guidelines apply to everyone from myself at the top all the way down to those wishing to engage with these projects. 6 | 7 | Don't take this necessarially as a list of things which cannot be done. It is simply a guideline, which may be enhanced by a set of rules that apply to specific situations, which will be clearly posted if needed. 8 | 9 | Violations of this code of conduct are primarly enforced where it is applied, however violations outside of these spaces may preclude an individual from participation in these spaces. 10 | 11 | If you believe an individual has violated the Code of Conduct, please send an email to conduct@j3b.in. Please read the section titled **Reporting Guidelines** before doing so, and if you want to know how enforcement is handled, please read the section titled **Enforcement**. 12 | 13 | Thank You 14 | John Bradley 15 | (userjack6880) 16 | 17 | ## The Code 18 | 19 | ### Be Kind 20 | The world can be tough at times, and we do not need to be reminded of this fact through these spaces. A kind, considerate, and welcoming demeanor makes this space a better place, and can make someone's day a little brighter. Welcome those who wish to engage with this space, regardless of identity. This includes, but is not limited to, members of any race, ethnicity, culture, national origin, immigration status, social and economic class, education level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and ability both mental and physical. 21 | 22 | ### Be Respectful 23 | In addition to being kind, throught he course of participation in these spaces, one should be considerate and respectful. Your contributions may be used by others, and you may use others' contributations, and your decisions will affect others. Take this in account when making these decisions. Additionally, you may disagree with the decision, action, or opinion of another individual, and vice-versa. Handle disagreements with respect to the other individual. Do not allow frustration to be an excuse for poor behavior, poor manners, or personal attacks. These spaces are intended to be welcoming, and making someone feel uncomfortable or threatened is not productive. Instead, try to understand where the other person is coming from, and make an attempt to address the issue. 24 | 25 | Additionally, the following actions are not considered kind, respectful, or acceptable: 26 | - Violent threats or language directed against another person. 27 | - Discriminatory jokes and language. 28 | - Posting sexually explicit or violent material. 29 | - Posting, or threatening to post, other people's personally identifying information (PII), also known as "doxing". 30 | - Personal insults, especially using bigoted language such as racist or sexist terms. 31 | - Unwelcomed attention or harassment, sexual or otherwise. No means no. 32 | - Advocating for or encouraging the above behavior. 33 | 34 | ## Enforcement 35 | Breaking these guidelines does not always mean immediate expulsion from participation in these spaces. Infractions are investigated and handled on a case-by-case basis. Enforcement may come in many forms, from initial warnings for minor first-offense, requesting that the offending individual apologize to those who were harmed, to finally explusion for the most egregious violations of the Code of Conduct. 36 | 37 | Those put in charge of enforcement of the Code of Conduct, the Council, have final say in how it is enforced. A formal request for reconsideration is allowed, but reversasl in a decision is not guaranteed. 38 | 39 | ## Council Members 40 | - Chair: John Bradley (john@j3b.in) 41 | 42 | Because these projects are currently small in nature, the council consists of one member. Positions will open up as projects and related communities grow. The Code of Conduct will be updated as needed. 43 | 44 | ## Reporting Guidelines 45 | If you believe someone is violating the Code of Conduct, please email conduct@j3b.in. **All reports will remain confidential**. If a public statement is required in the course of enforcement, any identifying information will remain confidential **unless instructed otherwise** by those individuals. 46 | 47 | **If you believe anyone is in physical danger, please contact law enforcement first**. If you are unsure who needs to be contacted, please include that in your report and we will make an attempt to notify the appropriate agencies. 48 | 49 | If you are unsure if an incident is a violation of the Code of Conduct, report it anyways. Remember, **all reports will remain confidential**, and if a report isn't a violation, no harm will have been done. Likewise, if a violation isn't reported, nothing will be resolved. You will not be negatively looked upon if an incident isn't a violation, and knowing about these incidents will allow us to better adjust the Code of Conduct and processes related to the Code of Conduct as well as adjust specific rules and processes that apply to individual spaces. 50 | 51 | Please include in your report: 52 | - Your contact info, so that we can get in touch with you for a follow up. 53 | - Names, real or otherwise, so as long as it is able to allow us to identify the individual that violated the Code of Conduct. Include any witnesses that can back up your report. 54 | - When and where the incident occured. Please be as specific as possible. Also indicate if the issue is ongoing. 55 | - Your account of what occured, and a copy or link to any publicly available record of what occured. 56 | - Any additional context or information that you believe may be relevant. 57 | 58 | ## What Happens When We Receive a Report 59 | When an incident is reported, the Council will acknolwedge as soon as possible to the individual that submitted the report that we received it an have begun investigations. Once this has occured, the Council will immediately review: 60 | - What happened. 61 | - If this was a violation of the Code of Conduct. 62 | - Who violated the Code of Conduct. 63 | - If this is ongoing or if there is a threat to someone's safety. 64 | 65 | If the violation is ongoing or a threat to safety, the Council will work immediately to resolve the situation as best as possible, and may delay an official response until the situation has been resolved. 66 | 67 | Once there is a clear picture of what occured, an official response will be issued. It may include: 68 | - Nothing, if there is no violation. 69 | - A public and/or private reprimand. 70 | - A request for public and/or private apology. 71 | - Request the violator to take a break from these spaces. 72 | - Temporarially or permanently ban the violator from some or all of these spaces. 73 | 74 | The reporter will be notified of the Council's decision, and any related individuals will be contacted as needed. Public actions are reserved for the most severe violations of the Code of Conduct. 75 | 76 | ## What If a Report Includes a Violation By a Council Member? 77 | Currently, because the council consists solely of one member, it can be a difficult decision to make a report. This is understandable. There is no real good solution to this problem at this time. 78 | 79 | We still request that, if you are comfortable, to report a violation by the Council member, since this will give them an opportunity for self-reflection and self-correction. 80 | 81 | *All decisions* regarding violations by a Council member are considered public, and all reprimands to and apologies by a Council member will be public. Individuals making these reports will remain confidential unless instructed otherwise. -------------------------------------------------------------------------------- /docs/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute to Open Report Parser 2 | 3 | ## **Bug Reporting** 4 | 5 | - **Please do not report security issues publically on GitHub!** For details, see `SECURITY`. 6 | 7 | - **Ensure the bug was not already reported** by searching on GitHub under [Issues](https://github.com/userjack6880/Open-Report-Parser/issues). 8 | 9 | - If an open issue addressing the problem does not exist, [open a new one](https://github.com/userjack6880/Open-Report-Parser/issues/new). Be sure to include a title and clear description, and as much relevant information as possible, including error messages, screenshots, or configuration files. **Please sanitize any passwords or sensitive information**. 10 | 11 | ## **Contributing Bugfixes and Patches** 12 | 13 | - Open a new GitHub pull request with the patch. Issue PRs to the main branch for bugfixes and patches. See **Contributing Feature Changes and Additions** for non-fixes. 14 | 15 | - Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. 16 | 17 | - Pull requests will be reviewed and encorporated once it has been tested. 18 | 19 | ## **Contributing Feature Changes and Additions** 20 | 21 | - First issue a feature request under [Issues](https://github.com/userjack6880/Open-Report-Parser/issues/new) using the appropriate template. 22 | 23 | - Open a new GitHub pull request with the feature change or addition. Issue PRs to the testing branch and include in the PR description the relevant issue number. Changes will be pushed through to the dev branch once it has been tested, and could possibly become part of the main branch. 24 | 25 | ## **Formatting PRs** 26 | 27 | Pull requests that are only formatting and whitespace changes will be rejected. 28 | 29 | ## **Additional Info** 30 | 31 | Open Report Parser is a continually changing project. Contributions, requests, and bug reports help made it what it is today and continues to be a source of inspiration and continual improvement, and are greatly appreciated. 32 | 33 | Thank You 34 | John Bradley 35 | (userjack6880) 36 | -------------------------------------------------------------------------------- /docs/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | Security is a serious concern for any modern project, open source or otherwise. In general, this policy applies to all projects found under control of [userjack6880](https://github.com/userjack6880) or as part of [System Anomaly](https://systemanomaly.com). If you believe you have found a security vulnerability in any of these projects, please report it as described below. 4 | 5 | ## Reporting a Vulnerability 6 | 7 | **Please Do Not Report Security Issues Publically!** Instead, please send an email to [security@j3b.in](mailto:security@j3b.in), and if possible, use our [PGP Key available from the System Anomaly website](https://systemanomaly.com/pgp/). 8 | 9 | A response should be recieved within 72 hours. If no response is given, please follow up to ensure the original message was received. Please include in your message: 10 | - Type of issue 11 | - Location of the affected source code and path to the affected file(s) 12 | - Any special configuration required to reproduce the issue 13 | - Step-by-step instructions to reproduce the issue 14 | - Proof-of-concept or exploit if possible 15 | - Impact of the issue and how it may be exploited 16 | 17 | ## Supported Versions 18 | 19 | Open DMARC Analyzer Version Security Support 20 | 21 | | Version | Supported | End of Life | 22 | | -------------------------- | --------- | ---------------- | 23 | | Version 0 Alpha 5 | YES | TBD | 24 | | Version 0 Alpha 4 | YES | TBD | 25 | | Version 0 Alpha 3 | NO | 10 July 2023 | 26 | | Version 0 Alpha 2 | NO | 8 June 2023 | 27 | | Version 0 Alpha 1 | NO | 25 May 2023 | -------------------------------------------------------------------------------- /docs/SUPPORT.md: -------------------------------------------------------------------------------- 1 | # Software Support Chart 2 | 3 | Due to the limited time available to developrs to maintain support, dates must be set where support must end. The following is a chart outlining the support shedule for Open Report Parser. 4 | 5 | | Version | Support Level | Released | End of Support | End of Life | 6 | | ----------------------------------- | ---------------- | ---------------- | ---------------- | ---------------- | 7 | | Version 1 Alpha 5 | Full Support | 10 July 2023 | TBD | TBD | 8 | | Version 1 Alpha 4 | Critical Support | 8 June 2023 | 10 July 2023 | TBD | 9 | | Version 1 Alpha 3 | End of Life | 25 May 2023 | 8 June 2023 | 10 July 2023 | 10 | | Version 1 Alpha 2 | End of LIfe | 26 April 2023 | 25 May 2023 | 8 June 2023 | 11 | | Version 1 Alpha 1 | End of Life | 19 April 2023 | 26 April 2023 | 25 May 2023 | 12 | 13 | # Support Cycle 14 | 15 | - Pre-stable versions recieve one version cycle of full spport and one cycle of critical support before being considered end of life. Due to the lack of release cycle for these versions, support time can wildly vary. 16 | - The final release candidate will have critical support until the end of a year that the stable version is released. 17 | - All versions of a stable version are considered supported, though it is encouraged to keep updated to the latest stable release. 18 | - Stable versions reach end of life at the end of a year that a new stable version is released. The exception is LTS versions - those will recieve 3 years of support. 19 | 20 | # Support Levels 21 | 22 | - **Full Support** means that software will recieve regular bug fixes, feature updates (if applicable), and security fixes. All current versions do not have an expected End of Support or End of Life date, as new version releases are not always predictable. 23 | 24 | - **Critical Support** means that software will no longer recieve regular bug fixes or feature updates, but security fixes will still be provided. 25 | 26 | - **End of Life** means that there is no more support what-so-ever. Issues, bug reports, and code contributions to these versions will be ignored or rejected. 27 | -------------------------------------------------------------------------------- /docs/VERSIONING.md: -------------------------------------------------------------------------------- 1 | # Versioning-Scheme 2 | 3 | This is a general guideline for all projects controlled by John Bradley (userjack6880) or part of the System Anomaly sphere of influence. This scheme shall be called the Anomaly Versioning Scheme (2022). 4 | 5 | ## Overview 6 | ``` 7 | Major - (Stage) SubMajor . Minor 8 | 9 | ex 10 | 11 | Alpha Project: 0-α1.6 Version 0 Alpha 1.6 12 | Feature Complete: 1-fc Version 1 Feature Complete 13 | Beta Project: 1-β4 Version 1 Beta 4 14 | Release Candidate: 5-rc2 Version 5 Release Candidate 2 15 | Stable: 1 Version 1 16 | Stable Update: 1-u3 Version 1 Update 3 17 | ``` 18 | 19 | ## Stages 20 | Project stages are defined as followed: 21 | - Alpha: the project is still in a state where features may be added and serious errors and fixes are not the primary focus of development. This is the "get shit working" stage of development. Alpha versions are not production ready. These versions are denoted with the Greek letter α or the word "Alpha". 22 | - Feature Complete: this project is still not in a state where fixes are the primary focus of development, but no new features are added. Existing features are fleshed out for full functionality before moving onto beta. It's still technically an Alpha version and is not production ready. Usually there will only be one feature complete version. These versions are denoted with "fc" or "Feature Complete". 23 | - Beta: the project has moved onto bug fixes and error correcting. This is where everything is tested and polished. While not considered production ready, these versions can be put into production at the risk of the user, as no new features will be added. These version are denoted with the Greek letter β or the word "Beta". 24 | - Release Candidate: the project is ready for release. It is assumed this version will become a stable release if no major bugs are found. Fixes are only applied to the Beta Stage and pushed back up to a new Release Candidate version. During this stage, documentation is completed. These versions are denoted with "rc" or "Release Candidate". 25 | - Stable: the project is finally released. No major bugs are known, all features are implemented, and the software is production safe. These have no denotations unless an update is issued. 26 | - Stable Update: A major fix was applied or a minor feature update was issued. These are denoted with "u" or "Update". 27 | 28 | ## Major Versions 29 | Major versions are established in one of two ways. Initial project creation has a major version number of 0, but are incremented to version 1 once it becomes feature complete. Feature completeness means that no major features will be added to this version. Additional features are agregated into the next version, which may begin as soon as a version exits alpha and begins beta testing. 30 | 31 | ## Submajor Versions 32 | Submajor version are limited to the stage of development in which the code was changed. Submajor changes also vary depending on stage of development. 33 | 34 | - Alpha submajor versions include significant rewrites of the code or new features added. 35 | - Feature Complete code does not have a submajor. 36 | - Beta submajor versions are included when a major bug is fixed, a feature is fleshed out, or there is a significant rewrite to accomplished either goal. 37 | - Release Candidate submajor versions are issued if a major bug is found and fixed. The first submajor release candidate version will not have a number attached. 38 | - Stable submajor versions are issued if a major bug is found and fixed or a feature is tweaked after release. Stable submajor versions add the stage indicater "u" or "Update". 39 | 40 | ## Minor Versions 41 | Minor versions are updates to submajor versions. Like submajor versions, these also vary depending on stage of development. 42 | 43 | - Alpha minor versions are very minor code changes, like a small tweak to a variable or changing single digit lines. 44 | - Feature Complete code does not have minor versions. 45 | - Beta minor versions are like Alpha minor versions, and are very minor code changes. 46 | - Release Candidate code does not have minor versions. 47 | - Stable code does not have minor versions. 48 | 49 | # Implementation 50 | This versioning system will be implemented on date of publish (29 March, 2022), and projects will be updated accordingly. -------------------------------------------------------------------------------- /lib/OAuth.pm: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # 3 | # Open Report Parser - Open Source report parser 4 | # Copyright (C) 2023 John Bradley (userjack6880) 5 | # Copyright (C) 2016 TechSneeze.com 6 | # Copyright (C) 2012 John Bieling 7 | # 8 | # oauth.pl 9 | # oauth2 module 10 | # 11 | # Available at: https://github.com/userjack6880/Open-Report-Parser 12 | # 13 | # ----------------------------------------------------------------------------- 14 | # 15 | # This file is part of Open Report Parser. 16 | # 17 | # Open Report Parser is free software: you can redistribute it and/or modify it under 18 | # the terms of the GNU General Public License as published by the Free Software 19 | # Foundation, either version 3 of the License, or (at your option) any later 20 | # version. 21 | # 22 | # This program is distributed in the hope that it will be useful, but WITHOUT ANY 23 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | # PARTICULAR PURPOSE. See the GNU General Public License for more details. 25 | # 26 | # You should have received a copy of the GNU General Public License along with 27 | # this program. If not, see . 28 | # 29 | # ----------------------------------------------------------------------------- 30 | 31 | package OAuth; 32 | use LWP::UserAgent; 33 | use LWP::Protocol::https; 34 | use JSON; 35 | use Encode; 36 | use Time::Piece; 37 | 38 | our @EXPORT = qw( get_oauth ); 39 | 40 | sub get_oauth { 41 | my ($oauthuri, $oauthclientid, $dbh, $db_tx_support, $clear_token) = (@_); 42 | 43 | # clear token if requested 44 | if ($clear_token) { 45 | my $sql = qq{DELETE FROM oauth}; 46 | $dbh->do($sql, undef); 47 | if ($dbh->errstr) { 48 | warn "$scriptname: $org: $id: Cannot invalidate OAuth tokens.\n"; 49 | exit; 50 | } 51 | else { 52 | if ($db_tx_support) { 53 | $dbh->commit; 54 | if ($dbh->errstr) { 55 | warn "$scriptname: $org: $id: Cannot commit transaction.\n"; 56 | } 57 | } 58 | } 59 | } 60 | 61 | # check if valid oauth token exists 62 | my $sth = $dbh->prepare(qq{SELECT access_token, refresh_token, UNIX_TIMESTAMP(expire) AS expire, valid FROM oauth WHERE valid=1}); 63 | $sth->execute(); 64 | my $result = $sth->fetchrow_hashref(); 65 | 66 | # first check if there's a result and it's valid 67 | if ($result && $result->{valid} == 1) { 68 | # check to see if it's expired 69 | if ($result->{expire} > time()) { 70 | return $result->{access_token}; 71 | } 72 | # if token is expired, refresh 73 | else { 74 | print "expired token, refreshing\n"; 75 | # setup the useragent 76 | my $ua = LWP::UserAgent->new( 77 | protocols_allowed => ['https'], 78 | ); 79 | 80 | # send the device authorization request 81 | my $request = HTTP::Request->new( 82 | 'POST', 83 | $oauthuri."token", 84 | [ 85 | 'Content-Type' => 'application/x-www-form-urlencoded' 86 | ] 87 | ); 88 | my $refresh_token = $result->{refresh_token}; 89 | $request->content(encode("UTF-8","client_id=$oauthclientid&refresh_token=$refresh_token&grant_type=refresh_token")); 90 | 91 | my $response = $ua->request($request); 92 | my $respJSON = $response->decoded_content(); 93 | my $respData = decode_json($respJSON); 94 | 95 | # if there's an error, print it out 96 | if (exists($respData->{error})) { 97 | print "Oauth2 Error: ".$respData->{error}."\n". 98 | $respData->{error_description}."\n"; 99 | exit; 100 | } 101 | 102 | # mark all other oauth tokens invalid 103 | my $sql = qq{UPDATE oauth SET valid = 0 WHERE valid = 1}; 104 | $dbh->do($sql, undef); 105 | if ($dbh->errstr) { 106 | warn "$scriptname: $org: $id: Cannot invalidate OAuth tokens.\n"; 107 | exit; 108 | } 109 | else { 110 | if ($db_tx_support) { 111 | $dbh->commit; 112 | if ($dbh->errstr) { 113 | warn "$scriptname: $org: $id: Cannot commit transaction.\n"; 114 | } 115 | } 116 | } 117 | 118 | # throw the info back into the DB 119 | my $access_token = $respData->{access_token}; 120 | $refresh_token = $respData->{refresh_token}; 121 | my $expires_in = $respData->{expires_in}; 122 | 123 | my $sql = qq{INSERT INTO oauth (access_token, refresh_token, expire, valid) 124 | VALUES (?,?,FROM_UNIXTIME(?),1)}; 125 | $token_expire = time()+$expires_in; 126 | $dbh->do($sql, undef, $access_token, $refresh_token, $token_expire); 127 | if ($dbh->errstr) { 128 | warn "$scriptname: $org: $id: Cannot add OAuth to database.\n"; 129 | exit; 130 | } 131 | else { 132 | if ($db_tx_support) { 133 | $dbh->commit; 134 | if ($dbh->errstr) { 135 | warn "$scriptname: $org: $id: Cannot commit transaction.\n"; 136 | } 137 | } 138 | } 139 | 140 | # now we can return the current access token 141 | return $access_token; 142 | } 143 | } 144 | 145 | # if there is no refresh or valid token does not exist, get a new token 146 | else { 147 | print "no token found, requesting\n"; 148 | # setup the useragent 149 | my $ua = LWP::UserAgent->new( 150 | protocols_allowed => ['https'], 151 | ); 152 | 153 | my $scope = "openid%20email"; 154 | 155 | # if it's m365, we need to request offline_access too 156 | if ($oauthuri =~ m/microsoft/) { 157 | $scope .= "%20offline_access%20https%3A%2F%2Foutlook.office.com%2F.default"; 158 | } 159 | 160 | # send the device authorization request 161 | my $request = HTTP::Request->new( 162 | 'POST', 163 | $oauthuri."devicecode", 164 | [ 165 | 'Content-Type' => 'application/x-www-form-urlencoded' 166 | ] 167 | ); 168 | $request->content(encode("UTF-8","client_id=$oauthclientid&scope=$scope")); 169 | 170 | my $response = $ua->request($request); 171 | my $respJSON = $response->decoded_content(); 172 | my $respData = decode_json($respJSON); 173 | 174 | # if there's an error, print it out 175 | if (exists($respData->{error})) { 176 | print "Oauth2 Error: ".$respData->{error}."\n". 177 | $respData->{error_description}."\n". 178 | $respData->{error_uri}."\n"; 179 | exit; 180 | } 181 | 182 | # now we present a URI to the user and wait for auth 183 | my $device_code = $respData->{device_code}; 184 | my $user_code = $respData->{user_code}; 185 | my $verification_uri = $respData->{verification_uri}; 186 | my $expires_in = $respData->{expires_in}; 187 | my $interval = $respData->{interval}; 188 | my $message = $respData->{message}; 189 | 190 | print "$message\n\n". 191 | "URL: $verification_uri\n". 192 | "Expires in $expires_in seconds.\n". 193 | "User Code: $user_code\n"; 194 | 195 | # count elapsed, we want to force a timeout regardless if we get a response 196 | my $elapsed = 0; 197 | while ($elapsed < $expires_in) { 198 | $request->uri($oauthuri."token"); 199 | $request->content(encode("UTF-8","grant_type=urn:ietf:params:oauth:grant-type:device_code&client_id=$oauthclientid&device_code=$device_code")); 200 | 201 | $response = $ua->request($request); 202 | $respJSON = $response->decoded_content(); 203 | $respData = decode_json($respJSON); 204 | 205 | if(exists($respData->{error})) { 206 | if ($respData->{error} eq 'authorization_pending') { 207 | sleep $interval; 208 | $elapsed += $interval-2; # this should give us a bit of headroom; 209 | next; 210 | } 211 | elsif ($respData->{error} eq 'authorization_declined') { 212 | print "Authorization declined. Exiting.\n"; 213 | exit; 214 | } 215 | elsif ($respData->{error} eq 'bad_verification_code') { 216 | print "Bad verification code. Device code sent: $device_code. Exiting.\n"; 217 | exit; 218 | } 219 | elsif ($respData->{error} eq 'expired_token') { 220 | print "Authorization took too long. Token expired. Exiting.\n"; 221 | exit; 222 | } 223 | else { 224 | print "Other Error: ".$respData->{error}." - Exiting.\n". 225 | "Description: ".$respData->{error_description}."\n". 226 | "Error URI: ".$respData->{error_uri}."\n"; 227 | exit; 228 | } 229 | } 230 | 231 | # if it's a token... we can break out of the while loop 232 | if(exists($respData->{token_type})) { 233 | last; 234 | } 235 | } 236 | # if we get out of the loop and it didn't error, then we should have a token now 237 | # and we can save it to the database 238 | my $access_token = $respData->{access_token}; 239 | my $refresh_token = $respData->{refresh_token}; 240 | my $expires_in = $respData->{expires_in}; 241 | 242 | my $sql = qq{INSERT INTO oauth (access_token, refresh_token, expire, valid) 243 | VALUES (?,?,FROM_UNIXTIME(?),1)}; 244 | my $token_expire = time()+$expires_in; 245 | $dbh->do($sql, undef, $access_token, $refresh_token, $token_expire); 246 | if ($dbh->errstr) { 247 | warn "$scriptname: $org: $id: Cannot add OAuth to database.\n"; 248 | exit; 249 | } 250 | else { 251 | if ($db_tx_support) { 252 | $dbh->commit; 253 | if ($dbh->errstr) { 254 | warn "$scriptname: $org: $id: Cannot commit transaction.\n"; 255 | } 256 | } 257 | } 258 | 259 | return $access_token; 260 | } 261 | } 262 | 263 | 1; -------------------------------------------------------------------------------- /report-parser.conf.pub: -------------------------------------------------------------------------------- 1 | # ----------------------------------------------------------------------------- 2 | # 3 | # Open Report Parser - Open Source report parser 4 | # Copyright (C) 2023 John Bradley (userjack6880) 5 | # Copyright (C) 2016 TechSneeze.com 6 | # Copyright (C) 2012 John Bieling 7 | # 8 | # report-parser.conf 9 | # configuration file 10 | # 11 | # Available at: https://github.com/userjack6880/Open-Report-Parser 12 | # 13 | # ----------------------------------------------------------------------------- 14 | # 15 | # This file is part of Open Report Parser. 16 | # 17 | # Open Report Parser is free software: you can redistribute it and/or modify it under 18 | # the terms of the GNU General Public License as published by the Free Software 19 | # Foundation, either version 3 of the License, or (at your option) any later 20 | # version. 21 | # 22 | # This program is distributed in the hope that it will be useful, but WITHOUT ANY 23 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 24 | # PARTICULAR PURPOSE. See the GNU General Public License for more details. 25 | # 26 | # You should have received a copy of the GNU General Public License along with 27 | # this program. If not, see . 28 | # 29 | # ----------------------------------------------------------------------------- 30 | 31 | # If IMAP access is not used, config options starting with $imap do not need to 32 | # be set and are ignored. 33 | 34 | $debug = 0; 35 | $delete_reports = 0; 36 | #$dmarc_only = 0; 37 | # if set to 1, do not process tls reports, if set to -1 do not process 38 | # dmarc reports - defaults to 1 for legacy support 39 | # this is ignored for all methods except IMAP, use --tls to process 40 | # TLS reports for other methods 41 | 42 | #$dbtype = 'mysql'; # Supported types - mysql, postgres - defaults to mysql if unset 43 | $dbname = 'dmarc'; 44 | $dbuser = 'dmarc'; 45 | $dbpass = 'password'; 46 | #$dbhost = 'dbhost'; # Set the hostname if we can't connect to the local socket. 47 | $dbport = '3306'; 48 | 49 | $imapserver = 'imap.server'; 50 | $imapuser = 'username'; 51 | $imappass = 'password'; 52 | $imapport = '143'; 53 | $imapssl = '0'; # If set to 1, remember to change server port to 993 and disable imaptls. 54 | $imaptls = '0'; 55 | $tlsverify = '0'; 56 | $imapignoreerror = '0'; # recommended if you use MS Exchange 2007, ... 57 | #$imapauth = 'simple'; # supported - simple, oauth2 - defaults to simple if unset 58 | 59 | # see documentation for detailed setup 60 | #$oauthclientid = ''; 61 | #$oauthuri = ''; 62 | 63 | $imapdmarcfolder = 'dmarc'; 64 | $imaptlsfolder = 'tls'; 65 | 66 | # If $imapxxxproc is set, processed IMAP messages will be moved (overruled by 67 | # the --delete option!) 68 | # $imapdmarcproc = 'dmarc.Processed'; 69 | # $imaptlsproc = 'tls.Processed'; 70 | 71 | # If $imapxxxerr is set, IMAP messages that fail will be moved. If unset, failed messages 72 | # will move to $imapdmarcproc (if it is set). Overruled by the --delete option! 73 | # $imapdmarcerr = 'dmarc.notProcessed'; 74 | # $imaptlserr = 'tls.notProcessed'; 75 | 76 | # maximum size of XML/JSON files to store in database, long files can cause transaction aborts 77 | $maxsize_xml = 50000; 78 | $maxsize_json = 50000; 79 | 80 | # store XML/JSON as base64 encopded gzip in database (save space, harder usable) 81 | $compress_xml = 0; 82 | $compress_json = 0; 83 | 84 | # if there was an error during file processing (message does not contain XML or ZIP parts, 85 | # or a database error) the parser reports an error and does not delete the file, even if 86 | # delete_reports is set (or --delete is given). Deletion can be enforced by delete_failed, 87 | # however not for database errors. 88 | $delete_failed = 0; -------------------------------------------------------------------------------- /report-parser.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | # ----------------------------------------------------------------------------- 4 | # 5 | # Open Report Parser - Open Source report parser 6 | # Copyright (C) 2023 John Bradley (userjack6880) 7 | # Copyright (C) 2016 TechSneeze.com 8 | # Copyright (C) 2012 John Bieling 9 | # 10 | # report-parser.pl 11 | # main script 12 | # 13 | # Available at: https://github.com/userjack6880/Open-Report-Parser 14 | # 15 | # ----------------------------------------------------------------------------- 16 | # 17 | # This file is part of Open Report Parser. 18 | # 19 | # Open Report Parser is free software: you can redistribute it and/or modify it under 20 | # the terms of the GNU General Public License as published by the Free Software 21 | # Foundation, either version 3 of the License, or (at your option) any later 22 | # version. 23 | # 24 | # This program is distributed in the hope that it will be useful, but WITHOUT ANY 25 | # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 26 | # PARTICULAR PURPOSE. See the GNU General Public License for more details. 27 | # 28 | # You should have received a copy of the GNU General Public License along with 29 | # this program. If not, see . 30 | # 31 | # ----------------------------------------------------------------------------- 32 | # 33 | # The subroutines storeXMLInDatabase() and getXMLFromMessage() are based on 34 | # John R. Levine's rddmarc (http://www.taugh.com/rddmarc/). The following 35 | # special conditions apply to those subroutines: 36 | # 37 | # Copyright 2012, Taughannock Networks. All rights reserved. 38 | # 39 | # Redistribution and use in source and binary forms, with or without 40 | # modification, are permitted provided that the following conditions are met: 41 | # 42 | # Redistributions of source code must retain the above copyright notice, this 43 | # list of conditions and the following disclaimer. 44 | # 45 | # Redistributions in binary form must reproduce the above copyright notice, this 46 | # list of conditions and the following disclaimer in the documentation and/or 47 | # other materials provided with the distribution. 48 | # 49 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 50 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 51 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 52 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 53 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 54 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 55 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 56 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 57 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 58 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 59 | # 60 | # ----------------------------------------------------------------------------- 61 | 62 | # Always be safe 63 | use strict; 64 | use warnings; 65 | 66 | # Use these modules 67 | use Getopt::Long; 68 | use IO::Compress::Gzip qw(gzip $GzipError); 69 | #use Data::Dumper; 70 | use Mail::IMAPClient; 71 | use Mail::Mbox::MessageParser; 72 | use MIME::Base64 qw(encode_base64); 73 | use MIME::Words qw(decode_mimewords); 74 | use MIME::Parser; 75 | use MIME::Parser::Filer; 76 | use XML::Simple; 77 | use JSON; 78 | use DBI; 79 | use Socket; 80 | use Socket6; 81 | use PerlIO::gzip; 82 | use File::Basename (); 83 | use File::MimeInfo; 84 | use IO::Socket::SSL; 85 | #use IO::Socket::SSL 'debug3'; 86 | 87 | use lib 'lib'; 88 | use OAuth; 89 | 90 | # ----------------------------------------------------------------------------- 91 | # usage 92 | # ----------------------------------------------------------------------------- 93 | 94 | sub show_usage { 95 | print "\n"; 96 | print " Usage: \n"; 97 | print " ./report-parser.pl [OPTIONS] [PATH] \n"; 98 | print "\n"; 99 | print " This script needs a configuration file called in the\n"; 100 | print " current working directory, which defines a database server with credentials \n"; 101 | print " and (if used) an IMAP server with credentials. \n"; 102 | print "\n"; 103 | print " Additionaly, one of the following source options must be provided: \n"; 104 | print " -i : Read reports from messages on IMAP server as defined in the \n"; 105 | print " config file. \n"; 106 | print " -m : Read reports from mbox file(s) provided in PATH. \n"; 107 | print " -e : Read reports from MIME email file(s) provided in PATH. \n"; 108 | print " -x : Read reports from xml file(s) provided in PATH. \n"; 109 | print " -j : Read reports from json files(s) provided in PATH. \n"; 110 | print " -z : Read reports from zip file(s) provided in PATH. \n"; 111 | print "\n"; 112 | print " The following optional options are allowed: \n"; 113 | print " -d : Print debug info. \n"; 114 | print " -r : Replace existing reports rather than skipping them. \n"; 115 | print " --delete : Delete processed message files (the XML is stored in the \n"; 116 | print " database for later reference). \n"; 117 | print " --info : Print out number of XML files or emails processed. \n"; 118 | print " --tls : Force TLS-Only Mode. \n"; 119 | print "\n"; 120 | } 121 | 122 | # ----------------------------------------------------------------------------- 123 | # main 124 | # ----------------------------------------------------------------------------- 125 | 126 | # Define all possible configuration options. 127 | our ($debug, $delete_reports, $delete_failed, $reports_replace, $dmarc_only, 128 | $maxsize_xml, $compress_xml, $maxsize_json, $compress_json, 129 | $dbtype, $dbname, $dbuser, $dbpass, $dbhost, $dbport, $db_tx_support, 130 | $imapserver, $imapport, $imapuser, $imappass, $imapignoreerror, $imapssl, $imaptls, 131 | $imapauth, $oauthclientid, $oauthuri, 132 | $imapdmarcfolder, $imapdmarcproc, $imapdmarcerr, 133 | $imaptlsfolder, $imaptlsproc, $imaptlserr, 134 | $tlsverify, $processInfo, 135 | $clear_token); 136 | 137 | # defaults 138 | $maxsize_xml = 50000; 139 | $maxsize_json = 50000; 140 | $dbtype = 'mysql'; 141 | $dbhost = 'localhost'; 142 | $db_tx_support = 1; 143 | $dmarc_only = 1; 144 | $reports_replace = 0; 145 | $imapauth = 'simple'; 146 | $clear_token = 0; 147 | $processInfo = 0; 148 | $oauthuri = ''; 149 | $oauthclientid = ''; 150 | 151 | # used in messages 152 | my $scriptname = 'Open Report Parser'; 153 | my $version = 'Version 0 Alpha 5'; 154 | 155 | # allowed values for the DB columns, also used to build the enum() in the 156 | # CREATE TABLE statements in checkDatabase(), in order defined here 157 | use constant ALLOWED_DISPOSITION => qw( 158 | none 159 | quarantine 160 | reject 161 | unknown 162 | ); 163 | use constant ALLOWED_DKIM_ALIGN => qw( 164 | fail 165 | pass 166 | unknown 167 | ); 168 | use constant ALLOWED_SPF_ALIGN => qw( 169 | fail 170 | pass 171 | unknown 172 | ); 173 | use constant ALLOWED_DKIMRESULT => qw( 174 | none 175 | pass 176 | fail 177 | neutral 178 | policy 179 | temperror 180 | permerror 181 | unknown 182 | ); 183 | use constant ALLOWED_SPFRESULT => qw( 184 | none 185 | neutral 186 | pass 187 | fail 188 | softfail 189 | temperror 190 | permerror 191 | unknown 192 | ); 193 | 194 | # Load script configuration options from local config file. The file is expected 195 | # to be in the current working directory. 196 | my $conf_file = 'report-parser.conf'; 197 | 198 | # Get command line options. 199 | my %options = (); 200 | use constant { TS_IMAP => 0, 201 | TS_MESSAGE_FILE => 1, 202 | TS_XML_FILE => 2, 203 | TS_MBOX_FILE => 3, 204 | TS_ZIP_FILE => 4, 205 | TS_JSON_FILE => 5 }; 206 | GetOptions( \%options, 'd', 'r', 'x', 'j', 'm', 'e', 'i', 'z', 'delete', 'info', 'c' => \$conf_file, 'clear' ); 207 | 208 | # locate conf file or die 209 | if ( -e $conf_file ) { 210 | #$conf_file = "./$conf_file"; 211 | } 212 | elsif ( -e (File::Basename::dirname($0) . "/$conf_file" ) ) { 213 | $conf_file = ( File::Basename::dirname($0) . "/$conf_file" ); 214 | } 215 | else { 216 | show_usage(); 217 | die "$scriptname: Could not read config file '$conf_file' from current working directory or path (" . File::Basename::dirname($0) . ')' 218 | } 219 | 220 | # load conf file with error handling 221 | if ( substr($conf_file, 0, 1) ne '/' and substr($conf_file, 0, 1) ne '.') { 222 | $conf_file = "./$conf_file"; 223 | } 224 | my $conf_return = do $conf_file; 225 | die "$scriptname: couldn't parse $conf_file: $@" if $@; 226 | die "$scriptname: couldn't do $conf_file: $!" unless defined $conf_return; 227 | 228 | # check config 229 | if (!defined $imapdmarcfolder ) { 230 | die "$scriptname: \$imapdmarcfolder not defined. Check config file"; 231 | } 232 | if (!defined $imapignoreerror ) { 233 | $imapignoreerror = 0; # maintain compatibility to old version 234 | } 235 | 236 | # Evaluate command line options 237 | my $source_options = 0; 238 | our $reports_source; 239 | 240 | if (exists $options{m}) { 241 | $source_options++; 242 | $reports_source = TS_MBOX_FILE; 243 | $dmarc_only = 1; 244 | } 245 | 246 | if (exists $options{x}) { 247 | $source_options++; 248 | $reports_source = TS_XML_FILE; 249 | $dmarc_only = 1; 250 | } 251 | 252 | if (exists $options{j}) { 253 | $source_options++; 254 | $reports_source = TS_JSON_FILE; 255 | $dmarc_only = -1; 256 | } 257 | 258 | if (exists $options{e}) { 259 | $source_options++; 260 | $reports_source = TS_MESSAGE_FILE; 261 | $dmarc_only = 1; 262 | } 263 | 264 | if (exists $options{i}) { 265 | $source_options++; 266 | $reports_source = TS_IMAP; 267 | } 268 | 269 | if (exists $options{z}) { 270 | $source_options++; 271 | $reports_source = TS_ZIP_FILE; 272 | $dmarc_only = 1; 273 | } 274 | 275 | if (exists $options{c}) { 276 | $source_options++; 277 | } 278 | 279 | if ($source_options > 1) { 280 | show_usage(); 281 | die "$scriptname: Only one source option can be used (-i, -x, -m, -e or -z).\n"; 282 | } 283 | elsif ($source_options == 0) { 284 | show_usage(); 285 | die "$scriptname: Please provide a source option (-i, -x, -m, -e or -z).\n"; 286 | } 287 | 288 | if ($ARGV[0]) { 289 | if ($reports_source == TS_IMAP) { 290 | show_usage(); 291 | die "$scriptname: The IMAP source option (-i) may not be used together with a PATH.\n"; 292 | } 293 | } 294 | else { 295 | if ($reports_source != TS_IMAP && $source_options == 1) { 296 | show_usage(); 297 | die "$scriptname: The provided source option requires a PATH.\n"; 298 | } 299 | } 300 | 301 | # Override config options by command line options. 302 | if (exists $options{r}) {$reports_replace = 1;} 303 | if (exists $options{d}) {$debug = 1;} 304 | if (exists $options{delete}) {$delete_reports = 1;} 305 | if (exists $options{info}) {$processInfo = 1;} 306 | if (exists $options{tls}) {$dmarc_only = -1;} 307 | if (exists $options{clear}) {$clear_token = 1;} 308 | 309 | # Cludgy, but it lets us preserve filename for dbx_postgres.pl 310 | my $dbitype = 'mysql'; 311 | $dbitype = 'Pg' if $dbtype eq 'postgres'; 312 | 313 | # Print info 314 | printInfo($scriptname."\n $version"); 315 | 316 | # Print out config if debug 317 | if ($debug) { 318 | print "$scriptname DEBUG ENABLED\n". 319 | "-- Script Options --\n\n". 320 | "Report Source: $reports_source\n". 321 | "(0: IMAP, 1: Message, 2: XML, 3: MBOX, 4: ZIP, 5: JSON)\n". 322 | "Show Processed: $processInfo\n". 323 | "Delete Reports: $delete_reports\n". 324 | "Delete Failed: $delete_failed\n". 325 | "Replace Reports: $reports_replace\n". 326 | "DMARC Only: $dmarc_only\n". 327 | "(0: DMARC\\TLS, 1: DMARC Only, -1: TLS Only)\n\n". 328 | "-- Database Options --\n\n". 329 | "DB Type: $dbtype\n". 330 | "DB Name: $dbname\n". 331 | "DB User: $dbuser\n". 332 | "DB Host/Port: $dbhost:$dbport\n". 333 | "DB TX Support: $db_tx_support\n\n". 334 | "Max XML Size: $maxsize_xml\n". 335 | "Max JSON Size: $maxsize_json\n". 336 | "Compress XML: $compress_xml\n". 337 | "Compress JSON: $compress_json\n\n". 338 | "-- IMAP Options --\n\n". 339 | "IMAP Server: $imapserver\n". 340 | "IMAP Port: $imapport\n". 341 | "TLS: $imaptls\n". 342 | "SSL: $imapssl\n". 343 | "TLS Verify: $tlsverify\n". 344 | "IMAP User: $imapuser\n". 345 | "IMAP Ignore Err: $imapignoreerror\n". 346 | "IMAP Auth: $imapauth\n". 347 | "Oauth2 URI: $oauthuri\n". 348 | "OAuth2 Client ID: $oauthclientid\n". 349 | "DMARC Folders: \n". 350 | " Reports: $imapdmarcfolder\n"; 351 | print " Processed: $imapdmarcproc\n" if defined($imapdmarcproc); 352 | print " Error: $imapdmarcerr\n" if defined($imapdmarcerr); 353 | print "TLS Folders: \n". 354 | " Reports: $imaptlsfolder\n"; 355 | print " Processed: $imaptlsproc\n" if defined($imaptlsproc); 356 | print " Error: $imaptlserr\n" if defined($imaptlserr); 357 | print "----\n\n"; 358 | } 359 | 360 | # Setup connection to database server. 361 | our %dbx; 362 | my $dbx_file = File::Basename::dirname($0) . "/dbx_$dbtype.pl"; 363 | my $dbx_return = do $dbx_file; 364 | die "$scriptname: couldn't load DB definition for type $dbtype: $@" if $@; 365 | die "$scriptname: couldn't load DB definition for type $dbtype: $!" unless defined $dbx_return; 366 | 367 | my $dbh = DBI->connect("DBI:$dbitype:database=$dbname;host=$dbhost;port=$dbport", 368 | $dbuser, 369 | $dbpass) 370 | or die "$scriptname: Cannot connect to database\n"; 371 | 372 | if ($db_tx_support) { 373 | $dbh->{AutoCommit} = 0; 374 | } 375 | 376 | checkDatabase($dbh); 377 | 378 | # Process messages based on $reports_source. 379 | if ($reports_source == TS_IMAP) { 380 | my $socketargs = ''; 381 | my $processedReport = 0; 382 | 383 | # Disable verify mode for TLS support. 384 | if ($imaptls == 1) { 385 | if ( $tlsverify == 0 ) { 386 | printDebug("use tls without verify servercert."); 387 | $socketargs = [ SSL_verify_mode => SSL_VERIFY_NONE ]; 388 | } 389 | else { 390 | printDebug("use tls with verify servercert."); 391 | $socketargs = [ SSL_verify_mode => SSL_VERIFY_PEER ]; 392 | } 393 | # The whole point of setting this socket arg is so that we don't get the nasty warning 394 | } 395 | else { 396 | printDebug("using ssl without verify servercert."); 397 | $socketargs = [ SSL_verify_mode => SSL_VERIFY_NONE ]; 398 | } 399 | 400 | printDebug("connection to $imapserver with Ssl => $imapssl, User => $imapuser, Ignoresizeerrors => $imapignoreerror"); 401 | 402 | # Setup connection to IMAP server. 403 | my $imap = Mail::IMAPClient->new( 404 | server => $imapserver, 405 | port => $imapport, 406 | ssl => $imapssl, 407 | starttls => $imaptls, 408 | debug => $debug, 409 | socketargs => $socketargs 410 | ) 411 | # module uses eval, so we use $@ instead of $! 412 | or die "$scriptname: IMAP Failure: $@\n"; 413 | 414 | # This connection is finished this way because of the tradgedy of exchange... 415 | if ($imapauth eq 'simple') { 416 | printDebug("using simple auth"); 417 | $imap->User($imapuser); 418 | $imap->Password($imappass); 419 | $imap->connect(); 420 | } 421 | elsif ($imapauth eq 'oauth2') { 422 | printDebug("using oauth2"); 423 | # get the bearer token 424 | my $oauth2token = OAuth::get_oauth($oauthuri, $oauthclientid, $dbh, $db_tx_support, $clear_token); 425 | 426 | # authenticate 427 | my $oauth_b64 = encode_base64("user=".$imapuser."\x01auth=Bearer ".$oauth2token."\x01\x01",''); 428 | printDebug("AUTHENTICATE XOAUTH2 $oauth_b64\n---\noauth token: $oauth2token"); 429 | $imap->authenticate('XOAUTH2', sub { return $oauth_b64 }) 430 | or die "$scriptname: IMAP Failure: ".$imap->LastError."\n"; 431 | } 432 | else { 433 | die "$scriptname: unsupported authentication type\n"; 434 | } 435 | 436 | # Ignore Size Errors due to issues with Exchange 437 | $imap->Ignoresizeerrors($imapignoreerror); 438 | 439 | # Set $imap to UID mode, which will force imap functions to use/return 440 | # UIDs, instead of message sequence numbers. UIDs are not allowed to 441 | # change during a session and are not allowed to be used twice. Looping 442 | # over message sequence numbers and deleting a msg in between could have 443 | # unwanted side effects. 444 | $imap->Uid(1); 445 | 446 | # How many msgs are we going to process? 447 | printInfo("Processing ". $imap->message_count($imapdmarcfolder)." messages in folder <$imapdmarcfolder>.") if $dmarc_only >= 0; 448 | printInfo("Processing ". $imap->message_count($imaptlsfolder)." messages in folder <$imaptlsfolder>.") if $dmarc_only <= 0; 449 | 450 | # Only select and search $imapdmarcfolder, if we actually 451 | # have something to do. 452 | 453 | printDebug("report processing"); 454 | 455 | if ($imap->message_count($imapdmarcfolder) && $dmarc_only >= 0) { 456 | $processedReport = processIMAP($imap, $processedReport, $imapdmarcfolder, $imapdmarcproc, $imapdmarcerr, 0); 457 | } 458 | if ($imap->message_count($imaptlsfolder) && $dmarc_only <= 0) { 459 | $processedReport = processIMAP($imap, $processedReport, $imaptlsfolder, $imaptlsproc, $imaptlserr, 1); 460 | } 461 | 462 | # We're all done with IMAP here. 463 | $imap->logout(); 464 | printInfo("Processed $processedReport emails."); 465 | 466 | } 467 | else { # TS_MESSAGE_FILE or TS_XML_FILE or TS_MBOX_FILE 468 | 469 | my $counts = 0; 470 | foreach my $a (@ARGV) { 471 | # Linux bash supports wildcard expansion BEFORE the script is 472 | # called, so here we only see a list of files. Other OS behave 473 | # different, so we should not depend on that feature: Use glob 474 | # on each argument to manually expand the argument, if possible. 475 | my @file_list = glob($a); 476 | 477 | foreach my $f (@file_list) { 478 | my $filecontent; 479 | 480 | if ($reports_source == TS_MBOX_FILE) { 481 | my $parser = Mail::Mbox::MessageParser->new({"file_name" => $f, "debug" => $debug, "enable_cache" => 0}); 482 | my $num = 0; 483 | 484 | do { 485 | $num++; 486 | $filecontent = $parser->read_next_email(); 487 | if (defined($filecontent)) { 488 | if ($dmarc_only == 1) { 489 | if (processXML(TS_MESSAGE_FILE, $filecontent, "message #$num of mbox file <$f>") & 2) { 490 | # processXML return a value with delete bit enabled 491 | warn "$scriptname: Removing message #$num from mbox file <$f> is not yet supported.\n"; 492 | } 493 | } 494 | else { 495 | if (processJSON(TS_MESSAGE_FILE, $filecontent, "message #$num of mbox file <$f>") & 2) { 496 | warn "$scriptname: Removing message #$num from mbox file <$f> is not yet supportd.\n"; 497 | } 498 | } 499 | $counts++; 500 | } 501 | } while(defined($filecontent)); 502 | 503 | } 504 | elsif ($reports_source == TS_ZIP_FILE) { 505 | # filecontent is zip file 506 | if ($dmarc_only == 1) { 507 | $filecontent = getXMLFromFile($f); 508 | if (processXML(TS_ZIP_FILE, $filecontent, "xml file <$f>") & 2) { 509 | # processXML return a value with delete bit enabled 510 | unlink($f); 511 | } 512 | } 513 | else { 514 | $filecontent = getJSONFromFile($f); 515 | if (processJSON(TS_ZIP_FILE, $filecontent, "xml file <$f>") & 2) { 516 | unlink($f); 517 | } 518 | } 519 | $counts++; 520 | } 521 | elsif (open(FILE, "<", $f)) { 522 | 523 | $filecontent = join("", ); 524 | close FILE; 525 | 526 | if ($reports_source == TS_MESSAGE_FILE) { 527 | # filecontent is a mime message with zip or xml part 528 | if ($dmarc_only == 1) { 529 | if (processXML(TS_MESSAGE_FILE, $filecontent, "message file <$f>") & 2) { 530 | # processXML return a value with delete bit enabled 531 | unlink($f); 532 | } 533 | } 534 | else { 535 | if (processJSON(TS_MESSAGE_FILE, $filecontent, "message file <$f>") & 2) { 536 | unlink($f); 537 | } 538 | } 539 | $counts++; 540 | } 541 | elsif ($reports_source == TS_XML_FILE) { 542 | # filecontent is xml file 543 | if (processXML(TS_XML_FILE, $filecontent, "xml file <$f>") & 2) { 544 | # processXML return a value with delete bit enabled 545 | unlink($f); 546 | } 547 | $counts++; 548 | } 549 | elsif ($reports_source == TS_JSON_FILE) { 550 | # filecontent is json file 551 | if (processJSON(TS_JSON_FILE, $filecontent, "json file <$f>") & 2) { 552 | unlink($f); 553 | } 554 | $counts++; 555 | } 556 | else { 557 | warn "$scriptname: Unknown reports_source <$reports_source> for file <$f>. Skipped.\n"; 558 | } 559 | 560 | } 561 | else { 562 | warn "$scriptname: Could not open file <$f>: $!. Skipped.\n"; 563 | # Could not retrieve filecontent, the skipped message 564 | # will be processed every time the script is run even if 565 | # delete_reports and delete_failed is given. The user 566 | # has to look at the actual file. 567 | } 568 | } 569 | } 570 | printInfo("$scriptname: Processed $counts messages(s)."); 571 | } 572 | 573 | # ----------------------------------------------------------------------------- 574 | # subroutines 575 | # ----------------------------------------------------------------------------- 576 | 577 | sub printDebug { 578 | my $message = shift; 579 | print "\n\n--- DEBUG ---\n". 580 | " $message". 581 | "\n-------------\n" if $debug; 582 | } 583 | 584 | # ----------------------------------------------------------------------------- 585 | 586 | sub printInfo { 587 | my $message = shift; 588 | print "\n\n--- DEBUG ---\n" if $debug; 589 | print " $message\n" if $debug || $processInfo; 590 | print "-------------\n" if $debug; 591 | } 592 | 593 | # ----------------------------------------------------------------------------- 594 | 595 | sub processIMAP { 596 | my $imap = shift; 597 | my $processedReport = shift; 598 | my $imapfolder = shift; 599 | my $imapproc = shift; 600 | my $imaperr = shift; 601 | my $type = shift; 602 | 603 | printDebug("processing <$imapfolder>."); 604 | 605 | # Select the mailbox to get messages from. 606 | $imap->select($imapfolder) 607 | or die "$scriptname: IMAP Select Error: $!"; 608 | 609 | # Store each message as an array element. 610 | my @msgs = $imap->search('ALL') 611 | or die "$scriptname: Couldn't get all messages\n"; 612 | 613 | # Loop through IMAP messages. 614 | foreach my $msg (@msgs) { 615 | 616 | my $processResult; 617 | if ($type == 0) { 618 | $processResult = processXML(TS_MESSAGE_FILE, $imap->message_string($msg), "IMAP message with UID #".$msg); 619 | } 620 | else { 621 | $processResult = processJSON(TS_MESSAGE_FILE, $imap->message_string($msg), "IMAP message with UID #".$msg); 622 | } 623 | $processedReport++; 624 | if ($processResult & 4) { 625 | # processXML/JSON returned a value with database error bit enabled, do nothing at all! 626 | if ($imaperr) { 627 | # if we can, move to error folder 628 | moveToImapFolder($imap, $msg, $imaperr); 629 | } 630 | else { 631 | # do nothing at all 632 | next; 633 | } 634 | } 635 | elsif ($processResult & 2) { 636 | # processXML/JSON return a value with delete bit enabled. 637 | $imap->delete_message($msg) 638 | or warn "$scriptname: Could not delete IMAP message. [$@]\n"; 639 | } 640 | elsif ($imapproc) { 641 | if ($processResult & 1 || !$imaperr) { 642 | # processXML/JSON processed the XML OK, or it failed and there is no error imap folder 643 | moveToImapFolder($imap, $msg, $imapproc); 644 | } 645 | elsif ($imaperr) { 646 | # processXML/JSON failed and error folder set 647 | moveToImapFolder($imap, $msg, $imaperr); 648 | } 649 | } 650 | elsif ($imaperr && !($processResult & 1)) { 651 | # processXML/JSON failed, error imap folder set, but imapdmarcproc unset. An unlikely setup, but still... 652 | moveToImapFolder($imap, $msg, $imaperr); 653 | } 654 | } 655 | 656 | # Expunge and close the folder. 657 | $imap->expunge($imapfolder); 658 | $imap->close($imapfolder); 659 | return $processedReport; 660 | } 661 | 662 | # ----------------------------------------------------------------------------- 663 | 664 | sub moveToImapFolder { 665 | my $imap = $_[0]; 666 | my $msg = $_[1]; 667 | my $imapfolder = $_[2]; 668 | 669 | print "Moving (copy and delete) IMAP message file to IMAP folder: $imapfolder\n" if $debug; 670 | 671 | # Try to create $imapfolder, if it does not exist. 672 | if (!$imap->exists($imapfolder)) { 673 | $imap->create($imapfolder) 674 | or warn "$scriptname: Could not create IMAP folder: $imapfolder.\n"; 675 | } 676 | 677 | # Try to move the message to $imapfolder. 678 | my $newid = $imap->copy($imapfolder, [ $msg ]); 679 | if (!$newid) { 680 | warn "$scriptname: Error on moving (copy and delete) processed IMAP message: Could not COPY message to IMAP folder: <$imapfolder>!\n"; 681 | warn "$scriptname: Messsage will not be moved/deleted. [$@]\n"; 682 | } 683 | else { 684 | $imap->delete_message($msg) 685 | or do { 686 | warn "$scriptname: Error on moving (copy and delete) processed IMAP message: Could not DELETE message\n"; 687 | warn "$scriptname: after copying it to <$imapfolder>. [$@]\n"; 688 | } 689 | } 690 | } 691 | 692 | # ----------------------------------------------------------------------------- 693 | 694 | sub processXML { 695 | my ($type, $filecontent, $f) = (@_); 696 | 697 | if ($debug) { 698 | print "\n"; 699 | print "----------------------------------------------------------------\n"; 700 | print "Processing $f \n"; 701 | print "----------------------------------------------------------------\n"; 702 | print "Type: $type\n"; 703 | print "FileContent: $filecontent\n"; 704 | print "MSG: $f\n"; 705 | print "----------------------------------------------------------------\n"; 706 | } 707 | 708 | my $xml; #TS_XML_FILE or TS_MESSAGE_FILE 709 | if ($type == TS_MESSAGE_FILE) {$xml = getXMLFromMessage($filecontent);} 710 | elsif ($type == TS_ZIP_FILE) {$xml = $filecontent;} 711 | else {$xml = getXMLFromXMLString($filecontent);} 712 | 713 | # If !$xml, the file/mail is probably not a DMARC report. 714 | # So do not storeXMLInDatabase. 715 | if ($xml && storeXMLInDatabase($xml) <= 0) { 716 | # If storeXMLInDatabase returns false, there was some sort 717 | # of database storage failure and we MUST NOT delete the 718 | # file, because it has not been pushed into the database. 719 | # The user must investigate this issue. 720 | warn "$scriptname: Skipping $f due to database errors.\n"; 721 | return 5; #xml ok(1), but database error(4), thus no delete (!2) 722 | } 723 | 724 | # Delete processed message, if the --delete option 725 | # is given. Failed reports are only deleted, if delete_failed is given. 726 | if ($delete_reports && ($xml || $delete_failed)) { 727 | if ($xml) { 728 | printDebug("Removing after report has been processed."); 729 | return 3; #xml ok (1), delete file (2) 730 | } 731 | else { 732 | # A mail which does not look like a DMARC report 733 | # has been processed and should now be deleted. 734 | # Print its content so it gets send as cron 735 | # message, so the user can still investigate. 736 | warn "$scriptname: The $f does not seem to contain a valid DMARC report. Skipped and Removed. Content:\n"; 737 | warn $filecontent."\n"; 738 | return 2; #xml not ok (!1), delete file (2) 739 | } 740 | } 741 | 742 | if ($xml) { 743 | return 1; 744 | } 745 | else { 746 | warn "$scriptname: The $f does not seem to contain a valid DMARC report. Skipped.\n"; 747 | return 0; 748 | } 749 | } 750 | 751 | # ----------------------------------------------------------------------------- 752 | 753 | # Walk through a mime message and return a reference to the XML data containing 754 | # the fields of the first ZIPed XML file embedded into the message. The XML 755 | # itself is not checked to be a valid DMARC report. 756 | sub getXMLFromMessage { 757 | printDebug("getting XML from message"); 758 | my ($message) = (@_); 759 | 760 | # fixup type in trustwave SEG mails 761 | $message =~ s/ContentType:/Content-Type:/; 762 | 763 | my $parser = new MIME::Parser; 764 | $parser->output_dir("/tmp"); 765 | $parser->filer->ignore_filename(1); 766 | my $ent = $parser->parse_data($message); 767 | 768 | my $body = $ent->bodyhandle; 769 | my $mtype = $ent->mime_type; 770 | my $subj = decode_mimewords($ent->get('subject')); 771 | chomp($subj); # Subject always contains a \n. 772 | 773 | printDebug("Subject: $subj\n". 774 | " MimeType: $mtype"); 775 | 776 | my $location; 777 | my $isgzip = 0; 778 | 779 | if(lc $mtype eq "application/zip") { 780 | printDebug("This is a ZIP file"); 781 | 782 | $location = $body->path; 783 | 784 | } 785 | elsif (lc $mtype eq "application/gzip" or lc $mtype eq "application/x-gzip") { 786 | printDebug("This is a GZIP file"); 787 | 788 | $location = $body->path; 789 | $isgzip = 1; 790 | 791 | } 792 | elsif (lc $mtype =~ "multipart/") { 793 | # At the moment, nease.net messages are multi-part, so we need 794 | # to breakdown the attachments and find the zip. 795 | printDebug("This is a multipart attachment"); 796 | #print Dumper($ent->parts); 797 | 798 | my $num_parts = $ent->parts; 799 | for (my $i=0; $i < $num_parts; $i++) { 800 | my $part = $ent->parts($i); 801 | 802 | # Find a zip file to work on... 803 | if(lc $part->mime_type eq "application/gzip" or lc $part->mime_type eq "application/x-gzip") { 804 | $location = $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}; 805 | $isgzip = 1; 806 | printDebug("$location"); 807 | last; # of parts 808 | } 809 | elsif(lc $part->mime_type eq "application/x-zip-compressed" 810 | or $part->mime_type eq "application/zip") { 811 | 812 | $location = $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}; 813 | printDebug("$location"); 814 | } 815 | elsif(lc $part->mime_type eq "application/octet-stream") { 816 | $location = $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}; 817 | $isgzip = 1 if $location =~ /\.gz$/; 818 | printDebug("$location"); 819 | } 820 | else { 821 | # Skip the attachment otherwise. 822 | printDebug("Skipped an unknown attachment (".lc $part->mime_type.")"); 823 | next; # of parts 824 | } 825 | } 826 | } 827 | else { 828 | ## Clean up dangling mime parts in /tmp of messages without ZIP. 829 | my $num_parts = $ent->parts; 830 | for (my $i=0; $i < $num_parts; $i++) { 831 | if ($debug) { 832 | if ($ent->parts($i)->{ME_Bodyhandle} && $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}) { 833 | printDebug($ent->parts($i)->{ME_Bodyhandle}->{MB_Path}); 834 | } 835 | else { 836 | printDebug("undef"); 837 | } 838 | } 839 | if($ent->parts($i)->{ME_Bodyhandle}) {$ent->parts($i)->{ME_Bodyhandle}->purge;} 840 | } 841 | } 842 | 843 | 844 | # If a ZIP has been found, extract XML and parse it. 845 | my $xml; 846 | printDebug("body is in " . $location) if defined($location); 847 | $xml = getXMLFromZip($location,$isgzip); 848 | if($body) {$body->purge;} 849 | if($ent) {$ent->purge;} 850 | return $xml; 851 | } 852 | 853 | # ----------------------------------------------------------------------------- 854 | 855 | sub getXMLFromFile { my $filename = $_[0]; 856 | printDebug("getting XML from file"); 857 | my $mtype = mimetype($filename); 858 | 859 | if ($debug) { 860 | print "Filename: $filename, MimeType: $mtype\n"; 861 | } 862 | 863 | my $isgzip = 0; 864 | 865 | if(lc $mtype eq "application/zip") { 866 | if ($debug) { 867 | print "This is a ZIP file \n"; 868 | } 869 | } 870 | elsif (lc $mtype eq "application/gzip" or lc $mtype eq "application/x-gzip") { 871 | if ($debug) { 872 | print "This is a GZIP file \n"; 873 | } 874 | 875 | $isgzip = 1; 876 | } 877 | else { 878 | if ($debug) { 879 | print "This is not an archive file \n"; 880 | } 881 | } 882 | 883 | # If a ZIP has been found, extract XML and parse it. 884 | my $xml = getXMLFromZip($filename,$isgzip); 885 | return $xml; 886 | } 887 | 888 | # ----------------------------------------------------------------------------- 889 | 890 | sub getXMLFromZip { 891 | printDebug("getting XML from ZIP"); 892 | my $filename = shift; 893 | my $isgzip = shift; 894 | 895 | my $xml; 896 | if (defined($filename)) { 897 | # Open the zip file and process the XML contained inside. 898 | my $unzip = ""; 899 | if ($isgzip) { 900 | open(XML, "<:gzip", $filename) 901 | or $unzip = "gzip"; 902 | 903 | # check to see if the mimetype was incorrectly set to gzip *cough mimecast* 904 | if ($unzip eq "gzip") { 905 | printDebug("gzip failed, checking if incorrect mime type"); 906 | # incorrect mimetype with incorrect file extension seems to manifest as a .dat 907 | # so let's check for that 908 | my $ext = ''; 909 | if ($filename =~ /\.([^.]+)$/) { 910 | print "extension: $1" if $debug; 911 | $ext = $1; 912 | } 913 | else { 914 | warn "$scriptname: Could not find extension for (<$filename>)! \n"; 915 | } 916 | 917 | # if it's a dat file, then run this process again, but with $isgzip set to 0 918 | if ($ext eq "dat") { 919 | printDebug("Trying again using unzip"); 920 | $xml = getXMLFromZip($filename,0); 921 | 922 | # if it fails again, it'll warn, if not, it'll return the correct xml 923 | return $xml; 924 | } 925 | } 926 | } 927 | else { 928 | open(XML, "-|", "unzip", "-p", $filename) 929 | or $unzip = "unzip"; # Will never happen. 930 | 931 | # Sadly unzip -p never fails, but we can check if the 932 | # filehandle points to an empty file and pretend it did 933 | # not open/failed. 934 | if (eof XML) { 935 | $unzip = "unzip"; 936 | } 937 | } 938 | 939 | # Read XML if possible (if open) 940 | if ($unzip eq "") { 941 | $xml = getXMLFromXMLString(join("", )); 942 | if (!$xml) { 943 | warn "$scriptname: The XML found in ZIP file (<$filename>) does not seem to be valid XML! \n"; 944 | } 945 | close XML; 946 | } 947 | else { 948 | warn "$scriptname: Failed to $unzip ZIP file (<$filename>)! \n"; 949 | close XML; 950 | } 951 | } 952 | else { 953 | warn "$scriptname: Could not find an <$filename>! \n"; 954 | } 955 | 956 | return $xml; 957 | } 958 | 959 | # ----------------------------------------------------------------------------- 960 | 961 | sub getXMLFromXMLString { 962 | printDebug("getting XML from string"); 963 | my $raw_xml = $_[0]; 964 | 965 | eval { 966 | my $xs = XML::Simple->new(); 967 | my $ref = $xs->XMLin($raw_xml, SuppressEmpty => ''); 968 | $ref->{'raw_xml'} = $raw_xml; 969 | 970 | return $ref; 971 | } 972 | or do { 973 | return undef; 974 | } 975 | } 976 | 977 | # ----------------------------------------------------------------------------- 978 | 979 | # Extract fields from the XML report data hash and store them into the database. 980 | # return 1 when ok, 0, for serious error and -1 for minor errors 981 | sub storeXMLInDatabase { 982 | printDebug("storing XML in database"); 983 | my $xml = $_[0]; # $xml is a reference to the xml data 984 | 985 | my $from = $xml->{'report_metadata'}->{'date_range'}->{'begin'}; 986 | my $to = $xml->{'report_metadata'}->{'date_range'}->{'end'}; 987 | my $org = $xml->{'report_metadata'}->{'org_name'}; 988 | my $id = $xml->{'report_metadata'}->{'report_id'}; 989 | my $email = $xml->{'report_metadata'}->{'email'}; 990 | my $extra = $xml->{'report_metadata'}->{'extra_contact_info'}; 991 | 992 | my $domain = undef; 993 | my $policy_adkim = undef; 994 | my $policy_aspf = undef; 995 | my $policy_p = undef; 996 | my $policy_sp = undef; 997 | my $policy_pct = undef; 998 | 999 | if (ref $xml->{'policy_published'} eq "HASH") { 1000 | $domain = $xml->{'policy_published'}->{'domain'}; 1001 | $policy_adkim = $xml->{'policy_published'}->{'adkim'}; 1002 | $policy_aspf = $xml->{'policy_published'}->{'aspf'}; 1003 | $policy_p = $xml->{'policy_published'}->{'p'}; 1004 | $policy_sp = $xml->{'policy_published'}->{'sp'}; 1005 | $policy_pct = $xml->{'policy_published'}->{'pct'}; 1006 | } 1007 | else { 1008 | $domain = $xml->{'policy_published'}[0]->{'domain'}; 1009 | $policy_adkim = $xml->{'policy_published'}[0]->{'adkim'}; 1010 | $policy_aspf = $xml->{'policy_published'}[0]->{'aspf'}; 1011 | $policy_p = $xml->{'policy_published'}[0]->{'p'}; 1012 | $policy_sp = $xml->{'policy_published'}[0]->{'sp'}; 1013 | $policy_pct = $xml->{'policy_published'}[0]->{'pct'}; 1014 | } 1015 | 1016 | my $record = $xml->{'record'}; 1017 | if ( ! defined($record) ) { 1018 | warn "$scriptname: $org: $id: No records in report. Skipped.\n"; 1019 | return 0; 1020 | } 1021 | 1022 | # see if already stored 1023 | my $sth = $dbh->prepare(qq{SELECT org, serial FROM report WHERE reportid=?}); 1024 | $sth->execute($id); 1025 | while ( my ($xorg,$sid) = $sth->fetchrow_array() ) 1026 | { 1027 | if ($reports_replace) { 1028 | # $sid is the serial of a report with reportid=$id 1029 | # Remove this $sid from rptrecord and report table, but 1030 | # try to continue on failure rather than skipping. 1031 | print "$scriptname: $org: $id: Replacing data.\n"; 1032 | $dbh->do(qq{DELETE from rptrecord WHERE serial=?}, undef, $sid); 1033 | if ($dbh->errstr) { 1034 | warn "$scriptname: $org: $id: Cannot remove report data from database. Try to continue.\n"; 1035 | } 1036 | $dbh->do(qq{DELETE from report WHERE serial=?}, undef, $sid); 1037 | if ($dbh->errstr) { 1038 | warn "$scriptname: $org: $id: Cannot remove report from database. Try to continue.\n"; 1039 | } 1040 | } 1041 | else { 1042 | print "$scriptname: $org: $id: Already have report, skipped\n"; 1043 | # Do not store in DB, but return true, so the message can 1044 | # be moved out of the way, if configured to do so. 1045 | return 1; 1046 | } 1047 | } 1048 | 1049 | my $sql = qq{INSERT INTO report (mindate,maxdate,domain,org,reportid,email,extra_contact_info,policy_adkim, policy_aspf, policy_p, policy_sp, policy_pct, raw_xml) 1050 | VALUES ($dbx{epoch_to_timestamp_fn}(?),$dbx{epoch_to_timestamp_fn}(?),?,?,?,?,?,?,?,?,?,?,?)}; 1051 | my $storexml = $xml->{'raw_xml'}; 1052 | if ($compress_xml) { 1053 | my $gzipdata; 1054 | if(!gzip(\$storexml => \$gzipdata)) { 1055 | warn "$scriptname: $org: $id: Cannot add gzip XML to database ($GzipError). Skipped.\n"; 1056 | rollback($dbh); 1057 | return 0; 1058 | $storexml = ""; 1059 | } 1060 | else { 1061 | $storexml = encode_base64($gzipdata, ""); 1062 | } 1063 | } 1064 | if (length($storexml) > $maxsize_xml) { 1065 | warn "$scriptname: $org: $id: Skipping storage of large XML (".length($storexml)." bytes) as defined in config file.\n"; 1066 | $storexml = ""; 1067 | } 1068 | $dbh->do($sql, undef, $from, $to, $domain, $org, $id, $email, $extra, $policy_adkim, $policy_aspf, $policy_p, $policy_sp, $policy_pct, $storexml); 1069 | if ($dbh->errstr) { 1070 | warn "$scriptname: $org: $id: Cannot add report to database. Skipped.\n"; 1071 | return 0; 1072 | } 1073 | 1074 | my $serial = $dbh->last_insert_id(undef, undef, 'report', undef); 1075 | printDebug("serial $serial"); 1076 | 1077 | sub dorow($$$$) { 1078 | my ($serial,$recp,$org,$id) = @_; 1079 | my %r = %$recp; 1080 | 1081 | my $ip = $r{'row'}->{'source_ip'}; 1082 | if ( $ip eq '' ) { 1083 | warn "$scriptname: $org: $id: source_ip is empty. Skipped.\n"; 1084 | rollback($dbh); 1085 | return 0; 1086 | } 1087 | my $count = $r{'row'}->{'count'}; 1088 | my $disp = $r{'row'}->{'policy_evaluated'}->{'disposition'}; 1089 | if ( ! grep { $_ eq $disp } ALLOWED_DISPOSITION ) { 1090 | $disp = 'unknown'; 1091 | }; 1092 | # some reports don't have dkim/spf, "unknown" is default for these 1093 | my $dkim_align = $r{'row'}->{'policy_evaluated'}->{'dkim'}; 1094 | if ( ! grep { $_ eq $dkim_align } ALLOWED_DKIM_ALIGN ) { 1095 | $dkim_align = 'unknown'; 1096 | }; 1097 | my $spf_align = $r{'row'}->{'policy_evaluated'}->{'spf'}; 1098 | if ( ! grep { $_ eq $spf_align } ALLOWED_SPF_ALIGN ) { 1099 | $spf_align = 'unknown'; 1100 | }; 1101 | 1102 | my $identifier_hfrom = $r{'identifiers'}->{'header_from'}; 1103 | 1104 | my ($dkim, $dkimresult, $spf, $spfresult, $reason); 1105 | if(ref $r{'auth_results'} ne "HASH"){ 1106 | warn "$scriptname: $org: $id: Report has no auth_results data. Skipped.\n"; 1107 | return 0; 1108 | } 1109 | my $rp = $r{'auth_results'}->{'dkim'}; 1110 | if(ref $rp eq "HASH") { 1111 | $dkim = $rp->{'domain'}; 1112 | $dkim = undef if ref $dkim eq "HASH"; 1113 | $dkimresult = $rp->{'result'}; 1114 | } 1115 | else { # array, i.e. multiple dkim results (usually from multiple domains) 1116 | # glom sigs together 1117 | $dkim = join '/',map { my $d = $_->{'domain'}; ref $d eq "HASH"?"": $d } @$rp; 1118 | # report results 1119 | my $rp_len = scalar(@$rp); 1120 | for ( my $i=0; $i < $rp_len; $i++ ) { 1121 | if ( $rp->[$i]->{'result'} eq "pass" ) { 1122 | # If any one dkim result is a "pass", this should yield an overall "pass" and immediately exit the for loop, ignoring any remaing results 1123 | # See 1124 | # RFC 6376, DomainKeys Identified Mail (DKIM) Signatures 1125 | # Section 4.2: https://tools.ietf.org/html/rfc6376#section-4.2 and 1126 | # Section 6.1: https://tools.ietf.org/html/rfc6376#section-6.1 1127 | # And the GitHub issues at 1128 | # https://github.com/techsneeze/dmarcts-report-viewer/issues/47 1129 | # https://github.com/techsneeze/dmarcts-report-parser/pull/78 1130 | $dkimresult = "pass"; 1131 | last; 1132 | } 1133 | else { 1134 | for ( my $j=$i+1; $j < $rp_len; $j++ ) { 1135 | if ( $rp->[$i]->{'result'} eq $rp->[$j]->{'result'} ) { 1136 | # Compare each dkim result to the next one to see if all of the dkim results are the same. 1137 | # If all of the dkim results are the same, that will be the overall result. 1138 | # If any of them are different, and don't contain a "pass" result, then $dkimresult will be empty 1139 | $dkimresult = $rp->[0]->{'result'}; 1140 | } else { 1141 | $dkimresult = 'unknown'; 1142 | } 1143 | } 1144 | } 1145 | } 1146 | } 1147 | if ( ! defined($dkimresult) || ! grep { $_ eq $dkimresult } ALLOWED_DKIMRESULT ) { 1148 | $dkimresult = 'unknown'; 1149 | }; 1150 | 1151 | $rp = $r{'auth_results'}->{'spf'}; 1152 | if(ref $rp eq "HASH") { 1153 | $spf = $rp->{'domain'}; 1154 | $spf = undef if ref $spf eq "HASH"; 1155 | $spfresult = $rp->{'result'}; 1156 | } 1157 | else { # array, i.e. multiple dkim results (usually from multiple domains) 1158 | # glom sigs together 1159 | $spf = join '/',map { my $d = $_->{'domain'}; ref $d eq "HASH"?"": $d } @$rp; 1160 | # report results 1161 | my $rp_len = scalar(@$rp); 1162 | for ( my $i=0; $i < $rp_len; $i++ ) { 1163 | if ( $rp->[$i]->{'result'} eq "pass" ) { 1164 | # If any one spf result is a "pass", this should yield an overall "pass" and immediately exit the for loop, ignoring any remaing results 1165 | $spfresult = "pass"; 1166 | last; 1167 | } 1168 | else { 1169 | for ( my $j=$i+1; $j < $rp_len; $j++ ) { 1170 | if ( $rp->[$i]->{'result'} eq $rp->[$j]->{'result'} ) { 1171 | # Compare each spf result to the next one to see if all of the spf results are the same. 1172 | # If all of the spf results are the same, that will be the overall result. 1173 | # If any of them are different, and don't contain a "pass" result, then $spfresult will be empty 1174 | $spfresult = $rp->[0]->{'result'}; 1175 | } 1176 | else { 1177 | $spfresult = 'unknown'; 1178 | } 1179 | } 1180 | } 1181 | } 1182 | } 1183 | if ( ! defined($spfresult) || ! grep { $_ eq $spfresult } ALLOWED_SPFRESULT ) { 1184 | $spfresult = 'unknown'; 1185 | }; 1186 | 1187 | $rp = $r{'row'}->{'policy_evaluated'}->{'reason'}; 1188 | if(ref $rp eq "HASH") { 1189 | $reason = $rp->{'type'}; 1190 | } 1191 | else { 1192 | $reason = join '/',map { $_->{'type'} } @$rp; 1193 | } 1194 | #print "ip=$ip, count=$count, disp=$disp, r=$reason,"; 1195 | #print "dkim=$dkim/$dkimresult, spf=$spf/$spfresult\n"; 1196 | 1197 | # What type of IP address? 1198 | my ($nip, $iptype, $ipval); 1199 | printDebug("ip=$ip"); 1200 | 1201 | if($nip = inet_pton(AF_INET, $ip)) { 1202 | $ipval = unpack "N", $nip; 1203 | $iptype = "ip"; 1204 | } 1205 | elsif($nip = inet_pton(AF_INET6, $ip)) { 1206 | $ipval = $dbx{to_hex_string}($nip); 1207 | $iptype = "ip6"; 1208 | } 1209 | else { 1210 | warn "$scriptname: $org: $id: ??? mystery ip $ip\n"; 1211 | rollback($dbh); 1212 | return 0; 1213 | } 1214 | 1215 | $dbh->do(qq{INSERT INTO rptrecord (serial,$iptype,rcount,disposition,spf_align,dkim_align,reason,dkimdomain,dkimresult,spfdomain,spfresult,identifier_hfrom) 1216 | VALUES (?,$ipval,?,?,?,?,?,?,?,?,?,?)},undef,$serial,$count,$disp,$spf_align,$dkim_align,$reason,$dkim,$dkimresult,$spf,$spfresult,$identifier_hfrom); 1217 | if ($dbh->errstr) { 1218 | warn "$scriptname: $org: $id: Cannot add report data to database. Skipped.\n"; 1219 | rollback($dbh); 1220 | return 0; 1221 | } 1222 | return 1; 1223 | } 1224 | 1225 | my $res = 1; 1226 | if(ref $record eq "HASH") { 1227 | printDebug("single record"); 1228 | $res = -1 if !dorow($serial,$record,$org,$id); 1229 | } 1230 | elsif(ref $record eq "ARRAY") { 1231 | printDebug("multi record"); 1232 | foreach my $row (@$record) { 1233 | $res = -1 if !dorow($serial,$row,$org,$id); 1234 | } 1235 | } 1236 | else { 1237 | warn "$scriptname: $org: $id: mystery type " . ref($record) . "\n"; 1238 | } 1239 | 1240 | if ($res <= 0) { 1241 | printDebug("Result $res XML: $xml->{raw_xml}"); 1242 | } 1243 | 1244 | if ($res <= 0) { 1245 | if ($db_tx_support) { 1246 | warn "$scriptname: $org: $id: Cannot add records to rptrecord. Rolling back DB transaction.\n"; 1247 | rollback($dbh); 1248 | } 1249 | else { 1250 | warn "$scriptname: $org: $id: errors while adding to rptrecord, serial $serial records likely obsolete.\n"; 1251 | } 1252 | } 1253 | else { 1254 | if ($db_tx_support) { 1255 | $dbh->commit; 1256 | if ($dbh->errstr) { 1257 | warn "$scriptname: $org: $id: Cannot commit transaction.\n"; 1258 | } 1259 | } 1260 | } 1261 | return $res; 1262 | } 1263 | 1264 | # ----------------------------------------------------------------------------- 1265 | 1266 | sub processJSON { 1267 | my ($type, $filecontent, $f) = (@_); 1268 | 1269 | if ($debug) { 1270 | print "\n"; 1271 | print "----------------------------------------------------------------\n"; 1272 | print "Processing $f \n"; 1273 | print "----------------------------------------------------------------\n"; 1274 | print "Type: $type\n"; 1275 | print "FileContent: $filecontent\n"; 1276 | print "MSG: $f\n"; 1277 | print "----------------------------------------------------------------\n"; 1278 | } 1279 | 1280 | my $json; #TS_JSON_FILE or TS_MESSAGE_FILE 1281 | if ($type == TS_MESSAGE_FILE) { $json = getJSONFromMessage($filecontent); } 1282 | elsif ($type == TS_ZIP_FILE) { $json = getJSONFromFile($filecontent); } 1283 | else { $json = getJSONFromString($filecontent); } 1284 | 1285 | # If !$json, the file/mail is probably not a TLS report. 1286 | # So do not storeJSONInDatabase. 1287 | if ($json && storeJSONInDatabase($json) <= 0) { 1288 | # If storeJSONInDatabase returns false, there was some sort 1289 | # of database storage failure and we MUST NOT delete the 1290 | # file, because it has not been pushed into the database. 1291 | # The user must investigate this issue. 1292 | warn "$scriptname: Skipping $f due to database errors.\n"; 1293 | return 5; #json ok(1), but database error(4), thus no delete (!2) 1294 | } 1295 | 1296 | # Delete processed message, if the --delete option 1297 | # is given. Failed reports are only deleted, if delete_failed is given. 1298 | if ($delete_reports && ($json || $delete_failed)) { 1299 | if ($json) { 1300 | print "Removing after report has been processed.\n" if $debug; 1301 | return 3; #json ok (1), delete file (2) 1302 | } 1303 | else { 1304 | # A mail which does not look like a TLS report 1305 | # has been processed and should now be deleted. 1306 | # Print its content so it gets send as cron 1307 | # message, so the user can still investigate. 1308 | warn "$scriptname: The $f does not seem to contain a valid TLS report. Skipped and Removed. Content:\n"; 1309 | warn $filecontent."\n"; 1310 | return 2; #json not ok (!1), delete file (2) 1311 | } 1312 | } 1313 | 1314 | if ($json) { 1315 | return 1; 1316 | } 1317 | else { 1318 | warn "$scriptname: The $f does not seem to contain a valid TLS report. Skipped.\n"; 1319 | return 0; 1320 | } 1321 | } 1322 | 1323 | # ----------------------------------------------------------------------------- 1324 | 1325 | sub getJSONFromMessage { 1326 | my ($message) = (@_); 1327 | 1328 | # fixup type in trustwave SEG mails 1329 | $message =~ s/ContentType:/Content-Type:/; 1330 | 1331 | my $parser = new MIME::Parser; 1332 | $parser->output_dir("/tmp"); 1333 | $parser->filer->ignore_filename(1); 1334 | my $ent = $parser->parse_data($message); 1335 | 1336 | my $body = $ent->bodyhandle; 1337 | my $mtype = $ent->mime_type; 1338 | my $subj = decode_mimewords($ent->get('subject')); 1339 | chomp($subj); # Subject always contains a \n. 1340 | 1341 | printDebug("Subject: $subj\n". 1342 | " MimeType: $mtype"); 1343 | 1344 | my $location; 1345 | my $isgzip = 0; 1346 | 1347 | if (lc $mtype eq "application/tlsrpt+gzip" or lc $mtype eq "application/tlsrpt+x-gzip") { 1348 | printDebug("This is a GZIP file"); 1349 | 1350 | $location = $body->path; 1351 | $isgzip = 1; 1352 | 1353 | } 1354 | elsif (lc $mtype =~ "multipart/") { 1355 | # At the moment, nease.net messages are multi-part, so we need 1356 | # to breakdown the attachments and find the zip. 1357 | printDebug("This is a multipart attachment"); 1358 | #print Dumper($ent->parts); 1359 | 1360 | my $num_parts = $ent->parts; 1361 | for (my $i=0; $i < $num_parts; $i++) { 1362 | my $part = $ent->parts($i); 1363 | 1364 | # Find a zip file to work on... 1365 | if(lc $part->mime_type eq "application/tlsrpt+gzip" or lc $part->mime_type eq "application/tlsrpt+x-gzip") { 1366 | $location = $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}; 1367 | $isgzip = 1; 1368 | printDebug("$location"); 1369 | last; # of parts 1370 | } 1371 | elsif(lc $part->mime_type eq "application/octet-stream") { 1372 | $location = $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}; 1373 | $isgzip = 1 if $location =~ /\.gz$/; 1374 | printDebug("$location"); 1375 | } 1376 | else { 1377 | # Skip the attachment otherwise. 1378 | printDebug("Skipped an unknown attachment (".lc $part->mime_type.")"); 1379 | next; # of parts 1380 | } 1381 | } 1382 | } 1383 | else { 1384 | ## Clean up dangling mime parts in /tmp of messages without ZIP. 1385 | my $num_parts = $ent->parts; 1386 | for (my $i=0; $i < $num_parts; $i++) { 1387 | if ($debug) { 1388 | if ($ent->parts($i)->{ME_Bodyhandle} && $ent->parts($i)->{ME_Bodyhandle}->{MB_Path}) { 1389 | printDebug($ent->parts($i)->{ME_Bodyhandle}->{MB_Path}); 1390 | } 1391 | else { 1392 | printDebug("undef"); 1393 | } 1394 | } 1395 | if($ent->parts($i)->{ME_Bodyhandle}) {$ent->parts($i)->{ME_Bodyhandle}->purge;} 1396 | } 1397 | } 1398 | 1399 | 1400 | # If a ZIP has been found, extract XML and parse it. 1401 | my $json; 1402 | if (defined($location)) { 1403 | printDebug("body is in " . $location); 1404 | } 1405 | $json = getJSONFromZip($location,$isgzip); 1406 | if($body) {$body->purge;} 1407 | if($ent) {$ent->purge;} 1408 | return $json; 1409 | } 1410 | 1411 | # ----------------------------------------------------------------------------- 1412 | 1413 | sub getJSONFromFile { 1414 | printDebug("getting JSON from File"); 1415 | my $filename = $_[0]; 1416 | my $mtype = mimetype($filename); 1417 | 1418 | printDebug("Filename: $filename, MimeType: $mtype"); 1419 | 1420 | my $isgzip = 0; 1421 | 1422 | if (lc $mtype eq "application/tlsrpt+gzip" or lc $mtype eq "application/tlsrpt+x-gzip") { 1423 | printDebug("This is a GZIP file"); 1424 | 1425 | $isgzip = 1; 1426 | } 1427 | else { 1428 | printDebug("This is not an archive file"); 1429 | } 1430 | 1431 | # If a ZIP has been found, extract XML and parse it. 1432 | my $json = getJSONFromZip($filename,$isgzip); 1433 | return $json; 1434 | } 1435 | 1436 | # ----------------------------------------------------------------------------- 1437 | 1438 | sub getJSONFromZip { 1439 | printDebug("getting JSON from ZIP"); 1440 | my $filename = shift; 1441 | my $isgzip = shift; 1442 | 1443 | my $json; 1444 | if (defined($filename)) { 1445 | # Open the zip file and process the XML contained inside. 1446 | my $unzip = ""; 1447 | if ($isgzip) { 1448 | open(JSON, "<:gzip", $filename) 1449 | or $unzip = "gzip"; 1450 | 1451 | # check to see if the mimetype was incorrectly set to gzip *cough mimecast* 1452 | if ($unzip eq "gzip") { 1453 | printDebug("gzip failed, checking if incorrect mime type"); 1454 | # incorrect mimetype with incorrect file extension seems to manifest as a .dat 1455 | # so let's check for that 1456 | my $ext = ''; 1457 | if ($filename =~ /\.([^.]+)$/) { 1458 | print "extension: $1" if $debug; 1459 | $ext = $1; 1460 | } 1461 | else { 1462 | warn "$scriptname: Could not find extension for (<$filename>)! \n"; 1463 | } 1464 | 1465 | # if it's a dat file, then run this process again, but with $isgzip set to 0 1466 | if ($ext eq "dat") { 1467 | printDebug("Trying again using unzip"); 1468 | $json = getJSONFromZip($filename,0); 1469 | 1470 | # if it fails again, it'll warn, if not, it'll return the correct xml 1471 | return $json; 1472 | } 1473 | } 1474 | } 1475 | else { 1476 | open(JSON, "-|", "unzip", "-p", $filename) 1477 | or $unzip = "unzip"; # Will never happen. 1478 | 1479 | # Sadly unzip -p never fails, but we can check if the 1480 | # filehandle points to an empty file and pretend it did 1481 | # not open/failed. 1482 | if (eof JSON) { 1483 | $unzip = "unzip"; 1484 | } 1485 | } 1486 | 1487 | # Read JSON if possible (if open) 1488 | if ($unzip eq "") { 1489 | $json = getJSONFromString(join("", )); 1490 | if (!$json) { 1491 | warn "$scriptname: The JSON found in ZIP file (<$filename>) does not seem to be valid JSON! \n"; 1492 | } 1493 | close JSON; 1494 | } 1495 | else { 1496 | warn "$scriptname: Failed to $unzip ZIP file (<$filename>)! \n"; 1497 | close JSON; 1498 | } 1499 | } 1500 | else { 1501 | warn "$scriptname: Could not find an <$filename>! \n"; 1502 | } 1503 | 1504 | return $json; 1505 | } 1506 | 1507 | # ----------------------------------------------------------------------------- 1508 | 1509 | sub getJSONFromString { 1510 | printDebug("getting JSON from string"); 1511 | my $raw_json = $_[0]; 1512 | 1513 | eval { 1514 | my $json = decode_json($raw_json); 1515 | return $json; 1516 | } 1517 | or do { 1518 | return undef; 1519 | } 1520 | } 1521 | 1522 | # ----------------------------------------------------------------------------- 1523 | 1524 | sub storeJSONInDatabase { 1525 | printDebug("storing JSON into database"); 1526 | my $json = shift; 1527 | 1528 | my $org = $json->{'organization-name'}; 1529 | my $from = $json->{'date-range'}{'start-datetime'}; 1530 | my $to = $json->{'date-range'}{'end-datetime'}; 1531 | my $email = $json->{'contact-info'}; 1532 | my $reportid = $json->{'report-id'}; 1533 | # I don't think mulptile policies per report are sent right now 1534 | my $mode = $json->{'policies'}[0]{'policy'}{'policy-string'}[1] // ''; # this can be blank for some reason... 1535 | my $domain = $json->{'policies'}[0]{'policy'}{'policy-domain'}; 1536 | my $success = $json->{'policies'}[0]{'summary'}{'total-successful-session-count'}; 1537 | my $failure = $json->{'policies'}[0]{'summary'}{'total-failure-session-count'} // 0; # we need to make sure this has a value 1538 | 1539 | my $record = $json->{'policies'}[0]{'failure-details'}; 1540 | 1541 | # remove "mode:" 1542 | $mode =~ s/mode: //; 1543 | 1544 | # date timestamp is close, but needs to be cleaned up 1545 | $from =~ s/T/ /; 1546 | $from =~ s/Z//; 1547 | $to =~ s/T/ /; 1548 | $to =~ s/Z//; 1549 | 1550 | printDebug("org: $org\n". 1551 | " date: $from - $to\n". 1552 | " email: $email\n". 1553 | " report id: $reportid\n". 1554 | " sts mode: $mode\n". 1555 | " policy domain: $domain\n". 1556 | " success count: $success\n". 1557 | " failure count: $failure"); 1558 | 1559 | # see if already stored 1560 | my $sth = $dbh->prepare(qq{SELECT org, serial FROM tls WHERE reportid=?}); 1561 | $sth->execute($reportid); 1562 | while ( my ($xorg,$sid) = $sth->fetchrow_array() ) 1563 | { 1564 | if ($reports_replace) { 1565 | # $sid is the serial of a report with reportid=$id 1566 | # Remove this $sid from rptrecord and report table, but 1567 | # try to continue on failure rather than skipping. 1568 | printDebug("$scriptname: $org: $reportid: Replacing data."); 1569 | $dbh->do(qq{DELETE from tlsrecord WHERE serial=?}, undef, $sid); 1570 | if ($dbh->errstr) { 1571 | warn "$scriptname: $org: $reportid: Cannot remove report data from database. Try to continue.\n"; 1572 | } 1573 | $dbh->do(qq{DELETE from tls WHERE serial=?}, undef, $sid); 1574 | if ($dbh->errstr) { 1575 | warn "$scriptname: $org: $reportid: Cannot remove report from database. Try to continue.\n"; 1576 | } 1577 | } 1578 | else { 1579 | printDebug("$scriptname: $org: $reportid: Already have report, skipped"); 1580 | # Do not store in DB, but return true, so the message can 1581 | # be moved out of the way, if configured to do so. 1582 | return 1; 1583 | } 1584 | } 1585 | 1586 | my $sql = qq{INSERT INTO tls (mindate,maxdate,domain,org,reportid,email,policy_mode,summary_success,summary_failure,raw_json) 1587 | VALUES (?,?,?,?,?,?,?,?,?,?)}; 1588 | my $storejson = encode_json $json; 1589 | if ($compress_json) { 1590 | my $gzipdata; 1591 | if(!gzip(\$storejson => \$gzipdata)) { 1592 | warn "$scriptname: $org: $reportid: Cannot add gzip JSON to database ($GzipError). Skipped.\n"; 1593 | rollback($dbh); 1594 | return 0; 1595 | $storejson = ""; 1596 | } 1597 | else { 1598 | $storejson = encode_base64($gzipdata, ""); 1599 | } 1600 | } 1601 | 1602 | if (length($storejson) > $maxsize_json) { 1603 | warn "$scriptname: $org: $reportid: Skipping storage of large JSON (".length($storejson)." bytes) as defined in config file.\n"; 1604 | $storejson = ""; 1605 | } 1606 | 1607 | $dbh->do($sql, undef, $from, $to, $domain, $org, $reportid, $email, $mode, $success, $failure, $storejson); 1608 | if ($dbh->errstr) { 1609 | warn "$scriptname: $org: $reportid: Cannot add report to database. Skipped.\n"; 1610 | return 0; 1611 | } 1612 | 1613 | my $serial = $dbh->last_insert_id(undef, undef, 'tls', undef); 1614 | printDebug("serial $serial"); 1615 | 1616 | sub dorowtls($$$$) { 1617 | my ($serial,$rec,$org,$id) = @_; 1618 | my %r = %$rec; 1619 | 1620 | my $send_ip = $r{'sending-mta-ip'}; 1621 | my $recv_ip = $r{'receiving-ip'}; 1622 | my $type = $r{'result-type'}; 1623 | my $recv_mx = $r{'receiving-mx-hostname'}; 1624 | my $count = $r{'failed-session-count'}; 1625 | 1626 | if ($debug) { 1627 | # because apparently these can be undefined... 1628 | print "\n\n--- DEBUG ---\n"; 1629 | print " result-type: $type\n" if defined($type); 1630 | print " sending-mta-ip: $send_ip\n" if defined($send_ip); 1631 | print " receiving-ip: $recv_ip\n" if defined($recv_ip); 1632 | print " receiving-mx-hostname: $recv_mx\n" if defined($recv_mx); 1633 | print " failed-session-count: $count\n" if defined($count); 1634 | print "-------------\n\n"; 1635 | } 1636 | 1637 | my ($send_ip_type, $recv_ip_type) = "ip"; 1638 | 1639 | # this subroutine reduces these lines from existing multiple times for both sender and reciever 1640 | sub iptype($) { 1641 | my $ip = shift; 1642 | my ($iptype, $ipval, $nip); 1643 | 1644 | if ($nip = inet_pton(AF_INET, $ip)) { 1645 | $ipval = unpack "N", $nip; 1646 | $iptype = "ip"; 1647 | } 1648 | elsif($nip = inet_pton(AF_INET6, $ip)) { 1649 | $ipval = $dbx{to_hex_string}{$nip}; 1650 | $iptype = "ip6"; 1651 | } 1652 | else { 1653 | warn "$scriptname: ??? mystery ip $ip\n"; 1654 | return 0,0; 1655 | } 1656 | return $ipval,$iptype; 1657 | } 1658 | 1659 | ($send_ip,$send_ip_type) = iptype($send_ip) if defined($send_ip); 1660 | ($recv_ip,$recv_ip_type) = iptype($recv_ip) if defined($recv_ip); 1661 | 1662 | printDebug("sending ip type: $send_ip_type\n". 1663 | " recieving ip type: $recv_ip_type"); 1664 | 1665 | my $sql = qq{INSERT INTO tlsrecord (serial,send_$send_ip_type,recv_$recv_ip_type,recv_mx,type,count) 1666 | VALUES (?,?,?,?,?,?)}; 1667 | $dbh->do($sql,undef,$serial,$send_ip,$recv_ip,$recv_mx,$type,$count); 1668 | if ($dbh->errstr) { 1669 | warn "$scriptname: $org: $id: Cannot add failure report data to database. Skipped.\n"; 1670 | rollback($dbh); 1671 | return 0; 1672 | } 1673 | return 1; 1674 | } 1675 | 1676 | my $res = 1; 1677 | 1678 | # if there are no records, don't bother 1679 | if($failure == 0) { 1680 | # do nothing 1681 | } 1682 | elsif(ref $record eq "HASH") { 1683 | printDebug("single record"); 1684 | $res = -1 if !dorowtls($serial,$record,$org,$reportid); 1685 | } 1686 | elsif(ref $record eq "ARRAY") { 1687 | printDebug("multi record"); 1688 | foreach my $row (@$record) { 1689 | $res = -1 if !dorowtls($serial,$row,$org,$reportid); 1690 | } 1691 | } 1692 | else { 1693 | warn "$scriptname: $org: $reportid: mystery type " . ref($record) . "\n"; 1694 | } 1695 | 1696 | if ($res <= 0) { 1697 | printDebug("Result $res JSON: ". encode_json $json); 1698 | } 1699 | 1700 | if ($res <= 0) { 1701 | if ($db_tx_support) { 1702 | warn "$scriptname: $org: $reportid: Cannot add records to tlsrecord. Rolling back DB transaction.\n"; 1703 | rollback($dbh); 1704 | } 1705 | else { 1706 | warn "$scriptname: $org: $reportid: errors while adding to tlsrecord, serial $serial records likely obsolete.\n"; 1707 | } 1708 | } 1709 | else { 1710 | if ($db_tx_support) { 1711 | $dbh->commit; 1712 | if ($dbh->errstr) { 1713 | warn "$scriptname: $org: $reportid: Cannot commit transaction.\n"; 1714 | } 1715 | } 1716 | } 1717 | return $res; 1718 | } 1719 | 1720 | # ----------------------------------------------------------------------------- 1721 | 1722 | # Tries to roll back the transaction (if enabled). 1723 | # If an error happens, warn the user, but continue execution 1724 | sub rollback { 1725 | my $dbh = $_[0]; 1726 | 1727 | if ($db_tx_support) { 1728 | $dbh->rollback; 1729 | if ($dbh->errstr) { 1730 | warn "$scriptname: Cannot rollback transaction.\n"; 1731 | } 1732 | } 1733 | } 1734 | 1735 | # ----------------------------------------------------------------------------- 1736 | 1737 | # Check, if the database contains needed tables and columns. The idea is, that 1738 | # the user only has to create the database/database_user. All needed tables and 1739 | # columns are created automatically. Furthermore, if new columns are introduced, 1740 | # the user does not need to make any changes to the database himself. 1741 | sub checkDatabase { 1742 | my $dbh = $_[0]; 1743 | 1744 | my $tables = $dbx{tables}; 1745 | 1746 | # Create missing tables and missing columns. 1747 | for my $table ( keys %{$tables} ) { 1748 | if (!db_tbl_exists($dbh, $table)) { 1749 | 1750 | # Table does not exist, build CREATE TABLE cmd from tables hash. 1751 | printInfo("$scriptname: Adding missing table <" . $table . "> to the database."); 1752 | my $sql_create_table = "CREATE TABLE " . $table . " (\n"; 1753 | for (my $i=0; $i <= $#{$tables->{$table}{"column_definitions"}}; $i+=3) { 1754 | my $col_name = $tables->{$table}{"column_definitions"}[$i]; 1755 | my $col_type = $tables->{$table}{"column_definitions"}[$i+1]; 1756 | my $col_opts = $tables->{$table}{"column_definitions"}[$i+2]; 1757 | # add comma if second or later entry 1758 | if ($i != 0) { 1759 | $sql_create_table .= ",\n"; 1760 | } 1761 | $sql_create_table .= "$col_name $col_type $col_opts"; 1762 | } 1763 | # Add additional_definitions, if defined. 1764 | if ($tables->{$table}{"additional_definitions"} ne "") { 1765 | $sql_create_table .= ",\n" . $tables->{$table}{"additional_definitions"}; 1766 | } 1767 | # Add options. 1768 | $sql_create_table .= ") " . $tables->{$table}{"table_options"} . ";"; 1769 | # Create table. 1770 | printDebug("$sql_create_table"); 1771 | $dbh->do($sql_create_table); 1772 | 1773 | # Create indexes. 1774 | foreach my $sql_idx (@{$tables->{$table}{indexes}}) { 1775 | printDebug("$sql_idx\n"); 1776 | $dbh->do($sql_idx); 1777 | } 1778 | } 1779 | else { 1780 | 1781 | #Table exists, get current columns in this table from DB. 1782 | my %db_col_exists = db_column_info($dbh, $table); 1783 | 1784 | # Check if all needed columns are present, if not add them at the desired position. 1785 | my $insert_pos; 1786 | for (my $i=0; $i <= $#{$tables->{$table}{"column_definitions"}}; $i+=3) { 1787 | my $col_name = $tables->{$table}{"column_definitions"}[$i]; 1788 | my $col_type = $tables->{$table}{"column_definitions"}[$i+1]; 1789 | my $col_opts = $tables->{$table}{"column_definitions"}[$i+2]; 1790 | 1791 | if (!$db_col_exists{$col_name}) { 1792 | # add column 1793 | my $sql_add_column = $dbx{add_column}($table, $col_name, $col_type, $col_opts, $insert_pos); 1794 | printDebug("$sql_add_column\n"); 1795 | $dbh->do($sql_add_column); 1796 | } 1797 | elsif ($db_col_exists{$col_name} !~ /^\Q$col_type\E/) { 1798 | # modify column 1799 | my $sql_modify_column = $dbx{modify_column}($table, $col_name, $col_type, $col_opts); 1800 | printDebug("$sql_modify_column\n"); 1801 | $dbh->do($sql_modify_column); 1802 | } 1803 | $insert_pos = $col_name; 1804 | } 1805 | } 1806 | } 1807 | 1808 | $dbh->commit; 1809 | } 1810 | 1811 | # ----------------------------------------------------------------------------- 1812 | 1813 | # Checks if the table exists in the database 1814 | sub db_tbl_exists { 1815 | my ($dbh, $table) = @_; 1816 | 1817 | my @res = $dbh->tables(undef, undef, $table, undef); 1818 | return scalar @res > 0; 1819 | } 1820 | 1821 | # ----------------------------------------------------------------------------- 1822 | 1823 | # Gets columns and their data types in a given table 1824 | sub db_column_info { 1825 | my ($dbh, $table) = @_; 1826 | 1827 | my $db_info = $dbh->column_info(undef, undef, $table, undef)->fetchall_hashref('COLUMN_NAME'); 1828 | my %columns; 1829 | foreach my $column (keys(%$db_info)) { 1830 | $columns{$column} = $db_info->{$column}{$dbx{column_info_type_col}}; 1831 | } 1832 | return %columns; 1833 | } --------------------------------------------------------------------------------