├── .gitignore ├── COPYING ├── Dockerfile ├── MANIFEST.in ├── README.md ├── domain_stats.gif ├── domain_stats ├── __init__.py ├── config.py ├── data │ ├── domain_stats.service │ ├── domain_stats.zeek │ ├── elasticsearch.zeek.domain.pipeline │ ├── freqtable2018.freq │ └── top1m.import ├── domain-loader.py ├── expiring_diskcache.py ├── freq.py ├── launch.py ├── network_io.py ├── rdap_query.py ├── server.py ├── settings.py └── utils.py ├── overview.drawio ├── overview.jpg ├── setup.py └── start.sh /.gitignore: -------------------------------------------------------------------------------- 1 | build/* 2 | domain_stats/__pycache__/* 3 | dist/* 4 | *.egg-info 5 | .vscode/launch.json 6 | .vscode/settings.json 7 | */diskcache/* 8 | */*.db 9 | cache.db* 10 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:18.04 2 | 3 | #docker build -tag domain_stats_image http://github.com/markbaggett/domain_stats.git 4 | #Configure the container choosing your hosts path and port 5 | #docker run --name domain_stats_container -v /:/host_mounted_dir -p 8000: domain_stats_image 6 | 7 | 8 | # Install all the tools 9 | RUN apt-get update && apt-get install python3.8 python3-pip -y 10 | RUN python3 -m pip install setuptools rdap pyyaml flask diskcache gunicorn requests python-dateutil publicsuffixlist python-whois 11 | RUN mkdir /app 12 | COPY . /app 13 | RUN cd app && pip3 install . 14 | RUN mkdir /host_mounted_dir 15 | 16 | CMD ["domain-stats" ,"/host_mounted_dir"] 17 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include domain_stats/data/*.* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # domain_stats2 2 | 3 | ## Introduction 4 | Domain_stats is a log enhancment utility that is intended help you find threats in your environment. It will identify the following possible threats in your environment. 5 | - Domains that were recently registered 6 | - Domains that no one in your organization has ever visited before 7 | - Domains with hostnames that appear to be random characters 8 | - Domains that the security community has identified as new (**Pending ISC Integration) 9 | - Domains that SANS ISC issues warning for (**Pending ISC Integration) 10 | 11 | ## The Old Domain_stats support 12 | This version of domains_stats provides a number of benefits over the old version including performance, scalability, alerting, and isc integration. It does focus on born-on information which was the primary use of the tool and achieves its increaces performance by not processing the entire whois record. If you are looking for a copy of the old domain_stats which rendered ALL of the whois record rather than just the born-on information please let me make two suggestions. First, that functionality has been moved to a new tool called "APIify" which can render any standard linux command in a json response for consumption. It also has improved caching and scalability over the old domain_stats. You can download [APIify HERE](https://github.com/markbaggett/apiify). You can also find the old version of domain_stats [in the releases section](https://github.com/MarkBaggett/domain_stats/releases/tag/1.0). 13 | 14 | ## Special Thanks 15 | Thanks to the following individuals for their support, suggestions and inspirations without whom this version of domain_stats would not be possible. 16 | - Justin Henderson [@securitymapper](https://twitter.com/securitymapper) 17 | - Don Williams [@bashwrapper](https://twitter.com/bashwrapper) 18 | - Dustin "cuz" Lee [@_dustinlee](https://twitter.com/_dustinlee) 19 | - Luke Flinders [@The1WhoPrtNocks](https://twitter.com/The1WhoPrtNocks) 20 | 21 | ## Ubuntu system preparation: 22 | On Ubuntu you usually have to install Python PIP first. At a bash prompt run the following: 23 | ``` 24 | $ apt-get install python3-pip 25 | ``` 26 | 27 | ## Install published package via PIP 28 | ``` 29 | $ python3 -m pip install domain-stats 30 | ``` 31 | 32 | ## Install from latest source via PIP 33 | Alternatively download the latest build from this github repo and install it as follows. Use PIP to install domain_stats rather than running setup.py. 34 | ``` 35 | $ git clone https://github.com/markbaggett/domain_stats 36 | $ cd domain_stats 37 | $ python3 -m pip install . 38 | ``` 39 | 40 | ## Configure and Start 41 | 42 | One the package is installed, make a directory that will be used to for storage of data and configuration files. Then run 'domain-stats-settings' and followed by 'domain-stats'. Both of those programs require you pass it the path to your data directory. The first command 'domain-stats-settings' creates or edits the required settings files. If you are not sure how to answer the questions just press enter and allow it to create the configuration files. The second command 'domain-stats' will run the server. 43 | 44 | ``` 45 | $ mkdir /mydata 46 | $ domain-stats-settings /mydata 47 | $ domain-stats /mydata 48 | ``` 49 | 50 | Here is what that looks like installed from source. 51 | 52 | ![alt text](./domain_stats.gif "Installation and use") 53 | 54 | ## Optional Load of top1m 55 | **With the server up and running** you can use ```domain-stats-utils``` to enhance the domain stats data. For example, to use whois to patch records that RDAP was unable to resolve you can use the -f or --fix option. 56 | ``` 57 | $ domain-stats-utils -f /path_to_data 58 | ``` 59 | You can also avoid the initial (likely to be terms of service violating) volume of request to RDAP when you first start your server by prestaging a group of roughly 35K records from domains taken from the Cisco Umbrealla Projects top1m domains. **WARNING: By choosing to prepopulate these domains in the 'seen database' you will not be alerted to the "FIRST CONTACT" when someone visits them for the first time**. That said, these are from the top 1 million most commonly used domains and you likely don't care about first contact with them. To import these you again use domain-stats-utils. These records will be tagged with "top1m" in the "seen-by-isc" field. 60 | ``` 61 | $ domain-stats-utils -i domains-stats\data\top1m.import -nx /mydata 62 | ``` 63 | The -nx options tells domain_stats to never expire these records from its cache. Without this option it will use its default behavior and the records will expire from the database when the domain registration expires. For the top most commonly used established domains this will prevent you from unessisarily looking up the domain registration date every year for these sites. 64 | 65 | --- 66 | ## Install and running in a container 67 | 68 | To get a container up and running with domain_stats `docker build` passing the git file as a url. The `docker run` command must mount a directory into the container as the folder "host_mounted_dir" and to TCP port 8000 so you can access the server. In the example below port 5730 on the docker server is forwarded to the domain_stats server running inside the container on port 8000. Run docker run once with the -it option so you can go through the setup questions. One change you must make for a docker configuration is to change the default port from 127.0.0.1 to 0.0.0.0. Otherwise, if you do not know a better answer then the default just press ENTER. When it is finished run the container again with the -d and --name options as shown below. After that you can `docker stop domain_stats` and `docker start domain_stats` as needed. 69 | 70 | ``` 71 | $ docker build --tag domain_stats_image http://github.com/markbaggett/domain_stats.git 72 | $ mkdir ~/dstat_data 73 | $ docker run -it --rm -v ~/dstat_data:/host_mounted_dir -p 8000:5730 domain_stats_image 74 | Set value for ip_address. Default=127.0.0.1 Current=127.0.0.1 (Enter to keep Current): 0.0.0.0 75 | Set value for local_port. Default=5730 Current=5730 (Enter to keep Current): 76 | Set value for workers. Default=3 Current=3 (Enter to keep Current): 77 | Set value for threads_per_worker. Default=3 Current=3 (Enter to keep Current): 78 | Set value for timezone_offset. Default=0 Current=0 (Enter to keep Current): 79 | Set value for established_days_age. Default=730 Current=730 (Enter to keep Current): 80 | Set value for mode. Default=rdap Current=rdap (Enter to keep Current): 81 | Set value for freq_table. Default=freqtable2018.freq Current=freqtable2018.freq (Enter to keep Current): 82 | Set value for enable_freq_scores. Default=True Current=True (Enter to keep Current): 83 | Set value for freq_avg_alert. Default=5.0 Current=5.0 (Enter to keep Current): 84 | Set value for freq_word_alert. Default=4.0 Current=4.0 (Enter to keep Current): 85 | Set value for log_detail. Default=0 Current=0 (Enter to keep Current): 86 | Commit Changes to disk?y 87 | 88 | $ docker run -d --name domain_stats -v ~/dstat_data:/host_mounted_dir -p 8000:5730 --restart unless-stopped domain_stats_image 89 | ``` 90 | 91 | Once the container is running if you would like to change the settings or use the domain-stats-utils to import domains you can launch a second terminal process in the running image. For example, here is how to import the top1m domains. Always point domain-stats-utils and domain-stats-settings to /host_mounted_dir/ when inside the container. 92 | 93 | ``` 94 | $ docker exec -it domain_stats /bin/bash 95 | root@8f6561dc0766:/# domain-stats-utils -i /app/domain_stats/data/top1m.import -nx /host_mounted_dir/ 96 | root@8f6561dc0766:/# exit 97 | ``` 98 | or 99 | ``` 100 | $ docker exec -it domain_stats /bin/bash 101 | root@8f6561dc0766:/# domain-stats-settings /host_mounted_dir/ 102 | root@8f6561dc0766:/# exit 103 | 104 | ``` 105 | --- 106 | 107 | ## To Run domain_stats as a service 108 | If you are not going to use a docker you may want to run domain_stats as a server. After installing domain_stats as described above you can set it to run as a service on your system using the provided .service file in the data folder. It will be necessary to edit the domain_stats.service file and change the "WorkingDirectory" entry so that it points to the location you are storing your data. After editing the file add the ["domain_stats.service"](./domain_stats/data/domain_stats.service) file to your `/etc/systemd/system` folder. Then use `systemctl enable domain_stats` to set it to start automatically. 109 | 110 | ## SEIM Integration: 111 | This varies depending upon the SEIM. The web interface is designed for your SEIM to make API calls to it. It will respond back with a JSON responce for you it to consume. Since many SEIM products are already configured to consume ZEEK logs another easy option is to add the ["domain_stats.zeek"](./domain_stats/data/domain_stats.zeek) module to your zeek configuration. Check the zeek domainstats.log for "NEW" domains and check for alerts such as "YOUR-FIRST-CONTACT". 112 | 113 | ### Example Zeek Configuration: 114 | 115 | Assuming that zeek is installed in `/opt/zeek` and you don't already have custom scripts configured you can do this: 116 | 117 | - Place domain_stats.zeek in a new directory called `/opt/zeek/share/zeek/policy/custom-script` 118 | - Add `@load ./domain_stats` to a new file called `/opt/zeek/share/zeek/policy/custom-script/__load__.zeek` 119 | - Add `@load custom-scripts` to `/opt/zeek/share/zeek/site/local.zeek` 120 | - Make sure curl is installed. This is a dependency of zeeks ActiveHTTP module. (try `apt install curl`) 121 | - If you are running zeek in a VM you need uncomment `redef ignore_checksums = T;` in domain_stats.zeek 122 | - Start domain_stats server 123 | - In zeekctl `deploy` 124 | - Confirm domain_stats appears in loaded_scripts.log 125 | 126 | 127 | ## Using domain_stats 128 | 129 | When LogStash or any other system makes a web request to the system it returns back data relevant to the domain queried. 130 | 131 | The request is in the form ```http://ip:port/domain``` For example: 132 | ``` 133 | $ wget -q -O- http://127.0.0.1:5730/sans.org 134 | {"alerts":["YOUR-FIRST-CONTACT"],"category":"ESTABLISHED","freq_score":[6.2885,7.9696],"seen_by_isc":"RDAP","seen_by_web":"Fri, 04 Aug 1995 04:00:00 GMT","seen_by_you":"Sat, 07 Nov 2020 17:19:49 GMT"} 135 | ``` 136 | 137 | #### Here is what the response fields mean 138 | 139 | - alerts - A list of alarms associated with the domain queried. This can include 140 | * YOUR-FIRST-CONTACT - This is the first time you have every queried this domain 141 | * SUSPECT-FREQ-SCORE - One of the two freq scores is low 142 | * LOW-FREQ-SCORE - Both of the freq scores are low 143 | * Other - Other alerts may be added with ISC integration 144 | 145 | - SEEN_BY_YOU - This is the date this domain was first seen by you 146 | 147 | - SEEN_BY_ISC - This may be one of a few possible values 148 | * RDAP - When in RDAP mode this will contain the word RDAP 149 | * datetime - When in ISC mode this will contain the date and time when the domain was first seen by the ISC 150 | * top1m or other name - When domains are preloaded into your database with domain-stats-utils the name of the import is displayed here 151 | 152 | - SEEN_BY_WEB - This is the date when the domain was first seen on the internet (ie the registration date) 153 | 154 | - CATEGORY - This can be one of two possible values 155 | * NEW - The registration date is less than the configured "established_days_age" (Default is two years) 156 | * ESTABLISHED - The domain is more than "established_days_age" days old 157 | 158 | - freq_score - This contains two values measuring the "normalness" of the domain letters. If these numbers are below the thresholds established in the settings it will generate alerts. 159 | 160 | #### In addition to requesting a domain the following urls can be used to check on your server. 161 | 162 | ``` 163 | $ wget -q -O- http://127.0.0.1:5730/stats 164 | ``` 165 | This will show statistics on the efficiency of the cache and rdap. This also runs a consistency check on the database and repairs any issues. The database is locked while this is running so don't constantly hit this url. 166 | 167 | ``` 168 | $ wget -q -O- http://127.0.0.1:5730/stats-reset 169 | ``` 170 | Resets the RDAP failure and success 171 | 172 | ``` 173 | $ wget -q -O- http://127.0.0.1:5730/cache_get?domain=python.org 174 | ``` 175 | This will retrieve the record from the cache if it exists. 176 | 177 | ``` 178 | $ wget -q -O- http://127.0.0.1:5730/cache_browse?offset=1&limit=100 179 | ``` 180 | This will retrieve the first 100 record from the cache and display them. Adjust offset and limit to see others. 181 | 182 | 183 | ## Configuration 184 | To change the settings run the tool and pass it the path where your data is stored. 185 | 186 | ``` 187 | $ domain-stats-settings /home/student/mydata 188 | Existing config found in directory. Using it. 189 | Set value for ip_address. Default=0.0.0.0 Current=0.0.0.0 (Enter to keep Current): 190 | Set value for local_port. Default=5730 Current=5730 (Enter to keep Current): 191 | Set value for workers. Default=3 Current=1 (Enter to keep Current): 192 | Set value for threads_per_worker. Default=3 Current=3 (Enter to keep Current): 193 | Set value for timezone_offset. Default=0 Current=0 (Enter to keep Current): 194 | Set value for established_days_age. Default=730 Current=730 (Enter to keep Current): 195 | Set value for mode. Default=rdap Current=rdap (Enter to keep Current): 196 | Set value for rdap_error_ttl_days. Default=7 Current=7 (Enter to keep Current): 197 | Set value for freq_table. Default=freqtable2018.freq Current=freqtable2018.freq (Enter to keep Current): 198 | Set value for enable_freq_scores. Default=True Current=True (Enter to keep Current): 199 | Set value for freq_avg_alert. Default=5.0 Current=5.0 (Enter to keep Current): 200 | Set value for freq_word_alert. Default=4.0 Current=4.0 (Enter to keep Current): 201 | Set value for log_detail. Default=0 Current=3 (Enter to keep Current): 202 | Set value for cache_browse_limit. Default=100 Current=100 (Enter to keep Current): 203 | Commit Changes to disk?y 204 | ``` 205 | I think most of these are self explainatory. Here is a description of the ones that are not or require some discussion. 206 | - ip_address - You listen on this ip. 127.0.0.1 is safer than 0.0.0.0. Otherwise unauthenticated anyone on your network can see the dns cache for your enterprise. IPTABLES is nice. 207 | - mode - 'rdap' is all that works right now. 208 | - timezone_offset - If set, this is only used on the "seen_by_you" date. By default all times are UTC. 209 | - rdap_error_ttl_days - RDAP errors are cached are cached for a short period of time for performance. By default it is 7 days. 210 | - established_days_age - Defines how long before a domain is considered established. Default is two years. 211 | - freq_table - If you created custom freq tables you can select them here. They should be stored in your data directory. 212 | - enable_freq_scores - If you don't want freq scores, disabling them can enhance your server performance 213 | - log_detail - Logging will significantly impact performance. Id suggest leaving it disabled unless you are diagnosing an issue. 214 | - cache_browse_limit - Limit the max number of records that someone can request with http://ip:port/cache_browse?offset=0&limit=9999999999999 215 | 216 | 217 | # RDAP vs ISC Support 218 | They each have their own advantages. We will discuss them here. 219 | 220 | - RDAP works today! The ISC support engine is still in the works. 221 | - If you trust your ISP, and commercial and government entities that support DNS infrastructure with your DNS queries but not the ISC then RDAP will let you live in your bubble. 222 | - As of August 2019 RDAP ICANN requires providers support for gTLDs (Top Level: .com, .gov, etc) and not ccTLDs (country code :google.com.au, .ga.us, etc) or eTLDs (Effective TLDs: Where we register domains). You basically can't resolve those domains until ISC support is enabled. More info on RDAP Support timelines are [HERE](https://www.icann.org/resources/pages/rdap-background-2018-08-31-en) 223 | - ISC support will support all domains and not be limited by RDAP support. 224 | - ISC will provide additional alerting on domains 225 | 226 | # ISC API Specification 227 | API requests look like this 228 | ``` 229 | {"command": , additional arguments depending upon command} 230 | ``` 231 | Valid COMMANDS include "CONFIG", "STATUS", and "QUERY" 232 | 233 | 234 | 235 | ### **CONFIG command requests configuration options the ISC would like to enforce on the client** 236 | request: 237 | ``` 238 | {"command": "config"} 239 | ``` 240 | response: 241 | ``` 242 | {"min_software_version": "major.minor string", "min_database_version", "major.minor string", prohitited_tlds:["string1","string2"]} 243 | ``` 244 | - clients will not query ISC for Domains listed in prohibited_tlds. Examples may be ['.local', '.arpa'] 245 | - If min_software_version is higher than the client software version it causes the software to abort 246 | - if min_database_version is higher than database version it forces the client to download new domains from github.com/markbaggett and add it to its local database 247 | 248 | 249 | 250 | ### **STATUS command allows the clients to tell the ISC how they are doing and see if they can continue. This can be used to tune client efficiency and reduce ISC requests.** 251 | Request: 252 | ``` 253 | {"command":"status", "client_version":client_version, "database_version":database_version, "cache_efficiency":[cache.hits, cache.miss, cache.expire], "database_efficiency":[database_stats.hits, database_stats.miss]} 254 | ``` 255 | Response: 256 | ``` 257 | {"interval": "integer number of minutes ISC wishes to wait until next status update", "deny_client": "client message string"} 258 | ``` 259 | - interval: The interval tells the client how many minutes to wait before sending another status updates 260 | - deny_client: If set aborts the client with the specified message 261 | 262 | 263 | 264 | ### **QUERY command allows clients to query a domain record.** 265 | Requests: 266 | ``` 267 | {"command": "query", "domain": "example.tld"} 268 | ``` 269 | RESPONSES (two possible): 270 | ##### A success response looks like this: 271 | 272 | ``` 273 | {"seen_by_web": '%Y-%m-%d %H:%M:%S', "expires": '%Y-%m-%d %H:%M:%S', "seen_by_isc":'%Y-%m-%d %H:%M:%S', "alerts":['list','of','alerts]} 274 | ``` 275 | - seen_by_web is the domains creation date from the whois record. The time stamp must be in '%Y-%m-%d %H:%M:%S' format 276 | - expires is the date that the domains registration expires from the whois record. The timestamp must be in '%Y-%m-%d %H:%M:%S' format 277 | - seen_by_isc is the date that the first domain_stats client requested this domain from the isc. If this was the first request it will have the current date and time and 'ISC-FIRST-CONTACT' will be added to the alerts. The timestamp must be in '%Y-%m-%d %H:%M:%S' format. 278 | - Alerts must include "ISC-FIRST-CONTACT" if this is the first time anyone has ever queried ISC for this domain 279 | - Setting any additional alerts limits will cause the client record to not be commited to the database. Instead it is cached for 24 hours on the client. After 24 hours the client will query the isc again. 280 | ##### An error response looks like this: 281 | 282 | ``` 283 | {"seen_by_web":"ERROR", "expires":"ERROR", "seen_by_isc":, "alerts":['alerts','for','that','domain']} 284 | ``` 285 | - seen_by_web and expires must be set to "ERROR" when an error has occured. 286 | - Error time to live tell the client how long to cache and reuse the error for that domain. 287 | - Integer > 0 - will cache the error for that many hours 288 | - 0 - will not cache the error at all 289 | - -1 - will cache it such that it does not expire, but the domain can still drop out of cache based on LRU algorithm 290 | - -2 - PERMANENT cache entry. Will never expire. DANGEROUS. Use with caution. 291 | 292 | -------------------------------------------------------------------------------- /domain_stats.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkBaggett/domain_stats/759c52c84c8bdc98ad49a70e8828d8a91a9a9a3d/domain_stats.gif -------------------------------------------------------------------------------- /domain_stats/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkBaggett/domain_stats/759c52c84c8bdc98ad49a70e8828d8a91a9a9a3d/domain_stats/__init__.py -------------------------------------------------------------------------------- /domain_stats/config.py: -------------------------------------------------------------------------------- 1 | from collections import UserDict 2 | import yaml 3 | 4 | class Config(UserDict): 5 | 6 | def __init__(self, filename=""): 7 | super().__init__() 8 | self.filename = filename 9 | self.load_config(filename) 10 | 11 | def load_config(self, filename = None): 12 | filename = filename or self.filename 13 | with open(filename) as fh: 14 | self.data = yaml.safe_load(fh.read()) 15 | 16 | def save_config(self, filename = None): 17 | filename = filename or self.filename 18 | with open(filename, 'w') as fp: 19 | yaml.dump(self.data, fp, default_flow_style=False) 20 | -------------------------------------------------------------------------------- /domain_stats/data/domain_stats.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Domain Stats Service 3 | After=network.target 4 | 5 | [Service] 6 | #You may need to change the path so it points to where you are storing your data 7 | WorkingDirectory=/host_mounted_dir 8 | ExecStart=domain-stats ./ 9 | PIDFile=/var/run/domainstats.pid 10 | Restart=always 11 | 12 | [Install] 13 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /domain_stats/data/domain_stats.zeek: -------------------------------------------------------------------------------- 1 | #Thanks to SANS Instructor Don Williams for writing this https://www.sans.org/instructors/donald-williams 2 | #Don based this off of Dustin Lee's Security Onion integration Script here: https://github.com/dlee35/domain_stats2_so/blob/master/domainstats.bro 3 | 4 | module DomainStats; 5 | 6 | #Uncomment the next line if running in a VM or other system where packets normally have bad checksums. 7 | redef ignore_checksums = T; 8 | 9 | export { 10 | # This redef is purely for testing pcap and not designed for active networks 11 | # Set to F or comment before adding to production 12 | # redef exit_only_after_terminate = T; 13 | 14 | global domainstats_url = "http://localhost:5730/"; # add desired DS url here 15 | global ignore_domains = set(".rdap.net"); # add domains to exclude here 16 | global queried_domains: table[string] of count &default=0 &create_expire=1days; # keep state of domains to prevent duplicate queries 17 | global domain_suffixes = /MATCH_NOTHING/; # idea borrowed from: https://github.com/theflakes/bro-large_uploads 18 | redef enum Log::ID += { LOG }; 19 | 20 | type Info: record { 21 | ts: time &log; 22 | uid: string &log; 23 | query: string &log; 24 | alerts: vector of string &log &optional; 25 | category: string &log; 26 | freq_avg_prob: string &log; 27 | freq_word_prob: string &log; 28 | seen_by_web: string &log; 29 | seen_by_isc: string &log; 30 | seen_by_you: string &log; 31 | }; 32 | 33 | redef record connection += { 34 | domainstats : Info &optional; 35 | }; 36 | } 37 | 38 | event zeek_init() &priority=5 39 | { 40 | domain_suffixes = set_to_regex(ignore_domains, "(~~)$"); 41 | Log::create_stream(DomainStats::LOG, [$columns=Info, $path="domainstats"]); 42 | } 43 | 44 | event dns_request(c: connection, msg: dns_msg, query: string, qtype: count, qclass: count) 45 | { 46 | if (c$id$resp_p == 53/udp || c$id$resp_p == 53/tcp) { 47 | local dsurl = domainstats_url; 48 | local domain = fmt("%s",c$dns$query); 49 | if (domain in queried_domains || domain_suffixes in domain) { 50 | return; 51 | } 52 | else { 53 | local request: ActiveHTTP::Request = [ 54 | $url = dsurl + domain 55 | ]; 56 | queried_domains[domain] = 1; 57 | when (local res = ActiveHTTP::request(request)) { 58 | print res?$body; 59 | if (|res| > 0) { 60 | if (res?$body && |split_string(res$body,/,/)| > 2) { 61 | local resbody = fmt("%s", res$body); 62 | local alerts_entry = split_string(resbody,/,\"category/)[0]; 63 | alerts_entry = gsub(alerts_entry, /\"/, ""); 64 | alerts_entry = gsub(alerts_entry, /\[/ ,""); 65 | alerts_entry = gsub(alerts_entry, /\]/, ""); 66 | local alerts = split_string( split_string(alerts_entry,/alerts:/)[1], /,/); 67 | local cat_entry = split_string(resbody, /\",\"freq/)[0]; 68 | local cat_string = split_string( cat_entry, /category\":\"/ )[1]; 69 | local freq_entry = split_string(resbody, /,\"seen_by_isc/)[0]; 70 | freq_entry = split_string(freq_entry, /freq_score\":/)[1]; 71 | local freq_avg_prob = freq_entry; 72 | local freq_word_prob = freq_entry; 73 | if (/\[[[:digit:].]+, ?[[:digit:].]+\]/ == freq_entry) 74 | { 75 | freq_entry = freq_entry[1:-1]; 76 | freq_avg_prob = split_string( freq_entry, /,/)[0]; 77 | freq_word_prob = split_string( freq_entry, /,/)[1]; 78 | } 79 | local seen_by_isc_entry = split_string(resbody,/\",\"seen_by_web/)[0]; 80 | local seen_by_isc_date = split_string(seen_by_isc_entry,/seen_by_isc\":\"/)[1]; 81 | local seen_by_web_entry = split_string(resbody,/\",\"seen_by_you/)[0]; 82 | local seen_by_web_date = split_string(seen_by_web_entry,/by_web\":\"/)[1]; 83 | local seen_by_you_entry = split_string(resbody,/seen_by_you\":\"/)[1]; 84 | local seen_by_you_date = split_string(seen_by_you_entry,/\"/)[0]; 85 | local rec: DomainStats::Info = [$ts=c$start_time, $uid=c$uid, $query=domain, $seen_by_web=seen_by_web_date, $seen_by_isc=seen_by_isc_date, $seen_by_you=seen_by_you_date, $category=cat_string, $alerts=alerts,$freq_avg_prob=freq_avg_prob, $freq_word_prob=freq_word_prob]; 86 | Log::write(DomainStats::LOG, rec); 87 | } 88 | } 89 | } 90 | } 91 | } 92 | } -------------------------------------------------------------------------------- /domain_stats/data/elasticsearch.zeek.domain.pipeline: -------------------------------------------------------------------------------- 1 | PUT _ingest/pipeline/zeek.domainstats 2 | { 3 | "description" : "zeek.domainstats", 4 | "processors" : [ 5 | { 6 | "remove" : { 7 | "field" : [ 8 | "host" 9 | ], 10 | "ignore_failure" : true 11 | } 12 | }, 13 | { 14 | "json" : { 15 | "field" : "message", 16 | "target_field" : "message2", 17 | "ignore_failure" : true 18 | } 19 | }, 20 | { 21 | "remove" : { 22 | "field" : [ 23 | "message" 24 | ], 25 | "ignore_failure" : true 26 | } 27 | }, 28 | { 29 | "rename" : { 30 | "field" : "message2.alerts", 31 | "target_field" : "domainstats.alerts", 32 | "ignore_missing" : true 33 | } 34 | }, 35 | { 36 | "rename" : { 37 | "field" : "message2.seen_by_isc", 38 | "target_field" : "domainstats.seen_by_isc", 39 | "ignore_missing" : true 40 | } 41 | }, 42 | { 43 | "rename" : { 44 | "field" : "message2.seen_by_web", 45 | "target_field" : "domainstats.seen_by_web", 46 | "ignore_missing" : true 47 | } 48 | }, 49 | { 50 | "rename" : { 51 | "field" : "message2.seen_by_you", 52 | "target_field" : "domainstats.seen_by_you", 53 | "ignore_missing" : true 54 | } 55 | }, 56 | { 57 | "rename" : { 58 | "field" : "message2.category", 59 | "target_field" : "domainstats.category", 60 | "ignore_missing" : true 61 | } 62 | }, 63 | { 64 | "rename" : { 65 | "field" : "message2.query", 66 | "target_field" : "domainstats.domain", 67 | "ignore_missing" : true 68 | } 69 | }, 70 | { 71 | "rename" : { 72 | "field" : "message2.freq_avg_prob", 73 | "target_field" : "domainstats.freq_avg_prob", 74 | "ignore_missing" : true 75 | } 76 | }, 77 | { 78 | "rename" : { 79 | "field" : "message2.freq_word_prob", 80 | "target_field" : "domainstats.freq_word_prob", 81 | "ignore_missing" : true 82 | } 83 | }, 84 | { 85 | "pipeline" : { 86 | "name" : "zeek.common" 87 | } 88 | } 89 | ] 90 | } 91 | -------------------------------------------------------------------------------- /domain_stats/data/freqtable2018.freq: -------------------------------------------------------------------------------- 1 | [true, "\n\t~`!@#$%^&*()_+-", [["\f", [["f", 2]]], [" ", [[" ", 312527], ["$", 12], ["(", 1520], [",", 6], ["0", 2], ["4", 210], ["8", 75], ["<", 58], ["D", 5449], ["H", 14898], ["L", 6849], ["P", 10276], ["T", 23773], ["X", 290], ["`", 1958], ["d", 74474], ["h", 195782], ["l", 64742], ["p", 65902], ["t", 408490], ["x", 22], ["|", 38], ["#", 6], ["'", 3062], ["+", 2], ["/", 12], ["3", 300], ["7", 134], [";", 8], ["?", 8], ["C", 9334], ["G", 5688], ["K", 2484], ["O", 4266], ["S", 13139], ["W", 9355], ["[", 408], ["_", 220], ["c", 90632], ["g", 44086], ["k", 13940], ["o", 161371], ["s", 182472], ["w", 187994], ["{", 8], ["\"", 22346], ["&", 42], ["*", 112], [".", 2358], ["2", 691], ["6", 180], [":", 14], [">", 2], ["B", 12213], ["F", 8428], ["J", 5957], ["N", 7370], ["R", 5046], ["V", 3389], ["Z", 250], ["b", 109654], ["f", 95818], ["j", 6186], ["n", 56010], ["r", 54486], ["v", 15242], ["z", 238], ["~", 2], ["%", 2], [")", 2], ["-", 550], ["1", 1613], ["5", 132], ["9", 74], ["A", 16635], ["E", 4590], ["I", 45393], ["M", 17353], ["Q", 356], ["U", 753], ["Y", 2574], ["a", 293192], ["e", 47200], ["i", 125201], ["m", 99016], ["q", 5914], ["u", 27850], ["y", 29288]]], ["$", [[" ", 2], ["3", 2], ["2", 6], ["4", 10]]], ["(", [[" ", 2], ["\"", 34], ["$", 12], ["'", 24], ["*", 8], ["1", 28], ["3", 24], ["2", 30], ["5", 2], ["A", 54], ["C", 12], ["B", 32], ["E", 12], ["D", 16], ["G", 6], ["F", 40], ["I", 120], ["H", 48], ["K", 10], ["J", 2], ["M", 48], ["L", 14], ["O", 20], ["N", 26], ["P", 26], ["S", 46], ["U", 8], ["T", 124], ["W", 38], ["V", 2], ["Y", 4], ["_", 14], ["a", 306], ["`", 2], ["c", 22], ["b", 50], ["e", 24], ["d", 18], ["g", 10], ["f", 80], ["i", 122], ["h", 102], ["k", 2], ["j", 2], ["m", 20], ["l", 20], ["o", 86], ["n", 38], ["p", 16], ["s", 106], ["r", 6], ["u", 6], ["t", 240], ["w", 212], ["v", 2], ["y", 6], ["~", 8]]], [",", [["!", 2], [" ", 200706], ["\"", 10148], ["'", 1656], [")", 4], ["*", 18], ["-", 780], [",", 10], ["1", 40], ["0", 263], ["3", 6], ["2", 42], ["5", 44], ["4", 28], ["7", 4], ["6", 20], ["9", 12], ["8", 18], [":", 4], ["A", 4], ["I", 42], ["J", 2], ["M", 2], ["T", 2], ["[", 2], ["a", 328], ["c", 8], ["b", 76], ["e", 6], ["d", 4], ["g", 10], ["f", 60], ["i", 36], ["h", 36], ["k", 6], ["m", 10], ["l", 6], ["o", 22], ["n", 8], ["q", 2], ["p", 2], ["s", 64], ["r", 8], ["t", 84], ["w", 70]]], ["0", [[" ", 512], ["%", 16], ["'", 14], [")", 20], ["-", 20], [",", 155], [".", 70], ["1", 38], ["0", 714], ["3", 17], ["2", 32], ["5", 34], ["4", 13], ["7", 30], ["6", 21], ["9", 34], ["8", 20], [";", 8], [":", 22], ["@", 20], ["I", 6], ["]", 46], ["m", 2], ["s", 6], ["t", 74], ["x", 10], ["}", 18]]], ["4", [[" ", 70], ["'", 4], [")", 2], ["-", 12], [",", 70], [".", 46], ["1", 24], ["0", 82], ["3", 24], ["2", 24], ["5", 34], ["4", 16], ["7", 28], ["6", 16], ["9", 24], ["8", 34], [";", 6], [":", 44], ["@", 8], ["T", 2], ["]", 60], ["t", 64], ["}", 18], ["|", 32]]], ["8", [[" ", 64], ["'", 6], ["-", 12], [",", 68], [".", 28], ["1", 192], ["0", 155], ["3", 132], ["2", 89], ["5", 26], ["4", 56], ["7", 26], ["6", 74], ["9", 37], ["8", 12], [";", 12], [":", 14], ["?", 2], ["@", 10], ["]", 54], ["m", 2], ["t", 56], ["}", 18], ["|", 44]]], ["<", [["A", 64], ["C", 132], ["B", 10], ["E", 18], ["D", 14], ["G", 4], ["F", 20], ["I", 14], ["H", 94], ["K", 2], ["M", 14], ["L", 8], ["O", 14], ["N", 2], ["P", 14], ["S", 14], ["R", 10], ["T", 224], ["W", 24], ["Y", 2], ["m", 2], ["s", 2]]], ["@", [[" ", 102], ["c", 8], ["e", 14], [",", 8], [".", 8], ["u", 6], ["v", 16]]], ["D", [["!", 4], [" ", 358], ["'", 72], ["*", 16], ["-", 64], [",", 14], [".", 66], [";", 2], ["?", 2], ["A", 93], ["C", 2], ["E", 240], ["D", 2], ["G", 10], ["F", 8], ["I", 220], ["M", 2], ["L", 2], ["O", 89], ["N", 14], ["P", 2], ["S", 28], ["R", 70], ["U", 24], ["V", 2], ["Y", 12], ["a", 1027], ["e", 2124], ["i", 779], ["j", 6], ["m", 148], ["o", 2366], ["n", 8], ["r", 642], ["u", 914], ["w", 4], ["y", 20]]], ["H", [[" ", 112], ["'", 14], [",", 8], [".", 210], ["1", 126], ["3", 42], ["2", 54], ["5", 12], ["4", 12], ["7", 12], ["6", 12], ["9", 12], ["8", 12], ["?", 2], ["A", 410], ["E", 722], ["F", 4], ["I", 298], ["M", 4], ["O", 260], ["N", 2], ["Q", 4], ["S", 6], ["R", 20], ["U", 26], ["T", 60], ["Y", 20], ["a", 2890], ["e", 16114], ["i", 2886], ["h", 2], ["m", 2], ["o", 2880], ["s", 4], ["u", 596], ["v", 2], ["y", 24]]], ["L", [["!", 2], [" ", 102], ["'", 40], [")", 2], ["-", 4], [",", 10], [".", 40], ["1", 6], ["2", 8], ["5", 2], ["4", 2], ["6", 2], ["8", 2], [":", 8], ["A", 120], ["C", 14], ["E", 261], ["D", 38], ["G", 14], ["F", 26], ["I", 210], ["H", 4], ["K", 46], ["J", 2], ["M", 6], ["L", 134], ["O", 98], ["N", 2], ["P", 4], ["S", 36], ["R", 6], ["U", 84], ["T", 12], ["W", 2], ["Y", 32], ["a", 2534], ["e", 1957], ["i", 1482], ["h", 70], ["l", 2], ["o", 2216], ["u", 614], ["w", 2], ["y", 30]]], ["P", [["!", 2], [" ", 30], ["-", 4], [".", 72], ["A", 198], ["E", 228], ["G", 8], ["I", 66], ["H", 24], ["K", 2], ["M", 8], ["L", 90], ["O", 110], ["P", 26], ["S", 18], ["R", 198], ["U", 54], ["T", 202], ["Y", 10], ["a", 2387], ["e", 1866], ["f", 50], ["i", 2690], ["h", 472], ["l", 486], ["o", 1094], ["s", 84], ["r", 4898], ["u", 314], ["t", 12], ["w", 2], ["y", 38]]], ["T", [["!", 20], [" ", 496], ["'", 18], ["*", 34], ["-", 20], [",", 66], [".", 132], [":", 6], ["A", 150], ["C", 14], ["B", 2], ["E", 2568], ["F", 2], ["I", 236], ["H", 1216], ["M", 20], ["L", 24], ["O", 330], ["N", 14], ["P", 14], ["S", 62], ["R", 71], ["U", 70], ["T", 106], ["W", 110], ["Y", 144], ["Z", 2], ["a", 643], ["e", 802], ["i", 1134], ["h", 41758], ["o", 3328], ["s", 100], ["r", 532], ["u", 500], ["w", 517], ["v", 8], ["y", 54], ["z", 4]]], ["X", [["A", 2], [" ", 22], ["C", 6], ["E", 2], ["'", 2], ["I", 444], ["-", 2], [",", 4], [".", 84], ["1", 2], ["P", 6], ["2", 2], ["u", 30], ["T", 78], ["V", 302], ["X", 266], [":", 6], ["e", 4]]], ["`", [[" ", 4], ["\"", 2], ["'", 2], ["2", 2], ["A", 122], ["C", 26], ["B", 74], ["E", 14], ["D", 38], ["G", 30], ["F", 28], ["I", 270], ["H", 66], ["K", 4], ["J", 30], ["M", 66], ["L", 44], ["O", 26], ["N", 52], ["P", 34], ["S", 80], ["R", 14], ["U", 6], ["T", 166], ["W", 92], ["V", 4], ["Y", 66], ["_", 2], ["a", 62], ["c", 32], ["b", 40], ["e", 40], ["d", 24], ["g", 28], ["f", 38], ["i", 24], ["h", 26], ["k", 6], ["j", 2], ["m", 40], ["l", 28], ["o", 24], ["n", 14], ["q", 2], ["p", 40], ["s", 34], ["r", 18], ["u", 10], ["t", 98], ["w", 22], ["v", 2], ["y", 8]]], ["d", [["!", 1346], [" ", 316392], ["\"", 78], ["'", 892], [")", 158], ["-", 2110], [",", 27454], [".", 15448], ["1", 6], [";", 2238], [":", 1318], ["?", 904], [">", 32], ["]", 6], ["_", 10], ["a", 15612], ["`", 12], ["c", 64], ["b", 98], ["e", 66856], ["d", 5952], ["g", 2672], ["f", 682], ["i", 36856], ["h", 178], ["k", 152], ["j", 316], ["m", 1162], ["l", 4894], ["o", 27386], ["n", 2680], ["q", 32], ["p", 44], ["s", 12352], ["r", 13004], ["u", 5376], ["t", 176], ["w", 382], ["v", 1300], ["y", 5438], ["z", 4], ["}", 6]]], ["h", [["!", 1480], [" ", 66490], ["\"", 16], ["'", 580], [")", 46], ["-", 674], [",", 7634], [".", 3060], [";", 500], [":", 124], ["?", 354], [">", 8], ["_", 8], ["a", 130321], ["`", 2], ["c", 78], ["b", 454], ["e", 366316], ["d", 180], ["g", 2], ["f", 464], ["i", 118000], ["h", 16], ["k", 98], ["m", 1012], ["l", 810], ["o", 56794], ["n", 878], ["q", 34], ["p", 20], ["s", 1392], ["r", 8693], ["u", 9628], ["t", 23686], ["w", 410], ["v", 4], ["y", 4342], ["z", 2]]], ["l", [["!", 688], [" ", 55493], ["\"", 28], ["'", 776], [")", 58], ["*", 8], ["-", 1168], [",", 9058], ["/", 2], [".", 4175], ["1", 2], ["2", 4], [";", 588], [":", 138], ["?", 512], [">", 18], ["@", 2], ["]", 2], ["_", 14], ["a", 40424], ["c", 880], ["b", 428], ["e", 90647], ["d", 35897], ["g", 498], ["f", 11866], ["i", 53960], ["h", 30], ["k", 3952], ["j", 880], ["m", 2350], ["l", 72010], ["o", 43088], ["n", 488], ["q", 6], ["p", 1936], ["s", 9240], ["r", 1482], ["u", 8878], ["t", 7890], ["w", 1710], ["v", 3288], ["y", 43772], ["x", 2], ["z", 52]]], ["p", [["!", 222], [" ", 12684], ["\"", 12], ["'", 274], [")", 8], ["*", 16], ["-", 458], [",", 2678], [".", 1598], [";", 206], [":", 32], ["?", 102], [">", 2], ["_", 2], ["a", 24384], ["c", 110], ["b", 74], ["e", 40018], ["d", 12], ["g", 26], ["f", 100], ["i", 12578], ["h", 3890], ["k", 248], ["m", 220], ["l", 19938], ["o", 24960], ["n", 82], ["p", 12676], ["s", 4980], ["r", 27372], ["u", 7468], ["t", 8624], ["w", 150], ["y", 1538], ["z", 4]]], ["t", [["!", 1698], [" ", 244288], ["\"", 74], ["'", 4144], [")", 206], ["*", 10], ["-", 2634], [",", 24442], ["/", 22], [".", 15012], ["9", 30], [";", 1952], [":", 386], ["?", 2014], [">", 34], ["@", 16], ["I", 4], ["N", 2], ["]", 6], ["_", 20], ["a", 36864], ["c", 4804], ["b", 164], ["e", 93708], ["d", 32], ["g", 50], ["f", 1186], ["i", 67393], ["h", 380618], ["k", 30], ["j", 2], ["m", 1109], ["l", 15192], ["o", 120320], ["n", 980], ["p", 168], ["s", 20376], ["r", 31046], ["u", 18070], ["t", 25046], ["w", 8348], ["v", 6], ["y", 14950], ["x", 22], ["z", 596]]], ["x", [["!", 16], [" ", 1654], ["'", 108], [")", 6], ["-", 174], [",", 480], ["/", 2], [".", 262], ["1", 10], [";", 40], [":", 6], ["?", 20], ["_", 4], ["a", 1314], ["c", 2462], ["b", 4], ["e", 1456], ["g", 2], ["f", 26], ["i", 1676], ["h", 354], ["l", 20], ["o", 82], ["q", 56], ["p", 3828], ["s", 6], ["u", 144], ["t", 3514], ["w", 4], ["y", 88], ["x", 30]]], ["|", [[" ", 30], ["C", 294]]], ["#", [["1", 6], [" ", 2]]], ["'", [["!", 22], [" ", 5218], ["\"", 130], ["'", 52], [")", 8], ["-", 136], [",", 274], [".", 194], ["9", 24], ["8", 10], [";", 12], [":", 4], ["?", 40], ["A", 506], ["C", 94], ["B", 292], ["E", 88], ["D", 124], ["G", 154], ["F", 90], ["I", 826], ["H", 360], ["K", 12], ["J", 52], ["M", 174], ["L", 102], ["O", 202], ["N", 222], ["Q", 12], ["P", 86], ["S", 328], ["R", 24], ["U", 38], ["T", 922], ["W", 482], ["V", 22], ["Y", 356], ["a", 288], ["c", 614], ["b", 42], ["e", 614], ["d", 2832], ["g", 48], ["f", 28], ["i", 98], ["h", 36], ["k", 6], ["m", 1148], ["l", 1792], ["o", 90], ["n", 44], ["q", 2], ["p", 40], ["s", 16835], ["r", 660], ["u", 62], ["t", 7172], ["w", 60], ["v", 880], ["y", 66], ["}", 2]]], ["+", [[";", 2], ["B", 2], ["-", 4]]], ["/", [[" ", 26], ["\"", 2], ["e", 20], ["I", 14], ["h", 6], ["1", 2], ["s", 2], ["2", 4], ["5", 4], ["4", 2], ["6", 2]]], ["3", [["!", 2], [" ", 76], [")", 18], ["*", 8], ["-", 6], [",", 98], ["/", 2], [".", 66], ["1", 54], ["0", 158], ["3", 44], ["2", 60], ["5", 42], ["4", 18], ["7", 38], ["6", 24], ["9", 26], ["8", 20], [";", 10], [":", 48], ["?", 2], ["@", 4], ["]", 60], ["d", 6], ["i", 4], ["h", 2], ["r", 50], ["t", 26], ["v", 2], ["}", 18], ["|", 38]]], ["7", [["!", 2], [" ", 64], ["'", 10], ["-", 8], [",", 68], ["/", 4], [".", 46], ["1", 21], ["0", 36], ["3", 12], ["2", 35], ["5", 16], ["4", 14], ["7", 32], ["6", 26], ["9", 40], ["8", 34], [";", 10], [":", 28], ["@", 18], ["]", 48], ["h", 2], ["m", 4], ["t", 34], ["}", 18], ["|", 26]]], [";", [[" ", 14368], ["\"", 42], ["'", 54], ["h", 2], ["*", 2], ["-", 146], [",", 2], ["[", 4]]], ["?", [[" ", 5000], ["\"", 7386], ["'", 680], [")", 14], ["-", 90], [",", 2], [".", 118], ["[", 2], ["?", 2], [">", 2]]], ["C", [[" ", 50], ["\"", 14], ["'", 12], ["*", 2], ["-", 4], [",", 6], ["/", 2], [".", 24], ["A", 126], ["C", 22], ["E", 112], ["D", 20], ["I", 76], ["H", 3260], ["K", 60], ["L", 26], ["O", 164], ["P", 6], ["S", 8], ["R", 38], ["U", 26], ["T", 117], ["Y", 16], ["a", 2763], ["e", 294], ["i", 277], ["h", 2428], ["l", 446], ["o", 4926], ["s", 4], ["r", 556], ["u", 212], ["y", 42], ["z", 24]]], ["G", [["!", 2], [" ", 132], ["\"", 8], ["'", 8], ["-", 56], [",", 22], [".", 10], [";", 2], [":", 2], ["?", 4], ["A", 72], ["E", 134], ["G", 10], ["F", 2], ["I", 34], ["H", 70], ["L", 16], ["O", 60], ["N", 14], ["S", 10], ["R", 64], ["U", 92], ["T", 2], ["Y", 2], ["Z", 2], ["a", 744], ["e", 958], ["d", 2], ["i", 460], ["h", 266], ["l", 212], ["o", 2628], ["n", 6], ["r", 1160], ["u", 880], ["w", 2], ["y", 2]]], ["K", [[" ", 28], ["'", 2], [",", 6], [".", 8], ["?", 2], ["A", 4], ["E", 64], ["F", 2], ["I", 44], ["H", 2], ["K", 4], ["L", 12], ["O", 2], ["N", 4], ["S", 12], ["R", 6], ["U", 2], ["W", 4], ["Y", 2], ["a", 442], ["e", 504], ["i", 860], ["h", 122], ["l", 40], ["o", 290], ["n", 96], ["r", 96], ["u", 782], ["y", 10]]], ["O", [["!", 6], [" ", 466], ["\"", 2], ["'", 106], ["-", 4], [",", 12], [".", 38], [":", 2], ["?", 2], ["A", 6], ["C", 47], ["B", 32], ["E", 13], ["D", 52], ["G", 52], ["F", 288], ["I", 18], ["H", 28], ["K", 222], ["J", 50], ["M", 160], ["L", 98], ["O", 78], ["N", 489], ["P", 30], ["S", 64], ["R", 346], ["U", 338], ["T", 104], ["W", 64], ["V", 39], ["Y", 8], ["Z", 2], ["a", 2], ["c", 234], ["b", 128], ["e", 2], ["d", 26], ["g", 14], ["f", 1458], ["i", 6], ["h", 1000], ["k", 2], ["m", 60], ["l", 240], ["o", 44], ["n", 3744], ["p", 86], ["s", 22], ["r", 798], ["u", 554], ["t", 162], ["w", 32], ["v", 74], ["y", 2], ["x", 6], ["z", 68]]], ["S", [["!", 8], [" ", 616], ["'", 12], ["*", 6], ["-", 20], [",", 40], [".", 122], [";", 2], [":", 12], ["?", 2], ["A", 56], ["C", 58], ["E", 296], ["D", 2], ["G", 4], ["F", 4], ["I", 91], ["H", 76], ["K", 8], ["M", 14], ["L", 10], ["O", 98], ["N", 2], ["Q", 4], ["P", 30], ["S", 104], ["R", 2], ["U", 42], ["T", 322], ["W", 4], ["Y", 2], ["a", 2150], ["c", 1208], ["e", 1405], ["i", 968], ["h", 5152], ["k", 34], ["m", 374], ["l", 166], ["o", 4132], ["n", 120], ["q", 44], ["p", 776], ["s", 2], ["u", 1246], ["t", 1564], ["w", 144], ["v", 8], ["y", 126], ["z", 18]]], ["W", [["!", 2], [" ", 58], [")", 2], [",", 10], [".", 28], ["A", 136], ["E", 96], ["D", 4], ["G", 2], ["I", 90], ["H", 128], ["L", 4], ["O", 76], ["N", 12], ["S", 2], ["R", 8], ["Y", 4], ["a", 1096], ["e", 4362], ["i", 2096], ["h", 10098], ["o", 1611], ["r", 58], ["u", 18]]], ["[", [["*", 2], ["1", 112], ["3", 56], ["2", 112], ["5", 30], ["4", 40], ["7", 4], ["6", 34], ["9", 4], ["8", 2], ["A", 12], ["C", 2], ["B", 6], ["E", 24], ["D", 4], ["G", 14], ["F", 2], ["I", 22], ["H", 30], ["J", 34], ["M", 28], ["L", 16], ["N", 4], ["P", 42], ["S", 6], ["R", 36], ["T", 18], ["W", 4], ["a", 2], ["b", 4], ["d", 2], ["g", 2], ["f", 14], ["m", 2], ["l", 4], ["o", 4], ["p", 6], ["s", 4], ["t", 50]]], ["_", [[" ", 100], ["'", 2], ["-", 12], [",", 38], [".", 28], [";", 4], ["A", 14], ["D", 2], ["I", 30], ["H", 4], ["M", 4], ["L", 2], ["O", 2], ["N", 2], ["T", 12], ["_", 736], ["^", 6], ["a", 14], ["c", 12], ["b", 4], ["e", 6], ["d", 6], ["f", 14], ["i", 4], ["h", 2], ["m", 8], ["l", 6], ["o", 2], ["n", 14], ["p", 4], ["s", 10], ["r", 2], ["u", 4], ["t", 10], ["w", 8], ["v", 4], ["y", 4], ["x", 4]]], ["c", [["!", 38], [" ", 2940], ["\"", 6], ["'", 62], ["-", 122], [",", 498], [".", 480], [";", 56], [":", 18], ["?", 22], ["C", 8], ["G", 8], ["F", 2], ["L", 230], ["Q", 2], ["P", 2], ["S", 2], ["a", 38996], ["c", 5012], ["e", 54872], ["d", 38], ["i", 13186], ["h", 55038], ["k", 20111], ["m", 4], ["l", 12408], ["o", 57624], ["n", 26], ["q", 496], ["p", 66], ["s", 944], ["r", 13732], ["u", 9748], ["t", 19868], ["w", 8], ["v", 6], ["y", 1692], ["z", 12]]], ["g", [["!", 572], [" ", 77496], ["\"", 32], ["'", 490], [")", 44], ["-", 1388], [",", 8820], [".", 5284], [";", 654], [":", 276], ["?", 530], [">", 4], ["a", 16556], ["c", 8], ["b", 10], ["e", 31120], ["d", 134], ["g", 3662], ["f", 14], ["i", 11514], ["h", 36708], ["m", 368], ["l", 8714], ["o", 16464], ["n", 4300], ["p", 22], ["s", 6714], ["r", 16774], ["u", 6849], ["t", 1104], ["w", 42], ["y", 516], ["z", 14], ["}", 8]]], ["k", [["!", 306], [" ", 20132], ["\"", 14], ["'", 392], [")", 32], ["-", 554], [",", 4148], [".", 2414], ["1", 2], [";", 294], [":", 60], ["?", 214], [">", 10], ["@", 10], ["a", 870], ["c", 66], ["b", 38], ["e", 34087], ["d", 24], ["g", 58], ["f", 344], ["i", 13220], ["h", 948], ["k", 244], ["j", 22], ["m", 100], ["l", 2880], ["o", 816], ["n", 11134], ["q", 2], ["p", 12], ["s", 4228], ["r", 68], ["u", 68], ["t", 20], ["w", 314], ["v", 10], ["y", 768], ["z", 2]]], ["o", [["!", 648], [" ", 114177], ["\"", 18], ["'", 1162], [")", 38], ["-", 958], [",", 5210], [".", 2232], [";", 354], [":", 58], ["?", 516], ["K", 2], ["J", 2], ["]", 4], ["_", 6], ["a", 7834], ["`", 2], ["c", 9710], ["b", 5854], ["e", 2996], ["d", 16602], ["g", 5294], ["f", 99287], ["i", 10524], ["h", 872], ["k", 14852], ["j", 986], ["m", 51326], ["l", 30027], ["o", 36626], ["n", 131194], ["q", 172], ["p", 16136], ["s", 26802], ["r", 99219], ["u", 128095], ["t", 47116], ["w", 48246], ["v", 20522], ["y", 3366], ["x", 840], ["z", 456], ["}", 2]]], ["s", [["!", 2144], [" ", 245069], ["\"", 154], ["'", 1554], [")", 266], ["*", 14], ["-", 1948], [",", 37726], [".", 19990], ["1", 4], [";", 3000], [":", 928], ["=", 2], ["?", 1424], [">", 50], ["[", 6], ["]", 38], ["_", 24], ["a", 37342], ["c", 11410], ["b", 1092], ["e", 89922], ["d", 372], ["g", 288], ["f", 1206], ["i", 41018], ["h", 48184], ["k", 7002], ["j", 20], ["m", 5638], ["l", 7892], ["o", 41490], ["n", 2836], ["q", 1070], ["p", 17022], ["s", 38918], ["r", 118], ["u", 22362], ["t", 98283], ["w", 5082], ["v", 104], ["y", 2112], ["z", 8]]], ["w", [["!", 302], [" ", 25552], ["\"", 32], ["'", 332], [")", 38], ["-", 630], [",", 4620], ["/", 2], [".", 2130], [";", 296], [":", 56], ["?", 312], [">", 6], ["_", 4], ["a", 69912], ["c", 62], ["b", 88], ["e", 43746], ["d", 980], ["g", 230], ["f", 300], ["i", 50742], ["h", 55558], ["k", 232], ["j", 2], ["m", 12], ["l", 1768], ["o", 28157], ["n", 11280], ["p", 14], ["s", 3452], ["r", 3078], ["u", 116], ["t", 106], ["w", 8], ["y", 240], ["z", 2]]], ["{", [["`", 2], ["c", 2], ["E", 2], ["G", 2], ["s", 6], ["o", 4], ["1", 224], ["3", 226], ["2", 230], ["5", 24], ["4", 34], ["7", 22], ["6", 22], ["9", 22], ["8", 24], ["t", 8]]], ["\"", [[" ", 19496], ["\"", 12], ["'", 120], [")", 34], ["*", 70], ["-", 198], [",", 42], [".", 98], ["1", 4], ["3", 2], ["2", 4], ["5", 4], ["4", 4], ["6", 2], ["8", 6], [";", 74], [":", 2], ["?", 4], ["A", 4542], ["C", 1250], ["B", 2388], ["E", 472], ["D", 1474], ["G", 1096], ["F", 924], ["I", 8984], ["H", 2746], ["K", 138], ["J", 270], ["M", 1850], ["L", 912], ["O", 1848], ["N", 2630], ["Q", 110], ["P", 880], ["S", 1906], ["R", 350], ["U", 236], ["T", 5524], ["W", 6722], ["V", 340], ["Y", 4228], ["X", 4], ["[", 14], ["Z", 6], ["]", 8], ["_", 20], ["a", 732], ["`", 158], ["c", 118], ["b", 452], ["e", 46], ["d", 138], ["g", 54], ["f", 182], ["i", 408], ["h", 256], ["k", 10], ["j", 14], ["m", 148], ["l", 118], ["o", 112], ["n", 94], ["q", 4], ["p", 130], ["s", 230], ["r", 36], ["u", 32], ["t", 1014], ["w", 398], ["v", 22], ["y", 272]]], ["&", [["h", 2], ["c", 8], [" ", 26]]], ["*", [[" ", 206], ["\"", 146], [")", 6], ["*", 636], [",", 12], [".", 4], [":", 8], [">", 2], ["A", 16], ["C", 4], ["B", 16], ["E", 20], ["D", 8], ["G", 2], ["F", 12], ["I", 6], ["H", 4], ["K", 4], ["L", 4], ["O", 6], ["N", 2], ["P", 2], ["S", 16], ["T", 92], ["W", 18], ["V", 14], ["Y", 2], ["[", 36], ["]", 54], ["n", 6]]], [".", [["!", 36], [" ", 88376], ["\"", 12990], ["'", 1624], [")", 132], ["(", 2], ["*", 27], ["-", 436], [",", 236], [".", 4176], ["0", 16], ["2", 8], ["4", 6], ["7", 2], ["6", 2], ["9", 14], [";", 20], [":", 166], ["?", 38], ["A", 46], ["C", 12], ["B", 12], ["E", 20], ["D", 4], ["G", 22], ["F", 12], ["I", 138], ["H", 38], ["K", 2], ["J", 2], ["M", 34], ["L", 10], ["O", 10], ["N", 20], ["Q", 2], ["P", 8], ["S", 38], ["R", 2], ["U", 4], ["T", 108], ["W", 42], ["V", 6], ["Y", 20], ["[", 26], ["]", 10], ["_", 8], ["a", 4], ["`", 6], ["c", 32], ["b", 2], ["e", 36], ["i", 16], ["m", 26], ["o", 2], ["s", 4], ["u", 24], ["t", 40], ["x", 10], ["z", 2]]], ["2", [[" ", 128], ["\"", 2], ["'", 6], [")", 12], ["*", 6], ["-", 20], [",", 132], ["/", 2], [".", 82], ["1", 127], ["0", 229], ["3", 90], ["2", 98], ["5", 112], ["4", 96], ["7", 78], ["6", 88], ["9", 51], ["8", 80], [";", 4], [":", 56], ["@", 14], ["]", 70], ["d", 6], ["n", 28], ["t", 20], ["}", 20], ["|", 66]]], ["6", [[" ", 60], ["-", 12], [",", 70], ["/", 2], [".", 30], ["1", 24], ["0", 76], ["3", 14], ["2", 34], ["5", 26], ["4", 19], ["7", 26], ["6", 32], ["9", 21], ["8", 22], [";", 10], [":", 32], ["?", 2], ["@", 10], ["]", 44], ["m", 4], ["t", 68], ["}", 18], ["|", 52]]], [":", [[" ", 3056], ["\"", 2], ["'", 20], [")", 2], ["(", 8], ["*", 2], ["-", 1142], [".", 260], ["1", 118], ["I", 4], ["3", 44], ["2", 90], ["5", 14], ["4", 30], ["7", 14], ["6", 16], ["9", 12], ["8", 12], ["R", 4], ["r", 4]]], [">", [[" ", 88], ["#", 2], ["\"", 4], ["$", 2], ["-", 2], [",", 2], [":", 2], ["<", 24], ["A", 2], ["@", 2], ["C", 2], ["F", 8], ["I", 10], ["M", 2], ["L", 2], ["T", 14], ["W", 4], ["_", 2], ["^", 2], ["a", 6], ["c", 8], ["f", 10], ["i", 12], ["h", 6], ["m", 8], ["o", 8], ["p", 2], ["s", 8], ["t", 8], ["w", 6], ["v", 2], ["{", 2]]], ["B", [[" ", 16], ["'", 2], [",", 4], [".", 12], ["A", 44], ["C", 38], ["B", 6], ["E", 200], ["I", 62], ["K", 702], ["M", 6], ["L", 69], ["O", 247], ["S", 8], ["R", 26], ["U", 52], ["Y", 62], ["a", 2602], ["e", 3594], ["i", 1068], ["h", 100], ["j", 2], ["l", 520], ["o", 2392], ["r", 974], ["u", 8016], ["w", 2], ["y", 828]]], ["F", [["A", 194], [" ", 300], ["E", 36], ["F", 18], ["I", 98], ["j", 2], ["l", 372], ["O", 166], [",", 2], [">", 2], ["i", 958], ["r", 5046], ["U", 14], ["o", 3334], ["a", 2482], ["e", 430], ["R", 78], [".", 10], ["u", 184], ["L", 20], ["T", 30]]], ["J", [["A", 18], ["a", 1388], ["E", 82], ["d", 2], ["'", 2], ["I", 2], ["-", 2], ["o", 2830], [".", 132], ["i", 314], ["s", 2], ["U", 30], ["O", 54], ["e", 1904], ["u", 1679]]], ["N", [["!", 6], [" ", 451], ["\"", 8], ["'", 28], ["-", 4], [",", 48], [".", 96], [";", 2], [":", 8], ["?", 2], ["A", 108], ["C", 124], ["B", 48], ["E", 247], ["D", 328], ["G", 216], ["F", 2], ["I", 92], ["H", 2], ["K", 22], ["J", 2], ["L", 4], ["O", 186], ["N", 40], ["S", 124], ["R", 13], ["U", 20], ["T", 298], ["V", 13], ["Y", 14], ["a", 3392], ["e", 2202], ["i", 1384], ["o", 4850], ["u", 72]]], ["R", [["!", 2], [" ", 2352], ["\"", 4], ["'", 20], ["*", 6], ["-", 4], [",", 78], [".", 718], [":", 2], ["?", 2], ["A", 178], ["C", 20], ["B", 12], ["E", 320], ["D", 100], ["G", 68], ["F", 4], ["I", 219], ["K", 70], ["M", 30], ["L", 42], ["O", 189], ["N", 84], ["Q", 2], ["P", 18], ["S", 90], ["R", 70], ["U", 34], ["T", 272], ["W", 16], ["V", 14], ["Y", 93], ["a", 374], ["e", 1237], ["i", 323], ["h", 52], ["o", 2304], ["u", 2014], ["t", 2], ["y", 20]]], ["V", [["A", 47], ["a", 1798], ["B", 2], ["E", 276], ["'", 2], [" ", 18], ["I", 587], ["-", 2], [",", 12], ["O", 26], ["l", 30], ["i", 510], ["r", 4], ["U", 2], ["o", 228], ["y", 26], ["e", 465], ["R", 22], [".", 162], ["u", 4], ["Y", 6]]], ["Z", [["a", 32], ["\"", 2], ["E", 16], ["d", 4], ["I", 2], ["h", 68], [",", 4], ["o", 22], ["n", 30], ["i", 26], ["u", 10], ["O", 4], ["e", 124]]], ["b", [["!", 40], [" ", 1058], ["'", 68], [")", 4], ["*", 4], ["-", 98], [",", 414], [".", 244], [";", 24], [":", 6], ["?", 36], [">", 4], ["a", 13924], ["c", 22], ["b", 1618], ["e", 60104], ["d", 78], ["g", 4], ["f", 16], ["i", 6998], ["h", 46], ["j", 990], ["m", 324], ["l", 22082], ["o", 19980], ["n", 44], ["s", 2992], ["r", 13256], ["u", 20366], ["t", 1570], ["w", 30], ["v", 88], ["y", 13906]]], ["f", [["!", 178], [" ", 90391], ["\"", 8], ["'", 72], [")", 16], ["*", 2], ["-", 876], [",", 2770], [".", 1846], [";", 240], [":", 102], ["?", 144], ["G", 2], ["I", 2], ["a", 20108], ["c", 14], ["b", 38], ["e", 23990], ["d", 2], ["g", 10], ["f", 10886], ["i", 22788], ["h", 6], ["k", 12], ["j", 16], ["m", 12], ["l", 7808], ["o", 46468], ["n", 16], ["p", 2], ["s", 464], ["r", 21052], ["u", 10540], ["t", 10202], ["w", 62], ["v", 2], ["y", 396], ["x", 2]]], ["j", [["a", 724], ["!", 2], ["e", 4002], ["'", 2], ["i", 118], ["o", 3558], [".", 4], ["u", 4654]]], ["n", [["!", 1140], [" ", 164227], ["\"", 84], ["'", 9982], [")", 108], ["*", 6], ["-", 2184], [",", 19804], [".", 11592], [";", 1670], [":", 478], ["?", 1178], [">", 50], ["J", 4], ["]", 18], ["_", 4], ["a", 17316], ["c", 30762], ["b", 372], ["e", 74881], ["d", 155134], ["g", 116276], ["f", 3720], ["i", 23814], ["h", 996], ["k", 7828], ["j", 896], ["m", 518], ["l", 7014], ["o", 57750], ["n", 7832], ["q", 950], ["p", 298], ["s", 29725], ["r", 506], ["u", 4864], ["t", 72732], ["w", 558], ["v", 3580], ["y", 9090], ["x", 498], ["z", 154], ["}", 4]]], ["r", [["!", 1102], [" ", 128583], ["\"", 78], ["'", 2438], [")", 108], ["*", 14], ["-", 2050], [",", 18518], [".", 12898], [";", 1346], [":", 332], ["?", 1112], [">", 28], ["A", 2], ["@", 14], ["_", 6], ["a", 45838], ["c", 7992], ["b", 2520], ["e", 175663], ["d", 22490], ["g", 6450], ["f", 3064], ["i", 57977], ["h", 1474], ["k", 6764], ["j", 14], ["m", 12284], ["l", 8396], ["o", 61720], ["n", 15999], ["q", 220], ["p", 3358], ["s", 36440], ["r", 17042], ["u", 12282], ["t", 29678], ["w", 1522], ["v", 4906], ["y", 24200], ["x", 6], ["z", 128]]], ["v", [["!", 34], [" ", 1478], ["'", 360], [")", 2], ["-", 58], [",", 566], [".", 316], [";", 12], [":", 4], ["?", 30], ["_", 2], ["a", 8210], ["e", 85189], ["g", 2], ["i", 17242], ["k", 2], ["m", 16], ["l", 218], ["o", 6350], ["n", 508], ["s", 216], ["r", 658], ["u", 248], ["t", 4], ["v", 22], ["y", 640]]], ["z", [["!", 8], [" ", 344], ["\"", 2], ["'", 14], [")", 4], ["-", 40], [",", 172], [".", 178], [";", 8], [":", 2], ["?", 22], ["a", 592], ["b", 6], ["e", 3788], ["d", 18], ["g", 8], ["i", 920], ["h", 122], ["k", 6], ["m", 104], ["l", 356], ["o", 1122], ["n", 2], ["s", 6], ["r", 2], ["u", 156], ["v", 14], ["y", 202], ["z", 622]]], ["~", [[")", 6]]], ["\t", [["\t", 174], [" ", 136], ["D", 2]]], ["!", [["!", 12], [" ", 7580], ["\"", 6860], ["'", 556], [")", 42], ["*", 12], ["-", 108], [",", 4], [".", 170], ["I", 2], ["v", 6], ["[", 2], ["_", 6]]], ["%", [[" ", 8]]], [")", [[" ", 830], ["-", 56], [",", 506], [".", 102], ["5", 2], ["[", 2], [":", 16], [";", 58], ["?", 2]]], ["-", [["!", 8], [" ", 5090], ["\"", 550], ["'", 68], ["(", 2], ["+", 4], ["-", 6008], [",", 22], [".", 2], ["1", 12], ["2", 16], ["5", 24], ["4", 2], ["7", 4], ["6", 6], ["8", 4], ["?", 22], ["A", 170], ["C", 118], ["B", 200], ["E", 88], ["D", 116], ["G", 118], ["F", 62], ["I", 194], ["H", 172], ["K", 16], ["J", 90], ["M", 196], ["L", 74], ["O", 38], ["N", 44], ["Q", 6], ["P", 134], ["S", 172], ["R", 44], ["T", 160], ["W", 74], ["V", 28], ["Y", 22], ["Z", 4], ["a", 1098], ["`", 16], ["c", 1092], ["b", 1366], ["e", 476], ["d", 942], ["g", 452], ["f", 1014], ["i", 408], ["h", 966], ["k", 224], ["j", 64], ["m", 808], ["l", 922], ["o", 468], ["n", 446], ["q", 40], ["p", 884], ["s", 1836], ["r", 562], ["u", 122], ["t", 1410], ["w", 812], ["v", 66], ["y", 140], ["z", 12]]], ["1", [[" ", 112], ["'", 4], [")", 16], ["*", 10], ["-", 14], [",", 112], ["/", 2], [".", 68], ["1", 246], ["0", 318], ["3", 164], ["2", 280], ["5", 224], ["4", 214], ["7", 188], ["6", 204], ["9", 126], ["8", 572], [";", 4], [":", 40], ["@", 4], ["O", 2], ["]", 48], ["s", 52], ["t", 22], ["}", 18], ["|", 88]]], ["5", [[" ", 98], ["\"", 2], ["'", 2], ["-", 4], [",", 88], [".", 46], ["1", 22], ["0", 140], ["3", 28], ["2", 32], ["5", 32], ["4", 22], ["7", 32], ["6", 16], ["9", 14], ["8", 18], [";", 10], [":", 48], ["?", 2], ["@", 14], ["]", 64], ["t", 82], ["}", 18], ["|", 44]]], ["9", [[" ", 74], ["'", 2], [")", 4], ["-", 6], [",", 40], [".", 22], ["1", 26], ["0", 43], ["3", 48], ["2", 14], ["5", 18], ["4", 15], ["7", 34], ["6", 20], ["9", 18], ["8", 10], [";", 12], [":", 38], ["@", 6], ["]", 44], ["t", 32], ["}", 18], ["|", 46]]], ["=", [["E", 2], ["=", 8], ["T", 14], [" ", 12]]], ["A", [[" ", 4464], ["\"", 2], ["'", 12], ["-", 18], [",", 4], [".", 24], ["A", 6], ["C", 108], ["B", 58], ["E", 22], ["D", 77], ["G", 50], ["F", 18], ["I", 98], ["H", 10], ["K", 18], ["M", 89], ["L", 220], ["N", 497], ["Q", 2], ["P", 2116], ["S", 220], ["R", 481], ["U", 44], ["T", 292], ["W", 18], ["V", 78], ["Y", 66], ["X", 6], ["Z", 2], ["a", 2], ["c", 208], ["b", 496], ["e", 2], ["d", 372], ["g", 352], ["f", 1144], ["i", 66], ["h", 554], ["k", 64], ["j", 4], ["m", 1358], ["l", 3042], ["o", 140], ["n", 12454], ["q", 4], ["p", 230], ["s", 2898], ["r", 1643], ["u", 754], ["t", 3060], ["w", 48], ["v", 60], ["y", 30], ["x", 2], ["z", 30]]], ["E", [["!", 20], [" ", 1253], ["\"", 2], ["'", 18], ["*", 2], ["-", 14], [",", 30], [".", 100], [":", 8], ["?", 4], ["A", 176], ["C", 152], ["B", 30], ["E", 92], ["D", 166], ["G", 32], ["F", 34], ["I", 60], ["H", 6], ["K", 8], ["M", 80], ["L", 142], ["O", 14], ["N", 490], ["Q", 6], ["P", 124], ["S", 360], ["R", 730], ["U", 18], ["T", 184], ["W", 90], ["V", 102], ["Y", 34], ["X", 64], ["a", 450], ["c", 46], ["b", 14], ["d", 90], ["g", 62], ["f", 20], ["i", 64], ["h", 58], ["k", 6], ["m", 1500], ["l", 226], ["o", 4], ["n", 1398], ["q", 20], ["p", 138], ["s", 148], ["r", 118], ["u", 358], ["t", 98], ["v", 1326], ["y", 70], ["x", 298], ["z", 2], ["}", 2]]], ["I", [["!", 34], [" ", 40514], ["\"", 4], ["'", 2748], ["-", 52], [",", 526], [".", 576], [";", 42], [":", 6], ["?", 88], ["A", 76], ["C", 182], ["B", 47], ["E", 82], ["D", 78], ["G", 140], ["F", 78], ["I", 1054], ["K", 12], ["M", 76], ["L", 150], ["O", 134], ["N", 704], ["Q", 4], ["P", 18], ["S", 277], ["R", 122], ["U", 2], ["T", 378], ["V", 298], ["X", 156], ["Z", 8], ["_", 46], ["a", 2], ["c", 146], ["b", 10], ["d", 16], ["g", 48], ["f", 1944], ["m", 196], ["l", 216], ["o", 30], ["n", 5298], ["p", 28], ["s", 930], ["r", 122], ["t", 8656], ["v", 100], ["x", 2], ["z", 2]]], ["M", [["!", 4], [" ", 68], ["\"", 2], ["'", 12], ["-", 4], [",", 12], ["/", 8], [".", 1208], [":", 2], ["A", 346], ["C", 28], ["B", 34], ["E", 243], ["D", 6], ["G", 12], ["I", 130], ["M", 24], ["L", 2], ["O", 117], ["N", 16], ["P", 50], ["S", 26], ["R", 8], ["U", 28], ["W", 6], ["Y", 24], ["a", 8688], ["c", 378], ["e", 1576], ["f", 2], ["i", 2158], ["o", 4266], ["s", 2], ["r", 2578], ["u", 518], ["y", 1492]]], ["Q", [["U", 48], ["C", 2], ["u", 494], [".", 4]]], ["U", [["!", 2], [" ", 106], ["'", 6], [",", 2], [".", 10], ["A", 16], ["C", 48], ["B", 24], ["E", 54], ["D", 44], ["G", 12], ["F", 6], ["I", 12], ["K", 2], ["M", 60], ["L", 68], ["N", 116], ["P", 26], ["S", 130], ["R", 182], ["U", 2], ["T", 156], ["V", 2], ["Z", 6], ["c", 2], ["g", 12], ["h", 34], ["k", 4], ["m", 16], ["l", 30], ["n", 859], ["p", 360], ["s", 32], ["r", 68], ["t", 50], ["v", 16]]], ["Y", [["!", 4], [" ", 260], ["\"", 2], ["'", 4], ["-", 68], [",", 10], [".", 22], [";", 2], ["A", 2], ["B", 2], ["E", 26], ["L", 4], ["O", 112], ["S", 26], ["R", 4], ["T", 2], ["a", 122], ["c", 2], ["e", 1328], ["i", 10], ["o", 3878], ["s", 10], ["u", 26], ["v", 8]]], ["]", [["!", 2], [" ", 322], ["J", 2], ["-", 2], [",", 44], [".", 14], [";", 24], [">", 2]]], ["a", [["!", 310], [" ", 65518], ["\"", 24], ["'", 716], [")", 20], ["*", 1], ["-", 724], [",", 2766], [".", 1558], ["1", 2], [";", 152], [":", 30], ["?", 144], [">", 2], ["S", 2], ["_", 6], ["a", 122], ["`", 6], ["c", 35608], ["b", 19042], ["e", 752], ["d", 56288], ["g", 18377], ["f", 7666], ["i", 47228], ["h", 1140], ["k", 13604], ["j", 480], ["m", 24754], ["l", 68865], ["o", 314], ["n", 216874], ["q", 102], ["p", 18548], ["s", 105951], ["r", 97182], ["u", 12725], ["t", 135418], ["w", 10880], ["v", 25744], ["y", 29029], ["x", 666], ["z", 1906], ["}", 2]]], ["e", [["!", 3010], [" ", 487805], ["\"", 166], ["'", 4249], [")", 336], ["*", 10], ["-", 4298], [",", 40540], [".", 24278], [";", 3704], [":", 890], ["?", 2866], [">", 78], ["B", 2], ["I", 2], ["S", 2], ["[", 6], ["]", 18], ["_", 42], ["a", 79086], ["`", 2], ["c", 27918], ["b", 1598], ["e", 45884], ["d", 142368], ["g", 8394], ["f", 13916], ["i", 18692], ["h", 2842], ["k", 1590], ["j", 380], ["m", 31126], ["l", 54118], ["o", 4898], ["n", 129345], ["q", 1706], ["p", 17078], ["s", 100714], ["r", 205409], ["u", 2658], ["t", 41944], ["w", 11422], ["v", 24561], ["y", 23800], ["x", 14052], ["z", 560], ["}", 4]]], ["i", [["!", 50], [" ", 1222], ["\"", 2], ["'", 184], [")", 4], ["*", 2], ["-", 384], [",", 450], [".", 254], [";", 14], [":", 6], ["?", 14], ["@", 2], ["G", 2], ["Y", 2], ["]", 2], ["_", 8], ["a", 10716], ["c", 45183], ["b", 6986], ["e", 33445], ["d", 40015], ["g", 26388], ["f", 17002], ["i", 24], ["h", 72], ["k", 7006], ["j", 18], ["m", 40198], ["l", 43870], ["o", 33038], ["n", 232657], ["q", 394], ["p", 5884], ["s", 107323], ["r", 32008], ["u", 1844], ["t", 102683], ["w", 38], ["v", 16166], ["y", 2], ["x", 2074], ["z", 2892]]], ["m", [["!", 462], [" ", 35852], ["\"", 24], ["'", 294], [")", 58], ["-", 610], [",", 7564], [".", 6290], ["1", 2], [";", 758], [":", 298], ["?", 470], [">", 22], ["]", 2], ["a", 45673], ["c", 96], ["b", 7420], ["e", 83120], ["d", 36], ["g", 4], ["f", 768], ["i", 24836], ["h", 10], ["k", 22], ["m", 5770], ["l", 522], ["o", 32940], ["n", 1218], ["p", 15046], ["s", 8640], ["r", 202], ["u", 10278], ["t", 200], ["w", 24], ["y", 17480]]], ["q", [["a", 2], [" ", 2], ["u", 12073], [",", 2], ["'", 2]]], ["u", [["!", 428], [" ", 17752], ["\"", 16], ["'", 1182], [")", 6], ["-", 186], [",", 1924], [".", 1140], [";", 124], [":", 18], ["?", 428], ["S", 12], ["T", 2], ["_", 2], ["a", 6632], ["c", 12934], ["b", 5730], ["e", 10797], ["d", 6988], ["g", 18286], ["f", 2056], ["i", 9148], ["h", 30], ["k", 496], ["j", 84], ["m", 8440], ["l", 37068], ["o", 708], ["n", 43221], ["q", 64], ["p", 17232], ["s", 44836], ["r", 48568], ["u", 18], ["t", 49162], ["w", 10], ["v", 428], ["y", 210], ["x", 498], ["z", 722]]], ["y", [["!", 1032], [" ", 118640], ["\"", 62], ["'", 1440], [")", 154], ["-", 2010], [",", 18388], [".", 10860], [";", 1366], [":", 466], ["?", 946], [">", 26], ["]", 2], ["_", 4], ["a", 2624], ["`", 2], ["c", 242], ["b", 640], ["e", 11272], ["d", 206], ["g", 138], ["f", 198], ["i", 4422], ["h", 84], ["k", 76], ["m", 714], ["l", 818], ["o", 28106], ["n", 212], ["p", 410], ["s", 8723], ["r", 738], ["u", 58], ["t", 3028], ["w", 464], ["v", 110], ["x", 14], ["z", 40]]], ["}", [[" ", 6], [",", 2]]]]] -------------------------------------------------------------------------------- /domain_stats/domain-loader.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import datetime 3 | import argparse 4 | import pathlib 5 | import sys 6 | import os 7 | 8 | log = logging.getLogger("domain_stats_util_whois") 9 | 10 | from domain_stats.config import Config 11 | from domain_stats.expiring_diskcache import ExpiringCache 12 | from domain_stats.freq import FreqCounter 13 | from flask import Flask,jsonify 14 | 15 | 16 | def whois_patch_domain(domain, freq, alerts): 17 | who_rec = whois.whois(domain) 18 | if not who_rec: 19 | if args.verbose: print(f"No whois record found for {domain}") 20 | return 0 21 | created = who_rec.get('creation_date') 22 | if not created: 23 | if args.verbose: print(f"No creation date found for {domain}") 24 | return 0 25 | if isinstance(created,list): 26 | created = max(created) 27 | created = created.replace(tzinfo=datetime.timezone.utc) 28 | domain_age_seconds = (now - created).total_seconds() 29 | expires = who_rec.get("expiration_date") 30 | if not expires: 31 | if args.verbose: print(f"No expiration date found for {domain}") 32 | return 0 33 | if isinstance(expires,list): 34 | expires = max(expires) 35 | expires = expires.replace(tzinfo=datetime.timezone.utc) 36 | until_expires = (expires - now).total_seconds() 37 | if domain_age_seconds > (est_day_age *86400): 38 | category = "ESTABLISHED" 39 | else: 40 | category = "NEW" 41 | until_established = (est_day_age * 86400) - domain_age_seconds 42 | until_expires = min( until_expires, until_established ) 43 | with app.app_context(): 44 | resp = jsonify({"seen_by_web":created , "seen_by_isc":"WHOIS", "seen_by_you":now, "category":category, "alerts":alerts, "freq_score": freq}) 45 | if args.preview: 46 | print(f"Patchup record for {domain} \nTo {resp.json}") 47 | else: 48 | cache.cache.set( domain, resp.json, expire= until_expires, tag="whois") 49 | return 1 50 | 51 | app = Flask(__name__) 52 | app.name = "domain_stats" 53 | 54 | try: 55 | import whois 56 | except Exception as e: 57 | print(str(e)) 58 | print("You need to install the Python whois module. Install PIP (https://bootstrap.pypa.io/get-pip.py). Then 'pip install python-whois' ") 59 | sys.exit(0) 60 | 61 | parser = argparse.ArgumentParser() 62 | parser.add_argument("data_folder", help="Folder it data") 63 | parser.add_argument("-p","--preview", action="store_true", help="Do not commit to disk. Show changes.") 64 | parser.add_argument("-d","--domain_file", help="Open specified domain file and use whois to build entries.") 65 | parser.add_argument("-e","--errors", action="store_true", help="Try to use whois to resolve each entry with an RDAP error") 66 | parser.add_argument("-v","--verbose",action="store_true", help="Be verbose in output.") 67 | 68 | args = parser.parse_args() 69 | #current directory must be set by launcher to the location of the config and database 70 | cache = ExpiringCache(args.data_folder) 71 | config = Config( args.data_folder + "/domain_stats.yaml") 72 | 73 | est_day_age = config.get("established_days_age",720) 74 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 75 | 76 | if args.domain_file: 77 | fc = FreqCounter() 78 | fc.load( args.data_folder +"/" + config.get("freq_table", "freqtable2018.freq") ) 79 | written = 0 80 | for eachline in open(args.domain_file): 81 | domain = eachline.strip() 82 | freq = fc.probability(domain) 83 | written += whois_patch_domain(domain, freq, []) 84 | print(f"{written} entries added to database.") 85 | elif args.errors: 86 | written = 0 87 | for domain in cache.cache: 88 | val, expires = cache.cache.get(domain, expire_time=True) 89 | if val.get("seen_by_web") != "ERROR": 90 | continue 91 | whois_patch_domain(domain, val.get("freq_score"), val.get("alerts")) 92 | print(f"{written} rdap errors were fixed.") 93 | else: 94 | print("Use either the --domains or --errors argument.") 95 | 96 | cache.cache.close() -------------------------------------------------------------------------------- /domain_stats/expiring_diskcache.py: -------------------------------------------------------------------------------- 1 | from diskcache import FanoutCache 2 | import datetime 3 | 4 | class ExpiringCache: 5 | 6 | def __init__(self, cache_path): 7 | __slots__ = ["cache"] 8 | self.cache = FanoutCache(directory=cache_path, timeout=2, retry=True) 9 | 10 | def set(self, domain, domain_record, seconds_to_live, tag=None): 11 | self.cache.set(domain, domain_record.json, expire = seconds_to_live, tag=tag) 12 | 13 | def get(self, key): 14 | return self.cache.get(key) 15 | 16 | def cache_dump(self,offset=0, limit=100): 17 | res = [] 18 | for eachkey in self.cache: 19 | if offset != 0: 20 | offset -= 1 21 | continue 22 | if limit == 0: 23 | break 24 | val, expires = self.cache.get(eachkey, expire_time=True) 25 | if expires: 26 | exp_date = datetime.datetime.fromtimestamp(expires) 27 | else: 28 | exp_date = "Never" 29 | res.append( {"domain":eachkey,"cache_value": val ,"cache_expires":exp_date} ) 30 | limit -= 1 31 | return res 32 | 33 | def cache_get(self,key): 34 | val, expires = self.cache.get(key, expire_time=True) 35 | if not val: 36 | return {"text":"That domain is not in the database."} 37 | if expires: 38 | exp_date = datetime.datetime.fromtimestamp(expires) 39 | else: 40 | exp_date = "Never" 41 | res = {"domain":key,"cache_value": val ,"cache_expires":exp_date} 42 | return res 43 | 44 | def cache_info(self): 45 | hits,miss = self.cache.stats() 46 | size = self.cache.volume() 47 | warnings = self.cache.check(fix=True) 48 | return {"hit":hits, "miss":miss, "size": size, "warnings":warnings} 49 | 50 | -------------------------------------------------------------------------------- /domain_stats/freq.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | from __future__ import division 3 | 4 | import sys 5 | import string 6 | import re 7 | import weakref 8 | import json 9 | 10 | from collections import Counter, defaultdict 11 | from pprint import pprint 12 | 13 | class node(): 14 | """ 15 | A class to represent a node. 16 | 17 | Note: Assigning a weight actually adds that value. It doesn't set 18 | it to that value. For example node['c'] = 5 increases the value 19 | in node by 5 20 | 21 | Attributes 22 | ---------- 23 | 24 | parent : node 25 | the parent to this node 26 | count : int 27 | the current count for the node 28 | """ 29 | 30 | def __init__(self,parent): 31 | self.parent = parent 32 | self._pairs = Counter() 33 | self._cachecount = 0 34 | self._dirtycount = False 35 | 36 | def __getitem__(self,key): 37 | if self.parent.ignore_case and (key.islower() or key.isupper()): 38 | return self._pairs[key.lower()] + self._pairs[key.upper()] 39 | else: 40 | return self._pairs[key] 41 | 42 | def __setitem__(self,key,value): 43 | 44 | # TODO: should consider using the __addr__ magic method instead 45 | # since the described behavior is this instead 46 | self._dirtycount = True 47 | self._pairs[key] += value 48 | 49 | @property 50 | def count(self): 51 | if self._dirtycount: 52 | self._cachecount = sum(self._pairs.values()) 53 | self._dirtycount = False 54 | return self._cachecount 55 | 56 | class FreqCounter(dict): 57 | """ 58 | A class used for frequency counting. 59 | 60 | Attributes 61 | ---------- 62 | 63 | ignore_case : bool 64 | TODO: Update 65 | ignorechars : str 66 | TODO: Update 67 | verbose : bool 68 | When enabled, print verbose messages to the console. 69 | count : int 70 | The number of entries in the table 71 | 72 | 73 | Methods 74 | ------- 75 | 76 | toJSON() 77 | Returns a JSON representation of the Table as a string 78 | fromJSON(jsondata) 79 | Imports the JSON representation into the Table 80 | tally_str(line, weight=1) 81 | TODO: Update 82 | probability(line) 83 | Returns the probability of a given letter combination 84 | save(filename) 85 | Writes the table to a frequency file 86 | load(filename) 87 | Loads the table from a given frequency file 88 | printtable() 89 | Prints the JSON table to the console 90 | """ 91 | def __init__(self, *args,**kwargs): 92 | self._table = defaultdict(lambda :node(self)) 93 | self.ignore_case = False 94 | 95 | # TODO: consider refactoring to ignore_chars for consistency 96 | self.ignorechars = "" 97 | self.verbose = "verbose" in kwargs 98 | 99 | def __getitem__(self,key): 100 | return self._table[key] 101 | 102 | def __iter__(self): 103 | return iter(self._table) 104 | 105 | def __len__(self): 106 | return len(self._table) 107 | 108 | def toJSON(self): 109 | """ 110 | Returns a string JSON reperesentation of the table. 111 | """ 112 | serial = [] 113 | for key,val in self._table.items(): 114 | serial.append( (key, list(val._pairs.items())) ) 115 | return json.dumps((self.ignore_case, self.ignorechars, serial)) 116 | 117 | def fromJSON(self,jsondata): 118 | """ 119 | Imports the table from a string JSON representation of the table 120 | 121 | Parameters 122 | ---------- 123 | jsondata : str 124 | A string that represents the JSON Data 125 | 126 | Returns 127 | ------- 128 | str 129 | the JSON representation of the table 130 | """ 131 | 132 | # TODO: Raise an error if we get something that we didn't 133 | # expect. 134 | args = json.loads(jsondata) 135 | if args: 136 | self.ignore_case = args[0] 137 | self.ignorechars = args[1] 138 | for outerkey,val in args[2]: 139 | self._table[outerkey] = node(self) 140 | for letter,count in val: 141 | self._table[outerkey][letter] = count 142 | 143 | def tally_str(self,line,weight=1): 144 | """ 145 | TODO: Update 146 | 147 | Parameters 148 | ---------- 149 | line : string 150 | TODO: Update 151 | weight : int, optional 152 | the weight to be assigned to the pair (default = 1) 153 | """ 154 | allpairs = re.findall(r"..", line) 155 | allpairs.extend(re.findall(r"..",line[1:])) 156 | for eachpair in allpairs: 157 | self[eachpair[0]][eachpair[1]] = weight 158 | 159 | def probability(self,line): 160 | """ 161 | Calculates the probability of the word pair 162 | 163 | Parameters 164 | ---------- 165 | line : str 166 | TODO: Update 167 | 168 | Returns 169 | ------- 170 | float 171 | TODO: verify; the probability of the given word pair 172 | """ 173 | allpairs = re.findall(r"..", line) 174 | allpairs.extend(re.findall(r"..",line[1:])) 175 | if self.verbose: 176 | print("All pairs: {0}".format(allpairs)) 177 | probs = [] 178 | for eachpair in allpairs: 179 | pair = [eachpair[0], eachpair[1]] 180 | 181 | # check if any part of the pair should be ignored and alert 182 | # the user this was skipped 183 | if not all(x in self.ignorechars for x in pair): 184 | probs.append(self._probability(eachpair)) 185 | if self.verbose: 186 | print ("Probability of {0}: {1}".format(eachpair,probs)) 187 | elif self.verbose: 188 | print("Pair '{}' was ignored",format(self.ignorechars)) 189 | if probs: 190 | average_probability = sum(probs) / len(probs) * 100 191 | else: 192 | average_probability = 0.0 193 | if self.verbose: 194 | print("Average Probability: {0}% \n\n".format(average_probability)) 195 | 196 | totl1 = 0 197 | totl2 = 0 198 | for eachpair in allpairs: 199 | l1 = l2 = 0 200 | pair = [eachpair[0], eachpair[1]] 201 | 202 | if not all(x in self.ignorechars for x in pair): 203 | l1 += self[eachpair[0]].count 204 | if self.ignore_case and (eachpair[0].islower() or eachpair[0].isupper()): 205 | l1 += self[eachpair[0].swapcase()].count 206 | l2 += self[eachpair[0]][eachpair[1]] 207 | if self.ignore_case and (eachpair[0].islower() or eachpair[0].isupper()): 208 | l2 += self[eachpair[0].swapcase()][eachpair[1]] 209 | totl1 += l1 210 | totl2 += l2 211 | if self.verbose: 212 | print("Letter1:{0} Letter2:{1} - This pair {2}:{3} {4}:{5}".format( 213 | totl1, 214 | totl2, 215 | eachpair[0], 216 | l1, 217 | eachpair[1], 218 | l2 219 | )) 220 | if (totl1 == 0) or (totl2 == 0): 221 | total_word_probability = 0.0 222 | else: 223 | total_word_probability = totl2/totl1 * 100 224 | if self.verbose: print("Total Word Probability: {0}/{1} = {2}".format(totl2, totl1, total_word_probability)) 225 | return round(average_probability,4),round(total_word_probability,4) 226 | 227 | def _probability(self,twoletters): 228 | if self.ignore_case and (self[twoletters[0]].count == 0 and self[twoletters[0].swapcase()].count == 0): 229 | return 0.0 230 | if not self.ignore_case and self[twoletters[0]].count == 0: 231 | return 0.0 232 | if self.ignore_case and (twoletters[0].islower() or twoletters[0].isupper()): 233 | ignored_tot = sum([self[twoletters[0].lower()][eachlet] for eachlet in self.ignorechars]) + sum([self[twoletters[0].upper()][eachlet] for eachlet in self.ignorechars]) 234 | let2 = self[twoletters[0].lower()][twoletters[1]] + self[twoletters[0].upper()][twoletters[1]] 235 | let1 = self[twoletters[0].lower()].count + self[twoletters[0].upper()].count 236 | if let1 - ignored_tot == 0: 237 | return 0.0 238 | return let2/(let1-ignored_tot) 239 | else: 240 | ignored_tot = sum([self[twoletters[0]][eachlet] for eachlet in self.ignorechars]) 241 | if self[twoletters[0]].count - ignored_tot == 0: 242 | return 0.0 243 | return self[twoletters[0]][twoletters[1]] / (self[twoletters[0]].count - ignored_tot) 244 | 245 | def save(self,filename): 246 | try: 247 | file_handle = open(filename, 'wb') 248 | file_handle.write(self.toJSON().encode("latin1")) 249 | file_handle.flush() 250 | file_handle.close() 251 | except Exception as e: 252 | print("Unable to write freq file :" + str(e)) 253 | raise(e) 254 | 255 | def load(self,filename): 256 | try: 257 | file_handle = open(filename,"rb") 258 | self.fromJSON(file_handle.read().decode("latin1")) 259 | file_handle.close() 260 | except Exception as e: 261 | print("Unable to load freq file :",str(e)) 262 | raise(e) 263 | 264 | @property 265 | def count(self): 266 | return sum(map(lambda y:y.count, x._table.values())) 267 | 268 | def printtable(self): 269 | pprint(self.toJSON()) 270 | 271 | 272 | 273 | if __name__ == "__main__": 274 | import argparse 275 | import os 276 | parser=argparse.ArgumentParser() 277 | parser.add_argument( 278 | '-m', 279 | '--measure', 280 | required=False, 281 | help='Measure likelihood of a given string', 282 | dest='measure' 283 | ) 284 | parser.add_argument( 285 | '-n', 286 | '--normal', 287 | required=False, 288 | help='Update the table based on the following normal string', 289 | dest='normal' 290 | ) 291 | parser.add_argument( 292 | '-f', 293 | '--normalfile', 294 | required=False, 295 | help='Update the table based on the contents of the normal file', 296 | dest='normalfile' 297 | ) 298 | parser.add_argument( 299 | '-p', 300 | '--print', 301 | action='store_true', 302 | required=False, 303 | help='Print a table of the most likely letters in order', 304 | dest='printtable' 305 | ) 306 | parser.add_argument( 307 | '-c', 308 | '--create', 309 | action='store_true', 310 | required=False, 311 | help='Create a new empty frequency table',dest='create' 312 | ) 313 | parser.add_argument( 314 | '-v', 315 | '--verbose', 316 | action='store_true', 317 | required=False, 318 | help='show calculation process', 319 | dest='verbose' 320 | ) 321 | 322 | parser.add_argument( 323 | '-b', 324 | '--bulk', 325 | default=None, 326 | required=False, 327 | help='Measure every line in a file.', 328 | dest='bulk' 329 | ) 330 | 331 | # TODO: break these up as well 332 | parser.add_argument('-t','--toggle_case_sensitivity',action='store_true',required=False,help='Ignore case in all future frequecy tabulations',dest='toggle_case') 333 | parser.add_argument('-s','--case_sensitive',action='store_true',required=False,help='Consider case in calculations. Default ignores case.',dest='case_sensitive') 334 | parser.add_argument('-w','--weight',type=int,default = 1, required=False,help='Affects weight of promote, update and update file (default is 1)',dest='weight') 335 | parser.add_argument('-e','--exclude',default = "\n\t~`!@#$%^&*()_+-", required=False,help='Provide a list of characters to ignore from the tabulations.',dest='exclude') 336 | parser.add_argument('freqtable',help='File storing character frequencies.') 337 | 338 | args=parser.parse_args() 339 | 340 | if args.verbose: 341 | fc = FreqCounter(verbose=True) 342 | else: 343 | fc = FreqCounter() 344 | if args.create and os.path.exists(args.freqtable): 345 | print("Frequency table already exists. " + args.freqtable) 346 | sys.exit(1) 347 | 348 | if not args.create: 349 | if not os.path.exists(args.freqtable): 350 | print("Frequency Character file not found. - %s " % (args.freqtable)) 351 | raise(Exception("File not found.")) 352 | fc.load(args.freqtable) 353 | 354 | if args.printtable: 355 | fc.printtable() 356 | if args.normal: 357 | fc.tally_str(args.normal, args.weight) 358 | if args.toggle_case: 359 | print("This feature has been depricated. By default all calculations ignore case. Use -s to consider case.") 360 | fc.ignore_case = not args.case_sensitive 361 | fc.ignorechars = args.exclude 362 | if args.verbose: 363 | print("Ignoring Case: {0}".format(fc.ignore_case)) 364 | if args.verbose: 365 | print("Ignoring Characters: {0}".format(fc.ignorechars)) 366 | if args.normalfile: 367 | with open(args.normalfile,"rb") as filehandle: 368 | for eachline in filehandle: 369 | fc.tally_str(eachline.decode("latin1")) 370 | if args.measure: 371 | print(fc.probability(args.measure)) 372 | if args.bulk: 373 | with open(args.bulk,"rt") as filehandle: 374 | for eachline in filehandle: 375 | print(fc.probability(eachline),"-",eachline) 376 | 377 | fc.save(args.freqtable) -------------------------------------------------------------------------------- /domain_stats/launch.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import os 3 | import sys 4 | from domain_stats.settings import setup_directory 5 | 6 | 7 | 8 | def launch_from_config(tgt_folder): 9 | os.chdir(tgt_folder) 10 | launch_cmd = f"""{sys.executable} -m gunicorn.app.wsgiapp 'domain_stats.server:config_app("{tgt_folder}")' -c {tgt_folder}/gunicorn_config.py""" 11 | print(f"Running {launch_cmd}") 12 | os.system(launch_cmd) 13 | 14 | def main(): 15 | if len(sys.argv) != 2: 16 | typed_folder = input("Where do you want to store your domain_stats data and binaries? ") 17 | else: 18 | typed_folder = sys.argv[1] 19 | 20 | tgt_folder = pathlib.Path(typed_folder) 21 | if typed_folder.startswith("."): 22 | tgt_folder = pathlib.Path().cwd() / tgt_folder 23 | if not tgt_folder.is_dir(): 24 | print("That directory does not exist. Please create it and/or try again.") 25 | sys.exit(1) 26 | if (tgt_folder / "domain_stats.yaml").is_file(): 27 | print("Existing config found in directory. Using it.") 28 | launch_from_config(str(tgt_folder)) 29 | elif input("Would you like to setup this directory now?").lower().startswith("y"): 30 | setup_directory(tgt_folder) 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | 36 | -------------------------------------------------------------------------------- /domain_stats/network_io.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import json 4 | import random 5 | import datetime 6 | 7 | 8 | log = logging.getLogger("domain_stats") 9 | 10 | def dateconverter(o): 11 | if isinstance(o, datetime.datetime): 12 | return o.strftime("%Y-%m-%d %H:%M:%S") 13 | 14 | class IscConnection(): 15 | def __init__(self, enabled = True, login=None, token = None): 16 | self.isc_enabled = enabled 17 | self.isc_login = login 18 | self.isc_authtoken = token 19 | self.prohibited_tlds = [] 20 | 21 | 1#to isc 22 | #{"command" : "query", "domain": toplevel.tld} 23 | #response: 24 | ### ISC Response is a JSON packet in the following format: 25 | # { "seen_by_web" = Domain Created Date in format YYYY-mm-DD HH:MM:SS, (If domain has multiple dates this is the most recent) 26 | # "expires" = domain expiration date Date in format YYYY-mm-DD HH:MM:SS, (if domain has multiple dates this is the most recent) 27 | # "seen_by_isc" = date when ISC first queried whoisxml to build this record in format YYYY-mm-DD HH:MM:SS,als 28 | # "alerts" = A list of strings to make the user aware of regarding the domain in question (for later use) formta is ['alert1','alert2'] 29 | ##STub an ISC response 30 | 31 | #When a client starts it sends a status to isc. ISC can force database updates on client, deny client access 32 | #To isc 33 | #{"command": "status", "client_version":"client version number","database_version":database version info, cache_efficiency": [hit,miss,expired], "database_efficiency": [hit,miss]} 34 | #response: 35 | # {"current_database_version": "database version expected", "interval": "number of seconds ISC wishes to wait until next status update", "deny_client": "client message"} 36 | 37 | def get_status(self,client_version, database_version, cache_stats, database_stats): 38 | #To isc 39 | #submit = json.dumps({"command":"status", "client_version":client_version, "database_version":database_version, "cache_efficiency":[cache.hits, cache.miss, cache.expire], "database_efficiency":[database_stats.hits, database_stats.miss]) 40 | #{"command": "status", "client_version":"client version number","database_version":database version info, cache_efficiency": [hit,miss,expired], "database_efficiency": [hit,miss]} 41 | #response from isc 42 | # { "interval": "number of minutes ISC wishes to wait until next status update", "deny_client": "client message"} 43 | #functions returns tuple: 44 | # Position 1 of Tuple is boolean representing "CRITICAL ERROR" which, when True causes the program to abort. 45 | # a list of messages to give to the clients regarding its health and operating ability 46 | fake_isc_response = json.dumps({"interval":5, "deny_client":""}) 47 | isc_response = json.loads(fake_isc_response) 48 | interval = isc_response.get("interval", 60) 49 | deny_client = isc_response.get("deny_client") 50 | if deny_client: 51 | reason = ",".join(deny_client) 52 | log.info("The ISC denied the client. Reason: {}".format(reason)) 53 | self.isc_enable = False 54 | return interval 55 | 56 | def get_config(self): 57 | #To isc 58 | #submit = json.dumps({"command":"config"}) 59 | # 60 | #response from isc 61 | # {"min_database_version": database version expected","min_client_version":client version expected,prohibited_tlds:[] } 62 | #functions returns tuple: 63 | # Position 1 min client version 64 | # Position 2 in min database version 65 | fake_isc_response = json.dumps({"min_database_version":1.2, "min_client_version":1.0, "prohibited_tlds": ['.local','.arpa]']}) 66 | isc_response = json.loads(fake_isc_response) 67 | self.prohibited_tlds.extend(isc_response.get("prohibited_tlds", [])) 68 | return isc_response.get("min_client_version"), isc_response.get("min_database_version") 69 | 70 | def health_check(self, client_version, database_version, cache, database_stats): 71 | #To isc 72 | #submit = json.dumps({"command":"status", "client_version":client_version, "database_version":database_version, "cache_efficiency":[cache.hits, cache.miss, cache.expire], "database_efficiency":[database_stats.hits, database_stats.miss]) 73 | #{"command": "status", "client_version":"client version number","database_version":database version info, cache_efficiency": [hit,miss,expired], "database_efficiency": [hit,miss]} 74 | #response from isc 75 | # {"expected_database_version": "database version expected","expected_client_version":client version expected, "interval": "number of minutes ISC wishes to wait until next status update", "deny_client": "client message", "notice":['messages' 'to' 'client']} 76 | #functions returns tuple: 77 | # Position 1 of Tuple is boolean representing "CRITICAL ERROR" which, when True causes the program to abort. 78 | # a list of messages to give to the clients regarding its health and operating ability 79 | client_messages = [] 80 | fake_isc_response = json.dumps({"expected_database_version":1.1, "expected_client_version":1.0, "interval":5, "deny_client":"", "notice":['message1']}) 81 | isc_response = json.loads(fake_isc_response) 82 | expected_database = isc_response.get("expected_database_version") 83 | if expected_database != database_version: 84 | log.debug("Database is out of date. ISC expected {}. Running {}".format(expected_database, database_version) ) 85 | return ( True, 0.1 , ["UPDATE-DATABASE", str(expected_database)] ) 86 | expected_client = isc_response.get("expected_client_version") 87 | if expected_client != client_version: 88 | log.debug("Warning Client Software is out of data.") 89 | client_messages.append("Your version of domain_stats is out of date. Please update.") 90 | deny_client = isc_response.get("deny_client") 91 | if deny_client: 92 | client_messages.insert(0, deny_client) 93 | client_messages.extend(isc_response.get("notice")) 94 | return ( deny_client, isc_response.get("interval", 60), client_messages ) 95 | 96 | def get_server_config(self): 97 | #To isc 98 | #submit = json.dumps({"command":"config"}, "client_version":client_version, "database_version":database_version}) 99 | # 100 | #response from isc 101 | # {"expected_database_version": "database version expected","expected_client_version":client version expected, "prohibited_tlds":['.local' 'to' 'arpa']} 102 | #resp = request.post( , configrequest) 103 | resp = json.loads(json.dumps({'expected_database_version':1.0, 'expected_client_version':1.0, 'prohibited_tlds': ['.local', '.arpa'] })) 104 | if sorted(resp.keys()) != ['expected_client_version', 'expected_database_version', 'prohibited_tlds']: 105 | print("Invalid ISC response requesting server config {}".format(resp)) 106 | log.info("Invalid ISC response requesting server config {0}".format(resp)) 107 | return resp 108 | 109 | 110 | def retrieve_isc(self, domain): 111 | #to isc 112 | #{"command" : "query", "domain": toplevel.tld} 113 | ### ISC Response is a JSON packet in the following format: 114 | # { "seen_by_web" = Domain Created Date in format YYYY-mm-DD HH:MM:SS, (If domain has multiple dates this is the most recent) 115 | # "expires" = domain expiration date Date in format YYYY-mm-DD HH:MM:SS, (if domain has multiple dates this is the most recent) 116 | # "seen_by_isc" = date when ISC first queried whoisxml to build this record in format YYYY-mm-DD HH:MM:SS,als 117 | # "alerts" = A list of strings to make the user aware of regarding the domain in question (for later use) formta is ['alert1','alert2'] 118 | ##Stub an ISC response 119 | if not self.isc_enabled: 120 | return ("ERROR","ERROR", 0, ['ISC Lookups disabled. See Log for details.']) 121 | fake_alerts = [] 122 | fake_date1 = (datetime.datetime.now() - datetime.timedelta(days=random.randrange(365,3000))).replace(microsecond=0).isoformat().replace("T"," ") 123 | if bool(random.getrandbits(1)): 124 | fake_date1= datetime.datetime.utcnow() 125 | fake_alerts = ['ISC-FIRST-CONTACT'] 126 | fake_date2 = (datetime.datetime.now() - datetime.timedelta(days=random.randrange(365,3000))).replace(microsecond=0).isoformat().replace("T"," ") 127 | fake_date3 = (datetime.datetime.now() + datetime.timedelta(days=random.randrange(365,3000))).replace(microsecond=0).isoformat().replace("T"," ") 128 | fake_isc_response1 = json.dumps({"seen_by_web":fake_date2, "expires":fake_date3, "seen_by_isc":fake_date1, "alerts":fake_alerts}, default=dateconverter) 129 | #ISC can also generate Error responses and define how long the error is cached on the client (preventing repeated queries) 130 | #Those responses look like this: 131 | #{ "seen_by_web" = "ERROR", 132 | # "expires = "ERROR" 133 | # "seen_by_isc = hours to live for this error in client cache for the queried domain. 0=dont cache,-1=dont expire but allow lru,-2=permenant (use with caution)" 134 | # "alerts" = ['alert1','alert2' ] list if alerts to associate with this query. } 135 | fake_error_ttl = random.randrange(-1,5) 136 | alertoptions= ['bad thing happened', 'domain doesnt exist','login expired','isc temporarily unavailable', 'bad domain','bad record from registrar','unable to connect to whois'] 137 | fake_alerts = [random.choice(alertoptions) for _ in range(random.randrange(1,3))] 138 | fake_isc_response2 = json.dumps({"seen_by_web":"ERROR", "expires":"ERROR", "seen_by_isc":fake_error_ttl, "alerts":fake_alerts}, default=dateconverter) 139 | fake_isc_response = random.choice([ fake_isc_response1]*5 + [fake_isc_response2]) 140 | #Process ISC response 141 | resp = json.loads(fake_isc_response) 142 | if sorted(resp.keys()) != ['alerts', 'expires', 'seen_by_isc', 'seen_by_web']: 143 | log.info("INVALID ISC RESPONSE MISSING KEY FIELDS {0}".format(resp)) 144 | raise Exception("ISC RESPONSE to domain request MISSING KEY FIELDS.") 145 | web = resp['seen_by_web'] 146 | if web != "ERROR": 147 | web = datetime.datetime.strptime(web, '%Y-%m-%d %H:%M:%S') 148 | expire = datetime.datetime.strptime(resp['expires'], '%Y-%m-%d %H:%M:%S') 149 | isc = resp['seen_by_isc'] 150 | if isc != "FIRST-CONTACT": 151 | isc = datetime.datetime.strptime(isc, '%Y-%m-%d %H:%M:%S') 152 | return (web,expire, isc, resp['alerts']) 153 | return ("ERROR","ERROR", resp['seen_by_isc'], resp['alerts']) -------------------------------------------------------------------------------- /domain_stats/rdap_query.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import requests 3 | import rdap 4 | import json 5 | import datetime 6 | import dateutil.parser 7 | import dateutil.tz 8 | import pathlib 9 | import os 10 | import sqlite3 11 | 12 | log = logging.getLogger("domain_stats") 13 | 14 | def get_config(update_url): 15 | try: 16 | config = requests.get( update_url + "/version.json").json() 17 | except Exception as e: 18 | print("Unable to retreive /version.json info from {} {}".format( update_url,str(e))) 19 | return 9999,99999 20 | return config.get("min_client_version"), config.get("min_database_version") 21 | 22 | 23 | def retrieve_data(action_name,eventlist): 24 | for entry in eventlist: 25 | if entry.get("eventAction") == action_name: 26 | return entry.get("eventDate") 27 | return None 28 | 29 | def get_domain_record(domain): 30 | client = rdap.client.RdapClient() 31 | client.url = "https://www.rdap.net" 32 | client.timeout = 5 33 | log.debug("RDAP Query of domain {0}".format(domain)) 34 | try: 35 | resp = client.get_domain(domain).data 36 | except Exception as e: 37 | return "ERROR","ERROR", str(e) 38 | reg = retrieve_data( 'registration', resp.get('events')) 39 | reg = dateutil.parser.isoparse(reg) 40 | reg.replace(tzinfo=datetime.timezone.utc) 41 | exp = retrieve_data( 'expiration', resp.get('events')) 42 | try: 43 | exp = dateutil.parser.isoparse(exp) 44 | except Exception as e: 45 | return "ERROR","ERROR", "Invalid RDAP response Domain:{} generated {}".format(domain,str(e)) 46 | exp.replace(tzinfo=datetime.timezone.utc) 47 | log.debug("RDAP Query of domain {0} resolved {1}".format(domain,resp)) 48 | return reg,exp,"" -------------------------------------------------------------------------------- /domain_stats/server.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from flask import Flask, jsonify, request, session, abort 3 | import functools 4 | import datetime 5 | import argparse 6 | import pathlib 7 | import sys 8 | import os 9 | 10 | log = logging.getLogger("domain_stats") 11 | default_flask_logger = logging.getLogger('werkzeug') 12 | default_flask_logger.setLevel(logging.CRITICAL) 13 | 14 | 15 | from publicsuffixlist import PublicSuffixList 16 | from domain_stats.config import Config 17 | from domain_stats.network_io import IscConnection 18 | import domain_stats.rdap_query as rdap 19 | from domain_stats.freq import FreqCounter 20 | from domain_stats.expiring_diskcache import ExpiringCache 21 | from diskcache import Cache 22 | 23 | 24 | #current directory must be set by launcher to the location of the config and database 25 | cache = ExpiringCache(os.getcwd()) 26 | memocache = Cache(pathlib.Path().cwd() / "memocache") 27 | if not memocache.get("rdap_good"): 28 | memocache.set("rdap_good",0) 29 | memocache.set("rdap_fail",0) 30 | config = Config(os.getcwd()+"/domain_stats.yaml") 31 | 32 | if config.get("enable_freq_scores"): 33 | freq = FreqCounter() 34 | freq.load(config.get("freq_table")) 35 | 36 | logfile = logging.FileHandler(str(pathlib.Path.cwd() / 'domain_stats.log')) 37 | logformat = logging.Formatter('%(asctime)s : %(levelname)s : %(module)s : %(process)d : %(message)s') 38 | logfile.setFormatter(logformat) 39 | if config['log_detail'] == 0: 40 | log.setLevel(level=logging.CRITICAL) 41 | elif config['log_detail'] == 1: 42 | log.addHandler(logfile) 43 | log.setLevel(logging.INFO) 44 | else: 45 | log.addHandler(logfile) 46 | log.setLevel(logging.DEBUG) 47 | 48 | app = Flask(__name__) 49 | app.name = "domain_stats" 50 | app.config['SESSION_TYPE'] = 'filesystem' 51 | app.config['SECRET_KEY'] ="Change This to a unique very long string for your installation. Make it a few hundred characters long. You never have to remember it or use it, but you want it to be unique to your install." 52 | app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(hours=10) 53 | #app.logger.removeHandler(default_handler) 54 | 55 | def json_response(web,isc,you,cat,alert,freq=None): 56 | resp = {"seen_by_web":web,"seen_by_isc":isc, "seen_by_you":you, "category":cat, "alerts":alert} 57 | if app.config.get("enable_freq_scores"): 58 | resp['freq_score'] = freq 59 | return jsonify(resp) 60 | 61 | @memocache.memoize(tag="reduce_domain") 62 | def reduce_domain(domain_in): 63 | if not PublicSuffixList().publicsuffix(domain_in,accept_unknown=False): 64 | return None 65 | domain = PublicSuffixList().privatesuffix(domain_in) 66 | if domain: 67 | domain=domain.lower() 68 | else: 69 | log.debug("No eTLD for {}".format(domain)) 70 | log.debug("Trimmed domain from {0} to {1}".format(domain_in,domain)) 71 | return domain 72 | 73 | @app.route("/stats", methods=['GET']) 74 | def cache_info(): 75 | res = cache.cache_info() 76 | res.update({ "rdap_good":memocache.get("rdap_good"), "rdap_fail": memocache.get("rdap_fail")}) 77 | return jsonify(res) 78 | 79 | @app.route("/stats-reset", methods=['GET']) 80 | def cache_reset(): 81 | cache.cache.stats(enable=True, reset=True) 82 | memocache.set("rdap_good",0) 83 | memocache.set("rdap_fail",0) 84 | return jsonify({"text":"Success"}) 85 | 86 | @app.route("/cache_browse", methods=['GET']) 87 | def cache_browse(): 88 | offset = request.args.get('offset',0, type=int) 89 | limit = request.args.get('limit',100, type=int) 90 | max_limit = min( limit, app.config.get("cache_browse_limit",100)) 91 | resp = cache.cache_dump(offset,max_limit) 92 | if len(resp) >= limit: 93 | resp.insert(0, {"next":f"{request.base_url}?offset={offset+limit}&limit={limit}"}) 94 | return jsonify(resp) 95 | 96 | @app.route("/cache_get", methods=['GET']) 97 | def cache_get(): 98 | domain = request.args.get('domain') 99 | if not domain: 100 | return jsonify({"text":"Try /cache_get?domain=markbaggett.com"}) 101 | resp = cache.cache_get(domain) 102 | return jsonify(resp) 103 | 104 | @app.route("/depuny", methods=['GET']) 105 | def depunyfy(): 106 | domain = request.args.get('domain') 107 | if not domain: 108 | return jsonify({"text":"Try /depuny?domain=xn--yutube-wqf.com"}) 109 | resp = domain.encode('utf-8').decode('idna') 110 | return jsonify(resp) 111 | 112 | @app.route("/", methods=['GET']) 113 | def get_domain(domain): 114 | log.debug("New Request for domain {0}.".format(domain) ) 115 | #Reduce the domain and produce an error if it can't be reduced 116 | domain = reduce_domain(domain) 117 | if not domain: 118 | return json_response("ERROR","ERROR","ERROR","ERROR",['No valid eTLD exists for this domain.'],'ERROR') 119 | #retreive value from cache and serve it without modification 120 | cache_data = cache.get(domain) 121 | log.debug("Is the domain in cache? {}".format(bool(cache_data))) 122 | if cache_data: 123 | return cache_data 124 | #Not in cache so build a new record, return it an store it in cache 125 | else: 126 | freq_score = "disabled" 127 | alerts = [] 128 | if app.config.get("enable_freq_scores"): 129 | freq_score = freq.probability(domain) 130 | if freq_score[0] < app.config.get("freq_avg_alert") and freq_score[1] < app.config.get("freq_word_alert"): 131 | alerts.append("LOW-FREQ-SCORES") 132 | elif freq_score[0] < app.config.get("freq_avg_alert") or freq_score[1] < app.config.get("freq_word_alert"): 133 | alerts.append("SUSPECT-FREQ-SCORE") 134 | if app.config.get("mode")=="rdap": 135 | alerts.append("YOUR-FIRST-CONTACT") 136 | rdap_seen_by_you = (datetime.datetime.utcnow()+datetime.timedelta(hours=app.config['timezone_offset'])) 137 | rdap_seen_by_web, rdap_expires, rdap_error = rdap.get_domain_record(domain) 138 | if rdap_error: 139 | cache_expiration = app.config.get("rdap_error_ttl_days",7) * 86400 140 | alerts.append(rdap_error) 141 | resp = json_response("ERROR","ERROR","ERROR","ERROR",alerts,freq_score) 142 | if "YOUR-FIRST-CONTACT" in alerts: 143 | alerts.remove("YOUR-FIRST-CONTACT") 144 | cache_resp = json_response("ERROR","ERROR","ERROR","ERROR",alerts, freq_score) 145 | cache.set(domain, cache_resp, seconds_to_live=cache_expiration) 146 | if app.config.get("count_rdap_errors",False): 147 | memocache.incr("rdap_fail") 148 | log.debug("rdap failed for domain {0}. Cached {1} seconds.".format(domain,cache_expiration) ) 149 | return resp 150 | #if not expires and its doesn't expire for two years then its established. 151 | est_day_age = app.config.get("established_days_age",720) 152 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 153 | domain_age_seconds = (now - rdap_seen_by_web).total_seconds() 154 | until_expires = (rdap_expires - now).total_seconds() 155 | if domain_age_seconds > (est_day_age *86400): 156 | category = "ESTABLISHED" 157 | else: 158 | category = "NEW" 159 | #It stays in the cache until it becomes established or it expires 160 | until_established = (est_day_age * 86400) - domain_age_seconds 161 | until_expires = min( until_expires, until_established ) 162 | resp = json_response(rdap_seen_by_web, "RDAP", rdap_seen_by_you, category, alerts , freq_score ) 163 | if "YOUR-FIRST-CONTACT" in alerts: 164 | alerts.remove("YOUR-FIRST-CONTACT") 165 | cache_response = json_response(rdap_seen_by_web, "RDAP", rdap_seen_by_you, category, alerts, freq_score ) 166 | cache.set(domain, cache_response, until_expires) 167 | if app.config.get("count_rdap_errors",False): 168 | memocache.incr("rdap_good") 169 | log.debug("rdap success for domain {0}.Expires {1}.Cached {2} {3}".format(domain,rdap_expires,until_expires,category) ) 170 | return resp 171 | else: 172 | #Mode is not RDAP ask SANS ISC for domain data 173 | return "ISC Mode is still in development" 174 | 175 | 176 | def config_app(working_path): 177 | working_path = pathlib.Path(working_path) 178 | if not working_path.is_dir(): 179 | print("Sorry. The path specified is invalid. The directory you provide must already exist.") 180 | sys.exit(1) 181 | if sys.version_info.minor < 5 or sys.version_info.minor < 3: 182 | print("Please update your installation of Python.") 183 | sys.exit(1) 184 | #Initialize the global variables 185 | if not (working_path / "domain_stats.yaml").exists(): 186 | print("No configuration file found.") 187 | sys.exit(1) 188 | yaml_path = str(working_path / "domain_stats.yaml") 189 | print("Using config {}".format( str(yaml_path))) 190 | app.config.update(config) 191 | os.chdir(working_path) 192 | return app 193 | 194 | if __name__ == "__main__": 195 | os.chdir("/home/student/mydata") 196 | x = config_app("/home/student/mydata") 197 | x.run(host="0.0.0.0",port=5730) 198 | 199 | -------------------------------------------------------------------------------- /domain_stats/settings.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import os 3 | import sys 4 | import shutil 5 | import yaml 6 | import multiprocessing 7 | 8 | 9 | def create_gunicorn_config(tgt_folder,ip,port,cpu,thread): 10 | gunicorn_config = f""" 11 | import gunicorn 12 | import multiprocessing 13 | import os 14 | 15 | os.environ["SERVER_SOFTWARE"] = "domain_stats" 16 | bind = "{ip}:{port}" 17 | workers = {cpu} 18 | threads = {thread} 19 | gunicorn.SERVER_SOFTWARE = 'domain_stats' 20 | """ 21 | config_file = pathlib.Path(tgt_folder / "gunicorn_config.py") 22 | config_file.write_text(gunicorn_config) 23 | 24 | def update_setting(config, key, default): 25 | current_val = config.get(key,default) 26 | new_val = input(f"Set value for {key}. Default={default} Current={current_val} (Enter to keep Current): ") or current_val 27 | config[key]= default.__class__(new_val) 28 | 29 | def setup_directory(tgt_folder): 30 | config = {} 31 | file_path = tgt_folder / "domain_stats.yaml" 32 | if file_path.is_file(): 33 | print("Existing config found in directory. Using it.") 34 | config = yaml.safe_load(file_path.read_text()) 35 | if not config: 36 | print("domain_stats.yaml config exists but is blank or could not be loaded. Erase the file to begin again.") 37 | sys.exit(1) 38 | source_folder = pathlib.Path(os.path.realpath(__file__)).parent 39 | if not (tgt_folder / "freqtable2018.freq").is_file(): 40 | shutil.copy(source_folder / "data/freqtable2018.freq", tgt_folder) 41 | #create gunicorn config 42 | update_setting(config, "ip_address", "127.0.0.1") 43 | update_setting(config, "local_port", 5730) 44 | rec_workers = multiprocessing.cpu_count() * 2 + 1 45 | update_setting(config, "workers", rec_workers) 46 | rec_threads = multiprocessing.cpu_count() * 3 47 | update_setting(config, "threads_per_worker", rec_threads) 48 | #Configure Additional settings in domain_stats.yaml 49 | update_setting(config,'timezone_offset', 0) 50 | update_setting(config,'established_days_age', 730) 51 | update_setting(config,'mode',"rdap") 52 | update_setting(config,"rdap_error_ttl_days",7) 53 | update_setting(config,'freq_table', 'freqtable2018.freq') 54 | update_setting(config,'enable_freq_scores', True) 55 | update_setting(config,'freq_avg_alert',5.0) 56 | update_setting(config,'freq_word_alert',4.0) 57 | update_setting(config,'log_detail',0) 58 | update_setting(config,'count_rdap_errors',False) 59 | update_setting(config,'cache_browse_limit',100) 60 | if input("Commit Changes to disk?").lower().startswith("y"): 61 | create_gunicorn_config(tgt_folder, config['ip_address'], config['local_port'],config['workers'], config['threads_per_worker']) 62 | with file_path.open('w') as fp: 63 | yaml.dump(config, fp, default_flow_style=False) 64 | print("Configuration Written.") 65 | import_pth = str(source_folder / "data/top1m.import") 66 | import_cmd = f"domain-stats-utils -i {import_pth} -nx {tgt_folder}" 67 | print("If this is a new installation you might consider preloading the top1m.import file with domain-stats-utils after starting the server.") 68 | print("Try: ",import_cmd) 69 | else: 70 | print("The configuration selected was not saved.") 71 | 72 | def main(): 73 | if len(sys.argv) != 2: 74 | typed_folder = input("Where do you want to store your domain_stats data and binaries? ") 75 | else: 76 | typed_folder = sys.argv[1] 77 | 78 | tgt_folder = pathlib.Path(typed_folder) 79 | if not tgt_folder.is_dir(): 80 | print("That directory does not exist. Please create it and/or try again.") 81 | sys.exit(1) 82 | 83 | setup_directory(tgt_folder) 84 | 85 | if __name__ == "__main__": 86 | main() 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /domain_stats/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import datetime 3 | import argparse 4 | import pathlib 5 | import sys 6 | import os 7 | import time 8 | import json 9 | import requests 10 | import pathlib 11 | 12 | 13 | log = logging.getLogger("domain_stats_util_whois") 14 | 15 | from domain_stats.config import Config 16 | from domain_stats.expiring_diskcache import ExpiringCache 17 | from domain_stats.freq import FreqCounter 18 | from flask import Flask,jsonify 19 | 20 | def max(listofdatetimes): 21 | m = None 22 | for eachd in listofdatetimes: 23 | if not isinstance(eachd,datetime.datetime): 24 | continue 25 | if eachd > m: 26 | m = eachd 27 | return m 28 | 29 | def to_json(**kwargs): 30 | with app.app_context(): 31 | resp = jsonify(**kwargs).json 32 | return resp 33 | 34 | 35 | def import_domain_rec(import_rec, never_expire=False): 36 | """ import rec is created by the export of this same program. Records look like this 37 | {"freq_score": [9.3769, 6.832], "seen_by_isc": "TOP1M", "seen_by_web": "Mon, 26 Nov 2018 01:42:03 GMT", "expires": 1637890923.0005548, "domain": "betterme-magazine.com"}, 38 | """ 39 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 40 | domain = import_rec.get("domain") 41 | created = import_rec.get("seen_by_web") 42 | isc_tag = pathlib.Path(args.importer).stem 43 | by_you = now 44 | alerts = [] 45 | freq = import_rec.get("freq_score") 46 | if freq[0] < app.config.get("freq_avg_alert", 5.0) and freq[1] < app.config.get("freq_word_alert",4.0): 47 | alerts.append("LOW-FREQ-SCORES") 48 | elif freq[0] < app.config.get("freq_avg_alert",5.0) or freq[1] < app.config.get("freq_word_alert",4.0): 49 | alerts.append("SUSPECT-FREQ-SCORE") 50 | created_as_date = datetime.datetime.strptime(created,"%a, %d %b %Y %H:%M:%S %Z") 51 | created_as_date = created_as_date.replace(tzinfo=datetime.timezone.utc) 52 | domain_age_seconds = (now - created_as_date).total_seconds() 53 | if domain_age_seconds > (app.config.get('established_days_age', 730) *86400): 54 | category = "ESTABLISHED" 55 | else: 56 | category = "NEW" 57 | expire = None 58 | record_expires = import_rec.get("expires") 59 | if not never_expire and record_expires: 60 | expire = datetime.datetime.fromtimestamp(record_expires).replace(tzinfo=datetime.timezone.utc) - now 61 | expire = expire.total_seconds() 62 | resp = to_json(**{"seen_by_web":created , "seen_by_isc":isc_tag, "seen_by_you":now, "category":category, "alerts":alerts, "freq_score": freq}) 63 | if args.verbose: 64 | print(f"Patchup record for {domain} \nTo {resp}") 65 | cache.cache.set( domain, resp, expire= expire, tag=isc_tag) 66 | return 1 67 | 68 | 69 | def whois_patch_domain(domain, alerts, freq=None): 70 | now = datetime.datetime.utcnow() 71 | try: 72 | who_rec = whois.whois(domain) 73 | except: 74 | return 0 75 | if not who_rec: 76 | if args.verbose: print(f"No whois record found for {domain}") 77 | return 0 78 | created = who_rec.get('creation_date') 79 | if not created: 80 | if args.verbose: print(f"No creation date found for {domain}") 81 | return 0 82 | if isinstance(created,list): 83 | created = max(created) 84 | if not isinstance(created, datetime.datetime): 85 | print(f"{created} is not datetime") 86 | return 0 87 | created = created.replace(tzinfo=datetime.timezone.utc) 88 | domain_age_seconds = (now - created).total_seconds() 89 | expires = who_rec.get("expiration_date") 90 | if not expires: 91 | if args.verbose: print(f"No expiration date found for {domain}") 92 | return 0 93 | if isinstance(expires,list): 94 | expires = max(expires) 95 | expires = expires.replace(tzinfo=datetime.timezone.utc) 96 | until_expires = (expires - now).total_seconds() 97 | if domain_age_seconds > (config.get('established_days_age', 730) *86400): 98 | category = "ESTABLISHED" 99 | else: 100 | category = "NEW" 101 | until_established = (config.get('established_days_age', 730) * 86400) - domain_age_seconds 102 | until_expires = min( until_expires, until_established ) 103 | if not freq: 104 | freq = fc.probability(domain) 105 | if freq[0] < config.get("freq_avg_alert", 5.0) and freq[1] < config.get("freq_word_alert",4.0): 106 | alerts.append("LOW-FREQ-SCORES") 107 | elif freq[0] < config.get("freq_avg_alert",5.0) or freq[1] < config.get("freq_word_alert",4.0): 108 | alerts.append("SUSPECT-FREQ-SCORE") 109 | with app.app_context(): 110 | resp = jsonify({"seen_by_web":created , "seen_by_isc":"WHOIS", "seen_by_you":now, "category":category, "alerts":alerts, "freq_score": freq}) 111 | print(f"Patchup record for {domain} \nTo {resp.json}") 112 | cache.cache.set( domain, resp.json, expire= until_expires, tag="whois") 113 | return 1 114 | 115 | app = Flask(__name__) 116 | app.name = "domain_stats" 117 | 118 | try: 119 | import whois 120 | except Exception as e: 121 | print(str(e)) 122 | print("You need to install the Python whois module. Install PIP (https://bootstrap.pypa.io/get-pip.py). Then 'pip install python-whois' ") 123 | sys.exit(0) 124 | 125 | args=config=cache=fc= None 126 | 127 | def main(): 128 | global args, config, cache, fc 129 | parser = argparse.ArgumentParser() 130 | parser.add_argument("data_folder", help="Folder with the domain data must be provided") 131 | parser.add_argument("-e","--export", help="Export database entries as json to the specified text file.") 132 | parser.add_argument("-i","--import", dest="importer", help="Import the specified json text file into the database.") 133 | parser.add_argument("-d","--domain_file", help="Open specified domain file and build records for them.") 134 | parser.add_argument("-f","--fix", action="store_true", help="Use whois to resolve each entry with an RDAP error") 135 | parser.add_argument("-nx","--no-expire", dest='noexpire', action="store_true", help="Set imported record never to expire instead of using domain expiration.") 136 | parser.add_argument("-v","--verbose",action="store_true", help="Be verbose in output.") 137 | 138 | args = parser.parse_args() 139 | #current directory must be set by launcher to the location of the config and database 140 | yaml_file = args.data_folder + "/domain_stats.yaml" 141 | if not pathlib.Path(yaml_file).is_file(): 142 | print("The specified data_folder does not contain a domain_stats.yaml configuration file.") 143 | exit(1) 144 | 145 | cache = ExpiringCache(args.data_folder) 146 | config = Config(yaml_file) 147 | 148 | establish_age = config.get("established_days_age",720) 149 | low_avg = config.get('freq_avg_alert',5.0) 150 | low_word = config.get('freq_word_alert',4.0) 151 | now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc) 152 | fc = FreqCounter() 153 | fc.load( args.data_folder +"/" + config.get("freq_table", "freqtable2018.freq") ) 154 | if args.domain_file: 155 | written = 0 156 | ip = config.get("ip_address","127.0.0.1") 157 | port = config.get("local_port") 158 | with open(args.domain) as domain_file: 159 | for eachline in domain_file: 160 | domain = eachline.strip() 161 | url = f"http://{ip}:{port}/{domain}" 162 | resp = requests.get(url).json() 163 | if resp.get("seen_by_web") == "ERROR": 164 | written += whois_patch_domain(domain, []) 165 | elif "FIRST CONTACT" in resp.get("alerts"): 166 | written += 1 167 | time.sleep(1) 168 | print(f"{written} entries added to database.") 169 | elif args.fix: 170 | written = 0 171 | for domain in cache.cache: 172 | val, expires = cache.cache.get(domain, expire_time=True) 173 | if not val: 174 | continue 175 | if val.get("seen_by_web") != "ERROR": 176 | continue 177 | written += whois_patch_domain(domain, val.get("alerts"), val.get("freq"),) 178 | print(f"{written} rdap errors were fixed.") 179 | elif args.export: 180 | result = [] 181 | for domain in cache.cache: 182 | val, expires = cache.cache.get(domain, expire_time=True) 183 | if not val: 184 | continue 185 | if val.get("seen_by_web")=="ERROR": 186 | continue 187 | val['seen_by_isc'] = args.export.split(".")[0] 188 | del val['category'] 189 | del val['seen_by_you'] 190 | del val['alerts'] 191 | val.update({"expires":expires, "domain":domain}) 192 | result.append(to_json(**val)) 193 | res = json.dumps(result) 194 | fh = open(args.export,"wt") 195 | fh.write(res) 196 | fh.close() 197 | elif args.importer: 198 | written = 0 199 | with open(args.importer) as fh: 200 | new_data = json.load(fh) 201 | for each_entry in new_data: 202 | import_domain_rec(each_entry, args.noexpire) 203 | else: 204 | print("What do you want me to do?") 205 | parser.print_help() 206 | 207 | cache.cache.close() 208 | 209 | 210 | if __name__=="__main__": 211 | main() 212 | -------------------------------------------------------------------------------- /overview.drawio: -------------------------------------------------------------------------------- 1 | 1VptU6s4FP41/Xg7gRTaflxbvTrjHd2tO173y50U0pIRCIZg2/31mxTCS4CW1qJ7dUbJIW8958lznhMdwFmw/c5Q5P2gLvYHJnC3AzgfmKYBgCV+ScsutdjGODWsGXGzToVhQf7FamRmTYiL40pHTqnPSVQ1OjQMscMrNsQY3VS7rahfXTVCa1wzLBzk163PxOVeap1YoLDfYrL21MriE6dvAqQ6Z4bYQy7dlEzwegBnjFKePgXbGfal85Rf0nE3LW/zjTEc8i4DvpMw+ufnG3qfPb3Zdzxi6wf7G0xneUd+kn3g26enx2zDfKe8IPYeyceVj7d/SK8O4BUO3exx7vgojokjjDFHjNfNHg98YTD2wzjb/RQNoBovsjG0VHO+Lb+c77LWJvO+dJxcO4PKeAjkrOmOsVsLZuEdhR7E1pgfcIlh5cERqMY0wGIbYmAG6W9gCMYjM51sU0BCIcIroUHZGPYRJ+/VvaEMmet8iXzVR0rErvMlDZjNk50hc2xWp4hpwhycjSpDQJvIhBPhrmnxNdHnHQJYem1Xl0ldV1tGhBvtSt0i2SFu3ojqQ1erGFdmEQ8ldxemPYpPQPSohuiBafsiIFcueRePa/l4F3LMQiQnW1zf/VA9xIKlTg3jlGnJdMvRoQvsJIzw3UNIaNh9FF1d+6/dl9XO7cYjHC8i5Mj2RjB09SyiOEo5c0W22M0neMeM4+3hg9R6PgwNq6pdOiqG2XBWcmPTuaiA5FREjLsg4low19InsSf8IHdio0A6K/2ZWs6N/A1hscT+jIYcOfJknBlNxcLOziehi5lkxcMBXtJEdHTvl7kBOa9rJq0PCRez4Mx+gcCbk2rkodUQedAQ+UlfgZ82BL7FpcIVr215qkhNL+V3LXkKbwkvDROtl9KbYpBsqDHds1fK9MfAXo/R5yQqCDQIjLXQdk1UUMt4UCeHllR0qSRi1HVRw8H+C69JzBlicWcueL59uFvsdSjrPOaKMpEwwEP4MRqaI45/p0Ri2VUMTOt0MvlMNjGalIXmpg9r4nO5ZmTDEttIjarYp5lxZOMRMyJcI/PIiSx0XEPDr6QhazoeTsdVGWJqWrYrE9manjF0Suubiawa6uY0QCT8JWDFY/lq5hMZoPqJvxfshENBTkAqTvA0E4UdeKSMn0AkDMcRDd14X3fnchm8JQI8OG7NpxGjDo7jDgqlRZDEaXkngTwFle8LqRVoaQCx6mpl2oDRqdUTv5h1fvl73mspfpmS+v9UKY9MLar29Lxjb+llTMdj314Lt2zYbl6nAFI646eX0YovS2i8W8z2VUwQJKEoZMWzLKPlTDd4XzVt5C5aeaVc1XoCRHLEs0eJpJY/BZ3ICWfI8fDHZE69dBM7VhvWSrGz5ZBwIIliLE+Zqsl8mrjH6e4CzDWaapAx6szVqIwMoy9pZE5qYLmnzv56RUV242GZg1IMpc4ygUtiUXTvkSD1MLhBZN9qV1UhlRniykX7Qj31aQchVUinw0KqLJzSa8lRjzLqaDGnypCz7yw/SW+NNY00OrPs08hwZPVDunp1aZgHSPdShAqN2hlpYC8XcbREMf6F3ICEw0h+rCjxfUmSSSTe4lyJ4cqNlRqo3jqZKDyBSvuScpfgPA0ZjXdLdhPngb44D5pd4rkm3EuWQ4cGJySwmwCx1yVaC6zz3yAh2V0u/pqufHsr1WHT9c25OrqcXlS9XUkRRyptlZKMIYCVnDS0jdzQlpdkq8cEA7sW9F96rahpcUu/DDw3vXxyKQ/rpfxlUJkjrAqvY39RLW6PDDCpINqGk8OY7lf2KGo9ikrYQkyfA0t7egRPZ+LS0uVT37isq/dMpiMp2Ymoncj+7hhwj+TyQ8gTEsgLA9FDii3gU3Qh6W6Oq+J9OLGOYrmJKEvXo2ZZ1UuVb3wpwLvSblqFf5mu1+7IoKXdfXW+TZloEwFtorMRLprFf9Ck3Yv/Q4LX/wE= -------------------------------------------------------------------------------- /overview.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MarkBaggett/domain_stats/759c52c84c8bdc98ad49a70e8828d8a91a9a9a3d/overview.jpg -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="domain_stats", 8 | version="1.0.1", 9 | author="MarkBaggett", 10 | author_email="lo127001@gmail.com", 11 | description="Malicious Domain Detection base on domain creation and first contact", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/markbaggett/domain_stats", 15 | license = "GNU General Public License v3 (GPLv3", 16 | packages=setuptools.find_packages(), 17 | install_requires = [ 18 | 'diskcache>=5.1.0', 19 | 'Flask>=1.1.2', 20 | 'gunicorn>=20.0.4', 21 | 'publicsuffixlist>=0.7.6', 22 | 'python-dateutil>=2.8.1', 23 | 'PyYAML>=5.3.1', 24 | 'rdap>=1.1.0', 25 | 'requests==2.25.1' 26 | ], 27 | include_package_data = True, 28 | classifiers=[ 29 | "Programming Language :: Python :: 3", 30 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 31 | "Operating System :: OS Independent", 32 | ], 33 | python_requires='>=3.6', 34 | entry_points = { 35 | 'console_scripts': ['domain-stats=domain_stats.launch:main', 36 | 'domain-stats-settings=domain_stats.settings:main', 37 | 'domain-stats-utils=domain_stats.utils:main'], 38 | }, 39 | package_data={'domain_stats': ['data/*.*']} 40 | ) 41 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | python -m gunicorn.app.wsgiapp 'server:config_app("/home/student/dsdata")' -c ./gunicorn_config.py 2 | 3 | --------------------------------------------------------------------------------