grokevt-0.5.0/0000755000175000017500000000000011577710546011356 5ustar timtimgrokevt-0.5.0/INSTALL0000644000175000017500000000302111577706600012377 0ustar timtimPrerequisites ============= In order to install this package, you must have the following already set up on your system: - Python (tested on 2.6 and 3.1) - GNU Make In order to use this software you also need: - RegLookup (version 1.0.0 or later) Earlier versions of Python may work, but they have not yet been tested. To obtain RegLookup, please see the project page at: http://www.sentinelchicken.org/projects/reglookup/ You do not need to have RegLookup installed before installing this software, but you will need to have it installed and in your PATH whenever you run grokevt-builddb(1). Building ======== For most installations, this is as simple as: make which will create the build/ directory with all install-ready items neatly arranged. (If your system does not use GNU Make by default, you'll probably have to use `gmake' instead.) If you wish to change the path of the configuration files, you will want to instead set the ETC_PREFIX variable: make ETC_PREFIX=/path/to/etc This path defaults to '/usr/local/etc'. Installing ========== Installation is typically as simple as: make install If you wish to override any of the installation prefixes (please see the top-level make file for all available paths), you'll need to specify those on the command line as well. By default, everything installs somewhere under '/usr/local'. If you wanted to change this to '/usr', you could do: make PREFIX=/usr install If you just want to override the ETC_PREFIX, you need to override it during build *and* during install. grokevt-0.5.0/LICENSE0000644000175000017500000010437411577670023012367 0ustar timtim GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . grokevt-0.5.0/Makefile0000644000175000017500000000222411576211775013015 0ustar timtim# $Id: Makefile 117 2011-06-15 20:20:13Z tim $ PYTHON3_PATH:=`which python3` PYTHON_PATH:=`which python` # Installation prefixes. Change to install elsewhere. PREFIX=/usr/local BIN_PREFIX=$(PREFIX)/bin ETC_PREFIX=$(PREFIX)/etc/grokevt DOC_PREFIX=$(PREFIX)/share/doc/grokevt MAN_PREFIX=$(PREFIX)/man ################################################################################ BUILD=$(CURDIR)/build BUILD_BIN=$(BUILD)/bin BUILD_LIB=$(BUILD)/lib BUILD_ETC=$(BUILD)/etc BUILD_DOC=$(BUILD)/doc BUILD_TREE=$(BUILD_BIN) $(BUILD_LIB) $(BUILD_ETC) $(BUILD_DOC) SUB_DIRS=bin lib etc doc .PHONY: $(SUB_DIRS) clean export all: $(BUILD_TREE) $(SUB_DIRS) # XXX: This should be more generalized. install: all mkdir -p $(BIN_PREFIX) mkdir -p $(ETC_PREFIX) mkdir -p $(DOC_PREFIX) cp -r $(BUILD_BIN)/* $(BIN_PREFIX) cp -r $(BUILD_ETC)/* $(ETC_PREFIX) cp -r $(BUILD_DOC)/* $(DOC_PREFIX) if [ "x$(PYTHON_PATH)" != "x" ]; then $(PYTHON_PATH) grokevt-distutils.py install; fi if [ "x$(PYTHON3_PATH)" != "x" ]; then $(PYTHON_PATH) grokevt-distutils.py install; fi $(MAKE) -C doc install $(SUB_DIRS): $(MAKE) -C $@ $(BUILD_TREE): mkdir -p $@ clean: rm -rf $(BUILD) grokevt-0.5.0/README0000644000175000017500000000075310257575042012235 0ustar timtimGrokEVT is an collection of scripts built for reading Windows NT(tm) event log files. GrokEVT is released under the GNU GPL, and is implemented in Python. Installation ============ Please see the file INSTALL in this directory. Using ===== A guide on how to get started can be found in: doc/grokevt.txt or in the man page grokevt(7) after installation. Other ===== If you have any other questions, please see the project website: http://www.sentinelchicken.org/projects/grokevt/ grokevt-0.5.0/bin/0000755000175000017500000000000011577710546012126 5ustar timtimgrokevt-0.5.0/bin/Makefile0000644000175000017500000000156410602607641013561 0ustar timtim# $Id: Makefile 105 2007-03-29 01:00:17Z tim $ ################################################################################ ADDLOG=$(BUILD_BIN)/grokevt-addlog BUILDDB=$(BUILD_BIN)/grokevt-builddb DUMPMSGS=$(BUILD_BIN)/grokevt-dumpmsgs FINDLOGS=$(BUILD_BIN)/grokevt-findlogs PARSELOG=$(BUILD_BIN)/grokevt-parselog RIPDLL=$(BUILD_BIN)/grokevt-ripdll FILES=$(ADDLOG) $(BUILDDB) $(DUMPMSGS) $(FINDLOGS) $(PARSELOG) $(RIPDLL) all: $(FILES) $(ADDLOG): grokevt-addlog install -m 0755 grokevt-addlog $(ADDLOG) $(BUILDDB): grokevt-builddb install -m 0755 grokevt-builddb $(BUILDDB) $(DUMPMSGS): grokevt-dumpmsgs install -m 0755 grokevt-dumpmsgs $(DUMPMSGS) $(FINDLOGS): grokevt-findlogs install -m 0755 grokevt-findlogs $(FINDLOGS) $(PARSELOG): grokevt-parselog install -m 0755 grokevt-parselog $(PARSELOG) $(RIPDLL): grokevt-ripdll install -m 0755 grokevt-ripdll $(RIPDLL) grokevt-0.5.0/bin/grokevt-addlog0000755000175000017500000000344211577670023014763 0ustar timtim#!/bin/sh # This script takes a raw Windows event log and adds it to a # previously built database generated by grokevt-builddb. # See the man page for more details. # # Copyright (C) 2006 Timothy D. Morgan # # 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 version 3 of the # License. # # 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. # # $Id: grokevt-addlog 118 2011-06-20 16:06:43Z tim $ usage() { echo "USAGE:" 1>&2 echo " $0 " 1>&2 echo 1>&2 echo "This script takes a raw Windows event log and adds it to a" 1>&2 echo "previously built database generated by grokevt-builddb." 1>&2 echo "See the man page for more details." 1>&2 } if [ $# -ne 4 ]; then usage exit 1 fi DATABASE_DIR="$1" EVT_FILE="$2" NEW_TYPE="$3" BASE_TYPE="$4" if [ ! -d "$DATABASE_DIR" ]; then echo "ERROR: '$DATABASE_DIR' is not a directory." 1>&2 exit 2 fi if [ ! -r "$EVT_FILE" ]; then echo "ERROR: '$EVT_FILE' could not be read." 1>&2 exit 2 fi if [ -e "${DATABASE_DIR}/logs/${NEW_TYPE}.evt" ]; then echo "ERROR: A '$NEW_TYPE' log already exists." 1>&2 exit 2 fi if [ ! -d "${DATABASE_DIR}/services/${BASE_TYPE}" ]; then echo "ERROR: A '$BASE_TYPE' log does not exist." 1>&2 exit 2 fi cp "$EVT_FILE" "${DATABASE_DIR}/logs/${NEW_TYPE}.evt"\ || ( echo "ERROR: Could not copy log file." 1>&2; exit 3 ) ln -s "$BASE_TYPE" "${DATABASE_DIR}/services/${NEW_TYPE}"\ || ( echo "ERROR: Could not create symlink to BASE_TYPE." 1>&2; exit 3 ) grokevt-0.5.0/bin/grokevt-builddb0000755000175000017500000003016211577670023015135 0ustar timtim#!/usr/bin/env python # This script builds message databases for use by grokevt-parselog. # # Copyright (C) 2005-2008,2011 Timothy D. Morgan # # 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 version 3 of the # License. # # 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. # # vi:set tabsize=4: # $Id: grokevt-builddb 118 2011-06-20 16:06:43Z tim $ import sys import os import re import subprocess import dbm import select import pyregfi import grokevt # XXX: should these be changed to absolute paths discovered at install time? CURRENT_DB_VERSION=2 PATH_RIPDLL='grokevt-ripdll' missing_dlls = {} def usage(): sys.stderr.write("USAGE:\n") sys.stderr.write(" %s [-v] [-c CSID] \n\n" % os.path.basename(sys.argv[0])) sys.stderr.write("grokevt-builddb builds a database tree based on a\n") sys.stderr.write("single windows system for the purpose of event log\n") sys.stderr.write("conversion. Please see the man page for more\n") sys.stderr.write("information.\n") def unquoteString(s): chunks = re.split("\\\\x([0-9A-F]{2})", s); for i in range(1,len(chunks),2): chunks[i] = "%c" % int(chunks[i], 16) return ''.join(chunks) def resolveCaseSensitivePath(prefix, insensitive): if len(insensitive) == 0: return prefix for sub in os.listdir(prefix): if sub.lower() == insensitive[0]: return resolveCaseSensitivePath("%s/%s" % (prefix, sub), insensitive[1:]) def windowsPathToUnixPath(path_list, variables, drives): paths = path_list.lower().split(';') for i in range(0,len(paths)): for var,value in variables.items(): paths[i] = paths[i].replace(var.lower(), value.lower()).replace("\\","/") # Some paths have been found with trailing nulls and garbage. paths[i] = paths[i].split('\x00')[0] ret_val = [] for p in paths: for letter,upath in drives.items(): if p.startswith(letter.lower()): p = resolveCaseSensitivePath(upath, p[len(letter)+1:].split('/')) break if p != None: ret_val.append(p) return ret_val def pyregfiPrintMessages(): messages = pyregfi.getLogMessages() if messages != '' and messages != None: lines = messages.split('\n') for l in lines: sys.stderr.write("WARN: pyregfi reported: %s\n" % l) def ripdllStderrHandler(e, args): sys.stderr.write(("WARNING: while reading %s and writing %s.db," +" grokevt-ripdll returned: %s")\ % (args[0], args[1], e.decode('utf-8', 'replace'))) class procWrapper: child = None exe_name = None def __init__(self, args): self.exe_name = args[0] self.child = subprocess.Popen(args, shell=False, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) def readline(self): return self.child.stdout.readline() def wait(self): while self.readline() != b'': continue child_ret = self.child.wait() if child_ret > 0: sys.stderr.write("WARNING: %s returned code: %d. Is it in your path?" % (self.exe_name, child_ret)) return child_ret def buildShortNamesPathsDicts(paths): ret_val1 = {} ret_val2 = {} for p in paths.keys(): if os.path.isfile(p): sn = os.path.basename(p).replace(':','_') ext = '' i = 2 while (sn+ext) in ret_val1: ext = '_%d' % i i += 1 ret_val1[sn+ext] = p ret_val2[p] = sn+ext else: # XXX: this might be handy later #missing_dlls[p] = paths[p] sys.stderr.write("WARNING: %s doesn't exist.\n" % p + "WARNING: (This may affect log output " + "for the following services: %s)\n" % paths[p]) return (ret_val1, ret_val2) def makeOutputDirectories(topdir, logs): dirs = [] for log in logs: dirs.append('%s/services/%s' % (topdir,log)) dirs.append('%s/messages' % topdir) dirs.append('%s/logs' % topdir) for p in dirs: if os.path.exists(p): if not os.path.isdir(p) or not os.access(p, os.W_OK): sys.stderr.write("ERROR: Access denied to '%s'.\n" % p) sys.exit(os.EX_CANTCREAT) else: os.makedirs(p, 0o755) # Write DB version vf = open('%s/version' % topdir, 'w+b') vf.write(('%d\n' % CURRENT_DB_VERSION).encode('utf-8')) vf.close() def writeServiceMapping(topdir, maps): for lt in maps.keys(): for t in maps[lt].keys(): db_file = "%s/services/%s/%s"%(topdir,lt,t) db = dbm.open(db_file, "n", 0o644) for k,v in maps[lt][t].items(): if len(v) != 0: db[k] = v db.close() def writeDBFiles(topdir, names2paths): for npi in names2paths.items(): outdb = "%s/messages/%s" % (topdir, npi[0]) db_call = (PATH_RIPDLL, npi[1], outdb) ripdll_proc = procWrapper(db_call) l = ripdll_proc.readline() while l != b'': ripdllStderrHandler(l, (npi[1], outdb)) l = ripdll_proc.readline() ripdll_proc.wait() # Parse command line arguments CONTROL_SET_ID = None print_verbose = 0 next_is_cid = 0 argv_len = len(sys.argv) if argv_len < 3: usage() sys.stderr.write("ERROR: Requires at least 2 arguments.\n") sys.exit(os.EX_USAGE) else: for option in sys.argv[1:argv_len-2]: if next_is_cid: CONTROL_SET_ID = int(option) if CONTROL_SET_ID < 1: usage() sys.stderr.write("ERROR: CONTROL_SET_ID must be positive.\n") sys.exit(os.EX_USAGE) next_is_cid = 0 elif option == '-v': print_verbose = 1 elif option == '-c': next_is_cid = 1 else: usage() sys.stderr.write("ERROR: Unrecognized option '%s'.\n" % option) sys.exit(os.EX_USAGE) if next_is_cid: usage() sys.stderr.write("ERROR: -c requires parameter.\n") sys.exit(os.EX_USAGE) CONFIG_PROFILE=sys.argv[argv_len-2] PATH_OUTPUT=sys.argv[argv_len-1] if print_verbose: sys.stderr.write("INFO: Loading configuration...\n") config = grokevt.grokevtConfig(grokevt.PATH_CONFIG, CONFIG_PROFILE) system_hive = pyregfi.openHive(config.registry_path) pyregfiPrintMessages() if print_verbose: sys.stderr.write("INFO: Reading system registry for service information...\n") # Need to determine correct 'CurrentControlSet', if not specified at # command line if not CONTROL_SET_ID: try: csid_key = system_hive.root.subkeys['Select'] CONTROL_SET_ID = int(csid_key.values['Current'].fetch_data()) del csid_key pyregfiPrintMessages() except Exception as e: sys.stderr.write("ERROR: Could not automatically " +"determine CONTROL_SET_ID\n") sys.exit(os.EX_IOERR) if print_verbose: sys.stderr.write("INFO: Detected CONTROL_SET_ID=%d\n" % CONTROL_SET_ID) EVENTLOG_PATH=('ControlSet%.3d' % CONTROL_SET_ID, 'Services', 'Eventlog') # Next, identify all log types by grabbing all keys under the eventlog key log_types = {} evt_files = {} files = {} eventlog_key = system_hive.subtree(EVENTLOG_PATH).current_key() for ltype in eventlog_key.subkeys: lt = ltype.name log_types[lt] = {} # Obtain path to .evt file try: data = ltype.values['File'].fetch_data() evt_files[lt] = windowsPathToUnixPath(unquoteString(data), config.path_vars, config.drive_mapping)[0] pyregfiPrintMessages() except Exception as e: if print_verbose: sys.stderr.write('WARNING: Event log file path not found' +' for log type "%s". Removing this type.\n' % lt) del log_types[lt] continue # Collect list of sources/services under this log type log_types[lt]["event"] = {} log_types[lt]["category"] = {} log_types[lt]["parameter"] = {} try: sources = ltype.values['Sources'].fetch_data() if len(data) == 0 and print_verbose: sys.stderr.write('WARNING: No sources found for log type "%s".\n' % lt) pyregfiPrintMessages() except Exception as e: sys.stderr.write('WARNING: Could not obtain list of sources' +' for log type "%s". Removing this type.\n' % lt) del log_types[lt] continue # For each source under this log type, compile the list of paths for various # message files for s in sources: source_key = ltype.subkeys[s] log_types[lt]["event"][s] = [] value = source_key.values.get('EventMessageFile', None) if value != None: log_types[lt]["event"][s] = windowsPathToUnixPath(value.fetch_data(), config.path_vars, config.drive_mapping) log_types[lt]["category"][s] = [] value = source_key.values.get('CategoryMessageFile', None) if value != None: log_types[lt]["category"][s] = windowsPathToUnixPath(value.fetch_data(), config.path_vars, config.drive_mapping) log_types[lt]["parameter"][s] = [] value = source_key.values.get('ParameterMessageFile', None) if value != None: log_types[lt]["parameter"][s] = windowsPathToUnixPath(value.fetch_data(), config.path_vars, config.drive_mapping) # Retain unique list of file names and their associated services for f in (log_types[lt]['event'][s] + log_types[lt]['category'][s] + log_types[lt]['parameter'][s]): if f in files: files[f] = files[f]+","+s else: files[f] = s pyregfiPrintMessages() (names2paths,paths2names) = buildShortNamesPathsDicts(files) # Convert path lists to named path strings. Filter out any unusable resources # and any services that have no remaining resources. for lt in log_types.keys(): for t in log_types[lt].keys(): for s in log_types[lt][t].keys(): if len(log_types[lt][t][s]) > 0: tmp_str = '' for i in range(0,len(log_types[lt][t][s])): if log_types[lt][t][s][i] in paths2names: tmp_str += ':' + paths2names[log_types[lt][t][s][i]] log_types[lt][t][s] = tmp_str.lstrip(':') if print_verbose: sys.stderr.write("INFO: Writing service mappings...\n") makeOutputDirectories(PATH_OUTPUT, log_types.keys()) writeServiceMapping(PATH_OUTPUT, log_types) if print_verbose: sys.stderr.write("INFO: Writing DLL databases...\n") writeDBFiles(PATH_OUTPUT, names2paths) if print_verbose: sys.stderr.write("INFO: Copying log files...\n") try: for ei in evt_files.items(): o = open("%s/logs/%s.evt" % (PATH_OUTPUT,ei[0]), "w+b") i = open(ei[1], "rb") buf = i.read(4096) while buf != b'': o.write(buf) buf = i.read(4096) o.close() i.close() except Exception as inst: sys.stderr.write("ERROR: %s\n" % inst) sys.stderr.write("ERROR: could not copy all log files.\n") sys.exit(os.EX_IOERR) if print_verbose: sys.stderr.write("INFO: Done.\n") grokevt-0.5.0/bin/grokevt-dumpmsgs0000755000175000017500000000337011577677746015413 0ustar timtim#!/usr/bin/python # This script dumps the contents of message databases built by grokevt-ripdll. # # Copyright (C) 2006-2007,2011 Timothy D. Morgan # # 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 version 3 of the # License. # # 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. # # vi:set tabsize=4: # $Id: grokevt-dumpmsgs 119 2011-06-20 17:14:14Z tim $ import sys import os import dbm import grokevt def usage(): sys.stderr.write("USAGE:\n") sys.stderr.write(" %s [ ...]\n\n"\ % os.path.basename(sys.argv[0])) sys.stderr.write("grokevt-dumpmsgs dumps the contents of message databases\n") sys.stderr.write("built previously by grokevt-ripdll.\n") if len(sys.argv) < 2: usage() sys.exit(os.EX_USAGE) for dbfile in sys.argv[1:]: if not os.access(dbfile, os.R_OK): sys.stderr.write("ERROR: DB file could not be read.") sys.exit(1) db = dbm.open(dbfile.split('.db', 1)[0], 'r') if grokevt.template_encoding == grokevt.output_encoding: for key in db.keys(): print('%s,%s' % (key.decode('ascii'), grokevt.quoteBinary(db[key], b'%,"'))) else: for key in db.keys(): msg = db[key].decode(grokevt.template_encoding) msg = grokevt.quoteBinary(msg.encode(grokevt.output_encoding,'replace'), b'%,"') print('%s,%s' % (key.decode('ascii'), msg)) db.close() grokevt-0.5.0/bin/grokevt-findlogs0000755000175000017500000001235311577706600015340 0ustar timtim#!/usr/bin/python # This script attempts to find log file fragments in raw binary # files, such as memory dumps and disk images. # # Copyright (C) 2006-2007 Timothy D. Morgan # # 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 version 3 of the # License. # # 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. # # vi:set tabsize=4: # $Id: grokevt-findlogs 120 2011-06-20 18:12:16Z tim $ import sys import os import types import time import struct import grokevt class fileSearcher: f = None largest = 0 bs = 512*1024 strings = None sz = -1 def __init__(self, file_name, strings): self.f = open(BIN_FILE, 'rb') self.largest = max([len(s) for s in strings]) self.bs = max(self.largest,self.bs) self.strings = strings def findOne(self, start=0): self.f.seek(start) offset = start buf = self.f.read(self.bs) while buf != '': hits = [] for s in self.strings: h = buf.find(s) if h != -1: hits.append(h) if len(hits) > 0: return offset+min(hits) buf = buf[(self.bs - self.largest):] + self.f.read(self.bs) offset += (self.bs - self.largest) return -1 def read(self, offset, count): self.f.seek(offset) return self.f.read(count) def size(self): if self.sz > 0: return self.sz o = self.f.tell() self.f.seek(0, 2) self.sz = self.f.tell() self.f.seek(o) return self.sz def close(self): self.f.close() def usage(): sys.stderr.write("USAGE:\n") sys.stderr.write(" %s -?\n" % os.path.basename(sys.argv[0])) sys.stderr.write(" %s [-v] [-h] [-H] [-o ] \n\n" % os.path.basename(sys.argv[0])) sys.stderr.write("grokevt-findlogs attempts to find log file fragments in raw\n") sys.stderr.write("binary files, such as memory dumps and disk images.\n") sys.stderr.write("Please see the man page for more information.\n") # Globals influenced by command line options print_header = 1 # XXX: not currently used print_verbose = 0 start_offset = 0 # Parse command line argv_len = len(sys.argv) if (argv_len < 2) or (sys.argv[1] == '-?') or (sys.argv[1] == '--help'): usage() sys.exit(os.EX_USAGE) else: BIN_FILE=sys.argv[argv_len-1] skip_one = 0 for i in range(1,len(sys.argv)-1): if skip_one: skip_one = 0 else: if sys.argv[i] == '-H': print_header = 0 elif sys.argv[i] == '-h': print_header = 1 elif sys.argv[i] == '-v': print_verbose = 1 elif sys.argv[i] == '-o': if i+1 < len(sys.argv): # XXX: might be nice to allow hexadecimal in addition to decimal start_offset = int(sys.argv[i+1]) skip_one = 1 else: usage() sys.stderr.write("ERROR: -o option requires parameter.\n") sys.exit(os.EX_USAGE) else: usage() sys.stderr.write("ERROR: Unrecognized option '%s'.\n" % option) sys.exit(os.EX_USAGE) if not os.access(BIN_FILE, os.R_OK): sys.stderr.write("ERROR: Input file could not be read.\n") sys.exit(os.EX_OSFILE) searcher = fileSearcher(BIN_FILE, (grokevt.header_log_magic, grokevt.cursor_magic)) if print_header: print("OFFSET,LENGTH,TYPE,MESSAGE_NUM,CREATED,CONTIGUOUS") contig_next = -1 i = searcher.findOne(start_offset) while i != -1: found_one = False if (i + grokevt.min_record_size < searcher.size()): offset = i-4 size1 = struct.unpack("= grokevt.min_record_size) and (end < searcher.size()): size2 = struct.unpack("\n" % command\ +" %s -m \n" % command\ +" %s [-v] [-H] [-h] \n\n"\ % command\ +"This program parses a windows event log and prints a\n"\ +"CSV version of the log to stdout. Please see the man\n"\ +"page for more information.\n") # Globals influenced by command line options mode_loglist = 0 mode_meta = 0 print_verbose = 0 print_header = 1 DB_PATH = None LOG = None # Parse command line argv_len = len(sys.argv) if (argv_len < 3) or (sys.argv[1] == '-?') or (sys.argv[1] == '--help'): usage() sys.exit(os.EX_OK) elif sys.argv[1] == '-l': if argv_len == 3: mode_loglist = 1 DB_PATH=sys.argv[2] else: usage() sys.stderr.write("ERROR: Incorrect usage for log list mode.\n") sys.exit(os.EX_USAGE) elif sys.argv[1] == '-m': if argv_len == 4: mode_meta = 1 DB_PATH=sys.argv[2] LOG=sys.argv[3] else: usage() sys.stderr.write("ERROR: Incorrect usage for meta information mode.\n") sys.exit(os.EX_USAGE) else: if (argv_len >= 3): DB_PATH=sys.argv[argv_len-2] LOG=sys.argv[argv_len-1] for option in sys.argv[1:argv_len-2]: if option == '-v': print_verbose = 1 elif option == '-H': print_header = 0 elif option == '-h': print_header = 1 else: usage() sys.stderr.write("ERROR: Unrecognized option '%s'.\n" % option) sys.exit(os.EX_USAGE) else: usage() sys.stderr.write("ERROR: Incorrect usage for log parse command.\n") sys.exit(os.EX_USAGE) if mode_loglist: try: logs = os.listdir("%s/services" % DB_PATH) for l in logs: print(l) except Exception as inst: sys.stderr.write("%s\n" % inst) sys.stderr.write("ERROR: Could not list services directory.\n") sys.stderr.write(" Did you run grokevt-builddb first?\n") sys.exit(os.EX_OSFILE) sys.exit(os.EX_OK) try: if print_verbose: sys.stderr.write("INFO: Opening message repository '%s'.\n" % DB_PATH) msg_repo = messageRepository(DB_PATH, LOG) except Exception as inst: sys.stderr.write("%s\n" % inst) sys.stderr.write("ERROR: Could not read message repository.\n") sys.stderr.write(" Did you specify the correct DATABASE_DIR?\n") sys.stderr.write(" Did you run grokevt-builddb first?\n") sys.exit(os.EX_OSFILE) evt_file = None evt_filename = "%s/logs/%s.evt" % (DB_PATH, LOG) try: if print_verbose: sys.stderr.write("INFO: Opening event log file at '%s'.\n" % evt_filename) evt_file = evtFile(evt_filename, msg_repo) except Exception as inst: sys.stderr.write("%s\n" % inst) sys.stderr.write("ERROR: Could not open log file.\n") sys.stderr.write(" Did grokevt-builddb finish without errors?\n") sys.exit(os.EX_OSFILE) evt_size = evt_file.size() # Begin parsing logic if mode_meta: csvwriter = csv.DictWriter(sys.stdout, meta_fields, '', 'ignore') row = {'header_first_off':"Unknown", 'cursor_first_off':"Unknown", 'header_first_num':"Unknown", 'cursor_first_num':"Unknown", 'header_next_off':"Unknown", 'cursor_next_off':"Unknown", 'header_next_num':"Unknown", 'cursor_next_num':"Unknown", 'header_file_size':"Unknown", 'real_file_size':evt_size, 'retention_period':"Unknown", 'flag_dirty':"Unknown", 'flag_wrapped':"Unknown", 'flag_logfull':"Unknown", 'flag_primary':"Unknown"} if evt_file.header: row['header_first_off'] = evt_file.header['first_off'] row['header_first_num'] = evt_file.header['first_num'] row['header_next_off'] = evt_file.header['next_off'] row['header_next_num'] = evt_file.header['next_num'] row['header_file_size'] = evt_file.header['file_size'] row['retention_period'] = evt_file.header['retention'] row['flag_dirty'] = evt_file.header['flag_dirty'] row['flag_wrapped'] = evt_file.header['flag_wrapped'] row['flag_logfull'] = evt_file.header['flag_logfull'] row['flag_primary'] = evt_file.header['flag_primary'] if evt_file.cursor: row['cursor_first_off'] = evt_file.cursor['first_off'] row['cursor_first_num'] = evt_file.cursor['first_num'] row['cursor_next_off'] = evt_file.cursor['next_off'] row['cursor_next_num'] = evt_file.cursor['next_num'] csvwriter.writerow(meta_header) csvwriter.writerow(row) sys.exit(os.EX_OK) def encodeRec(rec): for k in rec.keys(): if k == 'strings': rec[k] = '|'.join((quoteUnicode(s) for s in rec[k])) rec[k] = rec[k].strip('|') elif isinstance(rec[k], bytes) or isinstance(rec[k], bytearray): rec[k] = quoteBinary(rec[k]) elif not isinstance(rec[k], int): rec[k] = quoteUnicode(rec[k]) return rec csvwriter = csv.DictWriter(sys.stdout, log_fields, '', 'ignore') if print_header: csvwriter.writerow(log_header) if print_verbose: sys.stderr.write("INFO: Now parsing file.\n") if evt_file.header and evt_file.header['flag_dirty']: sys.stderr.write("WARNING: Log file marked as dirty.\n") if (evt_file.header == None) or (evt_file.cursor == None): sys.stderr.write("WARNING: Naive parsing enabled.\n") record_type = None while record_type != 'wrapped-log': # First, try to find the first log record. This will skip over any split # log records at the beginning of the file. record_type = evt_file.guessRecordType() while ((evt_file.guessRecordType()=='unknown') and (evt_file.tell()= evt_size: break # Next walk through the file hoping to stay aligned with proper records # We skip over anything that looks like a header or cursor, and bail out # as soon as we run across a non-record. if record_type in ('log', 'wrapped-log'): # XXX: catch exceptions? rec = evt_file.getLogRecord() rec = encodeRec(rec) csvwriter.writerow(rec) elif record_type == 'cursor': sys.stderr.write("WARNING: Skipping potential cursor record " +"at offset %d.\n" % evt_file.tell()) evt_file.seek(evt_file.tell()+cursor_size) elif record_type == 'header': sys.stderr.write("WARNING: Skipping potential header record " +"at offset %d.\n" % evt_file.tell()) evt_file.seek(evt_file.tell()+header_size) else: for i in range(evt_file.cursor['first_num'],evt_file.cursor['next_num']): # XXX: catch exceptions? rec = evt_file.getLogRecord() rec = encodeRec(rec) csvwriter.writerow(rec) grokevt-0.5.0/bin/grokevt-ripdll0000755000175000017500000001652711577670023015027 0ustar timtim#!/usr/bin/env python # This script parses a PE formatted file (EXE/DLL) and extracts the # message resources out of the .rsrc section. They are then written to # a database file. # # Original PE header code borrowed from the pymavis project. # For more information, see: http://www.mplayerhq.hu/~arpi/pymavis/ # # Copyright (C) 2005-2006 Timothy D. Morgan # Copyright (C) 2004 A'rpi # # 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 version 3 of the # License. # # 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. # # vi:set tabsize=4: # $Id: grokevt-ripdll 118 2011-06-20 16:06:43Z tim $ import os import sys import string import struct import traceback import dbm from grokevt import * # XXX: this whole script needs sanity checks on all data read, and on # length of data read. It may also be best to switch to using mmap # instead of using so many seeks. def usage(): sys.stderr.write("USAGE:\n") sys.stderr.write(" %s \n\n" % os.path.basename(sys.argv[0])) sys.stderr.write("grokevt-ripdll is a tool for extracting message resources") sys.stderr.write(" from a PE-formatted file.\nPlease see the man page for more") sys.stderr.write(" information.\n\n") def unpack(fmt,f): return struct.unpack(fmt,f.read(struct.calcsize(fmt))) def find_name_dir(f,num_dir_names,num_dir_ids): ret_val = None f.seek(f.tell()+8*num_dir_names) for i in range(0,num_dir_ids): (type_id, type_offset) = unpack("=32: sect_name+=c if sect_name == '.rsrc': f.seek(sect_off) (rsrc_flags,date,majver,minver, num_dir_names,num_dir_ids) = unpack("=0x40: try: # new-exe: f.seek(startoff+0x3c) ne_off,=unpack(" %s" % (repr(k),repr(v))) db.close() grokevt-0.5.0/doc/0000755000175000017500000000000011577710546012123 5ustar timtimgrokevt-0.5.0/doc/Makefile0000644000175000017500000000231011577677746013575 0ustar timtim# $Id: Makefile 119 2011-06-20 17:14:14Z tim $ sh-var-F=$F MAN_PAGES=1/grokevt-addlog.1 1/grokevt-builddb.1 1/grokevt-dumpmsgs.1\ 1/grokevt-findlogs.1 1/grokevt-parselog.1 1/grokevt-ripdll.1 7/grokevt.7 build: mkdir -p $(BUILD_DOC)/devel cp *.docbook $(BUILD_DOC) cp devel/*.txt $(BUILD_DOC)/devel mkdir -p $(BUILD_DOC)/man/man1 mkdir -p $(BUILD_DOC)/man/man7 for F in $(foreach p,$(MAN_PAGES),man/man$(p).gz);\ do cp $(value sh-var-F) $(BUILD_DOC)/$(value sh-var-F); done install: mkdir -p $(MAN_PREFIX)/man1 mkdir -p $(MAN_PREFIX)/man7 ln -sf $(DOC_PREFIX)/man/man1/* $(MAN_PREFIX)/man1 ln -sf $(DOC_PREFIX)/man/man7/* $(MAN_PREFIX)/man7 #XXX: Used during release only $(foreach p,$(MAN_PAGES),man/man$(p)): docbook2x-man --to-stdout $(notdir $@).docbook \ | sed 's/.SH DESCRIPTION/\n.SH DESCRIPTION/' | sed 's/^\\fR.PP$$/\\fR\n.PP/' > $@ $(foreach p,$(MAN_PAGES),man/man$(p).gz): $(foreach p,$(MAN_PAGES),man/man$(p)) gzip -c -9 $(subst .gz,,$@) > $@ && rm $(subst .gz,,$@) release: $(foreach p,$(MAN_PAGES),man/man$(p).gz) release-clean: rm -f $(foreach p,$(MAN_PAGES),man/man$(p)) rm -f $(foreach p,$(MAN_PAGES),man/man$(p).gz) rm -f $(foreach p,$(MAN_PAGES),$(basename $(notdir $(p))).txt) grokevt-0.5.0/doc/devel/0000755000175000017500000000000011577710546013222 5ustar timtimgrokevt-0.5.0/doc/devel/format.txt0000644000175000017500000001273510427472367015262 0ustar timtimWindows Event Log Format Reference ================================== Information on the header and cursor records is courtesy of Andreas Schuster. The log record format is a combination of information from Jamie French and Tim's own guess & check, and additions by Andreas. Please see references.txt for more information. Header Record ============= 0. 32bits, little endian record length in bytes, which is always 0x30 1. char[4] magic number, always "LfLe" 2. 32bits, little endian unknown (always 1, possibly part of a format version number) 3. 32bits, little endian unknown (always 1, possibly part of a format version number) 4. 32bits, little endian offset from beginning of file to the first record 5. 32bits, little endian offset from beginning of file to the next record to be written (or is this really the cursor record?) 6. 32bits, little endian number of the next record to be written 7. 32bits, little endian number of the first record 8. 32bits, little endian filesize in bytes (unreliable?) 9. 32bits, little endian flags: 0x1 (DIRTY): This flag is set upon the first write. In my opinion it is the most important flag. If it is set, you can't rely on any of the other fields provided in the header record. 0x2 (WRAPPED): This flag indicates a wrapped log. That means, the newest event record is at a lower offset than the oldest one. This flag is updated only during shutdown of the service. 0x4 (LOGFULL): This flag is set as soon as a record could not be written because there's not: 1. enough free space left in the file AND 2. the file could not grow any further (no space left on device, MaxSize reached) AND 3. AutoBackupLogFiles is not configured AND 4. Retention does not allow to overwrite the oldest event record. 0x8 (PRIMARY): I doubt that I completely understand this flag. It's set in all configured and active log files I've seen so far. It's cleared in all files written by BackupEventLog(). Maybe this flag is used to disable some checks while opening the file. For sure I'll still have to spend some time playing around with that flag. 10. 32bits, little endian retention period in seconds 11. 32bits, little endian length repeated, always 0x30 Cursor Record ============= 0. 32bits, little endian record length in bytes, which is always 0x28 1. 128bits magic number, which is always: "\x11\x11\x11\x11\x22\x22\x22\x22\x33\x33\x33\x33\x44\x44\x44\x44" 2. 32bits, little endian offset from beginning of file to the first log record 3. 32bits, little endian offset from beginning of file to the next record to be written (or last record in file which has already be written?) 4. uint32, little endian number of the next record to be written 5. uint32, little endian number of the first record 6. 32bits, little endian length repeated, always 0x28 Log Record ========== 0: 32bits, little endian Length of record, in bytes, including these 4 bytes 1: 32bits, fixed value Magic number, with value: 1001100011001100100110001100101b or 0x4c664c65 or "LfLe" 2: 32bits, little endian Message Number 3: 32bits, little endian Date Created UTC/GMT, in seconds since the epoch(unix?). 4: 32bits, little endian Date Written UTC/GMT, in seconds since the epoch(unix?). 5: 32bits, little endian Event ID and Offset High two bytes are the offset into the windoze DLL which holds the messages. The two low order bytes are what is displayed to the user as the Event ID. The number taken as a whole is used to grab the message from the DLL using the windoze FormatMessage() call. 6: 16bits, little endian Event Type One of 5 values. 7: 16bits, little endian String Count The number of strings in the event? Not always accurate? 8: 16bits, little endian Category 9: 16bits UNKNOWN 10: 32bits UNKNOWN 11: 32bits, little endian Strings Offset Pointer to a sequence of NULL terminated UTF-16 strings (NULL == '\x00\x00') used in the message template. This pointer is relative to the very beginning of the record. The end of the strings section appears to be the beginning of the other data section. 12: 32bits, little endian SID string length Set to 0 if it isn't included. 13: 32bits, little endian SID pointer This pointer is relative to the very beginning of the record. 14: 32bits, little endian Other data length Length of supplimentary data included in log. 0 if none exists. 15: 32bits, little endian Other data pointer This pointer is relative to the very beginning of the record. 16: variable length fields 16.1: NULL terminated UTF-16 string (NULL == '\x00\x00') The windoze log source. This value is used to look up (using the registry) what DLLs need to be searched for the proper EventID message template. 16.2: NULL terminated UTF-16 string (NULL == '\x00\x00') Computer Name which generated the log entry. 16.3: General buffer. Everything here is pointed to by the pointers in fields 11, 13, and 15. grokevt-0.5.0/doc/devel/references.txt0000644000175000017500000000272010430235270016064 0ustar timtimEvent Log Format ================ The best reference found to date on the format: Schuster, A. (2005). Windows Eventlogs in der forensischen Analyse. In M. Thorbr?gge (Ed.), Proceedings of the 12th DFN-CERT Workshop "Sicherheit in vernetzten Systemen", Hamburg, March 2005 (pp. D1-D16). ISBN: 3-00-015369-1 And the associated presentation slides: http://www.dfn-cert.de/events/ws/2005/dfncert-ws2005-f4.pdf The info by Jamie French (aka Malik) which inspired the creation of GrokEVT: http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html Helpful chapter from "Windows NT Event Logging" (O'Reilly): http://www.oreilly.com/catalog/winlog/chapter/ch02.html#40421 Other References ================ Micro$oft's PE executable format: http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html http://www.wotsit.org/download.asp?f=pe Language Codes (exist in .rsrc sections of PE files): http://msdn.microsoft.com/library/en-us/intl/nls_238z.asp FormatMessage(): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/debug/base/formatmessage.asp http://msdn.microsoft.com/library/en-us/tools/tools/message_text_files.asp Converting binary SID's to text: http://blogs.msdn.com/oldnewthing/archive/2004/03/15/89753.aspx Event Types: http://technet2.microsoft.com/WindowsServer/en/Library/7e77c2f0-8835-4bea-b972-26edb2aceb3d1033.mspx System Error Codes: http://msdn.microsoft.com/library/en-us/debug/base/system_error_codes.asp grokevt-0.5.0/doc/grokevt-addlog.1.docbook0000644000175000017500000001017411577677746016556 0ustar timtim grokevt-addlog 1 File Conversion Utilities grokevt-addlog A tool for adding a raw event log to an existing GrokEVT database. SYNOPSIS grokevt-addlog database-dir evt-file new-type base-type DESCRIPTION grokevt-addlog takes a raw event log (.evt file) and adds it to a pre-built database generated by grokevt-builddb(1). This new log file will be set up to use the message templates of another log, as determined by the user. This tool is primarily useful for processing deleted logs and log fragments found on a system. While it is possible to use the database generated from one system with the logs of another, this is not recommended for investigations unless no alternatives exist. ARGUMENTS grokevt-addlog uses the following arguments: The base directory for the database generated previously by grokevt-builddb(1). The file to be added to the database. The new log type/name that evt-file will take on. This is the name that will need to be used later with grokevt-parselog(1) to access the new log. This type must not already exist in the database. The existing log type that this new log will be based on. The message templates from this type will be used with the new log when parsing. This type must exist in the current database. BUGS Probably several. This particular script has not been extensively tested. CREDITS Written by Timothy D. Morgan. LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-builddb(1) grokevt-dumpmsgs(1) grokevt-findlogs(1) grokevt-parselog(1) grokevt-ripdll(1) grokevt-0.5.0/doc/grokevt-builddb.1.docbook0000644000175000017500000001207611577677746016734 0ustar timtim grokevt-builddb 1 File Conversion Utilities grokevt-builddb Builds a database tree based on a single windows system for the purpose of event log conversion. SYNOPSIS grokevt-builddb [ -c CSID ] config-profile output-dir DESCRIPTION grokevt-builddb uses grokevt-ripdll(1) and reglookup(1) along with information found in configuration files to extract all necessary information from a windows installation for the conversion of event log files. The registry is read to determine the locations of critical DLLs and the event log files themselves. This, and other information out of the registry is stored in a directory structure which acts as a kind of flat-file database. This database can then be used by grokevt-parselog(1) to generate human-readable output. The key to successfully running this utility is proper configuration. Please see grokevt(7) for information on what needs to be configured. ARGUMENTS This is the name of the configuration profiles stored in the global configuration directory under the directory 'systems'. See grokevt(7) for more details on how to properly configure a system profile. The path to the location of the output database. If anything already exists in this directory, it may be overwritten or deleted. OPTIONS This option allows one to explicitly set which ControlSet in the registry is used to extract event log message mappings. If specified, this item must be a positive decimal integer. If unspecified, grokevt-builddb will attempt to determine the best ControlSet by looking at the most recent CurrentControlSet, stored in the system registry under the path '/Select/Current'. Most users should ignore this option unless there is a specific reason why the last CurrentControlSet should not be used. EXAMPLES To generate a database at '~/win2k.grokevt' based on the system configuration profile 'win2k': grokevt-builddb win2k ~/win2k.grokevt To repeat the last command, instead using registry information explicitly from /ControlSet002: grokevt-builddb -c 2 win2k ~/win2k.grokevt BUGS Probably a few. This script has not been extensively tested with some guest platforms. The databases built with this script may not be portable to other systems, depending on the database drivers installed and used in Python. CREDITS Written by Timothy D. Morgan. LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-addlog(1) grokevt-dumpmsgs(1) grokevt-findlogs(1) grokevt-parselog(1) grokevt-ripdll(1) reglookup(1) grokevt-0.5.0/doc/grokevt-dumpmsgs.1.docbook0000644000175000017500000000666011577677746017170 0ustar timtim grokevt-dumpmsgs 1 File Conversion Utilities grokevt-dumpmsgs A tool for dumping the contents of message databases built previously by grokevt-ripdll(1). SYNOPSIS grokevt-dumpmsgs message-db1 [message-db2 ...] DESCRIPTION grokevt-dumpmsgs takes one or more message databases previously built with grokevt-ripdll(1) and prints out all entries to stdout. This is mainly a debugging tool, but may be useful for analyzing the message contents of PE files while developing other applications. ARGUMENTS grokevt-dumpmsgs uses the following arguments: If multiple message databases are supplied, entries of all databases are printed to stdout in the order they are provided. OUTOUT grokevt-dumpmsgs prints each database entry out on a single line, in two comma-separated columns. The first column is the message ID, which is in the format: XXXX-YYYYYYYY Here, XXXX represents the message's language code, and the YYYYYYYY represents the message's relative virtual address (RVA) within the message block of the PE file. The second column contains the message itself. Messages containing special characters (such as newlines or commas) are encoded in the same manner that grokevt-parselog(1) encodes them ("%XX" where XX is the hexadecimal value of the character). BUGS Probably several. This particular script has not been extensively tested. CREDITS Written by Timothy D. Morgan. LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-addlog(1) grokevt-builddb(1) grokevt-findlogs(1) grokevt-parselog(1) grokevt-ripdll(1) grokevt-0.5.0/doc/grokevt-findlogs.1.docbook0000644000175000017500000001052411577677746017130 0ustar timtim grokevt-findlogs 1 File Conversion Utilities grokevt-findlogs Attempts to find log file fragments in raw binary files, such as memory dumps and disk images. SYNOPSIS grokevt-findlogs -? grokevt-findlogs [-v] [-h] [-H] [-o offset] raw-file DESCRIPTION grokevt-findlogs searches a raw binary file for event log records. It produces a simple comma-separated values (CSV) output to stdout which includes metadata and offsets of any hits. Using the metadata and offset/contiguity information, it should be easy to determine if the hits are false positives or not. ARGUMENTS The binary file to be searched. OPTIONS Prints a basic usage statement. Verbose mode. Prints status messages to stderr, which can be helpful for debugging. (Currently does nothing.) Prints a header row at the top of the CSV output containing labels for each column. (This is the default behavior.) Disables the printing of a header row. This is useful when grokevt-findlogs is used in a script. Begin search at this byte offset within the binary file. BUGS Probably a few. This script has not been extensively tested with some guest platforms. There are likely some speed improvements that could be made. CREDITS Written by Timothy D. Morgan LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-addlog(1) grokevt-builddb(1) grokevt-dumpmsgs(1) grokevt-parselog(1) grokevt-ripdll(1) grokevt-0.5.0/doc/grokevt-parselog.1.docbook0000644000175000017500000001755311577677746017150 0ustar timtim grokevt-parselog 1 File Conversion Utilities grokevt-parselog Parse a windows event log and generate human-readable output based on message resources stored in a database. SYNOPSIS grokevt-parselog -?|--help grokevt-parselog -l database-dir grokevt-parselog -m database-dir log-type grokevt-parselog [-v] [-H] [-h] database-dir log-type DESCRIPTION grokevt-parselog reads a windows event log (.evt file) and combines that information with messages templates and other resources stored in a pre-generated database. This is then printed to stdout in a comma-separated values (CSV) format. The database must first be created by grokevt-builddb(1). ARGUMENTS This is the directory where the database is stored. Currently, the actual log files from the original system are also stored in this directory tree. This is the windows name for the log. By default windows has the following logs: Application Security System But others may have been created by third party software. Use the -l option to print a list of all available log types. (The log names are case-sensitive.) OPTIONS Prints a basic usage statement. Same as -?. Log list mode. Lists the logs available in the specified database. Meta information mode. Lists meta information stored in the header of the specified log file. Does not print any actual log records. (Format of output in this mode is still subject to change.) Verbose mode. Prints status messages to stderr, which can be helpful for debugging. Prints a header row at the top of the CSV output containing labels for each column. (This is the default behavior.) Disables the printing of a header row. This is useful when grokevt-parselog is used in a script. OUTPUT While the output format is compatible with programs (such as spreadsheets) that understand the de-facto CSV standard format, the format is additionally constrained in that each log entry is written to a single line. Also, special characters and non-printable characters are encoded using a URL-like encoding format of "%XX" where XX are the hexadecimal digits of an encoded character. New line characters and other special characters along with binary data are encoded this way to allow for easy use of grep(1) and similar command line tools. EXAMPLES To list all available logs types stored in '~/example.grokevt': grokevt-parselog -l ~/example.grokevt To read the 'Application' log from the database stored in '~/example.grokevt' and print it to stdout: grokevt-parselog ~/example.grokevt Application To read the 'System' log from the database stored in '~/example.grokevt' and print it to stdout without a header, and with verbosity turned on: grokevt-parselog -v -H ~/example.grokevt System BUGS Probably a few. This script has not been extensively tested with some guest platforms. The file event log file format is pretty well understood and implemented, but some diabolical wrapped, dirty, or fragmentary logs may not be correctly parsed. Unicode support is currently limited. Any suggestions on how to better handle unicode output would be appreciated. CREDITS Originally written by Jamie French. Converted to Python and extended by Timothy D. Morgan. Andreas Schuster has contributed greatly to the understanding of the event log format. LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-addlog(1) grokevt-builddb(1) grokevt-dumpmsgs(1) grokevt-findlogs(1) grokevt-ripdll(1) grokevt-0.5.0/doc/grokevt-ripdll.1.docbook0000644000175000017500000000734111577677746016614 0ustar timtim grokevt-ripdll 1 File Conversion Utilities grokevt-ripdll A tool for extracting message resources from a PE-formatted file. SYNOPSIS grokevt-ripdll input-dll output-db DESCRIPTION grokevt-ripdll parses a PE-formatted file (modern .exe and .dll files are examples PE-formatted files) and extracts all message resources. These resources are then stored in a Berkeley-style database file, which maps relative virtual addresses (RVAs) to the message resources themselves. These RVAs are what can be found in a windows event log file (.evt extension) to reference the proper message resource. This utility is not intended to be used directly by end-users. It is used by grokevt-builddb(1) to extract resources from all DLL/EXEs referenced in the registry. ARGUMENTS This is the PE formatted file to extract resources from. (It doesn't need to have a .dll extension, but it is most commonly used on DLLs.) The database file to store the RVA->message mapping in. If this file already exists, it will be overwritten. To extract the entries stored in this database, see grokevt-dumpmsgs(1). BUGS Probably a few. This script has not been extensively tested with some guest platforms or with non-english systems. The documentation used as a reference for PE formatted files was not complete or not completely accurate in places. Much guess-and-check took place. CREDITS Original PE header code borrowed from the pymavis project. For more information, see: http://www.mplayerhq.hu/~arpi/pymavis/ Message resource parsing added by Timothy D. Morgan. LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt(7) grokevt-addlog(1) grokevt-builddb(1) grokevt-dumpmsgs(1) grokevt-findlogs(1) grokevt-parselog(1) grokevt-0.5.0/doc/grokevt.7.docbook0000644000175000017500000002427111577677746015337 0ustar timtim grokevt 7 File Conversion Utilities GrokEVT a collection of scripts built for reading windows event log files. DESCRIPTION This document serves as an overview to using the GrokEVT suite of tools. Please see the man pages for each tool for specific command-line options. USING Using GrokEVT on a set of windows partitions is a three stage process. One must first mount the partitions and configure the system's profile. Next, grokevt-builddb(1) must be run to extract the necessary information from these partitions. Finally, grokevt-parselog(1) may be run to use this information to convert the logs to something useful. Mounting and configuration: This is the most labor-intensive step of the process. There are several technical reasons why this cannot be simpler, and it is unlikely many will be resolved anytime soon. (Sorry, blame the vendor who produced these logs that you wish to convert.) First mount the partitions used by your windows system. Specifically, mount any partition that has software installed on it. (You can probably get away with not mounting ones with no software, or no software that produces events in the event log.) This includes windows shares, if you have any with software installed on them. The key point when mounting partitions or shares, is that you must mount them with case-insensitive filenames. To do this in Linux, you should be able to use the NTFS option 'posix=0', or with type vfat this appears to be the default. On FreeBSD, one can use the -i option with NTFS and mount_ntfs, but this hasn't been tested. (More research is necessary in this area. Please let me know if case-insensitivity is available on other *NIXes and what the options are.) All of this, of course, depends on your version of mount and related software. See mount(8) for more information. Once you have all necessary filesystems mounted for your windows image, you need to configure GrokEVT so it knows where everything is. If you look in the main configuration directory, (by default at '/usr/local/etc/grokevt') you'll find a sub-directory called 'systems'. In there is a set of system configuration profiles. Each directory under 'systems' represents the configuration for a single windows host. You may create directories here of any name. It is suggested you use the host name of the system you wish to extract logs from. By default, there will be one system configuration there already, named 'example'. I suggest you make a full copy of this, and edit it from there to create your own configuration: # cd /usr/local/etc/grokevt/systems # cp -r example mysystem Now that you have your own configuration, take a look at the files under this directory: path-vars/%SystemRoot% system-registry drives/c: drives/d: Each file represents a single configuration setting. The first line of every file is the setting, all others are ignored. You should start by configuring your drive letters. These drive letters need to map to the *NIX path of the drives. So, if you mounted your C: partition under '/mnt/win/c', then you should do the following: echo /mnt/win/c > drives/c: This will of course, overwrite that file with your actual mount point for the C: drive. Do this for all drives mounted on your windows system. Next, you need to configure your %SystemRoot% path variable. Since the registry often references files in relation to this variable, we need to know where it is on your system. Typically, on W2K this should be 'C:\WINNT'. On other windows systems it is often 'C:\Windows'. This case-insensitive path must as a full windows path (including a drive letter). Finally, you need to set the path of the system registry. This path must be a *NIX path, and not a windows path, and it is case-sensitive. It should be located under your %SystemRoot%. For instance, if you mount a W2K machine's C: on '/mnt/win/c', this path will probably be: /mnt/win/c/WINNT/system32/config/system This will vary from system to system, but if you have ever done any forensics, you should be able to find the correct path pretty quickly. Using grokevt-builddb(1): Once you get past the mounting and configuration step, you're in good shape. To extract the necessary information from the system you just mounted, you just need to decide where you want to store the output database. Based on the example paths above, one could run grokevt-builddb(1) like so: grokevt-builddb mysystem /var/db/grokevt/mysystem Or something similar. This step will take some time, as a lot of files need to be parsed. You will likely get some warnings about missing DLLs and possibly service removals. This is normal if software on the windows system failed to clean up the registry correctly when it was un-installed. You might want to record this information though, if later you find you are missing a lot of message templates in your log output. Now that you have finished this step, you have fully extracted all information needed to interpret the event logs. Using grokevt-parselog(1): To run grokevt-parselog(1), you must specify the database directory that you generated with grokevt-builddb(1). Initially, you will want to find out what event logs were extracted by running: grokevt-parselog -l /var/db/grokevt/mysystem This will print out all available event log types, based on information found previously in the system's registry. Then you may view one of those logs simply by dropping the -l option, and adding it's name as the second parameter. For instance, to view the 'System' log: grokevt-parselog /var/db/grokevt/mysystem System See the grokevt-parselog(1) man page for further options. Finding and Parsing Log Fragments: One may find it useful to parse deleted log files or fragments of log files found in a system's RAM dump. A special-purpose tool, grokevt-findlogs(1) is included in this distribution which makes finding log fragments easy. It can find even a single log record by itself with a relatively low rate of false positives. Suppose one has a file, dump.img, which contains an image of a system's RAM, or perhaps the unallocated blocks of a filesystem (as might be produced by The SleuthKit's dls(1)). One could search this dump by running: grokevt-findlogs dump.img This will produce a listing of all hits in the file, which may include header records, cursor records, or log records, offsets and contiguity information to help one eliminate any false positives. Supposing we found a log fragment in this dump that we're interested in, we could simply use dd(1) or some other tool to carve out the relevant data in to a file named fragment.evt. We'd then need to find a way to associate this log with a set of message templates. This is what grokevt-addlog(1) is for. Let's take a guess that the fragment.evt was originally a part of System log. We would add the log into our previously built message database by running: grokevt-addlog /var/db/grokevt/mysystem fragment.evt System-fragment System Finally, we can parse the log by simply specifying the newly imported name with grokevt-parselog(1): grokevt-parselog /var/db/grokevt/mysystem System-fragment If we found that most of the log entries didn't have associated message templates (which would result in lots of warnings to stderr), we would be pretty that fragment.evt really wasn't based on a System log. Simply re-importing it as another log type (and a different name) would let us parse it again as if it were of another type. Please see the grokevt-findlogs(1) and grokevt-addlog(1) man pages for more information. CREDITS This man page written by Timothy D. Morgan LICENSE Please see the file "LICENSE" included with this software distribution. 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 version 3 for more details. SEE ALSO grokevt-addlog(1) grokevt-builddb(1) grokevt-findlogs(1) grokevt-parselog(1) grokevt-ripdll(1) reglookup(1) grokevt-0.5.0/doc/man/0000755000175000017500000000000011577710546012676 5ustar timtimgrokevt-0.5.0/doc/man/man1/0000755000175000017500000000000011577710547013533 5ustar timtimgrokevt-0.5.0/doc/man/man1/grokevt-addlog.1.gz0000644000175000017500000000211611577710547017145 0ustar timtimfMgrokevt-addlog.1uUMo6W  l$.ǐzDRAR?6$ oͼ庐MZ;6Y$KZ7èEoonD%~eQ!hz z=4Ejvy΢*77EtE4HK%h7a TIaq6`QHӔYhLNkE6#'w$D;9M!]Z17;q+.,a}rvCFFn=|qq7M&lΞ8M؟2Fp!(%<#ik(krG*TFDAXsSCDFZB{`I(dv[ZX+zjIHCW- S˦ AMK5Fw(ۮc[sDm)>q@/4Q 6[rxt مF=ȻMH:D=ѻK;2"5(<Җ)TqZj$Pfw5VOEzA^؆4J ?c~~aL@;m!;t;&ukс8:IB&HXx?rz* {k] B?hNDpdWӝԈ.| }<Ԗ+^bVL?>%Vօse/]!x6=b9ua킘'^ PwxSeGQ7!8Qb=5/w!aK3A{pɼUܐ͍:n2!6u9."o諃ӻdbWZ*kԞ"zҦM9MdʖJxZ- A8@rz䑙եqA#N ~+чIw^^l+OzϫƋWzxkp$:&}^޸={ƓGogYJY& ?S-q:㘖xL#J:a0mdNsȂOakm_\*ەrL4'σ pa칭_G?'` `aGrS+)\{ D~*^ڌ?:J/)V)⧔I~ejyUPf,W&#JO.(_<,Y,6٧9QBl6gwxM?dz7P/cԾ(  d5[gWNzVWi_ݼ!Yd.7橮Bnʝ8h']BzF135v꒚tj.#%Gސ[x|R%9i)a..z@P1 #Y#owu,eue i(^ Ct󈖹z7 J-=Ԡ Ri ՗b$C+gKYK%_MP_=q$ j4anQ|Q D'Nq{sD6Td{CCBgY}A(93}DB)ԕsMڋB~:!<RRqZ*mtDZg?ZϏ'_(1UHMl\' ||71ZZ]t}qn΂mdUZќU*љVj %Q PKvQryN*[zlĦ( @y5]貓 bwma$9<;{S+YGF]fi N,]c#2xf4Fӿ4&%0~ϓl*ٵ4 _"*F~¿6ئGvҋA"ʴ4TCM(YA<5%z2soO:/YX,-j3%eA19VмhU:{= vYf ߑ刓'wD|eV)-6Q{RAj5n#-%,MVӻ|[kGh.pґ"7v'۝d7u ArI^MQ&iH_}s h4mgeA-Ҿ00vҷƋmZᅦ&J⼤Xܿ&_i68+rZ&񊖏CI@9S㇁ en%p;_pwM%=O grokevt-0.5.0/doc/man/man1/grokevt-dumpmsgs.1.gz0000644000175000017500000000217511577710547017557 0ustar timtimfMgrokevt-dumpmsgs.1uQo8)FNKW%Z'V+Q9QpmNֱrI`CHg7|0 8=_[ .p5-H=@eu#ԛV05՗x;!9LrcVtB 'g0<|pZK(oƂ9֮W΂.ҊV6onjLӈ r8|QJ<~jtMA餽6LIgb~^?09\ZAIU[*E8R0u dka5 oUSU-Ez1>Xe˦#MI0'q%6n{KvGam;Г~γI#>߶J-ڇF@C$7҉&EƶpvynĻ09EjцaAk YWb}k8-8m}. KĬP#nr]ӑjOв!c]om=Nt{ }U]䟇73~K9>nIP BԼʴmO~ N .Z {pr *2ߓV}獽 (V(\ծ3*RE>~A";kʯ$&<. WWd'V]x?c!:v%Rs4hnd8 ~EaWas>j'ٞW;r~ҙ$k$Jr oAmDFn7wSeO 4 ><+tq cDCF<ݓ:Xό ^ΣnW!La= `YLCXo* {w aF(Xw_Ȍʇp@ K:E.Q4tFǙ>ӛhEΚ_Ty.5UҞ(i,WVtCDgrokevt-0.5.0/doc/man/man1/grokevt-parselog.1.gz0000644000175000017500000000374711577710547017542 0ustar timtimgMgrokevt-parselog.1WnG}q6rdDY t!xm~ht!oϩ$kܷ:uT٢'e2cW?:UHE\.yIGXݼ^V,$Wׯ"ɴObwrq^(r8w"IvR"˕wMW]wʟkozwg -ohrMa{=Lq(N^Z~Jn6H6JT6+mWQu]*Zej [URI,uj>A<ۙ&x:E~}Q.*ND2}|=όǩ?QqُJ_qO?_cv8Ƴi& LԕKcl\XsK)[]˪@ŵT^fiȐvt!]xS~ooTQ/q-bweYRnem,[_]4<L>O)`, 2wUbMo'Y7kqDz"ojr#**r;ܻRЎfe,.U*;1¾8^[odxilJM`"N'z'2Ck\]Q8,dAbG! 0)3T7qjc{F$q|3,l4q$8%r R]4L`OaB.Te Jy>ka#RރS˪#[rB1  L )' Η A悵p}J)BOSb~ ]RQtjrs\t/?^恛5E{ _[]rN(%wljſ?CF$4(ZetCthtT-O4G{6d$".2W 7V"&& "յQelK+uiG"VRV5hdő h!ot(h[i7Uldy>gfֵ&} gļ{K*V^P#P?TܨZp!"Qh2Mq /+Bc֞PYf(=0g_ % Y[(W," DN$$68 yAEYg,B[Lx0[{xZ0j9ǧO|ĊDA JM E {|o3Oz>vioEP889AWwsn̈́ u4 =-SB|Ӿ&:W+Op*fD 0t%ً7ّuq"A(\{QȺ}-X_s\yNd^Q÷qjNNxQ g7L hV+(!*(ւUTT,Pj9,Bi=oT|J)*!00D,6HkOC**P Y ? iD=K6ne]Y@r+填iwlij'x΂د L!CI z!@0"!ZXΑ=犣<'no-F+T$AAFY"| }{teTMJ#ek#x<4&iHpVh_Z1B>9!+ZͶ?_^laS):WD9P^7k 8=褫YڴX-,[d 3**FBmji+{j h e~vEfݫ[eZOpl*mW# LOUH 87r#|Cb7|K+@yHla}et~9=0տQ՞VŸ/XTP#? W{3hWfUOt:giZl (u[<6;ufF=vx~` >S9z_ I>nˌƳ;>N,#„ q$J%=.n WrdqrqtyY\MYt5O.I6XN -b=qv=[ҵPZ494'T -㲶})ixn85Lt?4ߘoVU_ۇcK:grokevt-0.5.0/doc/man/man7/0000755000175000017500000000000011577710547013541 5ustar timtimgrokevt-0.5.0/doc/man/man7/grokevt.7.gz0000644000175000017500000000706011577710547015734 0ustar timtimgMgrokevt.7Yko d?p 8؆%7 VbDI!;3$mm 4"=@|"Sju&;w\j ]:LV2ɜ$W._\&LˇkX\ ,G$KgvMR">M+( UZ͛ype -/lэ3)Lko"}7.p\HB-nsԭm#j5UfNꍮZYؕ!%}9ͧ7b6Nf6JfT lcV^c۵QיV hZ[DZ94VZpUujrԖ/;) bk :RDp~KGkմCAt\ ɢnlTe"v0= 5*7a ۹Vh,y/7k{#zB^ϲ#R˦`mJJISRqƖ됈+S 2 QABZѱSlq/\򮀋"~"O|"10PKۜՕ3)"ZËF2)><]*s >\UyŎC؋-6:Í֔x*34p߲P"q۵%.39kʝp#F%Glx'3MFD}0~F9[8 qjp.L c@ҨK V*rC2VȴpY3%L ?r m=Uv*- ֭q;`;rZ!>(etpi !#88^d %(RV<ЂbkSu_Yk]R=d7Y !93_Ä\(XZHN:`t%W`wA1BNLL;a 2jҊZ he@'0! tCEB@dx"i1qn)!TYh#];Am?P4 H9r@i|H tscΎXpKL  ILk៎LrZt[z?08GAq S8x0TnFD2c;Ϣ$(}T*|x¢23 ʵ'CE;'kN 8mzrDN`Uu[g$9,J3]BTC*C3Ekqr' Kd5 C"H_{h$k]PBobw4' ǷźuDʩGǻ/d ^mB;I.<*E%/#P'QE S>:a a3IL3!Jm!+,wW!Hrn}ٯ-ddf<{U^l@X{k'T+fGײNӳїl [REciPTZmMf.99 7301I@A ] [ !+Yw m< {)UMlYvYĺwJ+"QRS$i:aWRYAF!Cofpy=j4-lf_q5RCǖb0%}18+3e?ܚtV` Eo PCf.0 -Hኚ%yk+9r{\n]C/=\-|-ʱ*gm {g=픠)0MCXGIhÐ26!Hl}5|fCwbCxVZo.՛DD ~#$xD^]ܤ"OS 2)Q5&?@ge(Dߜ/(N9r|{?K .T1ȟ~ J)z[n"|oYqx:>~֋Z6L <jڌZssugW"3^K['{i_3ժ%wJ_MUȐ%XPwi޳)]r 7/}ik߷hǜv 98#K7&i(>=5'%.7t)| 0,1Yy}%!ȤĞݨE 3hS9[Pj{ƣ#x`#9MoHiVCNeB\3\ ]hidt:('EF XW \ݧ{%Gacwt׈ _|7rD BoJWa:2)h:Eso9(^K@j'W4 q?%uCm iD1FaJ;]'TFBN4zcl] 5MдV[Yvhf}q~P i!'&[Z0qF9` 'WTqRwMMLҁIf+d"C&&`.k릕L+%9@tw&m?5,o!dz&_ao\inV] r_c»c1R+X)!o`sVi1;)BZ+jN}@()F(;nQ(y+xq7.i5L* 07G_rlDɇ[8Љ٘gwOX2»K\wl TgX H{N %d~ }[2IKqz9tlë'?6zQœW@N~M&Ȫ9))}mOIuɑ70DnkGQՎ1x= y?R𙼛#q-`!4vUz[Pm(^=i- bP0xɪIa/[C>Hh!bC^ h6B3@ -+J0f &~ \&39o8HxMABXmq eenHmY;}U̲'o-g|hD*B;>lR?v=]>׍9 x0TfFk\]qvu؄ڷ"ǂۇ<"?ߟ̿9r]s(RM}z:BL{5\f]|zp}~/ng 1͇;Bu¤[5?r'Q4 |^./@ យx_5Zc( ze?w5U!grokevt-0.5.0/etc/0000755000175000017500000000000011577710546012131 5ustar timtimgrokevt-0.5.0/etc/Makefile0000644000175000017500000000043410254412450013552 0ustar timtim# $Id: Makefile 9 2005-06-17 00:11:20Z tim $ ################################################################################ SYSTEMS=$(BUILD_ETC)/systems FILES=$(SYSTEMS) all: $(FILES) $(SYSTEMS): rm -rf $(SYSTEMS) cd systems && find . | grep -v '\.svn' | cpio -pmd $(SYSTEMS) grokevt-0.5.0/etc/systems/0000755000175000017500000000000011577710546013640 5ustar timtimgrokevt-0.5.0/etc/systems/example/0000755000175000017500000000000011577710546015273 5ustar timtimgrokevt-0.5.0/etc/systems/example/drives/0000755000175000017500000000000011577710546016567 5ustar timtimgrokevt-0.5.0/etc/systems/example/drives/c:0000644000175000017500000000001310241505531016777 0ustar timtim/mnt/win/c grokevt-0.5.0/etc/systems/example/drives/d:0000644000175000017500000000001310241505531017000 0ustar timtim/mnt/win/d grokevt-0.5.0/etc/systems/example/path-vars/0000755000175000017500000000000011577710546017200 5ustar timtimgrokevt-0.5.0/etc/systems/example/path-vars/%SystemDrive%0000644000175000017500000000000311067326234021473 0ustar timtimC: grokevt-0.5.0/etc/systems/example/path-vars/%SystemRoot%0000644000175000017500000000001310770555654021360 0ustar timtimc:\Windows grokevt-0.5.0/etc/systems/example/system-registry0000644000175000017500000000005210770555654020406 0ustar timtim/mnt/win/c/WINDOWS/system32/config/system grokevt-0.5.0/grokevt-distutils.py0000644000175000017500000000025211576211775015431 0ustar timtim# Called from make with appropriate python version from distutils.core import setup setup(name='grokevt', version='0.5', package_dir={'':'lib'}, py_modules=['grokevt']) grokevt-0.5.0/lib/0000755000175000017500000000000011577710546012124 5ustar timtimgrokevt-0.5.0/lib/Makefile0000644000175000017500000000044410254412450013546 0ustar timtim# $Id: Makefile 9 2005-06-17 00:11:20Z tim $ ################################################################################ GROKEVT=$(BUILD_LIB)/grokevt.py FILES=$(GROKEVT) all: $(FILES) $(GROKEVT): grokevt.py cp grokevt.py $(GROKEVT) echo 'PATH_CONFIG="$(ETC_PREFIX)"' >> $(GROKEVT) grokevt-0.5.0/lib/grokevt.py0000644000175000017500000006013111577670023014153 0ustar timtim# # Copyright (C) 2005-2006,2011 Timothy D. Morgan # # 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 version 3 of the # License. # # 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. # # vi:set tabsize=4: # $Id: grokevt.py 118 2011-06-20 16:06:43Z tim $ import sys import os import time import types import re import struct import dbm ################################################################################ # Constants # This information provided by: # http://technet2.microsoft.com/WindowsServer/en/Library/7e77c2f0-8835-4bea-b972-26edb2aceb3d1033.mspx eventTypeEnum = {0:'Success', 1:'Error', 2:'Warning', 4:'Information', 8:'SuccessAudit', 16:'FailureAudit'} # XXX: this probably never changes, but might be interesting to see if # it is big endian on NT Alpha/MIPS systems. source_encoding = 'utf-16le' # This is what we store message in when ripped from DLLs template_encoding = 'utf-8' # This is what we use if unicode output is enabled output_encoding = 'utf-8' # Log format constants header_log_magic = b"\x4c\x66\x4c\x65" header_version = b"\x01\x00\x00\x00\x01\x00\x00\x00" cursor_magic = b"\x11\x11\x11\x11\x22\x22\x22\x22\x33\x33\x33\x33\x44\x44\x44\x44" header_size = 0x30 cursor_size = 0x28 log_fixed_size = 0x38 min_record_size = min(header_size, cursor_size, log_fixed_size) ################################################################################ # String Formatting Functions # Reference: # http://blogs.msdn.com/oldnewthing/archive/2004/03/15/89753.aspx # # XXX: Need to replace this with calls to winsec library once winsec has a # better memory management interface def binSIDtoASCII(sid_str): rest = sid_str[8:] first = struct.unpack('BBBBBBBB', sid_str[0:8]) auth = ((first[2]<<40) | (first[3]<<32) | (first[4]<<24) | (first[5]<<16) | (first[6]<<8) | first[7]) result = "S-%d-%d" % (first[0], auth) for i in range(0,first[1]): if len(rest) >= 4: next_int = struct.unpack(' 126) or (c in specials): ret_val += ("%%%.2X" % c) else: ret_val += chr(c) return ret_val def quoteUnicode(s, specials='%\r\n'): ret_val = '' for c in s: if c in specials: ret_val += "%%%.2X" % ord(c) else: ret_val += c return ret_val # Reference: # http://msdn.microsoft.com/library/en-us/winui/winui/windowsuserinterface/resources/strings/stringreference/stringfunctions/wsprintf.asp # # returns a formatted string. def wsprintf(fmt, vars): # Python's string formatting is very close to wsprintf's. Just a # few types need to be converted to get a close approximation of # proper behavior. # XXX: However, as this isn't 100% compliant with the spec, it # should be re-written as a state-machine to be fully correct. optionals = r'(-?#?0?[0-9]*[.]?[0-9]*)' # S,ls,lS,hs,hS => s py_fmt = re.sub('%'+optionals+'[lh]{0,1}[sS]', r'%\1s', fmt) # lu,li,ld,hu,hi,hd => d py_fmt = re.sub('%'+optionals+'[lh][uid]', r'%\1d', py_fmt) # lc,lC,C => c py_fmt = re.sub('%'+optionals+'l{0,1}[cC]', r'%\1c', py_fmt) # lx => x; lX => X py_fmt = re.sub('%'+optionals+'l([xX])', r'%\1\2', py_fmt) # p => d py_fmt = re.sub('%'+optionals+'p', r'%\1d', py_fmt) return (py_fmt % vars) # References: # http://msdn.microsoft.com/library/en-us/debug/base/formatmessage.asp # http://msdn.microsoft.com/library/en-us/tools/tools/message_text_files.asp # XXX: Does someone know of a better reference for this? The author of # these pages couldn't write themselves out of a wet paper bag. def formatMessage(fmt, vars): # states: # 0: normal text # 1: in escape sequence # 3: in format string state=0 ret_val='' arg_num='' arg_index = None extended_fmt = '' for c in fmt: if state == 0: arg_index = None arg_num = '' if c == '%': state=1 else: ret_val += c elif state == 1: if len(arg_num) == 0: # ASCII digits {1..9} if ord(c) > 0x30 and ord(c) < 0x3a: arg_num = c # This probably isn't exactly correct, but it's better # than cutting off the message early. elif c == '0': ret_val += '\x00' state = 0 elif c == 'b': ret_val += ' ' state = 0 elif c == 't': ret_val += '\x09' state = 0 elif c == 'r': ret_val += '\x0d' state = 0 elif c == '\\': ret_val += '\x0a' state = 0 elif c == 'n': ret_val += '\x0d\x0a' state = 0 else: ret_val += c state = 0 elif len(arg_num) == 1: # ASCII digits {0..9} if ord(c) > 0x2f and ord(c) < 0x3a: arg_index = int(arg_num + c) - 1 else: if arg_index == None: arg_index = int(arg_num) - 1 if c == '!': state = 3 extended_fmt = '%' else: if arg_index < len(vars): if c == '%': ret_val += "%s" % vars[arg_index] state = 1 arg_num = '' arg_index = None else: ret_val += "%s%s" % (vars[arg_index], c) state = 0 else: # arg_num not in vars if c == '%': ret_val += "%%%s" % arg_num state = 1 arg_num = '' arg_index = None else: ret_val += "%%%s%s" % (arg_num, c) state = 0 elif state == 3: if c == '!': state = 0 ret_val += wsprintf(extended_fmt, vars[arg_index]) else: extended_fmt += c return ret_val def guessRecordType(record, wrapped=False): ret_val = 'unknown' # XXX: Can some of these be more strict? if (len(record) == header_size): magic = record[4:4+len(header_log_magic+header_version)] if magic == (header_log_magic+header_version): ret_val = 'header' elif (len(record) == cursor_size): magic = record[4:4+len(cursor_magic)] if(magic == cursor_magic): ret_val = 'cursor' elif (len(record) > log_fixed_size): magic = record[4:4+len(header_log_magic)] if(magic == header_log_magic): if wrapped: ret_val = 'wrapped-log' else: ret_val = 'log' return ret_val ################################################################################ # .evt log files class evtFile: # instance state f = None header = None cursor_offset = None cursor = None # Constructor for evtFile instances # Opens a log file and an associated message repository. # Optionally parses the .evt file's meta records (header and cursor). # # Raises: IOError # Resulting offset: # (error thrown) --> UNDEFINED # (parse_meta == 0) --> 0 # (parse_meta == 1 && missing header) --> 0 # (parse_meta == 1 && missing cursor) --> header_size # (parse_meta == 1 && found cursor) --> self.cursor['first_off'] # def __init__(self, filename, message_repository, parse_meta=1): self.f = open(filename, "rb") self.mr = message_repository if parse_meta: # First parse header if(self.guessRecordType() != 'header'): # XXX: should we search the file for a header and cursor # anyway? How would we trust offsets? sys.stderr.write("WARNING: Could not find header record.\n") self.f.seek(0) return self.header = self.getHeaderRecord() # Next, try to find the cursor self.f.seek(self.header['next_off']) if(self.guessRecordType() != 'cursor'): sys.stderr.write("WARNING: Header does not point "\ +"to cursor record.\n") sys.stderr.write("WARNING: Searching for cursor manually...\n") # XXX: This is kinda ugly. # Perhaps the whole file should be mmapped from the # beginning? self.f.seek(0) s = self.f.read() self.f.seek(0) if s.count(cursor_magic) > 1: sys.stderr.write("WARNING: Multiple cursors may exist."\ +" Attempting to use last one in file.\n") # Search for the cursor magic and attempt to validate the record magic_off = s.rfind(cursor_magic) if magic_off > 3: self.f.seek(magic_off-4) while (self.guessRecordType()!= 'cursor') and (magic_off != -1): magic_off = s.rfind(cursor_magic, magic_off-1) if magic_off > 3: self.f.seek(magic_off-4) s = None if magic_off == -1: sys.stderr.write("WARNING: Could not find cursor record.\n") self.f.seek(header_size) else: self.cursor_offset = magic_off-4 self.f.seek(self.cursor_offset) self.cursor = self.getCursorRecord() self.f.seek(self.cursor['first_off']) else: self.cursor_offset = self.header['next_off'] self.cursor = self.getCursorRecord() self.f.seek(self.cursor['first_off']) def tell(self): return self.f.tell() def seek(self, off, whence=0): self.f.seek(off, whence) def size(self): # XXX: is there a cleaner way to do this? cur_pos = self.f.tell() self.f.seek(0, 2) ret_val = self.f.tell() self.f.seek(cur_pos) return ret_val # Uses heuristics to determine the type of record at the current # file offset. Upon successful return, file offset remains the same. # Opon throwing an exception, offset is unspecified. # # Returns: a string indicating record type. Will be one of: # 'log','wrapped-log','header','cursor','unknown' # Raises: IOError def guessRecordType(self): if not self.f: raise IOError("Log file not open.") wrapped_log = False ret_val = 'unknown' cur_pos = self.f.tell() raw_str = self.f.read(4) if len(raw_str) == 4: (size1,) = struct.unpack('= cursor_size: if (size1 > log_fixed_size and (self.size() < cur_pos+size1)): if (self.size() < cur_pos+log_fixed_size): return ret_val wrapped_log = True self.f.seek(header_size+(cur_pos+size1-self.size()-4)) else: self.f.seek(cur_pos+size1-4) raw_str = self.f.read(4) if len(raw_str) == 4: (size2,) = struct.unpack('> 1 flag_logfull = (flags & 0x4) >> 2 flag_primary = (flags & 0x8) >> 3 ret_val = {'first_off':first_off, 'first_num':first_num, 'next_off':next_off, 'next_num':next_num, 'file_size':file_size, 'retention':retention, 'flag_dirty':flag_dirty, 'flag_wrapped':flag_wrapped, 'flag_logfull':flag_logfull, 'flag_primary':flag_primary} return ret_val # Parses a cursor record starting at the current log file offset # Resulting file offset will be set to the next record on success, # but is undefined if an exception is raised. # # Returns: a dictionary of cursor values # Raises: IOError, EOFError def getCursorRecord(self): fmt = ' 0: strs=rec_str[string_offset-4:data_offset-4].decode(source_encoding, 'replace').split('\x00') # Grab source and computer fields vstr = variable_str.decode(source_encoding, 'replace').split('\x00', 2) source = '' if len(vstr) > 0: source = vstr[0] computer = '' if len(vstr) > 1: computer = vstr[1] vstr = None # Grab SID sid = 'N/A' if sid_len > 0: sid_str = rec_str[sid_offset-4:sid_offset+sid_len-4] sid = binSIDtoASCII(sid_str) # Grab binary data chunk data = '' if data_len > 0: data = rec_str[data_offset-4:data_offset+data_len-4] # Retrieve and process message template event_rva = (event_rva_offset << 16) | event_id message_template = self.mr.getMessageTemplate(source, event_rva) message = '' if message_template: message = formatMessage(message_template, strs) else: sys.stderr.write("WARNING: Missing message"\ +" template for event record #%d. (service: %s)\n" % (msg_num, source)) event_type_str = eventTypeEnum.get(event_type, None) if not event_type_str: event_type_str = "Unknown(0x%.4X)" % event_type # Format fields and return return {'msg_num':msg_num, 'event_type':event_type_str, 'date_created':time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(date_created)), 'date_written':time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(date_written)), 'source':source, 'category':category, 'event_id':event_id, 'event_rva':"0x%s" % event_rva, 'user':sid, 'computer':computer, 'message':message, 'strings':strs, 'data':data} ################################################################################ # Message database wrapper class messageRepository: # XXX: Should this be made configurable, or do event logs implicitly # hard-code the language used at the time of writing a record via the # message ID (RVA)? In other words, does the same message in multiple # languages use the same RVA, just different language tables, or are # the RVAs different for each language (in addition to being in a # different table)? Should we base this on the default language # obtained from the registry? # XXX: The order is basically an arbitrary guess of the likelyhood of # finding logs in each of these languages. A better way of deciding # this is needed. # Codes for (en-US, de-DE, fr-FR, es-ES, Language Neutral) # See: http://msdn.microsoft.com/library/en-us/intl/nls_238z.asp languages = ("0409","0407", "040C", "0C0A", "0000") svc_dbs = {} msg_dbs = {} def __init__(self, topdir, log): # XXX: should these be opened on-demand and cached for repeated use? msg_dir = "%s/messages" % topdir dbs = os.listdir(msg_dir) for db in dbs: db = db[:len(db)-3] db_file = "%s/%s" % (msg_dir,db) self.msg_dbs[db] = dbm.open(db_file, "r", 0o644) log_dir = "%s/services" % topdir for t in ("category", "event", "parameter"): db_file = "%s/%s/%s" % (log_dir, log, t) self.svc_dbs[t] = dbm.open(db_file, "r") def getMessageTemplate(self, service, rva, lang_code=None): if lang_code: langs = (lang_code,) else: langs = self.languages service = service.lower().encode('utf-8', 'replace') for lang in langs: mdbs = self.svc_dbs["event"].get(service, None) if mdbs: mdbs = mdbs.decode('utf-8', 'replace') for mdb in mdbs.split(':'): ret_val = self.msg_dbs[mdb].get("%s-%.8X"%(lang, rva), None) if ret_val: # Templates shouldn't have any encoding issues. # If they do, we want to know about them, since this # means there's a bug in builddb. return ret_val.decode(template_encoding) return None ################################################################################ # Configuration wrapper class grokevtConfig: path_vars = {} drive_mapping = {} registry_path = '' profile_path = '' def __init__(self, config_dir, profile): # Non-profile-specific configs would be read here (if there were any). self.profile_path = "%s/systems/%s" % (config_dir,profile) # XXX: the os.access() call may not work correctly in suid situations. if not os.path.isdir(self.profile_path)\ or not os.access(self.profile_path, os.R_OK): sys.stderr.write("WARNING: Could not read profile"\ +" directory '%s'.\n" % dir) else: self.registry_path = self.readLineFromFile("%s/system-registry" % self.profile_path) self.path_vars = self.readMappingFromFiles("%s/path-vars" % self.profile_path) self.drive_mapping = self.readMappingFromFiles("%s/drives" % self.profile_path) def readMappingFromFiles(self, dir): ret_val = {} # XXX: the os.access() call may not work correctly in suid situations. if os.path.isdir(dir) and os.access(dir, os.R_OK): for k in os.listdir(dir): l = self.readLineFromFile("%s/%s" % (dir, k)) if l != None: ret_val[k] = l.decode('utf-8', 'replace') else: sys.stderr.write("WARNING: Could not read configuration"\ +" directory '%s'.\n" % dir) return ret_val def readLineFromFile(self, fp): ret_val = None # XXX: the os.access() call may not work correctly in suid situations. if os.path.isfile(fp): if os.access(fp, os.R_OK): f = open(fp, "rb") ret_val = f.readline().rstrip(b'\n\r') f.close() else: sys.stderr.write("WARNING: Could not read configuration"\ +" file '%s'.\n" % fp) return ret_val # This is only here to aide in debugging. # It will be overridden during a 'make install' below. PATH_CONFIG='/usr/local/etc/grokevt' ################################################################################ ### Below this line are build-time settings. ###