├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── pyproject.toml ├── samples ├── asyncio_example.py ├── exploits.py ├── linux_audit.py ├── search.py └── software_scanner.py ├── scripts └── format └── vulners ├── __init__.py ├── base.py ├── vscanner.py └── vulners.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # PyCharm 104 | .idea/ 105 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Primary authors: 2 | 3 | * Kirill Ermakov 4 | * Andrei Churin 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [Vulners API v3](https://vulners.com) Python wrapper 2 | 3 | 4 | # Description 5 | Python 3 library for the [Vulners Database](https://vulners.com). 6 | It provides *search, data retrieval, archive and vulnerability scanning* API's for the integration purposes. 7 | With this library you can create powerful security tools and get access to the world largest security database. 8 | 9 | ## How to install 10 | 11 | Package is available with [PyPI](https://pypi.python.org/pypi) 12 | 13 | You can use pip for the installation 14 | 15 | ```bash 16 | pip install -U vulners 17 | ``` 18 | 19 | ## Obtaining Vulners API key 20 | 21 | Please, register at [Vulners website](https://vulners.com). 22 | Go to the personal menu by clicking at your name at the right top corner. 23 | Follow "API KEYS" tab. 24 | Generate API key with scope "api" and use it with the library. 25 | 26 | # Documentation 27 | The full API methods description, usage examples, and integration guide are available in the official documentation: [API Reference](https://vulners.com/docs/api_reference/api/). 28 | 29 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "vulners" 3 | version = "2.3.7" 4 | description = "Python library and command-line utility for Vulners (https://vulners.com)" 5 | readme = "README.md" 6 | authors = ["Vulners Team"] 7 | keywords = ["security", "network", "vulners", "vulnerability", "CVE"] 8 | classifiers = [ 9 | "Development Status :: 5 - Production/Stable", 10 | "Operating System :: OS Independent", 11 | "Programming Language :: Python", 12 | "Topic :: Software Development :: Libraries :: Python Modules", 13 | "Intended Audience :: Developers", 14 | "Intended Audience :: Information Technology", 15 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 16 | "Topic :: Software Development :: Version Control", 17 | "Topic :: Utilities", 18 | ] 19 | packages = [ 20 | { include = "vulners" }, 21 | ] 22 | 23 | [tool.poetry.dependencies] 24 | python = ">=3.8" 25 | requests = "^2.31.0" 26 | six = "^1.16.0" 27 | appdirs = "^1.4.4" 28 | 29 | [tool.poetry.dev-dependencies] 30 | black = "^23.9.1" 31 | isort = "^5.12.0" 32 | autoflake = "^2.2.1" 33 | 34 | [tool.black] 35 | line-length = 100 36 | target-version = ['py311'] 37 | 38 | [tool.isort] 39 | profile = "black" 40 | line_length = 100 41 | 42 | [build-system] 43 | requires = ["poetry-core>=1.0.0", "setuptools"] 44 | build-backend = "poetry.core.masonry.api" 45 | 46 | -------------------------------------------------------------------------------- /samples/asyncio_example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import asyncio 4 | import functools 5 | import multiprocessing 6 | from concurrent.futures import ThreadPoolExecutor 7 | 8 | import vulners 9 | 10 | vulners_api = vulners.Vulners(api_key="YOUR_API_KEY_HERE") 11 | 12 | loop = asyncio.get_event_loop() 13 | # pool = ProcessPoolExecutor(max_workers=multiprocessing.cpu_count()) 14 | pool = ThreadPoolExecutor(max_workers=multiprocessing.cpu_count()) 15 | 16 | 17 | async def get_collection(): 18 | print("Get collections") 19 | # using default executor 20 | return await loop.run_in_executor(None, vulners_api.collections) 21 | 22 | 23 | async def search(query, **kwargs): 24 | # run using own executor 25 | print("Run search `%s`." % query) 26 | ret = await loop.run_in_executor(pool, functools.partial(vulners_api.search, query, **kwargs)) 27 | print("Searching `%s` done." % query) 28 | return ret 29 | 30 | 31 | async def main(): 32 | collection_names = await get_collection() 33 | queries = ["type:%s" % collection for collection in collection_names[:20]] 34 | futures = [asyncio.ensure_future(search(query, limit=10)) for query in queries] 35 | results = await asyncio.wait(futures) 36 | print(results) 37 | 38 | 39 | loop.run_until_complete(main()) 40 | loop.close() 41 | -------------------------------------------------------------------------------- /samples/exploits.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # ============== 4 | # Vulners search API usage example 5 | # ============== 6 | 7 | import vulners 8 | 9 | vulners_api = vulners.VulnersApi(api_key="YOUR_API_KEY_HERE") 10 | wordpress_exploits = vulners_api.find_exploit_all("wordpress 4.7.0") 11 | -------------------------------------------------------------------------------- /samples/linux_audit.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # ============== 4 | # Vulners Linux audit example 5 | # ============== 6 | 7 | import vulners 8 | 9 | vulners_api = vulners.VulnersApi(api_key="YOUR_API_KEY_HERE") 10 | 11 | # Example for CentOS 7 12 | # You can use it for any RPM based OS 13 | # Execute command: rpm -qa --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\\n' 14 | # Use it as package variable input 15 | 16 | centos_vulnerabilities = vulners_api.os_audit( 17 | os="centos", os_version="7", packages=["glibc-common-2.17-157.el7_3.5.x86_64"] 18 | ) 19 | vulnerable_packages = centos_vulnerabilities.get("packages") 20 | missed_patches_ids = centos_vulnerabilities.get("vulnerabilities") 21 | cve_list = centos_vulnerabilities.get("cvelist") 22 | how_to_fix = centos_vulnerabilities.get("cumulativeFix") 23 | 24 | # Example for Debian 8 25 | # You can use it for any DEB based OS 26 | # Execute command: dpkg-query -W -f='${Package} ${Version} ${Architecture}\\n' 27 | # Use it as package variable input 28 | 29 | debian_vulnerabilities = vulners_api.os_audit( 30 | os="debian", os_version="8", packages=["uno-libs3 4.3.3-2+deb8u7 amd64"] 31 | ) 32 | -------------------------------------------------------------------------------- /samples/search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Vulners search API usage example 5 | 6 | import os 7 | 8 | import vulners 9 | 10 | vulners_api = vulners.VulnersApi(api_key=os.environ["KEY"]) 11 | possible_autocomplete = vulners_api.query_autocomplete("heartbleed") 12 | heartbleed_related = vulners_api.find("heartbleed", limit=10) 13 | total_heartbleed = heartbleed_related.total 14 | CVE_2017_14174 = vulners_api.get_bulletin("CVE-2017-14174") 15 | -------------------------------------------------------------------------------- /samples/software_scanner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | # Vulners software vulnerabilities search example 5 | 6 | import os 7 | 8 | import vulners 9 | 10 | vulners_api = vulners.VulnersApi(api_key=os.environ["KEY"]) 11 | 12 | # Download web application vulnerability detection regex collection 13 | rules = vulners_api.get_web_application_rules() 14 | 15 | # Plain text software + version example for Apache Httpd 1.3 16 | sw_results = vulners_api.get_software_vulnerabilities("nginx", "1.4") 17 | sw_exploit_list = sw_results["exploit"] 18 | sw_vulnerabilities_list = [ 19 | sw_results[key] for key in sw_results if key not in ("info", "blog", "bugbounty") 20 | ] 21 | print(sw_vulnerabilities_list) 22 | 23 | # CPE vulnerability search example 24 | cpe_results = vulners_api.get_cpe_vulnerabilities("cpe:/a:cybozu:garoon:4.2.1") 25 | cpe_exploit_list = cpe_results["exploit"] 26 | cpe_vulnerabilities_list = [ 27 | cpe_results[key] for key in cpe_results if key not in ("info", "blog", "bugbounty") 28 | ] 29 | print(cpe_vulnerabilities_list) 30 | -------------------------------------------------------------------------------- /scripts/format: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -x 3 | 4 | autoflake --remove-all-unused-imports --recursive --remove-unused-variables --in-place . --exclude=__init__.py 5 | black . 6 | isort --atomic . 7 | -------------------------------------------------------------------------------- /vulners/__init__.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | 3 | from .base import VulnersApiError 4 | from .vscanner import VScannerApi 5 | from .vulners import Vulners, VulnersApi 6 | 7 | warnings.simplefilter("always", DeprecationWarning) 8 | -------------------------------------------------------------------------------- /vulners/base.py: -------------------------------------------------------------------------------- 1 | import functools 2 | import inspect 3 | import os 4 | import re 5 | import stat 6 | import uuid 7 | from collections import OrderedDict, defaultdict 8 | from http import cookiejar 9 | from importlib.metadata import version 10 | from time import sleep, time 11 | 12 | import requests 13 | from appdirs import user_cache_dir 14 | from requests import adapters, cookies 15 | from six import string_types, with_metaclass 16 | from urllib3.util.retry import Retry 17 | 18 | __version__ = version("vulners") 19 | 20 | 21 | try: 22 | _getargspec = inspect.getfullargspec # noqa 23 | except AttributeError: 24 | _getargspec = inspect.getargspec # noqa 25 | 26 | 27 | class VulnersApiError(Exception): 28 | def __init__(self, http_status, data): 29 | super(VulnersApiError, self).__init__(data) 30 | self.http_status = http_status 31 | 32 | 33 | class VulnersApiMeta(type): 34 | def __new__(cls, name, bases, attrs): 35 | new_type = type.__new__ 36 | if not bases: 37 | return new_type(cls, name, bases, attrs) 38 | for key, value in list(attrs.items()): 39 | if isinstance(value, Endpoint): 40 | attrs[key] = value.build(key, attrs.get("ratelimit_key")) 41 | new_class = new_type(cls, name, bases, attrs) 42 | return new_class 43 | 44 | 45 | class RateLimitBucket(object): 46 | """An implementation of the Token Bucket algorithm.""" 47 | 48 | def __init__(self, rate=10.0, burst=1.0): 49 | """Initialise an instance of the RateLimit allowing a default rate of 10 calls 50 | per 1 seconds when no arguments are supplied. 51 | :param rate: 52 | The number of calls per second. Default 10. 53 | """ 54 | self._rate = float(rate) 55 | self._burst = min(float(burst), self._rate) 56 | self._allowance = self._burst 57 | self._last_check = time() 58 | 59 | def update(self, rate, burst=1.0): 60 | self._rate = float(rate) 61 | self._burst = min(float(burst), self._rate) 62 | 63 | def consume(self): 64 | while 1: 65 | now = time() 66 | # number of seconds since the last call 67 | delta = now - self._last_check 68 | self._last_check = now 69 | # increase the number of allowed calls 70 | self._allowance += delta * self._rate 71 | if self._allowance > self._burst: 72 | # don't allow more than "burst" calls 73 | self._allowance = self._burst 74 | if self._allowance < 1: 75 | # cold down 76 | sleep((1 - self._allowance) / self._rate) 77 | continue 78 | self._allowance -= 1 79 | break 80 | 81 | 82 | class PersistentCookieJar(cookiejar.MozillaCookieJar, cookies.RequestsCookieJar): 83 | def __init__(self, filename=None, *args, **kwargs): 84 | if filename is None: 85 | cache_dir = user_cache_dir("Vulners", "Vulners.Inc") 86 | if not os.path.exists(cache_dir): 87 | os.makedirs(cache_dir) 88 | filename = os.path.join(cache_dir, "mozilla_cookies.jar") 89 | super().__init__(filename, *args, **kwargs) 90 | self._set_cookie_counter = 0 91 | self._recover() 92 | 93 | def _recover(self): 94 | try: 95 | mode = os.stat(self.filename).st_mode 96 | except OSError: 97 | return 98 | if not stat.S_ISREG(mode): 99 | raise OSError("%s is not a regular file" % self.filename) 100 | with self._cookies_lock: 101 | self.load(ignore_discard=True, ignore_expires=True) 102 | self._set_cookie_counter = 0 103 | 104 | def extract_cookies(self, response, request): 105 | with self._cookies_lock: 106 | super().extract_cookies(response, request) 107 | if self._set_cookie_counter > 0: 108 | self.save(ignore_discard=True, ignore_expires=True) 109 | self._set_cookie_counter = 0 110 | 111 | def set_cookie(self, *args, **kwargs): 112 | with self._cookies_lock: 113 | self._set_cookie_counter += 1 114 | return super().set_cookie(*args, **kwargs) 115 | 116 | 117 | class VulnersApiBase(with_metaclass(VulnersApiMeta)): 118 | # Retry status codes 119 | retry_codes = (502, 503, 504) 120 | # How many times to retry 121 | retry_count = 3 122 | 123 | _ratelimits = defaultdict(RateLimitBucket) 124 | 125 | def __init__(self, api_key, proxies=None, persistent=True, server_url="https://vulners.com"): 126 | """ 127 | Create VScanner API object. 128 | 129 | :param api_key: 130 | string with Vulners API key. You can obtain one from the https://vulners.com 131 | :param proxies: 132 | dict for proxy supporting. Example: {"https": "myproxy.com:3128"} 133 | """ 134 | if not api_key: 135 | raise ValueError( 136 | "API key must be provided. You can obtain one for free at https://vulners.com" 137 | ) 138 | 139 | if not isinstance(api_key, string_types): 140 | raise TypeError("api_key parameter must be a string value") 141 | 142 | self._sess = self._create_session(proxies, server_url, persistent) 143 | self._api_key = api_key 144 | self._server_url = server_url 145 | 146 | def _create_session(self, proxies, server_url, persistent): 147 | assert proxies is None or isinstance(proxies, dict), "proxies must be a dict" 148 | session = requests.session() 149 | retries = Retry(total=self.retry_count, status_forcelist=self.retry_codes) 150 | adapter = adapters.HTTPAdapter(max_retries=retries) 151 | session.mount(server_url, adapter) 152 | session.headers.update( 153 | { 154 | "Connection": "Keep-Alive", 155 | "User-Agent": "Vulners Python API %s" % __version__, 156 | } 157 | ) 158 | if persistent: 159 | session.cookies = PersistentCookieJar() 160 | if proxies: 161 | session.proxies.update(proxies) 162 | return session 163 | 164 | @staticmethod 165 | def adapt_response(response, method, expected_result): 166 | if expected_result == "json": 167 | if response.content: 168 | result = response.json() 169 | else: 170 | result = None 171 | if response.status_code >= 400: 172 | raise VulnersApiError(response.status_code, result) 173 | if isinstance(result, dict) and "data" in result: 174 | data = result["data"] 175 | if isinstance(data, dict) and data.get("error"): 176 | raise VulnersApiError(response.status_code, data) 177 | return data 178 | return result 179 | elif response.status_code >= 400: 180 | if response.content: 181 | result = response.json() 182 | else: 183 | result = None 184 | raise VulnersApiError(response.status_code, result) 185 | else: 186 | return response.content 187 | 188 | @staticmethod 189 | def _update_ratelimit(bucket, response): 190 | headers = response.headers 191 | limit = headers.get("X-Vulners-Ratelimit-Reqlimit") 192 | if limit: 193 | try: 194 | limit = float(limit) / 60.0 195 | except (TypeError, ValueError): 196 | return 197 | bucket.update(rate=limit) 198 | 199 | def _send_request( 200 | self, 201 | method, 202 | url, 203 | body_params, 204 | path_params, 205 | ratelimit_key=None, 206 | result_type="json", 207 | ): 208 | body_params["apiKey"] = self._api_key 209 | url = self._server_url + url.format(**path_params) 210 | kwargs = {"params" if method in ("get", "delete") else "json": body_params} 211 | bucket = self._ratelimits[ratelimit_key or url] 212 | bucket.consume() 213 | response = getattr(self._sess, method)(url, **kwargs) 214 | self._update_ratelimit(bucket, response) 215 | response.raise_for_status() 216 | result = self.adapt_response(response, method, result_type) 217 | return result, response.headers 218 | 219 | 220 | _Nothing = object() 221 | 222 | 223 | class ParamError(ValueError): 224 | def __init__(self, msg, param): 225 | self.msg = msg 226 | self.param = param 227 | 228 | def __str__(self): 229 | return self.msg % self.param 230 | 231 | 232 | class Param(object): 233 | def __init__( 234 | self, default=_Nothing, description=None, required=True, allow_null=False, param=None 235 | ): 236 | if not required: 237 | if default is _Nothing: 238 | default = None 239 | self.allow_null = allow_null 240 | self.param = param 241 | self.default = default 242 | self.required = required 243 | self.description = description 244 | 245 | 246 | class Const(object): 247 | def __init__(self, value): 248 | self.value = value 249 | 250 | 251 | class Any(Param): 252 | def __init__(self, *args, **kwargs): 253 | assert all([p.__base__ == Param for p in args]), "Invalid argument type" 254 | self.__params = [p(**kwargs) for p in args] 255 | super(Any, self).__init__(**kwargs) 256 | 257 | def validate(self, param, value): 258 | errs = [] 259 | for _param in self.__params: 260 | try: 261 | return _param.validate(param, value) 262 | except ParamError as e: 263 | errs.append(e) 264 | 265 | raise ParamError( 266 | "Expect %s but got '%s'", 267 | (" or ".join([p.__class__.__name__ for p in self.__params]), type(value)), 268 | ) 269 | 270 | 271 | class String(Param): 272 | def __init__(self, choices=None, *args, **kwargs): 273 | super(String, self).__init__(*args, **kwargs) 274 | self.choices = choices 275 | 276 | def validate(self, param, value): 277 | if value is None and self.allow_null: 278 | return value 279 | if not isinstance(value, string_types): 280 | raise ParamError("%s expected to be a string", param) 281 | if self.choices is not None and value not in self.choices: 282 | raise ParamError("%%s expected to be on of (%s)" % ", ".join(self.choices), param) 283 | return value 284 | 285 | 286 | class UUID(Param): 287 | def validate(self, param, value): 288 | if value is None and self.allow_null: 289 | return value 290 | try: 291 | return str(uuid.UUID(value)) 292 | except (TypeError, ValueError): 293 | raise ParamError("%s expected to be an uuid", param) 294 | 295 | 296 | class Dict(Param): 297 | def validate(self, param, value): 298 | if value is None and self.allow_null: 299 | return value 300 | if not isinstance(value, dict): 301 | raise ParamError("%s expected to be a dict", param) 302 | return value 303 | 304 | 305 | class List(Param): 306 | def __init__(self, item=None, **kwargs): 307 | super(List, self).__init__(**kwargs) 308 | self.item = item 309 | 310 | @staticmethod 311 | def validate_items(validator, param, value): 312 | result = [] 313 | for idx, val in enumerate(value): 314 | try: 315 | result.append(validator(idx, val)) 316 | except ParamError as e: 317 | raise ParamError(e.msg, "%s.%s" % (param, e.param)) 318 | return result 319 | 320 | def validate(self, param, value): 321 | if value is None and self.allow_null: 322 | return value 323 | if not isinstance(value, list): 324 | raise ParamError("%s expected to be a list", param) 325 | if self.item is not None: 326 | value = self.validate_items(self.item.validate, param, value) 327 | return value 328 | 329 | 330 | class Tuple(List): 331 | def __init__(self, accept_list=True, **kwargs): 332 | super(Tuple, self).__init__(**kwargs) 333 | self.accept_list = accept_list 334 | 335 | def validate(self, param, value): 336 | if value is None and self.allow_null: 337 | return value 338 | if not isinstance(value, (list, tuple) if self.accept_list else tuple): 339 | raise ParamError("%s expected to be a tuple", param) 340 | if self.item is not None: 341 | value = self.validate_items(self.item.validate, param, value) 342 | return tuple(value) 343 | 344 | 345 | class Integer(Param): 346 | def __init__(self, minimum=None, maximum=None, **kwargs): 347 | super(Integer, self).__init__(**kwargs) 348 | self.minimum = minimum 349 | self.maximum = maximum 350 | 351 | def validate(self, param, value): 352 | if value is None and self.allow_null: 353 | return value 354 | if not isinstance(value, int): 355 | raise ParamError("%s expected to be an int", param) 356 | if self.minimum is not None and value < self.minimum: 357 | raise ParamError("%%s must be greater or equal to %d" % self.minimum, param) 358 | if self.maximum is not None and value > self.maximum: 359 | raise ParamError("%%s must be less or equal to %d" % self.maximum, param) 360 | return value 361 | 362 | 363 | class Float(Param): 364 | def __init__(self, minimum=None, maximum=None, **kwargs): 365 | super(Float, self).__init__(**kwargs) 366 | self.minimum = minimum 367 | self.maximum = maximum 368 | 369 | def validate(self, param, value): 370 | if value is None and self.allow_null: 371 | return value 372 | if not isinstance(value, float): 373 | raise TypeError("%s expected to be a float" % param) 374 | if self.minimum is not None and value < self.minimum: 375 | raise ParamError("%%s must be greater or equal to %d" % self.minimum, param) 376 | if self.maximum is not None and value > self.maximum: 377 | raise ParamError("%%s must be less or equal to %d" % self.maximum, param) 378 | return value 379 | 380 | 381 | class Boolean(Param): 382 | def validate(self, param, value): 383 | if value is None and self.allow_null: 384 | return value 385 | if not isinstance(value, bool): 386 | raise TypeError("%s expected to be a bool" % param) 387 | return value 388 | 389 | 390 | _unset = object() 391 | 392 | 393 | def validate_params(**params): 394 | def decorator(func): 395 | spec = _getargspec(func) 396 | for param in params: 397 | if param not in spec.args: 398 | raise TypeError("No such argument %s" % param) 399 | spec_defaults = spec.defaults or () 400 | default_values = (_unset,) * (len(spec.args) - len(spec_defaults)) + spec_defaults 401 | defaults = {k: v for k, v in zip(spec.args, default_values) if v is not _unset} 402 | args = ", ".join([arg for arg in spec.args]) 403 | func_args = ", ".join( 404 | [ 405 | (name if default is _unset else ("%s=%r" % (name, default))) 406 | for name, default in zip(spec.args, default_values) 407 | ] 408 | ) 409 | body = "\n ".join( 410 | [ 411 | ( 412 | ("if {var} is not _D[{var!r}]: " if var in defaults else "") 413 | + "{var} = _V[{var!r}].validate({var!r}, {var})" 414 | ).format(var=var) 415 | for var in params 416 | ] 417 | ) 418 | code = "def {name}({func_args}):\n {body}\n return _func({args})".format( 419 | name=func.__name__, func_args=func_args, body=body, args=args 420 | ) 421 | exec_locals = {"_V": params, "_D": defaults, "_func": func} 422 | exec(code, exec_locals, exec_locals) 423 | new_func = exec_locals[func.__name__] 424 | functools.update_wrapper(new_func, func) 425 | return new_func 426 | 427 | return decorator 428 | 429 | 430 | class Endpoint(object): 431 | _mapping = { 432 | "str": String, 433 | "uuid": UUID, 434 | "int": Integer, 435 | "float": Float, 436 | "bool": Boolean, 437 | "dict": Dict, 438 | } 439 | 440 | def __call__(self, *args, **kwargs): 441 | raise RuntimeError("Only for typing") 442 | 443 | def __init__( 444 | self, 445 | method, 446 | url, 447 | description=None, 448 | params=None, 449 | result_type="json", 450 | content_handler=None, 451 | wrapper=None, 452 | ): 453 | assert method in ("get", "post", "put", "delete") 454 | assert isinstance(url, string_types) 455 | assert description is None or isinstance(description, string_types) 456 | assert params is None or isinstance(params, list) 457 | self.path_params = [] 458 | self.params = OrderedDict() 459 | for param in [item.strip("{}") for item in re.findall("{[^}]*}", url)]: 460 | if ":" in param: 461 | param_type, param_name = param.split(":", 1) 462 | else: 463 | param_type, param_name = "str", param 464 | if "|" in param_name: 465 | param_name, param_description = param_name.split("|", 1) 466 | else: 467 | param_description = "" 468 | url = url.replace("{" + param + "}", "{" + param_name + "}") 469 | param_obj = self._mapping[param_type](description=param_description) 470 | self.path_params.append(param_name) 471 | self.params[param_name] = param_obj 472 | self.method = method 473 | self.url = url 474 | self.description = description 475 | self.result_type = result_type 476 | self.content_handler = content_handler 477 | self.wrapper = wrapper 478 | if params: 479 | for k, v in params: 480 | self.params[k] = v 481 | 482 | def build(self, name, ratelimit_key=None): 483 | func_args = [] 484 | func_args_with_default = [] 485 | body_params = [] 486 | path_params = [] 487 | func_locals = {"_content_handler": self.content_handler, "_wrapper": self.wrapper} 488 | func_locals_reverse = {} 489 | func_doc = [self.description or name, ""] 490 | for key, param in self.params.items(): 491 | if isinstance(param, Const): 492 | const_key = "_const%d" % len(func_locals) 493 | func_locals[const_key] = param.value 494 | body_params.append( 495 | "body_params[{key!r}] = {const}".format(key=key, const=const_key) 496 | ) 497 | continue 498 | if param.default is not _Nothing: 499 | default_key = "_default%d" % len(func_locals) 500 | func_locals[default_key] = param.default 501 | func_args_with_default.append("%s=%s" % (key, default_key)) 502 | else: 503 | func_args.append(key) 504 | validate_key = "_validate%d" % len(func_locals) 505 | if param.validate in func_locals_reverse: 506 | validate_key = func_locals_reverse[param.validate] 507 | else: 508 | func_locals[validate_key] = param.validate 509 | func_locals_reverse[param.validate] = validate_key 510 | if key in self.path_params: 511 | path_params.append( 512 | "{key!r}: {validator}({key!r}, {key})".format(key=key, validator=validate_key) 513 | ) 514 | else: 515 | param_name = param.param or key 516 | if param.required: 517 | body_params.append( 518 | "body_params[{param_name!r}] = {validator}({key!r}, {key})".format( 519 | param_name=param_name, key=key, validator=validate_key 520 | ) 521 | ) 522 | else: 523 | body_params.append( 524 | ( 525 | "if {key} is not None: " 526 | "body_params[{param_name!r}] = {validator}({key!r}, {key})" 527 | ).format(param_name=param_name, key=key, validator=validate_key) 528 | ) 529 | if param.description: 530 | func_doc.append("%s: %s" % (key, param.description or "")) 531 | func_args += func_args_with_default 532 | code = ( 533 | "def {name}(self, {func_args}):\n" 534 | " '''{func_doc}'''\n" 535 | " body_params = {{}}\n" 536 | " {body_params}\n" 537 | " path_params = {{{path_params}}}\n" 538 | " r = self._send_request({method!r}, {url!r}, body_params, path_params, {ratelimit_key!r}, {result!r})\n" 539 | ).format( 540 | name=name, 541 | func_args=", ".join(func_args), 542 | func_doc="\n".join(func_doc), 543 | method=self.method, 544 | url=self.url, 545 | body_params="\n ".join(body_params), 546 | path_params=", ".join(path_params), 547 | ratelimit_key=ratelimit_key, 548 | result=self.result_type, 549 | ) 550 | if self.content_handler: 551 | code += " r = _content_handler(*r)\n" 552 | else: 553 | code += " r = r[0]\n" 554 | if self.wrapper: 555 | code += " r = _wrapper(self, r)\n" 556 | code += " return r" 557 | exec(code, func_locals, func_locals) 558 | return func_locals[name] 559 | 560 | 561 | class ResultSet(list): 562 | total = None 563 | 564 | @classmethod 565 | def from_dataset(cls, data, total): 566 | ret = cls(data) 567 | ret.total = total 568 | return ret 569 | -------------------------------------------------------------------------------- /vulners/vscanner.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from .base import UUID, Boolean, Dict, Endpoint, Float, Integer, List, String, VulnersApiBase 4 | 5 | try: 6 | from collections.abc import Mapping 7 | except ImportError: 8 | from collections import Mapping 9 | 10 | 11 | class MappingObject(Mapping): 12 | __slots__ = ("_api",) 13 | 14 | def __init__(self, api, data): 15 | self._api = api 16 | self.__dict__ = data 17 | 18 | def __len__(self): 19 | return len(self.__dict__) 20 | 21 | def __getitem__(self, k): 22 | return self.__dict__[k] 23 | 24 | def __iter__(self): 25 | return iter(self.__dict__) 26 | 27 | def __repr__(self): 28 | return repr(self.__dict__) 29 | 30 | 31 | class Project(MappingObject): 32 | def update(self, **kwargs): 33 | kwargs.setdefault("name", self.name) 34 | kwargs.setdefault("license_id", self.license_id) 35 | kwargs.setdefault("notification", self.notification) 36 | kwargs.setdefault("result_expire_in", self.result_expire_in) 37 | self.__dict__ = self._api.update_project(self._id, **kwargs).__dict__ 38 | 39 | def delete(self): 40 | self._api.delete_project(self._id) 41 | 42 | def get_tasks(self, *args, **kwargs): 43 | return self._api.get_tasks(self._id, *args, **kwargs) 44 | 45 | def create_task(self, *args, **kwargs): 46 | return self._api.create_task(self._id, *args, **kwargs) 47 | 48 | def get_results(self, *args, **kwargs): 49 | return self._api.get_results(self._id, *args, **kwargs) 50 | 51 | def get_statistics(self, *args, **kwargs): 52 | return self._api.get_statistics(self._id, *args, **kwargs) 53 | 54 | 55 | class Task(MappingObject): 56 | def update(self, **kwargs): 57 | kwargs.setdefault("name", self.name) 58 | kwargs.setdefault("networks", self.networks) 59 | kwargs.setdefault("ports", self.ports) 60 | kwargs.setdefault("timing", self.timing) 61 | kwargs.setdefault("schedule", self.schedule) 62 | kwargs.setdefault("enabled", self.enabled) 63 | self.__dict__ = self._api.update_task(self.project_id, self._id, **kwargs).__dict__ 64 | 65 | def delete(self): 66 | self._api.delete_task(self.project_id, self._id) 67 | 68 | def start_task(self): 69 | self.__dict__ = self._api.start_task(self.project_id, self._id).__dict__ 70 | 71 | def get_log(self): 72 | return self._api.get_task_log(self.context_id) 73 | 74 | 75 | class Result(MappingObject): 76 | def delete(self): 77 | self._api.delete_result(self.project_id, self._id) 78 | 79 | def get_screenshot(self, port, as_base64=False): 80 | try: 81 | screen = self.screens[str(port)]["screen"] 82 | except (AttributeError, KeyError): 83 | return None 84 | if not screen: 85 | return None 86 | return self._api.get_image_binary(screen, as_base64) 87 | 88 | 89 | class VScannerApi(VulnersApiBase): 90 | ratelimit_key = "vscanner" 91 | 92 | get_licenses = Endpoint( 93 | method="get", 94 | url="/api/v3/useraction/licenseids", 95 | description="Get user's license ids.", 96 | ) 97 | get_projects = Endpoint( 98 | method="get", 99 | url="/api/v3/proxy/vscanner/v2/projects/", 100 | description="Get existing projects.", 101 | params=[ 102 | ("offset", Integer(default=0)), 103 | ("limit", Integer(default=50)), 104 | ], 105 | wrapper=lambda api, c: [Project(api, x) for x in c], 106 | ) 107 | create_project = Endpoint( 108 | method="post", 109 | url="/api/v3/proxy/vscanner/v2/projects/", 110 | description="Create new project.", 111 | params=[ 112 | ("name", String(description="New project name")), 113 | ("license_id", UUID(description="User's license id")), 114 | ( 115 | "notification", 116 | Dict( 117 | description=( 118 | "Use VScannerApi.Notification or VScannerApi.DisabledNotification helpers " 119 | "to create notification object." 120 | ), 121 | ), 122 | ), 123 | ( 124 | "result_expire_in", 125 | Integer( 126 | description="Result expire in N days. Null means it will never expire", 127 | required=False, 128 | minimum=1, 129 | ), 130 | ), 131 | ], 132 | wrapper=Project, 133 | ) 134 | update_project = Endpoint( 135 | method="put", 136 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}", 137 | description="Update existing project.", 138 | params=[ 139 | ("name", String(description="Project name")), 140 | ("license_id", UUID(description="User's license id")), 141 | ( 142 | "notification", 143 | Dict( 144 | description=( 145 | "Use VScannerApi.Notification or VScannerApi.DisabledNotification helpers " 146 | "to create notification object." 147 | ), 148 | ), 149 | ), 150 | ( 151 | "result_expire_in", 152 | Integer( 153 | description="Result expire in N days. Null means it will never expire", 154 | minimum=1, 155 | allow_null=True, 156 | ), 157 | ), 158 | ], 159 | wrapper=Project, 160 | ) 161 | delete_project = Endpoint( 162 | method="delete", 163 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}", 164 | description="Delete existing project.", 165 | ) 166 | get_tasks = Endpoint( 167 | method="get", 168 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/tasks", 169 | description="Get project tasks", 170 | params=[("offset", Integer(default=0)), ("limit", Integer(default=50))], 171 | wrapper=lambda api, c: [Task(api, x) for x in c], 172 | ) 173 | create_task = Endpoint( 174 | method="post", 175 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/tasks", 176 | description="Create new task.", 177 | params=[ 178 | ("name", String(description="Task name")), 179 | ("networks", List(description="List of networks (ip or domains)", item=String())), 180 | ("ports", List(description="List of ports or port ranges", item=String())), 181 | ("schedule", String(description="Crontab string")), 182 | ("timing", String(description="Scan timing")), 183 | ("enabled", Boolean(description="Enable/disable task")), 184 | ], 185 | wrapper=Task, 186 | ) 187 | update_task = Endpoint( 188 | method="put", 189 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/tasks/{uuid:task_id|Task id}", 190 | description="Update task.", 191 | params=[ 192 | ("name", String(description="Task name")), 193 | ("networks", List(description="List of networks (ip or domains)", item=String())), 194 | ("ports", List(description="List of ports or port ranges", item=String())), 195 | ("schedule", String(description="Crontab string")), 196 | ("timing", String(description="Scan timing")), 197 | ("enabled", Boolean(description="Enable/disable task")), 198 | ], 199 | wrapper=Task, 200 | ) 201 | start_task = Endpoint( 202 | method="post", 203 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/tasks/{uuid:task_id|Task id}/start", 204 | description="Start task asap.", 205 | wrapper=Task, 206 | ) 207 | delete_task = Endpoint( 208 | method="delete", 209 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/tasks/{uuid:task_id|Task id}", 210 | description="Delete task.", 211 | ) 212 | get_results = Endpoint( 213 | method="get", 214 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/results", 215 | description="Get results.", 216 | params=[ 217 | ( 218 | "search", 219 | String(required=False, description="Search by ip, network, name or vuln_id."), 220 | ), 221 | ("in_port", List(required=False, description="Include ports")), 222 | ("ex_port", List(required=False, description="Exclude ports")), 223 | ("min_cvss", Float(required=False, description="Minimum CVSS value.")), 224 | ("max_cvss", Float(required=False, description="Maximum CVSS value.")), 225 | ("last_seen", Integer(required=False, description="last_seen >= given value.")), 226 | ("first_seen", Integer(required=False, description="first_seen >= given value.")), 227 | ( 228 | "last_seen_port", 229 | Integer(required=False, description="last_seen_port >= given value."), 230 | ), 231 | ( 232 | "first_seen_port", 233 | Integer(required=False, description="first_seen_port >= given value."), 234 | ), 235 | ( 236 | "sort", 237 | String( 238 | required=False, 239 | description=( 240 | "Sort by field. Allowable values are 'ip', 'name', 'last_seen', 'first_seen', " 241 | "'resolved', 'min_cvss' and 'max_cvss'. Default: last_seen" 242 | ), 243 | ), 244 | ), 245 | ( 246 | "sort_dir", 247 | String(required=False, description="Sort direction: asc or desc. Default: asc"), 248 | ), 249 | ("offset", Integer(default=0)), 250 | ("limit", Integer(default=50)), 251 | ], 252 | wrapper=lambda api, c: [Result(api, x) for x in c], 253 | ) 254 | delete_result = Endpoint( 255 | method="delete", 256 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/results/{uuid:result_id|Result id}", 257 | description="Delete result by id.", 258 | ) 259 | get_statistics = Endpoint( 260 | method="get", 261 | url="/api/v3/proxy/vscanner/v2/projects/{uuid:project_id|Project id}/statistic", 262 | description="Get project statistics.", 263 | params=[ 264 | ( 265 | "stat", 266 | List( 267 | required=True, 268 | description=( 269 | "List of required aggregations:" 270 | "total_hosts, vulnerable_hosts, unique_cve, min_max_cvss, " 271 | "vulnerabilities_rank, vulnerable_hosts_rank" 272 | ), 273 | item=String(), 274 | ), 275 | ) 276 | ], 277 | ) 278 | 279 | def get_image_binary(self, image_uri, as_base64=False): 280 | result, headers = self._send_request( 281 | "get", "/vscanner/screen/" + image_uri, {}, {}, self.ratelimit_key, "binary" 282 | ) 283 | if as_base64: 284 | return base64.b64encode(result) 285 | return result 286 | 287 | @staticmethod 288 | def Notification(period, emails=None, slack_webhooks=None): 289 | """ 290 | Create notification project 291 | 292 | period: one of "disabled", "asap", "hourly" or "daily" 293 | emails: list of emails 294 | slack_webhooks: list of slack webhooks 295 | """ 296 | if period not in ("disabled", "asap", "hourly", "daily"): 297 | raise ValueError('period expected to be one of "disabled", "asap", "hourly" or "daily"') 298 | return { 299 | "period": period, 300 | "email": emails or [], 301 | "slack": slack_webhooks or [], 302 | } 303 | 304 | @staticmethod 305 | def DisabledNotification(): 306 | """ 307 | Create stub notification object with "disabled" period and empty methods 308 | """ 309 | return { 310 | "period": "disabled", 311 | "email": [], 312 | "slack": [], 313 | } 314 | -------------------------------------------------------------------------------- /vulners/vulners.py: -------------------------------------------------------------------------------- 1 | import io 2 | import json 3 | import re 4 | import warnings 5 | import zipfile 6 | 7 | from .base import ( 8 | Any, 9 | Boolean, 10 | Const, 11 | Dict, 12 | Endpoint, 13 | Integer, 14 | List, 15 | ParamError, 16 | ResultSet, 17 | String, 18 | Tuple, 19 | VulnersApiBase, 20 | validate_params, 21 | ) 22 | 23 | 24 | class VulnersApi(VulnersApiBase): 25 | default_fields = ( 26 | "id", 27 | "title", 28 | "description", 29 | "type", 30 | "bulletinFamily", 31 | "cvss", 32 | "published", 33 | "modified", 34 | "lastseen", 35 | "href", 36 | "sourceHref", 37 | "sourceData", 38 | "cvelist", 39 | "vulnStatus", 40 | "assigned", 41 | ) 42 | 43 | __search = Endpoint( 44 | method="post", 45 | url="/api/v3/search/lucene/", 46 | params=[ 47 | ("query", String()), 48 | ("skip", Integer()), 49 | ("size", Integer()), 50 | ("fields", Tuple()), 51 | ], 52 | ) 53 | 54 | @validate_params( 55 | query=String(), 56 | limit=Integer(minimum=1, maximum=100), 57 | offset=Integer(minimum=0, maximum=9999), 58 | fields=Tuple(item=String()), 59 | ) 60 | def find(self, query, limit=20, offset=0, fields=default_fields): 61 | """ 62 | Search in Vulners database. 63 | 64 | query: Vulners query. See https://vulners.com/help for the details. 65 | limit: The maximum number of documents to return. 66 | offset: Skip this amount of documents. 10000 is the hard limit. 67 | fields: List of fields to return. 68 | 69 | Returns list of the documents. 70 | Use .total to get the total number of found documents. 71 | """ 72 | limit = min(limit, 10000 - offset) 73 | search = self.__search(query, offset, limit, fields) 74 | return ResultSet.from_dataset([e["_source"] for e in search["search"]], search["total"]) 75 | 76 | @validate_params( 77 | query=String(), 78 | limit=Integer(minimum=1, maximum=10000), 79 | offset=Integer(minimum=0, maximum=9999), 80 | fields=Tuple(item=String()), 81 | ) 82 | def find_all(self, query, limit=20, offset=0, fields=default_fields): 83 | """ 84 | Search in Vulners database and returns up to 10000 documents. 85 | 86 | query: Vulners query. See https://vulners.com/help for the details. 87 | limit: The maximum number of documents to return.. 88 | offset: The number of documents to skip in the result set. 10000 is the hard limit. 89 | fields: List of fields to return. 90 | 91 | Returns list of the documents. 92 | Use .total to get the total number of found documents. 93 | """ 94 | limit = min(limit, 10000 - offset) 95 | end = offset + limit 96 | batch_size = min(1000, limit) 97 | result = ResultSet() 98 | while limit > len(result) != result.total: 99 | chunk = self.__search(query, offset, min(batch_size, end - offset), fields) 100 | data = chunk["search"] 101 | result += [e["_source"] for e in data] 102 | result.total = chunk["total"] 103 | if not data: 104 | break 105 | if result.total <= len(data): 106 | break 107 | offset += len(data) 108 | return result 109 | 110 | @validate_params( 111 | query=String(), 112 | lookup_fields=Tuple(item=String()), 113 | limit=Integer(minimum=1, maximum=100), 114 | offset=Integer(minimum=0, maximum=9999), 115 | fields=Tuple(item=String()), 116 | ) 117 | def find_exploit(self, query, lookup_fields=None, limit=20, offset=0, fields=default_fields): 118 | """ 119 | Search in Vulners database for the exploits. 120 | 121 | query: Software name and criteria. 122 | lookup_fields: Make a strict search using lookup fields. Like ["title"] 123 | limit: The maximum number of documents to return. 124 | offset: Skip this amount of documents. 10000 is the hard limit. 125 | fields: List of fields to return. 126 | 127 | Returns list of the documents. 128 | Use .total to get the total number of found documents. 129 | """ 130 | if lookup_fields: 131 | search_query = "bulletinFamily:exploit AND (%s)" % ( 132 | " OR ".join('%s:"%s"' % (field, query) for field in lookup_fields) 133 | ) 134 | else: 135 | search_query = "bulletinFamily:exploit AND %s" % query 136 | return self.find(search_query, limit, offset, fields) 137 | 138 | @validate_params( 139 | query=String(), 140 | lookup_fields=Tuple(item=String()), 141 | limit=Integer(minimum=1, maximum=10000), 142 | offset=Integer(minimum=0, maximum=9999), 143 | fields=Tuple(item=String()), 144 | ) 145 | def find_exploit_all( 146 | self, query, lookup_fields=None, limit=20, offset=0, fields=default_fields 147 | ): 148 | """ 149 | Search in Vulners database for the exploits and returns up to 10000 documents. 150 | 151 | query: Software name and criteria. 152 | lookup_fields: Make a strict search using lookup fields. Like ["title"] 153 | limit: The maximum number of documents to return. 154 | offset: Skip this amount of documents. 10000 is the hard limit. 155 | fields: List of fields to return. 156 | 157 | Returns list of the documents. 158 | Use .total to get the total number of found documents. 159 | """ 160 | if re.match(r"^CVE-\d{4}-\d+$", (query := query.strip()), re.IGNORECASE): 161 | query = f'"{query}"' 162 | if lookup_fields: 163 | search_query = "bulletinFamily:exploit AND (%s)" % ( 164 | " OR ".join('%s:"%s"' % (field, query) for field in lookup_fields) 165 | ) 166 | else: 167 | search_query = "bulletinFamily:exploit AND %s" % query 168 | return self.find_all(search_query, limit, offset, fields) 169 | 170 | get_web_application_rules = Endpoint(method="get", url="/api/v3/burp/rules/") 171 | 172 | def _get_burp_software_content(content, _): 173 | result = {} 174 | # noinspection PyUnresolvedReferences 175 | for elem in content.get("search", ()): 176 | elem = elem["_source"] 177 | result.setdefault(elem["bulletinFamily"], []).append(elem) 178 | return result 179 | 180 | __get_burp_software = Endpoint( 181 | method="post", 182 | url="/api/v3/burp/softwareapi/", 183 | params=[ 184 | ("software", String()), 185 | ("version", String(required=False)), 186 | ("vendor", String(required=False)), 187 | ("update", String(required=False)), 188 | ("language", String(required=False)), 189 | ("sw_edition", String(required=False)), 190 | ("target_sw", String(required=False)), 191 | ("target_hw", String(required=False)), 192 | ( 193 | "respect_major_version", 194 | String(required=False, choices=["yes", "no", "true", "false"]), 195 | ), 196 | ("exclude_any_version", String(required=False, choices=["yes", "no", "true", "false"])), 197 | ("type", String(required=False)), # deprecated 198 | ("exactmatch", Boolean(default=False)), # deprecated 199 | ], 200 | content_handler=_get_burp_software_content, 201 | ) 202 | 203 | del _get_burp_software_content 204 | 205 | @validate_params(name=String(), version=String()) 206 | def get_software_vulnerabilities( 207 | self, 208 | name, 209 | version, 210 | vendor=None, 211 | update=None, 212 | language=None, 213 | sw_edition=None, 214 | target_sw=None, 215 | target_hw=None, 216 | respect_major_version=None, 217 | exclude_any_version=None, 218 | only_ids=None, 219 | ): 220 | warnings.warn( 221 | "get_software_vulnerabilities() is deprecated and will be removed in future release. " 222 | "Use VulnersApi.audit_software() or VulnersApi.audit_host() instead.", 223 | DeprecationWarning, 224 | ) 225 | """ 226 | Find software vulnerabilities using name and version. 227 | 228 | name: Software name, e.g. 'httpd' 229 | version: Software version, e.g. '2.1' 230 | """ 231 | return self.__get_burp_software( 232 | name, 233 | version, 234 | vendor, 235 | update, 236 | language, 237 | sw_edition, 238 | target_sw, 239 | target_hw, 240 | respect_major_version, 241 | exclude_any_version, 242 | only_ids, 243 | ) 244 | 245 | audit_software = Endpoint( 246 | method="post", 247 | url="/api/v4/audit/software/", 248 | params=[ 249 | ( 250 | "software", 251 | List( 252 | item=Any(Dict, String), 253 | description="List of dicts. E.g., [{'product': 'curl', 'version': '8.11.1', ...}, ...]", 254 | ), 255 | ), 256 | ( 257 | "match", 258 | String( 259 | required=False, 260 | description="'partial' (default) or 'full'", 261 | ), 262 | ), 263 | ( 264 | "fields", 265 | List( 266 | required=False, 267 | description="List of fields to retrieve about each vulnerability", 268 | ), 269 | ), 270 | ], 271 | content_handler=lambda c, _: c["result"], 272 | ) 273 | 274 | audit_host = Endpoint( 275 | method="post", 276 | url="/api/v4/audit/host/", 277 | params=[ 278 | ( 279 | "software", 280 | List( 281 | item=Any(Dict, String), 282 | description="List of dicts. E.g., [{'product': 'curl', 'version': '8.11.1', ...}, ...]", 283 | ), 284 | ), 285 | ("application", Any(String, Dict, required=False)), 286 | ("operating_system", Any(String, Dict, required=False)), 287 | ("hardware", Any(String, Dict, required=False)), 288 | ( 289 | "match", 290 | String( 291 | required=False, 292 | description="'partial' (default) or 'full'", 293 | ), 294 | ), 295 | ( 296 | "fields", 297 | List( 298 | required=False, 299 | description="List of fields to retrieve about each vulnerability", 300 | ), 301 | ), 302 | ], 303 | content_handler=lambda c, _: c["result"], 304 | ) 305 | 306 | @validate_params(cpe=String()) 307 | def get_cpe_vulnerabilities( 308 | self, cpe, respect_major_version=None, exclude_any_version=None, only_ids=None 309 | ): 310 | """ 311 | Find software vulnerabilities using CPE string. See CPE references at https://cpe.mitre.org/specification/ 312 | 313 | cpe: CPE software string, see https://cpe.mitre.org/specification/ 314 | exactmatch: if true searches only for bulletins corresponding to the specified minor version and revision 315 | """ 316 | return self.__get_burp_software( 317 | cpe, 318 | None, 319 | None, 320 | None, 321 | None, 322 | None, 323 | None, 324 | None, 325 | respect_major_version, 326 | exclude_any_version, 327 | only_ids, 328 | ) 329 | 330 | search_cpe = Endpoint( 331 | method="get", 332 | url="/api/v4/search/cpe/", 333 | params=[ 334 | ("product", String(required=True, description="Product string to search CPE for")), 335 | ("vendor", String(required=False, description="Optional vendor to include in CPE")), 336 | ], 337 | ) 338 | 339 | get_multiple_bulletins = Endpoint( 340 | method="post", 341 | url="/api/v3/search/id/", 342 | description="Fetch multiple bulletins by ids.", 343 | params=[ 344 | ( 345 | "id", 346 | Tuple(item=String(), description="List of ID's. E.g., ['CVE-2017-14174']"), 347 | ), 348 | ("fields", Tuple(item=String(), default=default_fields)), 349 | ], 350 | content_handler=lambda c, _: c["documents"], 351 | ) 352 | 353 | @validate_params(id=String(), fields=Tuple(item=String())) 354 | def get_bulletin(self, id, fields=default_fields): 355 | """ 356 | Fetch bulletin by id. 357 | 358 | id: Bulletin ID. E.g., "CVE-2017-14174" 359 | """ 360 | return self.get_multiple_bulletins([id], fields).get(id, {}) 361 | 362 | get_multiple_bulletin_references = Endpoint( 363 | method="post", 364 | url="/api/v3/search/id/", 365 | description="", 366 | params=[ 367 | ( 368 | "id", 369 | List(item=String(), description="List of ID's. E.g., ['CVE-2017-14174']"), 370 | ), 371 | ("fields", Tuple(item=String(), default=default_fields)), 372 | ("references", Const(True)), 373 | ], 374 | content_handler=lambda c, _: c["references"], 375 | ) 376 | 377 | @validate_params(id=String(), fields=Tuple(item=String())) 378 | def get_bulletin_references(self, id, fields=default_fields): 379 | """ 380 | Fetch bulletin references by identificator 381 | 382 | identificator: Bulletin ID. E.g., "CVE-2017-14174" 383 | """ 384 | return self.get_multiple_bulletin_references([id], fields=fields).get(id, {}) 385 | 386 | get_multiple_documents_with_references = Endpoint( 387 | method="post", 388 | url="/api/v3/search/id/", 389 | description="", 390 | params=[ 391 | ( 392 | "id", 393 | List(item=String(), description="List of ID's. E.g., ['CVE-2017-14174']"), 394 | ), 395 | ("fields", Tuple(item=String(), default=default_fields)), 396 | ("references", Const(True)), 397 | ], 398 | ) 399 | 400 | @validate_params(id=String(), fields=Tuple(item=String())) 401 | def get_document_with_references(self, id, fields=default_fields): 402 | """ 403 | Fetch bulletin with references by identificator 404 | 405 | identificator: Bulletin ID. E.g., "CVE-2017-14174" 406 | """ 407 | return self.get_multiple_documents_with_references([id], fields=fields) 408 | 409 | @validate_params(kbid=String()) 410 | def get_kb_seeds(self, kbid): 411 | """ 412 | Returns superseeds and parentseeds for the given KB. 413 | Superseeds means "KB which are covered by this KB". 414 | Parentseeds means "KB which are covering this KB". 415 | 416 | superseeds --> KB --> parentseeds 417 | 418 | kbid: Microsoft KB identificator 419 | """ 420 | candidate = self.get_bulletin(id=kbid, fields=["superseeds", "parentseeds"]) 421 | return { 422 | "superseeds": candidate.get("superseeds", []), 423 | "parentseeds": candidate.get("parentseeds", []), 424 | } 425 | 426 | @validate_params(kbid=String(), fields=Tuple(item=String())) 427 | def get_kb_updates(self, kbid, fields=default_fields): 428 | """ 429 | Returns list of updates for KB. 430 | 431 | kbid: Microsoft KB identificator. 432 | """ 433 | query = "type:msupdate AND kb:(%s)" % kbid 434 | return self.find_all(query, limit=1000, fields=fields) 435 | 436 | os_audit = Endpoint( 437 | method="post", 438 | url="/api/v3/audit/audit/", 439 | description=( 440 | "Linux Audit API for analyzing package vulnerabilities.\n" 441 | "Accepts RPM and DEB based package lists.\n" 442 | "For collecting RPM use command: rpm -qa --qf '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\\\\n'\n" 443 | "For collecting DEB use command: dpkg-query -W -f='${Package} ${Version} ${Architecture}\\\\n'\n" 444 | ), 445 | params=[ 446 | ( 447 | "os", 448 | String(description="Full name of the OS. Like Ubuntu, Debian, rhel, oraclelinux"), 449 | ), 450 | ("version", String(description="OS version")), 451 | ( 452 | "packages", 453 | List( 454 | item=String(), 455 | description="List of the installed packages", 456 | param="package", 457 | ), 458 | ), 459 | ], 460 | ) 461 | 462 | software_audit = Endpoint( 463 | method="post", 464 | url="/api/v3/burp/packages/", 465 | description=( 466 | "Software audit allow you to analyse software name / version pairs for the CVE's.\n" 467 | "Packages input format, list of dicts:\n" 468 | "[{'software': 'Mozilla Firefox', 'version': '80.0.1'}]\n" 469 | ), 470 | params=[ 471 | ( 472 | "os", 473 | String(description="Full name of the OS. Like Ubuntu, Debian, rhel, oraclelinux"), 474 | ), 475 | ("version", String(description="OS version", param="osVersion")), 476 | ("packages", List(item=Dict(), description="List of the software dicts")), 477 | ], 478 | ) 479 | 480 | kb_audit = Endpoint( 481 | method="post", 482 | url="/api/v3/audit/kb/", 483 | description="Windows KB audit function", 484 | params=[ 485 | ( 486 | "os", 487 | String(description="Windows OS name, like 'Windows Server 2012 R2'"), 488 | ), 489 | ( 490 | "kb_list", 491 | List( 492 | item=String(), 493 | description="List of installed KB's, ['KB2918614', 'KB2918616']", 494 | param="kbList", 495 | ), 496 | ), 497 | ], 498 | ) 499 | 500 | winaudit = Endpoint( 501 | method="post", 502 | url="/api/v3/audit/winaudit/", 503 | description="Windows KB and software audit function", 504 | params=[ 505 | ( 506 | "os", 507 | String(description="Windows OS name, like 'Windows Server 2012 R2'"), 508 | ), 509 | ( 510 | "os_version", 511 | String(description="Windows OS version, like '10.0.19045'"), 512 | ), 513 | ( 514 | "platform", 515 | String(required=False, description="os platform like x86"), 516 | ), 517 | ( 518 | "kb_list", 519 | List( 520 | item=String(), description="List of installed KB's, ['KB2918614', 'KB2918616']" 521 | ), 522 | ), 523 | ( 524 | "software", 525 | List( 526 | item=Dict(), 527 | description="List of the software dicts, {'software': 'Microsoft Edge', 'version': '107.0.1418.56'}", 528 | ), 529 | ), 530 | ], 531 | ) 532 | 533 | get_suggestion = Endpoint( 534 | method="post", 535 | url="/api/v3/search/suggest/", 536 | params=[("type", Const("distinct")), ("field_name", String(param="fieldName"))], 537 | content_handler=lambda c, _: c["suggest"], 538 | ) 539 | 540 | get_ai_score = Endpoint( 541 | method="post", 542 | url="/api/v3/ai/scoretext/", 543 | params=[ 544 | ("text", String()), 545 | ], 546 | content_handler=lambda c, _: c.get("score", 0), 547 | ) 548 | 549 | query_autocomplete = Endpoint( 550 | method="post", 551 | url="/api/v3/search/autocomplete/", 552 | description="Ask Vulners for possible suggestions to complete your query", 553 | params=[("query", String(description="Vulners Search query"))], 554 | content_handler=lambda c, _: [q[0] for q in c["suggestions"]], 555 | ) 556 | 557 | # noinspection PyTypeChecker 558 | def _unpack_json_file(c, _): 559 | with zipfile.ZipFile(io.BytesIO(c)) as zip_file: 560 | if len(zip_file.namelist()) > 1: 561 | raise Exception("Unexpected file count in Vulners ZIP archive") 562 | file_name = zip_file.namelist()[0] 563 | return json.loads(zip_file.open(file_name).read()) 564 | 565 | __archive_collection = Endpoint( 566 | method="get", 567 | url="/api/v3/archive/collection/", 568 | params=[("type", String()), ("datefrom", String()), ("dateto", String())], 569 | result_type="zipjson", 570 | content_handler=_unpack_json_file, 571 | ) 572 | 573 | __distributive = Endpoint( 574 | method="get", 575 | url="/api/v3/archive/distributive/", 576 | params=[("os", String()), ("version", String())], 577 | result_type="zipjson", 578 | content_handler=_unpack_json_file, 579 | ) 580 | 581 | getsploit = Endpoint( 582 | method="get", 583 | url="/api/v3/archive/getsploit/", 584 | params=[], 585 | result_type="zip", 586 | ) 587 | 588 | del _unpack_json_file 589 | 590 | @validate_params(collection=String(), start_date=String(), end_date=String()) 591 | def get_collection(self, collection, start_date="1950-01-01", end_date="2199-01-01"): 592 | """ 593 | Get entire collection data 594 | 595 | :param collection: Collection name 596 | """ 597 | collections = self.get_suggestion("type") 598 | if collection not in collections: 599 | raise ParamError("Unknown %%s. Available values are %s" % (collections,), "collection") 600 | return self.__archive_collection(type=collection, datefrom=start_date, dateto=end_date) 601 | 602 | @validate_params(os=String(), version=String()) 603 | def get_distributive(self, os, version): 604 | """ 605 | Get dict with data for OS vulnerability assessment 606 | 607 | os: OS name 608 | version: OS version 609 | """ 610 | supported_os = self.get_suggestion("affectedPackage.OS") 611 | if os.lower() not in [os_name.lower() for os_name in supported_os]: 612 | raise ParamError("Unknown %%s. Available values are %s" % (supported_os,), "os") 613 | data = self.__distributive(os=os, version=version) 614 | return [bulletin["_source"] for bulletin in data] 615 | 616 | __report = Endpoint( 617 | method="post", 618 | url="/api/v3/reports/vulnsreport", 619 | params=[ 620 | ( 621 | "reporttype", 622 | String(description="One of strings [vulnssummary, vulnslist, ipsummary, scanlist]"), 623 | ), 624 | ("skip", Integer(description="Skip this amount of items. 10000 is the hard limit")), 625 | ( 626 | "size", 627 | Integer( 628 | description="The maximum number of items to return. 10000 is the hard limit" 629 | ), 630 | ), 631 | ( 632 | "filter", 633 | Dict( 634 | description="Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'}" 635 | ), 636 | ), 637 | ( 638 | "sort", 639 | String(description="Field to sort, eg 'severity' or '-severity' to sort desc"), 640 | ), 641 | ], 642 | content_handler=lambda x, _: x["report"], 643 | ) 644 | 645 | @validate_params( 646 | limit=Integer(minimum=1, maximum=10000), 647 | offset=Integer(minimum=0, maximum=9999), 648 | filter=Dict(), 649 | sort=String(), 650 | ) 651 | def vulnssummary_report(self, limit=30, offset=0, filter=None, sort=""): 652 | """ 653 | Get Linux Audit results. Return summary for all found vulnerabilities - id, title, score, severity etc 654 | 655 | limit: The maximum number of items to return. 10000 is the hard limit. 656 | offset: Skip this amount of items. 10000 is the hard limit. 657 | filter: Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'} 658 | sort: Field to sort, eg 'severity' or '-severity' to sort desc 659 | """ 660 | 661 | return self.__report("vulnssummary", offset, limit, filter or {}, sort) 662 | 663 | @validate_params( 664 | limit=Integer(minimum=1, maximum=10000), 665 | offset=Integer(minimum=0, maximum=9999), 666 | filter=Dict(), 667 | sort=String(), 668 | ) 669 | def vulnslist_report(self, limit=30, offset=0, filter=None, sort=""): 670 | """ 671 | Get Linux Audit results. Return list of vulnerabilities found on hosts: 672 | vulnerability id, vulnerability title, vulnerability severity, host information, etc 673 | 674 | limit: The maximum number of items to return. 10000 is the hard limit. 675 | offset: Skip this amount of items. 10000 is the hard limit. 676 | filter: Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'} 677 | sort: Field to sort, eg 'severity' or '-severity' to sort desc 678 | """ 679 | 680 | return self.__report("vulnslist", offset, limit, filter or {}, sort) 681 | 682 | @validate_params( 683 | limit=Integer(minimum=1, maximum=10000), 684 | offset=Integer(minimum=0, maximum=9999), 685 | filter=Dict(), 686 | sort=String(), 687 | ) 688 | def ipsummary_report(self, limit=30, offset=0, filter=None, sort=""): 689 | """ 690 | Get Linux Audit results. Return summary for hosts: 691 | agent id, host ip, host fqdn, os name and version, found vulnerabilities count and severity 692 | 693 | limit: The maximum number of items to return. 10000 is the hard limit. 694 | offset: Skip this amount of items. 10000 is the hard limit. 695 | filter: Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'} 696 | sort: Field to sort, eg 'total' or '-total' to sort desc 697 | """ 698 | 699 | return self.__report("ipsummary", offset, limit, filter or {}, sort) 700 | 701 | @validate_params( 702 | limit=Integer(minimum=1, maximum=10000), 703 | offset=Integer(minimum=0, maximum=9999), 704 | filter=Dict(), 705 | sort=String(), 706 | ) 707 | def scanlist_report(self, limit=30, offset=0, filter=None, sort=""): 708 | """ 709 | Get Linux Audit results. Return list of scans: 710 | host ip and fqdn, os name and version, scan date, cvss score 711 | 712 | limit: The maximum number of items to return. 10000 is the hard limit. 713 | offset: Skip this amount of items. 10000 is the hard limit. 714 | filter: Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'} 715 | sort: Field to sort, eg 'modified' or '-modified' to sort desc 716 | """ 717 | 718 | return self.__report("scanlist", offset, limit, filter or {}, sort) 719 | 720 | get_subscriptions = Endpoint( 721 | method="get", 722 | url="/api/v3/subscriptions/listEmailSubscriptions/", 723 | content_handler=lambda hooks, _: hooks["subscriptions"], 724 | ) 725 | 726 | add_subscription = Endpoint( 727 | method="post", 728 | url="/api/v3/subscriptions/addEmailSubscription/", 729 | params=[ 730 | ("query", String()), 731 | ("email", String()), 732 | ("format", String(default="html", choices=("html", "json", "pdf"))), 733 | ("crontab", String(allow_null=True, default=None)), 734 | ("query_type", String(default="lucene")), 735 | ], 736 | ) 737 | 738 | edit_subscription = Endpoint( 739 | method="post", 740 | url="/api/v3/subscriptions/editEmailSubscription/", 741 | params=[ 742 | ("subscriptionid", String()), 743 | ("format", String(allow_null=True, default=None, choices=("html", "json", "pdf"))), 744 | ("crontab", String(allow_null=True, default=None)), 745 | ( 746 | "active", 747 | String(allow_null=True, default=None, choices=("yes", "no", "true", "false")), 748 | ), 749 | ], 750 | ) 751 | 752 | delete_subscription = Endpoint( 753 | method="post", 754 | url="/api/v3/subscriptions/removeEmailSubscription/", 755 | params=[ 756 | ("subscriptionid", String()), 757 | ], 758 | ) 759 | 760 | get_webhooks = Endpoint( 761 | method="get", 762 | url="/api/v3/subscriptions/listWebhookSubscriptions/", 763 | content_handler=lambda hooks, _: hooks["subscriptions"], 764 | ) 765 | 766 | add_webhook = Endpoint( 767 | method="post", 768 | url="/api/v3/subscriptions/addWebhookSubscription/", 769 | params=[ 770 | ("query", String()), 771 | ("active", Boolean(default=True)), 772 | ], 773 | content_handler=lambda hook, _: hook["subscription"], 774 | ) 775 | 776 | enable_webhook = Endpoint( 777 | method="post", 778 | url="/api/v3/subscriptions/enableWebhookSubscription/", 779 | params=[ 780 | ("subscriptionid", String()), 781 | ("active", Boolean()), 782 | ], 783 | ) 784 | 785 | delete_webhook = Endpoint( 786 | method="post", 787 | url="/api/v3/subscriptions/deleteWebhookSubscription/", 788 | params=[ 789 | ("subscriptionid", String()), 790 | ], 791 | ) 792 | 793 | read_webhook = Endpoint( 794 | method="get", 795 | url="/api/v3/subscriptions/webhook", 796 | params=[("subscriptionid", String()), ("newest_only", String(default="true"))], 797 | ) 798 | 799 | @validate_params( 800 | limit=Integer(minimum=1, maximum=10000), 801 | offset=Integer(minimum=0, maximum=9999), 802 | filter=Dict(), 803 | sort=String(), 804 | ) 805 | def hostvulns_report(self, limit=30, offset=0, filter=None, sort=""): 806 | """ 807 | Get Linux Audit results. Return list of hosts and host vulnerabilities: 808 | host ip and fqdn, os name and version, cumulative fix, vulnerability ids 809 | 810 | limit: The maximum number of items to return. 10000 is the hard limit. 811 | offset: Skip this amount of items. 10000 is the hard limit. 812 | filter: Dict of fields to filter, eg { 'OS': 'Centos', 'OSVersion': '7'} 813 | sort: Field to sort, eg 'modified' or '-modified' to sort desc 814 | """ 815 | 816 | return self.__report("hostvulns", offset, limit, filter or {}, sort) 817 | 818 | @validate_params(id=String()) 819 | def get_bulletin_history(self, id): 820 | data = self.__get_bulletin_history(id=id) 821 | return data["result"] 822 | 823 | __get_bulletin_history = Endpoint( 824 | method="get", 825 | url="/api/v3/search/history/", 826 | description="Bulletin history list", 827 | params=[("id", String(description="Bulletin ID"))], 828 | ) 829 | 830 | 831 | _Unset = object() 832 | 833 | 834 | # noinspection PyPep8Naming 835 | class DeprecatedVulnersApi(VulnersApi): 836 | def __init__(self, *args, **kwargs): 837 | super(DeprecatedVulnersApi, self).__init__(*args, **kwargs) 838 | warnings.warn( 839 | "Vulners is deprecated and will be removed in future release. " 840 | "Use VulnersApi instead.", 841 | DeprecationWarning, 842 | ) 843 | 844 | def search(self, query, limit=100, offset=0, fields=None): 845 | warnings.warn( 846 | "search() is deprecated and will be removed in future release. " 847 | "Use VulnersApi.find_all() instead.", 848 | DeprecationWarning, 849 | ) 850 | return self.find_all( 851 | query, limit=limit, offset=offset, fields=fields or self.default_fields 852 | ) 853 | 854 | def searchPage(self, query, pageSize=20, offset=0, fields=None): 855 | warnings.warn( 856 | "searchPage() is deprecated and will be removed in future release. " 857 | "Use VulnersApi.find() instead.", 858 | DeprecationWarning, 859 | ) 860 | return self.find(query, limit=pageSize, offset=offset, fields=fields or self.default_fields) 861 | 862 | def searchExploit(self, query, lookup_fields=None, limit=100, offset=0, fields=None): 863 | warnings.warn( 864 | "searchExploit() is deprecated and will be removed in future release. " 865 | "Use VulnersApi.find_exploit_all() instead.", 866 | DeprecationWarning, 867 | ) 868 | lookup_fields = lookup_fields or () 869 | if isinstance(lookup_fields, (set, list)): 870 | lookup_fields = tuple(lookup_fields) 871 | return self.find_exploit_all( 872 | query, 873 | lookup_fields=lookup_fields, 874 | limit=limit, 875 | offset=offset, 876 | fields=fields or self.default_fields, 877 | ) 878 | 879 | def searchExploitPage(self, query, lookup_fields=None, limit=100, offset=0, fields=None): 880 | warnings.warn( 881 | "searchExploitPage() is deprecated and will be removed in future release. " 882 | "Use VulnersApi.find_exploit() instead.", 883 | DeprecationWarning, 884 | ) 885 | lookup_fields = lookup_fields or () 886 | if isinstance(lookup_fields, (set, list)): 887 | lookup_fields = tuple(lookup_fields) 888 | return self.find_exploit( 889 | query, 890 | lookup_fields=lookup_fields, 891 | limit=limit, 892 | offset=offset, 893 | fields=fields or self.default_fields, 894 | ) 895 | 896 | def softwareVulnerabilities(self, name, version, maxVulnerabilities=_Unset): 897 | warnings.warn( 898 | "softwareVulnerabilities() is deprecated and will be removed in future release. " 899 | "Use VulnersApi.get_software_vulnerabilities() instead.", 900 | DeprecationWarning, 901 | ) 902 | if maxVulnerabilities is not _Unset: 903 | warnings.warn( 904 | "maxVulnerabilities is deprecated and will be removed in future release.", 905 | DeprecationWarning, 906 | ) 907 | return self.get_software_vulnerabilities(name, version) 908 | 909 | def cpeVulnerabilities(self, cpeString, maxVulnerabilities=_Unset): 910 | warnings.warn( 911 | "cpeVulnerabilities() is deprecated and will be removed in future release. " 912 | "Use VulnersApi.get_cpe_vulnerabilities() instead.", 913 | DeprecationWarning, 914 | ) 915 | if maxVulnerabilities is not _Unset: 916 | warnings.warn( 917 | "maxVulnerabilities is deprecated and will be removed in future release.", 918 | DeprecationWarning, 919 | ) 920 | return self.get_cpe_vulnerabilities(cpeString) 921 | 922 | def audit(self, os, os_version, package): 923 | warnings.warn( 924 | "audit() is deprecated and will be removed in future release. " 925 | "Use VulnersApi.os_audit() instead.", 926 | DeprecationWarning, 927 | ) 928 | return self.os_audit(os, os_version, package) 929 | 930 | def kbAudit(self, os, kb_list): 931 | warnings.warn( 932 | "kbAudit() is deprecated and will be removed in future release. " 933 | "Use VulnersApi.kb_audit() instead.", 934 | DeprecationWarning, 935 | ) 936 | return self.kb_audit(os, kb_list) 937 | 938 | def document(self, identificator, fields=None): 939 | warnings.warn( 940 | "document() is deprecated and will be removed in future release. " 941 | "Use VulnersApi.get_bulletin() instead.", 942 | DeprecationWarning, 943 | ) 944 | return self.get_bulletin(identificator, fields=fields or self.default_fields) 945 | 946 | def documentList(self, identificatorList, fields=None): 947 | warnings.warn( 948 | "documentList() is deprecated and will be removed in future release. " 949 | "Use VulnersApi.get_multiple_bulletins() instead.", 950 | DeprecationWarning, 951 | ) 952 | return self.get_multiple_bulletins(identificatorList, fields=fields or self.default_fields) 953 | 954 | def references(self, identificator, fields=None): 955 | warnings.warn( 956 | "references() is deprecated and will be removed in future release. " 957 | "Use VulnersApi.get_bulletin_references() instead.", 958 | DeprecationWarning, 959 | ) 960 | return self.get_bulletin_references(identificator, fields=fields or self.default_fields) 961 | 962 | def referencesList(self, identificatorList, fields=None): 963 | warnings.warn( 964 | "referencesList() is deprecated and will be removed in future release. " 965 | "Use VulnersApi.get_multiple_bulletin_references() instead.", 966 | DeprecationWarning, 967 | ) 968 | return self.get_multiple_bulletin_references( 969 | identificatorList, fields=fields or self.default_fields 970 | ) 971 | 972 | def collections(self): 973 | warnings.warn( 974 | "collections() is deprecated and will be removed in future release. " 975 | "Use VulnersApi.get_suggestion('type') instead.", 976 | DeprecationWarning, 977 | ) 978 | return self.get_suggestion("type") 979 | 980 | def suggest(self, field_name): 981 | warnings.warn( 982 | "suggest() is deprecated and will be removed in future release. " 983 | "Use VulnersApi.get_suggestion() instead.", 984 | DeprecationWarning, 985 | ) 986 | return self.get_suggestion(field_name) 987 | 988 | def aiScore(self, text): 989 | warnings.warn( 990 | "aiScore() is deprecated and will be removed in future release. " 991 | "Use VulnersApi.get_ai_score() instead.", 992 | DeprecationWarning, 993 | ) 994 | return self.get_ai_score(text) 995 | 996 | def rules(self): 997 | warnings.warn( 998 | "rules() is deprecated and will be removed in future release. " 999 | "Use VulnersApi.get_web_application_rules() instead.", 1000 | DeprecationWarning, 1001 | ) 1002 | return self.get_web_application_rules() 1003 | 1004 | def kbSuperseeds(self, kb_identificator): 1005 | warnings.warn( 1006 | "kbSuperseeds() is deprecated and will be removed in future release. " 1007 | "Use VulnersApi.get_kb_seeds() instead.", 1008 | DeprecationWarning, 1009 | ) 1010 | return self.get_kb_seeds(kb_identificator) 1011 | 1012 | def kbUpdates(self, kb_identificator, fields=None): 1013 | warnings.warn( 1014 | "kbUpdates() is deprecated and will be removed in future release. " 1015 | "Use VulnersApi.get_kb_updates() instead.", 1016 | DeprecationWarning, 1017 | ) 1018 | return self.get_kb_updates(kb_identificator, fields=fields or self.default_fields) 1019 | 1020 | def autocomplete(self, query): 1021 | warnings.warn( 1022 | "autocomplete() is deprecated and will be removed in future release. " 1023 | "Use VulnersApi.query_autocomplete() instead.", 1024 | DeprecationWarning, 1025 | ) 1026 | return self.query_autocomplete(query) 1027 | 1028 | def archive(self, collection, start_date="1950-01-01", end_date="2199-01-01"): 1029 | warnings.warn( 1030 | "archive() is deprecated and will be removed in future release. " 1031 | "Use VulnersApi.get_collection() instead.", 1032 | DeprecationWarning, 1033 | ) 1034 | return self.get_collection(collection, start_date, end_date) 1035 | 1036 | def distributive(self, os, version): 1037 | warnings.warn( 1038 | "distributive() is deprecated and will be removed in future release. " 1039 | "Use VulnersApi.get_distributive() instead.", 1040 | DeprecationWarning, 1041 | ) 1042 | return self.get_distributive(os, version) 1043 | 1044 | 1045 | Vulners = DeprecatedVulnersApi 1046 | --------------------------------------------------------------------------------