> For the complete documentation index, see [llms.txt](https://cortex-docs.paloaltonetworks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cortex-docs.paloaltonetworks.com/cortex-cloud-runtime-security/rules-and-policies/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule.md).

# Create a new custom detection rule

Create a custom detection rule for cloud workload security risks.

Creating Custom Detection Rules gives you the flexibility to define and enforce security best practices tailored to your organization's objectives. Use them to detect the conditions, misconfigurations, and policy violations that matter to your organization but are not covered by the built-in rules that ship with Cortex Cloud.

{% hint style="warning" %}
**Note**

A rule only detects criteria for evaluation, but do not initiate any actions unless incorporated within a policy.

To act on a detection, add the rule to a policy (to create issues or enforce prevention) and, optionally, associate it with a custom control so violations appear in your compliance reports.
{% endhint %}

### Before you begin

Ensure you have a custom compliance control defined to associate the Custom Detection Rule to. For more information, see [Use a built-in or custom standard](/cortex-cloud-runtime-security/compliance/monitor-and-track-compliance-adherence/choose-compliance-standards-from-the-compliance-catalog/use-a-built-in-or-custom-standard.md).

### How to create a custom detection rule

1. Go to **Posture Management** → **Rules & Policies** → **Rules** → **Cloud Workload**.
2. In the **Cloud Workload Rules** page, select **Create Custom Rule**.
3. Enter the following settings:
   * **Rule name**: A descriptive name for the custom rule.
   * **Description:** An optional field for adding additional details or context about the rule, such as its purpose or intended behavior.
4. Select a **Scanner**. A scanner determines the rule language, rule input, and assets that the rule can inspect.

Use the following table to select a scanner:

| Scanner                                                           | Language | Input your rule receives                            | Use it to                                                                   |
| ----------------------------------------------------------------- | -------- | --------------------------------------------------- | --------------------------------------------------------------------------- |
| <ol><li><strong>Agentless disk scan</strong></li></ol>            | Rego     | File content and metadata for each file you declare | Inspect disk-image files, such as `/etc/ssh/sshd_config` or `/etc/shadow`   |
| <ol start="2"><li><strong>Kubernetes connector</strong></li></ol> | Rego     | The Kubernetes resource object being evaluated      | Inspect Kubernetes resources, such as Deployments, Services, and RBAC roles |
| <ol start="3"><li><strong>XDR agent</strong></li></ol>            | Python   | Data that the script reads directly from the host   | Run read-only Python scripts for custom host checks                         |

{% hint style="warning" %}
**Note**:

Each scanner delivers input in a different structure. Writing your rule against the wrong structure produces a rule that never matches and reports no error. Review the input structure for your chosen scanner before writing detection logic.
{% endhint %}

5. Configure the scanner-specific settings:

<details>

<summary>Agentless Disk Scan settings</summary>

The **Agentless disk scan** evaluates files on a disk image using rules written in **Rego**. Each rule evaluates the file content and metadata provided by the scanner through a defined input structure.

<table><thead><tr><th width="173">Field</th><th>Description</th></tr></thead><tbody><tr><td>Operating System</td><td><p>The operating system targeted by the rule. The available options are:</p><ul><li>Linux</li><li>Windows</li></ul></td></tr><tr><td>Input file(s) path</td><td>The full file path for one or more files. For example, <strong><code>/nfs/an/disks/jj/home/dir/file.txt</code></strong></td></tr><tr><td>Define the Rule (Rego)</td><td><p>Agentless disk scan rules use the following structure:</p><p></p><ul><li>Declare the <code>panw.compliance</code> package.</li><li>Import <code>rego.v1</code>.</li><li>Define one or more <code>match</code> rules to specify the detection logic.</li><li>Assign a human-readable finding description to <code>msg</code>.</li></ul><pre><code>package panw.compliance

import rego.v1

match contains {"msg": msg} if {
\# Your detection logic here
msg := "Description of the finding"
} </code></pre><p>Use the default code in this box as a reference or starting point.  </p><p></p><p>For detailed configuration steps, see <a href="/cortex-cloud-runtime-security/rules-and-policies/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule/configure-agentless-disk-scan-rule.md">Configure Agentless disk scan rule</a>.</p></td></tr></tbody></table>

</details>

<details>

<summary>Kubernetes connector Settings</summary>

<table data-header-hidden><thead><tr><th width="153.5">Field</th><th>Description</th></tr></thead><tbody><tr><td>Kubernetes Resources</td><td><p>From the list, select one or more from the following:<br></p><ul><li><strong>Namespaces</strong>: Logical partitions within a Kubernetes cluster that allow resource isolation and organization.</li><li><strong>ReplicaSets</strong>: Ensures a specified number of pod replicas are running at all times by automatically scaling up or down.</li><li><strong>Deployments</strong>: Manages and controls pod replicas by providing declarative updates for ReplicaSets, enabling rolling updates and rollbacks.</li><li><strong>StatefulSets</strong>: Deploys stateful applications that require persistent identity and storage, ensuring stable pod names and ordered scaling.</li><li><strong>DaemonSets</strong>: Ensures that a copy of a specific pod runs on all or selected nodes in the cluster, commonly used for logging and monitoring agents.</li><li><strong>Jobs</strong>: Runs one-time or short-lived workloads that complete execution and then terminate.</li><li><strong>CronJobs</strong>: Defines scheduled jobs that run at specified times or intervals, similar to Linux cron jobs.</li><li><strong>ClusterRoles</strong>: Defines permissions at the cluster level, granting access to resources across all namespaces.</li><li><strong>Roles</strong>: Defines permissions within a specific namespace, restricting access to resources within that namespace.</li><li><strong>RoleBindings</strong>: Associates a role with a user, group, or service account within a specific namespace.</li><li><strong>ClusterRoleBindings</strong>: Associates a cluster role with users, groups, or service accounts at the cluster-wide level.</li><li><strong>NetworkPolicies</strong>: Defines rules that control the communication between pods and other network entities within the cluster, enforcing security restrictions.</li><li><strong>Services</strong>: Exposes a set of pods as a network service, allowing stable communication within and outside the cluster.</li><li><strong>ServiceAccounts</strong>: Provides an identity for pods to authenticate against the Kubernetes API, allowing controlled access to resources.</li><li><strong>Endpoints</strong>: Represents the actual network addresses of the pods backing a service, dynamically updated as pods start or stop.</li><li><strong>Ingresses</strong>: Manages external access to services, providing HTTP/HTTPS routing, load balancing, and SSL termination.</li><li><strong>ConfigMaps</strong>: Stores non-sensitive configuration data in key-value pairs, allowing applications to retrieve configuration without modifying container images.</li><li><strong>Secrets</strong>: Securely stores and manages sensitive data, such as API keys, passwords, and certificates, in an encrypted format.</li><li><strong>Nodes</strong>: Defines the physical or virtual machines that run the workloads in a Kubernetes cluster.</li></ul></td></tr><tr><td>Define the Rule (Rego)</td><td><p>Kubernetes connector rules must use the following structure:</p><p></p><ul><li>Declare the <code>panw.compliance</code> package.</li><li>Import <code>rego.v1</code>.</li><li>Define one or more <code>match</code> rules to specify the detection logic.</li><li>Assign a human-readable finding description to <code>msg</code>.</li></ul><pre><code>package panw.compliance

import rego.v1

match contains {"msg": msg} if {
\# Your detection logic here
msg := "Description of the finding"
} </code></pre><p>The rule is evaluated against each Kubernetes resource selected for the rule. When the detection conditions are satisfied, the <code>match</code> rule produces a finding containing the value assigned to <code>msg</code>.</p><p></p><p>For detailed configuration steps, see <a href="/cortex-cloud-runtime-security/rules-and-policies/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule/configure-kubernetes-connector-rule.md">Configure Kubernetes connector rule</a>.</p></td></tr></tbody></table>

</details>

<details>

<summary>XDR agent Settings</summary>

<table><thead><tr><th width="182">Field</th><th>Description</th></tr></thead><tbody><tr><td>Custom Code Execution</td><td><div data-gb-custom-block data-tag="hint" data-style="warning" class="hint hint-warning"><p><strong>Note</strong></p><p>Enable this setting for the scanner to perform custom compliance checks by executing user-defined Python scripts.</p><p><br>Only users with the following roles can enable or disable Custom Code Execution:</p><ul><li>Account Admin</li><li>Instance Administrator</li><li>Deployment Admin</li><li>Privileged Security Admin<br></li></ul></div><p>Select <strong>Confirm</strong> to accept the terms and conditions in the dialog box.</p><p></p><p>After you accept the terms, the remaining XDR agent settings appear.</p></td></tr><tr><td>Operating System</td><td><p>The operating system targeted by the rule. The available options are:</p><ul><li>Linux</li><li>Windows</li></ul></td></tr><tr><td>Define the Rule (Python)</td><td><p>XDR agent rules use a Python <code>run</code> function as the entry point. The function accepts positional and keyword arguments and returns the rule result.</p><pre><code>def run(*args, **kwargs):
    return {"result": True}
</code></pre><p>For detailed configuration steps, see <a href="/cortex-cloud-runtime-security/rules-and-policies/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule/configure-xdr-agent-rule.md">Configure XDR agent rule</a>.</p></td></tr></tbody></table>

</details>

6. Define **Compliance Violation Severity** of the compliance violation to ensure proper categorization and prioritization. Possible values are:
   * Critical
   * High
   * Medium
   * Low
   * Informational
7. Assign **Compliance Controls** to one or more existing compliance controls.

{% hint style="info" %}
**NOTE**

Only Custom Detection Rules (not built-in rules) can be assigned to custom controls.
{% endhint %}

   a. Click **Add**.\
   b. Select a custom compliance control from the list.\
   c. Click **Assign**.

8. For **Remediation**, you can optionally define the remediation steps to address any detected misconfiguration.
9. Select **Create**.\
   \
   The new rule appears in the Rules List.\
   \
   You can now use the rule as a check to either create an issue or monitor adherence to a specific requirement.

### Create an issue

Under **Posture Management → Policies → Cloud Workload**, add the Custom Detection Rule to a **Policy**. This policy automatically runs the rule and creates an issue if the check fails.

### Monitor compliance adherence

Under **Posture Management → Compliance → Catalogs → Standards**, create a custom standard that includes the custom control associated with the Custom Detection Rule, and then create an assessment profile that runs the custom standard. You can then monitor the compliance results in a report.&#x20;

For detailed information, see [Monitor and track compliance adherence](/cortex-cloud-runtime-security/compliance/monitor-and-track-compliance-adherence.md).

### Troubleshooting

| Symptom                                                          | Cause                                                                                                       | Resolution                                                                                                                                                                                                                                                                                                      |
| ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The rule runs but does not produce a finding or report an error. | The rule accesses the scanner input using an incorrect structure.                                           | Verify the input structure for the scanner. For **Agentless Disk Scan**, access files through `input.files[id]` and use fields such as `f.path` and `f.content`. For **Kubernetes Connector**, access the Kubernetes resource directly through fields such as `input.kind`, `input.metadata`, and `input.spec`. |
| A file permission comparison does not match the expected value.  | The expected permission value is expressed in octal rather than decimal.                                    | Convert the permission value to decimal. For example, `0600` is `384` and `0644` is `420`.                                                                                                                                                                                                                      |
| The rule fails validation and cannot be saved.                   | The rule is missing one or more required elements.                                                          | Ensure that the rule declares `package panw.compliance`, imports `rego.v1`, and defines at least one `match` rule.                                                                                                                                                                                              |
| A directory check does not produce a finding.                    | The rule attempts to evaluate file content for a directory.                                                 | Check the file type before evaluating `content`. For example, use `f.metadata.file_type == "file"` to limit the logic to regular files.                                                                                                                                                                         |
| A Python rule always passes.                                     | The `run` function returns `None` or does not return a `result` value.                                      | Return `{"result": False, "cause": "<description>"}` when a violation is detected. Return `{"result": True}` when the check passes.                                                                                                                                                                             |
| A Python rule reports an error during execution.                 | The script does not define the required `run` function, or the script encounters an error during execution. | Define `run(*args, **kwargs)` as the entry point and verify that the script executes successfully using supported, read-only operations.                                                                                                                                                                        |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://cortex-docs.paloaltonetworks.com/cortex-cloud-runtime-security/rules-and-policies/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
