Repository: Lazza/RecuperaBit Branch: master Commit: 535710c98229 Files: 14 Total size: 132.3 KB Directory structure: gitextract_1tjjzxzi/ ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── main.py └── recuperabit/ ├── __init__.py ├── fs/ │ ├── __init__.py │ ├── constants.py │ ├── core_types.py │ ├── ntfs.py │ └── ntfs_fmt.py ├── logic.py └── utils.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ ko_fi: thelazza ================================================ FILE: .gitignore ================================================ ### Code ### .vscode/* !.vscode/tasks.json !.vscode/launch.json *.code-workspace ### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ pytestdebug.log # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ doc/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ pythonenv* # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # profiling data .prof ================================================ FILE: LICENSE ================================================ 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. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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: {project} Copyright (C) {year} {fullname} 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 ================================================ # ![RecuperaBit](http://i.imgur.com/Q6mM385.jpg)

GPL-3.0 license Latest release Stars counter Stadium badge Donate on Ko-fi

A software which attempts to reconstruct file system structures and recover files. Currently it supports only NTFS. RecuperaBit attempts reconstruction of the directory structure regardless of: - missing partition table - unknown partition boundaries - partially-overwritten metadata - quick format You can get more information about **the reconstruction algorithms** and the architecture used in RecuperaBit by reading [my MSc thesis](https://www.scribd.com/doc/309337813/) or checking out [the slides](http://www.slideshare.net/TheLazza/recuperabit-forensic-file-system-reconstruction-given-partially-corrupted-metadata). ## Usage usage: main.py [-h] [-s SAVEFILE] [-w] [-o OUTPUTDIR] path Reconstruct the directory structure of possibly damaged filesystems. positional arguments: path path to the disk image optional arguments: -h, --help show this help message and exit -s SAVEFILE, --savefile SAVEFILE path of the scan save file -w, --overwrite force overwrite of the save file -o OUTPUTDIR, --outputdir OUTPUTDIR directory for restored contents and output files The main argument is the `path` to a bitstream image of a disk or partition. RecuperaBit automatically determines the sectors from which partitions start. RecuperaBit does not modify the disk image, however it does read some parts of it multiple times through the execution. It should also work on real devices, such as `/dev/sda` but **this is not advised** for damaged drives. RecuperaBit might worsen the situation by "stressing" a damaged drive or it could crash due to an I/O error. Optionally, a save file can be specified with `-s`. The first time, after the scanning process, results are saved in the file. After the first run, the file is read to only analyze interesting sectors and speed up the loading phase. Overwriting the save file can be forced with `-w`. RecuperaBit includes a small command line that allows the user to recover files and export the contents of a partition in CSV or [body file](http://wiki.sleuthkit.org/index.php?title=Body_file) format. These are exported in the directory specified by `-o` (or `recuperabit_output`). ### Limitation Currently RecuperaBit does not work with compressed files on an NTFS filesystem. If you have deep knowledge of the inner workings of file compression on NTFS filesystem, your help would be much appreciated, as available documentation is quite sparse on the topic. ### Pypy RecuperaBit can be run with the standard cPython implementation, however speed can be increased by using it with the Pypy interpreter and JIT compiler: pypy3 main.py /path/to/disk.img ### Recovery of File Contents Files can be restored one at a time or recursively, starting from a directory. After the scanning process has completed, you can check the list of partitions that can be recovered by issuing the following command at the prompt: recoverable Each line shows information about a partition. Let's consider the following output example: Partition #0 -> Partition (NTFS, 15.00 MB, 11 files, Recoverable, Offset: 2048, Offset (b): 1048576, Sec/Clus: 8, MFT offset: 2080, MFT mirror offset: 17400) If you want to recover files starting from a specific directory, you can either print the tree on screen with the `tree` command (very verbose for large drives) or you can export a CSV list of files (see `help` for details). If you rather want to extract all files from the *Root* and the *Lost Files* nodes, you need to know the identifier for the root directory, depending on the file system type. The following are those of file systems supported by RecuperaBit: | File System Type | Root Id | |------------------|---------| | NTFS | 5 | The id for *Lost Files* is -1 **for every file system.** Therefore, to restore `Partition #0` in our example, you need to run: restore 0 5 restore 0 -1 The files will be saved inside the output directory specified by `-o`. ## License This software is released under the GNU GPLv3. See `LICENSE` for more details. ================================================ FILE: __init__.py ================================================ ================================================ FILE: main.py ================================================ #!/usr/bin/env python3 """Main RecuperaBit process.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . import argparse import codecs import itertools import locale import logging import os.path import pickle import sys try: import readline readline # ignore unused import warning except ImportError: pass from recuperabit import logic, utils # scanners from recuperabit.fs.ntfs import NTFSScanner from typing import TYPE_CHECKING if TYPE_CHECKING: from recuperabit.fs.core_types import Partition __author__ = "Andrea Lazzarotto" __copyright__ = "(c) 2014-2021, Andrea Lazzarotto" __license__ = "GPLv3" __version__ = "1.1.6" __maintainer__ = "Andrea Lazzarotto" __email__ = "andrea.lazzarotto@gmail.com" # classes of available scanners plugins = ( NTFSScanner, ) commands = ( ('help', 'Print this help message'), ('recoverable', 'List recoverable partitions'), ('recoverable_size ', 'List recoverable partitions based on the minimum '), ('other', 'List unrecoverable partitions'), ('allparts', 'List all partitions'), ('tree ', 'Show contents of partition (tree)'), ('csv ', 'Save a CSV representation in a file'), ('bodyfile ', 'Save a body file representation in a file'), ('tikzplot []', 'Produce LaTeX code to draw a Tikz figure'), ('restore ', 'Recursively restore files from '), ('locate ', 'Print all file paths that match a string'), ('traceback ', 'Print ids and paths for all ancestors of '), ('merge ', 'Merge the two partitions into the first one'), ('quit', 'Close the program') ) rebuilt = set() def list_parts(parts, shorthands, test): """List partitions corresponding to test.""" for i, part in shorthands: if test(parts[part]): print('Partition #' + str(i), '->', parts[part]) def check_valid_part(num, parts, shorthands, rebuild=True): """Check if the required partition is valid.""" try: i = int(num) except ValueError: print('Value is not valid!') return None if i in range(len(shorthands)): i, par = shorthands[i] part = parts[par] if rebuild and par not in rebuilt: print('Rebuilding partition...') part.rebuild() rebuilt.add(par) print('Done') return part print('No partition with given ID!') return None def interpret(cmd, arguments, parts: dict[int, 'Partition'], shorthands, outdir): """Perform command required by user.""" if cmd == 'help': print('Available commands:') for name, desc in commands: print(' %s%s' % (name.ljust(28), desc)) elif cmd == 'tree': if len(arguments) != 1: print('Wrong number of parameters!') else: part = check_valid_part(arguments[0], parts, shorthands) if part is not None: print('-'*10) print(utils.tree_folder(part.root)) print(utils.tree_folder(part.lost)) print('-'*10) elif cmd == 'bodyfile': if len(arguments) != 2: print('Wrong number of parameters!') else: part = check_valid_part(arguments[0], parts, shorthands) if part is not None: contents = [ '# ---' + repr(part) + '---', '# Full paths' ] + utils.bodyfile_folder(part.root) + [ '# \n# Orphaned files' ] + utils.bodyfile_folder(part.lost) fname = os.path.join(outdir, arguments[1]) try: with codecs.open(fname, 'w', encoding='utf8') as outfile: outfile.write('\n'.join(contents)) print('Saved body file to %s' % fname) except IOError: print('Cannot open file %s for output!' % fname) elif cmd == 'csv': if len(arguments) != 2: print('Wrong number of parameters!') else: part = check_valid_part(arguments[0], parts, shorthands) if part is not None: contents = utils.csv_part(part) fname = os.path.join(outdir, arguments[1]) try: with codecs.open(fname, 'w', encoding='utf8') as outfile: outfile.write( '\n'.join(contents) ) print('Saved CSV file to %s' % fname) except IOError: print('Cannot open file %s for output!' % fname) elif cmd == 'tikzplot': if len(arguments) not in (1, 2): print('Wrong number of parameters!') else: part = check_valid_part(arguments[0], parts, shorthands) if part is not None: if len(arguments) > 1: fname = os.path.join(outdir, arguments[1]) try: with codecs.open(fname, 'w') as outfile: outfile.write(utils.tikz_part(part) + '\n') print('Saved Tikz code to %s' % fname) except IOError: print('Cannot open file %s for output!' % fname) else: print(utils.tikz_part(part)) elif cmd == 'restore': if len(arguments) != 2: print('Wrong number of parameters!') else: partid = arguments[0] part = check_valid_part(partid, parts, shorthands) if part is not None: index = arguments[1] partition_dir = os.path.join(outdir, 'Partition' + str(partid)) myfile = None try: indexi = int(index) except ValueError: indexi = index for i in [index, indexi]: myfile = part.get(i, myfile) if myfile is None: print('The index is not valid') else: logic.recursive_restore(myfile, part, partition_dir) elif cmd == 'locate': if len(arguments) != 2: print('Wrong number of parameters!') else: part = check_valid_part(arguments[0], parts, shorthands) if part is not None: text = arguments[1] results = utils.locate(part, text) for node, path in results: desc = ( ' [GHOST]' if node.is_ghost else ' [DELETED]' if node.is_deleted else '' ) print('[%s]: %s%s' % (node.index, path, desc)) elif cmd == 'traceback': if len(arguments) != 2: print('Wrong number of parameters!') else: partid = arguments[0] part = check_valid_part(partid, parts, shorthands) if part is not None: index = arguments[1] myfile = None try: indexi = int(index) except ValueError: indexi = index for i in [index, indexi]: myfile = part.get(i, myfile) if myfile is None: print('The index is not valid') else: while myfile is not None: print('[{}] {}'.format(myfile.index, myfile.full_path(part))) myfile = part.get(myfile.parent) elif cmd == 'merge': if len(arguments) != 2: print('Wrong number of parameters!') else: part1 = check_valid_part(arguments[0], parts, shorthands, rebuild=False) part2 = check_valid_part(arguments[1], parts, shorthands, rebuild=False) if None in (part1, part2): return if part1.fs_type != part2.fs_type: print('Cannot merge partitions with types (%s, %s)' % (part1.fs_type, part2.fs_type)) return print('Merging partitions...') utils.merge(part1, part2) source_position = int(arguments[1]) destination_position = int(arguments[0]) _, par_source = shorthands[source_position] _, par_destination = shorthands[destination_position] del shorthands[source_position] del parts[par_source] for par in (par_source, par_destination): try: rebuilt.remove(par) except: pass print('There are now %d partitions.' % (len(parts), )) elif cmd == 'recoverable': list_parts(parts, shorthands, lambda x: x.recoverable) elif cmd == 'recoverable_size': if len(arguments) != 1: print('Wrong number of parameters!') else: list_parts(parts, shorthands, lambda x: x.size is not None and x.size > int(arguments[0])) elif cmd == 'other': list_parts(parts, shorthands, lambda x: not x.recoverable) elif cmd == 'allparts': list_parts(parts, shorthands, lambda x: True) elif cmd == 'quit': exit(0) else: print('Unknown command.') def main(): """Wrap the program logic inside a function.""" logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) print(r" ___ ___ _ _ ") print(r" | _ \___ __ _ _ _ __ ___ _ _ __ _| _ |_) |_ ") print(r" | / -_) _| || | '_ \/ -_) '_/ _` | _ \ | _|") print(r" |_|_\___\__|\_,_| .__/\___|_| \__,_|___/_|\__|") print(" |_| v{}".format(__version__)) print(' ', __copyright__, '<%s>' % __email__) print(' Released under the', __license__) print('') parser = argparse.ArgumentParser( description='Reconstruct the directory structure of possibly damaged ' 'filesystems.' ) parser.add_argument('path', type=str, help='path to the disk image') parser.add_argument( '-s', '--savefile', type=str, help='path of the scan save file' ) parser.add_argument( '-w', '--overwrite', action='store_true', help='force overwrite of the save file' ) parser.add_argument( '-o', '--outputdir', type=str, help='directory for restored contents' ' and output files' ) args = parser.parse_args() try: image = open(args.path, 'rb') except IOError: logging.error('Unable to open image file!') exit(1) read_results = False write_results = False # Set output directory if args.outputdir is None: logging.info('No output directory specified, defaulting to ' 'recuperabit_output') args.outputdir = 'recuperabit_output' # Try to reload information from the savefile if args.savefile is not None: if args.overwrite: logging.info('Results will be saved to %s', args.savefile) write_results = True else: logging.info('Checking if results already exist.') try: savefile = open(args.savefile, 'rb') logging.info('Results will be read from %s', args.savefile) read_results = True except IOError: logging.info('Unable to open save file.') logging.info('Results will be saved to %s', args.savefile) write_results = True if read_results: logging.info('The save file exists. Trying to read it...') try: indexes = pickle.load(savefile) savefile.close() except IndexError: logging.error('Malformed save file!') exit(1) else: indexes = itertools.count() # Ask for confirmation before beginning the process try: confirm = input('Type [Enter] to start the analysis or ' '"exit" / "quit" / "q" to quit: ') except EOFError: print('') exit(0) if confirm in ('exit', 'quit', 'q'): exit(0) # Create the output directory if not logic.makedirs(args.outputdir): logging.error('Cannot create output directory!') exit(1) scanners = [pl(image) for pl in plugins] logging.info('Analysis started! This is going to take time...') interesting = utils.feed_all(image, scanners, indexes) logging.info('First scan completed') if write_results: logging.info('Saving results to %s', args.savefile) with open(args.savefile, 'wb') as savefile: pickle.dump(interesting, savefile) # Ask for partitions parts: dict[int, 'Partition'] = {} for scanner in scanners: parts.update(scanner.get_partitions()) shorthands = list(enumerate(parts)) logging.info('%i partitions found.', len(parts)) while True: print('\nWrite command ("help" for details):') try: command = input('> ').split(' ') except (EOFError, KeyboardInterrupt): print('') exit(0) cmd = command[0] arguments = command[1:] interpret(cmd, arguments, parts, shorthands, args.outputdir) if __name__ == '__main__': main() ================================================ FILE: recuperabit/__init__.py ================================================ # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . ================================================ FILE: recuperabit/fs/__init__.py ================================================ # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . ================================================ FILE: recuperabit/fs/constants.py ================================================ """Information needed by multiple plugins.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . sector_size: int = 512 max_sectors: int = 256 # Maximum block size for recovery ================================================ FILE: recuperabit/fs/core_types.py ================================================ """Recuperabit Core Types. This module contains the class declarations of all objects which are used in the Recuperabit meta file system. Each plug-in is supposed to extend the File and DiskScanner classes with subclasses implementing the missing methods.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . import logging import os.path from typing import Optional, Dict, Set, List, Tuple, Union, Any, Iterator from datetime import datetime from .constants import sector_size from ..utils import readable_bytes class File(object): """Filesystem-independent representation of a file. Aka Node.""" def __init__(self, index: Union[int, str], name: str, size: Optional[int], is_directory: bool = False, is_deleted: bool = False, is_ghost: bool = False) -> None: self.index: Union[int, str] = index self.name: str = name self.size: Optional[int] = size self.is_directory: bool = is_directory self.is_deleted: bool = is_deleted self.is_ghost: bool = is_ghost self.parent: Optional[Union[int, str]] = None self.mac: Dict[str, Optional[datetime]] = { 'modification': None, 'access': None, 'creation': None } self.children: Set['File'] = set() self.children_names: Set[str] = set() # Avoid name clashes breaking restore self.offset: Optional[int] = None # Offset from beginning of disk def set_parent(self, parent: Optional[Union[int, str]]) -> None: """Set a pointer to the parent directory.""" self.parent = parent def set_mac(self, modification: Optional[datetime], access: Optional[datetime], creation: Optional[datetime]) -> None: """Set the modification, access and creation times.""" self.mac['modification'] = modification self.mac['access'] = access self.mac['creation'] = creation def get_mac(self) -> List[Optional[datetime]]: """Get the modification, access and creation times.""" keys = ('modification', 'access', 'creation') return [self.mac[k] for k in keys] def set_offset(self, offset: Optional[int]) -> None: """Set the offset of the file record with respect to the disk image.""" self.offset = offset def get_offset(self) -> Optional[int]: """Get the offset of the file record with respect to the disk image.""" return self.offset def add_child(self, node: 'File') -> None: """Add a new child to this directory.""" original_name = node.name i = 0 # Check for multiple rebuilds if node in self.children: return # Avoid name clashes while node.name in self.children_names: node.name = original_name + '_%03d' % i i += 1 if node.name != original_name: logging.warning(u'Renamed {} from {}'.format(node, original_name)) self.children.add(node) self.children_names.add(node.name) def full_path(self, part: 'Partition') -> str: """Return the full path of this file.""" if self.parent is not None: parent = part[self.parent] return os.path.join(parent.full_path(part), self.name) else: return self.name def get_content(self, partition: 'Partition') -> Optional[Union[bytes, Iterator[bytes]]]: # pylint: disable=W0613 """Extract the content of the file. This method is intentionally not implemented because it depends on each plug-in for a specific file system.""" if self.is_directory or self.is_ghost: return None raise NotImplementedError # pylint: disable=R0201 def ignore(self) -> bool: """The following method is used by the restore procedure to check files that should not be recovered. For example, in NTFS file $BadClus:$Bad shall not be recovered because it creates an output with the same size as the partition (usually many GBs).""" return False def __repr__(self) -> str: return ( u'File(#%s, ^^%s^^, %s, offset = %s sectors)' % (self.index, self.parent, self.name, self.offset) ) class Partition(object): """Simplified representation of the contents of a partition. Parameter root_id represents the identifier assigned to the root directory of a partition. This can be file system dependent.""" def __init__(self, fs_type: str, root_id: Union[int, str], scanner: 'DiskScanner') -> None: self.fs_type: str = fs_type self.root_id: Union[int, str] = root_id self.size: Optional[int] = None self.offset: Optional[int] = None self.root: Optional[File] = None self.lost: File = File(-1, 'LostFiles', 0, is_directory=True, is_ghost=True) self.files: Dict[Union[int, str], File] = {} self.recoverable: bool = False self.scanner: 'DiskScanner' = scanner def add_file(self, node: File) -> None: """Insert a new file in the partition.""" index = node.index self.files[index] = node def set_root(self, node: File) -> None: """Set the root directory.""" if not node.is_directory: raise TypeError('Not a directory') self.root = node self.root.set_parent(None) def set_size(self, size: int) -> None: """Set the (estimated) size of the partition.""" self.size = size def set_offset(self, offset: int) -> None: """Set the offset from the beginning of the disk.""" self.offset = offset def set_recoverable(self, recoverable: bool) -> None: """State if the partition contents are also recoverable.""" self.recoverable = recoverable def rebuild(self) -> None: """Rebuild the partition structure. This method processes the contents of files and it rebuilds the directory tree as accurately as possible.""" root_id = self.root_id rootname = 'Root' if root_id not in self.files: self.files[root_id] = File( root_id, rootname, 0, is_directory=True, is_ghost=True ) # Convert keys to list to avoid RuntimeError for identifier in list(self.files): node = self.files[identifier] if node.index == root_id: self.set_root(node) node.name = rootname else: parent_id = node.parent exists = parent_id is not None valid = parent_id in self.files if exists and valid: parent_node = self.files[parent_id] elif exists and not valid: parent_node = File(parent_id, 'Dir_' + str(parent_id), 0, is_directory=True, is_ghost=True) parent_node.set_parent(-1) self.files[parent_id] = parent_node self.lost.add_child(parent_node) else: parent_node = self.lost node.set_parent(-1) parent_node.add_child(node) return # pylint: disable=R0201 def additional_repr(self) -> List[Tuple[str, Any]]: """Return additional values to show in the string representation.""" return [] def __repr__(self) -> str: size = ( readable_bytes(self.size * sector_size) if self.size is not None else '??? b' ) data = [ ('Offset', self.offset), ( 'Offset (b)', self.offset * sector_size if self.offset is not None else None ), ] data += self.additional_repr() return u'Partition (%s, %s, %d files,%s %s)' % ( self.fs_type, size, len(self.files), ' Recoverable,' if self.recoverable else '', ', '.join(a+': '+str(b) for a, b in data) ) def __getitem__(self, index: Union[int, str]) -> File: if index in self.files: return self.files[index] if index == self.lost.index: return self.lost raise KeyError def get(self, index: Union[int, str], default: Optional[File] = None) -> Optional[File]: """Get a file or the special LostFiles directory.""" try: return self.__getitem__(index) except KeyError: return default class DiskScanner(object): """Abstract stub for the implementation of disk scanners.""" def __init__(self, pointer: Any) -> None: self.image: Any = pointer def get_image(self) -> Any: """Return the image reference.""" return self.image @staticmethod def get_image(scanner: 'DiskScanner') -> Any: """Static method to get image from scanner instance.""" return scanner.image def feed(self, index: int, sector: bytes) -> Optional[str]: """Feed a new sector.""" raise NotImplementedError def get_partitions(self) -> Dict[int, Partition]: """Get a list of the found partitions.""" raise NotImplementedError ================================================ FILE: recuperabit/fs/ntfs.py ================================================ """NTFS plug-in. This plug-in contains the necessary logic to parse traces of NTFS file systems, including MFT entries and directory indexes.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . import logging from collections import Counter from typing import Any, Dict, List, Optional, Tuple, Union, Iterator, Set from .constants import max_sectors, sector_size from .core_types import DiskScanner, File, Partition from .ntfs_fmt import (attr_header_fmt, attr_names, attr_nonresident_fmt, attr_resident_fmt, attr_types_fmt, attribute_list_parser, boot_sector_fmt, entry_fmt, indx_dir_entry_fmt, indx_fmt, indx_header_fmt) from ..logic import SparseList, approximate_matching from ..utils import merge, sectors, unpack # Some attributes may appear multiple times multiple_attributes: Set[str] = set([ '$FILE_NAME', '$DATA', '$INDEX_ROOT', '$INDEX_ALLOCATION', '$BITMAP' ]) # Size of records in sectors FILE_size: int = 2 INDX_size: int = 8 def best_name(entries: List[Tuple[int, str]]) -> Optional[str]: """Return the best file name available. This function accepts a list of tuples formed by a namespace and a string. In case of more than one choice, it returns preferrably the one in the NTFS namespace (code == 3).""" if len(entries) == 0: return None entries.sort() if entries[-1][0] == 3: name = entries[-1][1] else: name = entries[0][1] return name if len(name) else None def parse_mft_attr(attr: bytes) -> Tuple[Dict[str, Any], Optional[str]]: """Parse the contents of a MFT attribute.""" header = unpack(attr, attr_header_fmt) attr_type = header['type'] if attr_type not in attr_names: return header, None if header['non_resident']: nonresident = unpack(attr, attr_nonresident_fmt) if nonresident['runlist'] is None: nonresident['runlist'] = list() header.update(nonresident) else: resident = unpack(attr, attr_resident_fmt) header.update(resident) offset = header['content_off'] content = attr[offset:] name = attr_names[attr_type] if not header['non_resident'] and name in attr_types_fmt: size = header['content_size'] data = unpack(content[:size], attr_types_fmt[name]) header['content'] = data return header, name def _apply_fixup_values(header: Dict[str, Any], entry: bytearray) -> None: """Apply the fixup values to FILE and INDX records.""" offset = header['off_fixup'] for i in range(1, header['n_entries']): pos = sector_size * i entry[pos-2:pos] = entry[offset + 2*i:offset + 2*(i+1)] def _attributes_reader(entry: bytes, offset: int) -> Dict[str, Any]: """Read every attribute.""" attributes = {} while offset < len(entry) - 16: try: attr, name = parse_mft_attr(entry[offset:]) except TypeError: # The attribute was broken, we need to terminate here return attributes attr['dump_offset'] = offset if attr['length'] == 0: # End of attribute list break else: offset = offset + attr['length'] if name is None: # Skip broken/unknown attribute continue if name not in attributes: if name not in multiple_attributes: attributes[name] = attr else: attributes[name] = [attr] else: if name in multiple_attributes: attributes[name].append(attr) else: logging.error('Cannot handle multiple attribute %s', name) return attributes def parse_file_record(entry: bytes) -> Dict[str, Any]: """Parse the contents of a FILE record (MFT entry).""" header = unpack(entry, entry_fmt) if (header['size_alloc'] is None or header['size_alloc'] > len(entry) or len(entry) < FILE_size*sector_size): header['valid'] = False return header # Old versions of NTFS don't have a MFT record number. if header['off_fixup'] < 48: header['record_n'] = None _apply_fixup_values(header, entry) attributes = _attributes_reader(entry, header['off_first']) header['valid'] = True header['attributes'] = attributes return header def parse_indx_record(entry: bytes) -> Dict[str, Any]: """Parse the contents of a INDX record (directory index).""" header = unpack(entry, indx_fmt) _apply_fixup_values(header, entry) node_data = unpack(entry[24:], indx_header_fmt) node_data['off_start_list'] += 24 node_data['off_end_list'] += 24 node_data['off_end_buffer'] += 24 header.update(node_data) offset = header['off_start_list'] entries = [] while offset < header['off_end_list']: entry_data = unpack(entry[offset:], indx_dir_entry_fmt) if entry_data['content_length']: try: file_name = unpack( entry[offset + 16:], attr_types_fmt['$FILE_NAME'] ) except (UnicodeDecodeError, TypeError): # Invalid file name or invalid name length break # Perform checks to avoid false positives name_ok = file_name['name'] is not None namespace_ok = 0 <= file_name['namespace'] <= 3 size_ok = file_name['real_size'] <= file_name['allocated_size'] features_ok = not ( file_name['flags'] == 0 and file_name['parent_seq'] > 1024 ) if name_ok and namespace_ok and size_ok and features_ok: entry_data['file_info'] = file_name entries.append(entry_data) else: break if entry_data['entry_length']: offset += entry_data['entry_length'] else: break header['entries'] = entries header['valid'] = len(entries) > 0 return header def _integrate_attribute_list(parsed: Dict[str, Any], part: 'NTFSPartition', image: Any) -> None: """Integrate missing attributes in the parsed MTF entry.""" base_record = parsed['record_n'] attrs = parsed['attributes'] attr = attrs['$ATTRIBUTE_LIST'] spc = part.sec_per_clus if 'runlist' in attr: clusters_pos = 0 entries = [] size = attr['real_size'] for entry in attr['runlist']: clusters_pos += entry['offset'] length = min(entry['length'] * spc * sector_size, size) size -= length real_pos = clusters_pos * spc + part.offset dump = sectors(image, real_pos, length, 1) entries += attribute_list_parser(dump) attr['content'] = {'entries': entries} else: entries = attr['content']['entries'] # Divide entries by type types = set(e['type'] for e in entries) entries_by_type = { t: set( e['file_ref'] for e in entries if e['type'] == t and e['file_ref'] is not None ) for t in types } # Remove completely "local" types or empty lists for num in list(entries_by_type): files = entries_by_type[num] if ( len(files) == 0 or (len(files) == 1 and next(iter(files)) == base_record) ): del entries_by_type[num] mft_pos = part.mft_pos for num in entries_by_type: # Read contents of child entries for index in entries_by_type[num]: real_pos = mft_pos + index * FILE_size dump = sectors(image, real_pos, FILE_size) child_parsed = parse_file_record(dump) if 'attributes' not in child_parsed: continue # Update the main entry (parsed) if child_parsed['base_record'] == base_record: child_attrs = child_parsed['attributes'] for name in child_attrs: if name in multiple_attributes: try: attrs[name] += child_attrs[name] except KeyError: attrs[name] = child_attrs[name] else: attrs[name] = child_attrs[name] class NTFSFile(File): """NTFS File.""" def __init__(self, parsed: Dict[str, Any], offset: Optional[int], is_ghost: bool = False, ads: str = '') -> None: index = parsed['record_n'] ads_suffix = ':' + ads if ads != '' else ads if ads != '': index = str(index) + ads_suffix attrs = parsed['attributes'] filenames = attrs['$FILE_NAME'] datas = attrs.get('$DATA', []) size = None for attr in datas: if attr['name'] == ads: if 'real_size' in attr: size = attr['real_size'] elif not attr['non_resident']: size = attr['content_size'] break filtered = [ f for f in filenames if 'content' in f and f['content'] is not None and 'name_length' in f['content'] and f['content']['name_length'] > 0 and f['content']['name'] is not None ] name = best_name([ (f['content']['namespace'], f['content']['name'] + ads_suffix) for f in filtered ]) hasname = name is not None if not hasname: name = 'File_%s' % index std_info = attrs.get('$STANDARD_INFORMATION') is_dir = (parsed['flags'] & 0x02) > 0 and not len(ads) is_del = (parsed['flags'] & 0x01) == 0 File.__init__(self, index, name, size, is_dir, is_del, is_ghost) time_attribute = None # Additional attributes if hasname: first = filtered[0]['content'] parent_id = first['parent_entry'] File.set_parent(self, parent_id) File.set_offset(self, offset) time_attribute = std_info or filtered[0] if time_attribute and 'content' in time_attribute: File.set_mac( self, time_attribute['content']['modification_time'], time_attribute['content']['access_time'], time_attribute['content']['creation_time'], ) self.ads = ads @staticmethod def _padded_bytes(image: Any, offset: int, size: int) -> bytes: dump = sectors(image, offset, size, 1) if len(dump) < size: logging.warning( 'Failed to read byte(s). Padding with 0x00. Offset: {} Size: ' '{}'.format(offset, size)) dump += bytearray(b'\x00' * (size - len(dump))) return dump def content_iterator(self, partition: 'NTFSPartition', image: Any, datas: List[Dict[str, Any]]) -> Iterator[bytes]: """Return an iterator for the contents of this file.""" vcn = 0 spc = partition.sec_per_clus for attr in datas: diff = attr['start_VCN'] - vcn if diff > 0: # We do not try to fill with zeroes as this might produce huge useless files logging.warning( u'Missing part for {} expected VCN {}, ' u'got start_VCN={} ({} clusters skipped). '.format( self, vcn, attr['start_VCN'], diff, ) ) vcn += diff yield b'' elif diff < 0: # VCN went backwards: overlap, out-of-order, or cross-stream contamination logging.warning( u'$DATA attribute VCN overlap for {}. ' u'expected VCN {}, got start_VCN={}. ' u'This may indicate attribute filtering error or MFT corruption.'.format( self, vcn, attr['start_VCN'] ) ) clusters_pos = 0 size = attr['real_size'] if 'runlist' not in attr: logging.error( u'Cannot restore {}, missing runlist'.format(self) ) break for entry in attr['runlist']: length = min(entry['length'] * spc * sector_size, size) size -= length # Sparse runlist if entry['offset'] is None: while length > 0: amount = min(max_sectors*sector_size, length) length -= amount yield b'\x00' * amount continue # Normal runlists clusters_pos += entry['offset'] real_pos = clusters_pos * spc + partition.offset # Avoid to fill memory with huge blocks offset = 0 while length > 0: amount = min(max_sectors*sector_size, length) position = real_pos*sector_size + offset partial = self._padded_bytes(image, position, amount) length -= amount offset += amount yield bytes(partial) vcn = attr['end_VCN'] + 1 def get_content(self, partition: 'NTFSPartition') -> Optional[Union[bytes, Iterator[bytes]]]: """Extract the content of the file. This method works by extracting the $DATA attribute.""" if self.is_ghost: logging.error(u'Cannot restore ghost file {}'.format(self)) return None image = DiskScanner.get_image(partition.scanner) dump = sectors(image, File.get_offset(self), FILE_size) parsed = parse_file_record(dump) if not parsed['valid'] or 'attributes' not in parsed: logging.error(u'Invalid MFT entry for {}'.format(self)) return None attrs = parsed['attributes'] if ('$ATTRIBUTE_LIST' in attrs and partition.sec_per_clus is not None): _integrate_attribute_list(parsed, partition, image) if '$DATA' not in attrs: attrs['$DATA'] = [] datas = [d for d in attrs['$DATA'] if d['name'] == self.ads] if not len(datas): if not self.is_directory: logging.error(u'Cannot restore $DATA attribute(s) ' 'for {}'.format(self)) return None # TODO implemented compressed attributes for d in datas: if d['flags'] & 0x01: logging.error(u'Cannot restore compressed $DATA attribute(s) ' 'for {}'.format(self)) return None elif d['flags'] & 0x4000: logging.warning(u'Found encrypted $DATA attribute(s) ' 'for {}'.format(self)) # Handle resident file content if len(datas) == 1 and not datas[0]['non_resident']: single = datas[0] start = single['dump_offset'] + single['content_off'] end = start + single['content_size'] content = dump[start:end] return bytes(content) else: if partition.sec_per_clus is None: logging.error(u'Cannot restore non-resident $DATA ' 'attribute(s) for {}'.format(self)) return None non_resident = sorted( (d for d in datas if d['non_resident']), key=lambda x: x['start_VCN'] ) if len(non_resident) != len(datas): logging.warning( u'Found leftover resident $DATA attributes for ' '{}. Only those non-resident parts will be restored.'.format(self) ) return self.content_iterator(partition, image, non_resident) def ignore(self) -> bool: """Determine which files should be ignored.""" return ( (self.index == '8:$Bad') or (self.parent == 11 and self.ads == '$J') # $UsnJrnl ) class NTFSPartition(Partition): """Partition with additional fields for NTFS recovery.""" def __init__(self, scanner: 'NTFSScanner', position: Optional[int] = None) -> None: Partition.__init__(self, 'NTFS', 5, scanner) self.sec_per_clus: Optional[int] = None self.mft_pos: Optional[int] = position self.mftmirr_pos: Optional[int] = None def additional_repr(self) -> List[Tuple[str, Any]]: """Return additional values to show in the string representation.""" return [ ('Sec/Clus', self.sec_per_clus), ('MFT offset', self.mft_pos), ('MFT mirror offset', self.mftmirr_pos) ] class NTFSScanner(DiskScanner): """NTFS Disk Scanner.""" def __init__(self, pointer: Any) -> None: DiskScanner.__init__(self, pointer) self.found_file: Set[int] = set() self.parsed_file_review: Dict[int, Dict[str, Any]] = {} self.found_indx: Set[int] = set() self.parsed_indx: Dict[int, Dict[str, Any]] = {} self.indx_list: Optional[SparseList[int]] = None self.found_boot: List[int] = [] self.found_spc: List[int] = [] def feed(self, index: int, sector: bytes) -> Optional[str]: """Feed a new sector.""" # check boot sector if sector.endswith(b'\x55\xAA') and b'NTFS' in sector[:8]: self.found_boot.append(index) return 'NTFS boot sector' # check file record if sector.startswith((b'FILE', b'BAAD')): self.found_file.add(index) return 'NTFS file record' # check index record if sector.startswith(b'INDX'): self.found_indx.add(index) return 'NTFS index record' @staticmethod def add_indx_entries(entries: List[Dict[str, Any]], part: NTFSPartition) -> None: """Insert new ghost files which were not already found.""" for rec in entries: if (rec['record_n'] not in part.files and rec['$FILE_NAME'] is not None): # Compatibility with the structure of a MFT entry rec['attributes'] = { '$FILE_NAME': [{'content': rec['$FILE_NAME']}] } """Although the structure of r is similar to that of a MFT entry, flags were about the index, not about the file. We don't know if the element is a directory or not, hence we mark it as a file. It can be deduced if it is a directory by looking at the number of children, after the reconstruction.""" rec['flags'] = 0x1 part.add_file(NTFSFile(rec, None, is_ghost=True)) def add_from_indx_root(self, parsed: Dict[str, Any], part: NTFSPartition) -> None: """Add ghost entries to part from INDEX_ROOT attributes in parsed.""" for attribute in parsed['attributes']['$INDEX_ROOT']: if (attribute.get('content') is None or attribute['content'].get('records') is None): continue self.add_indx_entries(attribute['content']['records'], part) def most_likely_sec_per_clus(self) -> List[int]: """Determine the most likely value of sec_per_clus of each partition, to speed up the search.""" counter = Counter() counter.update(self.found_spc) counter.update(2**i for i in range(8)) return [i for i, _ in counter.most_common()] def find_boundary(self, part: NTFSPartition, mft_address: int, multipliers: List[int]) -> Tuple[Optional[int], Optional[int]]: """Determine the starting sector of a partition with INDX records.""" nodes = ( self.parsed_file_review[node.offset] for node in part.files.values() if node.offset in self.parsed_file_review and '$INDEX_ALLOCATION' in self.parsed_file_review[node.offset]['attributes'] ) text_list = self.indx_list width = text_list.__len__() base_pattern = {} for parsed in nodes: for attr in parsed['attributes']['$INDEX_ALLOCATION']: clusters_pos = 0 if 'runlist' not in attr: continue runlist = attr['runlist'] for entry in runlist: clusters_pos += entry['offset'] base_pattern[clusters_pos] = parsed['record_n'] if not len(base_pattern): return (None, None) results = [] min_support = 2 for sec_per_clus in multipliers: pattern = { i * sec_per_clus: base_pattern[i] for i in base_pattern } delta = min(pattern) normalized = { i-delta: pattern[i] for i in pattern if i-delta <= width # Avoid extremely long, useless patterns } if len(normalized) < min_support: continue pattern_list = SparseList(normalized) solution = approximate_matching( text_list, pattern_list, mft_address + delta, k=min_support ) if solution is not None: # Avoid negative offsets and ambiguous situations solution[0] = [i-delta for i in solution[0] if i-delta >= 0] if len(solution[0]) == 1: positions, amount, perc = solution results.append((positions, perc, sec_per_clus)) # Reasonably, this is a correct match if perc > 0.25 and amount > 256: break min_support = max(min_support, solution[1]) if len(results): results.sort(key=lambda r: r[1]) positions, _, spc = results[0] return (positions[0], spc) else: return (None, None) def add_from_indx_allocation(self, parsed: Dict[str, Any], part: NTFSPartition) -> None: """Add ghost entries to part from INDEX_ALLOCATION attributes in parsed. This procedure requires that the beginning of the partition has already been discovered.""" read_again = set() for attr in parsed['attributes']['$INDEX_ALLOCATION']: clusters_pos = 0 if 'runlist' not in attr: continue runlist = attr['runlist'] for entry in runlist: clusters_pos += entry['offset'] real_pos = clusters_pos * part.sec_per_clus + part.offset if real_pos in self.parsed_indx: content = self.parsed_indx[real_pos] # Check if the entry matches if parsed['record_n'] == content['parent']: discovered = set( c for c in content['children'] if c not in part.files ) # If there are new files, read the INDX again if len(discovered): read_again.add(real_pos) img = DiskScanner.get_image(self) for position in read_again: dump = sectors(img, position, INDX_size) entries = parse_indx_record(dump)['entries'] self.add_indx_entries(entries, part) def add_from_attribute_list(self, parsed: Dict[str, Any], part: NTFSPartition, offset: int) -> None: """Add additional entries to part from attributes in ATTRIBUTE_LIST. Files with many attributes may have additional attributes not in the MFT entry. When this happens, it is necessary to find the other attributes. They may contain additional information, such as $DATA attributes for ADS. This procedure requires that the beginning of the partition has already been discovered.""" image = DiskScanner.get_image(self) _integrate_attribute_list(parsed, part, image) attrs = parsed['attributes'] if '$DATA' in attrs: for attribute in attrs['$DATA']: ads_name = attribute['name'] if ads_name and len(ads_name): part.add_file(NTFSFile(parsed, offset, ads=ads_name)) def add_from_mft_mirror(self, part: NTFSPartition) -> None: """Fix the first file records using the MFT mirror.""" img = DiskScanner.get_image(self) mirrpos = part.mftmirr_pos if mirrpos is None: return for i in range(4): node = part.get(i) if node is None or node.is_ghost: position = mirrpos + i * FILE_size dump = sectors(img, position, FILE_size) parsed = parse_file_record(dump) if parsed['valid'] and '$FILE_NAME' in parsed['attributes']: node = NTFSFile(parsed, position) part.add_file(node) logging.info( u'Repaired MFT entry #%s - %s in partition at offset ' '%s from backup', node.index, node.name, part.offset ) def finalize_reconstruction(self, part: NTFSPartition) -> None: """Finish information gathering from a file. This procedure requires that the beginning of the partition has already been discovered.""" logging.info('Adding extra attributes from $ATTRIBUTE_LIST') # Select elements with many attributes many_attributes_it = ( node for node in list(part.files.values()) if node.offset in self.parsed_file_review and '$ATTRIBUTE_LIST' in self.parsed_file_review[node.offset]['attributes'] ) for node in many_attributes_it: parsed = self.parsed_file_review[node.offset] self.add_from_attribute_list(parsed, part, node.offset) logging.info('Adding ghost entries from $INDEX_ALLOCATION') # Select only elements with $INDEX_ALLOCATION allocation_it = ( node for node in list(part.files.values()) if node.offset in self.parsed_file_review and '$INDEX_ALLOCATION' in self.parsed_file_review[node.offset]['attributes'] ) for node in allocation_it: parsed = self.parsed_file_review[node.offset] self.add_from_indx_allocation(parsed, part) def get_partitions(self) -> Dict[int, NTFSPartition]: """Get a list of the found partitions.""" partitioned_files: Dict[int, NTFSPartition] = {} img = DiskScanner.get_image(self) logging.info('Parsing MFT entries') for position in self.found_file: dump = sectors(img, position, FILE_size) parsed = parse_file_record(dump) attrs = parsed.get('attributes', {}) if not parsed['valid'] or '$FILE_NAME' not in attrs: continue # Partition files based on corresponding entry 0 if parsed['record_n'] is not None: offset = position - parsed['record_n'] * FILE_size try: part = partitioned_files[offset] except KeyError: partitioned_files[offset] = NTFSPartition(self, offset) part = partitioned_files[offset] attributes = parsed['attributes'] if '$DATA' in attributes: for attribute in attributes['$DATA']: ads_name = attribute['name'] if ads_name: part.add_file(NTFSFile(parsed, position, ads=ads_name)) """Add the file again, just in case the $DATA attributes are missing.""" part.add_file(NTFSFile(parsed, position)) # Handle information deduced from INDX records if '$INDEX_ROOT' in attrs: self.add_from_indx_root(parsed, part) # Save for later use if '$INDEX_ALLOCATION' in attrs or '$ATTRIBUTE_LIST' in attrs: self.parsed_file_review[position] = parsed # TODO [Future] handle files for which there is no record_number # Parse INDX records logging.info('Parsing INDX records') for position in self.found_indx: dump = sectors(img, position, INDX_size) parsed = parse_indx_record(dump) if not parsed['valid']: continue entries = parsed['entries'] referred = (el['file_info']['parent_entry'] for el in entries) record_n = Counter(referred).most_common(1)[0][0] # Save references for future access self.parsed_indx[position] = { 'parent': record_n, 'children': set(el['record_n'] for el in entries) } indx_info = self.parsed_indx self.indx_list = SparseList({ pos: indx_info[pos]['parent'] for pos in indx_info }) # Extract boot record information logging.info('Reading boot sectors') for index in self.found_boot: dump = sectors(img, index, 1) parsed = unpack(dump, boot_sector_fmt) sec_per_clus = parsed['sectors_per_cluster'] self.found_spc.append(sec_per_clus) relative = parsed['MFT_addr'] * sec_per_clus mirr_relative = parsed['MFTmirr_addr'] * sec_per_clus part = None # Look for matching partition, either as boot sector or backup for delta in (0, parsed['sectors']): index = index - delta address = relative + index # Set partition as recoverable if address in partitioned_files: part = partitioned_files[address] part.set_recoverable(True) part.set_size(parsed['sectors']) part.offset = index part.sec_per_clus = sec_per_clus part.mftmirr_pos = mirr_relative + index break # Repair MFT if the mirror is available for address in list(partitioned_files): # This could have been deleted in a previous iteration if address not in partitioned_files: continue part = partitioned_files[address] mirrpos = part.mftmirr_pos if mirrpos is None: entry = part.get(1) # $MFTMirr if entry is None: continue else: # Infer MFT mirror position dump = sectors(img, entry.offset, FILE_size) mirror = parse_file_record(dump) if (mirror['valid'] and 'attributes' in mirror and '$DATA' in mirror['attributes']): datas = mirror['attributes']['$DATA'] if (len(datas) == 1 and datas[0]['non_resident'] and 'runlist' in datas[0] and len(datas[0]['runlist']) > 0 and 'offset' in datas[0]['runlist'][0]): relative = datas[0]['runlist'][0]['offset'] spc = part.sec_per_clus if spc is None: continue mirrpos = relative * spc + part.offset part.mftmirr_pos = mirrpos self.add_from_mft_mirror(part) # Remove bogus partitions generated by MFT mirrors if mirrpos in partitioned_files: bogus = partitioned_files[mirrpos] # Check if it looks like a MFT mirror if len(bogus.files) == 4 and max(bogus.files) < 4: logging.debug( 'Dropping bogus NTFS partition with MFT ' 'position %d generated by MFT mirror of ' 'partition at offset %d', bogus.mft_pos, part.offset ) partitioned_files.pop(mirrpos) # Acquire additional information from $INDEX_ALLOCATION logging.info('Finding partition geometry') most_likely = self.most_likely_sec_per_clus() for address in partitioned_files: part = partitioned_files[address] if part.offset is None: # Find geometry by approximate string matching offset, sec_per_clus = self.find_boundary( part, address, most_likely ) if offset is not None: part.set_recoverable(True) part.offset = offset part.sec_per_clus = sec_per_clus else: offset, sec_per_clus = part.offset, part.sec_per_clus if offset is not None: logging.info( 'Finalizing MFT reconstruction of partition at offset %i', offset ) self.finalize_reconstruction(part) # Merge pieces from fragmented MFT for address in list(partitioned_files): # This could have been deleted in a previous iteration if address not in partitioned_files: continue part = partitioned_files[address] entry = part.get(0) # $MFT if entry is None or part.sec_per_clus is None: continue dump = sectors(img, entry.offset, FILE_size) parsed = parse_file_record(dump) if not parsed['valid'] or 'attributes' not in parsed: continue if '$ATTRIBUTE_LIST' in parsed['attributes']: _integrate_attribute_list(parsed, part, img) attrs = parsed['attributes'] if '$DATA' not in attrs or len(attrs['$DATA']) < 1: continue if 'runlist' not in attrs['$DATA'][0]: continue runlist = attrs['$DATA'][0]['runlist'] if len(runlist) > 1: logging.info( 'MFT for partition at offset %d is fragmented. Trying to ' 'merge %d parts...', part.offset, len(runlist) ) clusters_pos = runlist[0]['offset'] spc = part.sec_per_clus size = runlist[0]['length'] for entry in runlist[1:]: clusters_pos += entry['offset'] real_pos = clusters_pos * part.sec_per_clus + part.offset position = real_pos - size*spc if position in partitioned_files: piece = partitioned_files[position] if piece.offset is None or piece.offset == part.offset: conflicts = [ i for i in piece.files if not piece.files[i].is_ghost and i in part.files and not part.files[i].is_ghost ] if not len(conflicts): logging.debug( 'Merging partition with MFT offset %d into' ' %s (fragmented MFT)', piece.mft_pos, part ) # Merge the partitions merge(part, piece) # Remove the fragment partitioned_files.pop(position) else: logging.debug( 'NOT merging partition with MFT offset %d into' ' %s (possible fragmented MFT) due to conflicts', piece.mft_pos, part ) size += entry['length'] return partitioned_files ================================================ FILE: recuperabit/fs/ntfs_fmt.py ================================================ """NTFS format descriptors.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . from datetime import datetime, timezone, timedelta from ..utils import printable, unpack time_start = datetime(1601, 1, 1, tzinfo=timezone.utc) def printable_name(name): """Return a printable name decoded in UTF-16.""" decoded = [] parts = (name[i:i+2] for i in range(0, len(name), 2)) for part in parts: try: decoded.append(part.decode('utf-16')) except UnicodeDecodeError: decoded.append('\x00') joined = ''.join(decoded) # basic check for false positives if '\x00\x00\x00' in joined: return None return printable(joined, '#') def windows_time(timestamp): """Convert a date-time value from Microsoft filetime to UTC.""" try: value = int.from_bytes(timestamp, byteorder='little', signed=False) converted = time_start + timedelta(milliseconds = value//10000) return converted except (ValueError, OverflowError, OSError): return None def index_entries(dump): """Interpret the entries of an index.""" offset = 0 entries = [] while offset < len(dump): parsed = unpack(dump[offset:], indx_dir_entry_fmt) filename = parsed['$FILE_NAME'] entry_length = parsed['entry_length'] valid_length = entry_length > 0 has_name = 'name' in filename valid_name = has_name and len(filename['name']) > 0 if valid_length and valid_name: if parsed['content_length']: entries.append(parsed) offset += entry_length else: break # Last entry if parsed['flags'] & 0x2: break # TODO handle carving of remnant entries in slack space return entries def index_root_parser(dump): """Parse the entries contained in a $INDEX_ROOT attribute.""" header = unpack(dump, indx_header_fmt) offset = header['off_start_list'] entries = index_entries(dump[offset:]) return entries def runlist_unpack(runlist): """Parse an attribute runlist.""" pieces = [] while len(runlist) and runlist[0] != 0: off_bytes, len_bytes = divmod(runlist[0], 2**4) end = len_bytes + off_bytes decoded = unpack(runlist, [ ('length', ('i', 1, len_bytes)), ('offset', ('+i', len_bytes + 1, end)) ]) if decoded['length'] is None or decoded['offset'] is None: break pieces.append(decoded) runlist = runlist[end+1:] return pieces def attribute_list_parser(dump): """Parse entries contained in a $ATTRIBUTE_LIST attribute.""" content = [] while len(dump): decoded = unpack(dump, [ ('type', ('i', 0, 3)), ('length', ('i', 4, 5)), ('name_length', ('i', 6, 6)), ('name_off', ('i', 7, 7)), ('start_VCN', ('i', 8, 15)), ('file_ref', ('i', 16, 19)), ('id', ('i', 24, 24)) ]) length = decoded['length'] # Check either if the length is 0 or if it is None if not length: break content.append(decoded) dump = dump[length:] return content def try_filename(dump): """Try to parse a $FILE_NAME attribute.""" try: unpack(dump, attr_types_fmt['$FILE_NAME']) except TypeError: # Broken attribute return {} entry_fmt = [ ('signature', ('s', 0, 3)), ('off_fixup', ('i', 4, 5)), ('n_entries', ('i', 6, 7)), ('LSN', ('i', 8, 15)), ('seq_val', ('i', 16, 17)), ('link_count', ('i', 18, 19)), ('off_first', ('i', 20, 21)), ('flags', ('i', 22, 23)), ('size_used', ('i', 24, 27)), ('size_alloc', ('i', 28, 31)), ('base_record', ('i', 32, 35)), ('record_n', ('i', 44, 47)) # Available only for NTFS >= 3.1 ] boot_sector_fmt = [ ('OEM_name', ('s', 3, 10)), ('bytes_per_sector', ('i', 11, 12)), ('sectors_per_cluster', ('i', 13, 13)), ('sectors', ('i', 40, 47)), ('MFT_addr', ('i', 48, 55)), ('MFTmirr_addr', ('i', 56, 63)), ('MFT_entry_size', ('i', 64, 64)), ('idx_size', ('i', 68, 68)), ('signature', ('s', 510, 511)) ] indx_fmt = [ ('signature', ('s', 0, 3)), ('off_fixup', ('i', 4, 5)), ('n_entries', ('i', 6, 7)), ('LSN', ('i', 8, 15)), ('seq_val', ('i', 16, 17)) ] indx_header_fmt = [ ('off_start_list', ('i', 0, 3)), ('off_end_list', ('i', 4, 7)), ('off_end_buffer', ('i', 8, 11)), ('flags', ('i', 12, 15)) ] indx_dir_entry_fmt = [ ('record_n', ('i', 0, 3)), ('entry_length', ('i', 8, 9)), ('content_length', ('i', 10, 11)), ('flags', ('i', 12, 15)), ('$FILE_NAME', ( try_filename, 16, lambda r: 15 + ( r['content_length'] if r['content_length'] is not None else 0 ) )) # The following is not very useful so it's not worth computing # 'VCN_child', ( # lambda s: int(str(s[::-1]).encode('hex'),16) if len(s) else None, # lambda r: r['entry_length'] - (8 if r['flags'] & 0x1 else 0), # lambda r: r['entry_length'] # ) ] attr_header_fmt = [ ('type', ('i', 0, 3)), ('length', ('i', 4, 7)), ('non_resident', ('i', 8, 8)), ('name_length', ('i', 9, 9)), ('name_off', ('i', 10, 11)), ('flags', ('i', 12, 13)), ('id', ('i', 14, 15)), ('name', ( printable_name, lambda r: r['name_off'], lambda r: r['name_off'] + r['name_length']*2 - 1 )) ] attr_resident_fmt = [ ('content_size', ('i', 16, 19)), ('content_off', ('i', 20, 21)) ] attr_nonresident_fmt = [ ('start_VCN', ('i', 16, 23)), ('end_VCN', ('i', 24, 31)), ('runlist_offset', ('i', 32, 33)), ('compression_unit', ('i', 34, 35)), ('allocated_size', ('i', 40, 47)), ('real_size', ('i', 48, 55)), ('initialized_size', ('i', 56, 63)), ('runlist', ( runlist_unpack, lambda r: r['runlist_offset'], lambda r: r['allocated_size'] )) ] attr_names = { 16: '$STANDARD_INFORMATION', 32: '$ATTRIBUTE_LIST', 48: '$FILE_NAME', 80: '$SECURITY_DESCRIPTOR', 96: '$VOLUME_NAME', 112: '$VOLUME_INFORMATION', 128: '$DATA', 144: '$INDEX_ROOT', 160: '$INDEX_ALLOCATION', 176: '$BITMAP' } # This structure extracts only interesting attributes. attr_types_fmt = { '$STANDARD_INFORMATION': [ ('creation_time', (windows_time, 0, 7)), ('modification_time', (windows_time, 8, 15)), ('MFT_modification_time', (windows_time, 16, 23)), ('access_time', (windows_time, 24, 31)), ('flags', ('i', 32, 35)) ], '$ATTRIBUTE_LIST': [ ('entries', (attribute_list_parser, 0, 1024)) ], '$FILE_NAME': [ ('parent_entry', ('i', 0, 5)), ('parent_seq', ('i', 6, 7)), ('creation_time', (windows_time, 8, 15)), ('modification_time', (windows_time, 16, 23)), ('MFT_modification_time', (windows_time, 24, 31)), ('access_time', (windows_time, 32, 39)), ('allocated_size', ('i', 40, 47)), ('real_size', ('i', 48, 55)), ('flags', ('i', 56, 59)), ('name_length', ('i', 64, 64)), ('namespace', ('i', 65, 65)), ('name', (printable_name, 66, lambda r: r['name_length']*2 + 65)) ], '$INDEX_ROOT': [ ('attr_type', ('i', 0, 3)), ('sorting_rule', ('i', 4, 7)), ('record_bytes', ('i', 8, 11)), ('record_clusters', ('i', 12, 12)), ('records', (index_root_parser, 16, lambda r: r['record_bytes'])) ] } ================================================ FILE: recuperabit/logic.py ================================================ """Filesystem-independent algorithmic logic.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . import bisect import codecs import logging import os import os.path import sys import time import types from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, Iterator, Set, Tuple, TypeVar, Generic T = TypeVar('T') if TYPE_CHECKING: from .fs.core_types import File, Partition class SparseList(Generic[T]): """List which only stores values at some places.""" def __init__(self, data: Optional[Dict[int, T]] = None, default: Optional[T] = None) -> None: self.keys: List[int] = [] # This is always kept in order self.elements: Dict[int, T] = {} self.default: Optional[T] = default if data is not None: self.keys = sorted(data) self.elements.update(data) def __len__(self) -> int: try: return self.keys[-1] + 1 except IndexError: return 0 def __getitem__(self, index: int) -> Optional[T]: return self.elements.get(index, self.default) def __setitem__(self, index: int, item: T) -> None: if item == self.default: if index in self.elements: del self.elements[index] del self.keys[bisect.bisect_left(self.keys, index)] else: if index not in self.elements: bisect.insort(self.keys, index) self.elements[index] = item def __contains__(self, element: T) -> bool: return element in self.elements.values() def __iter__(self) -> Iterator[int]: return self.keys.__iter__() def __repr__(self) -> str: elems = [] prevk = 0 if len(self.elements) > 0: k = self.keys[0] elems.append(str(k) + ' -> ' + repr(self.elements[k])) prevk = self.keys[0] for i in range(1, len(self.elements)): nextk = self.keys[i] if nextk <= prevk + 2: while prevk < nextk - 1: elems.append('__') prevk += 1 elems.append(repr(self.elements[nextk])) else: elems.append('\n... ' + str(nextk) + ' -> ' + repr(self.elements[nextk])) prevk = nextk return '[' + ', '.join(elems) + ']' def iterkeys(self) -> Iterator[int]: """An iterator over the keys of actual elements.""" return self.__iter__() def iterkeys_rev(self) -> Iterator[int]: """An iterator over the keys of actual elements (reversed).""" i = len(self.keys) while i > 0: i -= 1 yield self.keys[i] def itervalues(self) -> Iterator[T]: """An iterator over the elements.""" for k in self.keys: yield self.elements[k] def wipe_interval(self, bottom: int, top: int) -> None: """Remove elements between bottom and top.""" new_keys = set() if bottom > top: for k in self.keys: if top <= k < bottom: new_keys.add(k) else: del self.elements[k] else: for k in self.keys: if bottom <= k < top: del self.elements[k] else: new_keys.add(k) self.keys = sorted(new_keys) def preprocess_pattern(pattern: SparseList[T]) -> Dict[T, List[int]]: """Preprocess a SparseList for approximate string matching. This function performs preprocessing for the Baeza-Yates--Perleberg fast and practical approximate string matching algorithm.""" result: Dict[T, List[int]] = {} length = pattern.__len__() for k in pattern: name = pattern[k] if name not in result: result[name] = [length-k-1] elif name != result[name][-1]: result[name].append(length-k-1) return result def approximate_matching(records: SparseList[T], pattern: SparseList[T], stop: int, k: int = 1) -> Optional[List[Union[Set[int], int, float]]]: """Find the best match for a given pattern. The Baeza-Yates--Perleberg algorithm requires a preprocessed pattern. This function takes as input a SparseList of records and pattern that will be preprocessed. The records in the SparseList should be formed by single elements. If they have another shape, e.g. tuples of the form (namespace, name), the get function can be used to tell the algorithm how to access them. k is the minimum value for support.""" msize = pattern.__len__() if records.__len__() == 0 or msize == 0: return None lookup = preprocess_pattern(pattern) count: SparseList[int] = SparseList(default=0) match_offsets: Set[int] = set() i = 0 j = 0 # previous value of i # logging.debug('Starting approximate matching up to %i', stop) # Loop only on indexes where there are elements for i in records: if i > stop+msize-1: break # zero-out the parts that were skipped count.wipe_interval(j % msize, i % msize) j = i offsets = set(lookup.get(records[i], [])) for off in offsets: count[(i + off) % msize] += 1 score = count[(i + off) % msize] if score == k: match_offsets.add(i+off-msize+1) if score > k: k = score match_offsets = set([i+off-msize+1]) if len(match_offsets): logging.debug( 'Found MATCH in positions {} ' 'with weight {} ({}%)'.format( match_offsets, k, k * 100.0 / len(pattern.keys) ) ) return [match_offsets, k, float(k) / len(pattern.keys)] else: # logging.debug('No match found') return None def makedirs(path: str) -> bool: """Make directories if they do not exist.""" try: os.makedirs(path) except OSError: _, value, _ = sys.exc_info() # The directory already exists = no problem if value.errno != 17: logging.error(value) return False return True def recursive_restore(node: 'File', part: 'Partition', outputdir: str, make_dirs: bool = True) -> None: """Restore a directory structure starting from a file node.""" parent_path = str( part[node.parent].full_path(part) if node.parent is not None else '' ) file_path = os.path.join(parent_path, node.name) restore_parent_path = os.path.join(outputdir, parent_path) restore_path = os.path.join(outputdir, file_path) try: content = node.get_content(part) except NotImplementedError: logging.error(u'Restore of #%s %s is not supported', node.index, file_path) content = None if make_dirs: if not makedirs(restore_parent_path): return is_directory = node.is_directory or len(node.children) > 0 if is_directory: logging.info(u'Restoring #%s %s', node.index, file_path) if not makedirs(restore_path): return if is_directory and content is not None: logging.warning(u'Directory %s has data content!', file_path) restore_path += '_recuperabit_content' try: if content is not None: logging.info(u'Restoring #%s %s', node.index, file_path) with codecs.open(restore_path, 'wb') as outfile: if isinstance(content, types.GeneratorType): for piece in content: outfile.write(piece) else: outfile.write(content) else: if not is_directory: # Empty file open(restore_path, 'wb').close() except IOError: logging.error(u'IOError when trying to create %s', restore_path) try: # Restore Modification + Access time mtime, atime, _ = node.get_mac() if mtime is not None: atime = time.mktime(atime.astimezone().timetuple()) mtime = time.mktime(mtime.astimezone().timetuple()) os.utime(restore_path, (atime, mtime)) except IOError: logging.error(u'IOError while setting atime and mtime of %s', restore_path) if is_directory: for child in node.children: if not child.ignore(): recursive_restore(child, part, outputdir, make_dirs=False) else: logging.info(u'Skipping ignored file {}'.format(child)) ================================================ FILE: recuperabit/utils.py ================================================ """Collection of utility functions.""" # RecuperaBit # Copyright 2014-2021 Andrea Lazzarotto # # This file is part of RecuperaBit. # # RecuperaBit 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. # # RecuperaBit 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 RecuperaBit. If not, see . from datetime import datetime import logging import pprint import string import sys import time from typing import TYPE_CHECKING, Any, Iterable, Optional, List, Dict, Tuple, Union, Callable import unicodedata import io from .fs.constants import sector_size printer: pprint.PrettyPrinter = pprint.PrettyPrinter(indent=4) all_chars = (chr(i) for i in range(sys.maxunicode)) unicode_printable: set[str] = set( c for c in all_chars if not unicodedata.category(c)[0].startswith('C') ) ascii_printable: set[str] = set(string.printable[:-5]) if TYPE_CHECKING: from .fs.core_types import File, Partition def sectors(image: io.BufferedReader, offset: int, size: int, bsize: int = sector_size, fill: bool = True) -> Optional[bytearray]: """Read from a file descriptor.""" read = True try: image.seek(offset * bsize) except (IOError, OverflowError, ValueError): read = False if read: try: dump = image.read(size * bsize) except (IOError, MemoryError): logging.warning( "Cannot read sector(s). Filling with 0x00. Offset: {} Size: " "{} Bsize: {}".format(offset, size, bsize) ) read = False if not read: if fill: dump = size * bsize * b'\x00' else: return None return bytearray(dump) def unixtime(dtime: Optional[datetime]) -> float: """Convert datetime to UNIX epoch.""" if dtime is None: return 0.0 try: return time.mktime(dtime.timetuple()) except ValueError: return 0.0 # format: # [(label, (formatter, lower, higher)), ...] def unpack(data: bytes, fmt: List[Tuple[str, Tuple[Union[str, Callable[[bytes], Any]], Union[int, Callable[[Dict[str, Any]], Optional[int]]], Union[int, Callable[[Dict[str, Any]], Optional[int]]]]]]) -> Dict[str, Any]: """Extract formatted information from a string of bytes.""" result: Dict[str, Any] = {} for label, description in fmt: formatter, lower, higher = description # If lower is a function, then apply it low = lower(result) if callable(lower) else lower high = higher(result) if callable(higher) else higher if low is None or high is None: result[label] = None continue if callable(formatter): result[label] = formatter(data[low:high+1]) else: if formatter == 's': result[label] = str(data[low:high+1]) if formatter.startswith('utf'): result[label] = data[low:high+1].decode(formatter) if formatter.endswith('i') and len(formatter) < 4: # Use little-endian by default. Big-endian with >i. # Force sign-extension of first bit with >+i / +i. chunk = data[low:high+1] signed = False if '+' in formatter: signed = True byteorder = 'little' if formatter.startswith('>'): byteorder = 'big' if len(chunk): result[label] = int.from_bytes(chunk, byteorder=byteorder, signed=signed) else: result[label] = None return result def feed_all(image: io.BufferedReader, scanners: List[Any], indexes: Iterable[int]) -> List[int]: # Scan the disk image and feed the scanners interesting: List[int] = [] for index in indexes: sector = sectors(image, index, 1, fill=False) if not sector: break for instance in scanners: res = instance.feed(index, sector) if res is not None: logging.info('Found {} at sector {}'.format(res, index)) interesting.append(index) return interesting def printable(text: str, default: str = '.', alphabet: Optional[set[str]] = None) -> str: """Replace unprintable characters in a text with a default one.""" if alphabet is None: alphabet = unicode_printable return ''.join((i if i in alphabet else default) for i in text) def readable_bytes(amount: Optional[int]) -> str: """Return a human readable string representing a size in bytes.""" if amount is None: return '??? B' if amount < 1: return '%.2f B' % amount powers = { 0: '', 1: 'K', 2: 'M', 3: 'G', 4: 'T' } biggest = max(i for i in powers if amount / 1024.**i >= 1) scaled = amount / 1024.**biggest return '%.2f %sB' % (scaled, powers[biggest]) def _file_tree_repr(node: 'File') -> str: """Give a nice representation for the tree.""" desc = ( ' [GHOST]' if node.is_ghost else ' [DELETED]' if node.is_deleted else '' ) tail = '/' if node.is_directory else '' data = [ ('Id', node.index), ('Offset', node.offset), ( 'Offset bytes', node.offset * sector_size if node.offset is not None else None ) # ('MAC', node.mac) ] if not node.is_directory: data += [('Size', readable_bytes(node.size))] return u'%s%s (%s) %s' % ( node.name, tail, ', '.join(a + ': ' + str(b) for a, b in data), desc ) def tree_folder(directory: 'File', padding: int = 0) -> str: """Return a tree-like textual representation of a directory.""" lines: List[str] = [] pad = ' ' * padding lines.append( pad + _file_tree_repr(directory) ) padding = padding + 2 pad = ' ' * padding for entry in directory.children: if len(entry.children) or entry.is_directory: lines.append(tree_folder(entry, padding)) else: lines.append( pad + _file_tree_repr(entry) ) return '\n'.join(lines) def _bodyfile_repr(node: 'File', path: str) -> str: """Return a body file line for node.""" end = '/' if node.is_directory or len(node.children) else '' return '|'.join(str(el) for el in [ '0', # MD5 path + node.name + end, # name node.index, # inode '0', '0', '0', # mode, UID, GID node.size if node.size is not None else 0, unixtime(node.mac['access']), unixtime(node.mac['modification']), unixtime(node.mac['creation']), '0' ]) def bodyfile_folder(directory: 'File', path: str = '') -> List[str]: """Create a body file compatible with TSK 3.x. Format: '#MD5|name|inode|mode_as_string|UID|GID|size|atime|mtime|ctime|crtime' See also: http://wiki.sleuthkit.org/index.php?title=Body_file""" lines: List[str] = [_bodyfile_repr(directory, path)] path += directory.name + '/' for entry in directory.children: if len(entry.children) or entry.is_directory: lines += bodyfile_folder(entry, path) else: lines.append(_bodyfile_repr(entry, path)) return lines def _ltx_clean(label: Any) -> str: """Small filter to prepare strings to be included in LaTeX code.""" clean = str(label).replace('$', r'\$').replace('_', r'\_') if clean[0] == '-': clean = r'\textminus{}' + clean[1:] return clean def _tikz_repr(node: 'File') -> str: """Represent the node for a Tikz diagram.""" return r'node %s{%s\enskip{}%s}' % ( '[ghost]' if node.is_ghost else '[deleted]' if node.is_deleted else '', _ltx_clean(node.index), _ltx_clean(node.name) ) def tikz_child(directory: 'File', padding: int = 0) -> Tuple[str, int]: """Write a child row for Tikz representation.""" pad = ' ' * padding lines: List[str] = [r'%schild {%s' % (pad, _tikz_repr(directory))] count: int = len(directory.children) for entry in directory.children: content, number = tikz_child(entry, padding+4) lines.append(content) count += number lines.append('}') for entry in range(count): lines.append('child [missing] {}') return '\n'.join(lines).replace('\n}', '}'), count def tikz_part(part: 'Partition') -> str: """Create LaTeX code to represent the directory structure as a nice Tikz diagram. See also: http://www.texample.net/tikz/examples/filesystem-tree/""" preamble = (r"""%\usepackage{tikz} %\usetikzlibrary{trees}""") begin_tree = r"""\begin{tikzpicture}[% grow via three points={one child at (1.75em,-1.75em) and two children at (1.75em,-1.75em) and (1.75em,-3.5em)}, edge from parent path={(\tikzparentnode.south) |- (\tikzchildnode.west)}] \scriptsize """ end_tree = r"""\end{tikzpicture}""" lines = [r'\node [root] {File System Structure}'] lines += [tikz_child(entry, 4)[0] for entry in (part.root, part.lost)] lines.append(';') return '%s\n\n%s\n%s\n%s' % ( preamble, begin_tree, '\n'.join(lines), end_tree ) def csv_part(part: 'Partition') -> list[str]: """Provide a CSV representation for a partition.""" contents = [ ','.join(('Id', 'Parent', 'Name', 'Full Path', 'Modification Time', 'Access Time', 'Creation Time', 'Size (bytes)', 'Size (human)', 'Offset (bytes)', 'Offset (sectors)', 'Directory', 'Deleted', 'Ghost')) ] for index in part.files: obj = part.files[index] contents.append( u'%s,%s,"%s","%s",%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % ( obj.index, obj.parent, obj.name, obj.full_path(part), obj.mac['modification'], obj.mac['access'], obj.mac['creation'], obj.size, readable_bytes(obj.size), (obj.offset * sector_size if obj.offset is not None else None), obj.offset, '1' if obj.is_directory else '', '1' if obj.is_deleted else '', '1' if obj.is_ghost else '' ) ) return contents def _sub_locate(text: str, directory: 'File', part: 'Partition') -> List[Tuple['File', str]]: """Helper for locate.""" lines: List[Tuple['File', str]] = [] for entry in sorted(directory.children, key=lambda node: node.name): path = entry.full_path(part) if text in path.lower(): lines.append((entry, path)) if len(entry.children) or entry.is_directory: lines += _sub_locate(text, entry, part) return lines def locate(part: 'Partition', text: str) -> List[Tuple['File', str]]: """Return paths of files matching the text.""" lines: List[Tuple['File', str]] = [] text = text.lower() lines += _sub_locate(text, part.lost, part) lines += _sub_locate(text, part.root, part) return lines def merge(part: 'Partition', piece: 'Partition') -> None: """Merge piece into part (both are partitions).""" for index in piece.files: if ( index not in part.files or part.files[index].is_ghost ): part.add_file(piece.files[index])