├── Dockerfile ├── LICENSE ├── README.md ├── doc ├── binxml.txt └── fileformat │ ├── [MS-EVEN6].pdf │ └── p65-schuster.pdf ├── evtx ├── chunk.go ├── event.go ├── evtx.go ├── globals.go ├── goevtx.go ├── node.go ├── parser.go ├── structs.go ├── test │ └── evtx_test.go ├── todo.txt ├── utils.go └── values.go ├── go.mod ├── go.sum ├── output ├── httpOut.go ├── kafka.go ├── output.go └── tcpOut.go └── tools ├── evtxdump ├── evtxdump ├── evtxdump.go └── makefile ├── evtxmon ├── evtxmon ├── evtxmon.go └── makefile └── makefile /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine AS build-env 2 | LABEL maintainer "Alexander Makhinov " \ 3 | repository="https://github.com/0xrawsec/golang-evtx" 4 | 5 | COPY . /go/src/github.com/0xrawsec/golang-evtx 6 | 7 | RUN apk add --no-cache git mercurial \ 8 | && cd /go/src/github.com/0xrawsec/golang-evtx/tools/evtxdump \ 9 | && go get -t . \ 10 | && CGO_ENABLED=0 go build -ldflags="-s -w" \ 11 | -a \ 12 | -installsuffix static \ 13 | -o /evtxdump 14 | RUN adduser -D app 15 | 16 | FROM scratch 17 | 18 | COPY --from=build-env /evtxdump /app/evtxdump 19 | COPY --from=build-env /etc/passwd /etc/passwd 20 | 21 | USER app 22 | 23 | VOLUME /app/data 24 | 25 | WORKDIR /app/data 26 | 27 | ENTRYPOINT ["../evtxdump"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Description 2 | 3 | This project is a parsing library for Windows EVTX log files. Our goal was to 4 | make a resilient parser which provides a nice interface to interact with the 5 | events programmatically. We opted for an event representation as a `map` which 6 | is perfect to represent BinXML tree like structure. As a consequence, it is very 7 | easy to (de)serialize events with the standard Go API. We also provide the 8 | necessary APIs to query specific values of the event. 9 | 10 | An example is better than a long talk: 11 | ```json 12 | { 13 | "Event": { 14 | "EventData": { 15 | "Hashes": "SHA1=F04EE61F0C6766590492CD3D9E26ECB0D4F501D8,MD5=68D9577E9E9E3A3DF0348AB3B86242B1,SHA256=7AE581DB760BCEEE4D18D6DE7BB98F46584656A65D9435B4E0C4223798F416D2,IMPHASH=ADB9F71ACD4F7D3CF761AB6C59A7F1E5", 16 | "Image": "C:\\Windows\\splwow64.exe", 17 | "ImageLoaded": "C:\\Windows\\System32\\dwmapi.dll", 18 | "ProcessGuid": "B2796A13-E44F-5880-0000-001006E40F00", 19 | "ProcessId": "4952", 20 | "Signature": "Microsoft Windows", 21 | "Signed": "true", 22 | "UtcTime": "2017-01-19 16:07:45.279" 23 | }, 24 | "System": { 25 | "Channel": "Microsoft-Windows-Sysmon/Operational", 26 | "Computer": "DESKTOP-5SUA567", 27 | "Correlation": {}, 28 | "EventID": "7", 29 | "EventRecordID": "116913", 30 | "Execution": { 31 | "ProcessID": "1760", 32 | "ThreadID": "1952" 33 | }, 34 | "Keywords": "0x8000000000000000", 35 | "Level": "4", 36 | "Opcode": "0", 37 | "Provider": { 38 | "Guid": "5770385F-C22A-43E0-BF4C-06F5698FFBD9", 39 | "Name": "Microsoft-Windows-Sysmon" 40 | }, 41 | "Security": { 42 | "UserID": "S-1-5-18" 43 | }, 44 | "Task": "7", 45 | "TimeCreated": { 46 | "SystemTime": "2017-01-19T16:07:45Z" 47 | }, 48 | "Version": "3" 49 | } 50 | } 51 | } 52 | ``` 53 | 54 | # Command Line Tools 55 | 56 | Some utilities are packaged with this library and can be used without any 57 | dependencies. 58 | 59 | ## evtxdump 60 | 61 | Evtxdump can be used to print in JSON format the events of several EVTX files. 62 | The events are printed ordered by time and not by their order of appearance in 63 | the file. 64 | 65 | Evtxdump can also be used to carve Events from raw data. It can be very convenient 66 | to recover corrupted EVTX or to carve deleted EVTX files from disk images. We advise 67 | you to select the option `-t` made to print the timestamp as integer at the 68 | beginning of each line of the output. This can be used later on to sort the events 69 | for timelining purposes (with `sort` command for instance). 70 | 71 | ``` 72 | Usage of evtxdump: evtxdump [OPTIONS] FILES... 73 | -V Show version and exit 74 | -brURL string 75 | Kafka Broker URL 76 | -c Carve events from file 77 | -cID string 78 | Kafka client ID 79 | -cpuprofile string 80 | write cpu profile to this file 81 | -d Enable debug mode 82 | -l int 83 | Limit the number of chunks to parse (carving mode only) 84 | -memprofile string 85 | write memory profile to this file 86 | -o int 87 | Offset to start from (carving mode only) 88 | -start value 89 | Print logs starting from start 90 | -stop value 91 | Print logs before stop 92 | -t Prints event timestamp (as int) at the beginning of line to make sorting easier 93 | -tag string 94 | special tag for matching purpose on remote collector 95 | -tcp string 96 | tcp socket address for sending output to remote site over TCP. Only for type tcp 97 | -topic string 98 | Kafka topic 99 | -http string 100 | url for sending output to remote site over HTTP. Only for type http 101 | -type string 102 | Type of remote log collector. "http" - JSON-over-HTTP, "tcp" - JSON-over-TCP, "kafka" - Kafka 103 | -u Does not care about ordering the events before printing (faster for large files) 104 | ``` 105 | 106 | ### docker version evtxdump 107 | 108 | ``` 109 | docker build -t MonaxGT/evtxdump . 110 | docker run -it --rm -v /tmp:/app/data evtxdump /app/data/log.evtx 111 | 112 | ``` 113 | 114 | ## evtxmon 115 | 116 | Evtxmon is a small command line tool used to monitor in realtime the logs as they 117 | appear in the evtx files. 118 | 119 | ``` 120 | Usage: evtxmon [OPTIONS] EVTX-FILE 121 | -V Show version information 122 | -d Enable debug messages 123 | -f value 124 | Event ids to filter out 125 | -s Outputs stats about events processed 126 | -t value 127 | Timeout for the test 128 | -w string 129 | Write monitored events to output file 130 | ``` 131 | 132 | # Known Issues 133 | 134 | Some values are not parsed (because we did not have samples to test), so if you 135 | see "UnknowValue: ..." in your output, it means it is not supported. So please 136 | provide us a sample of file so that we can implement it. 137 | -------------------------------------------------------------------------------- /doc/binxml.txt: -------------------------------------------------------------------------------- 1 | https://github.com/libyal/libevtx/blob/master/documentation/Windows%20XML%20Event%20Log%20(EVTX).asciidoc#binary_xml 2 | 3 | https://msdn.microsoft.com/en-us/library/cc231334.aspx 4 | 5 | Simple BinXML: https://msdn.microsoft.com/en-us/library/cc231354.aspx 6 | -------------------------------------------------------------------------------- /doc/fileformat/[MS-EVEN6].pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xrawsec/golang-evtx/9b04117dad513b1c51bb4afcd8f5bb2e5053c05b/doc/fileformat/[MS-EVEN6].pdf -------------------------------------------------------------------------------- /doc/fileformat/p65-schuster.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xrawsec/golang-evtx/9b04117dad513b1c51bb4afcd8f5bb2e5053c05b/doc/fileformat/p65-schuster.pdf -------------------------------------------------------------------------------- /evtx/chunk.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | 8 | "github.com/0xrawsec/golang-utils/datastructs" 9 | "github.com/0xrawsec/golang-utils/encoding" 10 | "github.com/0xrawsec/golang-utils/log" 11 | ) 12 | 13 | // ChunkString is similare to BinXMLName 14 | type ChunkString struct { 15 | Name 16 | } 17 | 18 | // StringAt : utility function to get a ChunkString object at a given offset 19 | // @reader : reader containing ChunkString struct @ offset 20 | // @offset : offset at which we find the ChunkString 21 | // return ChunkString 22 | func StringAt(reader io.ReadSeeker, offset int64) (cs ChunkString, err error) { 23 | // Backup offset 24 | backup := BackupSeeker(reader) 25 | // Offsets are relative to start of chunk 26 | GoToSeeker(reader, offset) 27 | err = cs.Parse(reader) 28 | /*if err != nil { 29 | return 30 | }*/ 31 | GoToSeeker(reader, backup) 32 | return 33 | } 34 | 35 | // ChunkStringTable definition 36 | type ChunkStringTable map[int32]ChunkString 37 | 38 | // TemplateTable definition 39 | type TemplateTable map[int32]TemplateDefinitionData 40 | 41 | /////////////////////////////// ChunkHeader //////////////////////////////////// 42 | 43 | // ChunkHeader structure definition 44 | type ChunkHeader struct { 45 | Magic [8]byte 46 | NumFirstRecLog int64 47 | NumLastRecLog int64 48 | FirstEventRecID int64 49 | LastEventRecID int64 50 | SizeHeader int32 51 | OffsetLastRec int32 52 | Freespace int32 53 | CheckSum uint32 54 | } 55 | 56 | // Validate controls the validity of the chunk header 57 | func (ch *ChunkHeader) Validate() error { 58 | if string(ch.Magic[:]) != ChunkMagic { 59 | return fmt.Errorf("Invalid chunk magic: %q", ch.Magic) 60 | } 61 | if ch.SizeHeader != 128 { 62 | return fmt.Errorf("Invalid chunk header size: %d instead of 128", ch.SizeHeader) 63 | } 64 | if ch.OffsetLastRec >= ChunkSize { 65 | return fmt.Errorf("Last event offset exceed size of chunk") 66 | } 67 | return nil 68 | } 69 | 70 | func (ch ChunkHeader) String() string { 71 | return fmt.Sprintf( 72 | "\tMagic: %s\n"+ 73 | "\tNumFirstRecLog: %d\n"+ 74 | "\tNumLastRecLog: %d\n"+ 75 | "\tNumFirstRecFile: %d\n"+ 76 | "\tNumLastRecFile: %d\n"+ 77 | "\tSizeHeader: %d\n"+ 78 | "\tOffsetLastRec: %d\n"+ 79 | "\tFreespace: %d\n"+ 80 | "\tCheckSum: 0x%08x\n", 81 | ch.Magic, 82 | ch.NumFirstRecLog, 83 | ch.NumLastRecLog, 84 | ch.FirstEventRecID, 85 | ch.LastEventRecID, 86 | ch.SizeHeader, 87 | ch.OffsetLastRec, 88 | ch.Freespace, 89 | ch.CheckSum) 90 | } 91 | 92 | //////////////////////////////////// Chunk ///////////////////////////////////// 93 | 94 | // Chunk structure definition 95 | type Chunk struct { 96 | Offset int64 97 | Header ChunkHeader 98 | StringTable ChunkStringTable 99 | TemplateTable TemplateTable 100 | EventOffsets []int32 101 | Data []byte 102 | } 103 | 104 | // NewChunk initialize and returns a new Chunk structure 105 | // return Chunk 106 | func NewChunk() Chunk { 107 | return Chunk{StringTable: make(ChunkStringTable, 0), TemplateTable: make(TemplateTable, 0)} 108 | } 109 | 110 | // ParseChunkHeader parses a chunk header at offset 111 | func (c *Chunk) ParseChunkHeader(reader io.ReadSeeker) { 112 | err := encoding.Unmarshal(reader, &c.Header, Endianness) 113 | if err != nil { 114 | panic(err) 115 | } 116 | } 117 | 118 | // Less implement datastructs.Sortable 119 | func (c Chunk) Less(s datastructs.Sortable) bool { 120 | other := s.(Chunk) 121 | return c.Header.NumFirstRecLog < other.Header.NumFirstRecLog 122 | } 123 | 124 | // ParseStringTable parses the string table located at the current offset in the 125 | // reader and modify the chunk object 126 | // @reader : reader object to parse string table from 127 | func (c *Chunk) ParseStringTable(reader io.ReadSeeker) { 128 | strOffset := int32(0) 129 | for i := int64(0); i < sizeStringBucket*4; i += 4 { 130 | encoding.Unmarshal(reader, &strOffset, Endianness) 131 | if strOffset > 0 { 132 | cs, err := StringAt(reader, int64(strOffset)) 133 | if err != nil { 134 | if !ModeCarving { 135 | panic(err) 136 | } 137 | } 138 | c.StringTable[strOffset] = cs 139 | } 140 | } 141 | return 142 | } 143 | 144 | // ParseTemplaTable parses the template table located at the current offset in 145 | // the reader passed as parameter and modifies the current Chunk object 146 | // @reader : reader object to parse string table from 147 | func (c *Chunk) ParseTemplateTable(reader io.ReadSeeker) error { 148 | templateDataOffset := int32(0) 149 | for i := int32(0); i < sizeTemplateBucket*4; i = i + 4 { 150 | //parse(buf, i, &tempOffsetTable[j]) 151 | err := encoding.Unmarshal(reader, &templateDataOffset, Endianness) 152 | if err != nil { 153 | // panic(err) 154 | log.DebugDontPanic(err) 155 | return err 156 | } 157 | if templateDataOffset > 0 { 158 | backup := BackupSeeker(reader) 159 | // We arrive in template data, we have to do some offset patching in order to get 160 | // back to TemplateInstance token and make it easily parsable by binxml.Parse 161 | GoToSeeker(reader, int64(templateDataOffset)) 162 | tdd := TemplateDefinitionData{} 163 | err := tdd.Parse(reader) 164 | if err != nil { 165 | //panic(err) 166 | log.DebugDontPanic(err) 167 | return err 168 | } 169 | c.TemplateTable[templateDataOffset] = tdd 170 | GoToSeeker(reader, backup) 171 | } 172 | } 173 | return nil 174 | } 175 | 176 | // ParseEventOffsets parses the offsets at which we can find the events and 177 | // modifies the current Chunk object 178 | // @reader : reader object to parse event offsets from 179 | func (c *Chunk) ParseEventOffsets(reader io.ReadSeeker) (err error) { 180 | c.EventOffsets = make([]int32, 0) 181 | offsetEvent := int32(BackupSeeker(reader)) 182 | c.EventOffsets = append(c.EventOffsets, offsetEvent) 183 | for offsetEvent <= c.Header.OffsetLastRec { 184 | eh := EventHeader{} 185 | GoToSeeker(reader, int64(offsetEvent)) 186 | if err = encoding.Unmarshal(reader, &eh, Endianness); err != nil { 187 | log.DebugDontPanic(err) 188 | return err 189 | } 190 | // Event Header is not valid 191 | if err = eh.Validate(); err != nil { 192 | // we bruteforce in carving mode 193 | if ModeCarving { 194 | offsetEvent++ 195 | continue 196 | } 197 | return err 198 | } 199 | offsetEvent += eh.Size 200 | c.EventOffsets = append(c.EventOffsets, offsetEvent) 201 | } 202 | return nil 203 | } 204 | 205 | // ParseEvent parses an Event from the current chunk located at the relative 206 | // offset in c.Data, does not alter the current Chunk structure 207 | // @offset : offset to parse the Event at 208 | // return Event : parsed Event 209 | func (c *Chunk) ParseEvent(offset int64) (e Event) { 210 | if int64(c.Header.OffsetLastRec) < offset { 211 | return 212 | } 213 | reader := bytes.NewReader(c.Data) 214 | GoToSeeker(reader, offset) 215 | e.Offset = offset 216 | err := encoding.Unmarshal(reader, &e.Header, Endianness) 217 | if err != nil { 218 | panic(err) 219 | } 220 | /*err := encoding.Unmarshal(reader, &e.Magic, Endianness) 221 | if err != nil { 222 | panic(err) 223 | } 224 | err = encoding.Unmarshal(reader, &e.Size, Endianness) 225 | if err != nil { 226 | panic(err) 227 | } 228 | err = encoding.Unmarshal(reader, &e.ID, Endianness) 229 | if err != nil { 230 | panic(err) 231 | } 232 | err = encoding.Unmarshal(reader, &e.Timestamp, Endianness) 233 | if err != nil { 234 | panic(err) 235 | }*/ 236 | return e 237 | } 238 | 239 | // Events returns a channel of *GoEvtxMap 240 | // return (chan *GoEvtxMap) 241 | func (c *Chunk) Events() (cgem chan *GoEvtxMap) { 242 | // Unbuffered Event channel 243 | cgem = make(chan *GoEvtxMap, len(c.EventOffsets)) 244 | go func() { 245 | defer close(cgem) 246 | for _, eo := range c.EventOffsets { 247 | // for every event offset, we parsed the event at that position 248 | event := c.ParseEvent(int64(eo)) 249 | gem, err := event.GoEvtxMap(c) 250 | if err == nil { 251 | cgem <- gem 252 | } 253 | } 254 | }() 255 | return 256 | } 257 | 258 | func (c Chunk) String() string { 259 | templateOffsets := make([]int32, len(c.TemplateTable)) 260 | i := 0 261 | for to := range c.TemplateTable { 262 | templateOffsets[i] = to 263 | i++ 264 | } 265 | return fmt.Sprintf( 266 | "Header: %v\n"+ 267 | "StringTable: %v\n"+ 268 | "TemplateTable: %v\n"+ 269 | "EventOffsets: %v\n"+ 270 | "TemplatesOffsets (for debug): %v\n", c.Header, c.StringTable, c.TemplateTable, c.EventOffsets, templateOffsets) 271 | } 272 | -------------------------------------------------------------------------------- /evtx/event.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | 8 | "github.com/0xrawsec/golang-utils/log" 9 | ) 10 | 11 | ///////////////////////////////// Event //////////////////////////////////////// 12 | 13 | type EventHeader struct { 14 | Magic [4]byte 15 | Size int32 16 | ID int64 17 | Timestamp FileTime 18 | } 19 | 20 | // Validate controls the EventHeader 21 | func (h *EventHeader) Validate() error { 22 | // Validate the event magic 23 | if string(h.Magic[:]) != EventMagic { 24 | return fmt.Errorf("Bad event magic %q", h.Magic) 25 | } 26 | // An event cannot be bigger than a Chunk since an event is embedded into a 27 | // chunk 28 | if h.Size >= ChunkSize { 29 | return fmt.Errorf("Too big event") 30 | } 31 | // An event cannot be smaller than its header since the event size include the 32 | // size of the header 33 | if h.Size < EventHeaderSize { 34 | return fmt.Errorf("Too small event") 35 | } 36 | return nil 37 | } 38 | 39 | // Event structure 40 | type Event struct { 41 | Offset int64 // For debugging purposes 42 | Header EventHeader 43 | } 44 | 45 | // IsValid returns true if the Event is valid 46 | // TODO: find and replace because we now have Validate() method from the header 47 | func (e *Event) IsValid() bool { 48 | // Validate Magic Header 49 | return e.Header.Validate() == nil 50 | } 51 | 52 | // GoEvtxMap parses the BinXML inside the event and returns a pointer to a 53 | // structure GoEvtxMap 54 | // @c : chunk pointer used for template data already parsed 55 | // return (*GoEvtxMap, error) 56 | func (e Event) GoEvtxMap(c *Chunk) (pge *GoEvtxMap, err error) { 57 | // An Event can contain only BinXMLFragments 58 | if !e.IsValid() { 59 | err = ErrInvalidEvent 60 | return 61 | } 62 | reader := bytes.NewReader(c.Data) 63 | GoToSeeker(reader, e.Offset+EventHeaderSize) 64 | // Bug here if we put c 65 | element, err := Parse(reader, c, false) 66 | if err != nil && err != io.EOF { 67 | //panic(err) 68 | log.Error(err) 69 | } 70 | // If not a BinXMLFragment a panic will be raised 71 | fragment, ok := element.(*Fragment) 72 | switch { 73 | case !ok && ModeCarving: 74 | return 75 | case !ok: 76 | // Way to raise panic 77 | _ = element.(*Fragment) 78 | } 79 | return fragment.GoEvtxMap(), err 80 | } 81 | 82 | func (e Event) String() string { 83 | return fmt.Sprintf( 84 | "Magic: %s\n"+ 85 | "Size: %d\n"+ 86 | "ID: %d\n"+ 87 | "Timestamp: %d\n", 88 | //"Content: %x", 89 | e.Header.Magic, 90 | e.Header.Size, 91 | e.Header.ID, 92 | e.Header.Timestamp) 93 | } 94 | -------------------------------------------------------------------------------- /evtx/evtx.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "io" 8 | "math" 9 | "os" 10 | "regexp" 11 | "sync" 12 | "time" 13 | 14 | "github.com/0xrawsec/golang-utils/datastructs" 15 | "github.com/0xrawsec/golang-utils/encoding" 16 | "github.com/0xrawsec/golang-utils/log" 17 | ) 18 | 19 | // ChunkCache structure as a Set 20 | type ChunkCache struct { 21 | datastructs.SyncedSet 22 | } 23 | 24 | /////////////////////////////// ChunkSorter //////////////////////////////////// 25 | 26 | // ChunkSorter structure used to sort chunks before parsing the events inside 27 | // prevent unordered events 28 | type ChunkSorter []Chunk 29 | 30 | // Implement Sortable interface 31 | func (cs ChunkSorter) Len() int { 32 | return len(cs) 33 | } 34 | 35 | // Implement Sortable interface 36 | func (cs ChunkSorter) Less(i, j int) bool { 37 | return cs[i].Header.NumFirstRecLog < cs[j].Header.NumFirstRecLog 38 | } 39 | 40 | // Implement Sortable interface 41 | func (cs ChunkSorter) Swap(i, j int) { 42 | cs[i], cs[j] = cs[j], cs[i] 43 | } 44 | 45 | //////////////////////////////////// File ////////////////////////////////////// 46 | 47 | var ( 48 | ErrCorruptedHeader = fmt.Errorf("Corrupted header") 49 | ErrDirtyFile = fmt.Errorf("File is flagged as dirty") 50 | ErrRepairFailed = fmt.Errorf("File header could not be repaired") 51 | ) 52 | 53 | // FileHeader structure definition 54 | type FileHeader struct { 55 | Magic [8]byte 56 | FirstChunkNum uint64 57 | LastChunkNum uint64 58 | NextRecordID uint64 59 | HeaderSpace uint32 60 | MinVersion uint16 61 | MajVersion uint16 62 | ChunkDataOffset uint16 63 | ChunkCount uint16 64 | Unknown [76]byte 65 | Flags uint32 66 | CheckSum uint32 67 | } 68 | 69 | func (f *FileHeader) Verify() error { 70 | if !bytes.Equal(f.Magic[:], []byte("ElfFile\x00")) { 71 | return ErrCorruptedHeader 72 | } 73 | // File is dirty 74 | if f.Flags == 1 { 75 | return ErrDirtyFile 76 | } 77 | return nil 78 | } 79 | 80 | // Repair the header. It makes sense to use this function 81 | // whenever the file is flagged as dirty 82 | func (f *FileHeader) Repair(r io.ReadSeeker) error { 83 | chunkHeaderRE := regexp.MustCompile(ChunkMagic) 84 | rr := bufio.NewReader(r) 85 | cc := uint16(0) 86 | for loc := chunkHeaderRE.FindReaderIndex(rr); loc != nil; loc = chunkHeaderRE.FindReaderIndex(rr) { 87 | cc++ 88 | } 89 | 90 | if f.ChunkCount > cc { 91 | return ErrRepairFailed 92 | } 93 | 94 | // Fixing chunk count 95 | f.ChunkCount = cc 96 | // Fixing LastChunkNum 97 | f.LastChunkNum = uint64(f.ChunkCount - 1) 98 | // File is not dirty anymore 99 | f.Flags = 0 100 | return nil 101 | } 102 | 103 | // File structure definition 104 | type File struct { 105 | sync.Mutex // We need it if we want to parse (read) chunks in several threads 106 | Header FileHeader 107 | file io.ReadSeeker 108 | monitorExisting bool 109 | } 110 | 111 | // New EvtxFile structure initialized from an open buffer 112 | // @r : buffer containing evtx data to parse 113 | // return File : File structure initialized 114 | func New(r io.ReadSeeker) (ef File, err error) { 115 | ef.file = r 116 | ef.ParseFileHeader() 117 | return 118 | } 119 | 120 | // New EvtxFile structure initialized from file 121 | // @filepath : filepath of the evtx file to parse 122 | // return File : File structure initialized 123 | func Open(filepath string) (ef File, err error) { 124 | file, err := os.Open(filepath) 125 | if err != nil { 126 | return 127 | } 128 | 129 | ef, err = New(file) 130 | if err != nil { 131 | return 132 | } 133 | 134 | err = ef.Header.Verify() 135 | 136 | return 137 | } 138 | 139 | // OpenDirty is a wrapper around Open to handle the case 140 | // where the file opened has its dirty flag set 141 | func OpenDirty(filepath string) (ef File, err error) { 142 | // Repair the file header if file is dirty 143 | if ef, err = Open(filepath); err == ErrDirtyFile { 144 | err = ef.Header.Repair(ef.file) 145 | } 146 | return 147 | } 148 | 149 | // SetMonitorExisting sets monitorExisting flag of EvtxFile struct in order to 150 | // return already existing events when using MonitorEvents 151 | func (ef *File) SetMonitorExisting(value bool) { 152 | ef.monitorExisting = value 153 | } 154 | 155 | // ParseFileHeader parses a the file header of the file structure and modifies 156 | // the Header of the current structure 157 | func (ef *File) ParseFileHeader() { 158 | ef.Lock() 159 | defer ef.Unlock() 160 | 161 | GoToSeeker(ef.file, 0) 162 | err := encoding.Unmarshal(ef.file, &ef.Header, Endianness) 163 | if err != nil { 164 | panic(err) 165 | } 166 | } 167 | 168 | func (fh FileHeader) String() string { 169 | return fmt.Sprintf( 170 | "Magic: %q\n"+ 171 | "FirstChunkNum: %d\n"+ 172 | "LastChunkNum: %d\n"+ 173 | "NumNextRecord: %d\n"+ 174 | "HeaderSpace: %d\n"+ 175 | "MinVersion: 0x%04x\n"+ 176 | "MaxVersion: 0x%04x\n"+ 177 | "SizeHeader: %d\n"+ 178 | "ChunkCount: %d\n"+ 179 | "Flags: 0x%08x\n"+ 180 | "CheckSum: 0x%08x\n", 181 | fh.Magic, 182 | fh.FirstChunkNum, 183 | fh.LastChunkNum, 184 | fh.NextRecordID, 185 | fh.HeaderSpace, 186 | fh.MinVersion, 187 | fh.MajVersion, 188 | fh.ChunkDataOffset, 189 | fh.ChunkCount, 190 | fh.Flags, 191 | fh.CheckSum) 192 | 193 | } 194 | 195 | // FetchRawChunk fetches a raw Chunk (without parsing String and Template tables) 196 | // @offset : offset in the current file where to find the Chunk 197 | // return Chunk : Chunk (raw) parsed 198 | func (ef *File) FetchRawChunk(offset int64) (Chunk, error) { 199 | ef.Lock() 200 | defer ef.Unlock() 201 | c := NewChunk() 202 | GoToSeeker(ef.file, offset) 203 | c.Offset = offset 204 | c.Data = make([]byte, ChunkHeaderSize) 205 | if _, err := ef.file.Read(c.Data); err != nil { 206 | return c, err 207 | } 208 | reader := bytes.NewReader(c.Data) 209 | c.ParseChunkHeader(reader) 210 | return c, nil 211 | } 212 | 213 | // FetchChunk fetches a Chunk 214 | // @offset : offset in the current file where to find the Chunk 215 | // return Chunk : Chunk parsed 216 | func (ef *File) FetchChunk(offset int64) (Chunk, error) { 217 | ef.Lock() 218 | defer ef.Unlock() 219 | c := NewChunk() 220 | GoToSeeker(ef.file, offset) 221 | c.Offset = offset 222 | c.Data = make([]byte, ChunkSize) 223 | if _, err := ef.file.Read(c.Data); err != nil { 224 | return c, err 225 | } 226 | reader := bytes.NewReader(c.Data) 227 | c.ParseChunkHeader(reader) 228 | // Go to after Header 229 | GoToSeeker(reader, int64(c.Header.SizeHeader)) 230 | c.ParseStringTable(reader) 231 | if err := c.ParseTemplateTable(reader); err != nil { 232 | return c, err 233 | } 234 | if err := c.ParseEventOffsets(reader); err != nil { 235 | return c, err 236 | } 237 | return c, nil 238 | } 239 | 240 | // Chunks returns a chan of all the Chunks found in the current file 241 | // return (chan Chunk) 242 | func (ef *File) Chunks() (cc chan Chunk) { 243 | ss := datastructs.NewSortedSlice(0, int(ef.Header.ChunkCount)) 244 | cc = make(chan Chunk) 245 | go func() { 246 | defer close(cc) 247 | for i := uint16(0); i < ef.Header.ChunkCount; i++ { 248 | offsetChunk := int64(ef.Header.ChunkDataOffset) + int64(ChunkSize)*int64(i) 249 | chunk, err := ef.FetchRawChunk(offsetChunk) 250 | switch { 251 | case err != nil && err != io.EOF: 252 | panic(err) 253 | case err == nil: 254 | ss.Insert(chunk) 255 | } 256 | } 257 | // sorted slice has to be iterated backward 258 | for rc := range ss.ReversedIter() { 259 | cc <- rc.(Chunk) 260 | } 261 | }() 262 | return 263 | } 264 | 265 | // UnorderedChunks returns a chan of all the Chunks found in the current file 266 | // return (chan Chunk) 267 | func (ef *File) UnorderedChunks() (cc chan Chunk) { 268 | cc = make(chan Chunk) 269 | go func() { 270 | defer close(cc) 271 | for i := uint16(0); i < ef.Header.ChunkCount; i++ { 272 | offsetChunk := int64(ef.Header.ChunkDataOffset) + int64(ChunkSize)*int64(i) 273 | //chunk, err := ef.FetchChunk(offsetChunk) 274 | chunk, err := ef.FetchRawChunk(offsetChunk) 275 | switch { 276 | case err != nil && err != io.EOF: 277 | panic(err) 278 | case err == nil: 279 | cc <- chunk 280 | } 281 | } 282 | }() 283 | return 284 | } 285 | 286 | // monitorChunks returns a chan of the new Chunks found in the file under 287 | // monitoring created after the monitoring started 288 | // @stop: a channel used to stop the monitoring if needed 289 | // @sleep: sleep time 290 | // return (chan Chunk) 291 | func (ef *File) monitorChunks(stop chan bool, sleep time.Duration) (cc chan Chunk) { 292 | cc = make(chan Chunk, 4) 293 | sleepTime := sleep 294 | markedChunks := datastructs.NewSyncedSet() 295 | 296 | // Main routine to feed the Chunk Channel 297 | go func() { 298 | defer close(cc) 299 | firstLoopFlag := !ef.monitorExisting 300 | for { 301 | // Parse the file header again to get the updates in the file 302 | ef.ParseFileHeader() 303 | 304 | // check if we should stop or not 305 | select { 306 | case <-stop: 307 | return 308 | default: 309 | // go through 310 | } 311 | curChunks := datastructs.NewSyncedSet() 312 | //cs := make(ChunkSorter, 0, ef.Header.ChunkCount) 313 | ss := datastructs.NewSortedSlice(0, int(ef.Header.ChunkCount)) 314 | for i := uint16(0); i < ef.Header.ChunkCount; i++ { 315 | offsetChunk := int64(ef.Header.ChunkDataOffset) + int64(ChunkSize)*int64(i) 316 | chunk, err := ef.FetchRawChunk(offsetChunk) 317 | curChunks.Add(chunk.Header.FirstEventRecID, chunk.Header.LastEventRecID) 318 | // We append only the Chunks whose EventRecordIds have not been treated yet 319 | if markedChunks.Contains(chunk.Header.FirstEventRecID) && markedChunks.Contains(chunk.Header.LastEventRecID) { 320 | continue 321 | } 322 | switch { 323 | case err != nil && err != io.EOF: 324 | panic(err) 325 | case err == nil: 326 | markedChunks.Add(chunk.Header.FirstEventRecID) 327 | markedChunks.Add(chunk.Header.LastEventRecID) 328 | if !firstLoopFlag { 329 | //cs = append(cs, chunk) 330 | ss.Insert(chunk) 331 | } 332 | } 333 | } 334 | 335 | // Cleanup the useless cache entries (consider putting in go routine if worth) 336 | markedChunks = datastructs.NewSyncedSet(markedChunks.Intersect(curChunks)) 337 | 338 | // We flag out of first loop 339 | firstLoopFlag = false 340 | // We sort out the chunks 341 | //sort.Stable(cs) 342 | //for _, rc := range cs { 343 | for rc := range ss.ReversedIter() { 344 | chunk, err := ef.FetchChunk(rc.(Chunk).Offset) 345 | switch { 346 | case err != nil && err != io.EOF: 347 | panic(err) 348 | case err == nil: 349 | cc <- chunk 350 | } 351 | } 352 | 353 | // Check if we should quit 354 | if ef.Header.ChunkCount >= math.MaxUint16 { 355 | log.Info("Monitoring stopped: maximum chunk number reached") 356 | break 357 | } 358 | 359 | // Sleep between loops 360 | time.Sleep(sleepTime) 361 | } 362 | }() 363 | return 364 | } 365 | 366 | // Events returns a chan pointers to all the GoEvtxMap found in the current file 367 | // this is a slow implementation, FastEvents should be prefered 368 | // return (chan *GoEvtxMap) 369 | func (ef *File) Events() (cgem chan *GoEvtxMap) { 370 | cgem = make(chan *GoEvtxMap, 1) 371 | go func() { 372 | defer close(cgem) 373 | for c := range ef.Chunks() { 374 | cpc, err := ef.FetchChunk(c.Offset) 375 | switch { 376 | case err != nil && err != io.EOF: 377 | panic(err) 378 | case err == nil: 379 | for ev := range cpc.Events() { 380 | cgem <- ev 381 | } 382 | } 383 | } 384 | 385 | }() 386 | return 387 | } 388 | 389 | // FastEvents returns a chan pointers to all the GoEvtxMap found in the current 390 | // file. Same as Events method but the fast version 391 | // return (chan *GoEvtxMap) 392 | func (ef *File) FastEvents() (cgem chan *GoEvtxMap) { 393 | cgem = make(chan *GoEvtxMap, 42) 394 | go func() { 395 | defer close(cgem) 396 | chanQueue := make(chan (chan *GoEvtxMap), MaxJobs) 397 | go func() { 398 | defer close(chanQueue) 399 | for pc := range ef.Chunks() { 400 | cpc, err := ef.FetchChunk(pc.Offset) 401 | switch { 402 | case err != nil && err != io.EOF: 403 | panic(err) 404 | case err == nil: 405 | ev := cpc.Events() 406 | chanQueue <- ev 407 | } 408 | } 409 | }() 410 | for ec := range chanQueue { 411 | for event := range ec { 412 | log.Debug(event) 413 | cgem <- event 414 | } 415 | } 416 | }() 417 | return 418 | } 419 | 420 | // UnorderedEvents returns a chan pointers to all the GoEvtxMap found in the current 421 | // file. Same as FastEvents method but the order by time is not guaranteed. It can 422 | // significantly improve preformances for big files. 423 | // return (chan *GoEvtxMap) 424 | func (ef *File) UnorderedEvents() (cgem chan *GoEvtxMap) { 425 | cgem = make(chan *GoEvtxMap, 42) 426 | go func() { 427 | defer close(cgem) 428 | chanQueue := make(chan (chan *GoEvtxMap), MaxJobs) 429 | go func() { 430 | defer close(chanQueue) 431 | for pc := range ef.UnorderedChunks() { 432 | // We have to create a copy here because otherwise cpc.EventsChan() fails 433 | // I guess that because EventsChan takes a pointer to an object and that 434 | // and thus the chan is taken on the pointer and since the object pointed 435 | // changes -> kaboom 436 | cpc, err := ef.FetchChunk(pc.Offset) 437 | switch { 438 | case err != nil && err != io.EOF: 439 | panic(err) 440 | case err == nil: 441 | ev := cpc.Events() 442 | chanQueue <- ev 443 | } 444 | } 445 | }() 446 | for ec := range chanQueue { 447 | for event := range ec { 448 | cgem <- event 449 | } 450 | } 451 | }() 452 | return 453 | } 454 | 455 | // MonitorEvents returns a chan pointers to all the GoEvtxMap found in the File 456 | // under monitoring. This is the fast version 457 | // @stop: a channel used to stop the monitoring if needed 458 | // return (chan *GoEvtxMap) 459 | func (ef *File) MonitorEvents(stop chan bool, sleep ...time.Duration) (cgem chan *GoEvtxMap) { 460 | // Normally, it should not be needed to add a second check here on the 461 | // EventRecordID since the record ids in the chunks are not supposed to overlap 462 | // TODO: Add a EventRecordID marker if needed 463 | sleepTime := DefaultMonitorSleep 464 | if len(sleep) > 0 { 465 | sleepTime = sleep[0] 466 | } 467 | jobs := MaxJobs 468 | cgem = make(chan *GoEvtxMap, 42) 469 | go func() { 470 | defer close(cgem) 471 | chanQueue := make(chan (chan *GoEvtxMap), jobs) 472 | go func() { 473 | defer close(chanQueue) 474 | // this chan ends only when value is put into stop 475 | for pc := range ef.monitorChunks(stop, sleepTime) { 476 | // We have to create a copy here because otherwise cpc.EventsChan() fails 477 | // I guess that because EventsChan takes a pointer to an object 478 | // and thus the chan is taken on the pointer and since the object pointed 479 | // changes -> kaboom 480 | cpc := pc 481 | ev := cpc.Events() 482 | chanQueue <- ev 483 | } 484 | }() 485 | for ec := range chanQueue { 486 | for event := range ec { 487 | cgem <- event 488 | } 489 | } 490 | }() 491 | return 492 | } 493 | 494 | // Close file 495 | func (ef *File) Close() error { 496 | if f, ok := ef.file.(io.Closer); ok { 497 | return f.Close() 498 | } 499 | 500 | return nil 501 | } 502 | -------------------------------------------------------------------------------- /evtx/globals.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "encoding/binary" 5 | "errors" 6 | "math" 7 | "runtime" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | /////////////////////////////////// Errors ///////////////////////////////////// 13 | 14 | var ( 15 | ErrInvalidEvent = errors.New("Error Invalid Event") 16 | // ErrBadEvtxFile error definition 17 | ErrBadEvtxFile = errors.New("Bad file magic") 18 | // ErrBadChunkMagic error definition 19 | ErrBadChunkMagic = errors.New("Bad chunk magic") 20 | // ErrBadChunkSize error definition 21 | ErrBadChunkSize = errors.New("Bad chunk size") 22 | ErrTokenEOF = errors.New("TokenEOF") 23 | ) 24 | 25 | //////////////////////// Global Variables and their setters ///////////////////// 26 | var ( 27 | // Debug mode for parser 28 | Debug = false 29 | // ModeCarving flag to identify we run in carving mode 30 | ModeCarving = false 31 | // DefaultMonitorSleep default sleep time between two file update checks when 32 | // monitoring file 33 | DefaultMonitorSleep = 250 * time.Millisecond 34 | // MaxJobs controls the maximum jobs for some functions (MonitorEvents ...) 35 | MaxJobs = int(math.Floor(float64(runtime.NumCPU()) / 2)) 36 | ) 37 | 38 | // SetModeCarving changes the carving mode to value 39 | func SetModeCarving(value bool) { 40 | ModeCarving = value 41 | } 42 | 43 | // SetMonitorSleep sets the sleep time between two file update checks when 44 | // monitoring file 45 | func SetMonitorSleep(d time.Duration) { 46 | DefaultMonitorSleep = d 47 | } 48 | 49 | // SetMaxJobs sets the number of jobs for parsing 50 | func SetMaxJobs(jobs int) { 51 | MaxJobs = jobs 52 | } 53 | 54 | // SetDebug set variable enabling debugging at parser level 55 | func SetDebug(value bool) { 56 | Debug = value 57 | } 58 | 59 | ////////////////////////// EVTX Constants and globs //////////////////////////// 60 | 61 | const ( 62 | EventHeaderSize = 24 63 | EvtxMagic = "ElfFile" 64 | 65 | // ChunkSize 64KB 66 | ChunkSize = 0x10000 67 | // ChunkHeaderSize 68 | ChunkHeaderSize = 0x80 69 | // ChunkMagic magic string 70 | ChunkMagic = "ElfChnk\x00" 71 | sizeStringBucket = 0x40 72 | sizeTemplateBucket = 0x20 73 | DefaultNameOffset = -1 74 | 75 | EventMagic = "\x2a\x2a\x00\x00" 76 | 77 | // MaxSliceSize is a constant used to control the allocation size of some 78 | // structures. It is particularly useful to control side effect when carving 79 | MaxSliceSize = ChunkSize 80 | ) 81 | 82 | //type LastParsedElements 83 | 84 | var ( 85 | Endianness = binary.LittleEndian 86 | // Used for debug purposes 87 | //lastParsedElements LastParsedElements 88 | lastParsedElements struct { 89 | sync.RWMutex 90 | elements [4]Element 91 | } 92 | ) 93 | 94 | //////////////////////////////// BinXMLTokens ////////////////////////////////// 95 | 96 | const ( 97 | TokenEOF = 0x00 98 | TokenOpenStartElementTag1, TokenOpenStartElementTag2 = 0x01, 0x41 // (<)name> 99 | TokenCloseStartElementTag = 0x02 // ) 100 | TokenCloseEmptyElementTag = 0x03 // ) 101 | TokenEndElementTag = 0x04 // () 102 | TokenValue1, TokenValue2 = 0x05, 0x45 // attribute = ‘‘(value)’’ 103 | TokenAttribute1, TokenAttribute2 = 0x06, 0x46 // (attribute) = ‘‘value’’ 104 | TokenCDataSection1, TokenCDataSection2 = 0x07, 0x47 105 | TokenCharRef1, TokenCharRef2 = 0x08, 0x48 106 | TokenEntityRef1, TokenEntityRef2 = 0x09, 0x49 107 | TokenPITarget = 0x0a 108 | TokenPIData = 0x0b 109 | TokenTemplateInstance = 0x0c 110 | TokenNormalSubstitution = 0x0d 111 | TokenOptionalSubstitution = 0x0e 112 | FragmentHeaderToken = 0x0f 113 | ) 114 | 115 | //////////////////////////////// BinXMLValues ////////////////////////////////// 116 | 117 | const ( 118 | NullType = 0x00 119 | StringType = 0x01 120 | AnsiStringType = 0x02 121 | Int8Type = 0x03 122 | UInt8Type = 0x04 123 | Int16Type = 0x05 124 | UInt16Type = 0x06 125 | Int32Type = 0x07 126 | UInt32Type = 0x08 127 | Int64Type = 0x09 128 | UInt64Type = 0x0a 129 | Real32Type = 0x0b 130 | Real64Type = 0x0c 131 | BoolType = 0x0d 132 | BinaryType = 0x0e 133 | GuidType = 0x0f 134 | SizeTType = 0x10 135 | FileTimeType = 0x11 136 | SysTimeType = 0x12 137 | SidType = 0x13 138 | HexInt32Type = 0x14 139 | HexInt64Type = 0x15 140 | EvtHandle = 0x20 141 | BinXmlType = 0x21 142 | EvtXml = 0x23 143 | 144 | // If the MSB of the value type (0x80) is use to indicate an array type 145 | ArrayType = 0x80 146 | ) 147 | 148 | /////////////////////////////////// GoEvtx ///////////////////////////////////// 149 | 150 | var ( 151 | // Paths used by GoEvtxMap 152 | PathSeparator = "/" 153 | XmlnsPath = Path("/Event/xmlns") 154 | ChannelPath = Path("/Event/System/Channel") 155 | EventIDPath = Path("/Event/System/EventID") 156 | EventIDPath2 = Path("/Event/System/EventID/Value") 157 | EventRecordIDPath = Path("/Event/System/EventRecordID") 158 | SystemTimePath = Path("/Event/System/TimeCreated/SystemTime") 159 | UserIDPath = Path("/Event/System/Security/UserID") 160 | ) 161 | -------------------------------------------------------------------------------- /evtx/goevtx.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "regexp" 7 | "strconv" 8 | "strings" 9 | "time" 10 | ) 11 | 12 | type GoEvtxElement interface{} 13 | 14 | type GoEvtxMap map[string]interface{} 15 | 16 | type GoEvtxPath []string 17 | 18 | func (p GoEvtxPath) String() string { 19 | return strings.Join(p, "/") 20 | } 21 | 22 | type ErrEvtxEltNotFound struct { 23 | path GoEvtxPath 24 | } 25 | 26 | func (e *ErrEvtxEltNotFound) Error() string { 27 | return fmt.Sprintf("Element at path %v not found", e.path) 28 | } 29 | 30 | // Path : helper function that converts a path string to a table of strings 31 | // @s : path string, has to be in form of /correct/path/string with (correct, 32 | // path, string) being keys to look for recursively 33 | func Path(s string) GoEvtxPath { 34 | return strings.Split(strings.Trim(s, PathSeparator), PathSeparator) 35 | } 36 | 37 | // HasKeys : determines whether this map is in a key value form 38 | // return bool 39 | func (pg *GoEvtxMap) HasKeys(keys ...string) bool { 40 | for _, k := range keys { 41 | if _, ok := (*pg)[k]; !ok { 42 | return false 43 | } 44 | } 45 | return true 46 | } 47 | 48 | // Add : concatenate two GoEvtxMap together 49 | // @other: other map to concatenate with 50 | func (pg *GoEvtxMap) Add(other GoEvtxMap) { 51 | for k, v := range other { 52 | if _, ok := (*pg)[k]; ok { 53 | panic("Duplicated key") 54 | } 55 | (*pg)[k] = v 56 | } 57 | } 58 | 59 | // GetMap : Get the full map containing the path 60 | // @path : path to search for 61 | func (pg *GoEvtxMap) GetMap(path *GoEvtxPath) (*GoEvtxMap, error) { 62 | if len(*path) > 0 { 63 | if ge, ok := (*pg)[(*path)[0]]; ok { 64 | if len(*path) == 1 { 65 | return pg, nil 66 | } 67 | switch ge.(type) { 68 | case GoEvtxMap: 69 | p := ge.(GoEvtxMap) 70 | np := (*path)[1:] 71 | return p.GetMap(&np) 72 | } 73 | } 74 | } 75 | return nil, &ErrEvtxEltNotFound{*path} 76 | } 77 | 78 | func (pg *GoEvtxMap) GetMapStrict(path *GoEvtxPath) *GoEvtxMap { 79 | pg, err := pg.GetMap(path) 80 | if err != nil { 81 | panic(err) 82 | } 83 | return pg 84 | } 85 | 86 | func (pg *GoEvtxMap) GetMapWhere(path *GoEvtxPath, value interface{}) (*GoEvtxMap, error) { 87 | m, err := pg.GetMap(path) 88 | if err != nil { 89 | return nil, err 90 | } 91 | if m != nil && len(*path) > 0 { 92 | np := (*path)[len(*path)-1:] 93 | if m.Equal(&np, value) { 94 | return m, nil 95 | } 96 | } 97 | return nil, &ErrEvtxEltNotFound{*path} 98 | } 99 | 100 | func (pg *GoEvtxMap) GetMapWhereStrict(path *GoEvtxPath, value interface{}) *GoEvtxMap { 101 | pg, err := pg.GetMapWhere(path, value) 102 | if err != nil { 103 | panic(err) 104 | } 105 | return pg 106 | } 107 | 108 | // Recursive search in a GoEvtxMap according to a given path 109 | // @path : path to search for 110 | // return *GoEvtxElement, error : pointer to the element found at path 111 | func (pg *GoEvtxMap) Get(path *GoEvtxPath) (*GoEvtxElement, error) { 112 | if len(*path) > 0 { 113 | if i, ok := (*pg)[(*path)[0]]; ok { 114 | if len(*path) == 1 { 115 | cge := GoEvtxElement(i) 116 | return &cge, nil 117 | } 118 | switch i.(type) { 119 | case GoEvtxMap: 120 | p := i.(GoEvtxMap) 121 | np := (*path)[1:] 122 | return p.Get(&np) 123 | case map[string]interface{}: 124 | p := GoEvtxMap(i.(map[string]interface{})) 125 | np := (*path)[1:] 126 | return p.Get(&np) 127 | } 128 | } 129 | } 130 | return nil, &ErrEvtxEltNotFound{*path} 131 | } 132 | 133 | func (pg *GoEvtxMap) GetStrict(path *GoEvtxPath) *GoEvtxElement { 134 | gee, err := pg.Get(path) 135 | if err != nil { 136 | panic(err) 137 | } 138 | return gee 139 | } 140 | 141 | // GetUint returns the GoEvtxElement at path as a string 142 | // @path : path to search for 143 | // return string, error 144 | func (pg *GoEvtxMap) GetString(path *GoEvtxPath) (string, error) { 145 | pE, err := pg.Get(path) 146 | if err != nil { 147 | return "", err 148 | } 149 | if s, ok := (*pE).(string); ok { 150 | return s, nil 151 | } 152 | return "", fmt.Errorf("Bad type expect string got %T", (*pE)) 153 | } 154 | 155 | func (pg *GoEvtxMap) GetStringStrict(path *GoEvtxPath) string { 156 | s, err := pg.GetString(path) 157 | if err != nil { 158 | panic(err) 159 | } 160 | return s 161 | } 162 | 163 | // GetBool returns the GoEvtxElement at path as a bool 164 | // @path : path to search for 165 | // return (bool, error) 166 | func (pg *GoEvtxMap) GetBool(path *GoEvtxPath) (bool, error) { 167 | s, err := pg.GetString(path) 168 | if err != nil { 169 | return false, &ErrEvtxEltNotFound{*path} 170 | } 171 | b, err := strconv.ParseBool(s) 172 | if err != nil { 173 | return false, err 174 | } 175 | return b, err 176 | } 177 | 178 | func (pg *GoEvtxMap) GetBoolStrict(path *GoEvtxPath) bool { 179 | b, err := pg.GetBool(path) 180 | if err != nil { 181 | panic(err) 182 | } 183 | return b 184 | } 185 | 186 | // GetInt returns the GoEvtxElement at path as a int64 187 | // @path : path to search for 188 | // return int64, error 189 | func (pg *GoEvtxMap) GetInt(path *GoEvtxPath) (int64, error) { 190 | s, err := pg.GetString(path) 191 | if err != nil { 192 | return 0, &ErrEvtxEltNotFound{*path} 193 | } 194 | i, err := strconv.ParseInt(s, 0, 64) 195 | if err != nil { 196 | return 0, err 197 | } 198 | return i, nil 199 | } 200 | 201 | func (pg *GoEvtxMap) GetIntStrict(path *GoEvtxPath) int64 { 202 | i, err := pg.GetInt(path) 203 | if err != nil { 204 | panic(err) 205 | } 206 | return i 207 | } 208 | 209 | // GetUint returns the GoEvtxElement at path as a uint64 210 | // @path : path to search for 211 | // return uint64 212 | func (pg *GoEvtxMap) GetUint(path *GoEvtxPath) (uint64, error) { 213 | s, err := pg.GetString(path) 214 | if err != nil { 215 | return 0, &ErrEvtxEltNotFound{*path} 216 | } 217 | u, err := strconv.ParseUint(s, 0, 64) 218 | if err != nil { 219 | return 0, err 220 | } 221 | return u, nil 222 | } 223 | 224 | func (pg *GoEvtxMap) GetUintStrict(path *GoEvtxPath) uint64 { 225 | u, err := pg.GetUint(path) 226 | if err != nil { 227 | panic(err) 228 | } 229 | return u 230 | } 231 | 232 | // GetUint returns the GoEvtxElement at path as a Time struct 233 | // @path : path to search for 234 | // return Time 235 | func (pg *GoEvtxMap) GetTime(path *GoEvtxPath) (time.Time, error) { 236 | t, err := pg.Get(path) 237 | if err != nil { 238 | return time.Time{}, &ErrEvtxEltNotFound{*path} 239 | } 240 | // If the value was extracted from raw BinXML (not a template) it may happen 241 | // that the value stored at path is a string since in raw BinXML everything 242 | // seems to be ValueText 243 | switch (*t).(type) { 244 | case time.Time: 245 | return (*t).(time.Time), nil 246 | case UTCTime: 247 | return time.Time((*t).(UTCTime)), nil 248 | case string: 249 | return time.Parse(time.RFC3339Nano, (*t).(string)) 250 | default: 251 | return time.Time{}, fmt.Errorf("Cannot convert %T to time.Time", *t) 252 | } 253 | } 254 | 255 | func (pg *GoEvtxMap) GetTimeStrict(path *GoEvtxPath) time.Time { 256 | t, err := pg.GetTime(path) 257 | if err != nil { 258 | panic(err) 259 | } 260 | return t 261 | } 262 | 263 | // EventID returns the EventID of the Event as a int64 264 | // return int64 : EventID 265 | func (pg *GoEvtxMap) EventID() int64 { 266 | eid, err := pg.GetInt(&EventIDPath) 267 | if err != nil { 268 | eid, err = pg.GetInt(&EventIDPath2) 269 | if err != nil { 270 | panic(err) 271 | } 272 | return eid 273 | } 274 | return eid 275 | } 276 | 277 | // Channel returns the Channel attribute of the event 278 | // return string : Channel attribute 279 | func (pg *GoEvtxMap) Channel() string { 280 | return pg.GetStringStrict(&ChannelPath) 281 | } 282 | 283 | // EventRecordID returns the EventRecordID of the the event. It panics if the 284 | // attribute is not found in the event. 285 | func (pg *GoEvtxMap) EventRecordID() int64 { 286 | return pg.GetIntStrict(&EventRecordIDPath) 287 | } 288 | 289 | // TimeCreated returns the creation time of the event. It panics if the attribute 290 | // is not in the event 291 | func (pg *GoEvtxMap) TimeCreated() time.Time { 292 | return pg.GetTimeStrict(&SystemTimePath) 293 | } 294 | 295 | // UserID retrieves the UserID attribute located at /Event/System/Security/UserID 296 | // if present. If not present the ok flag will be false 297 | func (pg *GoEvtxMap) UserID() (userID string, ok bool) { 298 | userID, err := pg.GetString(&UserIDPath) 299 | if err == nil { 300 | ok = true 301 | } 302 | return 303 | } 304 | 305 | func (pg *GoEvtxMap) Before(t time.Time) bool { 306 | return pg.GetTimeStrict(&SystemTimePath).Before(t) 307 | } 308 | 309 | func (pg *GoEvtxMap) After(t time.Time) bool { 310 | return pg.GetTimeStrict(&SystemTimePath).After(t) 311 | } 312 | 313 | func (pg *GoEvtxMap) At(t time.Time) bool { 314 | return pg.GetTimeStrict(&SystemTimePath).Equal(t) 315 | } 316 | 317 | func (pg *GoEvtxMap) Between(t1, t2 time.Time) bool { 318 | return (pg.After(t1) || pg.At(t1)) && (pg.Before(t2) || pg.At(t2)) 319 | } 320 | 321 | // Equal returns true if element at path is equal to i 322 | // @path : path at witch GoEvtxElement is located 323 | // @i : interface to test equality with 324 | // return bool : true if equality is verified 325 | func (pg *GoEvtxMap) Equal(path *GoEvtxPath, i interface{}) bool { 326 | t, err := pg.Get(path) 327 | if err != nil { 328 | return false 329 | } 330 | return reflect.DeepEqual(*t, i) 331 | } 332 | 333 | // Equal returns true if element at path is equal to any object 334 | // @path : path at witch GoEvtxElement is located 335 | // @is : slice of interface to test equality with 336 | // return bool : true if equality is verified 337 | func (pg *GoEvtxMap) AnyEqual(path *GoEvtxPath, is []interface{}) bool { 338 | t, err := pg.Get(path) 339 | if err != nil { 340 | return false 341 | } 342 | for _, i := range is { 343 | if reflect.DeepEqual(i, *t) { 344 | return true 345 | } 346 | } 347 | return false 348 | } 349 | 350 | // RegexMatch returns true if GoEvtxElement located at path matches a regexp 351 | // @path : path at witch GoEvtxElement is located 352 | // @pattern : regexp to test 353 | // return bool 354 | func (pg *GoEvtxMap) RegexMatch(path *GoEvtxPath, pattern *regexp.Regexp) bool { 355 | s, err := pg.GetString(path) 356 | if err != nil { 357 | return false 358 | } 359 | return pattern.MatchString(s) 360 | } 361 | 362 | // IsEventID returns true if pg is one of the EventID number specified in parameter 363 | // @eids : EventID numbers to test against 364 | // return bool 365 | func (pg *GoEvtxMap) IsEventID(eids ...interface{}) bool { 366 | return pg.AnyEqual(&EventIDPath, eids) 367 | } 368 | 369 | // Set sets a new GoEvtxElement at path 370 | // @path... : path to look for 371 | // @new : new value 372 | // return error if any 373 | func (pg *GoEvtxMap) Set(path *GoEvtxPath, new GoEvtxElement) error { 374 | if len(*path) > 0 { 375 | i := (*pg)[(*path)[0]] 376 | if len(*path) == 1 { 377 | (*pg)[(*path)[0]] = new 378 | return nil 379 | } 380 | switch i.(type) { 381 | case GoEvtxMap: 382 | p := i.(GoEvtxMap) 383 | np := (*path)[1:] 384 | return p.Set(&np, new) 385 | case map[string]interface{}: 386 | p := GoEvtxMap(i.(map[string]interface{})) 387 | np := (*path)[1:] 388 | return p.Set(&np, new) 389 | } 390 | 391 | } 392 | return &ErrEvtxEltNotFound{*path} 393 | } 394 | 395 | // Del deletes the object referenced by path 396 | func (pg *GoEvtxMap) Del(path *GoEvtxPath) { 397 | if len(*path) > 0 { 398 | if ge, ok := (*pg)[(*path)[0]]; ok { 399 | if len(*path) == 1 { 400 | delete((*pg), (*path)[0]) 401 | } 402 | switch ge.(type) { 403 | case GoEvtxMap: 404 | p := ge.(GoEvtxMap) 405 | np := (*path)[1:] 406 | p.Del(&np) 407 | 408 | case map[string]interface{}: 409 | p := GoEvtxMap(ge.(map[string]interface{})) 410 | np := (*path)[1:] 411 | p.Del(&np) 412 | } 413 | } 414 | } 415 | } 416 | 417 | // DelXmlns : utility function to delete useless xlmns entry found in every 418 | // GoEvtxMap 419 | func (pg *GoEvtxMap) DelXmlns() { 420 | pg.Del(&XmlnsPath) 421 | } 422 | -------------------------------------------------------------------------------- /evtx/node.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Node struct { 8 | Start *ElementStart 9 | Element []Element 10 | Child []*Node 11 | } 12 | 13 | func NodeTree(es []Element, index int) (Node, int) { 14 | //i := 0 15 | var n Node 16 | for index < len(es) { 17 | e := es[index] 18 | switch e.(type) { 19 | case *ElementStart: 20 | var nn Node 21 | nn, index = NodeTree(es, index+1) 22 | nn.Start = e.(*ElementStart) 23 | n.Child = append(n.Child, &nn) 24 | case *BinXMLEndElementTag, *BinXMLCloseEmptyElementTag: 25 | return n, index 26 | case *BinXMLCloseStartElementTag: 27 | break 28 | default: 29 | n.Element = append(n.Element, e) 30 | } 31 | index++ 32 | } 33 | return n, index 34 | } 35 | 36 | // TODO: Not used 37 | func ElementToGoEvtx(elt Element) GoEvtxElement { 38 | switch elt.(type) { 39 | // BinXML specific 40 | case *ValueText: 41 | return elt.(*ValueText).String() 42 | /*case *OptionalSubstitution: 43 | s := elt.(*OptionalSubstitution) 44 | return ElementToGoEvtx(ti.Data.Values[int(s.SubID)]) 45 | case *NormalSubstitution: 46 | s := elt.(*NormalSubstitution) 47 | return ElementToGoEvtx(ti.Data.Values[int(s.SubID)]) 48 | */ 49 | case *Fragment: 50 | temp := elt.(*Fragment).BinXMLElement.(*TemplateInstance) 51 | root := temp.Root() 52 | return temp.NodeToGoEvtx(&root) 53 | case *TemplateInstance: 54 | temp := elt.(*TemplateInstance) 55 | root := temp.Root() 56 | return temp.NodeToGoEvtx(&root) 57 | case Value: 58 | return elt.(Value).Repr() 59 | default: 60 | panic(fmt.Errorf("Don't know how to handle: %T", elt)) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /evtx/parser.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | 8 | "github.com/0xrawsec/golang-utils/log" 9 | ) 10 | 11 | ////////////////////////////////// Helper ////////////////////////////////////// 12 | 13 | func checkParsingError(err error, reader io.ReadSeeker, e Element) { 14 | UpdateLastElements(e) 15 | if err != nil { 16 | log.DontPanicf("%s: parsing %T", err, e) 17 | if Debug { 18 | DebugReader(reader, 10, 5) 19 | } 20 | } 21 | } 22 | 23 | func checkFullParsingError(err error, reader io.ReadSeeker, e Element, c *Chunk) { 24 | UpdateLastElements(e) 25 | if err != nil { 26 | if c != nil { 27 | log.DebugDontPanicf("%s: parsing %T (chunk @ 0x%08x reader @ 0x%08x)", err, e, c.Offset, BackupSeeker(reader)) 28 | } else { 29 | log.DebugDontPanicf("%s: parsing %T (chunk @ NIL reader @ 0x%08x)", err, e, BackupSeeker(reader)) 30 | } 31 | if Debug { 32 | DebugReader(reader, 10, 5) 33 | } 34 | } 35 | } 36 | 37 | ///////////////////////////// ErrUnknownToken ////////////////////////////////// 38 | 39 | type ErrUnknownToken struct { 40 | Token uint8 41 | } 42 | 43 | func (e ErrUnknownToken) Error() string { 44 | return fmt.Sprintf("Unknown Token: 0x%02x", e.Token) 45 | } 46 | 47 | // Parse : parses an XMLElement from a reader object 48 | // @reader : reader to parse the Element from 49 | // @c : chunk pointer used for already parsed templates 50 | // return (Element, error) : parsed XMLElement and error 51 | func Parse(reader io.ReadSeeker, c *Chunk, tiFlag bool) (Element, error) { 52 | var token [1]byte 53 | var err error 54 | read, err := reader.Read(token[:]) 55 | if read != 1 || err != nil { 56 | return EmptyElement{}, err 57 | } 58 | _, err = reader.Seek(-1, os.SEEK_CUR) 59 | if err != nil { 60 | return EmptyElement{}, err 61 | } 62 | switch token[0] { 63 | case FragmentHeaderToken: 64 | f := Fragment{} 65 | err = f.Parse(reader) 66 | checkFullParsingError(err, reader, &f, c) 67 | f.BinXMLElement, err = Parse(reader, c, tiFlag) 68 | checkFullParsingError(err, reader, &f, c) 69 | if err != nil { 70 | return &f, err 71 | } 72 | // We hack a bit over here creating a fake TemplateInstance to benefit from 73 | // the further GoEvtxMap convertion of it. Conceptually it makes sense since 74 | // we just create a template without substitutions. 75 | if _, ok := f.BinXMLElement.(*ElementStart); ok { 76 | var e Element 77 | var ti TemplateInstance 78 | ti.Definition.Data.Elements = make([]Element, 0) 79 | 80 | ti.Definition.Data.Elements = append(ti.Definition.Data.Elements, f.BinXMLElement.(*ElementStart)) 81 | for e, err = Parse(reader, c, tiFlag); err == nil; e, err = Parse(reader, c, tiFlag) { 82 | ti.Definition.Data.Elements = append(ti.Definition.Data.Elements, e) 83 | if _, ok := e.(*BinXMLEOF); ok { 84 | break 85 | } 86 | } 87 | checkFullParsingError(err, reader, e, c) 88 | f.BinXMLElement = &ti 89 | } 90 | return &f, err 91 | case TokenOpenStartElementTag1, TokenOpenStartElementTag2: 92 | es := ElementStart{IsTemplateInstance: tiFlag} 93 | err = es.Parse(reader) 94 | checkFullParsingError(err, reader, &es, c) 95 | return &es, err 96 | case TokenNormalSubstitution: 97 | ns := NormalSubstitution{} 98 | err = ns.Parse(reader) 99 | checkParsingError(err, reader, &ns) 100 | return &ns, err 101 | case TokenOptionalSubstitution: 102 | os := OptionalSubstitution{} 103 | err = os.Parse(reader) 104 | checkParsingError(err, reader, &os) 105 | return &os, err 106 | case TokenCharRef1: 107 | tcr := CharEntityRef{} 108 | err = tcr.Parse(reader) 109 | checkParsingError(err, reader, &tcr) 110 | return &tcr, err 111 | case TokenTemplateInstance: 112 | var offset int32 113 | ti := TemplateInstance{} 114 | if c != nil { 115 | // Check if template already parsed 116 | offset, err = ti.DataOffset(reader) 117 | if err != nil { 118 | return nil, err 119 | } 120 | if t, ok := c.TemplateTable[offset]; ok { 121 | // We have now to fix the offset to continue to read 122 | err = ti.ParseTemplateDefinitionHeader(reader) 123 | if err != nil { 124 | return nil, err 125 | } 126 | // Only the definition is valid, not the data 127 | ti.Definition.Data = t 128 | // We jump over the template definition data if needed 129 | if int64(offset) == BackupSeeker(reader) { 130 | // We patch offset to jump off to arrive after definition data size 131 | RelGoToSeeker(reader, int64(ti.Definition.Data.Size)+24) 132 | } 133 | // We parse the data 134 | err = ti.Data.Parse(reader) 135 | if err != nil { 136 | return nil, err 137 | } 138 | return &ti, nil 139 | } 140 | } 141 | // We have to parse the template since it cannot be found the template table 142 | err = ti.Parse(reader) 143 | if c != nil { 144 | // Update template table 145 | c.TemplateTable[ti.Definition.Header.DataOffset] = ti.Definition.Data 146 | } 147 | checkParsingError(err, reader, &ti) 148 | return &ti, err 149 | case TokenValue1, TokenValue2: 150 | // ValueText 151 | vt := ValueText{} 152 | err = vt.Parse(reader) 153 | checkParsingError(err, reader, &vt) 154 | return &vt, err 155 | 156 | case TokenEntityRef1, TokenEntityRef2: 157 | e := BinXMLEntityReference{} 158 | err = e.Parse(reader) 159 | checkParsingError(err, reader, &e) 160 | return &e, err 161 | 162 | case TokenEndElementTag: 163 | b := BinXMLEndElementTag{} 164 | err = b.Parse(reader) 165 | checkParsingError(err, reader, &b) 166 | return &b, err 167 | case TokenCloseStartElementTag: 168 | t := BinXMLCloseStartElementTag{} 169 | err = t.Parse(reader) 170 | checkParsingError(err, reader, &t) 171 | return &t, err 172 | case TokenCloseEmptyElementTag: 173 | t := BinXMLCloseEmptyElementTag{} 174 | err = t.Parse(reader) 175 | checkParsingError(err, reader, &t) 176 | return &t, err 177 | case TokenEOF: 178 | b := BinXMLEOF{} 179 | err = b.Parse(reader) 180 | checkParsingError(err, reader, &b) 181 | return &b, nil 182 | } 183 | //log.DontPanic(ErrUnknownToken{token[0]}) 184 | log.DebugDontPanic(ErrUnknownToken{token[0]}) 185 | return EmptyElement{}, ErrUnknownToken{token[0]} 186 | } 187 | 188 | // ParseValueReader : Parse a value from a reader according to a ValueDescriptor 189 | // @vd : a ValueDescriptor structure 190 | // @reader : the reader position at the offset of the value that have to be parsed 191 | // return (Element, error) : a XMLElement and error 192 | func ParseValueReader(vd ValueDescriptor, reader io.ReadSeeker) (Element, error) { 193 | var err error 194 | t := vd.ValType 195 | switch { 196 | case t.IsType(NullType): 197 | n := ValueNull{Size: vd.Size} 198 | n.Parse(reader) 199 | return &n, err 200 | case t.IsType(StringType): 201 | str := ValueString{Size: vd.Size} 202 | err = str.Parse(reader) 203 | return &str, err 204 | case t.IsType(AnsiStringType): 205 | astring := AnsiString{Size: vd.Size} 206 | err = astring.Parse(reader) 207 | return &astring, err 208 | case t.IsType(Int8Type): 209 | i := ValueInt8{} 210 | err = i.Parse(reader) 211 | return &i, err 212 | case t.IsType(UInt8Type): 213 | u := ValueUInt8{} 214 | err = u.Parse(reader) 215 | return &u, err 216 | case t.IsType(Int16Type): 217 | i := ValueInt16{} 218 | err = i.Parse(reader) 219 | return &i, err 220 | case t.IsType(UInt16Type): 221 | u := ValueUInt16{} 222 | err = u.Parse(reader) 223 | return &u, err 224 | case t.IsType(Int32Type): 225 | i := ValueInt32{} 226 | err = i.Parse(reader) 227 | return &i, err 228 | case t.IsType(UInt32Type): 229 | u := ValueUInt32{} 230 | err = u.Parse(reader) 231 | return &u, err 232 | case t.IsType(Int64Type): 233 | i := ValueInt64{} 234 | err = i.Parse(reader) 235 | return &i, err 236 | case t.IsType(UInt64Type): 237 | u := ValueUInt64{} 238 | err = u.Parse(reader) 239 | return &u, err 240 | //Real32Type is missing 241 | //Real64Type is missing 242 | case t.IsType(Real64Type): 243 | r := ValueReal64{} 244 | err = r.Parse(reader) 245 | return &r, err 246 | case t.IsType(BoolType): 247 | b := ValueBool{} 248 | err = b.Parse(reader) 249 | return &b, err 250 | case t.IsType(BinaryType): 251 | binary := ValueBinary{Size: vd.Size} 252 | err = binary.Parse(reader) 253 | return &binary, err 254 | case t.IsType(GuidType): 255 | var guid ValueGUID 256 | err = guid.Parse(reader) 257 | return &guid, err 258 | //SizeTType is missing 259 | case t.IsType(FileTimeType): 260 | filetime := ValueFileTime{} 261 | err = filetime.Parse(reader) 262 | return &filetime, err 263 | case t.IsType(SysTimeType): 264 | systime := ValueSysTime{} 265 | err = systime.Parse(reader) 266 | return &systime, err 267 | case t.IsType(SidType): 268 | var sid ValueSID 269 | err = sid.Parse(reader) 270 | return &sid, err 271 | case t.IsType(HexInt32Type): 272 | hi := ValueHexInt32{} 273 | err = hi.Parse(reader) 274 | return &hi, err 275 | case t.IsType(HexInt64Type): 276 | hi := ValueHexInt64{} 277 | err = hi.Parse(reader) 278 | return &hi, err 279 | //EvtHandle type is missing but unknown 280 | case t.IsType(BinXmlType): 281 | var elt Element 282 | // Must be a Fragment 283 | //elt, err := Parse(reader, c) 284 | elt, err = Parse(reader, nil, true) 285 | if err != nil { 286 | //panic(err) 287 | log.Error(err) 288 | log.DebugDontPanic(err) 289 | } 290 | return elt, err 291 | //EvtXML type is missing but unknown 292 | case t.IsArrayOf(StringType): 293 | st := ValueStringTable{Size: vd.Size} 294 | err = st.Parse(reader) 295 | return &st, err 296 | // Many Array Types are missing 297 | case t.IsArrayOf(UInt16Type): 298 | a := ValueArrayUInt16{Size: vd.Size} 299 | err = a.Parse(reader) 300 | return &a, err 301 | case t.IsArrayOf(UInt64Type): 302 | a := ValueArrayUInt64{Size: vd.Size} 303 | err = a.Parse(reader) 304 | return &a, err 305 | default: 306 | // TODO: May cause crap 307 | uv := UnkVal{BackupSeeker(reader), t, vd} 308 | // Jump over the value data if we don't know it 309 | _, err = reader.Seek(int64(vd.Size), os.SEEK_CUR) 310 | if err != nil { 311 | panic(err) 312 | } 313 | return &uv, nil 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /evtx/structs.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/0xrawsec/golang-utils/encoding" 8 | "github.com/0xrawsec/golang-utils/log" 9 | ) 10 | 11 | // EventIDType is an alias to the type of EventID 12 | type EventIDType int64 13 | 14 | //////////////////////////////// Interfaces Definition ////////////////////////// 15 | 16 | type Element interface { 17 | Parse(reader io.ReadSeeker) error 18 | //GetSize() int32 19 | } 20 | 21 | type AttributeData interface { 22 | /* 23 | Can be: 24 | value text 25 | substitution 26 | character entity reference 27 | entity reference 28 | */ 29 | IsAttributeData() bool 30 | String() string 31 | } 32 | 33 | type Content interface { 34 | /* 35 | Can be: 36 | an element 37 | content string data 38 | character entity reference 39 | entity reference 40 | CDATA section 41 | PI 42 | */ 43 | } 44 | 45 | type ContentStringData interface { 46 | /* 47 | Can be: 48 | value text 49 | substitution 50 | */ 51 | } 52 | 53 | type Substitution interface { 54 | /* 55 | Can be: 56 | normal substitution 57 | optional substitution 58 | */ 59 | } 60 | 61 | type PI interface { 62 | /* 63 | Can be: 64 | PI target 65 | PI data 66 | */ 67 | 68 | } 69 | 70 | /////////////////////////////// BinXMLFrgamentHeader /////////////////////////// 71 | 72 | // FragmentHeader : BinXMLFragmentHeader 73 | type FragmentHeader struct { 74 | Token int8 75 | MajVersion int8 76 | MinVersion int8 77 | Flags int8 78 | } 79 | 80 | func (fh *FragmentHeader) Parse(reader io.ReadSeeker) error { 81 | err := encoding.Unmarshal(reader, fh, Endianness) 82 | if fh.Token != FragmentHeaderToken { 83 | return fmt.Errorf("Bad fragment header token (0x%02x) instead of 0x%02x", fh.Token, FragmentHeaderToken) 84 | } 85 | return err 86 | } 87 | 88 | func (fh FragmentHeader) String() string { 89 | return fmt.Sprintf("%T: %s", fh, string(ToJSON(fh))) 90 | } 91 | 92 | ////////////////////////////////// BinXMLFragment ////////////////////////////// 93 | 94 | type Fragment struct { 95 | Offset int64 // For debug 96 | Header FragmentHeader 97 | BinXMLElement Element 98 | } 99 | 100 | func (f *Fragment) GoEvtxMap() *GoEvtxMap { 101 | switch f.BinXMLElement.(type) { 102 | case *TemplateInstance: 103 | pgem := f.BinXMLElement.(*TemplateInstance).GoEvtxMap() 104 | //pgem.SetEventRecordID(fmt.Sprintf("%d", f.EventID)) 105 | //pgem.SetSystemTime(f.Timestamp) 106 | pgem.DelXmlns() 107 | return pgem 108 | /*case *ElementStart: 109 | elements := make([]Element, 0) 110 | elements = append(elements, f.BinXMLElement.(*ElementStart)) 111 | for e, err := Parse(reader, nil); err == nil; e, err = Parse(reader, nil) { 112 | 113 | }*/ 114 | } 115 | return nil 116 | } 117 | 118 | func (f *Fragment) Parse(reader io.ReadSeeker) error { 119 | f.Offset = BackupSeeker(reader) 120 | err := f.Header.Parse(reader) 121 | if err != nil { 122 | return err 123 | } 124 | return err 125 | } 126 | 127 | func (f Fragment) String() string { 128 | return fmt.Sprintf("%T: %s", f, string(ToJSON(f))) 129 | } 130 | 131 | /////////////////////////////// BinXMLElementStart ///////////////////////////// 132 | 133 | // ElementStart : BinXMLElementStart 134 | type ElementStart struct { 135 | Offset int64 136 | IsTemplateInstance bool 137 | Token int8 138 | DepID int16 139 | Size int32 140 | NameOffset int32 // relative to start of chunk 141 | Name Name 142 | AttributeList AttributeList 143 | EOESToken uint8 144 | } 145 | 146 | func (es *ElementStart) Parse(reader io.ReadSeeker) (err error) { 147 | //var elt Element 148 | // Default value 149 | es.Offset = BackupSeeker(reader) 150 | es.NameOffset = DefaultNameOffset 151 | //currentOffset := BackupSeeker(reader) 152 | err = encoding.Unmarshal(reader, &es.Token, Endianness) 153 | if err != nil { 154 | return err 155 | } 156 | 157 | // If it is not part of a TemplateInstance there is not DepID 158 | // Source: https://msdn.microsoft.com/en-us/library/cc231354.aspx 159 | if es.IsTemplateInstance { 160 | err = encoding.Unmarshal(reader, &es.DepID, Endianness) 161 | if err != nil { 162 | return err 163 | } 164 | } 165 | 166 | err = encoding.Unmarshal(reader, &es.Size, Endianness) 167 | if err != nil { 168 | return err 169 | } 170 | 171 | err = encoding.Unmarshal(reader, &es.NameOffset, Endianness) 172 | if err != nil { 173 | return err 174 | } 175 | 176 | // The name maybe elsewhere (reason of NameOffset ???) 177 | backup := BackupSeeker(reader) 178 | if backup != int64(es.NameOffset) { 179 | GoToSeeker(reader, int64(es.NameOffset)) 180 | } 181 | err = es.Name.Parse(reader) 182 | if err != nil { 183 | return err 184 | } 185 | // If the name is not following, we have to restore in order to parse the remaining 186 | if backup != int64(es.NameOffset) { 187 | GoToSeeker(reader, backup) 188 | } 189 | if es.Token == TokenOpenStartElementTag2 { 190 | err = es.AttributeList.Parse(reader) 191 | if err != nil { 192 | return err 193 | } 194 | } 195 | 196 | err = encoding.Unmarshal(reader, &es.EOESToken, Endianness) 197 | if err != nil { 198 | return err 199 | } 200 | 201 | if es.EOESToken != TokenCloseStartElementTag && es.EOESToken != TokenCloseEmptyElementTag { 202 | if es.Token == TokenOpenStartElementTag1 { 203 | //panic(fmt.Errorf("Bad close element token (0x%02x) instead of 0x%02x", es.EOESToken, TokenCloseEmptyElementTag)) 204 | return fmt.Errorf("Bad close element token (0x%02x) instead of 0x%02x", es.EOESToken, TokenCloseEmptyElementTag) 205 | } else { 206 | //panic(fmt.Errorf("Bad close element token (0x%02x) instead of 0x%02x", es.EOESToken, TokenCloseStartElementTag)) 207 | return fmt.Errorf("Bad close element token (0x%02x) instead of 0x%02x", es.EOESToken, TokenCloseStartElementTag) 208 | } 209 | } 210 | // Go back by one byte in order to generate the appropriate BinXMLElement in the chain of parsed elements 211 | RelGoToSeeker(reader, -1) 212 | return err 213 | } 214 | 215 | func (es *ElementStart) HasName() bool { 216 | return es.NameOffset != DefaultNameOffset 217 | } 218 | 219 | func (es ElementStart) String() string { 220 | return fmt.Sprintf("%T: %s", es, string(ToJSON(es))) 221 | } 222 | 223 | /////////////////////////// BinXMLNormalSubstitution /////////////////////////// 224 | ///////////////////////// BinXMLOptionalSubstitution /////////////////////////// 225 | 226 | //NormalSubstitution : BinXmlNormalSubstitution 227 | type NormalSubstitution struct { 228 | Token int8 229 | SubID int16 230 | ValType int8 231 | } 232 | 233 | type OptionalSubstitution struct { 234 | NormalSubstitution 235 | } 236 | 237 | func (n *NormalSubstitution) Parse(reader io.ReadSeeker) error { 238 | err := encoding.Unmarshal(reader, &n.Token, Endianness) 239 | if err != nil { 240 | return err 241 | } 242 | err = encoding.Unmarshal(reader, &n.SubID, Endianness) 243 | if err != nil { 244 | return err 245 | } 246 | return encoding.Unmarshal(reader, &n.ValType, Endianness) 247 | } 248 | 249 | func (n *NormalSubstitution) IsAttributeData() bool { 250 | return true 251 | } 252 | 253 | func (n *NormalSubstitution) String() string { 254 | return fmt.Sprintf("%T: %[1]v", *n) 255 | } 256 | 257 | ///////////////////////////////// BinXMLAttribute ////////////////////////////// 258 | 259 | type Attribute struct { 260 | Token int8 261 | NameOffset int32 // relative to start of chunk 262 | Name Name 263 | AttributeData Element 264 | } 265 | 266 | func (a *Attribute) IsLast() bool { 267 | return a.Token == TokenAttribute1 268 | } 269 | 270 | func (a *Attribute) Parse(reader io.ReadSeeker) error { 271 | var err error 272 | err = encoding.Unmarshal(reader, &a.Token, Endianness) 273 | if err != nil { 274 | return err 275 | } 276 | if a.Token != TokenAttribute1 && a.Token != TokenAttribute2 { 277 | return fmt.Errorf("Bad attribute Token : 0x%02x", uint8(a.Token)) 278 | } 279 | err = encoding.Unmarshal(reader, &a.NameOffset, Endianness) 280 | if err != nil { 281 | return err 282 | } 283 | // It may happen that the name of the attribute is somewhere else but the data 284 | // is after the offset 285 | cursor := BackupSeeker(reader) 286 | if int64(a.NameOffset) != cursor { 287 | GoToSeeker(reader, int64(a.NameOffset)) 288 | } 289 | a.Name.Parse(reader) 290 | if int64(a.NameOffset) != cursor { 291 | GoToSeeker(reader, cursor) 292 | } 293 | // TODO: may cause bug because of tiFlag 294 | a.AttributeData, err = Parse(reader, nil, false) 295 | return err 296 | } 297 | 298 | ///////////////////////////// BinXMLAttributeList ////////////////////////////// 299 | 300 | type AttributeList struct { 301 | Size int32 302 | Attributes []Attribute 303 | } 304 | 305 | func (al *AttributeList) ParseSize(reader io.ReadSeeker) error { 306 | return encoding.Unmarshal(reader, &al.Size, Endianness) 307 | } 308 | 309 | func (al *AttributeList) ParseAttributes(reader io.ReadSeeker) error { 310 | var err error 311 | al.Attributes = make([]Attribute, 0) 312 | // We stop when we reached the size of the attribute list 313 | for { 314 | attr := Attribute{} 315 | err = attr.Parse(reader) 316 | if err != nil { 317 | return err 318 | } 319 | al.Attributes = append(al.Attributes, attr) 320 | // Test if the attribute is the last one of the list 321 | if attr.IsLast() { 322 | break 323 | } 324 | } 325 | return err 326 | } 327 | 328 | func (al *AttributeList) Parse(reader io.ReadSeeker) error { 329 | err := al.ParseSize(reader) 330 | if err != nil { 331 | return err 332 | } 333 | return al.ParseAttributes(reader) 334 | } 335 | 336 | //////////////////////////////////// Name ////////////////////////////////////// 337 | 338 | // Name : 339 | // same as ChunkString 340 | type Name struct { 341 | OffsetPrevString int32 342 | Hash uint16 343 | Size uint16 344 | UTF16String UTF16String 345 | } 346 | 347 | // Parse Element implementation 348 | func (n *Name) Parse(reader io.ReadSeeker) error { 349 | err := encoding.Unmarshal(reader, &n.OffsetPrevString, Endianness) 350 | if err != nil { 351 | return err 352 | } 353 | err = encoding.Unmarshal(reader, &n.Hash, Endianness) 354 | if err != nil { 355 | return err 356 | } 357 | err = encoding.Unmarshal(reader, &n.Size, Endianness) 358 | if err != nil { 359 | return err 360 | } 361 | 362 | // No need to control size since it is uint16 363 | n.UTF16String = make([]uint16, n.Size+1) 364 | 365 | err = encoding.UnmarshaInitSlice(reader, &n.UTF16String, Endianness) 366 | return err 367 | } 368 | 369 | func (n *Name) String() string { 370 | return n.UTF16String.ToString() 371 | } 372 | 373 | ///////////////////////////// BinXmlEntityReference //////////////////////////// 374 | 375 | type CharEntityRef struct { 376 | Token int8 377 | Value int16 378 | } 379 | 380 | func (cer *CharEntityRef) Parse(reader io.ReadSeeker) error { 381 | err := encoding.Unmarshal(reader, cer, Endianness) 382 | return err 383 | } 384 | 385 | ///////////////////////////////// BinXmlValueText ////////////////////////////// 386 | 387 | type ValueText struct { 388 | Token int8 389 | ValType int8 390 | Value UnicodeTextString // UnicodeTextString 391 | } 392 | 393 | func (vt *ValueText) String() string { 394 | return vt.Value.String.ToString() 395 | } 396 | 397 | func (vt *ValueText) IsAttributeData() bool { 398 | return true 399 | } 400 | 401 | func (vt *ValueText) Parse(reader io.ReadSeeker) error { 402 | err := encoding.Unmarshal(reader, &vt.Token, Endianness) 403 | if err != nil { 404 | return err 405 | } 406 | err = encoding.Unmarshal(reader, &vt.ValType, Endianness) 407 | if err != nil { 408 | return err 409 | } 410 | if vt.ValType != StringType { 411 | return fmt.Errorf("Bad type, must be (0x%02x) StringType", StringType) 412 | } 413 | err = vt.Value.Parse(reader) 414 | return err 415 | } 416 | 417 | ////////////////////////////// UnicodeTextString /////////////////////////////// 418 | 419 | type UnicodeTextString struct { 420 | Size int16 // Number of characters, has to be x2 421 | String UTF16String // UTF-16 little-endian string without an end-of-string character 422 | } 423 | 424 | func (uts *UnicodeTextString) Parse(reader io.ReadSeeker) error { 425 | err := encoding.Unmarshal(reader, &uts.Size, Endianness) 426 | if err != nil { 427 | return err 428 | } 429 | 430 | if uts.Size > 0 { 431 | uts.String = make(UTF16String, uts.Size) 432 | err = encoding.UnmarshaInitSlice(reader, &uts.String, Endianness) 433 | //log.Debugf("len:%d value:%s", uts.Size, string(uts.String.ToASCII())) 434 | } 435 | 436 | return err 437 | } 438 | 439 | func (uts *UnicodeTextString) GetSize() int32 { 440 | return 2 + int32(uts.Size)*2 441 | } 442 | 443 | ///////////////////////// Not Implemented Structures /////////////////////////// 444 | 445 | // EntityReference : BinXmlEntityReference 446 | type EntityReference struct { 447 | Token int8 448 | EntityNameOffset int32 449 | } 450 | 451 | // CDATASection : BinXmlCDATASection 452 | type CDATASection struct { 453 | Token int8 454 | Text UnicodeTextString 455 | } 456 | 457 | // PITarget : BinXmlPITarget 458 | type PITarget struct { 459 | Token int8 460 | NameOffset int32 // relative to start of chunk 461 | } 462 | 463 | // PIData : BinXmlPIData 464 | type PIData struct { 465 | Token int8 466 | Text UnicodeTextString 467 | } 468 | 469 | ////////////////////////// BinXmlTemplateInstance ////////////////////////////// 470 | 471 | func (ti *TemplateInstance) Root() Node { 472 | node, _ := NodeTree(ti.Definition.Data.Elements, 0) 473 | return node 474 | } 475 | 476 | func (ti *TemplateInstance) ElementToGoEvtx(elt Element) GoEvtxElement { 477 | switch elt.(type) { 478 | // BinXML specific 479 | case *ValueText: 480 | return elt.(*ValueText).String() 481 | case *OptionalSubstitution: 482 | s := elt.(*OptionalSubstitution) 483 | // Manage Carving mode 484 | switch { 485 | case int(s.SubID) < len(ti.Data.Values): 486 | return ti.ElementToGoEvtx(ti.Data.Values[int(s.SubID)]) 487 | case !ModeCarving: 488 | panic("Index out of range") 489 | default: 490 | return nil 491 | } 492 | case *NormalSubstitution: 493 | s := elt.(*NormalSubstitution) 494 | // Manage Carving mode 495 | switch { 496 | case int(s.SubID) < len(ti.Data.Values): 497 | return ti.ElementToGoEvtx(ti.Data.Values[int(s.SubID)]) 498 | case !ModeCarving: 499 | panic("Index out of range") 500 | default: 501 | return nil 502 | } 503 | case *Fragment: 504 | temp := elt.(*Fragment).BinXMLElement.(*TemplateInstance) 505 | root := temp.Root() 506 | return temp.NodeToGoEvtx(&root) 507 | case *TemplateInstance: 508 | temp := elt.(*TemplateInstance) 509 | root := temp.Root() 510 | return temp.NodeToGoEvtx(&root) 511 | case Value: 512 | if _, ok := elt.(Value).(*ValueNull); ok { 513 | // We return nil if is ValueNull 514 | return nil 515 | } 516 | return elt.(Value).Repr() 517 | case *BinXMLEntityReference: 518 | ers := elt.(*BinXMLEntityReference).String() 519 | if ers == "" { 520 | err := fmt.Errorf("Unknown entity reference: %s", ers) 521 | if !ModeCarving { 522 | panic(err) 523 | } else { 524 | log.Error(err) 525 | return nil 526 | } 527 | } 528 | return ers 529 | 530 | default: 531 | err := fmt.Errorf("Don't know how to handle: %T", elt) 532 | if !ModeCarving { 533 | panic(err) 534 | } else { 535 | log.Error(err) 536 | return nil 537 | } 538 | } 539 | } 540 | 541 | func (ti *TemplateInstance) NodeToGoEvtx(n *Node) GoEvtxMap { 542 | switch { 543 | case n.Start == nil && len(n.Child) == 1: 544 | m := make(GoEvtxMap) 545 | m[n.Child[0].Start.Name.String()] = ti.NodeToGoEvtx(n.Child[0]) 546 | return m 547 | 548 | default: 549 | m := make(GoEvtxMap, len(n.Child)) 550 | for i, c := range n.Child { 551 | node := ti.NodeToGoEvtx(c) 552 | switch { 553 | // It seems that on EVTX files forwarded to WECs we have sometime just a 554 | // Name attribute without value. We notice that this happened to Element 555 | // that can be NULL. Maybe it is a default assumption or it is due to an 556 | // upstream parsing bug unidentified yet. Anyway the easiest way is to 557 | // fix it here 558 | // Example: "EventData": { 559 | //"Data": { 560 | // "Name": "SourcePortName" 561 | //}, 562 | //"Data16": { 563 | // "Name": "DestinationPortName" 564 | //}, 565 | // We only have one element Name 566 | case node.HasKeys("Name") && len(node) == 1: 567 | m[node["Name"].(string)] = "" 568 | // Case where the Node only has two elements Name and Value 569 | case node.HasKeys("Name", "Value") && len(node) == 2: 570 | m[node["Name"].(string)] = node["Value"] 571 | // All the other cases 572 | default: 573 | name := c.Start.Name.String() 574 | if _, ok := m[name]; ok { 575 | name = fmt.Sprintf("%s%d", name, i) 576 | } 577 | // If there is only one key "Value" we do not create a full node 578 | // Name: {"Value": blob} but Name: blob instead 579 | //if node.HasKeys("Value") && len(node) == 1 { 580 | if node.HasKeys("Value") && len(node) == 1 { 581 | m[name] = node["Value"] 582 | } else { 583 | // All the other cases 584 | m[name] = node 585 | } 586 | } 587 | // If we have only keys like "Name" "Value" top level is useless 588 | /*if node.HasKeys("Name", "Value") && len(node) == 2 { 589 | } else { 590 | }*/ 591 | } 592 | 593 | // It is assumed that all the Elements have a string representation 594 | for _, e := range n.Element { 595 | ge := ti.ElementToGoEvtx(e) 596 | switch ge.(type) { 597 | case GoEvtxMap: 598 | other := ge.(GoEvtxMap) 599 | m.Add(other) 600 | case string: 601 | if ge != nil { 602 | if m["Value"] == nil { 603 | m["Value"] = ge.(string) 604 | } else { 605 | m["Value"] = m["Value"].(string) + ge.(string) 606 | } 607 | } 608 | default: 609 | m["Value"] = ti.ElementToGoEvtx(n.Element[0]) 610 | } 611 | } 612 | // n.Start can be NULL in carving mode 613 | if n.Start != nil { 614 | for _, attr := range n.Start.AttributeList.Attributes { 615 | gee := ti.ElementToGoEvtx(attr.AttributeData) 616 | // We have a ValueNull 617 | if gee != nil { 618 | m[attr.Name.String()] = gee 619 | } 620 | } 621 | } 622 | return m 623 | } 624 | } 625 | 626 | func (ti *TemplateInstance) GoEvtxMap() *GoEvtxMap { 627 | root := ti.Root() 628 | gem := ti.NodeToGoEvtx(&root) 629 | return &gem 630 | } 631 | 632 | // TemplateInstance : BinXmlTemplateInstance 633 | type TemplateInstance struct { 634 | Token int8 635 | Definition TemplateDefinition 636 | Data TemplateInstanceData 637 | } 638 | 639 | func (ti *TemplateInstance) DataOffset(reader io.ReadSeeker) (offset int32, err error) { 640 | backup := BackupSeeker(reader) 641 | GoToSeeker(reader, backup+6) 642 | err = encoding.Unmarshal(reader, &offset, Endianness) 643 | GoToSeeker(reader, backup) 644 | return 645 | } 646 | 647 | func (ti *TemplateInstance) ParseTemplateDefinitionHeader(reader io.ReadSeeker) error { 648 | err := encoding.Unmarshal(reader, &ti.Token, Endianness) 649 | if err != nil { 650 | return err 651 | } 652 | return ti.Definition.Header.Parse(reader) 653 | } 654 | 655 | func (ti *TemplateInstance) Parse(reader io.ReadSeeker) error { 656 | err := encoding.Unmarshal(reader, &ti.Token, Endianness) 657 | if err != nil { 658 | return err 659 | } 660 | err = ti.Definition.Parse(reader) 661 | if err != nil { 662 | return err 663 | } 664 | err = ti.Data.Parse(reader) 665 | return err 666 | } 667 | 668 | func (ti TemplateInstance) String() string { 669 | /*root, _ := NodeTree(ti.Definition.Elements, 0) 670 | node := root 671 | for*/ 672 | return fmt.Sprintf("%T: %s", ti, string(ToJSON(ti))) 673 | } 674 | 675 | ////////////////////////// BinXmlTemplateDefinition ////////////////////////////// 676 | 677 | type TemplateDefinitionHeader struct { 678 | Unknown1 int8 679 | Unknown2 int32 680 | DataOffset int32 681 | } 682 | 683 | func (tdh *TemplateDefinitionHeader) Parse(reader io.ReadSeeker) error { 684 | return encoding.Unmarshal(reader, tdh, Endianness) 685 | } 686 | 687 | type TemplateDefinitionData struct { 688 | Unknown3 int32 689 | ID [16]byte 690 | Size int32 691 | FragHeader FragmentHeader 692 | Elements []Element 693 | EOFToken int8 694 | } 695 | 696 | func (td *TemplateDefinitionData) Parse(reader io.ReadSeeker) error { 697 | err := encoding.Unmarshal(reader, &td.Unknown3, Endianness) 698 | if err != nil { 699 | return err 700 | } 701 | err = encoding.Unmarshal(reader, &td.ID, Endianness) 702 | if err != nil { 703 | return err 704 | } 705 | err = encoding.Unmarshal(reader, &td.Size, Endianness) 706 | if err != nil { 707 | return err 708 | } 709 | 710 | err = td.FragHeader.Parse(reader) 711 | if err != nil { 712 | return err 713 | } 714 | 715 | td.Elements = make([]Element, 0) 716 | for { 717 | var elt Element 718 | elt, err = Parse(reader, nil, true) 719 | if err != nil { 720 | //panic(err) 721 | return err 722 | } 723 | if _, ok := elt.(*BinXMLEOF); ok { 724 | td.EOFToken = TokenEOF 725 | break 726 | } 727 | td.Elements = append(td.Elements, elt) 728 | } 729 | return nil 730 | } 731 | 732 | type TemplateDefinition struct { 733 | Header TemplateDefinitionHeader 734 | Data TemplateDefinitionData 735 | } 736 | 737 | func (td *TemplateDefinition) Parse(reader io.ReadSeeker) error { 738 | err := td.Header.Parse(reader) 739 | if err != nil { 740 | return err 741 | } 742 | backup := BackupSeeker(reader) 743 | // The following of the structure is located elsewhere in the chunk 744 | if int64(td.Header.DataOffset) != backup { 745 | GoToSeeker(reader, int64(td.Header.DataOffset)) 746 | } 747 | err = td.Data.Parse(reader) 748 | if err != nil { 749 | return err 750 | } 751 | // If we jumped off to get the template we have to come back because the Data 752 | // Are still located after 753 | if int64(td.Header.DataOffset) != backup { 754 | GoToSeeker(reader, backup) 755 | } 756 | return err 757 | } 758 | 759 | func (td TemplateDefinition) String() string { 760 | //return fmt.Sprintf("Template DataOffset: %v\nID: %v\nSize: %v\nFragHeader: %v\nElement: %v\n", td.DataOffset, td.ID, td.Size, td.FragHeader, td.Element) 761 | return fmt.Sprintf("%T: %s", td, string(ToJSON(td))) 762 | } 763 | 764 | ////////////////////////// BinXmlTemplateInstanceData ////////////////////////// 765 | 766 | // TemplateInstanceData structure 767 | type TemplateInstanceData struct { 768 | NumValues int32 769 | ValDescs []ValueDescriptor 770 | Values []Element 771 | ValueOffsets []int32 772 | } 773 | 774 | // Parse Element implementation 775 | func (tid *TemplateInstanceData) Parse(reader io.ReadSeeker) error { 776 | err := encoding.Unmarshal(reader, &tid.NumValues, Endianness) 777 | if err != nil { 778 | return err 779 | } 780 | if tid.NumValues < 0 { 781 | return fmt.Errorf("Negative number of values in TemplateInstanceData") 782 | } 783 | // Cannot definitely not be bigger than MaxSliceSize 784 | if tid.NumValues > MaxSliceSize { 785 | return fmt.Errorf("Too many values in TemplateInstanceData") 786 | } 787 | // We can now allocate process the values 788 | tid.Values = make([]Element, tid.NumValues) 789 | tid.ValueOffsets = make([]int32, tid.NumValues) 790 | tid.ValDescs = make([]ValueDescriptor, tid.NumValues) 791 | if tid.NumValues > 0 { 792 | err = encoding.UnmarshaInitSlice(reader, &tid.ValDescs, Endianness) 793 | if err != nil { 794 | return err 795 | } 796 | } 797 | 798 | // Parse the values 799 | for i := int32(0); i < tid.NumValues; i++ { 800 | tid.Values[i], err = ParseValueReader(tid.ValDescs[i], reader) 801 | if err != nil { 802 | log.Errorf("%v : %s", tid.ValDescs[i], err) 803 | log.DebugDontPanicf("%v : %s", tid.ValDescs[i], err) 804 | } 805 | } 806 | return err 807 | } 808 | 809 | ///////////////////////// BinXMLValue Related Structures /////////////////////// 810 | 811 | type ValueDescriptor struct { 812 | Size uint16 813 | ValType ValueType 814 | Unknown int8 // 0x00 815 | } 816 | 817 | func (v ValueDescriptor) String() string { 818 | return fmt.Sprintf("Size: %d ValType: 0x%02x Unk: 0x%02x", v.Size, v.ValType, v.Unknown) 819 | } 820 | 821 | // The value data depends on the value type 822 | type ValueData []byte 823 | 824 | //////////////////////////////// BinXMLEOF ///////////////////////////////////// 825 | 826 | type BinXMLEOF struct { 827 | Token int8 828 | } 829 | 830 | func (b *BinXMLEOF) Parse(reader io.ReadSeeker) error { 831 | // TODO: Remove this security later 832 | /*rs := ReadSeekerSize(reader) 833 | cur, err := reader.Seek(0, os.SEEK_CUR) 834 | if err != nil { 835 | panic(err) 836 | } 837 | if rs-cur > 10 { 838 | log.Errorf("[Remove this message later] probably missing data (%d bytes)", rs-cur) 839 | DebugReader(reader, 10, 5) 840 | } 841 | // Go to end of reader 842 | //reader.Seek(0, os.SEEK_END)*/ 843 | return encoding.Unmarshal(reader, &b.Token, Endianness) 844 | } 845 | 846 | ///////////////////////////// BinXmlEntityReference //////////////////////////// 847 | 848 | // BinXMLEntityReference implementation 849 | type BinXMLEntityReference struct { 850 | Token int8 851 | NameOffset uint32 852 | Name Name 853 | } 854 | 855 | // Parse implements Element 856 | func (e *BinXMLEntityReference) Parse(reader io.ReadSeeker) error { 857 | err := encoding.Unmarshal(reader, &e.Token, Endianness) 858 | if err != nil { 859 | return err 860 | } 861 | err = encoding.Unmarshal(reader, &e.NameOffset, Endianness) 862 | if err != nil { 863 | return err 864 | } 865 | o := BackupSeeker(reader) 866 | // if the Entity Name is just after 867 | if int64(e.NameOffset) == o { 868 | return e.Name.Parse(reader) 869 | } 870 | // We jump to the right offset 871 | GoToSeeker(reader, int64(e.NameOffset)) 872 | err = e.Name.Parse(reader) 873 | // We restore our position 874 | GoToSeeker(reader, o) 875 | return err 876 | } 877 | 878 | func (e *BinXMLEntityReference) String() string { 879 | switch e.Name.String() { 880 | case "amp": 881 | return "&" 882 | case "lt": 883 | return "<" 884 | case "gt": 885 | return ">" 886 | case "quot": 887 | return "\"" 888 | case "apos": 889 | return "'" 890 | } 891 | return "" 892 | } 893 | 894 | ///////////////////////////// BinXMLEndElementTag ////////////////////////////// 895 | 896 | type Token struct { 897 | Token int8 898 | } 899 | 900 | func (t *Token) Parse(reader io.ReadSeeker) error { 901 | return encoding.Unmarshal(reader, &t.Token, Endianness) 902 | } 903 | 904 | type BinXMLEndElementTag struct { 905 | //Token int8 906 | Token 907 | } 908 | 909 | ///////////////////////// TokenCloseStartElementTag //////////////////////////// 910 | 911 | type BinXMLCloseStartElementTag struct { 912 | Token 913 | } 914 | 915 | ////////////////////////// TokenCloseEmptyElementTag /////////////////////////// 916 | 917 | type BinXMLCloseEmptyElementTag struct { 918 | Token 919 | } 920 | 921 | ////////////////////////////// EmptyElement //////////////////////////////////// 922 | 923 | type EmptyElement struct{} 924 | 925 | func (EmptyElement) Parse(reader io.ReadSeeker) error { 926 | return nil 927 | } 928 | -------------------------------------------------------------------------------- /evtx/test/evtx_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | "io/ioutil" 8 | "path/filepath" 9 | "regexp" 10 | "testing" 11 | "time" 12 | 13 | "github.com/0xrawsec/golang-utils/datastructs" 14 | 15 | "github.com/0xrawsec/golang-evtx/evtx" 16 | "github.com/0xrawsec/golang-utils/log" 17 | ) 18 | 19 | var ( 20 | // system.evtx 21 | oneChunckEvtx = "one-chunk.evtx" 22 | evtxFile = "system.evtx" 23 | forwardedEvtxFile = "forwarded-events.evtx" 24 | // Sysmon 25 | sysmonFile = "sysmon.evtx" 26 | // AppReadyness 27 | appReadyFile = "files/Microsoft-Windows-AppReadiness%4Operational.evtx" 28 | // NTFS Operational 29 | ntfsOperational = "files/Microsoft-Windows-Ntfs%4Operational.evtx" 30 | testfilesDir = "./files" 31 | sysmonEventCount = 50213 // computed externally with evtxexport 32 | ) 33 | 34 | func init() { 35 | //log.InitLogger(log.LDebug) 36 | } 37 | 38 | func TestParseAt(t *testing.T) { 39 | ef, _ := evtx.Open(sysmonFile) 40 | offsetChunk := 0x033c1000 41 | offsetElt := 0x21c 42 | 43 | c, err := ef.FetchRawChunk(int64(offsetChunk)) 44 | if err != nil && err != io.EOF { 45 | panic(err) 46 | } 47 | reader := bytes.NewReader(c.Data) 48 | evtx.GoToSeeker(reader, int64(offsetElt)) 49 | elt, _ := evtx.Parse(reader, &c, false) 50 | switch elt.(type) { 51 | case *evtx.Fragment: 52 | t.Log(string(evtx.ToJSON(elt.(*evtx.Fragment).GoEvtxMap()))) 53 | case *evtx.TemplateInstance: 54 | t.Log(string(evtx.ToJSON(elt.(*evtx.TemplateInstance).GoEvtxMap()))) 55 | default: 56 | t.Log(elt) 57 | 58 | } 59 | } 60 | 61 | func TestNodeTree(t *testing.T) { 62 | ef, _ := evtx.Open(evtxFile) 63 | offsetChunk := 0x00251000 64 | offsetElt := 1852 65 | 66 | c, err := ef.FetchRawChunk(int64(offsetChunk)) 67 | reader := bytes.NewReader(c.Data) 68 | evtx.GoToSeeker(reader, int64(offsetElt)) 69 | elt, err := evtx.Parse(reader, &c, false) 70 | if err != nil { 71 | log.Debug(elt) 72 | panic(err) 73 | } 74 | 75 | temp := elt.(*evtx.TemplateInstance) 76 | //Debug 77 | l := make([]string, len(temp.Definition.Data.Elements)) 78 | for _, e := range temp.Definition.Data.Elements { 79 | switch e.(type) { 80 | case *evtx.ElementStart: 81 | l = append(l, fmt.Sprintf("%T", e)) 82 | t.Log(e.(*evtx.ElementStart).Name.String()) 83 | case *evtx.OptionalSubstitution: 84 | l = append(l, fmt.Sprintf("%T", temp.Data.Values[e.(*evtx.OptionalSubstitution).SubID])) 85 | default: 86 | l = append(l, fmt.Sprintf("%T", e)) 87 | } 88 | } 89 | t.Log(l) 90 | // Debug 91 | gem := temp.GoEvtxMap() 92 | t.Log(string(evtx.ToJSON(gem))) 93 | if err != nil { 94 | t.Error(err) 95 | } 96 | t.Log(string(evtx.ToJSON(gem))) 97 | } 98 | 99 | func TestParseOneChunk(t *testing.T) { 100 | ef, _ := evtx.Open(forwardedEvtxFile) 101 | offsetChunk := int64(0x016e1000) 102 | c, err := ef.FetchChunk(offsetChunk) 103 | if err != nil && err != io.EOF { 104 | panic(err) 105 | } 106 | for _, eo := range c.EventOffsets { 107 | e := c.ParseEvent(int64(eo)) 108 | gem, _ := e.GoEvtxMap(&c) 109 | t.Log(string(evtx.ToJSON(gem))) 110 | } 111 | } 112 | 113 | func TestParseEventAt(t *testing.T) { 114 | ef, _ := evtx.Open(forwardedEvtxFile) 115 | offsetChunk := 0x016e1000 116 | offsetEvent := 0x016ef748 - offsetChunk 117 | c, err := ef.FetchChunk(int64(offsetChunk)) 118 | if err != nil && err != io.EOF { 119 | panic(err) 120 | } 121 | e := c.ParseEvent(int64(offsetEvent)) 122 | gem, err := e.GoEvtxMap(&c) 123 | if err != nil { 124 | panic(err) 125 | } 126 | t.Log(string(evtx.ToJSON(gem))) 127 | } 128 | 129 | func TestParseEventByID(t *testing.T) { 130 | filepath := appReadyFile 131 | t.Logf("Parsing: %s ", filepath) 132 | ef, _ := evtx.Open(filepath) 133 | eventRecordID := int64(1448) 134 | loop: 135 | for c := range ef.Chunks() { 136 | for _, eo := range c.EventOffsets { 137 | e := c.ParseEvent(int64(eo)) 138 | if e.Header.ID == eventRecordID { 139 | t.Logf("Offset Chunk: 0x%08x", c.Offset) 140 | t.Logf("Offset Event: 0x%08x", eo) 141 | gem, _ := e.GoEvtxMap(&c) 142 | t.Log(string(evtx.ToJSON(gem))) 143 | break loop 144 | } 145 | } 146 | } 147 | } 148 | 149 | func TestParseAllEvents(t *testing.T) { 150 | eventCnt := 0 151 | recordIds := datastructs.NewSyncedSet() 152 | ef, err := evtx.OpenDirty(sysmonFile) 153 | if err != nil { 154 | t.Logf("Failed at opening EVTX file: %s", err) 155 | t.Fail() 156 | } 157 | log.Info(ef.Header) 158 | for e := range ef.Events() { 159 | if recordIds.Contains(e.EventRecordID()) { 160 | t.Log("Event already processed") 161 | t.Fail() 162 | } 163 | //t.Log(string(evtx.ToJSON(e))) 164 | recordIds.Add(e.EventRecordID()) 165 | eventCnt++ 166 | 167 | } 168 | t.Logf("%d events parsed", eventCnt) 169 | } 170 | 171 | func TestParseChunk(t *testing.T) { 172 | if testing.Short() { 173 | t.Skip("Skipping in short test") 174 | } 175 | ef, _ := evtx.Open(sysmonFile) 176 | for e := range ef.FastEvents() { 177 | t.Log(string(evtx.ToJSON(e))) 178 | } 179 | } 180 | 181 | /*func TestMonitorChunks(t *testing.T) { 182 | ef, _ := evtx.Open(sysmonFile) 183 | stop := make(chan bool, 1) 184 | go func() { 185 | time.Sleep(time.Second * 10) 186 | stop <- true 187 | }() 188 | for c := range ef.MonitorChunks(stop, evtx.DefaultMonitorSleep) { 189 | t.Log(c.String()) 190 | } 191 | }*/ 192 | 193 | func TestRightOrderSlowEvents(t *testing.T) { 194 | ef, _ := evtx.Open(sysmonFile) 195 | i := 0 196 | prevErid := uint64(0) 197 | sPath := evtx.Path("/Event/System/EventRecordID/Value") 198 | for e := range ef.Events() { 199 | erid := e.GetUintStrict(&sPath) 200 | if erid < prevErid { 201 | t.Fatalf("Order is not guaranteed") 202 | } 203 | prevErid = erid 204 | i++ 205 | } 206 | if sysmonEventCount != i { 207 | t.Fatalf("Bad event count %d instead of %d", i, sysmonEventCount) 208 | } 209 | t.Logf("Order is guaranteed accross events, %d events parsed", i) 210 | } 211 | 212 | func TestRightOrderFastEvents(t *testing.T) { 213 | ef, _ := evtx.Open(sysmonFile) 214 | prevErid := int64(0) 215 | i := 0 216 | for e := range ef.FastEvents() { 217 | erid := e.EventRecordID() 218 | if erid < prevErid { 219 | t.Fatalf("Order is not guaranteed") 220 | } 221 | prevErid = erid 222 | i++ 223 | } 224 | if sysmonEventCount != i { 225 | t.Fatalf("Bad event count %d instead of %d", i, sysmonEventCount) 226 | } 227 | t.Logf("Order is guaranteed accross events, %d events parsed", i) 228 | } 229 | 230 | func TestFilter(t *testing.T) { 231 | ef, _ := evtx.Open(sysmonFile) 232 | p := evtx.Path("/Event/EventData/Data1/Value") 233 | for e := range ef.FastEvents() { 234 | if e.Equal(&p, "B2796A13-E43D-5880-0000-0010C55A0F00") { 235 | t.Log(string(evtx.ToJSON(e))) 236 | break 237 | } 238 | } 239 | } 240 | 241 | func TestEventIDFilter(t *testing.T) { 242 | ef, _ := evtx.Open(sysmonFile) 243 | for e := range ef.FastEvents() { 244 | if e.IsEventID("1", "12") { 245 | t.Log(string(evtx.ToJSON(e))) 246 | } 247 | } 248 | } 249 | 250 | func TestPatternFilter(t *testing.T) { 251 | pattern := regexp.MustCompile("MD5=D81F3ABB789C1D4504203171467A5E4E") 252 | ef, _ := evtx.Open(sysmonFile) 253 | p := evtx.Path("/Event/EventData/Data11/Value") 254 | for e := range ef.FastEvents() { 255 | if e.RegexMatch(&p, pattern) { 256 | t.Log(string(evtx.ToJSON(e))) 257 | break 258 | } 259 | } 260 | } 261 | 262 | func TestMapFilter(t *testing.T) { 263 | ef, _ := evtx.Open(sysmonFile) 264 | p := evtx.Path("/Event/EventData/Data11/Name") 265 | for e := range ef.FastEvents() { 266 | m, err := e.GetMap(&p) 267 | if err == nil { 268 | t.Log(string(evtx.ToJSON(m))) 269 | break 270 | } 271 | } 272 | } 273 | 274 | func TestMapWhereFilter(t *testing.T) { 275 | ef, _ := evtx.Open(sysmonFile) 276 | p := evtx.Path("/Event/EventData/Data1/Name") 277 | for e := range ef.FastEvents() { 278 | m, err := e.GetMapWhere(&p, "SourceProcessGUID") 279 | if err == nil { 280 | t.Log(string(evtx.ToJSON(m))) 281 | break 282 | } 283 | } 284 | } 285 | 286 | func TestBetweenFilter(t *testing.T) { 287 | i := 0 288 | ef, _ := evtx.Open(sysmonFile) 289 | t1, err := time.Parse(time.RFC3339, "2017-01-19T17:07:20+01:00") 290 | if err != nil { 291 | panic(err) 292 | } 293 | t2, err := time.Parse(time.RFC3339, "2017-01-19T17:07:21+01:00") 294 | if err != nil { 295 | panic(err) 296 | } 297 | for e := range ef.FastEvents() { 298 | if e.Between(t1, t2) { 299 | t.Log(string(evtx.ToJSON(e))) 300 | i++ 301 | } 302 | } 303 | t.Logf("%d events between %v and %v", i, t1, t2) 304 | } 305 | 306 | func TestDelete(t *testing.T) { 307 | utctimePath := evtx.Path("/Event/EventData/UtcTime") 308 | ef, _ := evtx.Open(sysmonFile) 309 | for e := range ef.FastEvents() { 310 | e.Del(&utctimePath) 311 | if _, err := e.GetString(&utctimePath); err == nil { 312 | t.Errorf("Failed to delete field") 313 | t.FailNow() 314 | } 315 | } 316 | } 317 | 318 | func TestAddDelete(t *testing.T) { 319 | geneInfoPath := evtx.Path("/Event/GeneInfo") 320 | genInfo := map[string]interface{}{ 321 | "Signature": []string{"test", "blop"}, 322 | "Criticality": 10} 323 | ef, _ := evtx.Open(sysmonFile) 324 | for e := range ef.FastEvents() { 325 | e.Set(&geneInfoPath, genInfo) 326 | e.Del(&geneInfoPath) 327 | if _, err := e.Get(&geneInfoPath); err == nil { 328 | t.Errorf("Failed to delete field") 329 | t.FailNow() 330 | } 331 | } 332 | } 333 | 334 | func TestAllFiles(t *testing.T) { 335 | files, err := ioutil.ReadDir(testfilesDir) 336 | if err != nil { 337 | panic(err) 338 | } 339 | for _, fi := range files { 340 | fullpath := filepath.Join(testfilesDir, fi.Name()) 341 | t.Logf("Parsing : %s", fullpath) 342 | ef, _ := evtx.Open(fullpath) 343 | for _ = range ef.FastEvents() { 344 | } 345 | } 346 | } 347 | 348 | func TestUserID(t *testing.T) { 349 | files, err := ioutil.ReadDir(testfilesDir) 350 | if err != nil { 351 | panic(err) 352 | } 353 | for _, fi := range files { 354 | fullpath := filepath.Join(testfilesDir, fi.Name()) 355 | ef, _ := evtx.Open(fullpath) 356 | for e := range ef.FastEvents() { 357 | if uid, ok := e.UserID(); ok { 358 | if uid == "" { 359 | t.Log(string(evtx.ToJSON(e))) 360 | } 361 | t.Log(uid) 362 | } 363 | } 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /evtx/todo.txt: -------------------------------------------------------------------------------- 1 | TODO before publish:  2 | 1) Document and clean the code 3 | 2) Search for the unknown values 4 | 3) Create a Value interface and reduce code 5 | 4) Add control for File and Chunk headers 6 | -------------------------------------------------------------------------------- /evtx/utils.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "os" 8 | "strings" 9 | "time" 10 | "unicode/utf16" 11 | 12 | "github.com/0xrawsec/golang-utils/log" 13 | ) 14 | 15 | ///////////////////////////// Utility Functions //////////////////////////////// 16 | 17 | func ReadSeekerSize(reader io.ReadSeeker) int64 { 18 | old, err := reader.Seek(0, os.SEEK_CUR) 19 | if err != nil { 20 | panic(err) 21 | } 22 | len, err := reader.Seek(0, os.SEEK_END) 23 | if err != nil { 24 | panic(err) 25 | } 26 | _, err = reader.Seek(old, os.SEEK_SET) 27 | if err != nil { 28 | panic(err) 29 | } 30 | return len 31 | } 32 | 33 | func ToJSON(data interface{}) []byte { 34 | b, err := json.Marshal(data) 35 | if err != nil { 36 | panic(err) 37 | } 38 | return b 39 | } 40 | 41 | func DebugReader(reader io.ReadSeeker, before, after int64) { 42 | cur, err := reader.Seek(0, os.SEEK_CUR) 43 | if err != nil { 44 | panic(err) 45 | } 46 | if cur >= before { 47 | _, err = reader.Seek(-before, os.SEEK_CUR) 48 | } else { 49 | _, err = reader.Seek(0, os.SEEK_SET) 50 | } 51 | if err != nil { 52 | log.Debugf("before: %d, cur: %d", before, cur) 53 | panic(err) 54 | } 55 | b := make([]byte, before+after) 56 | reader.Read(b) 57 | var out string 58 | out += fmt.Sprintf("Relative offset: 0x%08x\n", cur) 59 | out += "Last parsed elements : " 60 | lastParsedElements.RLock() 61 | for _, e := range lastParsedElements.elements { 62 | out += fmt.Sprintf("%T, ", e) 63 | } 64 | lastParsedElements.RUnlock() 65 | out += "\n" 66 | for i, c := range b { 67 | if int64(i) == before { 68 | out += fmt.Sprintf(">%02x< ", c) 69 | } else { 70 | out += fmt.Sprintf("%02x ", c) 71 | } 72 | } 73 | out += "\n" 74 | out += fmt.Sprintf("r2 helper: %x", b) 75 | log.Debug(out) 76 | _, err = reader.Seek(cur, os.SEEK_SET) 77 | if err != nil { 78 | panic(err) 79 | } 80 | } 81 | 82 | func UpdateLastElements(e Element) { 83 | // There is a data race triggered there by the race 84 | // detector however it is an acceptable race since it 85 | // is a function used for debugging purposes. 86 | // issue: https://github.com/0xrawsec/golang-evtx/issues/25 87 | if Debug { 88 | lastParsedElements.Lock() 89 | defer lastParsedElements.Unlock() 90 | copy(lastParsedElements.elements[:], lastParsedElements.elements[1:]) 91 | lastParsedElements.elements[len(lastParsedElements.elements)-1] = e 92 | } 93 | } 94 | 95 | func BackupSeeker(seeker io.Seeker) int64 { 96 | backup, err := seeker.Seek(0, os.SEEK_CUR) 97 | if err != nil { 98 | panic(err) 99 | } 100 | return backup 101 | } 102 | 103 | func GoToSeeker(seeker io.Seeker, offset int64) { 104 | _, err := seeker.Seek(offset, os.SEEK_SET) 105 | if err != nil { 106 | //panic(err) 107 | } 108 | } 109 | 110 | func RelGoToSeeker(seeker io.Seeker, offset int64) { 111 | _, err := seeker.Seek(offset, os.SEEK_CUR) 112 | if err != nil { 113 | //panic(err) 114 | } 115 | } 116 | 117 | //////////////////////////////// UTF16String /////////////////////////////////// 118 | // NB: We keep those structure for compatibility with parts of the code 119 | type UTF16 uint16 120 | 121 | type UTF16String []uint16 122 | 123 | var ( 124 | UTF16EndOfString = uint16(0x0) 125 | ) 126 | 127 | func (us *UTF16String) Len() int32 { 128 | return int32(len(*us)) * 2 129 | } 130 | 131 | func (us UTF16String) ToString() string { 132 | return strings.TrimRight(string(utf16.Decode([]uint16(us))), "\u0000") 133 | } 134 | 135 | /////////////////////////////////// UTCTime /////////////////////////////////// 136 | 137 | // UTCTime structure definition 138 | type UTCTime time.Time 139 | 140 | // MarshalJSON implements JSON serialization 141 | func (u UTCTime) MarshalJSON() ([]byte, error) { 142 | return []byte(fmt.Sprintf("\"%s\"", time.Time(u).UTC().Format(time.RFC3339Nano))), nil 143 | } 144 | 145 | /////////////////////////////////// FileTime ///////////////////////////////// 146 | 147 | type FileTime struct { 148 | Nanoseconds int64 149 | } 150 | 151 | func (v *FileTime) Convert() (sec int64, nsec int64) { 152 | nano := int64(10000000) 153 | //milli := int64(10000) 154 | sec = int64(float64(v.Nanoseconds)/float64(nano) - 11644473600.0) 155 | nsec = ((v.Nanoseconds - 11644473600*nano) - sec*nano) * 100 156 | return 157 | } 158 | 159 | func (s *FileTime) Time() UTCTime { 160 | sec, nsec := s.Convert() 161 | return UTCTime(time.Unix(sec, nsec)) 162 | } 163 | 164 | func (s *FileTime) String() string { 165 | //"2015-12-10T17:56:53.515800800Z" 166 | sec, nsec := s.Convert() 167 | return time.Unix(sec, nsec).Format(time.RFC3339Nano) 168 | } 169 | -------------------------------------------------------------------------------- /evtx/values.go: -------------------------------------------------------------------------------- 1 | package evtx 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "os" 9 | "time" 10 | 11 | "github.com/0xrawsec/golang-utils/encoding" 12 | ) 13 | 14 | type Value interface { 15 | // Repr is the way it is represented in GoEvtx 16 | Repr() interface{} 17 | Value() interface{} 18 | String() string 19 | } 20 | 21 | type ValueType uint8 22 | 23 | ////////////////////////////////// Utilities /////////////////////////////////// 24 | 25 | func (v *ValueType) IsType(tvt ValueType) bool { 26 | return *v == tvt 27 | } 28 | 29 | func (v *ValueType) IsArray() bool { 30 | return (*v)&ArrayType == ArrayType 31 | } 32 | 33 | func (v *ValueType) IsArrayOf(tvt ValueType) bool { 34 | return v.IsArray() && ((*v)&tvt == tvt) 35 | } 36 | 37 | ////////////////////////////////// NullType //////////////////////////////////// 38 | 39 | type UnkVal struct { 40 | Offset int64 41 | Token ValueType 42 | Desc ValueDescriptor 43 | } 44 | 45 | func (*UnkVal) Parse(reader io.ReadSeeker) error { 46 | return nil 47 | } 48 | 49 | func (u *UnkVal) String() string { 50 | return fmt.Sprintf("Unknown value: %s @ 0x%08x", u.Desc, u.Offset) 51 | } 52 | 53 | func (u *UnkVal) Repr() interface{} { 54 | return u.String() 55 | } 56 | 57 | func (u *UnkVal) Value() interface{} { 58 | return u.Token 59 | } 60 | 61 | ////////////////////////////////// NullType //////////////////////////////////// 62 | 63 | type ValueNull struct { 64 | Size uint16 65 | } 66 | 67 | func (n *ValueNull) Parse(reader io.ReadSeeker) error { 68 | _, err := reader.Seek(int64(n.Size), os.SEEK_CUR) 69 | return err 70 | } 71 | 72 | func (ValueNull) String() string { 73 | return "" 74 | } 75 | 76 | func (ValueNull) Value() interface{} { 77 | return nil 78 | } 79 | 80 | func (ValueNull) Repr() interface{} { 81 | return "NULL" 82 | } 83 | 84 | ////////////////////////////////// Int8 /////////////////////////////////////// 85 | 86 | type ValueInt8 struct { 87 | value int8 88 | } 89 | 90 | func (i *ValueInt8) Parse(reader io.ReadSeeker) error { 91 | return encoding.Unmarshal(reader, &i.value, Endianness) 92 | } 93 | 94 | func (i *ValueInt8) String() string { 95 | return fmt.Sprintf("%d", i.value) 96 | } 97 | 98 | func (i *ValueInt8) Value() interface{} { 99 | return i.value 100 | } 101 | 102 | func (i *ValueInt8) Repr() interface{} { 103 | return i.String() 104 | } 105 | 106 | ////////////////////////////////// UInt8 /////////////////////////////////////// 107 | 108 | type ValueUInt8 struct { 109 | value uint8 110 | } 111 | 112 | func (u *ValueUInt8) Parse(reader io.ReadSeeker) error { 113 | return encoding.Unmarshal(reader, &u.value, Endianness) 114 | } 115 | 116 | func (u *ValueUInt8) String() string { 117 | return fmt.Sprintf("%d", u.value) 118 | } 119 | 120 | func (u *ValueUInt8) Value() interface{} { 121 | return u.value 122 | } 123 | 124 | func (u *ValueUInt8) Repr() interface{} { 125 | return u.String() 126 | } 127 | 128 | ////////////////////////////////// Int16 /////////////////////////////////////// 129 | 130 | type ValueInt16 struct { 131 | value int16 132 | } 133 | 134 | func (i *ValueInt16) Parse(reader io.ReadSeeker) error { 135 | return encoding.Unmarshal(reader, &i.value, Endianness) 136 | } 137 | 138 | func (i *ValueInt16) String() string { 139 | return fmt.Sprintf("%d", i.value) 140 | } 141 | 142 | func (i *ValueInt16) Value() interface{} { 143 | return i.value 144 | } 145 | 146 | func (i *ValueInt16) Repr() interface{} { 147 | return i.String() 148 | } 149 | 150 | ////////////////////////////////// UInt16 ////////////////////////////////////// 151 | 152 | type ValueUInt16 struct { 153 | value uint16 154 | } 155 | 156 | func (u *ValueUInt16) Parse(reader io.ReadSeeker) error { 157 | return encoding.Unmarshal(reader, &u.value, Endianness) 158 | } 159 | 160 | func (u *ValueUInt16) String() string { 161 | return fmt.Sprintf("%d", u.value) 162 | } 163 | 164 | func (u *ValueUInt16) Value() interface{} { 165 | return u.value 166 | } 167 | 168 | func (u *ValueUInt16) Repr() interface{} { 169 | return u.String() 170 | } 171 | 172 | ////////////////////////////////// Int32 ////////////////////////////////////// 173 | 174 | type ValueInt32 struct { 175 | value int32 176 | } 177 | 178 | func (i *ValueInt32) Parse(reader io.ReadSeeker) error { 179 | return encoding.Unmarshal(reader, &i.value, Endianness) 180 | } 181 | 182 | func (i *ValueInt32) String() string { 183 | return fmt.Sprintf("%d", i.value) 184 | } 185 | 186 | func (i *ValueInt32) Value() interface{} { 187 | return i.value 188 | } 189 | 190 | func (i *ValueInt32) Repr() interface{} { 191 | return i.String() 192 | } 193 | 194 | ////////////////////////////////// UInt32 ////////////////////////////////////// 195 | ////////////////////////////////// ValueHexInt32 /////////////////////////////// 196 | 197 | type ValueUInt32 struct { 198 | value uint32 199 | } 200 | 201 | type ValueHexInt32 struct { 202 | ValueUInt32 203 | } 204 | 205 | func (u *ValueUInt32) Parse(reader io.ReadSeeker) error { 206 | return encoding.Unmarshal(reader, &u.value, Endianness) 207 | } 208 | 209 | func (u *ValueUInt32) String() string { 210 | return fmt.Sprintf("%d", u.value) 211 | } 212 | 213 | func (u *ValueUInt32) Value() interface{} { 214 | return u.value 215 | } 216 | 217 | func (u *ValueUInt32) Repr() interface{} { 218 | return u.String() 219 | } 220 | 221 | func (i *ValueHexInt32) String() string { 222 | return fmt.Sprintf("0x%04x", i.value) 223 | } 224 | 225 | func (i *ValueHexInt32) Value() interface{} { 226 | return i.Value() 227 | } 228 | 229 | func (i *ValueHexInt32) Repr() interface{} { 230 | return i.String() 231 | } 232 | 233 | ////////////////////////////////// Int32 ////////////////////////////////////// 234 | 235 | type ValueInt64 struct { 236 | value int64 237 | } 238 | 239 | func (i *ValueInt64) Parse(reader io.ReadSeeker) error { 240 | return encoding.Unmarshal(reader, &i.value, Endianness) 241 | } 242 | 243 | func (i *ValueInt64) String() string { 244 | return fmt.Sprintf("%d", i.value) 245 | } 246 | 247 | func (i *ValueInt64) Value() interface{} { 248 | return i.value 249 | } 250 | 251 | func (i *ValueInt64) Repr() interface{} { 252 | return i.String() 253 | } 254 | 255 | ////////////////////////////////// UInt64 ////////////////////////////////////// 256 | ///////////////////////////////// HexInt64Type ///////////////////////////////// 257 | 258 | type ValueUInt64 struct { 259 | value uint64 260 | } 261 | 262 | // Just for display so that we have not the unsigned format of fmt 263 | type ValueHexInt64 struct { 264 | ValueUInt64 265 | } 266 | 267 | func (u *ValueUInt64) Parse(reader io.ReadSeeker) error { 268 | return encoding.Unmarshal(reader, &u.value, Endianness) 269 | } 270 | 271 | func (u *ValueUInt64) String() string { 272 | return fmt.Sprintf("%d", u.value) 273 | } 274 | 275 | func (u *ValueUInt64) Value() interface{} { 276 | return u.value 277 | } 278 | 279 | func (u *ValueUInt64) Repr() interface{} { 280 | return u.String() 281 | } 282 | 283 | func (i *ValueHexInt64) String() string { 284 | return fmt.Sprintf("0x%08x", i.value) 285 | } 286 | 287 | func (i *ValueHexInt64) Value() interface{} { 288 | return i.Value() 289 | } 290 | 291 | func (i *ValueHexInt64) Repr() interface{} { 292 | return i.String() 293 | } 294 | 295 | ///////////////////////////////// Real32Type ////////////////////////////////// 296 | /// Experimental 297 | 298 | type ValueReal32 struct { 299 | value float32 300 | } 301 | 302 | func (v *ValueReal32) Parse(reader io.ReadSeeker) error { 303 | return encoding.Unmarshal(reader, &v.value, Endianness) 304 | } 305 | 306 | func (v *ValueReal32) String() string { 307 | return fmt.Sprintf("%f", v.value) 308 | } 309 | 310 | func (v *ValueReal32) Value() interface{} { 311 | return v.value 312 | } 313 | 314 | func (v *ValueReal32) Repr() interface{} { 315 | return v.String() 316 | } 317 | 318 | ///////////////////////////////// Real64Type ////////////////////////////////// 319 | 320 | type ValueReal64 struct { 321 | value float64 322 | } 323 | 324 | func (v *ValueReal64) Parse(reader io.ReadSeeker) error { 325 | return encoding.Unmarshal(reader, &v.value, Endianness) 326 | } 327 | 328 | func (v *ValueReal64) String() string { 329 | return fmt.Sprintf("%f", v.value) 330 | } 331 | 332 | func (v *ValueReal64) Value() interface{} { 333 | return v.value 334 | } 335 | 336 | func (v *ValueReal64) Repr() interface{} { 337 | return v.String() 338 | } 339 | 340 | ///////////////////////////////// UTF16String ////////////////////////////////// 341 | 342 | type ValueString struct { 343 | Size uint16 344 | value UTF16String 345 | } 346 | 347 | func (s *ValueString) Parse(reader io.ReadSeeker) error { 348 | if s.Size > 0 { 349 | s.value = make(UTF16String, s.Size/2) 350 | return encoding.UnmarshaInitSlice(reader, &s.value, Endianness) 351 | } 352 | return nil 353 | } 354 | 355 | func (s *ValueString) String() string { 356 | return s.value.ToString() 357 | } 358 | 359 | func (s *ValueString) Value() interface{} { 360 | return s.value 361 | } 362 | 363 | func (s *ValueString) Repr() interface{} { 364 | return s.String() 365 | } 366 | 367 | ///////////////////////////// UTF16StringArray ///////////////////////////////// 368 | 369 | type ValueStringTable struct { 370 | Size uint16 371 | value []UTF16String 372 | } 373 | 374 | func (st *ValueStringTable) Parse(reader io.ReadSeeker) error { 375 | //cp := UTF16{} 376 | cp := uint16(0) 377 | st.value = make([]UTF16String, 0) 378 | s := make(UTF16String, 0) 379 | for i := 0; i < int(st.Size/2); i++ { 380 | err := encoding.Unmarshal(reader, &cp, Endianness) 381 | if err != nil { 382 | panic(err) 383 | } 384 | if cp == UTF16EndOfString { 385 | if len(s) > 0 { 386 | st.value = append(st.value, s) 387 | s = make(UTF16String, 0) 388 | } 389 | continue 390 | } 391 | s = append(s, cp) 392 | } 393 | return nil 394 | } 395 | 396 | func (st *ValueStringTable) Bytes() []byte { 397 | w := new(bytes.Buffer) 398 | w.Write([]byte("[")) 399 | for i, elt := range st.value { 400 | if elt.Len() == 0 { 401 | continue 402 | } 403 | w.Write([]byte(`"`)) 404 | w.Write([]byte(elt.ToString())) 405 | w.Write([]byte(`"`)) 406 | // Last element is always empty 407 | if i != len(st.value)-2 { 408 | w.Write([]byte(`, `)) 409 | } 410 | } 411 | w.Write([]byte("]")) 412 | return w.Bytes() 413 | } 414 | 415 | func (st *ValueStringTable) String() string { 416 | return string(st.Bytes()) 417 | } 418 | 419 | func (st *ValueStringTable) Value() interface{} { 420 | return st.value 421 | } 422 | 423 | func (st *ValueStringTable) Repr() interface{} { 424 | var out []string 425 | for _, elt := range st.value { 426 | if elt.Len() == 0 { 427 | continue 428 | } 429 | out = append(out, elt.ToString()) 430 | } 431 | return out 432 | } 433 | 434 | ///////////////////////////// ValueArrayInt16 ///////////////////////////////// 435 | 436 | type ValueArrayUInt16 struct { 437 | Size uint16 438 | value []uint16 439 | } 440 | 441 | func (a *ValueArrayUInt16) Parse(reader io.ReadSeeker) error { 442 | if a.Size > 0 { 443 | if a.Size%2 == 0 { 444 | a.value = make([]uint16, int(a.Size/2)) 445 | return encoding.UnmarshaInitSlice(reader, &a.value, Endianness) 446 | } 447 | return errors.New("Bad size data") 448 | } 449 | return nil 450 | } 451 | 452 | func (a *ValueArrayUInt16) String() string { 453 | return fmt.Sprintf("%v", a.value) 454 | } 455 | 456 | func (a *ValueArrayUInt16) Value() interface{} { 457 | return a.value 458 | } 459 | 460 | func (a *ValueArrayUInt16) Repr() interface{} { 461 | return a.value 462 | } 463 | 464 | ///////////////////////////// ValueArrayUInt64 ///////////////////////////////// 465 | 466 | type ValueArrayUInt64 struct { 467 | Size uint16 468 | value []uint64 469 | } 470 | 471 | func (a *ValueArrayUInt64) Parse(reader io.ReadSeeker) error { 472 | if a.Size > 0 { 473 | if a.Size%8 == 0 { 474 | a.value = make([]uint64, int(a.Size/8)) 475 | return encoding.UnmarshaInitSlice(reader, &a.value, Endianness) 476 | } 477 | return errors.New("Bad size data") 478 | } 479 | return nil 480 | } 481 | 482 | func (a *ValueArrayUInt64) String() string { 483 | return fmt.Sprintf("%v", a.value) 484 | } 485 | 486 | func (a *ValueArrayUInt64) Value() interface{} { 487 | return a.value 488 | } 489 | 490 | func (a *ValueArrayUInt64) Repr() interface{} { 491 | return a.value 492 | } 493 | 494 | ////////////////////////////////// ANSIString ////////////////////////////////// 495 | 496 | type AnsiString struct { 497 | Size uint16 498 | value []byte 499 | } 500 | 501 | func (as *AnsiString) Parse(reader io.ReadSeeker) error { 502 | as.value = make([]byte, as.Size) 503 | return encoding.UnmarshaInitSlice(reader, &as.value, Endianness) 504 | } 505 | 506 | func (as *AnsiString) String() string { 507 | return string(as.value) 508 | } 509 | 510 | func (as *AnsiString) Value() interface{} { 511 | return as.value 512 | } 513 | 514 | func (as *AnsiString) Repr() interface{} { 515 | return as.value 516 | } 517 | 518 | /////////////////////////////////// SystemTime ///////////////////////////////// 519 | 520 | type SysTime struct { 521 | Year int16 522 | Month int16 523 | DayOfWeek int16 524 | DayOfMonth int16 525 | Hours int16 526 | Minutes int16 527 | Seconds int16 528 | Milliseconds int16 529 | } 530 | 531 | func (s *SysTime) String() string { 532 | //"2015-12-10T17:56:53.515800800Z" 533 | return fmt.Sprintf("%d-%d-%dT%d:%d:%d.%dZ", s.Year, s.Month, s.DayOfMonth, s.Hours, s.Minutes, s.Seconds, s.Milliseconds) 534 | } 535 | 536 | type ValueSysTime struct { 537 | value SysTime 538 | } 539 | 540 | func (s *ValueSysTime) Parse(reader io.ReadSeeker) error { 541 | return encoding.Unmarshal(reader, &s.value, Endianness) 542 | } 543 | 544 | func (s *ValueSysTime) Time() UTCTime { 545 | return UTCTime(time.Date(int(s.value.Year), 546 | time.Month(s.value.Month), 547 | int(s.value.DayOfMonth), 548 | int(s.value.Hours), 549 | int(s.value.Minutes), 550 | int(s.value.Seconds), 551 | int(s.value.Milliseconds)*1000, 552 | time.UTC)) 553 | } 554 | 555 | func (s *ValueSysTime) String() string { 556 | return s.value.String() 557 | } 558 | 559 | func (s *ValueSysTime) Value() interface{} { 560 | return s.value 561 | } 562 | 563 | func (s *ValueSysTime) Repr() interface{} { 564 | return s.Time() 565 | } 566 | 567 | /////////////////////////////////// ValueFileTime ////////////////////////////// 568 | 569 | type ValueFileTime struct { 570 | value FileTime 571 | } 572 | 573 | func (s *ValueFileTime) Parse(reader io.ReadSeeker) error { 574 | return encoding.Unmarshal(reader, &s.value, Endianness) 575 | } 576 | 577 | func (s *ValueFileTime) String() string { 578 | return s.value.String() 579 | } 580 | 581 | func (s *ValueFileTime) Value() interface{} { 582 | return s.value.Time() 583 | } 584 | 585 | func (s *ValueFileTime) Repr() interface{} { 586 | return s.value.Time() 587 | } 588 | 589 | ///////////////////////////////// ValueBool ////////////////////////////////// 590 | 591 | type ValueBool struct { 592 | ValueInt32 593 | } 594 | 595 | func (b *ValueBool) Value() interface{} { 596 | return b.value == 0x1 597 | } 598 | 599 | func (b *ValueBool) String() string { 600 | return fmt.Sprintf("%t", b.Value()) 601 | } 602 | 603 | func (b *ValueBool) Repr() interface{} { 604 | return fmt.Sprintf("%t", b.Value()) 605 | } 606 | 607 | ///////////////////////////////// ValueBinary ////////////////////////////////// 608 | 609 | type ValueBinary struct { 610 | Size uint16 611 | value []byte 612 | } 613 | 614 | func (b *ValueBinary) Parse(reader io.ReadSeeker) error { 615 | // Fix of issue: https://github.com/0xrawsec/golang-evtx/issues/3 616 | if b.Size < 0 { 617 | return fmt.Errorf("%T has invalid size", *b) 618 | } 619 | b.value = make([]byte, b.Size) 620 | if b.Size > 0 { 621 | return encoding.UnmarshaInitSlice(reader, &b.value, Endianness) 622 | } 623 | return nil 624 | } 625 | 626 | func (b *ValueBinary) String() string { 627 | return fmt.Sprintf("%*X", b.Size, b.value) 628 | } 629 | 630 | func (b *ValueBinary) Value() interface{} { 631 | return b.value 632 | } 633 | 634 | func (b *ValueBinary) Repr() interface{} { 635 | return b.String() 636 | } 637 | 638 | ///////////////////////////////////// GUID ///////////////////////////////////// 639 | 640 | type GUID [16]byte 641 | 642 | func (g *GUID) String() string { 643 | return fmt.Sprintf("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", 644 | g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8], g[9], g[10], g[11], g[12], g[13], 645 | g[14], g[15]) 646 | } 647 | 648 | type ValueGUID struct { 649 | value GUID 650 | } 651 | 652 | func (g *ValueGUID) Parse(reader io.ReadSeeker) error { 653 | return encoding.Unmarshal(reader, &g.value, Endianness) 654 | } 655 | 656 | func (g *ValueGUID) String() string { 657 | return g.value.String() 658 | } 659 | 660 | func (g *ValueGUID) Value() interface{} { 661 | return g.value 662 | } 663 | 664 | func (g *ValueGUID) Repr() interface{} { 665 | return g.String() 666 | } 667 | 668 | ///////////////////////////////////// SID ///////////////////////////////////// 669 | // Source: https://github.com/dutchcoders/evtxparser/blob/master/sid.go 670 | 671 | type Sid struct { 672 | Revision uint8 673 | SubAuthorityCount uint8 674 | IdentifierAuthority [6]uint8 675 | SubAuthority []uint32 676 | } 677 | 678 | type ValueSID struct { 679 | value Sid 680 | } 681 | 682 | func (g *ValueSID) Parse(reader io.ReadSeeker) error { 683 | var err error 684 | err = encoding.Unmarshal(reader, &g.value.Revision, Endianness) 685 | if err != nil { 686 | return err 687 | } 688 | err = encoding.Unmarshal(reader, &g.value.SubAuthorityCount, Endianness) 689 | if err != nil { 690 | return err 691 | } 692 | err = encoding.Unmarshal(reader, &g.value.IdentifierAuthority, Endianness) 693 | if err != nil { 694 | return err 695 | } 696 | g.value.SubAuthority = make([]uint32, g.value.SubAuthorityCount) 697 | err = encoding.UnmarshaInitSlice(reader, &g.value.SubAuthority, Endianness) 698 | return err 699 | } 700 | 701 | func (g *ValueSID) String() string { 702 | s := fmt.Sprintf("S-%d", g.value.Revision) 703 | 704 | v := uint64(0) 705 | for _, ia := range g.value.IdentifierAuthority { 706 | v = v << 8 707 | v += uint64(ia) 708 | } 709 | s += fmt.Sprintf("-%d", v) 710 | 711 | for _, sa := range g.value.SubAuthority { 712 | s += fmt.Sprintf("-%d", sa) 713 | } 714 | return s 715 | } 716 | 717 | func (g *ValueSID) Value() interface{} { 718 | return g.value 719 | } 720 | 721 | func (g *ValueSID) Repr() interface{} { 722 | return g.String() 723 | } 724 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/0xrawsec/golang-evtx 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/0xrawsec/golang-utils v1.3.0 7 | github.com/0xrawsec/golang-win32 v1.0.6 8 | github.com/golang/snappy v0.0.1 // indirect 9 | github.com/segmentio/kafka-go v0.2.2 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/0xrawsec/golang-utils v1.1.0 h1:opQAwRONEfxOOl4nxhpPkXiTYgzAw0/wFATAffNjdII= 2 | github.com/0xrawsec/golang-utils v1.1.0/go.mod h1:DADTtCFY10qXjWmUVhhJqQIZdSweaHH4soYUDEi8mj0= 3 | github.com/0xrawsec/golang-utils v1.1.3 h1:ESJhyY4aGuiP4hmDcDNjoL/cc7SWDZVfgg4dEON9eIc= 4 | github.com/0xrawsec/golang-utils v1.1.3/go.mod h1:DADTtCFY10qXjWmUVhhJqQIZdSweaHH4soYUDEi8mj0= 5 | github.com/0xrawsec/golang-utils v1.2.0 h1:wzPUcLLcx2NPV9txupkn7+KXOUuVG4zaKZ/Y5s7GJZQ= 6 | github.com/0xrawsec/golang-utils v1.2.0/go.mod h1:DADTtCFY10qXjWmUVhhJqQIZdSweaHH4soYUDEi8mj0= 7 | github.com/0xrawsec/golang-utils v1.3.0 h1:fMgwKu5M2PXFwEfwN9B2T1bfg7LPCaV9fL6Xs/nf2Ps= 8 | github.com/0xrawsec/golang-utils v1.3.0/go.mod h1:DADTtCFY10qXjWmUVhhJqQIZdSweaHH4soYUDEi8mj0= 9 | github.com/0xrawsec/golang-win32 v1.0.6 h1:wVvfd+trSeUkG6m5TFzeBtWHSHetfhPO3b5MVjTgsWk= 10 | github.com/0xrawsec/golang-win32 v1.0.6/go.mod h1:MAxVU7dr8lujwknuhf4TwjYm8tVEELi2zwx1zDTu/RM= 11 | github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= 12 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 13 | github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= 14 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 15 | github.com/pkg/sftp v1.10.0/go.mod h1:NxmoDg/QLVWluQDUYG7XBZTLUpKeFa8e3aMf1BfjyHk= 16 | github.com/segmentio/kafka-go v0.2.2 h1:KIUln5unPisRL2yyAkZsDR/coiymN9Djunv6JKGQ6JI= 17 | github.com/segmentio/kafka-go v0.2.2/go.mod h1:X6itGqS9L4jDletMsxZ7Dz+JFWxM6JHfPOCvTvk+EJo= 18 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 19 | golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 20 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 21 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 22 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 23 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 24 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 25 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 26 | golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 27 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 28 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 29 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 30 | golang.org/x/tools v0.0.0-20190320215829-36c10c0a621f/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 31 | golang.org/x/tools v0.0.0-20190625160430-252024b82959/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= 32 | -------------------------------------------------------------------------------- /output/httpOut.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "bytes" 5 | "net/http" 6 | 7 | "github.com/0xrawsec/golang-evtx/evtx" 8 | "github.com/0xrawsec/golang-utils/log" 9 | ) 10 | 11 | type HttpJSON struct { 12 | client *http.Client 13 | Url string 14 | Tag string 15 | } 16 | 17 | func (hj *HttpJSON) Open(url string) error { 18 | hj.client = &http.Client{} 19 | return nil 20 | } 21 | 22 | func (hj *HttpJSON) Request(message *evtx.GoEvtxMap) { 23 | mark := evtx.GoEvtxMap{ 24 | "tags": hj.Tag, 25 | } 26 | message.Add(mark) 27 | req, err := http.NewRequest("POST", hj.Url, bytes.NewBuffer([]byte(evtx.ToJSON(message)))) 28 | req.Header.Set("Content-Type", "application/json") 29 | resp, err := hj.client.Do(req) 30 | if err != nil { 31 | log.Errorf("Can 't connect to remote http log server: %s", hj.Url) 32 | } 33 | defer resp.Body.Close() 34 | } 35 | -------------------------------------------------------------------------------- /output/kafka.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "context" 5 | "github.com/segmentio/kafka-go" 6 | "github.com/segmentio/kafka-go/snappy" 7 | "time" 8 | 9 | "github.com/0xrawsec/golang-evtx/evtx" 10 | "github.com/0xrawsec/golang-utils/log" 11 | ) 12 | 13 | type Kafka struct { 14 | conn *kafka.Writer 15 | BrokerURLs string 16 | ClientID string 17 | Topic string 18 | Tag string 19 | } 20 | 21 | func (k *Kafka) Open(url string) error { 22 | dialer := &kafka.Dialer{ 23 | Timeout: 10 * time.Second, 24 | ClientID: k.ClientID, 25 | } 26 | 27 | config := kafka.WriterConfig{ 28 | Brokers: []string{k.BrokerURLs}, 29 | Topic: k.Topic, 30 | Balancer: &kafka.LeastBytes{}, 31 | Dialer: dialer, 32 | WriteTimeout: 10 * time.Second, 33 | ReadTimeout: 10 * time.Second, 34 | CompressionCodec: snappy.NewCompressionCodec(), 35 | } 36 | k.conn = kafka.NewWriter(config) 37 | return nil 38 | } 39 | 40 | func (k *Kafka) Request(message *evtx.GoEvtxMap) { 41 | mark := evtx.GoEvtxMap{ 42 | "tags": k.Tag, 43 | } 44 | message.Add(mark) 45 | body := kafka.Message{ 46 | Key: nil, 47 | Value: evtx.ToJSON(message), 48 | Time: time.Now(), 49 | } 50 | err := k.conn.WriteMessages(context.Background(), body) 51 | if err != nil { 52 | log.Error(err) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /output/output.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import "github.com/0xrawsec/golang-evtx/evtx" 4 | 5 | type Output interface { 6 | Open(url string) error 7 | Request(message *evtx.GoEvtxMap) 8 | } 9 | -------------------------------------------------------------------------------- /output/tcpOut.go: -------------------------------------------------------------------------------- 1 | package output 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "net" 8 | 9 | "github.com/0xrawsec/golang-evtx/evtx" 10 | ) 11 | 12 | type TcpJSON struct { 13 | out *json.Encoder 14 | Tag string 15 | } 16 | 17 | func (tj *TcpJSON) Open(url string) error { 18 | conn, err := net.Dial("tcp", url) 19 | if err != nil { 20 | return errors.New(fmt.Sprintf("Can't connect to remote tcp log server: %s", url)) 21 | } 22 | tj.out = json.NewEncoder(conn) 23 | return nil 24 | } 25 | 26 | func (tj *TcpJSON) Request(message *evtx.GoEvtxMap) { 27 | mark := evtx.GoEvtxMap{ 28 | "tags": tj.Tag, 29 | } 30 | message.Add(mark) 31 | tj.out.Encode(message) 32 | } 33 | -------------------------------------------------------------------------------- /tools/evtxdump/evtxdump: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xrawsec/golang-evtx/9b04117dad513b1c51bb4afcd8f5bb2e5053c05b/tools/evtxdump/evtxdump -------------------------------------------------------------------------------- /tools/evtxdump/evtxdump.go: -------------------------------------------------------------------------------- 1 | /* 2 | EVTX dumping utility, it can be used to carve raw data and recover EVTX events 3 | 4 | Copyright (C) 2017 RawSec SARL (0xrawsec) 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | package main 21 | 22 | import ( 23 | "bufio" 24 | "bytes" 25 | "flag" 26 | "fmt" 27 | "io" 28 | "os" 29 | "path/filepath" 30 | "regexp" 31 | "runtime/pprof" 32 | "sync" 33 | "time" 34 | 35 | "github.com/0xrawsec/golang-evtx/evtx" 36 | "github.com/0xrawsec/golang-evtx/output" 37 | "github.com/0xrawsec/golang-utils/args" 38 | "github.com/0xrawsec/golang-utils/log" 39 | ) 40 | 41 | const ( 42 | // ExitSuccess RC 43 | ExitSuccess = 0 44 | // ExitFail RC 45 | ExitFail = 1 46 | Copyright = "Evtxdump Copyright (C) 2017 RawSec SARL (@0xrawsec)" 47 | License = `License GPLv3: This program comes with ABSOLUTELY NO WARRANTY. 48 | This is free software, and you are welcome to redistribute it under certain 49 | conditions;` 50 | ) 51 | 52 | var ( 53 | debug bool 54 | carve bool 55 | timestamp bool 56 | version bool 57 | unordered bool 58 | statflag bool 59 | header bool 60 | offset int64 61 | limit int 62 | tag string 63 | outTcp string 64 | outHttp string 65 | outType string 66 | brURL string 67 | cID string 68 | topic string 69 | start, stop args.DateVar 70 | chunkHeaderRE = regexp.MustCompile(evtx.ChunkMagic) 71 | defaultTime = time.Time{} 72 | ) 73 | 74 | //////////////////////////// stat structure //////////////////////////////////// 75 | 76 | type eventIDStat map[int64]uint 77 | 78 | type stats struct { 79 | sync.RWMutex 80 | EventCount uint 81 | ChannelStats map[string]eventIDStat 82 | } 83 | 84 | // stats contstructor 85 | func newStats() *stats { 86 | s := stats{} 87 | s.ChannelStats = make(map[string]eventIDStat) 88 | return &s 89 | } 90 | 91 | // update stats in a stat sturcture 92 | func (s *stats) update(channel string, eventID int64) { 93 | s.Lock() 94 | if _, ok := s.ChannelStats[channel]; !ok { 95 | s.ChannelStats[channel] = make(eventIDStat) 96 | } 97 | s.ChannelStats[channel][eventID]++ 98 | s.EventCount++ 99 | s.Unlock() 100 | } 101 | 102 | // prints in CSV format 103 | func (s *stats) print() { 104 | fmt.Printf("Channel,EventID,Count\n") 105 | for c := range s.ChannelStats { 106 | for eid, cnt := range s.ChannelStats[c] { 107 | fmt.Printf("%s,%d,%d\n", c, eid, cnt) 108 | } 109 | } 110 | //fmt.Printf("Total Events: %d\n", s.EventCount) 111 | } 112 | 113 | /////////////////////////////// Carving functions ////////////////////////////// 114 | 115 | // Find the potential chunks 116 | func findChunksOffsets(r io.ReadSeeker) (co chan int64) { 117 | co = make(chan int64, 42) 118 | realPrevOffset, _ := r.Seek(0, os.SEEK_CUR) 119 | go func() { 120 | defer close(co) 121 | rr := bufio.NewReader(r) 122 | for loc := chunkHeaderRE.FindReaderIndex(rr); loc != nil; loc = chunkHeaderRE.FindReaderIndex(rr) { 123 | realOffset, _ := r.Seek(0, os.SEEK_CUR) 124 | co <- realPrevOffset + int64(loc[0]) 125 | realPrevOffset = realOffset - int64(rr.Buffered()) 126 | } 127 | }() 128 | return 129 | } 130 | 131 | // return an evtx.Chunk object from a reader 132 | func fetchChunkFromReader(r io.ReadSeeker, offset int64) (evtx.Chunk, error) { 133 | var err error 134 | c := evtx.NewChunk() 135 | evtx.GoToSeeker(r, offset) 136 | c.Offset = offset 137 | c.Data = make([]byte, evtx.ChunkSize) 138 | if _, err = r.Read(c.Data); err != nil { 139 | return c, err 140 | } 141 | reader := bytes.NewReader(c.Data) 142 | c.ParseChunkHeader(reader) 143 | if err = c.Header.Validate(); err != nil { 144 | return c, err 145 | } 146 | // Go to after Header 147 | evtx.GoToSeeker(reader, int64(c.Header.SizeHeader)) 148 | c.ParseStringTable(reader) 149 | err = c.ParseTemplateTable(reader) 150 | if err != nil { 151 | return c, err 152 | } 153 | err = c.ParseEventOffsets(reader) 154 | if err != nil { 155 | return c, err 156 | } 157 | return c, nil 158 | } 159 | 160 | // main routine to carve a file 161 | func carveFile(datafile string, offset int64, limit int) { 162 | chunkCnt := 0 163 | f, err := os.Open(datafile) 164 | if err != nil { 165 | log.Abort(ExitFail, err) 166 | } 167 | defer f.Close() 168 | f.Seek(offset, os.SEEK_SET) 169 | dup, err := os.Open(datafile) 170 | if err != nil { 171 | log.Abort(ExitFail, err) 172 | } 173 | defer dup.Close() 174 | dup.Seek(offset, os.SEEK_SET) 175 | 176 | for offset := range findChunksOffsets(f) { 177 | log.Infof("Parsing Chunk @ Offset: %d (0x%08[1]x)", offset) 178 | chunk, err := fetchChunkFromReader(dup, offset) 179 | if err != nil { 180 | log.Error(err) 181 | } 182 | for e := range chunk.Events() { 183 | printEvent(e) 184 | } 185 | chunkCnt++ 186 | 187 | if limit > 0 && chunkCnt >= limit { 188 | break 189 | } 190 | log.Debug("End of the loop") 191 | } 192 | } 193 | 194 | // small routine that prints the EVTX event 195 | func printEvent(e *evtx.GoEvtxMap) { 196 | if e != nil { 197 | t, err := e.GetTime(&evtx.SystemTimePath) 198 | 199 | // If not between start and stop we do not print 200 | if time.Time(start) != defaultTime && time.Time(stop) != defaultTime { 201 | if t.Before(time.Time(start)) || t.After(time.Time(stop)) { 202 | return 203 | } 204 | } 205 | 206 | // If before start we do not print 207 | if time.Time(start) != defaultTime { 208 | if t.Before(time.Time(start)) { 209 | return 210 | } 211 | } 212 | 213 | // If after stop we do not print 214 | if time.Time(stop) != defaultTime { 215 | if t.After(time.Time(stop)) { 216 | return 217 | } 218 | } 219 | 220 | if timestamp { 221 | if err == nil { 222 | fmt.Printf("%d: %s\n", t.UnixNano(), string(evtx.ToJSON(e))) 223 | } else { 224 | log.Errorf("Event time not found: %s", string(evtx.ToJSON(e))) 225 | } 226 | } else { 227 | fmt.Printf("%s\n", string(evtx.ToJSON(e))) 228 | } 229 | 230 | } 231 | } 232 | 233 | ///////////////////////////////// Main ///////////////////////////////////////// 234 | 235 | func main() { 236 | var memprofile, cpuprofile string 237 | flag.BoolVar(&debug, "d", debug, "Enable debug mode") 238 | flag.BoolVar(&header, "H", header, "Display file header and quit") 239 | flag.BoolVar(&carve, "c", carve, "Carve events from file") 240 | flag.BoolVar(&version, "V", version, "Show version and exit") 241 | flag.BoolVar(×tamp, "t", timestamp, "Prints event timestamp (as int) at the beginning of line to make sorting easier") 242 | flag.BoolVar(&unordered, "u", unordered, "Does not care about ordering the events before printing (faster for large files)") 243 | flag.BoolVar(&statflag, "s", statflag, "Prints stats about events in files") 244 | flag.Int64Var(&offset, "o", offset, "Offset to start from (carving mode only)") 245 | flag.IntVar(&limit, "l", limit, "Limit the number of chunks to parse (carving mode only)") 246 | flag.Var(&start, "start", "Print logs starting from start") 247 | flag.Var(&stop, "stop", "Print logs before stop") 248 | 249 | flag.StringVar(&memprofile, "memprofile", "", "write memory profile to this file") 250 | flag.StringVar(&cpuprofile, "cpuprofile", "", "write cpu profile to this file") 251 | 252 | flag.StringVar(&outType, "type", "", "Type of remote log collector. JSON-over-HTTP, JSON-over-TCP, Kafka") 253 | flag.StringVar(&outHttp, "http", "", "url for sending output to remote site over HTTP") 254 | flag.StringVar(&outTcp, "tcp", "", "tcp socket address for sending output to remote site over TCP") 255 | flag.StringVar(&brURL, "brURL", "", "Kafka Broker URL") 256 | flag.StringVar(&topic, "topic", "", "Kafka topic") 257 | flag.StringVar(&cID, "cID", "", "Kafka client ID") 258 | flag.StringVar(&tag, "tag", "", "special tag for matching purpose on remote collector") 259 | 260 | flag.Usage = func() { 261 | fmt.Fprintf(os.Stderr, "%s (commit: %s)\n%s\n%s\n\n", Version, CommitID, Copyright, License) 262 | fmt.Fprintf(os.Stderr, "Usage of %s: %[1]s [OPTIONS] FILES...\n", filepath.Base(os.Args[0])) 263 | flag.PrintDefaults() 264 | } 265 | 266 | flag.Parse() 267 | 268 | // Debug mode 269 | if debug { 270 | log.InitLogger(log.LDebug) 271 | evtx.SetDebug(true) 272 | } 273 | 274 | // version 275 | if version { 276 | fmt.Fprintf(os.Stderr, "%s (commit: %s)\n%s\n%s\n", Version, CommitID, Copyright, License) 277 | return 278 | } 279 | 280 | // Handle profiling functions 281 | if memprofile != "" { 282 | defer func() { 283 | f, err := os.Create(memprofile) 284 | if err != nil { 285 | log.Abort(ExitFail, err) 286 | } 287 | pprof.WriteHeapProfile(f) 288 | f.Close() 289 | }() 290 | } 291 | 292 | if cpuprofile != "" { 293 | f, err := os.Create(cpuprofile) 294 | if err != nil { 295 | log.Abort(ExitFail, err) 296 | } 297 | err = pprof.StartCPUProfile(f) 298 | if err != nil { 299 | log.Abort(ExitFail, err) 300 | } 301 | defer func() { 302 | pprof.StopCPUProfile() 303 | f.Close() 304 | }() 305 | } 306 | 307 | // init stats in case needed 308 | s := newStats() 309 | 310 | // init tcp sender if exists 311 | var out output.Output 312 | switch outType { 313 | case "http": 314 | httpOut := &output.HttpJSON{ 315 | Url: outHttp, 316 | Tag: tag, 317 | } 318 | if err := httpOut.Open(outHttp); err != nil { 319 | log.Errorf("Can't init http conn", err) 320 | } 321 | out = httpOut 322 | case "tcp": 323 | tcpOut := &output.TcpJSON{ 324 | Tag: tag, 325 | } 326 | if err := tcpOut.Open(outTcp); err != nil { 327 | log.Errorf("Can't init tcp conn", err) 328 | } 329 | out = tcpOut 330 | case "kafka": 331 | kafkaOut := &output.Kafka{ 332 | BrokerURLs: brURL, 333 | Topic: topic, 334 | ClientID: cID, 335 | Tag: tag, 336 | } 337 | if err := kafkaOut.Open(outHttp); err != nil { 338 | log.Errorf("Can't init Kafka conn", err) 339 | } 340 | out = kafkaOut 341 | } 342 | 343 | for _, evtxFile := range flag.Args() { 344 | if !carve { 345 | // Regular EVTX file, we use OpenDirty because 346 | // the file might be in a dirty state 347 | ef, err := evtx.OpenDirty(evtxFile) 348 | 349 | // exceptionnaly we do some intermediary code 350 | // before error checking 351 | if header { 352 | fmt.Printf("\nFile Header: %s\n\n", evtxFile) 353 | fmt.Println(ef.Header) 354 | continue 355 | } 356 | 357 | if err != nil { 358 | log.Error(err) 359 | continue 360 | } 361 | 362 | for e := range ef.FastEvents() { 363 | if statflag { 364 | // We update the stats 365 | s.update(e.Channel(), e.EventID()) 366 | } else { 367 | // We print events 368 | if outType != "" { 369 | out.Request(e) 370 | } else { 371 | printEvent(e) 372 | } 373 | } 374 | } 375 | } else { 376 | evtx.SetModeCarving(true) 377 | // We have to carve the file 378 | carveFile(evtxFile, offset, limit) 379 | } 380 | } 381 | 382 | // We print the stats if needed 383 | if statflag { 384 | s.print() 385 | } 386 | } 387 | -------------------------------------------------------------------------------- /tools/evtxdump/makefile: -------------------------------------------------------------------------------- 1 | MAIN_BASEN_SRC=evtxdump 2 | RELEASE="$(GOPATH)/release/$(MAIN_BASEN_SRC)" 3 | VERSION=v1.2.4 4 | COMMITID=$(shell git rev-parse HEAD) 5 | # Strips symbols and dwarf to make binary smaller 6 | OPTS=-trimpath -ldflags "-s -w" 7 | ifdef DEBUG 8 | OPTS= 9 | endif 10 | 11 | all: 12 | $(MAKE) clean 13 | $(MAKE) init 14 | $(MAKE) compile 15 | 16 | init: buildversion 17 | mkdir -p $(RELEASE) 18 | mkdir -p $(RELEASE)/linux 19 | mkdir -p $(RELEASE)/windows 20 | mkdir -p $(RELEASE)/darwin 21 | 22 | compile:linux windows darwin 23 | 24 | install: 25 | go install ./ 26 | 27 | buildversion: 28 | printf "package main\n\nconst(\n Version=\"$(VERSION)\"\n CommitID=\"$(COMMITID)\"\n)\n" > version.go 29 | 30 | linux: 31 | GOARCH=386 GOOS=linux go build $(OPTS) -o $(RELEASE)/linux/$(MAIN_BASEN_SRC)-386 ./ 32 | GOARCH=amd64 GOOS=linux go build $(OPTS) -o $(RELEASE)/linux/$(MAIN_BASEN_SRC)-amd64 ./ 33 | cd $(RELEASE)/linux; shasum -a1 * > sha1.txt 34 | cd $(RELEASE)/linux; tar -cvzf ../$(MAIN_BASEN_SRC)-linux-$(VERSION).tar.gz * 35 | 36 | windows: 37 | GOARCH=386 GOOS=windows go build $(OPTS) -o $(RELEASE)/windows/$(MAIN_BASEN_SRC)-386.exe ./ 38 | GOARCH=amd64 GOOS=windows go build $(OPTS) -o $(RELEASE)/windows/$(MAIN_BASEN_SRC)-amd64.exe ./ 39 | cd $(RELEASE)/windows; shasum -a1 * > sha1.txt 40 | cd $(RELEASE)/windows; tar -cvzf ../$(MAIN_BASEN_SRC)-windows-$(VERSION).tar.gz * 41 | 42 | darwin: 43 | #GOARCH=386 GOOS=darwin go build $(OPTS) -o $(RELEASE)/darwin/$(MAIN_BASEN_SRC)-386 ./ 44 | GOARCH=amd64 GOOS=darwin go build $(OPTS) -o $(RELEASE)/darwin/$(MAIN_BASEN_SRC)-amd64 ./ 45 | cd $(RELEASE)/darwin; shasum -a1 * > sha1.txt 46 | cd $(RELEASE)/darwin; tar -cvzf ../$(MAIN_BASEN_SRC)-darwin-$(VERSION).tar.gz * 47 | 48 | clean: 49 | rm -rf $(RELEASE)/* 50 | -------------------------------------------------------------------------------- /tools/evtxmon/evtxmon: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0xrawsec/golang-evtx/9b04117dad513b1c51bb4afcd8f5bb2e5053c05b/tools/evtxmon/evtxmon -------------------------------------------------------------------------------- /tools/evtxmon/evtxmon.go: -------------------------------------------------------------------------------- 1 | /* 2 | EVTX monitoring utility, it can be used to make statistics on event generation 3 | and to dump events in real time to files. 4 | 5 | Copyright (C) 2017 RawSec SARL (0xrawsec) 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | */ 20 | 21 | package main 22 | 23 | import ( 24 | "compress/gzip" 25 | "encoding/json" 26 | "flag" 27 | "fmt" 28 | "os" 29 | "os/signal" 30 | "path/filepath" 31 | "sort" 32 | "sync" 33 | "time" 34 | 35 | "github.com/0xrawsec/golang-evtx/evtx" 36 | "github.com/0xrawsec/golang-utils/args" 37 | "github.com/0xrawsec/golang-utils/datastructs" 38 | "github.com/0xrawsec/golang-utils/log" 39 | "github.com/0xrawsec/golang-win32/win32/wevtapi" 40 | ) 41 | 42 | const ( 43 | // ExitSuccess RC 44 | ExitSuccess = 0 45 | // ExitFailure RC 46 | ExitFailure = 1 47 | Copyright = "Evtxmon Copyright (C) 2017 RawSec SARL (@0xrawsec)" 48 | License = `License GPLv3: This program comes with ABSOLUTELY NO WARRANTY. 49 | This is free software, and you are welcome to redistribute it under certain 50 | conditions;` 51 | ) 52 | 53 | var ( 54 | evtxfile string 55 | version bool 56 | statsFlag bool 57 | debug bool 58 | monitorExisting bool 59 | filters args.ListIntVar 60 | duration DurationArg 61 | output string 62 | utctime = evtx.Path("/Event/EventData/UtcTime") 63 | ) 64 | 65 | type DurationArg time.Duration 66 | 67 | func (da *DurationArg) String() string { 68 | return time.Duration(*da).String() 69 | } 70 | 71 | func (da *DurationArg) Set(input string) error { 72 | tda, err := time.ParseDuration(input) 73 | if err == nil { 74 | *da = DurationArg(tda) 75 | } 76 | return err 77 | } 78 | 79 | type Int64Slice []int64 80 | 81 | func (is Int64Slice) Len() int { 82 | return len(is) 83 | } 84 | 85 | func (is Int64Slice) Swap(i, j int) { 86 | is[i], is[j] = is[j], is[i] 87 | } 88 | func (is Int64Slice) Less(i, j int) bool { 89 | return is[i] < is[j] 90 | } 91 | 92 | func FormatTime(t time.Time) string { 93 | return t.UTC().Format(time.RFC3339) 94 | } 95 | 96 | type Stats struct { 97 | sync.RWMutex 98 | Start time.Time 99 | Stop time.Time 100 | TimeLastEvent time.Time 101 | Filters *datastructs.SyncedSet 102 | EventCount uint 103 | EventIDStats map[int64]uint 104 | EventIDs Int64Slice 105 | } 106 | 107 | func NewStats(filters ...int) (s Stats) { 108 | s.EventIDStats = make(map[int64]uint) 109 | s.EventIDs = make(Int64Slice, 0, 1024) 110 | s.Filters = datastructs.NewSyncedSet() 111 | for _, f := range filters { 112 | s.Filters.Add(int64(f)) 113 | } 114 | return 115 | } 116 | 117 | func (s *Stats) InitStart() { 118 | s.Start = time.Now() 119 | } 120 | 121 | func (s *Stats) Update(e *evtx.GoEvtxMap) { 122 | s.Lock() 123 | defer s.Unlock() 124 | // We take only those not filtered 125 | if !s.Filters.Contains(e.EventID()) { 126 | s.TimeLastEvent = e.TimeCreated() 127 | s.EventCount++ 128 | if _, ok := s.EventIDStats[e.EventID()]; !ok { 129 | s.EventIDs = append(s.EventIDs, e.EventID()) 130 | } 131 | s.EventIDStats[e.EventID()]++ 132 | } 133 | } 134 | 135 | func (s *Stats) DisplayStats() { 136 | s.RLock() 137 | defer s.RUnlock() 138 | fmt.Fprintf(os.Stderr, "Start: %s ", FormatTime(s.Start)) 139 | fmt.Fprintf(os.Stderr, "TimeLastEvent: %s ", FormatTime(s.TimeLastEvent)) 140 | fmt.Fprintf(os.Stderr, "EventCount: %d ", s.EventCount) 141 | eps := float64(s.EventCount) / time.Now().Sub(s.Start).Seconds() 142 | fmt.Fprintf(os.Stderr, "EPS: %.2f e/s\r", eps) 143 | } 144 | 145 | func (s *Stats) Summary() { 146 | s.RLock() 147 | defer s.RUnlock() 148 | s.Stop = time.Now() 149 | fmt.Printf("\n\n###### Summary #######\n\n") 150 | fmt.Printf("Start: %s\n", FormatTime(s.Start)) 151 | fmt.Printf("Stop: %s\n", FormatTime(s.Stop)) 152 | fmt.Printf("TimeLastEvent: %s\n", FormatTime(s.TimeLastEvent)) 153 | fmt.Printf("Duration (stop - start): %s\n", s.Stop.Sub(s.Start)) 154 | fmt.Printf("EventCount: %d\n", s.EventCount) 155 | eps := float64(s.EventCount) / s.Stop.Sub(s.Start).Seconds() 156 | fmt.Printf("Average EPS: %.2f eps\n", eps) 157 | fmt.Printf("EventIDs:\n") 158 | sort.Sort(s.EventIDs) 159 | for _, eid := range s.EventIDs { 160 | fmt.Printf("\t %d: %d (%.2f eps)\n", eid, s.EventIDStats[eid], float64(s.EventIDStats[eid])/s.Stop.Sub(s.Start).Seconds()) 161 | } 162 | } 163 | 164 | func XMLEventToGoEvtxMap(xe *wevtapi.XMLEvent) (*evtx.GoEvtxMap, error) { 165 | ge := make(evtx.GoEvtxMap) 166 | bytes, err := json.Marshal(xe.ToJSONEvent()) 167 | if err != nil { 168 | return &ge, err 169 | } 170 | err = json.Unmarshal(bytes, &ge) 171 | if err != nil { 172 | return &ge, err 173 | } 174 | return &ge, nil 175 | } 176 | 177 | func main() { 178 | var err error 179 | var ofile *os.File 180 | var writer *gzip.Writer 181 | 182 | flag.Usage = func() { 183 | fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS] EVTX-FILE\n", filepath.Base(os.Args[0])) 184 | flag.PrintDefaults() 185 | } 186 | 187 | flag.Var(&filters, "f", "Event ids to filter out") 188 | flag.Var(&duration, "t", "Timeout for the test") 189 | flag.BoolVar(&version, "V", version, "Show version information") 190 | flag.StringVar(&output, "w", output, "Write monitored events to output file") 191 | flag.BoolVar(&statsFlag, "s", statsFlag, "Outputs stats about events processed") 192 | flag.BoolVar(&debug, "d", debug, "Enable debug messages") 193 | flag.BoolVar(&monitorExisting, "e", monitorExisting, "Return also already existing events") 194 | 195 | flag.Parse() 196 | 197 | // set debug mode 198 | if debug { 199 | log.InitLogger(log.LDebug) 200 | } 201 | 202 | stats := NewStats(filters...) 203 | 204 | // Signal handler to catch interrupt 205 | c := make(chan os.Signal, 1) 206 | signal.Notify(c, os.Interrupt, os.Kill) 207 | go func() { 208 | <-c 209 | // No error handling 210 | writer.Flush() 211 | writer.Close() 212 | ofile.Close() 213 | if statsFlag { 214 | stats.Summary() 215 | } 216 | os.Exit(ExitFailure) 217 | }() 218 | 219 | // version 220 | if version { 221 | fmt.Fprintf(os.Stderr, "%s (commit: %s)\n%s\n%s\n", Version, CommitID, Copyright, License) 222 | return 223 | } 224 | 225 | evtxfile = flag.Arg(0) 226 | if output != "" { 227 | ofile, err = os.Create(output) 228 | if err != nil { 229 | panic(err) 230 | } 231 | writer = gzip.NewWriter(ofile) 232 | 233 | defer writer.Flush() 234 | defer writer.Close() 235 | defer ofile.Close() 236 | } 237 | 238 | if evtxfile == "" { 239 | flag.Usage() 240 | os.Exit(1) 241 | } else { 242 | stop := make(chan bool, 1) 243 | ef, err := evtx.Open(evtxfile) 244 | if err != nil && err != evtx.ErrDirtyFile { 245 | log.Abort(ExitFailure, err) 246 | } 247 | 248 | if statsFlag { 249 | go func() { 250 | for { 251 | time.Sleep(100 * time.Millisecond) 252 | stats.DisplayStats() 253 | } 254 | }() 255 | } 256 | 257 | if duration > 0 { 258 | go func() { 259 | start := time.Now() 260 | for time.Now().Sub(start) < time.Duration(duration) { 261 | time.Sleep(time.Millisecond * 500) 262 | } 263 | if statsFlag { 264 | stats.Summary() 265 | os.Exit(ExitFailure) 266 | } 267 | }() 268 | } 269 | 270 | stats.InitStart() 271 | if monitorExisting { 272 | ef.SetMonitorExisting(true) 273 | } 274 | /*xmlEvents := h.eventProvider.FetchEvents(channels, wevtapi.EvtSubscribeToFutureEvents) 275 | for xe := range xmlEvents { 276 | event, err := XMLEventToGoEvtxMap(xe) 277 | if err != nil { 278 | log.Errorf("Failed to convert event: %s", err) 279 | log.Debugf("Error data: %v", xe) 280 | } 281 | }*/ 282 | 283 | for e := range ef.MonitorEvents(stop) { 284 | if output != "" { 285 | writer.Write(evtx.ToJSON(e)) 286 | writer.Write([]byte("\n")) 287 | writer.Flush() 288 | } 289 | if statsFlag { 290 | stats.Update(e) 291 | } else { 292 | log.Infof("EventID:%d Time: %s EventRecordID: %d, ChunkCount: %d\n", e.EventID(), e.TimeCreated(), e.EventRecordID(), ef.Header.ChunkCount) 293 | } 294 | } 295 | } 296 | } 297 | -------------------------------------------------------------------------------- /tools/evtxmon/makefile: -------------------------------------------------------------------------------- 1 | MAIN_BASEN_SRC=evtxmon 2 | RELEASE="$(GOPATH)/release/$(MAIN_BASEN_SRC)" 3 | VERSION=v1.2.4 4 | COMMITID=$(shell git rev-parse HEAD) 5 | # Strips symbols and dwarf to make binary smaller 6 | OPTS=-trimpath -ldflags "-s -w" 7 | ifdef DEBUG 8 | OPTS= 9 | endif 10 | 11 | all: 12 | $(MAKE) clean 13 | $(MAKE) init 14 | $(MAKE) compile 15 | 16 | init: buildversion 17 | mkdir -p $(RELEASE) 18 | mkdir -p $(RELEASE)/linux 19 | mkdir -p $(RELEASE)/windows 20 | mkdir -p $(RELEASE)/darwin 21 | 22 | compile: windows 23 | 24 | install: 25 | go install ./ 26 | 27 | buildversion: 28 | printf "package main\n\nconst(\n Version=\"$(VERSION)\"\n CommitID=\"$(COMMITID)\"\n)\n" > version.go 29 | 30 | linux: 31 | GOARCH=386 GOOS=linux go build $(OPTS) -o $(RELEASE)/linux/$(MAIN_BASEN_SRC)-386 ./ 32 | GOARCH=amd64 GOOS=linux go build $(OPTS) -o $(RELEASE)/linux/$(MAIN_BASEN_SRC)-amd64 ./ 33 | cd $(RELEASE)/linux; shasum -a1 * > sha1.txt 34 | cd $(RELEASE)/linux; tar -cvzf ../$(MAIN_BASEN_SRC)-linux-$(VERSION).tar.gz * 35 | 36 | windows: 37 | GOARCH=386 GOOS=windows go build $(OPTS) -o $(RELEASE)/windows/$(MAIN_BASEN_SRC)-386.exe ./ 38 | GOARCH=amd64 GOOS=windows go build $(OPTS) -o $(RELEASE)/windows/$(MAIN_BASEN_SRC)-amd64.exe ./ 39 | cd $(RELEASE)/windows; shasum -a1 * > sha1.txt 40 | cd $(RELEASE)/windows; tar -cvzf ../$(MAIN_BASEN_SRC)-windows-$(VERSION).tar.gz * 41 | 42 | darwin: 43 | GOARCH=386 GOOS=darwin go build $(OPTS) -o $(RELEASE)/darwin/$(MAIN_BASEN_SRC)-386 ./ 44 | GOARCH=amd64 GOOS=darwin go build $(OPTS) -o $(RELEASE)/darwin/$(MAIN_BASEN_SRC)-amd64 ./ 45 | cd $(RELEASE)/darwin; shasum -a1 * > sha1.txt 46 | cd $(RELEASE)/darwin; tar -cvzf ../$(MAIN_BASEN_SRC)-darwin-$(VERSION).tar.gz * 47 | 48 | clean: 49 | rm -rf $(RELEASE)/* 50 | -------------------------------------------------------------------------------- /tools/makefile: -------------------------------------------------------------------------------- 1 | all: 2 | cd evtxdump; $(MAKE) all 3 | #cd evtxmon; $(MAKE) all 4 | 5 | install: 6 | cd evtxdump; $(MAKE) install 7 | #cd evtxmon; $(MAKE) install 8 | 9 | linux: 10 | cd evtxdump; $(MAKE) linux 11 | #cd evtxmon; $(MAKE) linux 12 | 13 | windows: 14 | cd evtxdump; $(MAKE) windows 15 | #cd evtxmon; $(MAKE) windows 16 | 17 | darwin: 18 | cd evtxdump; $(MAKE) darwin 19 | #cd evtxmon; $(MAKE) darwin 20 | 21 | clean: 22 | cd evtxdump; $(MAKE) clean 23 | #cd evtxmon; $(MAKE) clean 24 | --------------------------------------------------------------------------------