chore: fix license, add disclaimer, quick start, GitHub topics, issue templates

This commit is contained in:
mukul975
2026-03-11 01:42:50 +01:00
parent a15f57ad34
commit 8f7ab23bf3
1468 changed files with 152537 additions and 13659 deletions
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,40 @@
---
name: implementing-log-forwarding-with-fluentd
description: Configure Fluentd and Fluent Bit for centralized log aggregation, routing, filtering, and enrichment across distributed infrastructure
domain: cybersecurity
subdomain: security-operations
tags: [fluentd, fluent-bit, log-aggregation, log-forwarding, siem, centralized-logging, observability]
version: "1.0"
author: mahipal
license: Apache-2.0
---
# Implementing Log Forwarding with Fluentd
## Overview
This skill covers configuring Fluentd and Fluent Bit for centralized log collection, routing, and enrichment. Fluent Bit acts as a lightweight log forwarder on endpoints, while Fluentd serves as the central aggregator and processor. The configuration covers input plugins for syslog, file tailing, and application logs, with output routing to Elasticsearch, S3, and Splunk.
## Prerequisites
- Fluentd (td-agent) v1.16+ or Fluent Bit v3.0+
- Python 3.8+ with fluent-logger library
- Elasticsearch or Splunk for log destination
- Network access on port 24224 (Fluentd forward protocol)
- Ruby 2.7+ (for Fluentd plugin development)
## Steps
1. **Generate Fluent Bit Configuration** — Create input, filter, and output configuration for endpoint log collection
2. **Generate Fluentd Aggregator Configuration** — Configure the central Fluentd instance with forward input, parsing, and multi-output routing
3. **Configure Log Filtering and Enrichment** — Add record_transformer and grep filters for log enrichment and noise reduction
4. **Validate Configuration Syntax** — Parse and validate Fluentd/Fluent Bit configuration files for syntax errors
5. **Test Log Forwarding** — Send test events via fluent-logger Python library and verify delivery
6. **Generate Deployment Report** — Produce configuration summary with routing topology and health metrics
## Expected Output
- Fluent Bit and Fluentd configuration files (INI/YAML format)
- Configuration validation report
- Log routing topology diagram (text-based)
- Test event delivery confirmation
@@ -0,0 +1,111 @@
# Fluentd / Fluent Bit Log Forwarding API Reference
## Fluent Bit CLI
```bash
# Run Fluent Bit with config file
fluent-bit -c /etc/fluent-bit/fluent-bit.conf
# Validate configuration syntax
fluent-bit -c /etc/fluent-bit/fluent-bit.conf --dry-run
# Run with specific input and output (no config file)
fluent-bit -i cpu -o stdout -f 1
# Tail a log file and forward to Fluentd
fluent-bit -i tail -p path=/var/log/syslog -o forward -p host=fluentd.local -p port=24224
```
## Fluentd CLI
```bash
# Start Fluentd with config
fluentd -c /etc/fluentd/fluent.conf
# Validate config file
fluentd --dry-run -c /etc/fluentd/fluent.conf
# Install output plugin
fluent-gem install fluent-plugin-elasticsearch
fluent-gem install fluent-plugin-s3
fluent-gem install fluent-plugin-splunk-hec
```
## Fluent Bit Configuration Sections
```ini
[SERVICE]
Flush 5
Daemon Off
Log_Level info
[INPUT]
Name tail
Tag app.logs
Path /var/log/app/*.log
Parser json
DB /var/log/flb_app.db
[FILTER]
Name record_modifier
Match *
Record hostname ${HOSTNAME}
[OUTPUT]
Name forward
Match *
Host aggregator.local
Port 24224
```
## Fluentd Configuration Directives
```xml
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
<filter **>
@type record_transformer
<record>
hostname "#{Socket.gethostname}"
</record>
</filter>
<match **>
@type elasticsearch
host es.local
port 9200
logstash_format true
</match>
```
## Python fluent-logger
```python
from fluent import sender
from fluent import event
# Create sender (default: localhost:24224)
sender.setup('app', host='fluentd.local', port=24224)
event.Event('access', {'user': 'admin', 'action': 'login'})
# Direct sender usage
logger = sender.FluentSender('myapp', host='fluentd.local', port=24224)
logger.emit('follow', {'from': 'userA', 'to': 'userB'})
logger.close()
```
## Forward Protocol (TCP Port 24224)
Messages use MessagePack encoding: `[tag, timestamp, record]`
```bash
# Test connectivity
nc -zv fluentd.local 24224
# Monitor Fluentd buffer status
curl http://localhost:24220/api/plugins.json
```
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Fluentd/Fluent Bit log forwarding configuration generator and tester."""
import json
import argparse
import socket
import struct
import time
from datetime import datetime
try:
from fluent import sender, event
HAS_FLUENT = True
except ImportError:
HAS_FLUENT = False
def generate_fluentbit_config(inputs, output_host="127.0.0.1", output_port=24224):
"""Generate Fluent Bit configuration for log collection and forwarding."""
sections = ["[SERVICE]\n Flush 5\n Daemon Off\n Log_Level info\n Parsers_File parsers.conf\n"]
input_configs = {
"syslog": "[INPUT]\n Name syslog\n Tag syslog.*\n Listen 0.0.0.0\n Port 5140\n Mode udp\n Parser syslog-rfc3164\n",
"tail": "[INPUT]\n Name tail\n Tag file.*\n Path /var/log/*.log\n DB /var/log/flb_tail.db\n Read_from_Head True\n Refresh_Interval 10\n",
"systemd": "[INPUT]\n Name systemd\n Tag systemd.*\n Systemd_Filter _SYSTEMD_UNIT=sshd.service\n Read_From_Tail On\n",
"tcp": "[INPUT]\n Name tcp\n Tag tcp.*\n Listen 0.0.0.0\n Port 5170\n Format json\n",
}
for inp in inputs:
if inp in input_configs:
sections.append(input_configs[inp])
sections.append(
"[FILTER]\n"
" Name record_modifier\n"
" Match *\n"
" Record hostname ${HOSTNAME}\n"
" Record environment production\n"
)
sections.append(
"[FILTER]\n"
" Name grep\n"
" Match syslog.*\n"
" Exclude message ^healthcheck\n"
)
sections.append(
f"[OUTPUT]\n"
f" Name forward\n"
f" Match *\n"
f" Host {output_host}\n"
f" Port {output_port}\n"
f" Retry_Limit 5\n"
)
return "\n".join(sections)
def generate_fluentd_config(outputs, bind_port=24224):
"""Generate Fluentd aggregator configuration."""
sections = [
f"<source>\n"
f" @type forward\n"
f" port {bind_port}\n"
f" bind 0.0.0.0\n"
f" <security>\n"
f" shared_key fluentd_secure_key_change_me\n"
f" self_hostname aggregator.local\n"
f" </security>\n"
f"</source>\n",
]
sections.append(
"<filter **>\n"
" @type record_transformer\n"
" <record>\n"
" received_at ${time}\n"
" aggregator_host \"#{Socket.gethostname}\"\n"
" </record>\n"
"</filter>\n"
)
output_configs = {
"elasticsearch": (
'<match **>\n'
' @type elasticsearch\n'
' host elasticsearch.local\n'
' port 9200\n'
' logstash_format true\n'
' logstash_prefix fluentd\n'
' include_tag_key true\n'
' <buffer>\n'
' @type file\n'
' path /var/log/fluentd/buffer/es\n'
' flush_interval 10s\n'
' chunk_limit_size 8MB\n'
' retry_max_interval 30\n'
' retry_forever true\n'
' </buffer>\n'
'</match>\n'
),
"s3": (
'<match **>\n'
' @type s3\n'
' s3_bucket security-logs-bucket\n'
' s3_region us-east-1\n'
' path logs/\n'
' time_slice_format %Y%m%d%H\n'
' <buffer time>\n'
' @type file\n'
' path /var/log/fluentd/buffer/s3\n'
' timekey 3600\n'
' timekey_wait 10m\n'
' </buffer>\n'
'</match>\n'
),
"splunk": (
'<match **>\n'
' @type splunk_hec\n'
' hec_host splunk.local\n'
' hec_port 8088\n'
' hec_token YOUR_HEC_TOKEN\n'
' index main\n'
' source fluentd\n'
' <buffer>\n'
' @type memory\n'
' flush_interval 5s\n'
' </buffer>\n'
'</match>\n'
),
}
for out in outputs:
if out in output_configs:
sections.append(output_configs[out])
return "\n".join(sections)
def validate_config(config_text, config_type="fluentbit"):
"""Validate configuration syntax for common issues."""
errors = []
lines = config_text.split("\n")
open_sections = 0
for i, line in enumerate(lines, 1):
stripped = line.strip()
if stripped.startswith("[") and stripped.endswith("]"):
if config_type == "fluentbit":
valid_sections = {"[SERVICE]", "[INPUT]", "[FILTER]", "[OUTPUT]", "[PARSER]"}
if stripped not in valid_sections:
errors.append(f"Line {i}: Unknown section '{stripped}'")
if stripped.startswith("<") and not stripped.startswith("</"):
open_sections += 1
if stripped.startswith("</"):
open_sections -= 1
if open_sections < 0:
errors.append(f"Line {i}: Unexpected closing tag")
if config_type == "fluentd" and open_sections != 0:
errors.append(f"Unclosed XML-style tags: {open_sections} still open")
return {"valid": len(errors) == 0, "errors": errors}
def send_test_event(host="127.0.0.1", port=24224, tag="test.event"):
"""Send a test log event to Fluentd/Fluent Bit via forward protocol."""
if HAS_FLUENT:
fluentd_sender = sender.FluentSender(tag, host=host, port=port)
test_data = {
"message": "Log forwarding test event",
"level": "info",
"source": "fluentd-agent",
"timestamp": datetime.utcnow().isoformat(),
}
result = fluentd_sender.emit("test", test_data)
fluentd_sender.close()
return {"sent": result, "tag": f"{tag}.test", "data": test_data}
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect((host, port))
import msgpack
timestamp = int(time.time())
record = {"message": "test event", "source": "agent"}
packed = msgpack.packb([tag, timestamp, record])
sock.sendall(packed)
sock.close()
return {"sent": True, "method": "raw_msgpack"}
except Exception as e:
return {"sent": False, "error": str(e)}
def generate_report(fb_config, fd_config, fb_valid, fd_valid, test_result):
"""Generate deployment report."""
return {
"report_time": datetime.utcnow().isoformat(),
"fluent_bit_config_lines": len(fb_config.split("\n")),
"fluentd_config_lines": len(fd_config.split("\n")),
"fluent_bit_validation": fb_valid,
"fluentd_validation": fd_valid,
"test_event_result": test_result,
"topology": {
"forwarders": "Fluent Bit (endpoints)",
"aggregator": "Fluentd (central)",
"protocol": "Forward (TCP:24224)",
},
}
def main():
parser = argparse.ArgumentParser(description="Fluentd/Fluent Bit Log Forwarding Agent")
parser.add_argument("--inputs", nargs="+", default=["syslog", "tail"],
choices=["syslog", "tail", "systemd", "tcp"],
help="Fluent Bit input plugins to enable")
parser.add_argument("--outputs", nargs="+", default=["elasticsearch"],
choices=["elasticsearch", "s3", "splunk"],
help="Fluentd output destinations")
parser.add_argument("--aggregator-host", default="127.0.0.1")
parser.add_argument("--aggregator-port", type=int, default=24224)
parser.add_argument("--test-send", action="store_true", help="Send a test event")
parser.add_argument("--output", default="fluentd_report.json")
parser.add_argument("--write-configs", action="store_true", help="Write config files to disk")
args = parser.parse_args()
fb_config = generate_fluentbit_config(args.inputs, args.aggregator_host, args.aggregator_port)
fd_config = generate_fluentd_config(args.outputs, args.aggregator_port)
fb_valid = validate_config(fb_config, "fluentbit")
fd_valid = validate_config(fd_config, "fluentd")
test_result = {}
if args.test_send:
test_result = send_test_event(args.aggregator_host, args.aggregator_port)
if args.write_configs:
with open("fluent-bit.conf", "w") as f:
f.write(fb_config)
with open("fluentd.conf", "w") as f:
f.write(fd_config)
print("[+] Written fluent-bit.conf and fluentd.conf")
report = generate_report(fb_config, fd_config, fb_valid, fd_valid, test_result)
with open(args.output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"[+] Fluent Bit: {len(args.inputs)} inputs, validation={'PASS' if fb_valid['valid'] else 'FAIL'}")
print(f"[+] Fluentd: {len(args.outputs)} outputs, validation={'PASS' if fd_valid['valid'] else 'FAIL'}")
print(f"[+] Report saved to {args.output}")
if __name__ == "__main__":
main()