> 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/kubernetes-security/cloud-workload-policies-and-rules/cloud-workload-rules/create-a-new-custom-detection-rule.md).

# Create a new custom detection rule

Creating Custom Detection Rules give you the flexibility to define and enforce security best practices tailored to your organization's objectives, as well as regulatory requirements not already covered by the compliance standards in our catalog.

### 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](https://docs-cortex.paloaltonetworks.com/access?ft:baseId=UUID-534080f2-2697-630d-4618-ba39f1d08093).

### How to create a Custom Detection Rule

#### Navigate to Cloud Workload Rules

Go to **Posture Management** → **Rules & Policies** → **Rules** → **Cloud Workload**.

On the **Cloud Workload Rules** page, select **Create Custom Rule**.

#### Enter rule details

Enter the following settings:

* **Rule name**: A descriptive name for the custom rule.
* **Description**: Optional details or context for the rule, such as its purpose or intended behavior.

#### Select a scanner

Select a **Scanner** to execute the custom detection rule and its associated script:

* **Agentless Disk Scan**
* **Kubernetes Connector**
* **XDR Agent**

#### Configure scanner settings

Configure the settings for the scanner you selected.

**Agentless Disk Scan settings**

**Operating System**

The operating system targeted by the rule. The available options are:

* Linux
* Windows

**Input file(s) path**

The full file path for one or more files. For example, **`/nfs/an/disks/jj/home/dir/file.txt`**.

**Define the Rule (Rego)**

Use Rego to define the custom detection logic.

