Files
ja4sentinel/cmd/ja4sentinel/main.go
Jacquin Antoine dfd5e49dd9
Some checks failed
Build DEB Package / Build DEB Package (Debian/Ubuntu) (push) Has been cancelled
Build RPM Package / Build RPM Package (Rocky Linux) (push) Has been cancelled
feat(config): add configurable packet channel buffer size
- Add PacketBufferSize field to api.Config struct
- Add DefaultPacketBuffer constant (1000 packets)
- Add JA4SENTINEL_PACKET_BUFFER_SIZE environment variable support
- Update mergeConfigs to handle PacketBufferSize override
- Update main.go to use configurable buffer size with fallback
- Update config.yml.example with packet_buffer_size option

Allows tuning for high-traffic environments by increasing buffer size
via config file or environment variable

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-02-27 00:07:45 +01:00

216 lines
5.5 KiB
Go

// Package main provides the entry point for ja4sentinel
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"time"
"ja4sentinel/api"
"ja4sentinel/internal/capture"
"ja4sentinel/internal/config"
"ja4sentinel/internal/fingerprint"
"ja4sentinel/internal/logging"
"ja4sentinel/internal/output"
"ja4sentinel/internal/tlsparse"
)
var (
// Version information (set via ldflags)
Version = "1.0.0"
BuildTime = "unknown"
GitCommit = "unknown"
)
func main() {
// Parse command-line flags
configPath := flag.String("config", "", "Path to configuration file (YAML)")
version := flag.Bool("version", false, "Show version information")
flag.Parse()
if *version {
fmt.Printf("ja4sentinel version %s (built %s, commit %s)\n", Version, BuildTime, GitCommit)
os.Exit(0)
}
// Create logger factory
loggerFactory := &logging.LoggerFactory{}
appLogger := loggerFactory.NewDefaultLogger()
appLogger.Info("main", "Starting ja4sentinel", map[string]string{
"version": Version,
"build_time": BuildTime,
"git_commit": GitCommit,
})
// Load configuration
cfgLoader := config.NewLoader(*configPath)
appConfig, err := cfgLoader.Load()
if err != nil {
appLogger.Error("main", "Failed to load configuration", map[string]string{
"error": err.Error(),
})
os.Exit(1)
}
appLogger.Info("main", "Configuration loaded", map[string]string{
"interface": appConfig.Core.Interface,
"listen_ports": formatPorts(appConfig.Core.ListenPorts),
})
// Create context with cancellation for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Setup signal handling
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
// Create pipeline components
captureEngine := capture.New()
parser := tlsparse.NewParserWithTimeout(time.Duration(appConfig.Core.FlowTimeoutSec) * time.Second)
fingerprintEngine := fingerprint.NewEngine()
outputBuilder := output.NewBuilder()
outputWriter, err := outputBuilder.NewFromConfig(appConfig)
if err != nil {
appLogger.Error("main", "Failed to create output writer", map[string]string{
"error": err.Error(),
})
os.Exit(1)
}
// Create channel for raw packets (configurable buffer size)
bufferSize := appConfig.Core.PacketBufferSize
if bufferSize <= 0 {
bufferSize = 1000 // Default fallback
}
packetChan := make(chan api.RawPacket, bufferSize)
// Start capture goroutine
captureErrChan := make(chan error, 1)
go func() {
appLogger.Info("capture", "Starting packet capture", map[string]string{
"interface": appConfig.Core.Interface,
})
err := captureEngine.Run(appConfig.Core, packetChan)
close(packetChan) // Close channel to signal packet processor to shut down
captureErrChan <- err
}()
// Process packets
go func() {
for {
select {
case <-ctx.Done():
appLogger.Info("main", "Packet processor shutting down", nil)
return
case pkt, ok := <-packetChan:
if !ok {
return
}
// Parse TLS ClientHello
clientHello, err := parser.Process(pkt)
if err != nil {
appLogger.Warn("tlsparse", "Failed to parse TLS ClientHello", map[string]string{
"error": err.Error(),
})
continue
}
if clientHello == nil {
continue // Not a TLS ClientHello packet
}
appLogger.Debug("tlsparse", "ClientHello extracted", map[string]string{
"src_ip": clientHello.SrcIP,
"src_port": fmt.Sprintf("%d", clientHello.SrcPort),
"dst_ip": clientHello.DstIP,
"dst_port": fmt.Sprintf("%d", clientHello.DstPort),
})
// Generate fingerprints
fingerprints, err := fingerprintEngine.FromClientHello(*clientHello)
if err != nil {
appLogger.Warn("fingerprint", "Failed to generate fingerprints", map[string]string{
"error": err.Error(),
})
continue
}
appLogger.Debug("fingerprint", "Fingerprints generated", map[string]string{
"src_ip": clientHello.SrcIP,
"ja4": fingerprints.JA4,
})
// Create log record
logRecord := api.NewLogRecord(*clientHello, fingerprints)
// Write output
if err := outputWriter.Write(logRecord); err != nil {
appLogger.Error("output", "Failed to write log record", map[string]string{
"error": err.Error(),
})
}
}
}
}()
// Wait for shutdown signal or capture error
select {
case sig := <-sigChan:
appLogger.Info("main", "Received shutdown signal", map[string]string{
"signal": sig.String(),
})
case err := <-captureErrChan:
if err != nil {
appLogger.Error("capture", "Capture engine failed", map[string]string{
"error": err.Error(),
})
}
}
// Graceful shutdown
appLogger.Info("main", "Shutting down...", nil)
cancel()
// Close components
if err := captureEngine.Close(); err != nil {
appLogger.Error("main", "Failed to close capture engine", map[string]string{
"error": err.Error(),
})
}
if err := parser.Close(); err != nil {
appLogger.Error("main", "Failed to close parser", map[string]string{
"error": err.Error(),
})
}
if closer, ok := outputWriter.(interface{ Close() error }); ok {
if err := closer.Close(); err != nil {
appLogger.Error("main", "Failed to close output writer", map[string]string{
"error": err.Error(),
})
}
}
appLogger.Info("main", "ja4sentinel stopped", nil)
}
// formatPorts formats a slice of ports as a comma-separated string
func formatPorts(ports []uint16) string {
if len(ports) == 0 {
return ""
}
result := fmt.Sprintf("%d", ports[0])
for _, port := range ports[1:] {
result += fmt.Sprintf(",%d", port)
}
return result
}