mirror of
https://github.com/Security-Onion-Solutions/securityonion.git
synced 2026-12-03 17:26:16 +01:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6a08c776b | ||
|
|
df44fe7670 | ||
|
|
2773b8479f | ||
|
|
da7bdd63cd | ||
|
|
5a59a83fef | ||
|
|
dfcfa580e5 | ||
|
|
99ee0d9750 | ||
|
|
80c5c38cd5 | ||
|
|
4fa5b48035 | ||
|
|
01b7d6a4e1 | ||
|
|
2bbb211484 | ||
|
|
ce91c5249b | ||
|
|
79ec4f81cc | ||
|
|
f024208bd6 | ||
|
|
7f1d60d366 | ||
|
|
1ce378cc1b | ||
|
|
d6ac9d6989 | ||
|
|
df650478b2 | ||
|
|
8c899ef367 | ||
|
|
ad0c0f454b | ||
|
|
ba3282a963 | ||
|
|
462a5d9cd1 | ||
|
|
7d8edebf0e | ||
|
|
26d503cb1e | ||
|
|
e79b61f7ab | ||
|
|
5c77862e65 | ||
|
|
c06946a708 | ||
|
|
5c70f097dc | ||
|
|
1b4a9d2a3f | ||
|
|
399219b735 | ||
|
|
180a4814f9 | ||
|
|
9a0e88f8d2 | ||
|
|
d37241376a | ||
|
|
3d8e6d0c6e | ||
|
|
ddf168f062 | ||
|
|
693f7917ae | ||
|
|
3682e0fde6 | ||
|
|
161d0d145f | ||
|
|
c04f06af1e | ||
|
|
7b2c44e965 | ||
|
|
9895dfbe7f | ||
|
|
a21d4b5f1b | ||
|
|
f5edb1f6a4 | ||
|
|
708b872583 | ||
|
|
844ca33aed | ||
|
|
45046b946e |
No files matched your search
@@ -164,6 +164,7 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|syncing rule" # false positive (rule sync log line includes rule name which can contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|request_unauthorized" # false positive (login failures to Hydra result in an 'error' log)
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index lifecycle policy" # false positive (elasticsearch policy names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|adding ingest pipeline" # false positive (elasticsearch ingest pipeline names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating index template" # false positive (elasticsearch index or template names contain 'error')
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|updating component template" # false positive (elasticsearch index or template names contain 'error')
|
||||
@@ -179,6 +180,7 @@ if [[ $EXCLUDE_FALSE_POSITIVE_ERRORS == 'Y' ]]; then
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|Static assets preprocessor only supports GET and HEAD requests" # expected WARN log lines indicating invalid auth header
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|respondError" # respondError is a function name, output via http middleware as standard request logging
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|GET /kibana/" # Ignore Kibana queries with triggered words
|
||||
EXCLUDED_ERRORS="$EXCLUDED_ERRORS|error-logs" # Elastic indexes can contain error-logs in their names, which can trigger false positives in log checks
|
||||
fi
|
||||
|
||||
if [[ $EXCLUDE_KNOWN_ERRORS == 'Y' ]]; then
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
'logstash.node': 'logstash.stack_monitoring.node',
|
||||
'logstash.node_cel': 'logstash.node',
|
||||
'logstash.node_stats': 'logstash.stack_monitoring.node_stats',
|
||||
'mqtt.traces': 'traces-mqtt.traces',
|
||||
'synthetics.browser': 'synthetics-browser',
|
||||
'synthetics.browser_network': 'synthetics-browser.network',
|
||||
'synthetics.browser_screenshot': 'synthetics-browser.screenshot',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
elasticsearch:
|
||||
enabled: false
|
||||
esheap: '600m'
|
||||
version: 9.4.8
|
||||
version: 9.4.10
|
||||
index_clean: true
|
||||
data_retention_method: DLM
|
||||
vm:
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
{% set DATA_RETENTION_METHOD = ELASTICSEARCHMERGED.data_retention_method %}
|
||||
|
||||
{% set PILLAR_GLOBAL_OVERRIDES = {} %}
|
||||
{% set ES_INDEX_PILLAR = salt['pillar.get']('elasticsearch:index_settings', {}) %}
|
||||
{# merge into a copy: pillar.get returns a live reference and this map pops/updates ES_INDEX_PILLAR #}
|
||||
{% set ES_INDEX_PILLAR = salt['defaults.merge'](salt['pillar.get']('elasticsearch:index_settings', {}), {}, in_place=False) %}
|
||||
{% if ES_INDEX_PILLAR.global_overrides is defined %}
|
||||
{% set PILLAR_GLOBAL_OVERRIDES = ES_INDEX_PILLAR.pop('global_overrides') %}
|
||||
{% endif %}
|
||||
|
||||
@@ -140,7 +140,23 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"dynamic_templates": [
|
||||
{
|
||||
"event_data_scalars_as_keyword": {
|
||||
"path_match": "event_data.*",
|
||||
"match_mapping_type": [
|
||||
"long",
|
||||
"double",
|
||||
"boolean"
|
||||
],
|
||||
"mapping": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"_meta": {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{% from 'vars/globals.map.jinja' import GLOBALS %}
|
||||
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
|
||||
|
||||
{% if GLOBALS.role == 'so-eval' %}
|
||||
{% set NODE_CONTAINERS = [
|
||||
@@ -109,3 +110,7 @@
|
||||
{% set NODE_CONTAINERS = [] %}
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% if INFLUX_RETIRED and 'so-influxdb' in NODE_CONTAINERS %}
|
||||
{% do NODE_CONTAINERS.remove('so-influxdb') %}
|
||||
{% endif %}
|
||||
@@ -1,5 +1,6 @@
|
||||
{% from 'vars/globals.map.jinja' import GLOBALS %}
|
||||
{% from 'docker/docker.map.jinja' import DOCKERMERGED %}
|
||||
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
|
||||
{% import_yaml 'firewall/defaults.yaml' as FIREWALL_DEFAULT %}
|
||||
|
||||
{# add our ip to self #}
|
||||
@@ -60,3 +61,12 @@
|
||||
{% endif %}
|
||||
|
||||
{% set FIREWALL_MERGED = salt['pillar.get']('firewall', FIREWALL_DEFAULT.firewall, merge=True) %}
|
||||
|
||||
{# filtered after the merge so portgroup lists saved in Configuration lose influxdb too #}
|
||||
{% if INFLUX_RETIRED and (role.startswith('manager') or role in ['eval', 'standalone', 'import']) %}
|
||||
{% for hostgroup in FIREWALL_MERGED.role[role].chain['DOCKER-USER'].hostgroups.values() %}
|
||||
{% if 'influxdb' in hostgroup.get('portgroups', []) %}
|
||||
{% do hostgroup.update({'portgroups': hostgroup.portgroups | reject('equalto', 'influxdb') | list}) %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
@@ -8,10 +8,10 @@ influxdb:
|
||||
flux-log-enabled: false
|
||||
hardening-enabled: true
|
||||
http-bind-address: :8086
|
||||
http-idle-timeout: 0
|
||||
http-idle-timeout: 0s
|
||||
http-read-header-timeout: 10s
|
||||
http-read-timeout: 0
|
||||
http-write-timeout: 0
|
||||
http-read-timeout: 0s
|
||||
http-write-timeout: 0s
|
||||
influxql-max-select-buckets: 0
|
||||
influxql-max-select-point: 0
|
||||
influxql-max-select-series: 0
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
# Elastic License 2.0.
|
||||
|
||||
{% from 'influxdb/map.jinja' import INFLUXMERGED %}
|
||||
{% from 'telegraf/map.jinja' import INFLUX_RETIRED %}
|
||||
|
||||
include:
|
||||
{% if INFLUXMERGED.enabled %}
|
||||
{% if INFLUX_RETIRED %}
|
||||
- influxdb.retired
|
||||
{% elif INFLUXMERGED.enabled %}
|
||||
- influxdb.enabled
|
||||
{% else %}
|
||||
- influxdb.disabled
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Copyright Security Onion Solutions LLC and/or licensed to Security Onion Solutions LLC under one
|
||||
# or more contributor license agreements. Licensed under the Elastic License 2.0 as shown at
|
||||
# https://securityonion.net/license; you may not use this file except in compliance with the
|
||||
# Elastic License 2.0.
|
||||
|
||||
{% from 'allowed_states.map.jinja' import allowed_states %}
|
||||
{% if sls.split('.')[0] in allowed_states %}
|
||||
|
||||
include:
|
||||
- influxdb.disabled
|
||||
|
||||
influxdb_data_purged:
|
||||
file.directory:
|
||||
- name: /nsm/influxdb
|
||||
- clean: True
|
||||
- require:
|
||||
- docker_container: so-influxdb
|
||||
|
||||
influxdb_conf_purged:
|
||||
file.absent:
|
||||
- name: /opt/so/conf/influxdb
|
||||
- require:
|
||||
- docker_container: so-influxdb
|
||||
|
||||
{% else %}
|
||||
|
||||
{{sls}}_state_not_allowed:
|
||||
test.fail_without_changes:
|
||||
- name: {{sls}}_state_not_allowed
|
||||
|
||||
{% endif %}
|
||||
@@ -1,6 +1,6 @@
|
||||
influxdb:
|
||||
enabled:
|
||||
description: Enables the grid metrics collection storage system. Security Onion grid health monitoring requires this process to remain enabled. WARNING - Disabling the process is unsupported, and will cause unexpected results.
|
||||
description: Enables the grid metrics collection storage system. Security Onion grid health monitoring requires this process to remain enabled. WARNING - Disabling the process is unsupported, and will cause unexpected results. This setting has no effect when telegraf.output is POSTGRES.
|
||||
forcedType: bool
|
||||
helpLink: influxdb
|
||||
config:
|
||||
@@ -42,17 +42,17 @@ influxdb:
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-idle-timeout:
|
||||
description: Keep-alive timeout while a connection waits for new requests. A value of 0 is the same as no timeout enforced.
|
||||
description: Keep-alive timeout while a connection waits for new requests. A value of 0s is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-read-header-timeout:
|
||||
description: The duration to wait for a request header before closing the connection. A value of 0 is the same as no timeout enforced.
|
||||
description: The duration to wait for a request header before closing the connection. A value of 0s is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
http-read-timeout:
|
||||
description: The duration to wait for the request to be fully read before closing the connection. A value of 0 is the same as no timeout enforced.
|
||||
description: The duration to wait for the request to be fully read before closing the connection. A value of 0s is the same as no timeout enforced.
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
|
||||
@@ -128,7 +128,7 @@ lookup_org_id_with_wait() {
|
||||
wait=10
|
||||
while [[ $attempts -lt $max_attempts ]]; do
|
||||
response=$(request orgs?org=Security+Onion)
|
||||
oid=$(echo "$response" | jq -r ".orgs[] | select(.name == \"Security Onion\").id")
|
||||
oid=$(echo "$response" | jq -r ".orgs[]? | select(.name == \"Security Onion\").id")
|
||||
if [[ -z $oid ]]; then
|
||||
attempts=$((attempts+1))
|
||||
log "Server does not appear to be running or fully initialized - will try again in $wait seconds ($attempts / $max_attempts)"
|
||||
|
||||
@@ -22,7 +22,7 @@ kibana:
|
||||
- default
|
||||
- file
|
||||
migrations:
|
||||
discardCorruptObjects: "9.4.8"
|
||||
discardCorruptObjects: "9.4.10"
|
||||
telemetry:
|
||||
enabled: False
|
||||
xpack:
|
||||
|
||||
@@ -16,6 +16,9 @@ For each intent file under /opt/so/state/push_pending/*.json whose last_touch
|
||||
is older than debounce_seconds, this script:
|
||||
* concatenates the actions lists from every ready intent
|
||||
* dedupes by (state or __highstate__, tgt, tgt_type)
|
||||
* narrows each target to minions that have completed a highstate
|
||||
* keeps the part of an action that would reach a node still in its first highstate in
|
||||
push_pending/pending_<id>.json, which drains like any other intent once that highstate completes
|
||||
* drops actions whose target matches no accepted minion (e.g. a role with no nodes yet)
|
||||
* holds everything for a later pass while salt-master has only just started
|
||||
* dispatches a single `salt-run state.orchestrate orch.push_batch --async`
|
||||
@@ -48,6 +51,8 @@ LOCK_FILE = os.path.join(PENDING_DIR, '.lock')
|
||||
LOG_FILE = '/opt/so/log/salt/so-push-drainer.log'
|
||||
MASTER_CONFIG = '/etc/salt/master'
|
||||
MASTER_PIDFILE = '/var/run/salt-master.pid'
|
||||
MINION_KEYS_DIR = '/etc/salt/pki/master/minions'
|
||||
MAX_PATHS = 20
|
||||
|
||||
# Minions rejoin a restarted master's publisher up to ~22s after it returns (zmq reconnect interval
|
||||
# plus jitter, each up to recon_default + recon_max) and a job published before then reaches nobody.
|
||||
@@ -58,6 +63,12 @@ DISPATCHED_DIR = '/opt/so/state/push_dispatched'
|
||||
|
||||
HIGHSTATE_SENTINEL = '__highstate__'
|
||||
|
||||
# Grain written by setup and removed by salt.lasthighstate at the end of the node's first highstate.
|
||||
PENDING_GRAIN = 'first_highstate_pending'
|
||||
|
||||
# Node ids from the master's cache go into kept intent file names and targets.
|
||||
ID_RE = re.compile(r'[A-Za-z0-9._-]{1,253}')
|
||||
|
||||
RESULT_CHECK_DELAY = 30
|
||||
RESULT_RECHECK_MAX = 300
|
||||
RESULT_MAX_AGE = 7200
|
||||
@@ -126,30 +137,129 @@ def _dedupe_actions(actions):
|
||||
return deduped
|
||||
|
||||
|
||||
def _targeted(actions, log):
|
||||
"""Drops actions whose target matches no accepted minion (e.g. a role with no nodes yet), which
|
||||
the orchestration would otherwise report as failed with 'No minions responded'."""
|
||||
def _skip_pending(action):
|
||||
"""Narrows a compound target to minions that have completed a highstate. A newly accepted node matches
|
||||
its role's targets before orch.deploy_newnode has highstated it, and a single state fails there."""
|
||||
if action.get('tgt_type', 'compound') != 'compound':
|
||||
return action
|
||||
return dict(action, tgt='( {} ) and not G@{}:True'.format(action.get('tgt'), PENDING_GRAIN))
|
||||
|
||||
|
||||
def _ckminions():
|
||||
return salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
|
||||
|
||||
|
||||
def _pending_minions(ckminions, log):
|
||||
try:
|
||||
ckminions = salt.utils.minions.CkMinions(salt.config.master_config(MASTER_CONFIG))
|
||||
return set(ckminions.check_minions('G@{}:True'.format(PENDING_GRAIN), 'compound').get('minions') or [])
|
||||
except Exception as exc:
|
||||
log.warning('cannot list nodes still in their first highstate; keeping no pushes for them: %s', exc)
|
||||
return set()
|
||||
|
||||
|
||||
def _targeted(actions, log):
|
||||
"""Returns (targeted, kept). Drops actions whose target matches no accepted minion (e.g. a role with no
|
||||
nodes yet), which the orchestration would otherwise report as failed with 'No minions responded'. The part
|
||||
of a compound action that would reach a node still in its first highstate is returned in kept, by node id,
|
||||
narrowed to that node, so it can be applied once that highstate completes."""
|
||||
try:
|
||||
ckminions = _ckminions()
|
||||
except Exception:
|
||||
log.exception('cannot load master config; dispatching without checking targets')
|
||||
return actions
|
||||
return [_skip_pending(action) for action in actions], {}
|
||||
pending = _pending_minions(ckminions, log)
|
||||
targeted = []
|
||||
kept = {}
|
||||
for action in actions:
|
||||
narrowed = _skip_pending(action)
|
||||
tgt_type = action.get('tgt_type', 'compound')
|
||||
name = 'highstate' if action.get('highstate') else action.get('state')
|
||||
try:
|
||||
matched = ckminions.check_minions(action['tgt'], action.get('tgt_type', 'compound')).get('minions')
|
||||
matched = ckminions.check_minions(narrowed['tgt'], tgt_type).get('minions')
|
||||
unwrapped = []
|
||||
if pending and tgt_type == 'compound':
|
||||
unwrapped = ckminions.check_minions(action['tgt'], tgt_type).get('minions')
|
||||
except Exception:
|
||||
log.exception('cannot resolve tgt=%s; dispatching it anyway', action.get('tgt'))
|
||||
matched = True
|
||||
log.exception('cannot resolve tgt=%s; dispatching it anyway', narrowed.get('tgt'))
|
||||
matched, unwrapped = True, []
|
||||
held = False
|
||||
for minion in sorted(pending.intersection(unwrapped or [])):
|
||||
if not ID_RE.fullmatch(minion):
|
||||
log.warning('not keeping %s for %r: not a valid node id', name, minion)
|
||||
continue
|
||||
kept.setdefault(minion, []).append(
|
||||
dict(action, tgt='L@{} and ( {} )'.format(minion, action['tgt']), tgt_type='compound'))
|
||||
held = True
|
||||
if matched:
|
||||
targeted.append(action)
|
||||
else:
|
||||
log.info('skipping %s: no minions match tgt=%s',
|
||||
'highstate' if action.get('highstate') else action.get('state'), action.get('tgt'))
|
||||
return targeted
|
||||
targeted.append(narrowed)
|
||||
elif not held:
|
||||
log.info('skipping %s: no minions match tgt=%s', name, action['tgt'])
|
||||
return targeted, kept
|
||||
|
||||
|
||||
def _kept_path(node):
|
||||
return os.path.join(PENDING_DIR, 'pending_{}.json'.format(node))
|
||||
|
||||
|
||||
def _keep_for_pending(kept, paths, log):
|
||||
"""Merges each node's kept actions into its pending_<id>.json. The caller already holds the lock, which
|
||||
flock would not grant a second time. Returns False if any write failed."""
|
||||
now = time.time()
|
||||
written = True
|
||||
for node, actions in kept.items():
|
||||
path = _kept_path(node)
|
||||
intent = _read_intent(path, log) if os.path.exists(path) else {}
|
||||
if not isinstance(intent, dict):
|
||||
intent = {}
|
||||
known = intent.get('paths') or []
|
||||
intent.update(
|
||||
actions=_dedupe_actions((intent.get('actions') or []) + actions),
|
||||
pending=node,
|
||||
last_touch=now,
|
||||
paths=(known + [p for p in paths if p not in known])[-MAX_PATHS:],
|
||||
)
|
||||
intent.setdefault('first_touch', now)
|
||||
try:
|
||||
tmp_path = path + '.tmp'
|
||||
with open(tmp_path, 'w') as f:
|
||||
json.dump(intent, f)
|
||||
os.rename(tmp_path, path)
|
||||
except (OSError, ValueError) as exc:
|
||||
log.error('cannot keep pushes for %s until its first highstate completes: %s', node, exc)
|
||||
written = False
|
||||
continue
|
||||
prefix = 'L@{} and ( '.format(node)
|
||||
for action in actions:
|
||||
tgt = action['tgt']
|
||||
if tgt.startswith(prefix) and tgt.endswith(' )'):
|
||||
tgt = tgt[len(prefix):-len(' )')]
|
||||
log.info('push kept for %s until its first highstate completes: %s tgt=%s', node,
|
||||
'highstate' if action.get('highstate') else action.get('state'), tgt)
|
||||
return written
|
||||
|
||||
|
||||
def _still_pending(ckminions, ids, log):
|
||||
"""Ids whose first highstate has not completed. A node with no cache entry has not compiled pillar yet."""
|
||||
pending = set()
|
||||
for node in ids:
|
||||
try:
|
||||
data = ckminions.cache.fetch('minions/{}'.format(node), 'data')
|
||||
except Exception as exc:
|
||||
log.warning('cannot read the cached grains of %s; holding its kept pushes: %s', node, exc)
|
||||
pending.add(node)
|
||||
continue
|
||||
grains = data.get('grains') if isinstance(data, dict) else None
|
||||
if not isinstance(grains, dict) or PENDING_GRAIN in grains:
|
||||
pending.add(node)
|
||||
return pending
|
||||
|
||||
|
||||
def _master_settling(now):
|
||||
"""True while salt-master started less than MASTER_SETTLE_SECONDS ago. salt-master writes its pidfile
|
||||
when it starts, so the file's mtime is the master's start time. Minions take up to ~22s to rejoin a
|
||||
restarted master's publisher and a job published before then reaches nobody, so dispatch is held;
|
||||
held intents stay in push_pending and are drained on a later pass. A missing or unreadable pidfile
|
||||
returns False: the master is then normally not running, so _dispatch fails and keeps the intents."""
|
||||
try:
|
||||
age = now - os.path.getmtime(MASTER_PIDFILE)
|
||||
except OSError:
|
||||
@@ -418,18 +528,39 @@ def main():
|
||||
now = time.time()
|
||||
ready = []
|
||||
skipped = 0
|
||||
held = 0
|
||||
broken = []
|
||||
for path in intent_files:
|
||||
intent = _read_intent(path, log)
|
||||
if not isinstance(intent, dict):
|
||||
broken.append(path)
|
||||
continue
|
||||
node = intent.get('pending')
|
||||
if node is not None and not (isinstance(node, str) and ID_RE.fullmatch(node)):
|
||||
log.warning('removing kept intent %s: %r is not a valid node id', path, node)
|
||||
broken.append(path)
|
||||
continue
|
||||
if node is not None and not os.path.exists(os.path.join(MINION_KEYS_DIR, node)):
|
||||
log.info('removing kept pushes for %s: its key is no longer accepted', node)
|
||||
broken.append(path)
|
||||
continue
|
||||
last_touch = intent.get('last_touch', 0)
|
||||
if now - last_touch < debounce_seconds:
|
||||
skipped += 1
|
||||
continue
|
||||
ready.append((path, intent))
|
||||
|
||||
kept_nodes = {intent['pending'] for _, intent in ready if intent.get('pending') is not None}
|
||||
if kept_nodes:
|
||||
try:
|
||||
still_pending = _still_pending(_ckminions(), kept_nodes, log)
|
||||
except Exception as exc:
|
||||
log.warning('cannot load master config; holding kept pushes: %s', exc)
|
||||
still_pending = kept_nodes
|
||||
waiting = {path for path, intent in ready if intent.get('pending') in still_pending}
|
||||
held = len(waiting)
|
||||
ready = [(path, intent) for path, intent in ready if path not in waiting]
|
||||
|
||||
for path in broken:
|
||||
try:
|
||||
os.unlink(path)
|
||||
@@ -437,8 +568,9 @@ def main():
|
||||
pass
|
||||
|
||||
if not ready:
|
||||
if skipped:
|
||||
log.debug('no ready intents (%d still in debounce window)', skipped)
|
||||
if skipped or held:
|
||||
log.debug('no ready intents (%d still in debounce window, %d for nodes still in their first highstate)',
|
||||
skipped, held)
|
||||
return 0
|
||||
|
||||
if _master_settling(now):
|
||||
@@ -470,24 +602,32 @@ def main():
|
||||
'draining %d intent(s): %d action(s) after dedupe (raw=%d), '
|
||||
'debounce_duration=%.1fs, paths=%s',
|
||||
len(ready), len(deduped), len(combined_actions),
|
||||
debounce_duration, all_paths[:20],
|
||||
debounce_duration, all_paths[:MAX_PATHS],
|
||||
)
|
||||
for action in deduped:
|
||||
log.info('action: %s tgt=%s', 'highstate' if action.get('highstate') else action.get('state'),
|
||||
action.get('tgt'))
|
||||
|
||||
targeted = _targeted(deduped, log)
|
||||
targeted, kept = _targeted(deduped, log)
|
||||
if kept and not _keep_for_pending(kept, all_paths, log):
|
||||
log.warning('cannot keep pushes for nodes still in their first highstate; '
|
||||
'leaving intent files in place for retry')
|
||||
return 1
|
||||
written = {_kept_path(node) for node in kept}
|
||||
|
||||
if targeted:
|
||||
jid = _dispatch(targeted, log)
|
||||
if jid is None:
|
||||
log.warning('dispatch failed; leaving intent files in place for retry')
|
||||
return 1
|
||||
if jid:
|
||||
_record_dispatch(jid, targeted, all_paths[:20], log)
|
||||
else:
|
||||
_record_dispatch(jid, targeted, all_paths[:MAX_PATHS], log)
|
||||
elif not kept:
|
||||
log.info('no action matches a minion; nothing to dispatch')
|
||||
|
||||
for path, _ in ready:
|
||||
if path in written:
|
||||
continue
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
|
||||
@@ -3,14 +3,18 @@
|
||||
# https://securityonion.net/license; you may not use this file except in compliance with the
|
||||
# Elastic License 2.0.
|
||||
|
||||
import errno
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from importlib.machinery import SourceFileLoader
|
||||
@@ -34,6 +38,8 @@ JID = '20260930171554259426'
|
||||
ASYNC_STDERR = ('[WARNING ] Running in asynchronous mode. Results of this execution may be collected '
|
||||
'by attaching to the master event bus or by examining the master job cache, if '
|
||||
'configured. This execution is running under tag salt/run/{}\n'.format(JID))
|
||||
NOT_PENDING = ' and not G@first_highstate_pending:True'
|
||||
PENDING_TGT = 'G@first_highstate_pending:True'
|
||||
CONFLICT = ('The function "state.sls" is running as PID 372218 and was started at '
|
||||
'2026, Sep 30 17:15:40.466233 with jid 20260930171540466233')
|
||||
|
||||
@@ -490,8 +496,19 @@ class TestTargeted(DrainerTestCase):
|
||||
self.CkMinions = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def test_skip_pending(self):
|
||||
self.assertEqual(drainer._skip_pending({'state': 'soc', 'tgt': 'G@role:so-eval or G@role:so-manager'}),
|
||||
{'state': 'soc', 'tgt': '( G@role:so-eval or G@role:so-manager )' + NOT_PENDING})
|
||||
self.assertEqual(drainer._skip_pending({'highstate': True, 'tgt': '*', 'tgt_type': 'compound'}),
|
||||
{'highstate': True, 'tgt': '( * )' + NOT_PENDING, 'tgt_type': 'compound'})
|
||||
listed = {'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}
|
||||
self.assertEqual(drainer._skip_pending(listed), listed)
|
||||
|
||||
def test_drops_unmatched(self):
|
||||
matches = {'G@role:so-sensor': ['sensor_sensor'], 'manager_manager': ['manager_manager']}
|
||||
sensor = '( G@role:so-sensor )' + NOT_PENDING
|
||||
heavynode = '( G@role:so-heavynode )' + NOT_PENDING
|
||||
idh = '( G@role:so-idh )' + NOT_PENDING
|
||||
matches = {sensor: ['sensor_sensor'], 'manager_manager': ['manager_manager']}
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': matches.get(tgt, [])}
|
||||
actions = [
|
||||
{'state': 'strelka', 'tgt': 'G@role:so-sensor'},
|
||||
@@ -499,30 +516,503 @@ class TestTargeted(DrainerTestCase):
|
||||
{'highstate': True, 'tgt': 'G@role:so-idh'},
|
||||
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
|
||||
]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), [actions[0], actions[3]])
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'strelka', 'tgt': sensor}, actions[3]], {}))
|
||||
self.CkMinions.assert_called_once()
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
('G@role:so-sensor', 'compound'), ('G@role:so-heavynode', 'compound'),
|
||||
('G@role:so-idh', 'compound'), ('manager_manager', 'list'),
|
||||
(PENDING_TGT, 'compound'), (sensor, 'compound'), (heavynode, 'compound'), (idh, 'compound'),
|
||||
('manager_manager', 'list'),
|
||||
])
|
||||
info = self.logged('info')
|
||||
self.assertIn('skipping suricata: no minions match tgt=G@role:so-heavynode', info)
|
||||
self.assertIn('skipping highstate: no minions match tgt=G@role:so-idh', info)
|
||||
self.assertNotIn('strelka', info)
|
||||
|
||||
def test_list_target_unmatched(self):
|
||||
self.ckminions.check_minions.return_value = {'minions': []}
|
||||
actions = [{'state': 'soc', 'tgt': 'gone_manager', 'tgt_type': 'list'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([], {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), ('gone_manager', 'list'),
|
||||
])
|
||||
info = self.logged('info')
|
||||
self.assertIn('skipping soc: no minions match tgt=gone_manager', info)
|
||||
self.assertNotIn('first highstate', info)
|
||||
|
||||
def test_narrowed_match_checks_once(self):
|
||||
narrowed = '( G@role:so-sensor )' + NOT_PENDING
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
|
||||
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
|
||||
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), (narrowed, 'compound'),
|
||||
])
|
||||
|
||||
def test_pending_set_empty_no_extra_calls(self):
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {
|
||||
'minions': [] if tgt == PENDING_TGT else ['sensor_sensor']}
|
||||
actions = [
|
||||
{'state': 'suricata', 'tgt': 'G@role:so-sensor'},
|
||||
{'highstate': True, 'tgt': '*'},
|
||||
{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'},
|
||||
]
|
||||
targeted, kept = drainer._targeted(actions, self.log)
|
||||
self.assertEqual(len(targeted), 3)
|
||||
self.assertEqual(kept, {})
|
||||
tgts = [c.args[0] for c in self.ckminions.check_minions.call_args_list]
|
||||
self.assertEqual(tgts.count(PENDING_TGT), 1)
|
||||
self.assertEqual(len(tgts), 1 + len(actions))
|
||||
self.assertNotIn('G@role:so-sensor', tgts)
|
||||
|
||||
def test_list_target_not_kept(self):
|
||||
self.ckminions.check_minions.side_effect = lambda tgt, tgt_type: {'minions': ['manager_manager']}
|
||||
actions = [{'state': 'soc', 'tgt': 'manager_manager', 'tgt_type': 'list'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), (actions, {}))
|
||||
self.assertEqual([c.args for c in self.ckminions.check_minions.call_args_list], [
|
||||
(PENDING_TGT, 'compound'), ('manager_manager', 'list'),
|
||||
])
|
||||
|
||||
def test_original_check_error_keeps_action(self):
|
||||
narrowed = '( G@role:so-sensor )' + NOT_PENDING
|
||||
results = {PENDING_TGT: {'minions': ['sensor_new']}, narrowed: {'minions': []}}
|
||||
|
||||
def check(tgt, tgt_type):
|
||||
if tgt not in results:
|
||||
raise RuntimeError('boom')
|
||||
return results[tgt]
|
||||
self.ckminions.check_minions.side_effect = check
|
||||
actions = [{'state': 'suricata', 'tgt': 'G@role:so-sensor'}]
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'suricata', 'tgt': narrowed}], {}))
|
||||
self.log.exception.assert_called_once()
|
||||
|
||||
def test_master_config_error_keeps_actions(self):
|
||||
actions = [{'state': 'soc', 'tgt': '*'}]
|
||||
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
|
||||
self.assertEqual(drainer._targeted(actions, self.log), actions)
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( * )' + NOT_PENDING}], {}))
|
||||
self.log.exception.assert_called_once()
|
||||
self.CkMinions.assert_not_called()
|
||||
|
||||
def test_check_error_keeps_action(self):
|
||||
actions = [{'state': 'soc', 'tgt': 'G@role:'}]
|
||||
self.ckminions.check_minions.side_effect = RuntimeError('bad target')
|
||||
self.assertEqual(drainer._targeted(actions, self.log), actions)
|
||||
self.assertEqual(drainer._targeted(actions, self.log), ([{'state': 'soc', 'tgt': '( G@role: )' + NOT_PENDING}], {}))
|
||||
self.log.exception.assert_called_once()
|
||||
|
||||
def test_pending_minions_error(self):
|
||||
self.ckminions.check_minions.side_effect = RuntimeError('cache unavailable')
|
||||
self.assertEqual(drainer._pending_minions(self.ckminions, self.log), set())
|
||||
self.assertIn('cannot list nodes still in their first highstate', self.logged('warning'))
|
||||
self.assertIn('cache unavailable', self.logged('warning'))
|
||||
|
||||
def test_still_pending(self):
|
||||
cache = {'minions/a': {'grains': {drainer.PENDING_GRAIN: True}}, 'minions/b': {'grains': {'role': 'so-sensor'}},
|
||||
'minions/c': {}}
|
||||
self.ckminions.cache.fetch.side_effect = lambda bank, key: cache[bank]
|
||||
self.assertEqual(drainer._still_pending(self.ckminions, {'a', 'b', 'c'}, self.log), {'a', 'c'})
|
||||
self.assertEqual({c.args[1] for c in self.ckminions.cache.fetch.call_args_list}, {'data'})
|
||||
self.log.warning.assert_not_called()
|
||||
|
||||
def test_still_pending_lookup_error(self):
|
||||
self.ckminions.cache.fetch.side_effect = OSError('cache read failed')
|
||||
self.assertEqual(drainer._still_pending(self.ckminions, {'a'}, self.log), {'a'})
|
||||
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
|
||||
|
||||
|
||||
class FakeCkMinions:
|
||||
"""Evaluates the compound targets the drainer builds against a fixed set of role targets."""
|
||||
|
||||
def __init__(self):
|
||||
self.targets = {}
|
||||
self.accepted = set()
|
||||
self.pending = set()
|
||||
self.grains = {}
|
||||
self.fetch_error = None
|
||||
self.cache = MagicMock()
|
||||
self.cache.fetch.side_effect = self.fetch
|
||||
|
||||
def fetch(self, bank, key):
|
||||
if self.fetch_error:
|
||||
raise self.fetch_error
|
||||
node = bank.split('/', 1)[1]
|
||||
return {'grains': self.grains[node]} if node in self.grains else {}
|
||||
|
||||
def match(self, tgt):
|
||||
# Salt's greedy matching: an accepted minion with no cached grains matches any grain target.
|
||||
greedy = self.accepted - set(self.grains) if tgt.startswith('G@') else set()
|
||||
if tgt == PENDING_TGT:
|
||||
return self.pending | greedy
|
||||
wrapped = re.fullmatch(r'\( (.*) \)' + re.escape(NOT_PENDING), tgt)
|
||||
if wrapped:
|
||||
return self.match(wrapped.group(1)) - self.match(PENDING_TGT)
|
||||
narrowed = re.fullmatch(r'L@(\S+) and \( (.*) \)', tgt)
|
||||
if narrowed:
|
||||
return {narrowed.group(1)} & self.match(narrowed.group(2))
|
||||
return set(self.targets.get(tgt, [])) | greedy
|
||||
|
||||
def check_minions(self, tgt, tgt_type='compound'):
|
||||
return {'minions': sorted(self.match(tgt))}
|
||||
|
||||
def pend(self, *nodes):
|
||||
for node in nodes:
|
||||
self.pending.add(node)
|
||||
self.grains[node] = {'role': 'so-sensor', drainer.PENDING_GRAIN: True}
|
||||
|
||||
def release(self, *nodes):
|
||||
for node in nodes:
|
||||
self.pending.discard(node)
|
||||
self.grains[node] = {'role': 'so-sensor'}
|
||||
|
||||
|
||||
SURICATA = {'state': 'suricata', 'tgt': 'G@role:so-sensor'}
|
||||
|
||||
|
||||
def _kept_copy(node, action):
|
||||
return dict(action, tgt='L@{} and ( {} )'.format(node, action['tgt']), tgt_type='compound')
|
||||
|
||||
|
||||
class TestKeptPushes(DrainerTestCase):
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.ck = FakeCkMinions()
|
||||
self.ck.targets = {'G@role:so-sensor': ['a', 'b', 'c'], 'G@role:so-searchnode': ['s'], '*': ['a', 'b', 'c', 's']}
|
||||
self.ck.release('a', 'b', 'c', 's')
|
||||
self.keys = os.path.join(self.tmpdir, 'keys')
|
||||
os.makedirs(self.keys)
|
||||
for node in ('a', 'b', 'c', 's'):
|
||||
self.accept(node)
|
||||
self.cfg = {'enabled': True, 'debounce_seconds': 30}
|
||||
self.run = MagicMock(return_value=MagicMock(stdout='', stderr=ASYNC_STDERR))
|
||||
for target, name, kwargs in (
|
||||
(drainer.salt.utils.minions, 'CkMinions', {'return_value': self.ck}),
|
||||
(drainer.subprocess, 'run', {'new': self.run}),
|
||||
(drainer, 'MINION_KEYS_DIR', {'new': self.keys}),
|
||||
(drainer, '_make_logger', {'return_value': self.log}),
|
||||
(drainer, '_load_push_cfg', {'side_effect': lambda: self.cfg}),
|
||||
(drainer, '_check_dispatched', {}),
|
||||
(drainer, '_master_settling', {'return_value': False}),
|
||||
):
|
||||
patcher = patch.object(target, name, **kwargs)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def accept(self, node):
|
||||
self.write_json(self.keys, node, '')
|
||||
self.ck.accepted.add(node)
|
||||
|
||||
def source(self, actions, name='pillar_suricata.json', paths=None):
|
||||
now = time.time()
|
||||
return self.write_json(self.pending, name, {
|
||||
'first_touch': now - 65, 'last_touch': now - 60, 'actions': actions,
|
||||
'paths': paths or ['audit:suricata.config'],
|
||||
})
|
||||
|
||||
def kept_path(self, node):
|
||||
return os.path.join(self.pending, 'pending_{}.json'.format(node))
|
||||
|
||||
def kept(self, node):
|
||||
with open(self.kept_path(node)) as f:
|
||||
return json.load(f)
|
||||
|
||||
def age(self, node, seconds=60):
|
||||
intent = self.kept(node)
|
||||
intent['last_touch'] -= seconds
|
||||
self.write_json(self.pending, 'pending_{}.json'.format(node), intent)
|
||||
|
||||
def dispatched_actions(self):
|
||||
return [json.loads(c.args[0][3][len('pillar='):])['actions'] for c in self.run.call_args_list]
|
||||
|
||||
def test_keeps_pending_only(self):
|
||||
self.ck.targets['G@role:so-sensor'] = ['a']
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'], [
|
||||
{'state': 'suricata', 'tgt': 'L@a and ( G@role:so-sensor )', 'tgt_type': 'compound'}])
|
||||
self.assertEqual(intent['pending'], 'a')
|
||||
self.assertEqual(intent['paths'], ['audit:suricata.config'])
|
||||
self.assertFalse(os.path.exists(source))
|
||||
info = self.logged('info')
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata tgt=G@role:so-sensor', info)
|
||||
self.assertNotIn('L@a', info)
|
||||
self.assertNotIn('skipping', info)
|
||||
self.assertNotIn('nothing to dispatch', info)
|
||||
|
||||
def test_keeps_pending_only_highstate(self):
|
||||
self.ck.targets['*'] = ['a']
|
||||
self.ck.pend('a')
|
||||
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertEqual(self.kept('a')['actions'], [{'highstate': True, 'tgt': 'L@a and ( * )', 'tgt_type': 'compound'}])
|
||||
info = self.logged('info')
|
||||
self.assertIn('push kept for a until its first highstate completes: highstate tgt=*', info)
|
||||
self.assertNotIn('L@a', info)
|
||||
self.assertNotIn('error', info.lower())
|
||||
|
||||
def test_keeps_and_dispatches(self):
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata', self.logged('info'))
|
||||
|
||||
def test_keeps_several_pending(self):
|
||||
self.ck.pend('a', 'b')
|
||||
self.source([SURICATA])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertEqual(self.kept('b')['actions'], [_kept_copy('b', SURICATA)])
|
||||
self.assertEqual(self.dispatched_actions(), [[{'state': 'suricata', 'tgt': '( G@role:so-sensor )' + NOT_PENDING}]])
|
||||
|
||||
self.run.reset_mock()
|
||||
self.ck.release('a')
|
||||
self.age('a')
|
||||
self.age('b')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertTrue(os.path.exists(self.kept_path('b')))
|
||||
|
||||
def test_keep_merge(self):
|
||||
strelka = {'state': 'strelka', 'tgt': 'G@role:so-sensor'}
|
||||
paths = ['audit:p{}'.format(i) for i in range(30)]
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, paths[:15], self.log))
|
||||
first_touch = self.kept('a')['first_touch']
|
||||
with patch.object(drainer.time, 'time', return_value=first_touch + 100):
|
||||
self.assertTrue(drainer._keep_for_pending(
|
||||
{'a': [_kept_copy('a', strelka), _kept_copy('a', SURICATA)]}, paths[10:], self.log))
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'], [_kept_copy('a', SURICATA), _kept_copy('a', strelka)])
|
||||
self.assertEqual(intent['first_touch'], first_touch)
|
||||
self.assertEqual(intent['last_touch'], first_touch + 100)
|
||||
self.assertEqual(intent['paths'], paths[-drainer.MAX_PATHS:])
|
||||
self.assertEqual(intent['pending'], 'a')
|
||||
|
||||
def test_keep_corrupt_file(self):
|
||||
self.write_json(self.pending, 'pending_a.json', '{nope')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log))
|
||||
self.assertIn('cannot read intent', self.logged('warning'))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
def test_keep_logs_other_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@b and ( G@role:so-sensor )')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('push kept for a until its first highstate completes: suricata tgt=L@b and ( G@role:so-sensor )',
|
||||
self.logged('info'))
|
||||
self.assertEqual(self.kept('a')['actions'], [action])
|
||||
|
||||
def test_keep_logs_nested_parens_tgt(self):
|
||||
original = '( G@role:so-sensor or G@role:so-heavynode )'
|
||||
action = _kept_copy('a', dict(SURICATA, tgt=original))
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt={}\n'.format(original), self.logged('info') + '\n')
|
||||
self.assertEqual(self.kept('a')['actions'], [action])
|
||||
|
||||
def test_keep_logs_prefix_node_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@ab and ( G@role:so-sensor )')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt=L@ab and ( G@role:so-sensor )', self.logged('info'))
|
||||
|
||||
def test_keep_logs_unterminated_tgt_unchanged(self):
|
||||
action = dict(SURICATA, tgt='L@a and ( G@role:so-sensor')
|
||||
self.assertTrue(drainer._keep_for_pending({'a': [action]}, [], self.log))
|
||||
self.assertIn('suricata tgt=L@a and ( G@role:so-sensor', self.logged('info'))
|
||||
|
||||
def test_keep_write_fails(self):
|
||||
self.ck.targets['G@role:so-sensor'] = ['a', 'c']
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
real_open = open
|
||||
|
||||
def full_disk(path, *args, **kwargs):
|
||||
if str(path).endswith('pending_a.json.tmp'):
|
||||
raise OSError(errno.ENOSPC, 'No space left on device')
|
||||
return real_open(path, *args, **kwargs)
|
||||
|
||||
with patch('builtins.open', side_effect=full_disk):
|
||||
self.assertEqual(drainer.main(), 1)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(source))
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('cannot keep pushes for a until its first highstate completes', self.logged('error'))
|
||||
self.assertIn('No space left on device', self.logged('error'))
|
||||
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_called_once()
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
def test_dispatch_fails_keep_once(self):
|
||||
self.ck.pend('a')
|
||||
source = self.source([SURICATA])
|
||||
self.run.side_effect = subprocess.CalledProcessError(1, 'salt-run', '', 'master down')
|
||||
self.assertEqual(drainer.main(), 1)
|
||||
self.assertTrue(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
|
||||
self.run.side_effect = None
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('a')['actions'], [_kept_copy('a', SURICATA)])
|
||||
self.assertEqual(len(self.run.call_args_list), 2)
|
||||
|
||||
def test_keep_no_relock(self):
|
||||
lock_fd = os.open(drainer.LOCK_FILE, os.O_CREAT | os.O_RDWR, 0o644)
|
||||
self.addCleanup(os.close, lock_fd)
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX)
|
||||
self.addCleanup(fcntl.flock, lock_fd, fcntl.LOCK_UN)
|
||||
result = []
|
||||
worker = threading.Thread(
|
||||
target=lambda: result.append(drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)),
|
||||
daemon=True)
|
||||
worker.start()
|
||||
worker.join(timeout=5)
|
||||
self.assertFalse(worker.is_alive())
|
||||
self.assertEqual(result, [True])
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_not_ready_while_pending(self):
|
||||
self.ck.pend('a')
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertEqual([c.args for c in self.ck.cache.fetch.call_args_list], [('minions/a', 'data')])
|
||||
self.assertIn('no ready intents (0 still in debounce window, 1 for nodes still in their first highstate)',
|
||||
self.logged('debug'))
|
||||
|
||||
def test_kept_drains_after_release(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertEqual(len(os.listdir(self.dispatched)), 1)
|
||||
|
||||
def test_kept_waits_for_debounce(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.ck.cache.fetch.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_master_config_error(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
with patch.object(drainer.salt.config, 'master_config', side_effect=OSError('no config')):
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('holding kept pushes', self.logged('warning'))
|
||||
|
||||
def test_kept_removed_node(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, [], self.log)
|
||||
os.unlink(os.path.join(self.keys, 'a'))
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('removing kept pushes for a: its key is no longer accepted', self.logged('info'))
|
||||
|
||||
def test_kept_no_match_dropped(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('skipping elasticsearch: no minions match tgt=L@a and ( G@role:so-searchnode )', self.logged('info'))
|
||||
|
||||
def test_kept_uncached_node_greedy(self):
|
||||
self.accept('m')
|
||||
manager = {'state': 'nginx', 'tgt': 'G@role:so-manager'}
|
||||
source = self.source([manager])
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(source))
|
||||
self.assertEqual(self.kept('m')['actions'], [_kept_copy('m', manager)])
|
||||
|
||||
self.ck.release('m')
|
||||
self.age('m')
|
||||
self.log.reset_mock()
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertFalse(os.path.exists(self.kept_path('m')))
|
||||
self.assertEqual([c.args[0] % c.args[1:] for c in self.log.info.call_args_list if 'skipping' in c.args[0]],
|
||||
['skipping nginx: no minions match tgt=L@m and ( G@role:so-manager )'])
|
||||
|
||||
self.log.reset_mock()
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.log.info.assert_not_called()
|
||||
|
||||
def test_kept_partial_match_consumed(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA), _kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(self.dispatched_actions(), [[
|
||||
{'state': 'suricata', 'tgt': '( L@a and ( G@role:so-sensor ) )' + NOT_PENDING, 'tgt_type': 'compound'}]])
|
||||
self.assertFalse(os.path.exists(self.kept_path('a')))
|
||||
|
||||
def test_kept_cache_error_held(self):
|
||||
search = {'state': 'elasticsearch', 'tgt': 'G@role:so-searchnode'}
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', search)]}, [], self.log)
|
||||
self.age('a')
|
||||
self.ck.release('a')
|
||||
self.ck.fetch_error = OSError('cache read failed')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
self.assertTrue(os.path.exists(self.kept_path('a')))
|
||||
self.assertIn('cannot read the cached grains of a', self.logged('warning'))
|
||||
self.assertNotIn('skipping', self.logged('info'))
|
||||
|
||||
def test_no_unlink_written_this_pass(self):
|
||||
drainer._keep_for_pending({'a': [_kept_copy('a', SURICATA)]}, ['audit:suricata.config'], self.log)
|
||||
self.age('a')
|
||||
first_touch = self.kept('a')['first_touch']
|
||||
self.ck.release('a')
|
||||
self.ck.pending.add('a')
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.run.assert_not_called()
|
||||
intent = self.kept('a')
|
||||
self.assertEqual(intent['actions'][0], _kept_copy('a', SURICATA))
|
||||
self.assertIn('push kept for a', self.logged('info'))
|
||||
self.assertEqual(intent['first_touch'], first_touch)
|
||||
self.assertGreater(intent['last_touch'], first_touch)
|
||||
self.assertEqual(intent['paths'], ['audit:suricata.config'])
|
||||
|
||||
def test_bad_id(self):
|
||||
self.ck.targets['*'] = ['bad\n', 'a/../b', 'c']
|
||||
self.ck.pending = {'bad\n', 'a/../b'}
|
||||
self.source([{'highstate': True, 'tgt': '*'}], name='pillar_global.json')
|
||||
for name, node in (('pending_x.json', '../etc'), ('pending_y.json', 5), ('pending_z.json', 'z\n')):
|
||||
self.write_json(self.pending, name, {'pending': node, 'last_touch': 0, 'actions': [SURICATA]})
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(os.listdir(self.pending), ['.lock'])
|
||||
self.assertEqual(self.dispatched_actions(), [[{'highstate': True, 'tgt': '( * )' + NOT_PENDING}]])
|
||||
for call in self.run.call_args_list:
|
||||
self.assertNotIn('bad', call.args[0][3])
|
||||
self.assertNotIn('a/../b', call.args[0][3])
|
||||
warning = self.logged('warning')
|
||||
self.assertIn("not keeping highstate for 'bad\\n': not a valid node id", warning)
|
||||
self.assertIn("not keeping highstate for 'a/../b'", warning)
|
||||
self.assertIn("'../etc' is not a valid node id", warning)
|
||||
self.assertIn('5 is not a valid node id', warning)
|
||||
self.assertIn("'z\\n' is not a valid node id", warning)
|
||||
self.assertNotIn('push kept', self.logged('info'))
|
||||
|
||||
|
||||
class TestMain(DrainerTestCase):
|
||||
|
||||
@@ -533,7 +1023,7 @@ class TestMain(DrainerTestCase):
|
||||
('_make_logger', {'return_value': self.log}),
|
||||
('_load_push_cfg', {'side_effect': lambda: self.cfg}),
|
||||
('_check_dispatched', {}),
|
||||
('_targeted', {'side_effect': lambda actions, log: actions}),
|
||||
('_targeted', {'side_effect': lambda actions, log: (actions, {})}),
|
||||
('_master_settling', {'return_value': False}),
|
||||
):
|
||||
patcher = patch.object(drainer, name, **kwargs)
|
||||
@@ -630,7 +1120,7 @@ class TestMain(DrainerTestCase):
|
||||
def test_untargeted_not_dispatched(self):
|
||||
path = self.intent('strelka.json', actions=[{'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
self._targeted.side_effect = None
|
||||
self._targeted.return_value = []
|
||||
self._targeted.return_value = ([], {})
|
||||
with patch.object(drainer, '_dispatch') as dispatch, \
|
||||
patch.object(drainer, '_record_dispatch') as record:
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
@@ -640,15 +1130,15 @@ class TestMain(DrainerTestCase):
|
||||
self.assertIn('no action matches a minion; nothing to dispatch', self.logged('info'))
|
||||
|
||||
def test_dispatches_only_targeted(self):
|
||||
kept = {'state': 'soc', 'tgt': '*'}
|
||||
self.intent('mixed.json', actions=[kept, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
matched = {'state': 'soc', 'tgt': '*'}
|
||||
self.intent('mixed.json', actions=[matched, {'state': 'strelka', 'tgt': 'G@role:so-sensor'}])
|
||||
self._targeted.side_effect = None
|
||||
self._targeted.return_value = [kept]
|
||||
self._targeted.return_value = ([matched], {})
|
||||
with patch.object(drainer, '_dispatch', return_value=JID) as dispatch, \
|
||||
patch.object(drainer, '_record_dispatch') as record:
|
||||
self.assertEqual(drainer.main(), 0)
|
||||
self.assertEqual(dispatch.call_args[0][0], [kept])
|
||||
self.assertEqual(record.call_args[0][1], [kept])
|
||||
self.assertEqual(dispatch.call_args[0][0], [matched])
|
||||
self.assertEqual(record.call_args[0][1], [matched])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -39,8 +39,8 @@ SETTLE_STABLE_CHECKS=3
|
||||
SETTLE_INITIAL_WAIT=${GRID_HIGHSTATE_SETTLE_INITIAL_WAIT:-45}
|
||||
|
||||
BATCH=""
|
||||
BATCH_WAIT=""
|
||||
SALT_UPGRADED=false
|
||||
IGNORED_BATCH_WAIT=false
|
||||
REASON="manual"
|
||||
|
||||
log() {
|
||||
@@ -48,14 +48,14 @@ log() {
|
||||
}
|
||||
|
||||
usage() {
|
||||
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--batch-wait <sec>] [--salt-upgraded] [--reason <text>]"
|
||||
echo "Usage: so-soup-grid-highstate [--batch <spec>] [--salt-upgraded] [--reason <text>]"
|
||||
exit 1
|
||||
}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--batch) BATCH="$2"; shift 2 ;;
|
||||
--batch-wait) BATCH_WAIT="$2"; shift 2 ;;
|
||||
--batch-wait) IGNORED_BATCH_WAIT=true; shift 2 ;;
|
||||
--salt-upgraded) SALT_UPGRADED=true; shift ;;
|
||||
--reason) REASON="$2"; shift 2 ;;
|
||||
-h|--help) usage ;;
|
||||
@@ -64,6 +64,7 @@ while [ $# -gt 0 ]; do
|
||||
done
|
||||
|
||||
mkdir -p "$(dirname "$LOG_FILE")" "$(dirname "$LOCK_FILE")"
|
||||
[ "$IGNORED_BATCH_WAIT" = "true" ] && log "--batch-wait is no longer supported and is ignored"
|
||||
|
||||
# Serialize: a second invocation (e.g. two soups, or a manual run overlapping soup's)
|
||||
# should not dispatch a competing set of batches.
|
||||
@@ -79,10 +80,6 @@ if [ -z "$BATCH" ]; then
|
||||
BATCH=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch 2>/dev/null)
|
||||
[ -z "$BATCH" ] && BATCH='10%'
|
||||
fi
|
||||
if [ -z "$BATCH_WAIT" ]; then
|
||||
BATCH_WAIT=$(salt-call --out=newline_values_only pillar.get salt:auto_apply:batch_wait 2>/dev/null)
|
||||
[ -z "$BATCH_WAIT" ] && BATCH_WAIT=15
|
||||
fi
|
||||
|
||||
MINIONID=$(salt-call --local --out=newline_values_only grains.get id 2>/dev/null)
|
||||
[ -z "$MINIONID" ] && MINIONID=$(cat /etc/salt/minion_id 2>/dev/null)
|
||||
@@ -100,7 +97,7 @@ if [ "$NUM_ACCEPTED" -le 1 ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH batch_wait=$BATCH_WAIT salt_upgraded=$SALT_UPGRADED"
|
||||
log "starting grid highstate: reason=$REASON minion=$MINIONID accepted=$NUM_ACCEPTED batch=$BATCH salt_upgraded=$SALT_UPGRADED"
|
||||
|
||||
# Count minions currently responsive on the bus (includes this manager).
|
||||
count_up() {
|
||||
@@ -171,7 +168,7 @@ if [ "$SALT_UPGRADED" = "true" ]; then
|
||||
PRE_UP=$(count_up); PRE_UP=${PRE_UP:-1}
|
||||
log "pre-upgrade reachable minions (incl. this manager): $PRE_UP"
|
||||
dispatch "salt-upgrade pass (all remote minions)" \
|
||||
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}]" \
|
||||
"[{\"highstate\": true, \"tgt\": \"not $MINIONID\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}]" \
|
||||
true
|
||||
log "waiting for minions to reconnect on the new salt version"
|
||||
wait_for_settle "$PRE_UP"
|
||||
@@ -202,7 +199,7 @@ for tgt in "${TIER_TGTS[@]}"; do
|
||||
n=$(tier_count "$tgt"); n=${n:-0}
|
||||
if [ "$n" -ge 1 ]; then
|
||||
[ -n "$actions" ] && actions="$actions, "
|
||||
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\", \"batch_wait\": $BATCH_WAIT}"
|
||||
actions="$actions{\"highstate\": true, \"tgt\": \"$tgt\", \"tgt_type\": \"compound\", \"batch\": \"$BATCH\"}"
|
||||
log "tier matched $n minion(s): $tgt"
|
||||
else
|
||||
log "tier matched 0 minions, skipping: $tgt"
|
||||
|
||||
@@ -399,6 +399,16 @@ function syncElastic() {
|
||||
fi
|
||||
}
|
||||
|
||||
function syncInfluxdbUser() {
|
||||
local op=$1
|
||||
local email=$2
|
||||
if ! docker ps -a --format '{{.Names}}' < /dev/null | grep -qx so-influxdb; then
|
||||
echo "Skipped InfluxDB $op for $email: the so-influxdb container does not exist, so InfluxDB was not changed." >&2
|
||||
return 0
|
||||
fi
|
||||
so-influxdb-manage "$op" "$email"
|
||||
}
|
||||
|
||||
function syncAll() {
|
||||
ensureRoleFileExists
|
||||
|
||||
@@ -594,9 +604,9 @@ case "${operation}" in
|
||||
createUser "$email" "${role:-$DEFAULT_ROLE}" "${firstName}" "${lastName}" "${note}"
|
||||
syncAll
|
||||
echo "Successfully added new user to SOC"
|
||||
echo "$password" | so-influxdb-manage useradd "$email"
|
||||
echo "$password" | syncInfluxdbUser useradd "$email"
|
||||
if [[ "$role" == "superuser" ]]; then
|
||||
echo "$password" | so-influxdb-manage userpromote "$email"
|
||||
echo "$password" | syncInfluxdbUser userpromote "$email"
|
||||
fi
|
||||
;;
|
||||
|
||||
@@ -616,7 +626,7 @@ case "${operation}" in
|
||||
syncElastic
|
||||
echo "Successfully added role to user"
|
||||
if [[ "$role" == "superuser" ]]; then
|
||||
echo "$password" | so-influxdb-manage userpromote "$email"
|
||||
echo "$password" | syncInfluxdbUser userpromote "$email"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
@@ -632,7 +642,7 @@ case "${operation}" in
|
||||
syncElastic
|
||||
echo "Successfully removed role from user"
|
||||
if [[ "$role" == "superuser" ]]; then
|
||||
echo "$password" | so-influxdb-manage userdemote "$email"
|
||||
echo "$password" | syncInfluxdbUser userdemote "$email"
|
||||
fi
|
||||
;;
|
||||
|
||||
@@ -644,7 +654,7 @@ case "${operation}" in
|
||||
updateUserPassword "$email"
|
||||
syncAll
|
||||
echo "Successfully updated user password"
|
||||
echo "$password" | so-influxdb-manage userpass "$email"
|
||||
echo "$password" | syncInfluxdbUser userpass "$email"
|
||||
;;
|
||||
|
||||
"profile")
|
||||
@@ -664,7 +674,7 @@ case "${operation}" in
|
||||
updateStatus "$email" 'active'
|
||||
syncAll
|
||||
echo "Successfully enabled user"
|
||||
so-influxdb-manage userenable "$email"
|
||||
syncInfluxdbUser userenable "$email"
|
||||
;;
|
||||
|
||||
"disable")
|
||||
@@ -675,7 +685,7 @@ case "${operation}" in
|
||||
updateStatus "$email" 'locked'
|
||||
syncAll
|
||||
echo "Successfully disabled user"
|
||||
so-influxdb-manage userdisable "$email"
|
||||
syncInfluxdbUser userdisable "$email"
|
||||
;;
|
||||
|
||||
"delete")
|
||||
@@ -686,7 +696,7 @@ case "${operation}" in
|
||||
deleteUser "$email"
|
||||
syncAll
|
||||
echo "Successfully deleted user"
|
||||
so-influxdb-manage userdel "$email"
|
||||
syncInfluxdbUser userdel "$email"
|
||||
;;
|
||||
|
||||
"sync")
|
||||
|
||||
+246
-14
@@ -361,6 +361,187 @@ check_fleet_server() {
|
||||
fi
|
||||
}
|
||||
|
||||
TELEGRAF_PILLAR=/opt/so/saltstack/local/pillar/telegraf/soc_telegraf.sls
|
||||
TELEGRAF_CREDS=/opt/so/saltstack/local/pillar/telegraf/creds.sls
|
||||
INFLUXDB_DIRS=(/nsm/influxdb /opt/so/conf/influxdb)
|
||||
|
||||
telegraf_creds_present() {
|
||||
local mid=$1
|
||||
[[ -n $(so-yaml.py get -r "$TELEGRAF_CREDS" "telegraf.postgres_creds.${mid}.user" 2>/dev/null) ]] &&
|
||||
[[ -n $(so-yaml.py get -r "$TELEGRAF_CREDS" "telegraf.postgres_creds.${mid}.pass" 2>/dev/null) ]]
|
||||
}
|
||||
|
||||
# An unreadable docker or directory state counts as present so the POSTGRES path
|
||||
# asks, or refuses on -y, rather than letting a highstate delete data unannounced.
|
||||
influxdb_container_exists() {
|
||||
local names
|
||||
names=$(docker ps -a --format '{{.Names}}' 2>/dev/null) || return 0
|
||||
grep -qx so-influxdb <<< "$names"
|
||||
}
|
||||
|
||||
influxdb_present() {
|
||||
local dir contents
|
||||
influxdb_container_exists && return 0
|
||||
for dir in "${INFLUXDB_DIRS[@]}"; do
|
||||
[[ -e $dir ]] || continue
|
||||
contents=$(ls -A "$dir" 2>/dev/null) || return 0
|
||||
[[ -n $contents ]] && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
set_influxdb_size() {
|
||||
local dir
|
||||
local -a existing=()
|
||||
for dir in "${INFLUXDB_DIRS[@]}"; do
|
||||
[[ -e $dir ]] && existing+=("$dir")
|
||||
done
|
||||
INFLUXDB_SIZE=0
|
||||
(( ${#existing[@]} == 0 )) && return 0
|
||||
if ! INFLUXDB_SIZE=$(set -o pipefail; du -sch "${existing[@]}" 2>/dev/null | tail -n 1 | cut -f1) || [[ -z $INFLUXDB_SIZE ]]; then
|
||||
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to measure the size of InfluxDB's data in ${INFLUXDB_DIRS[*]}.")
|
||||
INFLUXDB_SIZE="an unknown amount"
|
||||
fi
|
||||
}
|
||||
|
||||
influxdb_switch_prompt() {
|
||||
local output answer mid mids
|
||||
local -a missing=()
|
||||
|
||||
# read the pillar files rather than salt, as influxdb_switch_apply must while salt-master is stopped
|
||||
output=$(so-yaml.py get -r "$TELEGRAF_PILLAR" telegraf.output 2>/dev/null) ||
|
||||
output=$(so-yaml.py get -r "$DEFAULT_SALT_DIR/salt/telegraf/defaults.yaml" telegraf.output 2>/dev/null) ||
|
||||
output=INFLUXDB
|
||||
output=${output^^}
|
||||
|
||||
if [[ "$output" == "POSTGRES" ]]; then
|
||||
if ! telegraf_creds_present "$MINIONID"; then
|
||||
echo ""
|
||||
echo "The metrics output is POSTGRES, but this manager has no Telegraf Postgres credentials."
|
||||
echo "The upgrade cannot complete without them. soup has not changed anything."
|
||||
echo ""
|
||||
echo "Add them, then run soup again:"
|
||||
echo " sudo so-telegraf-cred add $MINIONID"
|
||||
echo ""
|
||||
exit 0
|
||||
fi
|
||||
influxdb_present || return 0
|
||||
set_influxdb_size
|
||||
|
||||
if [[ -n $UNATTENDED ]]; then
|
||||
if [[ -n $DELETES_ACCEPTED ]]; then
|
||||
INFLUX_DELETE_ACCEPTED=1
|
||||
echo "InfluxDB ($INFLUXDB_SIZE) is still present on this POSTGRES grid; its deletion was accepted with --deletes-accepted."
|
||||
return 0
|
||||
fi
|
||||
echo ""
|
||||
echo "The metrics output is POSTGRES, so this upgrade would remove InfluxDB and delete"
|
||||
echo "all of its data ($INFLUXDB_SIZE). The deletion cannot be undone. soup has not changed anything."
|
||||
echo ""
|
||||
echo "To continue, choose one of the following:"
|
||||
echo " - Accept the deletion: sudo soup -y --deletes-accepted"
|
||||
echo " - Confirm the deletion at the prompt: sudo soup"
|
||||
echo " - Save the data if needed and remove InfluxDB by hand, then run sudo soup -y again:"
|
||||
# the installed release's scheduled highstate would otherwise start InfluxDB again before soup runs
|
||||
echo " sudo so-yaml.py replace /opt/so/saltstack/local/pillar/minions/$MINIONID.sls influxdb.enabled false"
|
||||
echo " sudo docker rm -f so-influxdb"
|
||||
echo " sudo find ${INFLUXDB_DIRS[*]} -mindepth 1 -delete"
|
||||
echo ""
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "The metrics output is POSTGRES, but InfluxDB is still on this manager with $INFLUXDB_SIZE"
|
||||
echo "of old data. This upgrade removes InfluxDB and deletes all of that data, and the"
|
||||
echo "deletion cannot be undone."
|
||||
echo "Exit now if you want to save or export the data first, then run soup again."
|
||||
echo ""
|
||||
read -rp "Press C to continue with the upgrade or E to exit: " answer
|
||||
if [[ "$answer" != [cC] ]]; then
|
||||
echo "Exiting soup"
|
||||
exit 0
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
# releases before 3.1.0 have no Telegraf credentials; influxdb_switch_apply creates them on a switch
|
||||
[[ $INSTALLEDVERSION =~ ^(2\.|3\.0\.) ]] && INFLUX_CREATE_CREDS=1
|
||||
|
||||
if ! mids=$(salt-key --out=json --list=accepted 2>/dev/null | jq -r '.minions[]?' 2>/dev/null) || [[ -z $mids ]]; then
|
||||
missing=("(unable to list accepted minions)")
|
||||
else
|
||||
INFLUX_SWITCH_MINIONS=$mids
|
||||
if [[ -z $INFLUX_CREATE_CREDS ]]; then
|
||||
for mid in $mids; do
|
||||
telegraf_creds_present "$mid" || missing+=("$mid")
|
||||
done
|
||||
fi
|
||||
fi
|
||||
if (( ${#missing[@]} > 0 )); then
|
||||
FINAL_MESSAGE_QUEUE+=("NOTE: soup did not offer to move metrics from InfluxDB to Postgres because these nodes have no Telegraf Postgres credentials: ${missing[*]}")
|
||||
FINAL_MESSAGE_QUEUE+=(" - Add them with sudo so-telegraf-cred add <minion_id>; the next soup will offer the switch.")
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [[ -n $UNATTENDED ]]; then
|
||||
FINAL_MESSAGE_QUEUE+=("NOTE: InfluxDB will be removed in a future Security Onion release, and this grid still stores metrics in it (telegraf.output is $output).")
|
||||
FINAL_MESSAGE_QUEUE+=(" - Setting telegraf.output to POSTGRES in Configuration switches the grid to Postgres and deletes InfluxDB and all its data.")
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "InfluxDB will be removed in a future Security Onion release. This grid stores its"
|
||||
echo "metrics in InfluxDB (telegraf.output is $output)."
|
||||
echo ""
|
||||
echo "Every grid must move its metrics to Postgres before that release. Existing InfluxDB"
|
||||
echo "metrics are not migrated."
|
||||
echo ""
|
||||
echo "Switching now points Telegraf at Postgres and removes InfluxDB, deleting all of its"
|
||||
echo "data, during this upgrade. This cannot be undone, and switching back afterwards is"
|
||||
echo "not supported. InfluxDB's alarm checks are deleted with it; the Postgres recommended"
|
||||
echo "alarms can be added from the Grid page."
|
||||
echo ""
|
||||
read -rp "Switch metrics to Postgres now? [y/N]: " answer
|
||||
if [[ "$answer" == [yY] ]]; then
|
||||
INFLUX_SWITCH_ACCEPTED=1
|
||||
else
|
||||
echo "Keeping telegraf.output set to $output."
|
||||
fi
|
||||
}
|
||||
|
||||
influxdb_switch_apply() {
|
||||
local mid
|
||||
local -a failed=()
|
||||
[[ -n $INFLUX_SWITCH_ACCEPTED ]] || return 0
|
||||
if [[ -n $INFLUX_CREATE_CREDS ]]; then
|
||||
echo "Creating Telegraf Postgres credentials for accepted minions."
|
||||
for mid in $INFLUX_SWITCH_MINIONS; do
|
||||
bash "$UPDATE_DIR/salt/manager/tools/sbin/so-telegraf-cred" add "$mid" || failed+=("$mid")
|
||||
done
|
||||
if (( ${#failed[@]} > 0 )); then
|
||||
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to create Telegraf Postgres credentials for these nodes, so the grid stays on its current metrics output: ${failed[*]}")
|
||||
FINAL_MESSAGE_QUEUE+=(" - Once their credentials exist, set telegraf.output to POSTGRES in Configuration to switch.")
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
echo "Setting telegraf.output to POSTGRES in $TELEGRAF_PILLAR."
|
||||
if ! { mkdir -p "$(dirname "$TELEGRAF_PILLAR")" && touch "$TELEGRAF_PILLAR" &&
|
||||
so-yaml.py replace "$TELEGRAF_PILLAR" telegraf.output POSTGRES; }; then
|
||||
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to set telegraf.output to POSTGRES in $TELEGRAF_PILLAR, so metrics stay in InfluxDB. Set it in Configuration to switch.")
|
||||
return 0
|
||||
fi
|
||||
chown socore:socore "$TELEGRAF_PILLAR" 2>/dev/null || true
|
||||
}
|
||||
|
||||
influxdb_retire_check() {
|
||||
[[ "$(so_telegraf_output 2>/dev/null)" == "POSTGRES" ]] || return 0
|
||||
if influxdb_container_exists; then
|
||||
FINAL_MESSAGE_QUEUE+=("NOTE: InfluxDB is still on this manager. The next highstate tries again to remove it and delete all its data.")
|
||||
elif [[ -n $INFLUX_DELETE_ACCEPTED ]]; then
|
||||
FINAL_MESSAGE_QUEUE+=("NOTE: This upgrade removed InfluxDB and deleted all its data, as accepted with --deletes-accepted.")
|
||||
fi
|
||||
}
|
||||
|
||||
check_saltmaster_status() {
|
||||
set +e
|
||||
echo "Waiting on the Salt Master service to be ready."
|
||||
@@ -1108,9 +1289,6 @@ post_to_3.3.0() {
|
||||
|
||||
### 3.4.0 Scripts ###
|
||||
up_to_3.4.0() {
|
||||
# download 9.4.8 elastic agent packages
|
||||
determine_elastic_agent_upgrade
|
||||
|
||||
set_soauth_range
|
||||
|
||||
echo "Removing so-kratos, so-hydra and so-soc so they are recreated on the soauth network."
|
||||
@@ -1188,10 +1366,6 @@ valid_soauth_range() {
|
||||
}
|
||||
|
||||
post_to_3.4.0() {
|
||||
# Generate 9.4.8 elastic agent installers
|
||||
echo "Regenerating Elastic Agent Installers"
|
||||
/sbin/so-elastic-agent-gen-installers
|
||||
|
||||
for idx in "metrics-logstash.node-default" "metrics-logstash.stack_monitoring.node-default"; do
|
||||
rollover_index "$idx"
|
||||
done
|
||||
@@ -1221,7 +1395,11 @@ add_detection_runtime_fields() {
|
||||
|
||||
### 3.5.0 Scripts ###
|
||||
up_to_3.5.0() {
|
||||
# download 9.4.10 elastic agent packages
|
||||
determine_elastic_agent_upgrade
|
||||
|
||||
remove_localrules_portgroup
|
||||
remove_auto_apply_batch_wait
|
||||
|
||||
INSTALLEDVERSION=3.5.0
|
||||
}
|
||||
@@ -1238,8 +1416,44 @@ remove_localrules_portgroup() {
|
||||
done
|
||||
}
|
||||
|
||||
remove_auto_apply_batch_wait() {
|
||||
local pillar_file
|
||||
|
||||
for pillar_file in /opt/so/saltstack/local/pillar/salt/{soc,adv}_salt.sls; do
|
||||
grep -qs batch_wait "$pillar_file" || continue
|
||||
so-yaml.py get -r "$pillar_file" salt.auto_apply.batch_wait >/dev/null 2>&1 || continue
|
||||
echo "Removing salt.auto_apply.batch_wait from $pillar_file."
|
||||
if ! so-yaml.py remove "$pillar_file" salt.auto_apply.batch_wait; then
|
||||
FINAL_MESSAGE_QUEUE+=("WARNING: Unable to remove the unused salt.auto_apply.batch_wait setting from $pillar_file. It has no effect and can be removed manually:")
|
||||
FINAL_MESSAGE_QUEUE+=(" - sudo so-yaml.py remove $pillar_file salt.auto_apply.batch_wait")
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
check_soc_postgres_upgrade() {
|
||||
local image
|
||||
[[ "$(so_telegraf_output 2>/dev/null)" != "INFLUXDB" ]] || return 0
|
||||
telegraf_creds_present "$MINIONID" || return 0
|
||||
image=$(docker inspect --format '{{.Config.Image}}' so-soc 2>/dev/null) || image=
|
||||
if [[ "$image" != *":$NEWVERSION" ]]; then
|
||||
echo ""
|
||||
echo "WARNING: SOC was not upgraded to $NEWVERSION because the Telegraf Postgres role setup failed. Fix Postgres, then run a highstate:"
|
||||
echo " - sudo salt-call state.highstate"
|
||||
fi
|
||||
}
|
||||
|
||||
post_to_3.5.0() {
|
||||
# Generate 9.4.10 elastic agent installers
|
||||
echo "Regenerating Elastic Agent Installers"
|
||||
/sbin/so-elastic-agent-gen-installers
|
||||
|
||||
telegraf_repair
|
||||
# ensure manager has new version of socloud.conf
|
||||
if [[ $SALT_CLOUD_CONFIGURED == true ]]; then
|
||||
salt-call state.apply salt.cloud.config concurrent=True || FINAL_MESSAGE_QUEUE+=("WARNING: Unable to update the salt-cloud profile. Run: sudo salt-call state.apply salt.cloud.config")
|
||||
fi
|
||||
|
||||
rollover_index "logs-detections.alerts-so"
|
||||
|
||||
set_postversion 3.5.0
|
||||
}
|
||||
@@ -1517,10 +1731,11 @@ verify_es_version_compatibility() {
|
||||
["8.18.4"]="8.18.6 8.18.8 9.0.8"
|
||||
["8.18.6"]="8.18.8 9.0.8"
|
||||
["8.18.8"]="9.0.8"
|
||||
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8"
|
||||
["9.3.3"]="9.3.7 9.4.5 9.4.8"
|
||||
["9.3.7"]="9.4.5 9.4.8"
|
||||
["9.4.5"]="9.4.8"
|
||||
["9.0.8"]="9.3.3 9.3.7 9.4.5 9.4.8 9.4.10"
|
||||
["9.3.3"]="9.3.7 9.4.5 9.4.8 9.4.10"
|
||||
["9.3.7"]="9.4.5 9.4.8 9.4.10"
|
||||
["9.4.5"]="9.4.8 9.4.10"
|
||||
["9.4.8"]="9.4.10"
|
||||
)
|
||||
|
||||
# Elasticsearch MUST upgrade through these versions
|
||||
@@ -2142,6 +2357,10 @@ main() {
|
||||
check_cluster_health
|
||||
check_fleet_server
|
||||
|
||||
if [[ "$is_hotfix" != "true" ]]; then
|
||||
influxdb_switch_prompt
|
||||
fi
|
||||
|
||||
echo "Checking for Salt Master and Minion updates."
|
||||
upgrade_check_salt
|
||||
set -e
|
||||
@@ -2231,6 +2450,7 @@ main() {
|
||||
echo "Running so-config-backup script."
|
||||
/sbin/so-config-backup
|
||||
fi
|
||||
influxdb_switch_apply
|
||||
|
||||
echo ""
|
||||
echo "Copying new Security Onion code from $UPDATE_DIR to $DEFAULT_SALT_DIR."
|
||||
@@ -2308,7 +2528,7 @@ main() {
|
||||
fi
|
||||
set -e
|
||||
|
||||
highstate
|
||||
highstate || { rc=$?; check_soc_postgres_upgrade; exit $rc; }
|
||||
check_saltmaster_status
|
||||
postupgrade_changes
|
||||
[[ $is_airgap -eq 0 ]] && unmount_update
|
||||
@@ -2382,6 +2602,8 @@ For more information, please see $DOC_BASE_URL/soup#distributed-deployments.
|
||||
EOF
|
||||
|
||||
fi
|
||||
|
||||
influxdb_retire_check
|
||||
fi
|
||||
|
||||
if [ "$NOTIFYCUSTOMELASTICCONFIG" = true ] ; then
|
||||
@@ -2409,12 +2631,22 @@ fi
|
||||
echo "### soup has been served at $(date) ###"
|
||||
}
|
||||
|
||||
soup_args=()
|
||||
for arg in "$@"; do
|
||||
if [[ "$arg" == "--deletes-accepted" ]]; then
|
||||
DELETES_ACCEPTED=true
|
||||
else
|
||||
soup_args+=("$arg")
|
||||
fi
|
||||
done
|
||||
set -- "${soup_args[@]}"
|
||||
|
||||
while getopts ":b:f:y" opt; do
|
||||
case ${opt} in
|
||||
b )
|
||||
BATCHSIZE="$OPTARG"
|
||||
# Accept either a plain count (e.g. 5) or a percentage (e.g. 25%); passed through
|
||||
# to so-soup-grid-highstate --batch, which salt's batch/batch_wait accepts in both forms.
|
||||
# to so-soup-grid-highstate --batch, which salt's batch accepts in both forms.
|
||||
if ! [[ "$BATCHSIZE" =~ ^[1-9][0-9]*%?$ ]]; then
|
||||
echo "Batch size must be a number greater than 0, optionally with a trailing % (e.g. 5 or 25%)."
|
||||
exit 1
|
||||
@@ -2432,7 +2664,7 @@ while getopts ":b:f:y" opt; do
|
||||
ISOLOC="$OPTARG"
|
||||
;;
|
||||
\? )
|
||||
echo "Usage: soup [-b] [-y] [-f <iso location>]"
|
||||
echo "Usage: soup [-b] [-y] [--deletes-accepted] [-f <iso location>]"
|
||||
exit 1
|
||||
;;
|
||||
: )
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
{%- from 'vars/globals.map.jinja' import GLOBALS %}
|
||||
{%- from 'docker/docker.map.jinja' import DOCKERMERGED %}
|
||||
{%- from 'nginx/map.jinja' import NGINXMERGED %}
|
||||
{%- from 'telegraf/map.jinja' import INFLUX_RETIRED %}
|
||||
{%- set role = grains.id.split('_') | last %}
|
||||
{%- set influxpass = salt['pillar.get']('secrets:influx_pass') %}
|
||||
{%- set influxauth = ('so:' + influxpass) | base64_encode %}
|
||||
{%- set all_names = [GLOBALS.hostname, GLOBALS.url_base] + NGINXMERGED.ssl.alt_names %}
|
||||
{%- set full_server_name = all_names | unique | join(' ') %}
|
||||
|
||||
@@ -310,6 +309,7 @@ http {
|
||||
autoindex_localtime on;
|
||||
}
|
||||
|
||||
{%- if not INFLUX_RETIRED %}
|
||||
location /influxdb/ {
|
||||
auth_request /auth/sessions/whoami;
|
||||
rewrite /influxdb/api/(.*) /api/$1 break;
|
||||
@@ -323,6 +323,7 @@ http {
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cookie_path /api/ /influxdb/api/;
|
||||
}
|
||||
{%- endif %}
|
||||
|
||||
location /app/dashboards/ {
|
||||
auth_request /auth/sessions/whoami;
|
||||
|
||||
+29
-17
@@ -1,16 +1,42 @@
|
||||
{% from 'salt/auto_apply.map.jinja' import AUTOAPPLY %}
|
||||
{% set actions = salt['pillar.get']('actions', []) %}
|
||||
{% set BATCH = AUTOAPPLY.batch %}
|
||||
{% set BATCH_WAIT = AUTOAPPLY.batch_wait %}
|
||||
{# Must exceed gather_job_timeout (10s): at the 5s default, one saltutil.find_job reply slower than that abandons
|
||||
a queued state run, and a master slow to accept the publish gets it a second time. #}
|
||||
{% set STATE_TIMEOUT = 60 %}
|
||||
|
||||
{# queue must be a top-level salt.state arg (kwarg is ignored); an int is max_queue and still fails on conflict #}
|
||||
{# refresh_pillar doubles as the reachability check: minions take up to ~22s to rejoin a restarted master's
|
||||
publisher, and a job published before then reaches nobody. Each failed attempt takes ~15s to time out. #}
|
||||
{# The first step of each action checks that its target is reachable: minions take up to ~22s to rejoin a
|
||||
restarted master's publisher, and each failed attempt takes ~15s to time out. salt.function does not count
|
||||
non-responders as failures, so the check passes as soon as any one minion answers. The drainer's 45s hold
|
||||
covers a restart before dispatch; the retry covers a restart during a running orchestration. expect_minions
|
||||
is not set on purpose: one offline node would then block the push to every node.
|
||||
A highstate checks with test.ping: it renders pillar itself, and the global and salt pillar actions push a
|
||||
highstate to '*', where an unbatched refresh_pillar would make every minion render pillar at once. A single
|
||||
state needs fresh pillar, so it checks with refresh_pillar. #}
|
||||
|
||||
{% for action in actions %}
|
||||
{% if action.get('highstate') %}
|
||||
ping_{{ loop.index }}:
|
||||
salt.function:
|
||||
- name: test.ping
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- retry:
|
||||
attempts: 3
|
||||
interval: 10
|
||||
|
||||
apply_highstate_{{ loop.index }}:
|
||||
salt.state:
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- highstate: True
|
||||
- batch: {{ action.get('batch', BATCH) }}
|
||||
- queue: True
|
||||
- timeout: {{ STATE_TIMEOUT }}
|
||||
- require:
|
||||
- salt: ping_{{ loop.index }}
|
||||
{% else %}
|
||||
refresh_pillar_{{ loop.index }}:
|
||||
salt.function:
|
||||
- name: saltutil.refresh_pillar
|
||||
@@ -20,19 +46,6 @@ refresh_pillar_{{ loop.index }}:
|
||||
attempts: 3
|
||||
interval: 10
|
||||
|
||||
{% if action.get('highstate') %}
|
||||
apply_highstate_{{ loop.index }}:
|
||||
salt.state:
|
||||
- tgt: '{{ action.tgt }}'
|
||||
- tgt_type: {{ action.get('tgt_type', 'compound') }}
|
||||
- highstate: True
|
||||
- batch: {{ action.get('batch', BATCH) }}
|
||||
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
|
||||
- queue: True
|
||||
- timeout: {{ STATE_TIMEOUT }}
|
||||
- require:
|
||||
- salt: refresh_pillar_{{ loop.index }}
|
||||
{% else %}
|
||||
apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
|
||||
salt.state:
|
||||
- tgt: '{{ action.tgt }}'
|
||||
@@ -40,7 +53,6 @@ apply_{{ action.state | replace('.', '_') }}_{{ loop.index }}:
|
||||
- sls:
|
||||
- {{ action.state }}
|
||||
- batch: {{ action.get('batch', BATCH) }}
|
||||
- batch_wait: {{ action.get('batch_wait', BATCH_WAIT) }}
|
||||
- queue: True
|
||||
- timeout: {{ STATE_TIMEOUT }}
|
||||
- require:
|
||||
|
||||
@@ -6,16 +6,12 @@
|
||||
{% from 'allowed_states.map.jinja' import allowed_states %}
|
||||
{% if sls.split('.')[0] in allowed_states %}
|
||||
{% from 'vars/globals.map.jinja' import GLOBALS %}
|
||||
{% from 'telegraf/map.jinja' import TELEGRAFMERGED %}
|
||||
|
||||
{# postgres.enabled declares the so-postgres container and postgres_wait_ready
|
||||
that the requires below reference. Salt de-duplicates the circular include. #}
|
||||
include:
|
||||
- postgres.enabled
|
||||
|
||||
{% set TG_OUT = TELEGRAFMERGED.output | upper %}
|
||||
{% if TG_OUT in ['POSTGRES', 'BOTH'] %}
|
||||
|
||||
# Ensure the shared Telegraf database exists. init-db.sh only runs on a
|
||||
# fresh data dir, so hosts upgraded onto an existing /nsm/postgres volume
|
||||
# would otherwise never get so_telegraf.
|
||||
@@ -70,8 +66,6 @@ postgres_telegraf_retention_reconcile:
|
||||
- cmd: postgres_telegraf_group_role
|
||||
- file: postgres_sbin
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% else %}
|
||||
|
||||
{{sls}}_state_not_allowed:
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
#
|
||||
# One pillar directory can map to multiple (state, tgt) actions.
|
||||
# tgt is a raw salt compound expression. tgt_type is always "compound".
|
||||
# Per-action `batch` / `batch_wait` override the orch defaults (10% / 15s).
|
||||
# so-push-drainer keeps pushes for nodes still in their first highstate and applies them after it completes.
|
||||
# Per-action `batch` overrides the orch default (10%).
|
||||
# An action with `highstate: True` triggers state.highstate instead of
|
||||
# state.apply -- see salt/orch/push_batch.sls.
|
||||
#
|
||||
@@ -98,7 +99,7 @@ elasticfleet:
|
||||
# global: fanout to a fleetwide highstate. The global pillar (soc_global.sls)
|
||||
# carries cross-cutting settings (pipeline, url_base, imagerepo, mdengine, ...)
|
||||
# that are consumed by virtually every state, so a targeted re-apply isn't
|
||||
# meaningful. The drainer's batch/batch_wait throttling controls blast radius.
|
||||
# meaningful. The drainer's batch throttling controls blast radius.
|
||||
global:
|
||||
- highstate: True
|
||||
tgt: '*'
|
||||
@@ -231,10 +232,20 @@ suricata:
|
||||
- state: suricata
|
||||
tgt: 'G@role:so-eval or G@role:so-heavynode or G@role:so-import or G@role:so-sensor or G@role:so-standalone'
|
||||
|
||||
# telegraf: universal.
|
||||
# telegraf: universal, then the manager states that follow the output setting.
|
||||
# They run after telegraf so InfluxDB is retired and SOC switches metrics
|
||||
# modules only once the nodes already point at the new output.
|
||||
telegraf:
|
||||
- state: telegraf
|
||||
tgt: '*'
|
||||
- state: influxdb
|
||||
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
|
||||
- state: nginx
|
||||
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
|
||||
- state: firewall
|
||||
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
|
||||
- state: soc
|
||||
tgt: 'G@role:so-eval or G@role:so-import or G@role:so-manager or G@role:so-managerhype or G@role:so-managersearch or G@role:so-standalone'
|
||||
|
||||
# versionlock: universal (top-of-file '*' branch in salt/top.sls).
|
||||
versionlock:
|
||||
|
||||
@@ -117,7 +117,7 @@ def _app_from_setting(setting_id):
|
||||
|
||||
def _node_actions(entry, node_id):
|
||||
# Copy the app's mapped actions but narrow each one to the single node.
|
||||
# Preserves the state/highstate selection and any batch/batch_wait overrides.
|
||||
# Preserves the state/highstate selection and any batch override.
|
||||
# The app's own target is kept so the state is not applied to a node that does not
|
||||
# run the app (e.g. an elasticsearch setting saved for a sensor fails to render there).
|
||||
actions = []
|
||||
|
||||
@@ -18,7 +18,7 @@ include:
|
||||
# Install the registry container
|
||||
so-dockerregistry:
|
||||
docker_container.running:
|
||||
- image: ghcr.io/security-onion-solutions/registry:3.1.1
|
||||
- image: ghcr.io/security-onion-solutions/registry:3.1.2
|
||||
# Intentionally `always`-- registry is critical and must
|
||||
# come back up even if it was manually stopped.
|
||||
- restart_policy: always
|
||||
|
||||
@@ -28,6 +28,8 @@ sool9_{{host}}:
|
||||
grains:
|
||||
hypervisor_host: {{host ~ "_" ~ role}}
|
||||
sosmodel: HVGUEST
|
||||
# so-push-drainer leaves the VM alone until its first highstate removes this
|
||||
first_highstate_pending: True
|
||||
preflight_cmds:
|
||||
- |
|
||||
{%- set hostnames = [MANAGERHOSTNAME] %}
|
||||
|
||||
@@ -4,6 +4,5 @@ salt:
|
||||
debounce_seconds: 30
|
||||
drain_interval: 15
|
||||
batch: '10%'
|
||||
batch_wait: 15
|
||||
schedule:
|
||||
highstate_interval_minutes: 120
|
||||
@@ -2,3 +2,12 @@ lasthighstate:
|
||||
file.touch:
|
||||
- name: /opt/so/log/salt/lasthighstate
|
||||
- order: 9001
|
||||
|
||||
# Set by setup and the hypervisor VM cloud profile; so-push-drainer does not target a node that still has it.
|
||||
# Auto-ordered states start at 10000, and a negative order runs after all of them, just before the
|
||||
# order: last states, so the grain goes only once the highstate has run every state. The touch above stays
|
||||
# at 9001 because so-status and so-salt-minion-check read it.
|
||||
first_highstate_pending:
|
||||
grains.absent:
|
||||
- destructive: True
|
||||
- order: -1
|
||||
+5
-11
@@ -3,38 +3,32 @@ salt:
|
||||
enabled:
|
||||
description: Master kill-switch for the active push feature. When disabled, rule and pillar changes are picked up at the next scheduled highstate instead of being pushed immediately.
|
||||
forcedType: bool
|
||||
helpLink: push
|
||||
helpLink: salt
|
||||
global: True
|
||||
debounce_seconds:
|
||||
description: Trailing-edge debounce window in seconds. A push intent must be quiet for this long before the drainer dispatches. Rapid bursts of edits within this window coalesce into one dispatch.
|
||||
forcedType: int
|
||||
helpLink: push
|
||||
helpLink: salt
|
||||
global: True
|
||||
advanced: True
|
||||
drain_interval:
|
||||
description: How often the push drainer checks for ready intents, in seconds. Small values lower dispatch latency at the cost of more background work on the manager.
|
||||
forcedType: int
|
||||
helpLink: push
|
||||
helpLink: salt
|
||||
global: True
|
||||
advanced: True
|
||||
batch:
|
||||
description: "Host batch size for push orchestrations. A number (e.g. '10') or a percentage (e.g. '25%'). Limits how many minions run the push state at once so large fleets don't thundering-herd."
|
||||
helpLink: push
|
||||
helpLink: salt
|
||||
global: True
|
||||
advanced: True
|
||||
regex: '^([0-9]+%?)$'
|
||||
regexFailureMessage: Enter a whole number or a whole-number percentage (e.g. 10 or 25%).
|
||||
batch_wait:
|
||||
description: Seconds to wait between host batches in a push orchestration. Gives the fleet time to breathe between waves.
|
||||
forcedType: int
|
||||
helpLink: push
|
||||
global: True
|
||||
advanced: True
|
||||
schedule:
|
||||
highstate_interval_minutes:
|
||||
description: How often every minion in the grid runs a scheduled state.highstate, in minutes. Minimum 15 minutes. Lower values keep minions closer in sync at the cost of more load; higher values reduce load but increase worst-case latency for non-pushed changes. If Auto Apply is disabled, set this to the 15-minute minimum so changes are still picked up promptly. The salt-minion health check restarts a minion if its last state apply is older than this value plus one hour.
|
||||
forcedType: int
|
||||
helpLink: push
|
||||
helpLink: salt
|
||||
global: True
|
||||
advanced: True
|
||||
regex: '^(1[5-9]|[2-9][0-9]|[1-9][0-9]{2,4})$'
|
||||
|
||||
@@ -5,9 +5,14 @@
|
||||
|
||||
{% from 'allowed_states.map.jinja' import allowed_states %}
|
||||
{% if sls.split('.')[0] in allowed_states %}
|
||||
{% from 'soc/merged.map.jinja' import SOCMERGED %}
|
||||
{% set use_pg_metrics = 'postgresmetrics' in SOCMERGED.config.server.modules %}
|
||||
|
||||
include:
|
||||
- manager.sync_es_users
|
||||
{% if use_pg_metrics %}
|
||||
- postgres.telegraf_users
|
||||
{% endif %}
|
||||
|
||||
sigmarepodir:
|
||||
file.directory:
|
||||
@@ -77,6 +82,10 @@ socconfig:
|
||||
- mode: 600
|
||||
- template: jinja
|
||||
- show_changes: False
|
||||
{% if use_pg_metrics %}
|
||||
- require:
|
||||
- sls: postgres.telegraf_users
|
||||
{% endif %}
|
||||
|
||||
socmotd:
|
||||
file.managed:
|
||||
|
||||
@@ -1638,6 +1638,12 @@ soc:
|
||||
- "user.effective.name"
|
||||
- "weird.name"
|
||||
- "tags"
|
||||
queryNotifications:
|
||||
defaultLimit: 10
|
||||
maxLimit: 50
|
||||
summaryMaxLength: 1000
|
||||
fieldValueMaxLength: 200
|
||||
maxEntries: 25
|
||||
onionconfig:
|
||||
saltstackDir: /opt/so/saltstack
|
||||
bypassEnabled: false
|
||||
@@ -2551,6 +2557,61 @@ soc:
|
||||
grid:
|
||||
maxUploadSize: 26214400
|
||||
staleMetricsMs: 120000
|
||||
recommendedAlarms:
|
||||
- name: Root Disk Usage
|
||||
metric: disk
|
||||
metricKey: disk_used_root
|
||||
operator: gt
|
||||
threshold: '95'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: NSM Disk Usage
|
||||
metric: disk
|
||||
metricKey: disk_used_nsm
|
||||
operator: gt
|
||||
threshold: '95'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Low PCAP Retention
|
||||
metric: pcap_retention
|
||||
metricKey: pcap_retention
|
||||
operator: lt
|
||||
threshold: '1'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Suricata Packet Loss
|
||||
metric: loss
|
||||
metricKey: suricata_loss
|
||||
operator: gt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Zeek Packet Loss
|
||||
metric: loss
|
||||
metricKey: zeek_loss
|
||||
operator: gt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
- name: Low Monitor Traffic
|
||||
metric: net
|
||||
metricKey: traffic_mon_in
|
||||
operator: lt
|
||||
threshold: '5'
|
||||
durationSeconds: 300
|
||||
severity: critical
|
||||
clearedSeverity: info
|
||||
enabled: true
|
||||
cases:
|
||||
advanced: false
|
||||
aggregationActionsEnabled: false
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
{% from 'soc/defaults.map.jinja' import SOCDEFAULTS with context %}
|
||||
{% from 'elasticsearch/config.map.jinja' import ELASTICSEARCH_NODES %}
|
||||
{% from 'manager/map.jinja' import MANAGERMERGED %}
|
||||
{% from 'telegraf/map.jinja' import TELEGRAFMERGED %}
|
||||
{% from 'telegraf/map.jinja' import PG_METRICS_READY %}
|
||||
{% from 'elastalert/map.jinja' import ELASTALERTMERGED %}
|
||||
{%- set PG_ENTRY = salt['pillar.get']('telegraf:postgres_creds:' ~ grains.id, {}) %}
|
||||
{%- set PG_USER = PG_ENTRY.get('user', '') %}
|
||||
@@ -129,7 +129,7 @@
|
||||
{% endif %}
|
||||
|
||||
{# Define the postgresmetrics module if telegraf is setup to only use Postgres #}
|
||||
{% if TELEGRAFMERGED.output != 'INFLUXDB' and PG_USER and PG_PASS %}
|
||||
{% if PG_METRICS_READY %}
|
||||
{% do SOCMERGED.config.server.modules.update({
|
||||
'postgresmetrics': {
|
||||
'database': 'so_telegraf',
|
||||
|
||||
@@ -1112,6 +1112,32 @@ soc:
|
||||
description: A whitelist of fields to return when OnionAI uses the query_events tool. All other fields are removed. One field per line.
|
||||
global: True
|
||||
multiline: True
|
||||
queryNotifications:
|
||||
defaultLimit:
|
||||
description: Number of notifications Onion AI reads with the query_notifications tool when it doesn't ask for a specific number. Must be greater than 0. Values above maxLimit use maxLimit.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
maxLimit:
|
||||
description: Maximum number of notifications Onion AI may read with one query_notifications call. Must be greater than 0. Higher values put more notification text into the model's context.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
summaryMaxLength:
|
||||
description: Maximum number of characters of each notification summary that query_notifications returns to Onion AI. Must be greater than 0. Longer summaries are shortened.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
fieldValueMaxLength:
|
||||
description: Maximum number of characters of each notification field value that query_notifications returns to Onion AI. Must be greater than 0. Longer values are shortened. Link values are never shortened.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
maxEntries:
|
||||
description: Maximum number of fields, of links, and of attachment names, each counted separately, per notification that query_notifications returns to Onion AI. Must be greater than 0. The result tells Onion AI how many were left out.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: int
|
||||
client:
|
||||
assistant:
|
||||
enabled:
|
||||
@@ -1317,6 +1343,69 @@ soc:
|
||||
staleMetricsMs:
|
||||
description: The age in milliseconds of node metrics when they are considered stale. Stale metrics have a faded appearance on the Grid screen.
|
||||
global: True
|
||||
recommendedAlarms:
|
||||
description: Recommended alarms offered on the Grid page's Alarms tab and Options dialog.
|
||||
global: True
|
||||
advanced: True
|
||||
forcedType: "[]{}"
|
||||
syntax: json
|
||||
helpLink: grid
|
||||
uiElements:
|
||||
- field: name
|
||||
label: Name
|
||||
required: True
|
||||
- field: metric
|
||||
label: Metric
|
||||
required: True
|
||||
- field: metricKey
|
||||
label: Metric Key
|
||||
required: False
|
||||
- field: operator
|
||||
label: Operator
|
||||
required: True
|
||||
options:
|
||||
- gt
|
||||
- gte
|
||||
- lt
|
||||
- lte
|
||||
- eq
|
||||
- ne
|
||||
- contains
|
||||
- field: threshold
|
||||
label: Threshold
|
||||
required: True
|
||||
forcedType: string
|
||||
- field: durationSeconds
|
||||
label: Duration Seconds
|
||||
required: False
|
||||
forcedType: int
|
||||
- field: severity
|
||||
label: Severity
|
||||
required: True
|
||||
options:
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
- info
|
||||
- field: clearedSeverity
|
||||
label: Cleared Severity
|
||||
required: False
|
||||
options:
|
||||
- none
|
||||
- critical
|
||||
- high
|
||||
- medium
|
||||
- low
|
||||
- info
|
||||
- field: enabled
|
||||
label: Enabled
|
||||
required: False
|
||||
forcedType: bool
|
||||
- field: note
|
||||
label: Note
|
||||
required: False
|
||||
multiline: True
|
||||
case:
|
||||
analyzerNodeId:
|
||||
description: The node ID on which analyzers will be executed.
|
||||
|
||||
@@ -158,6 +158,21 @@ tgraf_sbin_jinja:
|
||||
- defaults:
|
||||
CONTAINER_STATS: {{ TELEGRAFMERGED.container_stats }}
|
||||
|
||||
{% set tg_output = TELEGRAFMERGED.output | upper %}
|
||||
{% set pg_creds = salt['pillar.get']('telegraf:postgres_creds:' ~ GLOBALS.minion_id, {}) %}
|
||||
{% set pg_creds_missing = tg_output in ['POSTGRES', 'BOTH'] and not (pg_creds.get('user') and pg_creds.get('pass')) %}
|
||||
{% if pg_creds_missing %}
|
||||
{% set pg_creds_text = 'Telegraf Postgres credentials for ' ~ GLOBALS.minion_id ~ ' are missing from the pillar. On the manager, run so-telegraf-cred add ' ~ GLOBALS.minion_id ~ ', then run a highstate on this node.' %}
|
||||
telegraf_postgres_creds_missing:
|
||||
{% if tg_output == 'POSTGRES' %}
|
||||
test.fail_without_changes:
|
||||
- comment: {{ pg_creds_text | tojson }}
|
||||
{% else %}
|
||||
test.show_notification:
|
||||
- text: {{ pg_creds_text | tojson }}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
tgrafconf:
|
||||
file.managed:
|
||||
- name: /opt/so/conf/telegraf/etc/telegraf.conf
|
||||
@@ -171,6 +186,10 @@ tgrafconf:
|
||||
GLOBALS: {{ GLOBALS }}
|
||||
TELEGRAFMERGED: {{ TELEGRAFMERGED }}
|
||||
LOGSTASH_MERGED: {{ LOGSTASH_MERGED }}
|
||||
{% if pg_creds_missing %}
|
||||
- require:
|
||||
- test: telegraf_postgres_creds_missing
|
||||
{% endif %}
|
||||
|
||||
# this file will be read by telegraf to send node details (management interface, monitor interface, etc)
|
||||
# into influx
|
||||
|
||||
@@ -24,6 +24,8 @@ so-telegraf:
|
||||
- environment:
|
||||
- HOST_ETC=/host/etc
|
||||
- HOST_SYS=/host/sys
|
||||
- HOST_PROC=/host/proc
|
||||
- HOST_PROC_MOUNTINFO=/proc/1
|
||||
- HOST_MOUNT_PREFIX=/host
|
||||
- GODEBUG=x509ignoreCN=0
|
||||
{% if DOCKERMERGED.containers['so-telegraf'].extra_env %}
|
||||
|
||||
@@ -6,6 +6,13 @@
|
||||
{% from 'vars/globals.map.jinja' import GLOBALS %}
|
||||
{% import_yaml 'telegraf/defaults.yaml' as TELEGRAFDEFAULTS %}
|
||||
{% set TELEGRAFMERGED = salt['pillar.get']('telegraf', TELEGRAFDEFAULTS.telegraf, merge=True) %}
|
||||
{% set TG_OUTPUT = TELEGRAFMERGED.output | upper %}
|
||||
{% set TG_PG_ENTRY = salt['pillar.get']('telegraf:postgres_creds:' ~ GLOBALS.minion_id, {}) %}
|
||||
{% set PG_METRICS_READY = false %}
|
||||
{% if TG_OUTPUT != 'INFLUXDB' and TG_PG_ENTRY.get('user') and TG_PG_ENTRY.get('pass') %}
|
||||
{% set PG_METRICS_READY = true %}
|
||||
{% endif %}
|
||||
{% set INFLUX_RETIRED = TG_OUTPUT == 'POSTGRES' and PG_METRICS_READY %}
|
||||
|
||||
{% if GLOBALS.role in ['so-eval', 'so-standalone', 'so-sensor', 'so-heavynode'] %}
|
||||
{% from 'zeek/config.map.jinja' import ZEEKMERGED %}
|
||||
@@ -22,3 +29,10 @@
|
||||
{% do TELEGRAFMERGED.scripts[GLOBALS.role.split('-')[1]].remove('redis.sh') %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{% if INFLUX_RETIRED %}
|
||||
{% set role_scripts = TELEGRAFMERGED.scripts.get(GLOBALS.role.split('-')[1], []) %}
|
||||
{% if 'influxdbsize.sh' in role_scripts %}
|
||||
{% do role_scripts.remove('influxdbsize.sh') %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
@@ -5,14 +5,14 @@ telegraf:
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
output:
|
||||
description: Selects the backend(s) Telegraf writes metrics to. INFLUXDB keeps the current behavior; POSTGRES writes to the grid's Postgres instance; BOTH dual-writes for migration validation. When set to BOTH, the grid screen's metrics are pulled from Postgres, and the InfluxDB tool link remains visible. When set to POSTGRES, the InfluxDB tool link is removed.
|
||||
description: Selects the backend(s) Telegraf writes metrics to. INFLUXDB keeps the current behavior; POSTGRES writes to the grid's Postgres instance; BOTH dual-writes for migration validation. When set to BOTH, the grid screen's metrics are pulled from Postgres, and the InfluxDB tool link remains visible. When set to POSTGRES, the InfluxDB tool link is removed. WARNING - Choosing POSTGRES removes InfluxDB from the manager and permanently deletes all of its data; this cannot be undone. Switching back to INFLUXDB or BOTH afterwards is not supported, because InfluxDB would start again with no data. BOTH keeps InfluxDB running. InfluxDB will be removed in a future release, so grids should move to POSTGRES.
|
||||
options:
|
||||
- INFLUXDB
|
||||
- POSTGRES
|
||||
- BOTH
|
||||
global: True
|
||||
advanced: True
|
||||
helpLink: influxdb
|
||||
helpLink: postgresql
|
||||
config:
|
||||
interval:
|
||||
description: Data collection interval.
|
||||
|
||||
@@ -519,6 +519,8 @@ configure_minion() {
|
||||
info "Configuring minion type as $minion_type"
|
||||
logCmd "mkdir -p /etc/salt/minion.d"
|
||||
echo "role: so-$minion_type" > /etc/salt/grains
|
||||
# so-push-drainer leaves the node alone until salt.lasthighstate removes this
|
||||
echo "first_highstate_pending: True" >> /etc/salt/grains
|
||||
|
||||
local minion_config=/etc/salt/minion
|
||||
|
||||
|
||||
Reference in new issue
Block a user