Systemd Service Started by Unusual Parent Process

Systemctl is a process used in Linux systems to manage systemd processes through service configuration files. Malicious actors can leverage systemd services to achieve persistence by creating or modifying service files to execute malicious commands or payloads during system startup. This allows them to maintain unauthorized access, execute additional malicious activities, or evade detection.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2024/05/17"
  3integration = ["endpoint"]
  4maturity = "production"
  5updated_date = "2024/07/23"
  6
  7[transform]
  8[[transform.osquery]]
  9label = "Osquery - Retrieve File Listing Information"
 10query = """
 11SELECT * FROM file WHERE ( path LIKE '/etc/systemd/system/%' OR path LIKE '/usr/local/lib/systemd/system/%' OR path LIKE
 12'/lib/systemd/system/%' OR path LIKE '/usr/lib/systemd/system/%' OR path LIKE '/home/user/.config/systemd/user/%' )
 13"""
 14
 15[[transform.osquery]]
 16label = "Osquery - Retrieve Additional File Listing Information"
 17query = """
 18SELECT f.path, u.username AS file_owner, g.groupname AS group_owner, datetime(f.atime, 'unixepoch') AS
 19file_last_access_time, datetime(f.mtime, 'unixepoch') AS file_last_modified_time, datetime(f.ctime, 'unixepoch') AS
 20file_last_status_change_time, datetime(f.btime, 'unixepoch') AS file_created_time, f.size AS size_bytes FROM file f LEFT
 21JOIN users u ON f.uid = u.uid LEFT JOIN groups g ON f.gid = g.gid WHERE ( path LIKE '/etc/systemd/system/%' OR path LIKE
 22'/usr/local/lib/systemd/system/%' OR path LIKE '/lib/systemd/system/%' OR path LIKE '/usr/lib/systemd/system/%' OR path
 23LIKE '/home/{{user.name}}/.config/systemd/user/%' )
 24"""
 25
 26[[transform.osquery]]
 27label = "Osquery - Retrieve Running Processes by User"
 28query = "SELECT pid, username, name FROM processes p JOIN users u ON u.uid = p.uid ORDER BY username"
 29
 30[[transform.osquery]]
 31label = "Osquery - Retrieve Crontab Information"
 32query = "SELECT * FROM crontab"
 33
 34[[transform.osquery]]
 35label = "Osquery - Retrieve Listening Ports"
 36query = "SELECT pid, address, port, socket, protocol, path FROM listening_ports"
 37
 38[[transform.osquery]]
 39label = "Osquery - Retrieve Open Sockets"
 40query = "SELECT pid, family, remote_address, remote_port, socket, state FROM process_open_sockets"
 41
 42[[transform.osquery]]
 43label = "Osquery - Retrieve Information for a Specific User"
 44query = "SELECT * FROM users WHERE username = {{user.name}}"
 45
 46[[transform.osquery]]
 47label = "Osquery - Investigate the Account Authentication Status"
 48query = "SELECT * FROM logged_in_users WHERE user = {{user.name}}"
 49
 50
 51[rule]
 52author = ["Elastic"]
 53description = """
 54Systemctl is a process used in Linux systems to manage systemd processes through service configuration files. Malicious
 55actors can leverage systemd services to achieve persistence by creating or modifying service files to execute malicious
 56commands or payloads during system startup. This allows them to maintain unauthorized access, execute additional
 57malicious activities, or evade detection.
 58"""
 59from = "now-9m"
 60index = ["logs-endpoint.events.*"]
 61language = "kuery"
 62license = "Elastic License v2"
 63name = "Systemd Service Started by Unusual Parent Process"
 64note = """## Triage and analysis
 65
 66### Investigating Systemd Service Started by Unusual Parent Process
 67
 68Systemd service files are configuration files in Linux systems used to define and manage systemd services.
 69
 70Malicious actors can leverage systemd service files to achieve persistence by creating or modifying service files to execute malicious commands or payloads during system startup. This allows them to maintain unauthorized access, execute additional malicious activities, or evade detection.
 71
 72This rule monitors the execution of the systemctl binary to start, enable or reenable a systemd service, potentially indicating the creation of a persistence mechanism.
 73
 74> **Note**:
 75> This investigation guide uses the [Osquery Markdown Plugin](https://www.elastic.co/guide/en/security/master/invest-guide-run-osquery.html) introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide.
 76> This investigation guide uses [placeholder fields](https://www.elastic.co/guide/en/security/current/osquery-placeholder-fields.html) to dynamically pass alert data into Osquery queries. Placeholder fields were introduced in Elastic Stack version 8.7.0. If you're using Elastic Stack version 8.6.0 or earlier, you'll need to manually adjust this investigation guide's queries to ensure they properly run.
 77
 78#### Possible Investigation Steps
 79
 80- Investigate the currently enabled systemd services through the following command `sudo systemctl list-unit-files`.
 81- Investigate whether any other files in any of the available systemd directories have been altered through OSQuery.
 82  - $osquery_0
 83  - $osquery_1
 84- Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence and whether they are located in expected locations.
 85  - $osquery_2
 86- Investigate other alerts associated with the user/host during the past 48 hours.
 87- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
 88- Investigate whether the altered scripts call other malicious scripts elsewhere on the file system. 
 89  - If scripts or executables were dropped, retrieve the files and determine if they are malicious:
 90    - Use a private sandboxed malware analysis system to perform analysis.
 91      - Observe and collect information about the following activities:
 92        - Attempts to contact external domains and addresses.
 93          - Check if the domain is newly registered or unexpected.
 94          - Check the reputation of the domain or IP address.
 95        - File access, modification, and creation activities.
 96        - Cron jobs, services and other persistence mechanisms.
 97            - $osquery_3
 98- Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
 99  - Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
100    - $osquery_4
101    - $osquery_5
102  - Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
103    - $osquery_6
104- Investigate whether the user is currently logged in and active.
105    - $osquery_7
106
107### False Positive Analysis
108
109- If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
110- If this activity is related to a system administrator who uses systemd services for administrative purposes, consider adding exceptions for this specific administrator user account. 
111- Try to understand the context of the execution by thinking about the user, machine, or business purpose. A small number of endpoints, such as servers with unique software, might appear unusual but satisfy a specific business need.
112
113### Related Rules
114
115- New Systemd Service Created by Previously Unknown Process - 17b0a495-4d9f-414c-8ad0-92f018b8e001
116- Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
117- Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
118- New Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
119
120### Response and remediation
121
122- Initiate the incident response process based on the outcome of the triage.
123- Isolate the involved host to prevent further post-compromise behavior.
124- If the triage identified malware, search the environment for additional compromised hosts.
125  - Implement temporary network rules, procedures, and segmentation to contain the malware.
126  - Stop suspicious processes.
127  - Immediately block the identified indicators of compromise (IoCs).
128  - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
129- Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services.
130- Delete the service/timer or restore its original configuration.
131- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
132- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
133- Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).
134"""
135references = [
136    "https://symantec-enterprise-blogs.security.com/blogs/threat-intelligence/springtail-kimsuky-backdoor-espionage",
137    "https://pberba.github.io/security/2022/01/30/linux-threat-hunting-for-persistence-systemd-timers-cron/",
138]
139risk_score = 47
140rule_id = "b605f262-f7dc-41b5-9ebc-06bafe7a83b6"
141setup = """## Setup
142
143This rule requires data coming in from Elastic Defend.
144
145### Elastic Defend Integration Setup
146Elastic Defend is integrated into the Elastic Agent using Fleet. Upon configuration, the integration allows the Elastic Agent to monitor events on your host and send data to the Elastic Security app.
147
148#### Prerequisite Requirements:
149- Fleet is required for Elastic Defend.
150- To configure Fleet Server refer to the [documentation](https://www.elastic.co/guide/en/fleet/current/fleet-server.html).
151
152#### The following steps should be executed in order to add the Elastic Defend integration on a Linux System:
153- Go to the Kibana home page and click "Add integrations".
154- In the query bar, search for "Elastic Defend" and select the integration to see more details about it.
155- Click "Add Elastic Defend".
156- Configure the integration name and optionally add a description.
157- Select the type of environment you want to protect, either "Traditional Endpoints" or "Cloud Workloads".
158- Select a configuration preset. Each preset comes with different default settings for Elastic Agent, you can further customize these later by configuring the Elastic Defend integration policy. [Helper guide](https://www.elastic.co/guide/en/security/current/configure-endpoint-integration-policy.html).
159- We suggest selecting "Complete EDR (Endpoint Detection and Response)" as a configuration setting, that provides "All events; all preventions"
160- Enter a name for the agent policy in "New agent policy name". If other agent policies already exist, you can click the "Existing hosts" tab and select an existing policy instead.
161For more details on Elastic Agent configuration settings, refer to the [helper guide](https://www.elastic.co/guide/en/fleet/8.10/agent-policy.html).
162- Click "Save and Continue".
163- To complete the integration, select "Add Elastic Agent to your hosts" and continue to the next section to install the Elastic Agent on your hosts.
164For more details on Elastic Defend refer to the [helper guide](https://www.elastic.co/guide/en/security/current/install-endpoint.html).
165"""
166severity = "medium"
167tags = [
168    "Domain: Endpoint",
169    "OS: Linux",
170    "Use Case: Threat Detection",
171    "Tactic: Persistence",
172    "Tactic: Privilege Escalation",
173    "Data Source: Elastic Defend",
174]
175timestamp_override = "event.ingested"
176type = "new_terms"
177
178query = '''
179host.os.type:linux and event.category:process and event.type:start and event.action:exec and
180process.executable:/usr/bin/systemctl and process.args:(enable or reenable or start) and 
181process.entry_leader.entry_meta.type:* and
182not (
183  process.entry_leader.entry_meta.type:(container or init or unknown) or
184  process.parent.pid:1 or
185  process.parent.executable:(
186    /bin/adduser or /bin/dnf or /bin/dnf-automatic or /bin/dockerd or /bin/dpkg or /bin/microdnf or /bin/pacman or
187    /bin/podman or /bin/rpm or /bin/snapd or /bin/sudo or /bin/useradd or /bin/yum or /usr/bin/dnf or
188    /usr/bin/dnf-automatic or /usr/bin/dockerd or /usr/bin/dpkg or /usr/bin/microdnf or /usr/bin/pacman or
189    /usr/bin/podman or /usr/bin/rpm or /usr/bin/snapd or /usr/bin/sudo or /usr/bin/yum or /usr/sbin/adduser or
190    /usr/sbin/invoke-rc.d or /usr/sbin/useradd or /var/lib/dpkg/*
191  ) or
192  process.args_count >= 5
193)
194'''
195
196
197[[rule.threat]]
198framework = "MITRE ATT&CK"
199[[rule.threat.technique]]
200id = "T1543"
201name = "Create or Modify System Process"
202reference = "https://attack.mitre.org/techniques/T1543/"
203[[rule.threat.technique.subtechnique]]
204id = "T1543.002"
205name = "Systemd Service"
206reference = "https://attack.mitre.org/techniques/T1543/002/"
207
208
209
210[rule.threat.tactic]
211id = "TA0003"
212name = "Persistence"
213reference = "https://attack.mitre.org/tactics/TA0003/"
214[[rule.threat]]
215framework = "MITRE ATT&CK"
216[[rule.threat.technique]]
217id = "T1543"
218name = "Create or Modify System Process"
219reference = "https://attack.mitre.org/techniques/T1543/"
220[[rule.threat.technique.subtechnique]]
221id = "T1543.002"
222name = "Systemd Service"
223reference = "https://attack.mitre.org/techniques/T1543/002/"
224
225
226
227[rule.threat.tactic]
228id = "TA0004"
229name = "Privilege Escalation"
230reference = "https://attack.mitre.org/tactics/TA0004/"
231
232[rule.new_terms]
233field = "new_terms_fields"
234value = ["process.parent.executable"]
235[[rule.new_terms.history_window_start]]
236field = "history_window_start"
237value = "now-7d"

