Files
Naomi Kramer b923c39e2d Update configuration (#78)
* Update on config structure, functionality, and tests

Co-Authored-By: Naomi Kramer <naomiagoddard@gmail.com>

* Extend subnet type to read/write from db, update tests

Co-Authored-By: Liza Tsibur <liza@activecountermeasures.com>

* updated read file config test and subnet tests

* fixed config and util tests, updated subnet related functions

Co-Authored-By: Naomi Kramer <naomiagoddard@gmail.com>

* Remove error return from GetDefaultConfig

Co-Authored-By: Liza Tsibur <liza@activecountermeasures.com>

* added json tags to database struct

* Updated beacon weights validation for config

* updates to score thresholds validation tags

* changes to config subnet validation and testing

* Update subnet.go

* Write missing host entries to http to populate http_proto

* Updating some fields to uint64

* WIP update some field types

* Update zeek count types and fix tests

* Add clickhouse credentials

* Misc fixes

* Update pointer

* Add ability to mark datasets as sample datasets

* fix column name

* Fix datasets exiting import if hour is empty

* Fix zeek count parsing from TSV files

* Remove storing dns conns in arrays, Fix historical first seen dns lag

* Remove unused columns

* Update config.hjson

* Update config.hjson

* updated impact category score functions to use float64

Co-Authored-By: Naomi Kramer <naomiagoddard@gmail.com>

* Update subnet.go

* Store import version in imports table

* Fix duplicated SNI/IP long connections

* Update subnet_test.go

* Cleanup output

* Rolling files updates (#39)

* Limit number of days to import for rolling datasets

* Fix breaking imports when import was interrupted

* Remove debug output

---------

Co-authored-by: Naomi Kramer <naomi@activecountermeasures.com>

* Omit parts of env from output

* Set max for threat intel datasize

* Remove SELinux neutering for QA

* Add network size column

* Fix http_proto for missing host, update tests for missing host fixes

* Add online feeds to default config

* Update sshprep (#45)

* Update sshprep

Co-Authored-By: William Stearns <3538265+william-stearns@users.noreply.github.com>

* Update sshprep

Add Bradley's suggestion of using head -1 to limit to a single address.

---------

Co-authored-by: Naomi Kramer <naomi@activecountermeasures.com>
Co-authored-by: William Stearns <3538265+william-stearns@users.noreply.github.com>

* Installer Behavior Tweaks (#41)

* Add --yes flag to add-apt-repository command

* Add missing sudo flags, make sure we're using the SUDO variable instead

* Add ability to perform zone transfers (#48)

* Store zone transfer records

Co-Authored-By: moth <25512187+0x6d6f7468@users.noreply.github.com>

* Update config

* Add tests

* Tests, connectivity test

* Update tests

---------

Co-authored-by: moth <25512187+0x6d6f7468@users.noreply.github.com>

* Support RedHat/RHEL as a valid target (#47)

* Update sshprep

Co-Authored-By: William Stearns <3538265+william-stearns@users.noreply.github.com>

* Supporrt RedHat/RHEL as a valid target

---------

Co-authored-by: Naomi Kramer <naomi@activecountermeasures.com>
Co-authored-by: William Stearns <3538265+william-stearns@users.noreply.github.com>
Co-authored-by: moth <moth@blackhillsinfosec.com>

* Fix tests (#49)

* Fix tests

* Update WalkFiles to use UTC

* fixed issue with rolling datasets over 24hours old not getting historical first seen timestamp set (#52)

* Change values from float32 to float64 (#50)

* Switch float32 to float64

* Update threat category calculation to match CalculateBucketedScore (#51)

---------

Co-authored-by: Liza Tsibur <liza@activecountermeasures.com>

* Bump max query execution time default value

* Use string instead of error for ZoneTransferConnectivityErrors struct fields (#61)

* Upgrade Golang to version 1.24 (#59) (#60)

* Replace get_url with shell and curl (#58)

* Update sshprep

Co-Authored-By: William Stearns <3538265+william-stearns@users.noreply.github.com>

* Replace get_url with shell and curl

* Use get_url by default, fall back to curl if it fails

---------

Co-authored-by: Naomi Kramer <naomi@activecountermeasures.com>
Co-authored-by: William Stearns <3538265+william-stearns@users.noreply.github.com>
Co-authored-by: moth <moth@blackhillsinfosec.com>

* add automated log transfer, AC-Hunter issue 135 (#62)

* Update sshprep

Co-Authored-By: William Stearns <3538265+william-stearns@users.noreply.github.com>

* add automated log transfer, PR135

* cron requires non-executable permission

* Specify suggested YAML plugin and config in VSCode workspace

* Linting and light cleanup

* Update generate_installer.sh

Download zeek_log_transport.sh to send to the sensor.

* Create cron file if remote zeek installation

* Only run zeek log import steps for remote sensor installations

---------

Co-authored-by: Naomi Kramer <naomi@activecountermeasures.com>
Co-authored-by: William Stearns <3538265+william-stearns@users.noreply.github.com>
Co-authored-by: moth <moth@blackhillsinfosec.com>

* Temporarily disable RITA/Zeek log transport until installer is modular (#66)

* Uniform -y flag usage for repo management/package installation; Uniform SUDO variable usage (#68)

* Resolve Installer Side Effects and Formalize RHEL Support (#73)

* Add missing necessary wildcards for RHEL versions

* Remove Ansible task replacing python3-requests to avoid RHEL distro installation side effects

* Update supported distros in README

* Update scoring defaults

* Resolve Ansible Reboot Errors (#75)

* Clean up conditionals; Fix reboot step for Ubuntu

* Suppress erroneous error output on RPM systems, ignore errors on reboot necessity checks

* Ignore missing host rows for openhttp (#76)

* Fix integration tests due to prevalence (#77)

---------

Co-authored-by: Liza Tsibur <liza@activecountermeasures.com>
Co-authored-by: moth <moth@blackhillsinfosec.com>
Co-authored-by: William Stearns <william.l.stearns@gmail.com>
Co-authored-by: William Stearns <3538265+william-stearns@users.noreply.github.com>
Co-authored-by: moth <25512187+0x6d6f7468@users.noreply.github.com>
2025-09-22 16:21:05 -04:00

234 lines
8.0 KiB
Go

package importer
import (
"errors"
"net"
"sync/atomic"
"time"
"github.com/activecm/rita/v5/config"
"github.com/activecm/rita/v5/database"
"github.com/activecm/rita/v5/importer/zeektypes"
zlog "github.com/activecm/rita/v5/logger"
"github.com/activecm/rita/v5/progressbar"
"github.com/activecm/rita/v5/util"
"github.com/ClickHouse/clickhouse-go/v2"
tea "github.com/charmbracelet/bubbletea"
"github.com/google/uuid"
)
var errParseSrcDst = "unable to parse valid ip address pair from conn log entry, skipping entry"
type ConnEntry struct {
ImportTime time.Time `ch:"import_time"`
ZeekUID util.FixedString `ch:"zeek_uid"`
ImportID util.FixedString `ch:"import_id"`
Filtered bool `ch:"filtered"`
Hash util.FixedString `ch:"hash"`
Timestamp time.Time `ch:"ts"`
Src net.IP `ch:"src"`
Dst net.IP `ch:"dst"`
SrcNUID uuid.UUID `ch:"src_nuid"`
DstNUID uuid.UUID `ch:"dst_nuid"`
SrcPort uint32 `ch:"src_port"`
DstPort uint32 `ch:"dst_port"`
MissingHostHeader bool `ch:"missing_host_header"` // used to mark HTTP entries that have a missing host header
MissingHostUseragent string `ch:"missing_host_useragent"` // useragent for connections that have a missing host header
Proto string `ch:"proto"`
Service string `ch:"service"`
Duration float64 `ch:"duration"`
SrcLocal bool `ch:"src_local"`
DstLocal bool `ch:"dst_local"`
ICMPType int64 `ch:"icmp_type"`
ICMPCode int64 `ch:"icmp_code"`
SrcBytes uint64 `ch:"src_bytes"`
DstBytes uint64 `ch:"dst_bytes"`
SrcIPBytes uint64 `ch:"src_ip_bytes"`
DstIPBytes uint64 `ch:"dst_ip_bytes"`
SrcPackets uint64 `ch:"src_packets"`
DstPackets uint64 `ch:"dst_packets"`
ConnState string `ch:"conn_state"`
MissedBytes uint64 `ch:"missed_bytes"`
ZeekHistory string `ch:"zeek_history"`
}
type UniqueConn struct {
Hash util.FixedString `ch:"hash"`
Src net.IP `ch:"src"`
Dst net.IP `ch:"dst"`
SrcNUID uuid.UUID `ch:"src_nuid"`
DstNUID uuid.UUID `ch:"dst_nuid"`
ConnCount uint64
ConnType string
}
type ZeekUIDRecord struct {
UID util.FixedString
Timestamp time.Time
UsedByFQDNBeacon bool
UsedByDNS bool
LinkedToHTTPEntry bool
NumUsedByHTTP int
Duration float64
SrcBytes uint64
DstBytes uint64
SrcIPBytes uint64
DstIPBytes uint64
SrcPackets uint64
DstPackets uint64
ConnState string
Proto string
Service string
}
// parseConn listens on a channel of raw conn/openconn log records, formats them and sends them to be written to the database
func parseConn(cfg *config.Config, conn <-chan zeektypes.Conn, output chan<- database.Data, importID util.FixedString, importTime time.Time, numConns *uint64) {
logger := zlog.GetLogger()
// loop over raw conn/openconn channel
for c := range conn {
// parse raw record as a conn/openconn entry
entry, err := formatConnRecord(cfg, &c, importID, importTime)
if err != nil {
logger.Warn().Err(err).
Str("log_path", c.LogPath).
Str("zeek_uid", c.UID).
Str("timestamp", (time.Unix(int64(c.TimeStamp), 0)).String()).
Str("src", c.Source).
Str("dst", c.Destination).
Send()
continue
}
// entry was subject to filtering
if entry == nil {
continue
}
output <- entry // send to log writer
if !entry.Filtered {
atomic.AddUint64(numConns, 1) // increment record counter
}
}
}
// formatConnRecord takes a raw conn record and formats it into the structure needed by the database
func formatConnRecord(cfg *config.Config, parseConn *zeektypes.Conn, importID util.FixedString, importTime time.Time) (*ConnEntry, error) { // filter filter
// get source destination pair for connection record
src := parseConn.Source
dst := parseConn.Destination
// parse addresses into binary format
srcIP := net.ParseIP(src)
dstIP := net.ParseIP(dst)
// verify that both addresses were parsed successfully
if (srcIP == nil) || (dstIP == nil) {
return nil, errors.New(errParseSrcDst)
}
// check if the connection is an icmp connection
icmpType, icmpCode := int64(-1), int64(-1)
if parseConn.Proto == "icmp" {
icmpType = int64(parseConn.SourcePort)
icmpCode = int64(parseConn.DestinationPort)
}
srcNUID := util.ParseNetworkID(srcIP, parseConn.AgentUUID)
dstNUID := util.ParseNetworkID(dstIP, parseConn.AgentUUID)
hash, err := util.NewFixedStringHash(srcIP.To16().String() + srcNUID.String() + dstIP.To16().String() + dstNUID.String())
if err != nil {
return nil, err
}
zeekUID, err := util.NewFixedStringHash(parseConn.UID)
if err != nil {
return nil, err
}
filtered := cfg.Filtering.FilterConnPair(srcIP, dstIP)
entry := &ConnEntry{
ImportTime: importTime,
ZeekUID: zeekUID,
Filtered: filtered,
Hash: hash,
Timestamp: time.Unix(int64(parseConn.TimeStamp), 0),
ImportID: importID,
Src: srcIP,
Dst: dstIP,
SrcNUID: srcNUID,
DstNUID: dstNUID,
SrcPort: parseConn.SourcePort,
DstPort: parseConn.DestinationPort,
ZeekHistory: parseConn.History,
MissedBytes: parseConn.MissedBytes,
Proto: parseConn.Proto,
Service: parseConn.Service,
Duration: parseConn.Duration,
SrcLocal: cfg.Filtering.CheckIfInternal(srcIP),
DstLocal: cfg.Filtering.CheckIfInternal(dstIP),
ICMPType: icmpType,
ICMPCode: icmpCode,
SrcBytes: parseConn.OrigBytes,
DstBytes: parseConn.RespBytes,
SrcIPBytes: parseConn.OrigIPBytes,
DstIPBytes: parseConn.RespIPBytes,
SrcPackets: parseConn.OrigPackets,
DstPackets: parseConn.RespPackets,
ConnState: parseConn.ConnState,
}
// conn is treated differently than the rest of the logs since some other logs might need to correlate
// the zeek_uid data for entries that would otherwise be filtered out;
// For example: proxy connections require linking via zeek uid, but if the conn record is filtered out, then
// it will never get populated
// Filter out from never included list before adding it to the uconn map to allow blocking subnets
// that could end up overcommitting memory
ignore := cfg.Filtering.FilterConnPairForHTTP(srcIP, dstIP)
if ignore {
return nil, nil
}
return entry, nil
}
// writeUnfilteredConns copies connections from conn_tmp to conn that were not marked as being filtered
func (importer *Importer) writeUnfilteredConns(progress *tea.Program, open bool, spinnerID int) error {
tmpTable := "conn_tmp"
table := "conn"
if open {
tmpTable = "openconn_tmp"
table = "openconn"
}
chCtx := importer.Database.QueryParameters(clickhouse.Parameters{
"tmp_table": tmpTable,
"table": table,
})
err := importer.Database.Conn.Exec(chCtx, `
INSERT INTO {table:Identifier} (
import_time, import_id, zeek_uid, hash, ts, src, dst, src_nuid, dst_nuid,
src_port, dst_port, missing_host_header, missing_host_useragent, proto, service,
conn_state, duration, src_local, dst_local, icmp_type, icmp_code, src_bytes, dst_bytes,
src_ip_bytes, dst_ip_bytes, src_packets, dst_packets, missed_bytes, zeek_history
) SELECT import_time, import_id, zeek_uid, hash, ts, src, dst, src_nuid, dst_nuid,
src_port, dst_port, missing_host_header, missing_host_useragent, proto, service,
conn_state, duration, src_local, dst_local, icmp_type, icmp_code, src_bytes, dst_bytes,
src_ip_bytes, dst_ip_bytes, src_packets, dst_packets, missed_bytes, zeek_history
FROM {tmp_table:Identifier}
WHERE filtered = false
`)
progress.Send(progressbar.ProgressSpinnerMsg(spinnerID))
return err
}