<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Elastic Security Labs - Articles by Kseniia Ignatovych</title>
        <link>https://www.elastic.co/security-labs</link>
        <description>Trusted security news &amp; research from the team at Elastic.</description>
        <lastBuildDate>Fri, 05 Jun 2026 16:44:27 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>Elastic Security Labs - Articles by Kseniia Ignatovych</title>
            <url>https://www.elastic.co/security-labs/assets/security-labs-thumbnail.png</url>
            <link>https://www.elastic.co/security-labs</link>
        </image>
        <copyright>© 2026. elasticsearch B.V. All Rights Reserved</copyright>
        <item>
            <title><![CDATA[From plain English to production rule: AI-native Elasticsearch ES|QL detection in Elastic Security]]></title>
            <link>https://www.elastic.co/security-labs/ai-esql-detection-rule-creation</link>
            <guid>ai-esql-detection-rule-creation</guid>
            <pubDate>Mon, 04 May 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Elastic Security now lets analysts describe a threat behavior in plain language and receive a complete, validated Elasticsearch ES|QL detection rule in return, no query expertise required.]]></description>
            <content:encoded><![CDATA[<p>Elastic Security now includes AI-powered detection rule creation, built into the rule creation workflow. Analysts describe a threat behavior in plain English and receive a complete, validated Elasticsearch Query Language (ES|QL) rule in return, with MITRE ATT&amp;CK mappings, severity recommendations, and a preview against live data, all without leaving the platform or writing a single line of query syntax. This post walks through exactly how that works using an Okta credential stuffing and account takeover scenario as the example.</p>
<h2>Why detection engineering needs AI-native tooling</h2>
<p>The threat landscape has changed. Attackers are increasingly using AI to automate and scale their operations: generating <a href="https://hoxhunt.com/guide/phishing-trends-report">phishing campaigns at volume</a>, accelerating <a href="https://www.rapid7.com/blog/post/tr-accelerating-attack-cycle-2026-global-threat-landscape-report/">vulnerability research and exploitation</a>, and launching credential attacks that would have required significant manual effort just a few years ago. The result is a faster, higher-volume threat environment where the window between a new attack pattern emerging and it hitting your environment is narrowing.</p>
<p>Detection engineering teams are on the other side of that equation. The expectation is that coverage keeps pace with the threat, but the tooling available to write, test, and deploy rules hasn’t historically matched the speed at which new attack patterns appear. Writing an effective detection rule from scratch requires deep familiarity with the query language, the field schema, and the aggregation logic needed to express the behavior you are trying to catch, before you even begin thinking about the threat itself. For most security teams, that friction means a growing backlog and gaps in coverage that attackers can exploit.</p>
<p>Arming detection engineers with native, AI-powered tooling isn’t just about convenience; it’s also about keeping pace with an adversary that’s already using AI to move faster. Elastic Security is now adding AI rule creation, powered by the <a href="https://www.elastic.co/docs/explore-analyze/ai-features/elastic-agent-builder">Elastic Agent Builder</a>. Unlike external AI tooling or stand-alone code generation workflows, this capability is built into the detection engineering experience: The rule is created and validated, with results preview generated entirely within your platform, against your own data, without leaving Elastic Security. Analysts can now describe what they want to detect in natural language and receive a complete, ready-to-review ES|QL rule in return, without leaving the rule creation workflow. This capability is available at the Enterprise license tier.</p>
<p>Support for ES|QL rule creation is available now. Additional rule types are on the roadmap, so keep an eye on upcoming releases as these capabilities expand.</p>
<h2>Detections without the heavy lifting</h2>
<p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/esql-language.html">ES|QL</a>, Elastic's pipeline query language, is very helpful for behavioral and aggregation-based detections. Its pipe-based syntax makes it natural to express the kind of &quot;filter, count, group by, threshold&quot; logic that underlies most modern detections: How many failed logins came from this IP? Which accounts were targeted? Does this count exceed the expected baseline?</p>
<p>That same expressiveness is also what makes ES|QL harder to write by hand than a simple field-match query. You need to think in terms of pipelines: Filter first with <code>WHERE</code>, aggregate with <code>STATS...BY</code> , and then filter again on the computed values. It requires knowing the right Elastic Common Schema (ECS) field names, the correct function syntax, and how the pipeline stages interact. This is exactly the kind of structured, pattern-based logic that AI can translate reliably from a plain English description.</p>
<p>With the new detection engineering <a href="https://www.elastic.co/security-labs/skills-elastic-security-9-4">skills</a> and the knowledge of Elastic documentation, ECS field definitions, and local data access, the <a href="https://www.elastic.co/docs/explore-analyze/ai-features/agent-builder/builtin-agents-reference">Elastic AI Agent </a>uses detection engineering best practices to come up with the rule, and moreover, the generated rule query is validated before it’s returned: What you see in the editor will run.</p>
<h2>Walkthrough: Detecting Okta credential stuffing and account takeover</h2>
<p>A credential stuffing attack that succeeds in breaching an account doesn’t stop at the login. The full attack chain (multifactor authentication [MFA] bypass, session establishment, privilege escalation, and policy modification) leaves a distinct footprint across Okta system logs if you know what to correlate. This is exactly the kind of multistage behavioral pattern that ES|QL handles well: Collect all the relevant event types, classify each one, aggregate by the shared identity attributes, and then apply threshold logic that requires the full sequence to be present before alerting.</p>
<p>Writing that query manually means knowing the Okta-specific <a href="https://developer.okta.com/docs/reference/api/event-types/">event action names</a>, knowing how to use <code>EVAL</code> with <code>CASE</code> to create per-event type flags, and how to then aggregate those flags with <code>SUM</code> to count each stage independently. It’s a realistic but nontrivial query, exactly the kind that benefits most from AI generation.</p>
<p>Imagine your team has<a href="https://www.elastic.co/docs/reference/integrations/okta"> an Okta integration</a> and logs are coming in. Threat intelligence has flagged an active campaign targeting Okta tenants: automated credential stuffing followed by MFA fatigue and post-compromise privilege changes. You need detection coverage today. </p>
<p>Note: We’re skipping the step of checking whether prebuilt detection rules exist or are already enabled, for the simplicity of the scenario here.</p>
<h3>Opening the AI Agent rule creation flow</h3>
<p>From the Elastic Security sidebar, navigate to <strong>Detection rules</strong> and click <strong>Create a rule -&gt; AI rule creation</strong>. </p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-creation.png" alt="New AI rule creation option" title="A screenshot of the Elastic Security detection rules page showing options to create a rule, including AI rule creation and manual rule creation, along with navigation tabs for installed rules, rule monitoring, and rule updates." /></p>
<h3>Describing the detection in plain language</h3>
<p>No special syntax is required. Describe the full attack chain the way you would explain it to a colleague, including the data source and the specific event sequence you want to match:</p>
<p>Analyst prompt:</p>
<p><code>In Okta, detect when the same user and source IP shows: three or more failed logins due to bad credentials, at least one MFA failure, then a successful login, and then either a privilege grant or a policy update. That full sequence together is a credential stuffing attack that succeeded.</code></p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/threat-agent.png" alt="AI Agent panel open with the rule creation prompt." title="A screenshot of Elastic Security showing installed Okta credential‑stuffing detection rules on the left and a Threat Hunting Agent chat panel on the right with a prompt describing the sequence of events that should trigger a credential‑stuffing detection rule." /></p>
<p>The AI Agent processes this against its knowledge base, including Okta integration field mappings and ECS conventions, and executes multiple steps that we can follow and review:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-reasoning.png" alt="AI Agent panel open showing the agent reasoning steps." title="A screenshot of Elastic Security showing a list of Okta credential‑stuffing detection rules on the left and a detailed reasoning panel on the right that outlines the steps taken by an AI agent to generate an ES|QL detection rule, including reading files, generating the query, creating the rule name and description, and selecting tags." /></p>
<p>And then it returns a complete ES|QL rule that covers the full attack sequence described.</p>
<h3>Reviewing and adjusting the generated rule logic</h3>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-panel.png" alt="Resulting rule in the AI Agent panel and button to apply." title="A screenshot of an Elastic Security panel showing the completed ES|QL detection rule for an Okta credential‑stuffing attack, including the rule description, detection logic, tags, severity, risk score, interval, and lookback time, with a button to apply the rule." /></p>
<p>There’s a lot happening in this rule’s query, and it’s worth understanding each stage, because the structure itself tells the story of the attack chain.</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/query-preview.png" alt="Expanded generated ES|QL rule query preview." title="A screenshot showing an expanded ES|QL query preview for an Okta credential‑stuffing detection rule, displaying the full query with counts for failed logins, MFA failures, successful logins, and post‑compromise events, along with the final filtered and kept fields." /></p>
<p>The query is concise by design: It uses ES|QL's inline <code>WHERE</code> filtering inside <code>COUNT()</code> to compute each stage of the attack chain in a single <code>STATS</code> pass, without needing a separate <code>EVAL</code> block. Here’s what each part does:</p>
<p><code>FROM logs-okta*</code> scopes the query to all Okta log indices, using a wildcard that picks up <code>logs-okta.system-*</code> and any other Okta data streams in the environment.</p>
<p>The <code>STATS</code> block is the core of the detection. It aggregates all Okta activity and computes four counters per unique combination of <code>user.name</code> and <code>source.ip</code>, one for each stage of the attack chain. <code>failed_logins</code> counts <code>user.session.start</code> events with <code>outcome: failure</code> (the password spray attempts). <code>mfa_failures</code>counts failed MFA challenges, indicating the attacker encountered a second factor and attempted to push through it.</p>
<p><code>successful_logins</code> counts <code>user.session.start</code> events with <code>outcome: success</code>; a value of one or more means the attacker got in. <code>post_compromise_events</code> counts any of six actions that indicate the attacker is acting on their objective after login: adding the account to a group, granting application access, escalating privileges, modifying a policy lifecycle, updating a policy rule, or changing the account profile. This is a broad net that covers the full range of post-compromise behavior seen in Okta account takeover incidents.</p>
<p>The <code>WHERE</code> clause after the aggregation requires all four conditions to be true simultaneously before a row becomes an alert. This is what makes the rule high-fidelity. A user who forgot their password and eventually logged in won’t match because they’ll have no post-compromise events. An attacker who got through but took no further action won’t match either. All four stages must be present.</p>
<p>The <code>KEEP</code> statement trims the output to the six fields that matter for triage (the targeted account, the source IP, and the count for each stage), giving the responding analyst everything they need to start an investigation without querying the raw logs first.</p>
<p>Along with the query, the AI Agent generates the following rule metadata: rule name, description, severity and risk score recommendations, MITRE ATT&amp;CK technique and tactic mapping (T1110.004 Credential Stuffing, T1078 Valid Accounts, ), execution schedule, and tags. Where other rules exist, the AI Agent also reuses relevant tags from those rules, so new custom rules stay consistent with your existing detection library from the start. The data source is selected from indexes available in the system, or data ingestion is suggested. The rule fields are editable with an AI Agent before or after filling the resulting rule information in the rule creation form.</p>
<p><strong>Tip:</strong> You can also ask the AI Agent to explain an existing rule query, suggest threshold adjustments based on a description of your environment, or help troubleshoot unexpected results.</p>
<p>Let’s keep working on the rule to adjust a few things. We want to ensure the rule detects credential stuffing and not other failure reasons, like expired passwords or locked accounts. We want to ensure the attack sequence is preserved.</p>
<p>Using AI Agent, we’ll ask it to fix these few things. It comes back with the adjusted query and summarizes what it did.</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/logic-refinement.png" alt="AI Agent panel with additional refinement prompt and results." title="A screenshot of an Elastic Security rule editor showing an ES|QL rule definition on the left and an AI Agent panel on the right that provides additional refinement guidance for credential‑stuffing detection logic, including explanations of filtering failed logins and improving event specificity." /></p>
<p>We now apply the changes to the rule form from the AI Agent chat:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-changes.png" alt="AI Agent panel with summary of suggested rule changes." title="A screenshot of an AI Agent panel summarizing suggested updates to an Okta credential‑stuffing detection rule, including filters for invalid‑credential failures and a four‑stage ordered sequence for failure, MFA failure, successful login, and post‑compromise activity." /></p>
<h3>Previewing and enabling the rule</h3>
<p>Before enabling, use the Preview rule results panel to run the query against recent data in your environment. Any existing matches will surface immediately, running against your actual Okta log data in your Elastic deployment (no sample data, no sandbox, no external validation step required), useful both for validating that the query logic is correct and for checking whether an attack may already be in progress in your Okta tenant.</p>
<p>In this example, we’ve added sample logs to get a single alert generated:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-preview.png" alt="Rule editing view with Preview results, along with open AI Agent panel." title="A screenshot of an Elastic Security rule editing view showing an ES|QL query and preview results on the left, with an AI Agent panel on the right providing additional guidance for refining credential‑stuffing detection logic." /></p>
<p>Now, satisfied with the results, we’ll enable the rule. It will begin executing on its configured schedule and generate alerts for any user and source IP combination where the full attack sequence is observed within the query window.</p>
<p>If we execute the rule manually for the past week to find any past attacks and check resulting alerts, we see the same alert we’ve gotten in the Rule Preview.</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/rule-alerts.png" alt="Rule Alerts view." title="A screenshot of an Elastic Security rule alerts view showing an open alert for an Okta credential‑stuffing and account‑takeover rule, including a trend graph stacked by user name and a table listing the alert’s timestamp, rule name, severity, risk score, and reason." /></p>
<p><strong>Note:</strong> AI-generated rules should be reviewed before deployment in production environments. The AI Agent may not have full awareness of your specific data schema, log source quirks, or environment-specific baseline behavior. Use the rule preview to validate against your actual data before enabling. </p>
<h2>Impact on detection engineering workflows</h2>
<p>The walk-through above, from opening the rule creation form to having a validated, multistage, MITRE-mapped ES|QL rule covering the full Okta account takeover chain, takes a few minutes. Writing the same query manually would require knowing the Okta-specific event action names, the correct <code>okta.outcome.reason</code> field and its enumerated values, how to structure <code>EVAL</code> with <code>CASE</code> to produce per-stage flags, how to aggregate those flags with <code>SUM</code> rather than <code>COUNT</code>, and how to express a compound post-compromise condition using <code>OR</code> across two aggregated fields. For an analyst onboarding a new data source under time pressure, that’s a significant amount of context to hold simultaneously.</p>
<p>The AI Agent doesn’t replace detection expertise. The analyst still makes every meaningful decision: which event types constitute the attack chain, what thresholds make sense for their environment, and whether the preview results look correct. What changes is the time it takes to get from having threat knowledge to having a working rule. Engineers who understand the attack and can describe it iterate and get a production-quality query back quicker, rather than spending time on implementation mechanics.</p>
<p>This matters most at the moments when speed is most critical: when a new campaign is active, when a data source has just been onboarded, or when an existing rule needs rapid refinement because the threat has evolved. AI-powered attackers aren’t waiting for your rule backlog to clear. Detection engineering tooling shouldn’t require it either.</p>
<h2>What's next</h2>
<p>AI rule creation for ES|QL is the first step in a broader expansion of AI Agent-driven detection engineering in Elastic Security. ES|QL was the natural starting point given its aggregation-first pipeline structure, which maps cleanly to the behavioral descriptions analysts naturally provide. Support for additional rule types and additional quality of life rule creation steps and beyond is on the roadmap. Keep an eye on the<a href="https://www.elastic.co/security-labs"> Elastic Security Labs</a> blog and release notes for updates as new capabilities become available.</p>
<p>For a broader look at how AI Agents are reshaping the detection engineering role, from threat modeling and telemetry tuning through to rule authoring and maintenance at scale, see<a href="https://www.elastic.co/security-labs/supercharge-your-soc"> Supercharge Your SOC: Detection Engineering in the Era of AI Agents</a> on Elastic Security Labs. For a comprehensive overview of the full detection engineering toolset available in Elastic Security today, including prebuilt rules, alert suppression, MITRE ATT&amp;CK coverage, and Detections as Code, see<a href="https://www.elastic.co/blog/elastic-security-detection-engineering"> Know your tools: The full range of Elastic Security's detection engineering capabilities</a>.</p>
<p>Try the new AI rule creation capability on your deployment, or<a href="https://www.elastic.co/cloud/cloud-trial-overview/security"> start a free trial</a>. Connect with us on<a href="https://join.slack.com/t/elasticstack/shared_invite/zt-2sgssfr0n-NhTOlSwHbaGH85tYfx6kGg"> Elastic's community Slack</a> to share feedback or tell us what detection use cases you’re building and how we can help.</p>
<p><em>The release and timing of any features or functionality described in this post remain at Elastic's sole discretion. Any features or functionality not currently available may not be delivered on time or at all.</em></p>
<p><em>In this blog post, we may have used or referred to third-party generative AI tools, which are owned and operated by their respective owners. Elastic does not have any control over the third-party tools and we have no responsibility or liability for their content, operation or use, nor for any loss or damage that may arise from your use of such tools. Please exercise caution when using AI tools with personal, sensitive or confidential information. Any data you submit may be used for AI training or other purposes. There is no guarantee that information you provide will be kept secure or confidential. You should familiarize yourself with the privacy practices and terms of use of any generative AI tools prior to use.</em></p>
<p><em>Elastic, Elasticsearch, ESRE, Elasticsearch Relevance Engine and associated marks are trademarks, logos or registered trademarks of Elasticsearch N.V. in the United States and other countries. All other company and product names are trademarks, logos or registered trademarks of their respective owners.</em></p>
]]></content:encoded>
            <category>security-labs</category>
            <enclosure url="https://www.elastic.co/security-labs/assets/images/ai-esql-detection-rule-creation/cover.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Managing Elastic Security Detection Rules with Terraform]]></title>
            <link>https://www.elastic.co/security-labs/managing-rules-with-terraform</link>
            <guid>managing-rules-with-terraform</guid>
            <pubDate>Fri, 13 Mar 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Learn to define and deploy Elastic Security detection rules and exceptions using the Elastic Stack Terraform Provider vs detection-rules repository DaC capabilities.]]></description>
            <content:encoded><![CDATA[<p>At the core of Elastic Security lie <a href="https://www.elastic.co/blog/elastic-security-detection-engineering">outstanding detection capabilities</a>, allowing users to <a href="https://www.elastic.co/blog/elastic-security-building-effective-threat-hunting-detection-rules">create</a>, test, tune, manage, deploy detection rules, as code, in their environments. The ability to create robust detections is critical for Security Operations as detection logic elevates threat signal from the telemetry noise.</p>
<p>This article highlights how Elastic's new Terraform resources for security detection rules and exceptions expand practitioners' capabilities for detection-as-code deployment. Below you will find examples of defining and deploying your detection artifacts in Elastic Security with Terraform. We will also show how you can use Elastic's AI Agent to help quickly create the Terraform configuration for your custom rules. Finally, it also provides guidance on when to use the Elastic Stack Terraform <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_detection_rule">provider</a> versus <a href="https://github.com/elastic/detection-rules/blob/main/README.md#detections-as-code-dac">tools from the detection-rules repository</a>.</p>
<h2>Managing Elastic with Terraform</h2>
<p><a href="https://developer.hashicorp.com/terraform">Terraform is</a> a tool created by HashiCorp (now IBM) to manage infrastructure in the cloud, or in self-managed environments, as code. With a simple stroke of HCL (HashiCorp configuration language), users can define the desired state of their cloud provider infrastructure, application, configuration, and in Elastic’s case, cluster settings, configuration, indices or streams, and now also detection rules and alerts, as fully configurable, traceable, and reviewable code in your favorite source management tool.</p>
<p>The <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_detection_rule">Elastic Stack Terraform provider</a> helps search, observability, and security professionals, as well as DevOps and SREs, configure their Elastic clusters with the right indices and mappings for their search use cases, SLOs or Fleet policies for their observability use case, and now, detection rules, alerts, and exceptions for their security use case. It can easily configure those, and many more objects and settings in the Elastic Stack.</p>
<h2>Security Detection rules - now as code with Terraform</h2>
<p>With <a href="https://github.com/elastic/terraform-provider-elasticstack/releases/tag/v0.12.0">V0.12.0</a> and <a href="https://github.com/elastic/terraform-provider-elasticstack/releases/tag/v0.13.0">V0.13.0</a> of the <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_detection_rule">Elastic Stack Terraform provider,</a> users can now manage their Detection rules and rule exceptions using Terraform. This is especially useful for users who have already been managing their Elastic deployments with Terraform and want to extend it to Detection rules.</p>
<h3>Using the Elastic Stack Terraform Provider to deploy Rules and Exceptions</h3>
<p>Let's look at an example of using the Elastic Stack Terraform Provider to deploy an Elastic Security Rule. In this example, we want to detect Windows Service Accounts that are performing an interactive logon on a host.</p>
<p>Service accounts typically have elevated privileges and rarely-rotated passwords, making them high-value targets for attackers. Since these accounts should only perform automated service logons, an interactive logon can indicate credential theft or misuse.</p>
<p>The first thing we need to think of is what telemetry we need to see which logons are happening on our host. <a href="https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/auditing/event-4624">Logon events</a> are logged by the Windows Local Security Authority Subsystem Service (LSASS) whenever a logon session is successfully created on the machine. We can pick this up via an Elastic Agent with the <a href="https://www.elastic.co/docs/reference/integrations/windows">Windows Integration</a> installed.</p>
<p>The data will be written by the Elastic Agent into the system.security Data Stream, we can match it with this index pattern: <code>logs-system.security-*.</code> We also know that Logon events generate event code <code>4624</code> and that, in our example, the service account name starts with <code>svc</code> or ends with <code>$</code>.  In addition, an interactive login will have a logon type of <code>interactive</code>.</p>
<p>So, we can match these events with an <a href="https://www.elastic.co/docs/reference/query-languages/esql">ES|QL</a> rule like:</p>
<pre><code class="language-sql">FROM logs-system.security-\*  
| WHERE event.code \== &quot;4624&quot; AND (user.name LIKE &quot;svc\_\*&quot; OR user.name LIKE &quot;svc-\*&quot;  
     OR user.name LIKE &quot;\*\_svc&quot; OR user.name LIKE &quot;\*$&quot;)  
     AND winlog.logon.type IN (&quot;Interactive&quot;, &quot;RemoteInteractive&quot;,  
         &quot;CachedInteractive&quot;, &quot;CachedRemoteInteractive&quot;)  
</code></pre>
<p>There may be situations where we don't want this rule to run, for example, if there is a legacy application that we want to permit interactive logons from. So, we can create an <a href="https://www.elastic.co/docs/solutions/security/detect-and-alert/rule-exceptions">Exception Item</a>, like: <code>user.name IS svc\_sqlbackup</code>.</p>
<p>Now that we know what we want the Rule and its Exceptions to look like, we can use the Terraform provider's <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_detection_rule">elasticstack_kibana_security_detection_rule</a>, <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_exception_list">elasticstack_kibana_security_exception_list</a>, and <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs/resources/kibana_security_exception_item">elasticstack_kibana_security_exception_item</a> resources to define them in code.</p>
<p>Turning ES|QL rules into Terraform's configuration syntax, <a href="https://developer.hashicorp.com/terraform/language/syntax/configuration">HCL</a>, is a great use case for Elastic's <a href="https://www.elastic.co/docs/solutions/security/ai/agent-builder/agent-builder">AI Agent</a>.<br />
Elastic AI Agent capabilities help accelerate security operations across a wide range of tasks - from <a href="https://www.elastic.co/security-labs/speeding-apt-attack-discovery-confirmation-with-attack-discovery-workflows-and-agent-builder">alerts triage and incident response</a> to helping with detection lifecycle tasks.</p>
<p>Simply open AI Agent, and ask it to create Terraform configurations based on your query and exceptions.</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/managing-rules-with-terraform/image2.png" alt="" /></p>
<p>You should end up with something like this:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/managing-rules-with-terraform/image1.png" alt="" /></p>
<p>Here's a closer look at the code.</p>
<p>There are a few elements to call out specifically:</p>
<ul>
<li><code>type</code>: The type of exception list. For example: detection, endpoint, or endpoint_trusted_apps</li>
<li><code>namespace_type</code>: Determines whether the exception list is available in all Kibana spaces or just the single space in which it was created.</li>
</ul>
<pre><code>resource &quot;elasticstack_kibana_security_exception_list&quot; &quot;svc_account_interactive_login&quot; {
  list_id        = &quot;svc-account-interactive-login-exceptions&quot;
  name           = &quot;Service Account Interactive Login Exceptions&quot;
  description    = &quot;Documented exceptions for service accounts that legitimately require interactive logon&quot;
  type           = &quot;detection&quot;
  namespace_type = &quot;single&quot;
  tags           = [&quot;service-accounts&quot;,&quot;windows&quot;,&quot;authentication&quot;]
}  
</code></pre>
<p>This creates a new exception list.</p>
<p>Of note, the <code>entries</code> array contains the conditions under which the exception applies.</p>
<pre><code>resource &quot;elasticstack_kibana_security_exception_item&quot; &quot;svc_sqlbackup&quot; {
  list_id        = elasticstack_kibana_security_exception_list.svc_account_interactive_login.list_id
  item_id        = &quot;svc-sqlbackup-exception&quot;
  name           = &quot;svc_sqlbackup - Legacy SQL Backup Agent&quot;
  description    = &quot;Approved exception: Legacy SQL backup agent requires interactive logon per vendor documentation.&quot;
  type           = &quot;simple&quot;
  namespace_type = &quot;single&quot;
  tags           = [&quot;sql&quot;,&quot;backup&quot;,&quot;approved&quot;]
entries = [
    {
      field    = &quot;user.name&quot;
      type     = &quot;match&quot;
      operator = &quot;included&quot;
      value    = &quot;svc_sqlbackup&quot;
    }
  ]
} 
</code></pre>
<p>This adds our exception: that we don't want the rule to run if the username is <code>svc\_sqlbackup</code>.</p>
<p>Of note, the elements from <code>enabled</code> to the <code>technique</code> array are examples of the other properties that can be set on a rule.</p>
<pre><code>resource &quot;elasticstack_kibana_security_detection_rule&quot; &quot;svc_account_interactive_login&quot; {
  name        = &quot;Service Account Interactive Login&quot;
  description = &lt;&lt;-EOT
    Detects interactive logins by service accounts. Service accounts should authenticate
    via service (Type 5) or batch (Type 4) logon types, not interactively. Interactive
    logins by service accounts may indicate credential theft or misuse.

    This rule identifies service accounts by common naming conventions (svc_*, svc-*,
    *_svc) and managed service accounts (*$).
  EOT

  type     = &quot;esql&quot;
  language = &quot;esql&quot;
  query    = &lt;&lt;-EOT
    FROM logs-system.security-* metadata _id, _version, _index
    | WHERE event.code == &quot;4624&quot;
      AND (user.name LIKE &quot;svc_*&quot; OR user.name LIKE &quot;svc-*&quot; OR user.name LIKE &quot;*_svc&quot; OR user.name LIKE &quot;*$&quot;)
      AND winlog.logon.type IN (&quot;Interactive&quot;, &quot;RemoteInteractive&quot;, &quot;CachedInteractive&quot;, &quot;CachedRemoteInteractive&quot;)
    | KEEP @timestamp, host.name, user.name, user.domain, winlog.logon.type, source.ip, _id, _version, _index
  EOT

  enabled    = true 
  severity   = &quot;high&quot;
  risk_score = 73

  from     = &quot;now-6m&quot;
  to       = &quot;now&quot;
  interval = &quot;5m&quot;

  author  = [&quot;Security Team&quot;]
  license = &quot;Elastic License v2&quot;
  tags    = [
    &quot;Domain: Endpoint&quot;,
    &quot;OS: Windows&quot;,
    &quot;Use Case: Identity and Access Audit&quot;,
    &quot;Tactic: Initial Access&quot;,
    &quot;Data Source: Windows Security Event Log&quot;
  ]

  false_positives = [
    &quot;Service accounts with documented exceptions that require interactive logon&quot;,
    &quot;Break-glass procedures during incident response&quot;,
    &quot;Initial service account configuration or troubleshooting&quot;
  ]

  references = [
    &quot;https://learn.microsoft.com/en-us/entra/architecture/service-accounts-on-premises&quot;,
    &quot;https://blog.quest.com/10-microsoft-service-account-best-practices/&quot;,
    &quot;https://attack.mitre.org/techniques/T1078/002/&quot;
  ]

  threat = [
    {
      framework = &quot;MITRE ATT&amp;CK&quot;
      tactic = {
        id        = &quot;TA0001&quot;
        name      = &quot;Initial Access&quot;
        reference = &quot;https://attack.mitre.org/tactics/TA0001/&quot;
      }
      technique = [
        {
          id        = &quot;T1078&quot;
          name      = &quot;Valid Accounts&quot;
          reference = &quot;https://attack.mitre.org/techniques/T1078/&quot;
          subtechnique = [
            {
              id        = &quot;T1078.002&quot;
              name      = &quot;Domain Accounts&quot;
              reference = &quot;https://attack.mitre.org/techniques/T1078/002/&quot;
            }
          ]
        }
      ]
    }
  ]

  exceptions_list = [
    {
      id             = elasticstack_kibana_security_exception_list.svc_account_interactive_login.id
      list_id        = elasticstack_kibana_security_exception_list.svc_account_interactive_login.list_id
      namespace_type = elasticstack_kibana_security_exception_list.svc_account_interactive_login.namespace_type
      type           = elasticstack_kibana_security_exception_list.svc_account_interactive_login.type
    }
  ]
}
</code></pre>
<p>Finally, we define the rule, including the ES|QL query we provided earlier and MITRE ATT&amp;CK classification.</p>
<p>You can add these resource definitions into one configuration file (perhaps security-rules.tf), add it to your <a href="https://registry.terraform.io/providers/elastic/elasticstack/latest/docs#kibana">configured</a> Elastic Stack terraform directory, and then run the `terraform apply` command and parameter to deploy the Rule.</p>
<pre><code class="language-shell">terraform apply --auto-approve
</code></pre>
<p>Since <code>terraform apply</code> runs a plan before making changes, it will automatically detect if anyone has edited a rule directly in Kibana and show you exactly what drifted: no manual exports or diffs needed.</p>
<p>After Terraform has made the changes, we can see the Rule in Kibana:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/managing-rules-with-terraform/image5.png" alt="" /></p>
<p>We can also see the Exception List:</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/managing-rules-with-terraform/image4.png" alt="" /></p>
<p>This way, you can define your detections in Terraform and benefit from automatic deployment along with other objects you manage with Terraform.</p>
<h2>Terraform workspaces for multi-space Elastic deployments</h2>
<p>Terraform uses a concept called “<a href="https://developer.hashicorp.com/terraform/language/state/workspaces">workspaces</a>” allowing you to reuse the same infrastructure code for multiple deployments, for example, a dev, testing, and production environment. This concept is useful for managing rules across multiple deployments and/or Kibana spaces.</p>
<h2>Managing detections with Terraform and Detections as code</h2>
<p>Elastic also has <a href="https://www.elastic.co/security-labs/detection-as-code-timeline-and-new-features">Detections as Code functionality</a> available via our open <a href="https://github.com/elastic/detection-rules">detection-rules repository.</a></p>
<p>The two tools have complementary strengths and are aligned with different user profiles and workflow stages for implementing Detections as Code.</p>
<h3>Detection as Code features in detection-rules</h3>
<ul>
<li><strong>Best fit user profile</strong>: Detection engineers</li>
<li><strong>Intended workflow phase</strong>: Rule authoring and validation</li>
</ul>
<p>With dual-sync between your GitHub repo and Kibana, linting, schema validation, and unit-testing, detection-rules functionality is well-suited to experienced Detection Engineers comfortable with Git-based version control.</p>
<h3>Elastic Stack Terraform Provider</h3>
<ul>
<li><strong>Best fit user profile</strong>: DevOps engineers / Platform teams</li>
<li><strong>Intended workflow phase</strong>: Deployment and operations</li>
</ul>
<p>For users already using Terraform to manage their Elastic clusters, the Terraform Provider is a great fit, bringing consistency to all &quot;x-as-code&quot; operations and familiar state management and parameterization.</p>
<p>The key differences and optimal use cases for each tool are detailed in the comparison table below:</p>
<table>
<thead>
<tr>
<th align="left">Workflow Stage</th>
<th align="left">detection-rules</th>
<th align="left">Terraform Provider</th>
<th align="left">Best Fit</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><strong>Rule Authoring</strong></td>
<td align="left">Purpose-built tooling: create-rule wizard, TOML schema, KQL/EQL validation, field checks against ECS, Kibana-to-code export.</td>
<td align="left">Standard HCL definitions; teams integrate their preferred validation tooling into existing pipelines.</td>
<td align="left"><strong>detection-rules:</strong> Detection engineers authoring and refining rules daily. Teams wanting to automatically convert rules from Kibana into code. <strong>Terraform:</strong> Teams already using Terraform in their workflows, or teams wanting to automate and deploy detection rules as code, but without an established CI/CD platform.</td>
</tr>
<tr>
<td align="left"><strong>Testing &amp; Validation</strong></td>
<td align="left">Built-in unit testing framework, schema validation, query validation, configurable test suites.</td>
<td align="left">Terraform tests for optional unit testing. No built-in query validation: the provider relies on the Kibana API to accept or reject rule definitions at apply time.</td>
<td align="left"><strong>detection-rules:</strong> Teams wanting out-of-the-box detection testing. <strong>Terraform:</strong> Platform teams managing rules as part of broader IaC with existing validation pipelines. Teams happy to write custom tests in Terraform.</td>
</tr>
<tr>
<td align="left"><strong>Exception Management</strong></td>
<td align="left">Native exception list handling; export/import with rules, TOML storage, and rule linking.</td>
<td align="left">Exception lists can be referenced via rule attributes.</td>
<td align="left"><strong>detection-rules:</strong> Teams managing exceptions as part of detection content. <strong>Terraform:</strong> Teams managing exceptions as separate infrastructure resources.</td>
</tr>
<tr>
<td align="left"><strong>Governance &amp; Drift Management</strong></td>
<td align="left">VCS-based with dual sync: push rules from repo to Kibana and export from Kibana back to repo, allowing either to serve as the source of truth. Drift detection is achievable with custom export-and-diff tooling.</td>
<td align="left">VCS-authoritative: state file enforces declared configuration.  Native drift detection: Terraform plan surfaces any out-of-band changes made in Kibana.</td>
<td align="left"><strong>detection-rules:</strong> Teams comfortable with Git-based workflows and flexible sync models. <strong>Terraform:</strong> Organisations requiring formal state reconciliation and audit trails.</td>
</tr>
<tr>
<td align="left"><strong>Rollback</strong></td>
<td align="left">Git history provides version control; re-import previous versions from the repo.</td>
<td align="left">Revert HCL configuration in Git and re-apply to restore the previous state.</td>
<td align="left"><strong>detection-rules:</strong> Teams using Git-centric recovery workflows. <strong>Terraform:</strong> Organisations with standardised rollback mechanisms across infrastructure and rulesets.</td>
</tr>
<tr>
<td align="left"><strong>Parameterisation &amp; Templating</strong></td>
<td align="left">Achievable with external preprocessing (Jinja2, etc.) before import.</td>
<td align="left">Native HCL features: variables, locals, for_each, dynamic blocks, and modules.</td>
<td align="left"><strong>detection-rules:</strong> Teams not requiring parameterisation or with existing templating solutions.  <strong>Terraform:</strong> Teams wanting native IaC parameterisation.</td>
</tr>
<tr>
<td align="left"><strong>Operational Integration</strong></td>
<td align="left">Focused tooling optimised for detection engineering workflows.</td>
<td align="left">Unified control plane managing detection rules alongside cloud infrastructure, network policies, and other security tooling.  Integrates with other resources that may be required by detections such as external connectors.</td>
<td align="left"><strong>detection-rules:</strong> Specialist detection teams. More flexible if dual-sync (Kibana and repo are both sources of truth).  <strong>Terraform:</strong> Platform teams managing Elastic as part of broader infrastructure.</td>
</tr>
</tbody>
</table>
<p>In short, Detection Engineers are better served by the specialized creation and testing tools provided in the <code>detection-rules</code> repository, while DevOps/Platform Teams should use the Terraform provider to manage detection rules as part of their broader infrastructure-as-code strategy for deployment and operations.</p>
<h2>Try it out</h2>
<p>To experience the full benefits of what Elastic has to offer for detection engineers, upgrade to 9.3 or start your Elastic Security <a href="https://cloud.elastic.co/registration">free trial</a>. Visit <a href="https://www.elastic.co/security">elastic.co/security</a> to learn more and get started.</p>
<p><em>The release and timing of any features or functionality described in this post remain at Elastic's sole discretion. Any features or functionality not currently available may not be delivered on time or at all.</em></p>
]]></content:encoded>
            <category>security-labs</category>
            <enclosure url="https://www.elastic.co/security-labs/assets/images/managing-rules-with-terraform/managing-rules-with-terraform.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[The Engineer's Guide to Elastic Detections as Code]]></title>
            <link>https://www.elastic.co/security-labs/detection-as-code-timeline-and-new-features</link>
            <guid>detection-as-code-timeline-and-new-features</guid>
            <pubDate>Wed, 04 Feb 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[This post details the latest evolution of Elastic Security's Detections as Code (DaC) framework, including its development timeline, current feature highlights, and tailored implementation examples.]]></description>
            <content:encoded><![CDATA[<p>In an ever-evolving threat landscape, security operations are reaching a tipping point. As the velocity and complexity of threats increase, teams expand and managed environments multiply. Commonly, manual approaches to rule management become a bottleneck. This is where Detections as Code (DaC) steps in, not just as a tool, but as a methodology.</p>
<p>DaC as a methodology applies software development practices to the creation, management, and deployment of security detection rules. By treating detection rules as code, it enables version control, automated testing, and deployment processes, enhancing collaboration, consistency, and agility in response to threats. DaC streamlines the detection rule lifecycle, ensuring high-quality detections through peer reviews and automated tests. This methodology also supports compliance with change management requirements and fosters a mature security posture.</p>
<p>That's why we’re excited to share the latest updates to Elastic's <a href="https://github.com/elastic/detection-rules">detection-rules</a>, our open repository for writing, testing, and managing security detection rules in Elastic, that also allows you to create your own <a href="https://dac-reference.readthedocs.io/en/latest/">Detections as Code (DaC) framework</a>. Continue reading for highlighted implementation examples using extended functionality, and the announcement of Elastic's free Detections as Code Workshop.</p>
<h1>Elastic Security DaC: The journey from alpha to general availability</h1>
<p>With the functionality now provided in <a href="https://github.com/elastic/detection-rules">detection-rules</a> repository, users can manage all their detection rules as code, review rule tunings, automatically test and validate rules, and automate rules deployment across their environments.</p>
<h2>Pre-2024: Elastic’s internal use of DaC</h2>
<p>Elastic threat research and detection engineering team created and used the <a href="https://github.com/elastic/detection-rules">detection-rules</a> repository to develop, test, manage and release prebuilt rules, following DaC principles - reviewing rules as a team, automating their tests and release. The repository also has an interactive CLI to create rules, so engineers could start working on the rules right there.</p>
<p>As the security community's interest in as-code principles grew, and the available Elastic Security APIs already allowed users to implement their custom Detections as code solutions, Elastic decided to extend the <a href="https://github.com/elastic/detection-rules">detection-rules</a> repository functionality to enable our users to benefit from our tooling and aid them in creating their DaC processes.</p>
<p>Here are the key milestones of Elastic’s user-focused DaC development from alpha to general availability.</p>
<h2>May 2024: Alpha release of new &quot;roll your own” features</h2>
<p>Our detection-rules repository is adjusted for customer use, allowing for managing custom rules, adapting the test suite for user needs, and allowing for management of actions and exceptions alongside the rules.</p>
<p>Key additions:</p>
<ul>
<li>Custom rules directory support</li>
<li>Select which test to run based on your requirements</li>
<li><a href="https://www.elastic.co/docs/solutions/security/detect-and-alert/rule-exceptions">Exceptions</a> and Actions support</li>
</ul>
<p>We also published an extensive <a href="https://dac-reference.readthedocs.io/en/latest/">guidance</a> for Detections as Code with examples of implementation with Elastic Security using <a href="https://github.com/elastic/detection-rules">detection-rules</a> repository.</p>
<h2>August 2024: &quot;Roll your own” features now beta</h2>
<p>The functionality is extended to allow import and export of custom rules between Elastic Security and repository, more configuration options and versioning functionality extended to custom rules.</p>
<p>New features added:</p>
<ul>
<li>Bulk import/export of custom rules (based on Elastic Security APIs)</li>
<li>Fully configurable unit test, validation, and schemas</li>
<li>Version lock for custom rules</li>
</ul>
<h2>March - August 2025: are generally available and supported</h2>
<p>Using DaC with Elastic Security 8.18 and up:</p>
<ul>
<li><a href="https://www.elastic.co/guide/en/security/8.18/whats-new.html#_customize_and_manage_prebuilt_detection_rules">Supports prebuilt rules management</a>. You can export all prebuilt rules from Elastic Security and store them alongside your custom rules.</li>
<li>Support for rules filtering for export added.</li>
</ul>
<p>Adjacent to DaC efforts, we also released new Terraform resources (<a href="https://github.com/elastic/terraform-provider-elasticstack/releases/tag/v0.12.0">V0.12.0</a>  and <a href="https://github.com/elastic/terraform-provider-elasticstack/releases/tag/v0.13.0">V0.13.0</a>) in October-December 2025, allowing Terraform users to manage detection rules and exceptions.</p>
<p>With this foundation spelled out, let's explore the powerful features that are available to streamline your detection engineering process.</p>
<h1>Detection-rules DaC functionality highlights</h1>
<p>There are a few worthwhile additions since our <a href="https://www.elastic.co/security-labs/dac-beta-release">last DaC publication</a>, which we’ll expand on below.</p>
<h2>Additional filters</h2>
<p>The <a href="https://github.com/elastic/detection-rules/blob/main/CLI.md#exporting-rules">filter functionality</a> available when exporting rules from Kibana has been extended to allow you to precisely define which rules to sync in DaC. Here are the new flags:</p>
<table>
<thead>
<tr>
<th align="center">Flag</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center"><strong>-cro</strong></td>
<td>Filters the export to only include rules created by the user (not Elastic prebuilt rules).</td>
</tr>
<tr>
<td align="center"><strong>-eq</strong></td>
<td>Applies a query filter to the rules being exported.</td>
</tr>
</tbody>
</table>
<p>Let’s take an example of when you wish to organize rules by data source, and want to export the AWS rules to a specific folder. In this case, let’s use filtering on tags for data sources and export all rules with the <code>Data Source AWS</code> tag:</p>
<pre><code>python -m detection_rules kibana export-rules -d dac_test/rules #add rules to the dac_test/rules folder
-sv #strip the version fields from all rules
-cro #export only custom rules
-eq &quot;alert.attributes.tags: &quot;Data Source: AWS&quot;&quot; # export only rules with &quot;Data Source: AWS&quot; tag
</code></pre>
<p>See Kibana documentation for <a href="https://www.elastic.co/docs/api/doc/kibana/operation/operation-performrulesbulkaction#operation-performrulesbulkaction-body-application-json-query">query string filtering</a> for the underlying API call used here and the <a href="https://www.elastic.co/docs/api/doc/kibana/operation/operation-findrules">list all detection rules API call</a> for example available fields to construct the query filter.</p>
<h2>Custom folder structure</h2>
<p>In the detection-rules repo, we use a folder structure based on platform, integration, and MITRE ATT&amp;CK information. This helps us with our organization and rule development. This is by no means the only method of organization. You may want to organize your rules by customer, date, or source as examples. This will vary greatly depending on your use case.</p>
<p>Whether you use this export process or manual organization, once you have your rules in a location or folder structure that you like, you can now keep this local structure even when re-exporting rules. It is important to note that the new rules need to be placed in their desired location manually. The local rule-loading mechanism detects where the rules are placed in order to know where to put them. If the rule is not there, it will then use the specified output directory to place the new rule(s). To use the local rule loading for updating existing rules use the <code>--load-rule-loading / -lr</code> flag for the <code>kibana export-rules</code> and <code>import-rules-to-repo</code> commands. These flags enable you to make use of the local folders specified in your <code>config.yaml</code>.</p>
<p>Let’s look at example with the rules organised in folders the following way:</p>
<p><code>rule_dirs:</code><br />
<code>- rules</code><br />
<code>my_test_rule.toml</code><br />
<code>- another_rules_dir</code><br />
<code>high_number_of_process_and_or_service_terminations.toml</code></p>
<p>We’ll specify the following in the <code>config.yaml</code> file:</p>
<p><code>rule_dirs:</code><br />
<code>- rules</code><br />
<code>- another_rules_dir</code></p>
<p>With the new <code>-lr</code> option, rule updates from Kibana will now use these additional paths instead of exporting directly to the specified directory.</p>
<p>Running <code>python -m detection_rules kibana --space test_local export-rules -d dac_test/rules/ -sv -ac -e -lr,</code>will export rules from <code>test_local</code>  space,  <code>my_test_rule.toml</code> will be written to dac_test/rules/ as it was already on disk there and <code>high_number_of_process_and_or_service_terminations.toml</code> will be written to <code>dac_test/another_rules_dir/.</code></p>
<p>This can be particularly useful if you have the same rules in different sub-folder configurations for different customers. For example, let’s say you have your rules broken down by platform and integration similar to Elastic’s prebuilt rule folder structure. For your customers, SOCs, or threat-hunting teams, having the rules organized underneath these platform/integration folders may be the most useful mechanism for them to manage the rules. However, your information security team or primary detection engineering team may want to manage the rules by initiative or rule author instead so that all the rules a particular individual or team is responsible for are organized in one place. Now with the local rule-loading flags, you can simply have two configuration files and the duplicated rules in each structure. When you are exporting updates for the rules, you would then use the environment variable to select the appropriate configuration file and export the rule updates. These updates will then be applied to the rules in place, maintaining the directory structure.</p>
<h2>Miscellaneous local loading updates</h2>
<p>In addition to the above, we have added two smaller new features designed to help users who are adding local information in the detection rules TOML files and schema. These are as follows:</p>
<ol>
<li>Local date support from the local files where the local date will be maintained from the original file</li>
<li>Upgrades to the auto gen feature to inherit known types from existing schema.</li>
</ol>
<p>The local date component can be useful when one wants more manual control over the date field in the file. Without using the override, the date will be based on when the Kibana rule contents were exported. Using the <code>--local-creation-date</code> flag, the date will not be updated when the file contents are re-exported.</p>
<p>The automatic schema generation has been updated to inherit the types from other indices/integrations if they are present. This provides a potentially more accurate schema, as well as reducing the need for manual updates after the fact. For example, you have a rule that uses the index “new-integration*” with the following fields:</p>
<ul>
<li><code>host.os.type.new_field</code></li>
<li><code>dll.Ext.relative_file_creation_time</code></li>
<li><code>process.name.okta.thread</code></li>
</ul>
<p>Instead of each of these fields being added to the schema with a default type, their types are inherited from existing schemas. In this case, the types for <code>dll.Ext.relative_file_creation_time</code> and <code>process.name.okta.thread</code> are inherited.</p>
<pre><code>{
  &quot;new-integration*&quot;: {
    &quot;dll.Ext.relative_file_creation_time&quot;: &quot;double&quot;,
    &quot;host.os.type.new_field&quot;: &quot;keyword&quot;,
    &quot;process.name.okta.thread&quot;: &quot;keyword&quot;
  }
}
</code></pre>
<p>To see how to use this with your custom data types, see the <a href="#Custom-schemas-usage">Custom schemas usage</a> section within the Implementation examples part of this blog.</p>
<h1>Expanding on usage examples</h1>
<p>Below you will find more examples of DaC implementations, these are not focused on new functionality additions, but go deeper on the topics we see discussed in the community.</p>
<p>It’s worth noting that Detections as Code features are provided as components that can be used to build a custom implementation for your chosen process and architecture. When implementing DaC in your production environment, treat it as an engineering process and follow <a href="https://dac-reference.readthedocs.io/en/latest/dac_concept_and_workflows.html#best-practices">the best practices.</a></p>
<h2>DaC implementation with Gitlab</h2>
<p>When we look at implementations of DaC typically this revolves around using some form of CI/CD product to automatically perform rule management based on a given trigger. These triggers vary considerably based on the desired setup, specifically the authoritative source of rules and the desired state of your version control system (VCS). For a much more in-depth exploration of some of these considerations, see our <a href="https://dac-reference.readthedocs.io/en/latest/core_component_syncing_rules_and_data_from_vcs_to_elastic_security.html">DaC Reference Material</a>. Below is a simple example using Gitlab as VCS provider and using its in-built CI/CD via Gitlab Actions.</p>
<pre><code>stages:                # Define the pipeline stages
  - sync               # Add a 'sync' stage

sync-to-production:    # Define a job named 'sync-to-production'
  stage: sync          # Assign this job to the 'sync' stage
  image: python:3.12   # Use the Python 3.12 Docker image
  variables:
    CUSTOM_RULES_DIR: $CUSTOM_RULES_DIR    # Set custom rules env var
  script:                                  # List of commands to run 
    - python -m pip install --upgrade pip  # Upgrade pip
    - pip cache purge                      # Clear pip cache
    - pip install .[dev]                   # Install package w/ dev deps
    - |  # Multi-line command to import rules                                        
      FLAGS=&quot;-d ${CUSTOM_RULES_DIR}/rules/ --overwrite -e -ac&quot;
      python -m detection_rules kibana --space production import-rules $FLAGS
  environment:
    name: production   # Specify deployment environment as 'production'
  only:
    refs:
      - main           # Run this job only on the 'main' branch
    changes:
      - '**/*.toml'    # Run this job only if .toml files have changed

</code></pre>
<p>This is very similar to other inbuilt CI/CD from other Git-based VCS like Gitlab and Gitea. The main difference being in the syntax determining the triggering event. The DaC commands such as <code>kibana import-rules</code> would be the same regardless of VCS. In this example, we are syncing rules from our fork of the detection-rules repo to our Kibana Production Space. This is based on a number of prior decisions being made, for instance requiring unit tests to pass before merging rule updates and that rules on main being ready for prod. For a Github-based walkthrough of these considerations for this particular approach, please take a look at our <a href="https://dac-reference.readthedocs.io/en/latest/etoe_reference_example.html#demo-video">demo video</a>.</p>
<h2>Custom Unit Testing tips and examples</h2>
<p>When considering DaC as a capability to add to your detection toolkit, setting up the CI/CD and base infrastructure should be considered as the first step in an ongoing process to improve the quality and usefulness of your rules. One of the key purposes in having “as code” tooling is adding the ability to further customize tooling to your needs and environment.</p>
<p>One example of this is unit testing for rules. Beyond base functionality testing, some other key existing unit tests enforce Elastic-specific considerations around rule performance and optimization, as well as organization of metadata and tagging. This helps detection engineers and threat researchers remain consistent in their rule development. Building on this example, one may want to consider adding custom unit tests based on your specific needs.</p>
<p>To illustrate this, take a Security Operations Center (SOC) environment where there are a number of analysts responsible for various different domains and tasks. When an alert is raised in the SIEM, it may not be immediately obvious who should handle remediation, or what team(s) need to be informed of the incident. Tagging the rules with a team tag: e.g. <code>Team: Windows Servers</code> similarly to how Elastic uses tags for data sources, can provide the SOC with a point of contact directly in the alert for who can help with remediation.</p>
<p>In our DaC environment, we can quickly create a new testing module to enforce this on all of the custom rules (or pre-built too). For this test, we are going to enforce having a <code>Team: &lt;some name&gt;</code> tag on all production rules that are not authored by Elastic. In the detection-rules repo, our testing is handled through the Python test suite called <code>pytest</code> and as such unit tests are organized into python modules (files) and subsequent classes and functions in these files under the <code>tests/</code> folder. To add tests simply either add classes or functions to the existing files or create a new one. In general, we recommend creating new test files so that you can receive updates to the existing tests from Elastic without having to merge the differences.</p>
<p>We will start by creating a new python file called <code>test_custom_rules.py</code> in the <code>tests/</code> directory with the following contents:</p>
<pre><code class="language-py"># test_custom_rules.py

&quot;&quot;&quot;Unit Tests for Custom Rules.&quot;&quot;&quot;

from .base import BaseRuleTest


class TestCustomRules(BaseRuleTest):
    &quot;&quot;&quot;Test custom rules for given criteria.&quot;&quot;&quot;

    def test_custom_rule_team_tag(self):
        &quot;&quot;&quot;Unit test that all custom rules have a Team: &lt;team_name&gt; tag.&quot;&quot;&quot;
        tag_format = &quot;Team: &lt;team_name&gt;&quot;
        for rule in self.all_rules:
            if &quot;Elastic&quot; not in rule.contents.data.author:
                tags = rule.contents.data.tags
                if tags:
                    self.assertTrue(
                        any(tag.startswith(&quot;Team: &quot;) for tag in tags),
                        f&quot;Custom rule {rule.contents.data.rule_id} does not have a {tag_format} tag&quot;,
                    )
                else:
                    raise AssertionError(
                        f&quot;Custom rule {rule.contents.data.rule_id} does not have any tags, include a {tag_format} tag&quot;
                    )
</code></pre>
<p>Now each non-Elastic rule will be required to have a tag in the specified pattern for a team responsible for remediation. E.g. <code>Team: Team A.</code></p>
<h2>Custom schemas usage</h2>
<p>Elastic’s ability to bring your own data types also extends to our DaC capabilities. For example, let’s take a look at some custom schemas for network protocols. Diverse data you have in your stack can of course be queried by your rules, and we will also want to leverage the applicable validation and testing for any custom rules on these data types too. This is where Custom schemas come in handy.</p>
<p>When we are validating queries, the query is parsed into the respective fields and the types of these fields are compared against what is provided in a given schema (e.g. <a href="https://www.elastic.co/docs/reference/ecs/ecs-field-reference">ECS schema</a>, the AWS Integration for AWS data, etc.). For custom data types, this follows the same validation path, with the ability to pull from locally defined custom schemas. These schema files can be built by hand as one or more json files; however, if you have some sample data already in your stack, you can take advantage of this and use it as validation and generate your schemas automatically.</p>
<p>Assuming you already have a custom rules folder configured (if not see instructions), you can turn on automatic schema generation by adding <code>auto_gen_schema_file: &lt;path_to_your_json_file&gt;</code> to your config file. This will generate a schema file in the specified location that will be used to add entries for each field and index combination. The file will be updated during any command where rule contents are validated against a schema, including import-rules-to-repo, kibana export-rules, view-rule, and others. This will also automatically add it to your stack-schema-map.yaml file when using a custom rules directory and config.</p>
<p><img src="https://www.elastic.co/security-labs/assets/images/detection-as-code-timeline-and-new-features/image1.gif" alt="" /></p>
<p>With this power comes an increased responsibility on rule reviewers as any field used in the query is immediately assumed to be valid and added to the schema. One way to mitigate risk is to utilize a development space that has access to the data. In the PR, one can then link to a successful execution of the query with stack level validation on its data types. Once this is approved, one can remove the <code>auto_gen_schema_file</code> addition to the config and you now have a known valid schema based on your custom data. This provides a baseline for other rule authors to build upon as needed and maintains the type checking validation.</p>
<h1>Learn more about DaC and try it yourself</h1>
<p>You can experience Elastic Security's Detections as Code (DaC) functionality firsthand with our interactive <a href="https://play.instruqt.com/elastic/invite/uqlknuayvxhy">Instruqt training</a>. This training provides a straightforward way to explore core DaC features in a pre-configured test environment, eliminating the need for manual setup. Give it a try!</p>
<p>If you are implementing DaC, share your experience, ask your questions and help others on the community slack <a href="https://elasticstack.slack.com/archives/C06TE19EP09">DaC channel</a>.</p>
<h2>Trial Elastic Security</h2>
<p>To experience the full benefits of what Elastic has to offer for detection engineers, start your Elastic Security <a href="https://cloud.elastic.co/registration">free trial</a>. Visit <a href="https://www.elastic.co/security">elastic.co/security</a> to learn more.</p>
<p><em>The release and timing of any features or functionality described in this post remain at Elastic's sole discretion. Any features or functionality not currently available may not be delivered on time or at all.</em></p>
]]></content:encoded>
            <category>security-labs</category>
            <enclosure url="https://www.elastic.co/security-labs/assets/images/detection-as-code-timeline-and-new-features/image2.png" length="0" type="image/png"/>
        </item>
    </channel>
</rss>