Triage and analysis

Investigating Systemd Service Started by Unusual Parent Process

Systemd service files are configuration files in Linux systems used to define and manage systemd services.

Malicious actors can leverage systemd service files to achieve persistence by creating or modifying service files to execute malicious commands or payloads during system startup. This allows them to maintain unauthorized access, execute additional malicious activities, or evade detection.

This rule monitors the execution of the systemctl binary to start, enable or reenable a systemd service, potentially indicating the creation of a persistence mechanism.

Note: This investigation guide uses the Osquery Markdown Plugin introduced in Elastic Stack version 8.5.0. Older Elastic Stack versions will display unrendered Markdown in this guide. This investigation guide uses placeholder fields to dynamically pass alert data into Osquery queries. Placeholder fields were introduced in Elastic Stack version 8.7.0. If you're using Elastic Stack version 8.6.0 or earlier, you'll need to manually adjust this investigation guide's queries to ensure they properly run.

Possible Investigation Steps

  • Investigate the currently enabled systemd services through the following command sudo systemctl list-unit-files.
  • Investigate whether any other files in any of the available systemd directories have been altered through OSQuery.
    • $osquery_0
    • $osquery_1
  • Investigate the script execution chain (parent process tree) for unknown processes. Examine their executable files for prevalence and whether they are located in expected locations.
    • $osquery_2
  • Investigate other alerts associated with the user/host during the past 48 hours.
  • Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
  • Investigate whether the altered scripts call other malicious scripts elsewhere on the file system.
    • If scripts or executables were dropped, retrieve the files and determine if they are malicious:
      • Use a private sandboxed malware analysis system to perform analysis.
        • Observe and collect information about the following activities:
          • Attempts to contact external domains and addresses.
            • Check if the domain is newly registered or unexpected.
            • Check the reputation of the domain or IP address.
          • File access, modification, and creation activities.
          • Cron jobs, services and other persistence mechanisms.
            • $osquery_3
  • Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
    • Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
      • $osquery_4
      • $osquery_5
    • Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
      • $osquery_6
  • Investigate whether the user is currently logged in and active.
    • $osquery_7

False Positive Analysis

  • If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
  • If this activity is related to a system administrator who uses systemd services for administrative purposes, consider adding exceptions for this specific administrator user account.
  • Try to understand the context of the execution by thinking about the user, machine, or business purpose. A small number of endpoints, such as servers with unique software, might appear unusual but satisfy a specific business need.
  • New Systemd Service Created by Previously Unknown Process - 17b0a495-4d9f-414c-8ad0-92f018b8e001
  • Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
  • Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
  • New Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c

Response and remediation

  • Initiate the incident response process based on the outcome of the triage.
  • Isolate the involved host to prevent further post-compromise behavior.
  • If the triage identified malware, search the environment for additional compromised hosts.
    • Implement temporary network rules, procedures, and segmentation to contain the malware.
    • Stop suspicious processes.
    • Immediately block the identified indicators of compromise (IoCs).
    • Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
  • Investigate credential exposure on systems compromised or used by the attacker to ensure all compromised accounts are identified. Reset passwords for these accounts and other potentially compromised credentials, such as email, business systems, and web services.
  • Delete the service/timer or restore its original configuration.
  • Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
  • Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
  • Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).

References

Related rules

to-top