Systemd Service Created

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

Triage and analysis

Investigating Systemd Service Created

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