New Systemd Service Created by Previously Unknown Process

Systemd service files are configuration files in Linux systems used to define and manage system 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.

Elastic rule (View on GitHub)

  1[metadata]
  2creation_date = "2023/06/09"
  3integration = ["endpoint"]
  4maturity = "production"
  5min_stack_comments = "New fields added: required_fields, related_integrations, setup, New Term"
  6min_stack_version = "8.6.0"
  7updated_date = "2023/12/13"
  8
  9[transform]
 10[[transform.osquery]]
 11label = "Osquery - Retrieve File Information"
 12query = "SELECT * FROM file WHERE path = {{file.path}}"
 13
 14[[transform.osquery]]
 15label = "Osquery - Retrieve File Listing Information"
 16query = """
 17SELECT * FROM file WHERE (
 18path LIKE '/etc/systemd/system/%' OR 
 19path LIKE '/usr/local/lib/systemd/system/%' OR 
 20path LIKE '/lib/systemd/system/%' OR
 21path LIKE '/usr/lib/systemd/system/%' OR
 22path LIKE '/home/user/.config/systemd/user/%'
 23)
 24"""
 25
 26[[transform.osquery]]
 27label = "Osquery - Retrieve Additional File Listing Information"
 28query = """
 29SELECT
 30  f.path,
 31  u.username AS file_owner,
 32  g.groupname AS group_owner,
 33  datetime(f.atime, 'unixepoch') AS file_last_access_time,
 34  datetime(f.mtime, 'unixepoch') AS file_last_modified_time,
 35  datetime(f.ctime, 'unixepoch') AS file_last_status_change_time,
 36  datetime(f.btime, 'unixepoch') AS file_created_time,
 37  f.size AS size_bytes
 38FROM
 39  file f
 40  LEFT JOIN users u ON f.uid = u.uid
 41  LEFT JOIN groups g ON f.gid = g.gid
 42WHERE (
 43path LIKE '/etc/systemd/system/%' OR 
 44path LIKE '/usr/local/lib/systemd/system/%' OR 
 45path LIKE '/lib/systemd/system/%' OR
 46path LIKE '/usr/lib/systemd/system/%' OR
 47path LIKE '/home/{{user.name}}/.config/systemd/user/%'
 48)
 49"""
 50
 51[[transform.osquery]]
 52label = "Osquery - Retrieve Running Processes by User"
 53query = "SELECT pid, username, name FROM processes p JOIN users u ON u.uid = p.uid ORDER BY username"
 54
 55[[transform.osquery]]
 56label = "Osquery - Retrieve Crontab Information"
 57query = "SELECT * FROM crontab"
 58
 59[[transform.osquery]]
 60label = "Osquery - Retrieve Listening Ports"
 61query = "SELECT pid, address, port, socket, protocol, path FROM listening_ports"
 62
 63[[transform.osquery]]
 64label = "Osquery - Retrieve Open Sockets"
 65query = "SELECT pid, family, remote_address, remote_port, socket, state FROM process_open_sockets"
 66
 67[[transform.osquery]]
 68label = "Osquery - Retrieve Information for a Specific User"
 69query = "SELECT * FROM users WHERE username = {{user.name}}"
 70
 71[[transform.osquery]]
 72label = "Osquery - Investigate the Account Authentication Status"
 73query = "SELECT * FROM logged_in_users WHERE user = {{user.name}}"
 74
 75[rule]
 76author = ["Elastic"]
 77description = """
 78Systemd service files are configuration files in Linux systems used to define and manage system services. Malicious 
 79actors can leverage systemd service files to achieve persistence by creating or modifying service files to execute 
 80malicious commands or payloads during system startup. This allows them to maintain unauthorized access, execute 
 81additional malicious activities, or evade detection.
 82"""
 83from = "now-9m"
 84index = ["logs-endpoint.events.*", "endgame-*"]
 85language = "kuery"
 86license = "Elastic License v2"
 87name = "New Systemd Service Created by Previously Unknown Process"
 88note = """## Triage and analysis
 89
 90### Investigating New Systemd Service Created by Previously Unknown Process
 91
 92Systemd service files are configuration files in Linux systems used to define and manage system services.
 93
 94Malicious 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.
 95
 96This rule monitors the creation of new systemd service files, potentially indicating the creation of a persistence mechanism.
 97
 98> **Note**:
 99> 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.
100> 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.
101
102#### Possible Investigation Steps
103
104- Investigate the systemd service file that was created or modified.
105  - $osquery_0
106- Investigate the currently enabled systemd services through the following command `sudo systemctl list-unit-files`.
107- Investigate whether any other files in any of the available systemd directories have been altered through OSQuery.
108  - $osquery_1
109  - $osquery_2
110- 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.
111  - $osquery_3
112- Investigate other alerts associated with the user/host during the past 48 hours.
113- Validate the activity is not related to planned patches, updates, network administrator activity, or legitimate software installations.
114- Investigate whether the altered scripts call other malicious scripts elsewhere on the file system. 
115  - If scripts or executables were dropped, retrieve the files and determine if they are malicious:
116    - Use a private sandboxed malware analysis system to perform analysis.
117      - Observe and collect information about the following activities:
118        - Attempts to contact external domains and addresses.
119          - Check if the domain is newly registered or unexpected.
120          - Check the reputation of the domain or IP address.
121        - File access, modification, and creation activities.
122        - Cron jobs, services and other persistence mechanisms.
123            - $osquery_4
124- Investigate abnormal behaviors by the subject process/user such as network connections, file modifications, and any other spawned child processes.
125  - Investigate listening ports and open sockets to look for potential command and control traffic or data exfiltration.
126    - $osquery_5
127    - $osquery_6
128  - Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
129    - $osquery_7
130- Investigate whether the user is currently logged in and active.
131    - $osquery_8
132
133### False Positive Analysis
134
135- If this activity is related to new benign software installation activity, consider adding exceptions — preferably with a combination of user and command line conditions.
136- 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. 
137- 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.
138
139### Related Rules
140
141- Potential Persistence Through Run Control Detected - 0f4d35e4-925e-4959-ab24-911be207ee6f
142- Potential Persistence Through init.d Detected - 474fd20e-14cc-49c5-8160-d9ab4ba16c8b
143- New Systemd Timer Created - 7fb500fa-8e24-4bd1-9480-2a819352602c
144
145### Response and remediation
146
147- Initiate the incident response process based on the outcome of the triage.
148- Isolate the involved host to prevent further post-compromise behavior.
149- If the triage identified malware, search the environment for additional compromised hosts.
150  - Implement temporary network rules, procedures, and segmentation to contain the malware.
151  - Stop suspicious processes.
152  - Immediately block the identified indicators of compromise (IoCs).
153  - Inspect the affected systems for additional malware backdoors like reverse shells, reverse proxies, or droppers that attackers could use to reinfect the system.
154- 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.
155- Delete the service/timer or restore its original configuration.
156- Run a full antimalware scan. This may reveal additional artifacts left in the system, persistence mechanisms, and malware components.
157- Determine the initial vector abused by the attacker and take action to prevent reinfection through the same vector.
158- Leverage the incident response data and logging to improve the mean time to detect (MTTD) and the mean time to respond (MTTR).
159"""
160references = [
161    "https://opensource.com/article/20/7/systemd-timers",
162    "https://pberba.github.io/security/2022/01/30/linux-threat-hunting-for-persistence-systemd-timers-cron/"
163]
164risk_score = 47
165rule_id = "17b0a495-4d9f-414c-8ad0-92f018b8e001"
166setup = """## Setup
167
168This rule requires data coming in from Elastic Defend.
169
170### Elastic Defend Integration Setup
171Elastic 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.
172
173#### Prerequisite Requirements:
174- Fleet is required for Elastic Defend.
175- To configure Fleet Server refer to the [documentation](https://www.elastic.co/guide/en/fleet/current/fleet-server.html).
176
177#### The following steps should be executed in order to add the Elastic Defend integration on a Linux System:
178- Go to the Kibana home page and click "Add integrations".
179- In the query bar, search for "Elastic Defend" and select the integration to see more details about it.
180- Click "Add Elastic Defend".
181- Configure the integration name and optionally add a description.
182- Select the type of environment you want to protect, either "Traditional Endpoints" or "Cloud Workloads".
183- 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).
184- We suggest selecting "Complete EDR (Endpoint Detection and Response)" as a configuration setting, that provides "All events; all preventions"
185- 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.
186For more details on Elastic Agent configuration settings, refer to the [helper guide](https://www.elastic.co/guide/en/fleet/8.10/agent-policy.html).
187- Click "Save and Continue".
188- 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.
189For more details on Elastic Defend refer to the [helper guide](https://www.elastic.co/guide/en/security/current/install-endpoint.html).
190"""
191severity = "medium"
192tags = [
193        "Domain: Endpoint",
194        "OS: Linux",
195        "Use Case: Threat Detection",
196        "Tactic: Persistence",
197        "Tactic: Privilege Escalation",
198        "Data Source: Elastic Endgame",
199        "Data Source: Elastic Defend"
200        ]
201timestamp_override = "event.ingested"
202type = "new_terms"
203
204query = '''
205host.os.type:linux and event.category:file and event.action:("creation" or "file_create_event") and file.path:(
206  /etc/systemd/system/* or 
207  /usr/local/lib/systemd/system/* or 
208  /lib/systemd/system/* or 
209  /usr/lib/systemd/system/* or 
210  /home/*/.config/systemd/user/*
211) and 
212not (
213  process.name:(
214    "dpkg" or "dockerd" or "rpm" or "snapd" or "yum" or "exe" or "dnf" or "dnf-automatic" or python* or "puppetd" or
215    "elastic-agent" or "cinc-client" or "chef-client" or "pacman" or "puppet" or "cloudflared" or "packagekitd" or
216    "podman"
217  ) or 
218  file.extension:("swp" or "swpx")
219)
220'''
221
222[[rule.threat]]
223framework = "MITRE ATT&CK"
224
225[[rule.threat.technique]]
226id = "T1543"
227name = "Create or Modify System Process"
228reference = "https://attack.mitre.org/techniques/T1543/"
229
230[[rule.threat.technique.subtechnique]]
231id = "T1543.002"
232name = "Systemd Service"
233reference = "https://attack.mitre.org/techniques/T1543/002/"
234
235[rule.threat.tactic]
236id = "TA0003"
237name = "Persistence"
238reference = "https://attack.mitre.org/tactics/TA0003/"
239
240[[rule.threat]]
241framework = "MITRE ATT&CK"
242
243[[rule.threat.technique]]
244id = "T1543"
245name = "Create or Modify System Process"
246reference = "https://attack.mitre.org/techniques/T1543/"
247
248[[rule.threat.technique.subtechnique]]
249id = "T1543.002"
250name = "Systemd Service"
251reference = "https://attack.mitre.org/techniques/T1543/002/"
252
253[rule.threat.tactic]
254id = "TA0004"
255name = "Privilege Escalation"
256reference = "https://attack.mitre.org/tactics/TA0004/"
257
258[rule.new_terms]
259field = "new_terms_fields"
260value = ["host.id", "file.path", "process.executable"]
261
262[[rule.new_terms.history_window_start]]
263field = "history_window_start"
264value = "now-10d"

Triage and analysis

Investigating New Systemd Service Created by Previously Unknown Process

Systemd service files are configuration files in Linux systems used to define and manage system 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 creation of new systemd service files, 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 systemd service file that was created or modified.
    • $osquery_0
  • 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_1
    • $osquery_2
  • 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_3
  • 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_4
  • 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_5
      • $osquery_6
    • Identify the user account that performed the action, analyze it, and check whether it should perform this kind of action.
      • $osquery_7
  • Investigate whether the user is currently logged in and active.
    • $osquery_8

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.
  • 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