Cron Job Created or Changed by Previously Unknown Process

Linux cron jobs are scheduled tasks that can be leveraged by malicious actors for persistence, privilege escalation and command execution. By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.

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

Triage and analysis

Investigating Cron Job Created or Changed by Previously Unknown Process

Linux cron jobs are scheduled tasks that run at specified intervals or times, managed by the cron daemon.

By creating or modifying cron job configurations, attackers can execute malicious commands or scripts at predefined intervals, ensuring their continued presence and enabling unauthorized activities.

This rule monitors the creation of previously unknown cron jobs by monitoring for file creation events in the most common cron job task location directories.

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 cron job file that was created or modified.
  • Investigate whether any other files in any of the available cron job directories have been altered through OSQuery.
    • $osquery_0
    • $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.
  • 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 cron jobs 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.
  • Suspicious File Creation in /etc for Persistence - 1c84dd64-7e6c-4bad-ac73-a5014ee37042
  • 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
  • New Systemd Service Created by Previously Unknown Process - 17b0a495-4d9f-414c-8ad0-92f018b8e001

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