Repository: mazen160/bfac Branch: master Commit: 18fb0b5dc050 Files: 9 Total size: 114.2 KB Directory structure: gitextract_nagun_44/ ├── .travis.yml ├── CHANGELOG.txt ├── CONTRIBUTORS.txt ├── Dockerfile ├── LICENSE.txt ├── README.md ├── bfac ├── requirements.txt └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .travis.yml ================================================ language: python python: - "2.6" - "2.7" - "3.2" - "3.3" - "3.4" - "3.5" - "3.5-dev" # 3.5 development branch - "3.6" - "3.6-dev" # 3.6 development branch - "3.7-dev" # 3.7 development branch - "nightly" # development branches # command to install dependencies install: "pip install -r requirements.txt" # command to run tests script: python setup.py install ================================================ FILE: CHANGELOG.txt ================================================ # ******************************************************************* # *** BFAC: Backup File Artifacts Checker *** # * Description: # An automated tool that checks for backup artifacts # that may disclose the web-application's source code. # * Homepage: # https://github.com/mazen160/bfac # * Author: # Mazin Ahmed # ******************************************************************* ### Changelog:- * v1.4: Additions/Features:- [+] Added --proxy-file and --user-agents-file options. [+] Improved console output. [+] Added pattern for CVE-2017-12616. Fixed Bugs:- [*] Fixed a bug in proxying requests - Thanks Justin Kennedy @jstnkndy. Known Bugs/Issues:- None * v1.3: Additions/Features:- [+] BFAC now supports multithrading. [+] request-rate throttling support. [+] Redesigned command-line user interface. [+] Code refactor. [+] Better support for using BFAC as a module. [*] Removed --verbose and --api. [+] Improved the detection algorithm. [+] Added JSON and CSV reporting. Fixed Bugs:- None Known Bugs/Issues:- None * v1.2: Additions/Features:- [+] Complete code-rewrite of BFAC. [+] BFAC now can works as module. [+] Additional BFA patterns. Fixed Bugs:- [*] Improved url_handler() way of handling URLs. [*] Fixed UI/UX issues. Known Bugs/Issues:- None * v1.1: Additions/Features:- [+] Official BFAC User-Agent - Thanks Christian Folini (@ChrFolini) [+] Additional BFA patterns. [+] Better way of parsing URLs - Thanks Omar Kurt (@omarkurt) [+] --dvcs-test flag to only check for exposed DVCS repositories, (DVCS tests are done by default when using BFAC on level 4, now you can run it seperately). [+] --api flag to return findings in JSON form. [+] --timeout option to control the timeout. [+] --proxy flag to issue requests via proxies when testing. [+] --proxy-cred to be used with --proxy flag for handling proxy credintials. [+] --user-agent, -ua to specify your own user-agent, (--random-agent is available since v1.0). [+] --cookie flag to specify arbitray HTTP Cookie header. [+] --host flag to specify arbitray HTTP Host header. [+] --headers flag to add arbitrary HTTP headers in requests. [+] --invalid-content-length flag: When verifying the existence of files, BFAC by default send an initial request to determine the content-length and to build an idea about the invalid (not found) pages. This flag can be used to disable the automatic process of sending an initial request and manually specifying a content-length of an invalid page. It's an optional flag that can be used when facing false-positives, tests shows it rarely need this option, but it would be good to have it since BFAC aims to be an "All-in-One" tool for testing backup-file artifacts. [+] --content-length-range flag: This option can be used to optmise the range of the invalid pages based on the content-length. It's an optional flag, and the reason this flag is added is as same as --invalid-content-length flag. [+] New --help design. Fixed Bugs:- [*] Fixed a bug in url_handler(). [*] Better support for Windows machines. [*] Fixed a bug that can have same check in a test done more than one time. Now it only does the same check once. Known Bugs/Issues:- None * v1.0: Initial release. ================================================ FILE: CONTRIBUTORS.txt ================================================ # ******************************************************************* # *** BFAC: Backup File Artifacts Checker *** # * Description: # An automated tool that checks for backup artifacts # that may disclose the web-application's source code. # * Homepage: # https://github.com/mazen160/bfac # * Author: # Mazin Ahmed # ******************************************************************* Contributors (alphabetical-order):- * Christian Folini (@ChrFolini) * Ed (@EdOverflow) * James Kettle (@albinowax) * Justin Kennedy (@jstnkndy) * Liam Somerville (@leesoh) * Omar Kurt (@omarkurt) * Zeecka (@zeecka_) Thank you for making BFAC a better project for everyone! ================================================ FILE: Dockerfile ================================================ FROM python:alpine RUN apk add git RUN git clone https://github.com/mazen160/bfac.git WORKDIR bfac RUN python setup.py install ENTRYPOINT ["bfac"] ================================================ FILE: LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ BFAC ---- *Advanced Backup-File Artifacts Testing for Web-Applications* ![BFAC](https://raw.githubusercontent.com/mazen160/public/master/static/images/BFAC-banner.png) BFAC (Backup File Artifacts Checker) is an automated tool that checks for backup artifacts that may disclose the web-application's source code. The artifacts can also lead to leakage of sensitive information, such as passwords, directory structure, etc. **The goal of BFAC is to be an *all-in-one tool* for backup-file artifacts black-box testing.** ## Features * Multithreaded scanning. * Includes request rate throttling. * HTTP proxy support. * Uses multiple algorithms for automatically detecting valid and invalid pages. * HTTP proxy support * User agent randomization. * Batch processing. * Works both as a command-line tool and Python module. * Support for Windows, MacOS, and Linux operating systems. * Reporting: simple, verbose, CSV, JSON. ## Usage | Description | Command | |------------------------------------------------------------|-------------------------------------------------------------------------| | Help | `bfac --help` | | Check a single URL. | `bfac --url http://example.com/test.php` | | Check a list of URLs. | `bfac --list testing_list.txt` | | Single URL with a different level (level 2 for example). | `bfac --url http://example.com/test.php --level 2` | | Single URL and show the results only. | `bfac --no-text --url http://example.com/test.php` | | Limit the test to exposed DVCS tests. | `bfac --dvcs-test --url http://example.com/` | | Verify existence of files using Content-Length checks only.| `bfac --detection-technique content_length http://example.com/test.php` | | Verify existence of files using Status-Code checks only. | `bfac --detection-technique status_code http://example.com/test.php` | | Exclude results with specific status-codes. | `bfac --exclude-status-codes 301,999 http://example.com/test.php` | ## Using BFAC as a module ```python import bfac testing_level = 5 # Returns a list of BFA patterns for http://example.com/test.php bfa_urls = bfac.generate_bfa_urls( 'http://example.com/test.php', testing_level=testing_level) # Performs BFA testing using BFAC, and returns a list of findings, if any. # If nothing is identified, it returns an empty list. bfa_testing_result = bfac.test_url( 'http://example.com/test.php', testing_level=testing_level) ``` ## Requirements * Python2 or Python3 * requests * colorama ## Installation [Optional] `sudo python setup.py install` ## Compatibility The project currently supports all platforms that run Python. The project is compatible with both Python 2 and Python 3. ## Frequently Asked Questions **Q:** How to use BFAC with all levels? **A:** BFAC runs with all levels by default. if you would like to decrease the used testing level, you can do it by setting the `--level` flag to a lower value. **Q:** How do BFAC determines if the file actually exists on the web-server or not? **A:** BFAC approach regarding detection differs from regular security tools. Regular security tools determinate if a file exists on a server by checking the HTTP status code. Since there are system administrators that might spoof HTTP status codes for HTTP requests to fool security tools and bots, BFAC implemented an additional method. It checks for the general response of an invalid or non-available web resource. Then, it sends requests and compare the response size of the request with the initial base. * `--detection-technique all` uses both methods for HTTP Status Code checks, and the HTTP Content-Length. * `--detection-technique status_code`: uses HTTP status code checks only. * `--detection-technique content_length`: uses HTTP Content-Length checks only. ## Community Contribution Contribution from the community to the BFAC project is very welcome. If you find a bug, have an idea for a feature, ideas to reconstruct the code to work better, or anything else, feel free to submit an issue or a pull request. ### Using the issue tracker The issue tracker is the preferred channel for bug reports and features requests. [![GitHub issues](https://img.shields.io/github/issues/mazen160/bfac.svg?style=flat-square)](https://github.com/mazen160/bfac/issues) ## Legal Disclaimer This project is made for educational and ethical testing purposes only. Usage of BFAC for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program. ## License The project is currently licensed under GNU GPLv3.0 License. [![GitHub license](https://img.shields.io/badge/license-GPL-blue.svg?style=flat-square)](https://raw.githubusercontent.com/mazen160/bfac/master/LICENSE.txt) ## Author *Mazin Ahmed* * Website: [https://mazinahmed.net](https://mazinahmed.net) * Email: *mazin AT mazinahmed DOT net* * Twitter: [https://twitter.com/mazen160](https://twitter.com/mazen160) * Linkedin: [http://linkedin.com/in/infosecmazinahmed](http://linkedin.com/in/infosecmazinahmed) ================================================ FILE: bfac ================================================ #!/usr/bin/env python3 # coding=utf-8 # ******************************************************************* # *** BFAC: Backup File Artifacts Checker *** # * Description: # An automated tool that checks for backup artifacts # that may disclose the web-application's source code. # * Version: # v1.4 # * Homepage: # https://github.com/mazen160/bfac # * Author: # Mazin Ahmed # ******************************************************************* # Modules import sys import os import random import time import csv import json import argparse import platform import threading import webbrowser import colorama try: import Queue as queue except ImportError: import queue try: from urllib import parse as urlparse except ImportError: import urlparse try: import requests except ImportError: if (__name__ == '__main__'): print('[!] Error: requests module does not seem to be installed.') print('Use the following command to install requests module.') if (sys.version_info[0] == 2): print('$ pip install requests') else: print('$ pip3 install requests') print('\nExiting...') exit(1) # Disable SSL warnings try: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except Exception: pass def version(): """ Returns current version. """ version = "1.4" return(version) class symbols: """ Standard symbols list """ error = colorama.Fore.RED + '[!]' + colorama.Fore.RESET success = colorama.Fore.GREEN + '[$]' + colorama.Fore.RESET info = colorama.Fore.YELLOW + '[i]' + colorama.Fore.RESET def logo(enable_colored_logo=True): """ Returns logo. """ if enable_colored_logo is False: """ Uncolored Logo. """ logo = 70 * "-" + """" \t\t _____ _____ _____ _____ \t\t| __ | __| _ | | \t\t| __ -| __| | --| \t\t|_____|__| |__|__|_____| \t\t \t -:::Backup File Artifacts Checker:::- \t\t Version: """ + str(version()) + """ Advanced Backup-File Artifacts Testing for Web-Applications Author: Mazin Ahmed | | @mazen160\ \n""" + 70 * "-" if enable_colored_logo is True: """ Colored Logo. """ logo = 70 * "-" + colorama.Fore.CYAN + """ \t\t _____ _____ _____ _____ \t\t| __ | __| _ | | \t\t| __ -| __| | --| \t\t|_____|__| |__|__|_____| \t\t \t -:::Backup File Artifacts Checker:::- \t\t Version: """ + str(version()) + """ Advanced Backup-File Artifacts Testing for Web-Applications Author: Mazin Ahmed | | @mazen160\ \n"""\ + colorama.Style.RESET_ALL + 70 * "-" return(logo) def instructions(): """ Returns command-line instructions for using BFAC. """ instructions = """ Arguments:- * Target Options -u, --url URL Check a single URL. -L, --list LIST Check a list of URLs. --stdin Check URLs from STDIN input. * Testing Options -level, --level LEVEL Set testing level [1-5] (default: 5). --dvcs-test Perform DVCS testing only, which is also\ available by default on Level 5. --threads THREADS Thread workers to use (default 10). --request-rate-throttling REQUESTS_PER_SECOND Request rate throttling per second\ (default: 30) * Artifacts Detection Options --invalid-content-length INVALID_CONTENT_LENGTH Manually specify the invalid\ Content-Length, instead of performing this check automatically. --invalid-content-length-offset OFFSET Manually specify the Content-Length\ offset for invalid pages (default: 50). --technique, --detection-technique TECHNIQUE Technique to verify the availability\ of the file. (options: status_code, content_length, all)\ (default: all) -xsc, --exclude-status-codes EXCLUDE_STATUS_CODES Specify status codes to exclude,\ separated by commas. * Requests-Related Options -ua, --user-agent USER_AGENT HTTP User-Agent header value. -ra, --random-agent Use random User-Agents. --user-agents-file Use a User-Agents file. --cookie COOKIE HTTP Cookie header value. --host HOST HTTP Host header value. --headers HEADERS Extra headers\ (e.g. "Accept-Language: fr\\nETag: 123") --proxy PROXY Use a proxy on testing. --proxy-cred PROXY_CRED Proxy authentication credentials\ (name:password). --proxy-file PROXY_FILE Use a proxy list file. --timeout TIMEOUT HTTP Request timeout by seconds.\ (default: 5) * Output-Related Options -o, --output OUTPUT Save identified URLs into a file. --verbose-output OUTPUT Save identified URLs, with \ status-codes and content-length into a file. --json-output OUTPUT Save findings in JSON file. --csv-output OUTPUT Save findings in CSV file. * Other Options -h, --help Show this help message and exit. --no-text Print and write a clean output\ with results only. --debug Enable debugging. --issue Report an issue via GitHub. -V, --version Show current version and exit. """ return(instructions) def exception_handler(message, exception, enable_debug=True, notext=False): """ Handles exceptions. """ if enable_debug is not True: return(2) if ((notext is True) or (__name__ != '__main__')): return(1) # showing exception that --debug is not global used # or when used as a module or # --no-text is used. exception = str(exception) message = str(message) print("%sError: %s :: %s%s" % (colorama.Fore.RED, message, exception, colorama.Style.RESET_ALL)) class RequestsHandler: """ Responsible for handling URLs and performing requests. """ def __init__(self): self.timeout = 5 # Default timeout. def proxy_handler(self, link, proxy=None, proxy_cred=None, proxy_list=None): if proxy_list is not None: chosen_proxy = random.choice(proxy_list) elif proxy is not None: chosen_proxy = proxy proxy_scheme_original = chosen_proxy.split(':')[0].lower() proxy_scheme = 'http' if proxy_scheme_original == "socks": chosen_proxy = chosen_proxy.replace("socks://", "socks5://") if link.lower().split("://")[0] == 'https': proxy_scheme = 'https' proxy_url = chosen_proxy if (proxy_cred is not None): username = str(str(proxy_cred).split(':')[0]) password = str(str(proxy_cred).split(':')[1]) replace_original_start_with = (str(proxy_scheme_original) + '://' + str(username) + ':' + str(password) + str('@')) proxy_url = chosen_proxy.replace( str(proxy_scheme_original) + '://', replace_original_start_with) proxy_dict = {proxy_scheme: proxy_url} return(proxy_dict) def ua_handler(self, custom_user_agent_list=None, use_random_agent=False): if (use_random_agent is False) and (custom_user_agent_list is None): # BFAC DEFAULT UA chosen_agent = 'BFAC ' + str(version()) + \ ' (https://github.com/mazen160/bfac)' if (use_random_agent is True) or (custom_user_agent_list is not None): # List of random User-Agents. agents = [ "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) " + "Gecko/20100101 Firefox/51.0", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0)" + " Gecko/20100101 Firefox/51.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/56.0.2924.87 Safari/537.36", "Mozilla/5.0 (Windows NT 6.1; WOW64; " + "Trident/7.0; rv:11.0) like Gecko", "Mozilla/5.0 (Macintosh; Intel Mac OS " + "X 10_12_2) AppleWebKit/602.3.12 (KHTML, " + "like Gecko) Version/10.0.2 Safari/602.3.12", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; " + "rv:51.0) Gecko/20100101 Firefox/51.0", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 " + "like Mac OS X) AppleWebKit/602.4.6 (KHTML, " + "like Gecko) Version/10.0 Mobile/14D27" + " Safari/602.1", "Mozilla/5.0 (Linux; Android 6.0.1; " + "Nexus 6P Build/MTC19X) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/56.0.2924.87 " + "Mobile Safari/537.36", "Mozilla/5.0 (Linux; Android 4.4.4; Nexus 5 " + "Build/KTU84P) AppleWebKit/537.36 (KHTML, " + "like Gecko) Chrome/56.0.2924.87" + "Mobile Safari/537.36", "Mozilla/5.0 (compatible; Googlebot/2.1; " + "+http://www.google.com/bot.html)" ] if custom_user_agent_list is not None: agents = custom_user_agent_list chosen_agent = random.choice(agents) return(chosen_agent) def requester(self, link, proxy=None, proxy_cred=None, proxy_list=None, custom_user_agent=None, cookie=None, host_header=None, http_headers=None, random_user_agent=False, custom_user_agent_list=None, timeout=None, notext=False, enable_debug=False): if timeout is None: timeout = self.timeout # Use default timeout. try: if custom_user_agent is not None: user_agent = custom_user_agent else: if ((random_user_agent is True) or (custom_user_agent_list is not None)): user_agent = self.ua_handler( use_random_agent=random_user_agent, custom_user_agent_list=custom_user_agent_list) else: # Use BFAC default UA. user_agent = self.ua_handler(use_random_agent=False) headers = {'User-Agent': user_agent, 'Accept': '*/*'} if cookie is not None: cookie_dict = {'Cookie': str(cookie)} headers.update(cookie_dict) if host_header is not None: host_dict = {'Host': str(host_header)} headers.update(host_dict) if http_headers is not None: for _ in http_headers: headers.update(_) if (proxy is not None) or (proxy_list is not None): if proxy: proxy_dict = self.proxy_handler(link, proxy=proxy, proxy_cred=proxy_cred) if proxy_list: proxy_dict = self.proxy_handler(link, proxy_cred=proxy_cred, proxy_list=proxy_list) # Establishing request with proxy. req = requests.get(link, headers=headers, verify=False, allow_redirects=False, timeout=int(timeout), proxies=proxy_dict) if proxy is None: # Establishing request without proxy. req = requests.get(link, headers=headers, verify=False, allow_redirects=False, timeout=int(timeout)) request_response_code = req.status_code request_response_content_length = len(req.content) return(request_response_code, request_response_content_length) except requests.exceptions.SSLError as e: exception_handler('SSL Error at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) except requests.exceptions.ConnectionError as e: exception_handler('Connection Error at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) except requests.exceptions.MissingSchema as e: exception_handler('Error: Invalid URL' + ' - Missing Schema at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) except requests.exceptions.InvalidSchema as e: exception_handler('Error: Invalid URL' + ' - Invalid Schema at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) except requests.exceptions.InvalidURL as e: exception_handler('Error: Invalid URL at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) except requests.exceptions.ReadTimeout as e: exception_handler('Error: Connection Timeout at ' + str(link), str(e), notext=notext, enable_debug=enable_debug) return(None, None) def initial_request(self, link, force_initial_content_length=None, forced_initial_content_length=None, proxy=None, proxy_cred=None, proxy_list=None, custom_user_agent=None, custom_user_agent_list=None, cookie=None, host_header=None, http_headers=None, random_user_agent=False, timeout=None, notext=False, enable_debug=False): """ Performs initial request and gives a baseline, based on it, the detection for content-length will be done. if force_initial_content_length is set, it will force their values as a result. # Returns (None, None) if their is an error. """ if ((force_initial_content_length is True) and (forced_initial_content_length is not None)): expected_status_code = 200 return(expected_status_code, forced_initial_content_length) # Obtain site and file_dir via url_handler() site = url_handler(link)["site"] file_dir = url_handler(link)["file_dir"] random_ascii_charset = 'abcdefghijklmnopqrstuvwxyz0123456789' random_value = \ ''.join(random.choice(random_ascii_charset) for _ in range(5)) random_value_ext = \ ''.join(random.choice(random_ascii_charset) for _ in range(3)) link = site + file_dir + random_value + '.' + random_value_ext # Using Requester API resp = self.requester( link, proxy=proxy, proxy_cred=proxy_cred, proxy_list=proxy_list, custom_user_agent=custom_user_agent, cookie=cookie, host_header=host_header, http_headers=http_headers, random_user_agent=random_user_agent, custom_user_agent_list=custom_user_agent_list, timeout=timeout, notext=notext, enable_debug=enable_debug) initial_status_code = resp[0] initial_content_length = resp[1] return(initial_status_code, initial_content_length) def url_clean(url): """ Cleans-up a URL. """ url = url.split('?')[0] url = url.replace('#', '%23') url = url.replace(' ', '%20') return(url) def url_handler(url): """ Parses a URL, and returns output of URL structure. """ # Assuming URL is: http://example.com/uploads/test.php # Cleaning url url = url_clean(url) # Scheme: http default_protocol = 'http' if ('://' not in url): url = str(default_protocol) + str('://') + str(url) scheme = urlparse.urlparse(url).scheme # Domain: example.com domain = urlparse.urlparse(url).netloc # Site: http://example.com site = scheme + '://' + domain # FilePath: /uploads/test.php file_path = urlparse.urlparse(url).path if (file_path == ''): file_path = '/' # Filename: test.php try: filename = url.split('/')[-1] except IndexError: filename = '' # File Dir: /uploads/ file_dir = file_path.rstrip(filename) if (file_dir == ''): file_dir = '/' # FullPath: http://example.com/uploads/ full_path = site + file_dir # File Extension: php try: filename_ext = filename.split('.') filename_ext.pop(0) filename_ext = '.'.join(filename_ext) except IndexError: filename_ext = '' # File without Extension: test try: filename_without_ext = filename.split('.')[0] except IndexError: filename_without_ext = '' output = {"scheme": scheme, "domain": domain, "site": site, "file_path": file_path, "filename": filename, "file_dir": file_dir, "full_path": full_path, "filename_ext": filename_ext, "filename_without_ext": filename_without_ext} return(output) def generate_bfa_urls(url, testing_level=5, dvcs_test=False): """ Generates BFA testing URLs. Returns a list of BFA testing URLs of given URL. """ url_parsed = url_handler(url) (scheme, domain, site, file_path, filename, file_dir, full_path, filename_ext, filename_without_ext) = (url_parsed["scheme"], url_parsed["domain"], url_parsed["site"], url_parsed["file_path"], url_parsed["filename"], url_parsed["file_dir"], url_parsed["full_path"], url_parsed["filename_ext"], url_parsed["filename_without_ext"]) # LEVEL 1 backup_testing_level1 = [ site + file_path + '~', site + file_path + '%23', site + file_path + '.save', site + file_path + '.swp', site + file_path + '.swo', full_path + '%23' + filename + '%23', site + file_path + '.bak' ] # LEVEL 2 backup_testing_level2 = [ site + file_path + '1', site + file_path + 'bak', site + file_path + 'inc', site + file_path + 'old', site + file_path + '_', site + file_path + '~~', site + file_path + '_backup', site + file_path + '_bak', site + file_path + '-bak', site + file_path + '.bk', site + file_path + '.bkp', full_path + filename + '.bac', site + file_path + '.old', site + file_path + '_old', site + file_path + '.copy', site + file_path + '.original', site + file_path + '.orig', site + file_path + '.org', site + file_path + '.txt', site + file_path + '.default', full_path + filename + '.tpl', full_path + filename + '.tmp', full_path + filename + '.temp', full_path + '.' + filename + ".swp", full_path + '.' + filename + ".swo", full_path + '_' + filename + '.swp', full_path + '_' + filename + '.swo', full_path + filename + '.sav', full_path + filename + '.conf', full_path + filename_without_ext + '%20%28copy%29.' + filename_ext, full_path + 'Copy%20of%20' + filename, full_path + 'copy%20of%20' + filename, full_path + 'Copy_' + filename, full_path + 'Copy%20' + filename, full_path + 'Copy_of_' + filename, full_path + 'Copy_(1)_of_' + filename, full_path + 'Copy_(2)_of_' + filename, full_path + filename_without_ext + '%20-%20Copy.' + filename_ext, full_path + filename_without_ext + '%20copy.' + filename_ext ] # LEVEL 3 backup_testing_level3 = [ full_path + filename_without_ext + '.txt', full_path + filename_without_ext + '.backup', full_path + filename_without_ext + '.bak', full_path + filename_without_ext + '.bak1', full_path + filename_without_ext + '.bakup', full_path + filename_without_ext + '.bakup1', full_path + filename_without_ext + '.bkp', full_path + filename_without_ext + '.save', full_path + filename_without_ext + '.old', full_path + filename_without_ext + '.orig', full_path + filename_without_ext + '.original', full_path + filename_without_ext + '.sql', full_path + filename_without_ext + '.war', full_path + filename_without_ext + '.wim', full_path + filename_without_ext + '.xz', site + file_path + '%00', site + file_path + '%01', full_path + '~' + filename, full_path + filename_without_ext + '.tpl', full_path + filename_without_ext + '.tmp', full_path + filename_without_ext + '.temp', full_path + filename + '.saved', full_path + filename + '.back', full_path + filename + '.backup', full_path + filename + '.bck', full_path + filename + '.bakup', full_path + filename_without_ext + '.saved', full_path + filename_without_ext + '.bac', full_path + filename_without_ext + '.back', full_path + filename_without_ext + '.bck', full_path + filename_without_ext + '.bakup', full_path + '_' + filename, full_path + '%20' + filename, full_path + filename + '.nsx', full_path + filename + '.cs', full_path + filename + '.csproj', full_path + filename + '.vb', full_path + filename + '.0', full_path + filename + '.1', full_path + filename + '.2', full_path + filename + '.7z', full_path + filename + '.ar', full_path + filename + '.arc', full_path + filename + '.bz2', full_path + filename + '.cbz', full_path + filename + '.ear', full_path + filename + '.exe', full_path + filename + '.gz', full_path + filename + '.inc', full_path + filename + '.jar', full_path + filename + '.lst', full_path + filename + '.lzma', full_path + filename + '.war', full_path + filename + '.wim', full_path + filename + '.xz', full_path + '.~lock.' + filename + '%23', full_path + '.~' + filename, full_path + '~%24' + filename, full_path + filename_without_ext + '.1', full_path + filename_without_ext + '.7z', full_path + filename_without_ext + '.ar', full_path + filename_without_ext + '.bz2', full_path + filename_without_ext + '.cbz', full_path + filename_without_ext + '.ear', full_path + filename_without_ext + '.exe', full_path + filename_without_ext + '.gz', full_path + filename_without_ext + '.inc', full_path + filename_without_ext + '.include', full_path + filename_without_ext + '.jar', full_path + filename_without_ext + '.lzma', ] # LEVEL 4 backup_testing_level4 = [ site + file_path + '.tar', site + file_path + '.rar', site + file_path + '.zip', full_path + '~' + filename_without_ext + '.tmp', site + file_path + '.tar.7z', site + file_path + '.tar.bz2', site + file_path + '.tar.gz', site + file_path + '.tar.lzma', site + file_path + '.tar.xz', full_path + 'backup-' + filename, full_path + 'backup_' + filename, full_path + 'bak-' + filename, full_path + 'bak_' + filename, full_path + filename_without_ext + '-backup.' + filename_ext, full_path + filename_without_ext + '-bkp.' + filename_ext, full_path + filename_without_ext + '.tar', full_path + filename_without_ext + '.rar', full_path + filename_without_ext + '.zip', full_path + filename_without_ext + '.tar.7z', full_path + filename_without_ext + '.tar.bz2', full_path + filename_without_ext + '.tar.gz', full_path + filename_without_ext + '.tar.lzma', full_path + filename_without_ext + '.tar.xz', full_path + filename_without_ext + '.sql.gz', full_path + filename_without_ext + '.bak.sql', full_path + filename_without_ext + '.bak.sql.gz', full_path + filename_without_ext + '.bak.sql.bz2', full_path + filename_without_ext + '.bak.sql.tar.gz', site + file_path + '.', # CVE-2017-12616 site + file_path + '::$DATA', # CVE-2017-12616 full_path + filename_without_ext + '1', full_path + filename_without_ext + '1.' + filename_ext, full_path + filename_without_ext + '_backup', full_path + filename_without_ext + '_backup' + filename_ext, full_path + filename_without_ext + '_bak', full_path + filename_without_ext + '_bak' + filename_ext, full_path + filename_without_ext + '_old', full_path + filename_without_ext + '_old' + filename_ext, full_path + filename_without_ext + 'bak', full_path + filename_without_ext + 'inc', full_path + filename_without_ext + 'old', ] # LEVEL 5 backup_testing_level5 = [ site + '/.git/HEAD', full_path + '.git/HEAD', site + '/.git/index', full_path + '.git/index', site + '/.git/config', full_path + '.git/config', site + '/.gitignore', full_path + '.gitignore', site + '/.git-credentials', full_path + '.git-credentials', site + '/.bzr/README', full_path + '.bzr/README', site + '/.bzr/checkout/dirstate', full_path + '.bzr/checkout/dirstate', site + '/.hg/requires', full_path + '.hg/requires', site + '/.hg/store/fncache', full_path + '.hg/store/fncache', site + '/.svn/entries', full_path + '.svn/entries', site + '/.svn/all-wcprops', full_path + '.svn/all-wcprops', full_path + '.svn/wc.db', site + '/.svn/wc.db', site + '/.svnignore', full_path + '.svnignore', site + '/CVS/Entries', full_path + 'CVS/Entries', site + '/.cvsignore', full_path + '.cvsignore', site + '/.idea/misc.xml', full_path + '.idea/misc.xml', site + '/.idea/workspace.xml', full_path + '.idea/workspace.xml', site + '/.DS_Store', full_path + '.DS_Store', site + '/composer.lock', full_path + 'composer.lock' ] testing_level = str(testing_level) available_levels = ['1', '2', '3', '4', '5'] # Check is requested testing_level is within available levels. # If not within available levels, choose highest level. if (testing_level not in available_levels): testing_level = '5' if (testing_level == '1'): backup_testing_checks = backup_testing_level1 if (testing_level == '2'): backup_testing_checks = backup_testing_level1 + \ backup_testing_level2 if (testing_level == '3'): backup_testing_checks = backup_testing_level1 + \ backup_testing_level2 + \ backup_testing_level3 if (testing_level == '4'): backup_testing_checks = backup_testing_level1 + \ backup_testing_level2 + \ backup_testing_level3 + \ backup_testing_level4 if (testing_level == '5'): backup_testing_checks = backup_testing_level1 + \ backup_testing_level2 + \ backup_testing_level3 + \ backup_testing_level4 + \ backup_testing_level5 if (dvcs_test is True): backup_testing_checks = backup_testing_level5 backup_testing_checks = list(set(backup_testing_checks)) backup_testing_checks = random.sample(backup_testing_checks, len(backup_testing_checks) ) return(backup_testing_checks) class VerifyResponse: """ This class checks and verifies results of requested URLs, and verify file(s) existence. """ def calculate_valid_content_length(self, content_length, invalid_content_length_offset=50): """ Calculates expected valid content-lengths, based off the initial conducted request. Returns min and max. """ content_length = int(content_length) invalid_content_length_offset = int(invalid_content_length_offset) initial_content_length_min = \ content_length - invalid_content_length_offset initial_content_length_max = \ invalid_content_length_offset + content_length if (initial_content_length_max < 0): initial_content_length_max = 0 if (initial_content_length_min < 0): initial_content_length_min = 0 return(initial_content_length_min, initial_content_length_max) def verify_via_content_length(self, content_length, initial_content_length_min, initial_content_length_max): """ Verifies if the file exists by checking the content-length. * Returns True if the file exists. * Returns False if the file does not exist. * Returns int > 0 for exceptions. """ content_length_test = True if (content_length is None): content_length_test = False return(content_length_test) if ((initial_content_length_min is None) or (initial_content_length_max is None)): return(1) initial_content_length_max = int(initial_content_length_max) for num in range(initial_content_length_min, initial_content_length_max + 1): if (num == content_length): content_length_test = False return(content_length_test) def verify_via_status_code(self, response_status_code, valid_status_codes=[200], excluded_status_codes=[]): """ Performs checks on HTTP response status codes. * Returns True is the response is valid, and file seems to exist * Returns False if the file does not seem to exist. * Returns int > 0: if there is an issue in valid_status_codes or invalid_status_codes. """ # validating result = True if (response_status_code is None): result = False if (str(response_status_code) == str(404)): result = False return(result) for valid_status_code in valid_status_codes: if (str(response_status_code) == str(valid_status_code)): result = True break for excluded_status_code in excluded_status_codes: if (str(response_status_code) == str(excluded_status_code)): result = False break return(result) def request_check(self, use_content_length_checks=True, use_status_code_checks=True, content_length=None, initial_content_length_min=None, initial_content_length_max=None, invalid_content_length_offset=50, response_status_code=None, excluded_status_codes=[]): """ Checks whether a file exists based on the response. Returns True if the file exists. Returns False if the file does not exist. * Returns int > 0 for exceptions. """ # content-length check content_length_check_result = False # Initializing variable if (use_content_length_checks is True): if ((content_length is None) or (initial_content_length_min is None) or (initial_content_length_max is None)): return(1) # Invalid input. if (use_content_length_checks is True): content_length_check_result = self.verify_via_content_length( content_length, initial_content_length_min, initial_content_length_max) else: content_length_check_result = False # status-code check status_code_check_result = False # Initializing variable if (use_status_code_checks is True): status_code_check_result = self.verify_via_status_code( response_status_code, excluded_status_codes=excluded_status_codes) # Checking and returning result. if ((status_code_check_result is True) or (content_length_check_result is True)): request_check_result = True else: request_check_result = False return(request_check_result) def request_and_verify_response(url, use_content_length_checks=True, use_status_code_checks=True, excluded_status_codes=[], invalid_content_length_offset=50, initial_content_length_min=None, initial_content_length_max=None, proxy=None, proxy_cred=None, proxy_list=None, custom_user_agent=None, custom_user_agent_list=None, cookie=None, host_header=None, http_headers=None, random_user_agent=False, timeout=None, notext=False, findings_queue=None): """ This function uses the Request_Handler() and verify_via_status_code() classes to test a URL. and returns if the file exists or not. * Returns True: if the file exists. * Returns False: if the file does not exist. Note: This function is intended for a single URL; It only shows plain results based for a single URL and determines whether a file exists on the server or not. """ resp = RequestsHandler().requester( url, proxy=proxy, proxy_cred=proxy_cred, proxy_list=proxy_list, custom_user_agent=custom_user_agent, cookie=cookie, host_header=host_header, http_headers=http_headers, random_user_agent=random_user_agent, custom_user_agent_list=custom_user_agent_list, timeout=timeout, notext=notext) file_exists = VerifyResponse().request_check( use_content_length_checks=use_content_length_checks, use_status_code_checks=use_status_code_checks, content_length=resp[1], initial_content_length_min=initial_content_length_min, initial_content_length_max=initial_content_length_max, invalid_content_length_offset=invalid_content_length_offset, response_status_code=resp[0], excluded_status_codes=excluded_status_codes) # Remove if exists on excluded status-codes for excluded_status_code in excluded_status_codes: if str(resp[0]) == str(excluded_status_code): file_exists = False break if findings_queue is not None: if file_exists is True: output = {"url": url, "status_code": resp[0], "content_length": resp[1]} try: if url not in [_["url"] for _ in findings_queue.queue]: ConsoleOutput(notext=notext).found_message(url, resp[0], resp[1]) if notext is True: ConsoleOutput(notext=notext).found_message_notext(url) findings_queue.put(output) except RuntimeError as e: exception_handler('Error: RuntimeError at (%s)' % (url), str(e), enable_debug=True, notext=False) return(file_exists, resp) class OutputResults: """ Responsible for saving results in an external file. """ def __init__(self, notext=False, enable_debug=True): self.notext = notext self.enable_debug = enable_debug def save_in_simple_txt(self, findings_list, txt_file): """ Save results in plain text file. Save only URLs. """ try: output = open(txt_file, 'a') for url in [_["url"] for _ in findings_list]: output.write(url + "\n") output.close() except IOError as e: exception_handler('Error: IOError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) except TypeError as e: exception_handler('Error: TypeError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) return(0) def save_in_verbose_txt(self, findings_list, txt_file): """ Save results in plain text file. Save: URLs, Status-Code, Content-Length. """ try: output = open(txt_file, 'a') for _ in findings_list: url = _["url"] status_code = _["status_code"] content_length = _["content_length"] output_data = '[URL]: %s' % (str(url)) + \ ' | ' + \ '[Status-Code]: %s' % (str(status_code)) + \ ' | ' + \ '[Content-Length]: ' + \ '%s' % (str(content_length)) output.write(output_data + "\n") output.close() except IOError as e: exception_handler('Error: IOError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) except TypeError as e: exception_handler('Error: TypeError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) return(0) def save_in_json_file(self, findings_list, json_file): """ Save results in JSON file. """ try: output = open(json_file, 'a') data = str(json.dumps(list(findings_list))) output.write(data) output.close() except IOError as e: exception_handler('Error: IOError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) except TypeError as e: exception_handler('Error: TypeError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) return(0) def save_in_csv_file(self, findings_list, csv_file): """ Save results in plain text file. Save: URLs, Status-Code, Content-Length. """ try: csvfile = open(csv_file, 'a') csv_writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for _ in findings_list: csv_writer.writerow([_["url"], _["status_code"], _["content_length"]]) csvfile.close() except IOError as e: exception_handler('Error: IOError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) except TypeError as e: exception_handler('Error: TypeError', str(e), enable_debug=self.enable_debug, notext=self.notext) return(1) return(0) class ConsoleOutput: def __init__(self, notext=False): self.notext = notext def console_output_check(self): if (__name__ != '__main__'): return(1) if (self.notext is True): return(1) def erase_line(self): with threading.Lock(): if platform.system() == 'Windows': sys.stdout.write("\b" * 4096) else: sys.stdout.write('\033[1K') sys.stdout.write('\033[0G') def print_base_url(self, url, current_queue_counter=None, urls_queue_size=None): if self.console_output_check() == 1: return(1) with threading.Lock(): if urls_queue_size == 1: sys.stdout.write("\n\n%s URL: %s\n" % (symbols.info, url)) else: sys.stdout.write("\n\n%s [%s/%s] URL: %s\n" % ( symbols.info, current_queue_counter, urls_queue_size, url)) sys.stdout.flush() def testing_url_message(self, url, current_progress_percentage): if self.console_output_check() == 1: return(1) with threading.Lock(): self.erase_line() output = ('[%s] Testing:-> %s' % ( (str(current_progress_percentage) + "%"), url)) sys.stdout.write(output) sys.stdout.flush() def found_message(self, url, response_status_code, content_length): if self.console_output_check() == 1: return(1) with threading.Lock(): self.erase_line() sys.stdout.write((symbols.success + " Discovered: -> {%s}" + " (Response-Code: %s | Content-Length: %s)\n") % (url, response_status_code, content_length)) sys.stdout.flush() def found_message_notext(self, url): with threading.Lock(): sys.stdout.write("%s\n" % (url)) sys.stdout.flush() def message_with_all_findings(self, findings_list): if self.console_output_check() == 1: return(1) self.erase_line() sys.stdout.write("\n") sys.stdout.flush() print(symbols.info + '%s Findings:%s' % (colorama.Fore.CYAN, colorama.Style.RESET_ALL)) if (len(findings_list) == 0): print(symbols.info + ' No BFA was identified.') else: for _ in findings_list: if str(_["status_code"]).startswith('2'): status = colorama.Fore.GREEN elif str(_["status_code"]).startswith('3'): status = colorama.Fore.YELLOW elif str(_["status_code"]).startswith('4'): status = colorama.Fore.RED elif str(_["status_code"]).startswith('5'): status = colorama.Fore.MAGENTA else: status = "" status += '(%s)' % (str(_["status_code"])) print(_["url"] + ' %s | (Content-Length: %s)' % (status, str(_["content_length"]))) print('\n' + symbols.info + ' Finished performing scan.') def host_is_not_responding(self, url): if self.console_output_check() == 1: return(1) print(symbols.error + ' Host ' + '[%s]' % (url_handler(url)["domain"]) + ' does not seem to be responding as expected.') print(symbols.info + ' Skipping...') def test_url(url, dvcs_test=False, testing_level=5, use_content_length_checks=True, use_status_code_checks=True, excluded_status_codes=[], invalid_content_length_offset=50, force_initial_content_length=None, forced_initial_content_length=None, proxy=None, proxy_cred=None, proxy_list=None, custom_user_agent=None, custom_user_agent_list=None, cookie=None, host_header=None, http_headers=None, random_user_agent=False, timeout=None, notext=False, enable_debug=False, max_threads=10, request_rate_throttling=30, testedjar=None, findings_queue=None): """ This function performs BFA testing on a single URL. Returns a list of findings. Returns int > 0 if an exception occured. """ testedjar = queue.Queue() if not testedjar else testedjar findings_queue = queue.Queue() if not findings_queue else findings_queue current_scan_queue = queue.Queue() current_findings_queue = queue.Queue() generated_urls = generate_bfa_urls( url, testing_level=testing_level, dvcs_test=dvcs_test) for url in generated_urls: current_scan_queue.put(url) init_req = RequestsHandler().initial_request( url, force_initial_content_length=force_initial_content_length, proxy=proxy, proxy_cred=proxy_cred, proxy_list=proxy_list, custom_user_agent=custom_user_agent, cookie=cookie, host_header=host_header, http_headers=http_headers, random_user_agent=random_user_agent, custom_user_agent_list=custom_user_agent_list, timeout=timeout, notext=notext, enable_debug=enable_debug) if (None in init_req): ConsoleOutput(notext=notext).host_is_not_responding(url) return(1) init_req_content_length = init_req[1] if ((use_content_length_checks is True) and (force_initial_content_length is True)): init_req_content_length = forced_initial_content_length if use_content_length_checks is True: cl_calc = VerifyResponse().calculate_valid_content_length( init_req_content_length, invalid_content_length_offset) else: cl_calc = (0, 0) kwargs = {"use_content_length_checks": use_content_length_checks, "use_status_code_checks": use_status_code_checks, "excluded_status_codes": excluded_status_codes, "initial_content_length_min": cl_calc[0], "initial_content_length_max": cl_calc[1], "proxy": proxy, "proxy_cred": proxy_cred, "proxy_list": proxy_list, "custom_user_agent": custom_user_agent, "custom_user_agent_list": custom_user_agent_list, "cookie": cookie, "host_header": host_header, "http_headers": http_headers, "random_user_agent": random_user_agent, "timeout": timeout, "notext": notext, "findings_queue": current_findings_queue} threads_state = [] # Do request rate throttling i = queue.Queue() def counter_reset(i): while current_scan_queue.empty() is False: time.sleep(1) i.queue.clear() try: t = threading.Thread(target=counter_reset, args=(i,)) t.daemon = True t.start() threads_state.append(t) except KeyboardInterrupt: t.join() while current_scan_queue.empty() is False: if threading.active_count() < (int(max_threads) + 2): # +2 is made for the following: # - The main thread. # - A thread doing counter resetting. if len(i.queue) > request_rate_throttling: continue i.put(None) url = current_scan_queue.get() if (url in list(testedjar.queue)): continue testedjar.put(url) current_progress_percentage = round( float(float(len(generated_urls) - current_scan_queue.qsize()) / float(len(generated_urls))) * 100, 2) ConsoleOutput(notext=notext).testing_url_message( url, current_progress_percentage) t = threading.Thread(target=request_and_verify_response, args=(url,), kwargs=kwargs) t.daemon = True t.start() threads_state.append(t) else: time.sleep(0.5) for t in threads_state: t.join() current_findings = list(current_findings_queue.queue) for _ in current_findings: if _["url"] not in findings_queue.queue: findings_queue.put(_) return(current_findings) def main(): # Makes Colorama work on Windows colorama.init(autoreset=True) if ('--no-text' not in sys.argv): if (('-h' in sys.argv) or ('--help' in sys.argv) or ('-hh' in sys.argv) or (len(sys.argv) <= 1) or ('-help' in sys.argv) or ('--h' in sys.argv)): print(logo()) print(instructions()) exit(0) else: print(logo()) if ('-V' in sys.argv) or ('--version' in sys.argv): print(version()) exit(0) if ('--issue' in sys.argv): webbrowser.open('https://github.com/mazen160/bfac/issues/new') print(symbols.info + ' Opening GitHub repo.') exit(0) # Handling arguments (command-line use) parser = argparse.ArgumentParser() # Target Options parser.add_argument("-u", "--url", dest="url", help="Check a single URL.", action='store') parser.add_argument("-L", "--list", dest="usedlist", help="Check a list of URLs.", action='store') parser.add_argument("--stdin", dest="use_stdin", help="Check URLs from STDIN input.", action='store_true') # Testing Options parser.add_argument("-level", "--level", dest="testing_level", help="Set testing level [1-5]\ (default: 5).", action='store', default=5) parser.add_argument("--dvcs-test", dest="dvcs_test", help="Perform DVCS testing only,\ which is available by default on Level 5.", action='store_true') parser.add_argument("--threads", dest="max_threads", help="thread workers to use (default: 10).", action='store', default=10) parser.add_argument("--request-rate-throttling", dest="request_rate_throttling", help="request rate throttling per second\ (default: 30)", action="store", default=30) # Artifacts Detection Options parser.add_argument("--invalid-content-length", dest="invalid_content_length", help="Manually specify the invalid\ Content-Length, instead of performing\ this check automatically.", action='store') parser.add_argument("--invalid-content-length-offset", dest="invalid_content_length_offset", help="Manually specify the Content-Length\ offset for invalid pages. (default: 50)", action='store', default=50) parser.add_argument("--technique", "--detection-technique", dest="detection_technique", help="Technique to verify the availability\ of the file. (Options: status_code,\ content_length,all) (default: all)", action='store', default='all') parser.add_argument("-xsc", "--exclude-status-codes", dest="exclude_status_codes", help="Specify status codes to exclude,\ separated by commas.", action='store', default=[]) # Output-Related Options parser.add_argument("-o", "--output", dest='output_file', help="Save identified URLs into a file.", action='store') parser.add_argument("--verbose-output", dest='verbose_output_file', help="Save identified URLs, with \ status-codes and content-length into a file.", action='store') parser.add_argument("--json-output", dest='json_output', help="Save findings in JSON file.", action='store') parser.add_argument("--csv-output", dest='csv_output', help="Save findings in CSV file.", action='store') # Request-Related Options parser.add_argument("-ua", "--user-agent", dest='user_agent', help="HTTP User-Agent header value.", action='store') parser.add_argument("-ra", "--random-agent", "--random-agents", dest='random_agent', help="Use random User-Agents.", action='store_true') parser.add_argument("--user-agents-file", dest="custom_ua_file", help="Use a User-Agents file.", action='store') parser.add_argument("--cookie", dest='cookie', help="HTTP Cookie header value.", action='store') parser.add_argument("--host", dest='host', help="HTTP Host header value.", action='store') parser.add_argument("--headers", dest='headers', help="Extra headers\ (e.g. \"Accept-Language: fr\\n\ ETag: 123\")", action='store') parser.add_argument("--proxy", dest='proxy', help="Use a proxy\ on testing.", action='store') parser.add_argument("--proxy-cred", dest='proxy_cred', help="Proxy authentication credentials\ (name:password).", action='store') parser.add_argument("--proxy-file", dest='proxy_list_file', help="Use a proxy list file.", action='store') parser.add_argument("--timeout", dest='timeout', help="HTTP Request timeout by seconds.\ (default: 5)", action='store', default=5) # Other Options parser.add_argument("--no-text", dest='notext', help="Print and write a clean output\ with results ony.", action='store_true') parser.add_argument("--debug", dest='enable_debug', help="Enable debugging.", action='store_true', default=False) parser.add_argument("--issue", dest='report_issue', help="Report an issue on GitHub.", action='store_true') parser.add_argument("-V", "--version", dest='show_version', help="Show current version and exit.", action='store_true') args = parser.parse_args() # Handling input from argparse (Command-line use). url = args.url if args.url else None usedlist = args.usedlist if args.usedlist else None use_stdin = args.use_stdin if args.use_stdin else None testing_level = args.testing_level if args.testing_level else None dvcs_test = args.dvcs_test if args.dvcs_test else None max_threads = int(args.max_threads) if args.max_threads else None # Used if-statements on multiple lines to not break PEP8-E501 if args.request_rate_throttling: request_rate_throttling = int(args.request_rate_throttling) else: request_rate_throttling = None if args.invalid_content_length: invalid_content_length = args.invalid_content_length else: invalid_content_length = None if args.invalid_content_length_offset: invalid_content_length_offset = args.invalid_content_length_offset else: invalid_content_length_offset = None if args.detection_technique: detection_technique = args.detection_technique else: detection_technique = None if args.exclude_status_codes: exclude_status_codes = args.exclude_status_codes else: exclude_status_codes = None output_file = args.output_file if args.output_file else None if args.verbose_output_file: verbose_output_file = args.verbose_output_file else: verbose_output_file = None json_output = args.json_output if args.json_output else None csv_output = args.csv_output if args.csv_output else None user_agent = args.user_agent if args.user_agent else None random_agent = args.random_agent if args.random_agent else None if args.custom_ua_file: custom_ua_file = args.custom_ua_file else: custom_ua_file = None cookie = args.cookie if args.cookie else None headers = args.headers if args.headers else None proxy = args.proxy if args.proxy else None proxy_cred = args.proxy_cred if args.proxy_cred else None proxy_list_file = args.proxy_list_file if args.proxy_list_file else None host = args.host if args.host else None timeout = args.timeout if args.timeout else None notext = args.notext if args.notext else None enable_debug = args.enable_debug if args.enable_debug else False # Check if URL or List Input is used. if (url is None) and (usedlist is None) and (use_stdin is None): e = symbols.error + \ ' Error: Either a URL or a List should be supplied.' print(str(e)) print('\nExiting...') exit(1) # Check if requested level is not within levels available_levels = ['1', '2', '3', '4', '5'] if (str(testing_level) not in available_levels): e = symbols.error + ' Error: Chosen level is invalid.' print(str(e)) print('\nExiting...') exit(1) # Check Verify File Availability input: detection_techniques = ['status_code', 'content_length', 'all'] if (detection_technique not in detection_techniques): e = symbols.error + \ ' Error: Entered Verify File Availability option is invalid.' print(str(e)) print('\nExiting...') exit(1) # Initializing output file, # and checking if we have write access to file. if (output_file): try: open(output_file, 'a').close() except Exception as e: print(symbols.error + ' Error: There is an error in writing output.') exception_handler('Error: ', str(e)) print('\nExiting...') exit(1) if (verbose_output_file): try: open(verbose_output_file, 'a').close() except Exception as e: print(symbols.error + ' Error: There is an error in writing output.') exception_handler('Error: ', str(e)) print('\nExiting...') exit(1) if (json_output): try: open(json_output, 'a').close() except Exception as e: print(symbols.error + ' Error: There is an error in writing output.') exception_handler('Error: ', str(e)) print('\nExiting...') exit(1) if (csv_output): try: open(csv_output, 'a').close() except Exception as e: print(symbols.error + ' Error: There is an error in writing output.') exception_handler('Error: ', str(e)) print('\nExiting...') exit(1) # Parse status_codes if (isinstance(exclude_status_codes, str) is True): exclude_status_codes = exclude_status_codes.replace(' ', '') exclude_status_codes = exclude_status_codes.split(',') # Checking and validating excluded status-codes input. if ((exclude_status_codes is None) or (exclude_status_codes == '')): exclude_status_codes = [] for exclude_status_code in exclude_status_codes: if str.isdigit(str(exclude_status_code)) is False: e = symbols.error + \ ' Error: Invalid provided excluded status code.' print(str(e)) exit(1) if (detection_technique == 'all'): use_status_code_checks = True use_content_length_checks = True if (detection_technique == 'content_length'): use_status_code_checks = False use_content_length_checks = True if (detection_technique == 'status_code'): use_status_code_checks = True use_content_length_checks = False if (invalid_content_length is not None): force_initial_content_length = True forced_initial_content_length = invalid_content_length else: force_initial_content_length = False forced_initial_content_length = None if custom_ua_file: try: ua_list = open(custom_ua_file, "r").readlines() except Exception as e: print(symbols.error + " Error reading user-agents file.") exception_handler('Error: ', str(e)) exit(1) ua_list = [_.replace("\r", "").replace("\n", "") for _ in ua_list] custom_user_agent_list = ua_list del ua_list else: custom_user_agent_list = None if proxy_list_file: try: proxy_list = open(proxy_list_file, "r").read().replace("\r", "") proxy_list = proxy_list.split("\n") except Exception as e: print(symbols.error + " Error reading proxy-list file.") exception_handler('Error: ', str(e)) exit(1) else: proxy_list = None http_headers_list = [] if headers: extra_headers_handler = headers.replace('\r', '') headers_list = extra_headers_handler.split('\\n') for _ in headers_list: if (len(_.split(':')) != 2): pass else: header = _.split(':')[0] header_value = _.split(':')[1] header_value = list(header_value) # Need to check if first element is \x20 # because of an error shown when requesting. if (header_value[0] == ' '): header_value[0] = '' header_value = ''.join(header_value) add_header = {str(header): str(header_value)} http_headers_list.append(add_header) URLs_list = [] if url: URLs_list.append(url) if (usedlist): try: f_open = open(usedlist, 'r').readlines() except Exception as e: message = symbols.error + ' Unable to use list [%s].' % (usedlist) exception_handler(message, str(e)) print('\nExiting...') exit(1) for _ in f_open: _ = _.replace('\r', '').replace('\n', '') URLs_list.append(_) if (use_stdin): stdin_input = sys.stdin.readlines() for _ in stdin_input: _ = _.replace('\r', '').replace('\n', '') URLs_list.append(_) URLs_list = list(set(URLs_list)) testedjar = queue.Queue() findings_queue = queue.Queue() for url in enumerate(URLs_list): ConsoleOutput(notext=notext).print_base_url( url[1], current_queue_counter=(url[0] + 1), urls_queue_size=len(URLs_list)) test_url( url[1], dvcs_test=dvcs_test, testing_level=testing_level, use_content_length_checks=use_content_length_checks, use_status_code_checks=use_status_code_checks, excluded_status_codes=exclude_status_codes, invalid_content_length_offset=invalid_content_length_offset, force_initial_content_length=force_initial_content_length, forced_initial_content_length=forced_initial_content_length, proxy=proxy, proxy_cred=proxy_cred, proxy_list=proxy_list, custom_user_agent=user_agent, custom_user_agent_list=custom_user_agent_list, cookie=cookie, host_header=host, http_headers=http_headers_list, random_user_agent=random_agent, timeout=timeout, notext=notext, enable_debug=enable_debug, max_threads=max_threads, request_rate_throttling=request_rate_throttling, testedjar=testedjar, findings_queue=findings_queue) if (output_file): OutputResults(notext=notext).save_in_simple_txt(findings_queue.queue, output_file) if (verbose_output_file): OutputResults(notext=notext).save_in_verbose_txt(findings_queue.queue, verbose_output_file) if (json_output): OutputResults(notext=notext).save_in_json_file(findings_queue.queue, json_output) if (csv_output): OutputResults(notext=notext).save_in_csv_file(findings_queue.queue, csv_output) ConsoleOutput(notext=notext).message_with_all_findings( findings_queue.queue ) if (__name__ == '__main__'): try: main() except KeyboardInterrupt: print('\n' + symbols.info + ' KeyboardInterrupt Detected.') print('\nExiting...') os._exit(1) # *** END *** # ================================================ FILE: requirements.txt ================================================ colorama requests requests[socks] ================================================ FILE: setup.py ================================================ #!/usr/bin/env python3 # coding=utf-8 # ******************************************************************* # *** BFAC: Backup File Artifacts Checker *** # * Homepage: # https://github.com/mazen160/bfac # * setup.py: # BFAC setup script # * Author: # Mazin Ahmed # ******************************************************************* from setuptools import setup, find_packages setup( name='bfac', packages=find_packages(), version='1.4', scripts=['bfac'], description="Advanced Backup-File Artifacts Testing for Web-Applications", long_description="An automated tool that checks for backup artifacts " + "that may disclose the web-application's" + " source code.", author='Mazin Ahmed', author_email='mazin@mazinahmed.net', url='https://github.com/mazen160/bfac', keywords=['backup', 'artifacts', 'checker', 'web scanner', 'web vulnerability scanner', 'bfac'], install_requires=['colorama', 'requests', 'requests[socks]'], license='GPL-3.0' )