Use the default code in this box as a reference or starting point. Click [read here](https://www.openpolicyagent.org/docs/latest/policy-language/#learning-rego) for more information how to use Rego syntax.<br>

<details>

<summary>Example 1: Detect failed login attempts</summary>

**Code**

```json
{
  "/var/log/auth.log": {
    "content": "Failed password for invalid user test from 192.168.1.1 port 22 ssh2\n",
    "metadata": {
      "file_type": "file",
      "gid": 1000,
      "last_modified": 1737292449,
      "permissions": 436,
      "size": 6000,
      "uid": 1001
    },
    "path": "/var/log/auth.log"
  }
}
```

**Script**

```rego
package panw.compliance

import rego.v1

match contains {"msg": msg} if {
  authLogFile := input["/var/log/auth.log"]
  contains(authLogFile.content, "Failed password")
  authLogFile.metadata.permissions == 436
  authLogFile.metadata.size > 5000
  msg := "Failed login attempts detected in /var/log/auth.log"
}
```

**Output**

```json
{
  "match": [
    {
      "msg": "Failed login attempts detected in /var/log/auth.log"
    }
  ]
}
```

</details>

<details>

<summary>Example 2: Detect suspicious passwords</summary>

**Code**

```json
{
  "/etc/passwd": {
    "content": "root:x:0:0:root:/root:/bin/bash\nuser1:*:1001:1001:User One:/home/user1:/bin/bash\n",
    "metadata": {
      "file_type": "file",
      "gid": 1001,
      "last_modified": 1737292449,
      "permissions": 644,
      "size": 100,
      "uid": 1002
    },
    "path": "/etc/passwd"
  }
}
```

**Script**

```rego
package panw.compliance

import rego.v1

match contains {"msg": msg} if {
  passwdFile := input["/etc/passwd"]
  passwdFile.metadata.file_type == "file"
  passwdFile.metadata.permissions == 644
  passwdFile.metadata.size < 200
  contains(passwdFile.content, ":*:")
  msg := "Empty or suspicious password detected in /etc/passwd"
}
```

**Output**

```json
{
  "match": [
    {
      "msg": "Empty or suspicious password detected in /etc/passwd"
    }
  ]
}
```

</details>

<details>

<summary>Example 3: Detect weak shadow passwords</summary>

**Code**

```json
{
  "/etc/shadow": {
    "content": "root:$6$abc123$abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123abc123:17542:0:99999:7:::",
    "metadata": {
      "file_type": "file",
      "gid": 1001,
      "last_modified": 1737292449,
      "permissions": 640,
      "size": 100,
      "uid": 1002
    },
    "path": "/etc/shadow"
  }
}
```

**Script**

```rego
package panw.compliance

import rego.v1

match contains {"msg": msg} if {
  shadowFile := input["/etc/shadow"]
  shadowFile.metadata.file_type == "file"
  shadowFile.metadata.permissions != 600
  shadowFile.metadata.size > 30
  contains(shadowFile.content, "::")
  msg := "Empty or weak password detected in /etc/shadow"
}
```

**Output**

```json
{
  "match": [
    {
      "msg": "Empty or weak password detected in /etc/shadow"
    }
  ]
}
```

</details>

**Kubernetes Connector settings**

**Kubernetes Resources**

From the drop-down, select one or more resource types:

* **Namespaces**: Logical partitions that isolate and organize cluster resources.
* **ReplicaSets**: Ensures a specified number of pod replicas run at all times.
* **Deployments**: Manages pod replicas through declarative ReplicaSet updates, rollouts, and rollbacks.
* **StatefulSets**: Deploys stateful applications with persistent identity and storage.
* **DaemonSets**: Ensures a pod copy runs on all or selected nodes.
* **Jobs**: Runs one-time or short-lived workloads that terminate after completion.
* **CronJobs**: Defines jobs that run at scheduled times or intervals.
* **ClusterRoles**: Defines cluster-level permissions across all namespaces.
* **Roles**: Defines permissions within a specific namespace.
* **RoleBindings**: Associates a role with users, groups, or service accounts in a namespace.
* **ClusterRoleBindings**: Associates a cluster role with users, groups, or service accounts cluster-wide.
* **NetworkPolicies**: Controls communication between pods and network entities.
* **Services**: Exposes a set of pods as a network service.
* **ServiceAccounts**: Provides a pod identity for Kubernetes API authentication.
* **Endpoints**: Represents pod network addresses that back a service.
* **Ingresses**: Manages external service access, HTTP/HTTPS routing, and load balancing.
* **ConfigMaps**: Stores non-sensitive configuration data as key-value pairs.
* **Secrets**: Securely stores sensitive data, such as API keys and certificates.
* **Nodes**: Defines the physical or virtual machines that run cluster workloads.

**Define the Rule (Rego)**

All custom Rego policies in Cortex must follow this pattern:

```rego
package panw.compliance

import rego.v1

match contains {"msg": msg} if {
    # Your detection logic here
    msg := "Description of the finding"
}
```

The custom rule must use the `match` term. Do not use `deny` or other terms.

**XDR Agent settings**

| **Field**                    | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Custom Code Execution**    | <p>Enable this setting for the scanner to perform custom compliance checks by executing user-defined Python scripts.</p><blockquote><p><strong>Note:</strong><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</li></ul></blockquote><p>Click Confirm to accept the following terms:</p><ul><li>The Python scripts you provide will be executed in your cloud environment(s).</li><li>This capability is solely for the purpose of enabling you to define the compliance check rules for your cloud environment(s). Any other purposes are expressly prohibited.</li><li>Any actions involving WRITE, MODIFY, or DELETE operations of your cloud environment(s) are strictly prohibited. It is your responsibility to ensure that your custom Python scripts only perform read-only operations of your cloud environment(s) explicitly for compliance check purposes.</li><li>You are solely responsible for the quality, content, use, and execution results of your Python script. You assume all risks and liabilities arising from executing your Python script(s), including any potential errors, damages, or consequences resulting from its use.</li></ul><p>After you confirm accepting the terms, the rest of the XDR Agent settings appear.</p> |
| **Operating System**         | <p>The operating system targeted by the rule. The available options are:</p><ul><li>Linux</li><li>Windows</li></ul>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| **Define the Rule (Python)** | <p>Use Python to define the custom detection logic.</p><p>This section supports syntax highlighting and validation (IntelliSense) to help users create accurate and efficient rules.</p><p>Use the default code in this box as a reference or starting point.</p><blockquote><p>The custom Python scripts are intended to be executed exclusively for compliance checks and validations. To ensure the scripts are used properly and no security risks or unintended changes occur, the system implements the following restrictions and safeguards:</p><ul><li>Only a predefined set of Python libraries and functions required for compliance checks are available for use. Libraries or functions that enable writing, deleting, or creating operations are excluded.</li><li>Only authorized users with specific permissions can create or update custom scripts. This ensures that only trusted individuals can define compliance checks.</li></ul></blockquote>                                                                                                                                                                                                                                                                                                                                                                                                                                            |

### Finalize the rule

#### Compliance Violation Severity

For Compliance Violation Severity, define the severity level of the compliance violation to ensure proper categorization and prioritization. Possible values are:

* Critical
* High
* Medium
* Low
* Informational

#### Compliance Controls

For Compliance Controls, assign the rule to one or more existing compliance controls.

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

1. Click Add.
2. Select a custom compliance control from the list.
3. Click Assign.

#### Remediation

For Remediation, you can optionally define the remediation steps to address any detected misconfiguration.

#### Create

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

### Use the rule

#### 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. For more information, see Monitor and track compliance adherence.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
