Unexpected File Made Executable
osquery
Detect commands used to bless a file as executable
Description
ODK (osquery-defense-kit) is unique in that the queries are designed to be used as part of a production detection & response pipeline. The detection queries are formulated to return zero rows during normal expected behavior, so that they may be configured to generate alerts when rows are returned.
Query
-- Detect commands used to bless a file as executable
--
-- false positives:
-- * none observed, but they are expected
--
-- interval: 600
-- platform: posix
-- tags: process events
SELECT
-- Child
AS p0_path,
pe.path '.*/(.*)', 1) AS p0_name,
REGEX_MATCH (pe.path, TRIM(pe.cmdline) AS p0_cmd,
AS p0_cwd,
pe.cwd time AS p0_time,
pe.AS p0_euid,
pe.euid AS p0_pid,
pe.pid AS p0_cgroup,
p.cgroup_path -- Parent
parent AS p1_pid,
pe.AS p1_cgroup,
p1.cgroup_path TRIM(COALESCE(p1.cmdline, pe1.cmdline)) AS p1_cmd,
COALESCE(p1.path, pe1.path) AS p1_path,
COALESCE(p_hash1.sha256, pe_hash1.sha256) AS p1_hash,
COALESCE(p1.path, pe1.path), '.*/(.*)', 1) AS p1_name,
REGEX_MATCH (-- Grandparent
COALESCE(p1.parent, pe1.parent) AS p2_pid,
COALESCE(p1_p2.cgroup_path, pe1_p2.cgroup_path) AS p2_cgroup,
TRIM(
COALESCE(p1_p2.cmdline, pe1_p2.cmdline, pe1_pe2.cmdline)
AS p2_cmd,
) COALESCE(p1_p2.path, pe1_p2.path, pe1_pe2.path) AS p2_path,
COALESCE(
p1_p2_hash.path,
pe1_p2_hash.path,
pe1_pe2_hash.pathAS p2_hash,
)
REGEX_MATCH (COALESCE(p1_p2.path, pe1_p2.path, pe1_pe2.path),
'.*/(.*)',
1
AS p2_name,
) -- Extra fields
TRIM(pe.cmdline), ".* (.*?)$", 1) AS target_path
REGEX_MATCH (FROM
process_events pe,
uptimeLEFT JOIN processes p ON pe.pid = p.pid
-- Parents (via two paths)
LEFT JOIN processes p1 ON pe.parent = p1.pid
LEFT JOIN hash p_hash1 ON p1.path = p_hash1.path
LEFT JOIN process_events pe1 ON pe.parent = pe1.pid
AND pe1.cmdline != ''
LEFT JOIN hash pe_hash1 ON pe1.path = pe_hash1.path
-- Grandparents (via 3 paths)
LEFT JOIN processes p1_p2 ON p1.parent = p1_p2.pid -- Current grandparent via parent processes
LEFT JOIN processes pe1_p2 ON pe1.parent = pe1_p2.pid -- Current grandparent via parent events
LEFT JOIN process_events pe1_pe2 ON pe1.parent = pe1_p2.pid
AND pe1_pe2.cmdline != '' -- Past grandparent via parent events
LEFT JOIN hash p1_p2_hash ON p1_p2.path = p1_p2_hash.path
LEFT JOIN hash pe1_p2_hash ON pe1_p2.path = pe1_p2_hash.path
LEFT JOIN hash pe1_pe2_hash ON pe1_pe2.path = pe1_pe2_hash.path
WHERE
time > (strftime('%s', 'now') -600)
pe.AND pe.cmdline != ''
AND pe.path IN ('/bin/chmod', '/usr/bin/chmod')
AND (
LIKE '%chmod 7%'
p0_cmd OR p0_cmd LIKE '%chmod 5%'
OR p0_cmd LIKE '%chmod 1%'
OR p0_cmd LIKE '%chmod +%x'
)AND p0_cmd NOT LIKE 'chmod 700 /tmp/apt-key-gpghome.%'
AND p0_cmd NOT LIKE 'chmod 700 /home/%/snap/%/.config'
AND p0_cmd NOT LIKE 'chmod 755 /home/%/.gradle/wrapper/dists/gradle-%-bin/%bin/gradle'
AND p0_cmd NOT IN ('chmod 755 /usr/local/share/ca-certificates')
AND NOT p0_cgroup LIKE '/system.slice/docker-%'
GROUP BY
pe.pid
tags: SStagSS