Tag: TekStream

  • Looping Around the Block – Using Loops with Ansible Blocks

    Looping Around the Block – Using Loops with Ansible Blocks

    By William Phelps, Senior Technical Architect

    It’s a real “task” to use Ansible sometimes.

    In reality, everything in Ansible is a task. A task is the basic work unit within an Ansible playbook. A task is also the smallest unit of work within an Ansible script.

    Each task calls an Ansible “module” to perform its intended function. Once a task is completed, the next task is called. That next task can be blissfully unaware of anything that happened in the previous task (or any previous tasks as well.) This is actually a very powerful feature at times, as different tasks can then have differing environment variables or a different user executing each task. For example, think of needing to execute one or more tasks as root, whereas the rest of the play is meant to be executed with lower privilege.

    However, today’s topic initially looks at the need to execute a series of tasks as more or less a unit or “block”. Each task creates a result that subsequently needs to be passed to one or more following tasks. If a task fails, either the play stops with an error, or it needs to enter some kind of error handler.

    In general programming terms, this approach is called a try/catch/finally approach. Ansible uses the terminology block/rescue/always to refer to the same thing. Here is a schematic example:

    YAML code example showing an Ansible task block that includes a main block of commands, a rescue section for error handling, and an always section to execute final steps. Demonstrates control flow using blocks.

    Obviously this snippet would do very little, but merely illustrates the basic premise of an Ansible block.

    So now let’s further consider a use case where there this type of block needs to be executed repeatedly. For an example, there exists a list of file names in a folder. That list of files (or some attribute of each file) must be evaluated in the context of the block, and some series of actions must occur for each file.

    Normally, such looping is achieved in Ansible using the with_items or loop parameter within a task. For example, this snippet installs several packages using the yum module.

    Ansible playbook snippet using a loop to install multiple required libraries with the yum module. Features variables and with_items for iteration over packages.

    Depending on the Ansible module (in this case “yum”), the module may or may not support the with_items argument or the “loop” argument. “block” is one such module in Ansible. It also does not appear that Ansible will ever add such support.

    The approach to get around this limitation lies in a module called include_tasks. This module can work inside of a block, and also can accept loop arguments. For example:

    An Ansible task that loops over a list of files, using include_tasks to call an external subtasks.yml file, showing how to modularize repeated actions across items.

    All of the operations that need to looped then reside in the subtasks.yml file.  A simple example could be as shown:

    Contents of subtasks.yml, defining two tasks: one for copying a file to a specific location using a shell command, and another to echo the file name, both using {{ item }} to iterate over a list.

    Once the loop is finished, the next task in the main playbook script is executed.

    Don’t be thrown for a loop. This post is intended as more of a conceptual teaching post for Ansible rather than a working example. Please contact us if there is a need for working code for a real-world scenario.

  • Security Bulletin: SPLUNK it to detect MOVEit

    Security Bulletin: SPLUNK it to detect MOVEit

    By Bryan Bollou, Team Lead, Cybersecurity Engineering

    Background

    On May 31st, 2023, it was announced that there was an expanding occurrence of the MOVEit vulnerability – an application used on over 2.5k servers on the internet. This was a critical vulnerability that could be exploited using SQL injection to do the following: 

    • Obtain a list of all folders, files, and users within MOVEit 
    • Download any file within MOVEit 
    • Insert an administrative backdoor user into MOVEit and give attackers an active session to allow credential bypass 

    Since then, a patch has been released that will prevent this exploitation of systems. So, the issue is resolved, right? Absolutely not! We know change management processes can take a while, even in serious situations like this. It may take many cycles before the proper patching is done to your machines to stop this attack. You may have already put in some workarounds to prevent the attack such as disabling ports 80 and 443 on the web servers or some detections to see the exploit. So far, we have seen many good options and would like to present a few specific cases using everyone’s favorite SIEM: Splunk.

    Objective

    The purpose of this security bulletin is not to fully explain or give recommendations on remediating the vulnerability, as has been discussed at length by various resources such as Progress Community.

    Our goal here is to aggregate the detections to maximize your chances of detecting this critical attack. A part of that is gathering the list of IOCs scattered in multiple locations on the internet and looking at activity that could point to the MOVEit vulnerability being exploited. Here at TekStream, we have several security engineers that are intimate with cybersecurity knowledge and especially the logs of our clients.

    We will walk you through the various steps in the MOVEit vulnerability exploitation and detection. With this format, we are providing a more generic data model “tstats” command. This is taking advantage of the data model to quickly find data that may match our IOC list. We then provide examples of a more specific search that will add context to the first find. There will be a wide variety of specific searches as each client has their own specific technologies. To get help building detection for your specific client, fill in the form below and get access to our Splunk/security expertise.

    The following detection steps mirror the stages and TTP-related indicators used in the attack:

    1. Detect initial malicious file spawning SQL Injections
    2. Search for potential beaconing web traffic containing specific parameters
    3. Detect existence of downloaded malicious script
    4. Detect ancillary signs of malicious script activity
    5. Persistent malicious file install
    6. Detect data exfiltration
    7. Scan for related known malicious IPs
    8. Scan for related known malicious web domain

    Detections

    Step 1

    As part of the exploitation, a backdoor named “human2.aspx” was uploaded to multiple sites, this was a main file responsible for performing the SQL injection and exfiltrate sensitive data. Other executable files leveraged in the attack include:

    moveitisapi.dll to perform SQL injection directed by specific headers seen below.

    guestaccess.aspx to create a session and grab CSRF tokens and other parameters for more actions.

    Actions to Detect
    GET /human2.aspx – 443 
    POST /moveitisapi/moveitisapi.dll
    POST /guestaccess.aspx
    GET /human2.aspx

    SPL

    | tstats `summariesonly` sum("Web.bytes") as bytes,values("Web.http_content_type") as http_content_type,values("Web.http_method") as http_method,values("Web.http_user_agent") as http_user_agent,values("Web.status") as status from datamodel="Web"."Web" where (http_method = GET AND Web.url = "*human2.aspx*") OR (http_method = POST AND Web.url = "*/moveitisapi/moveitisapi.dll*") OR (http_method = POST AND Web.url = "*/guestaccess.aspx*") OR (http_method = GET AND Web.url = "*/human2.aspx") by "Web.src", "Web.dest", "Web.user", "Web.url", _time | fields _time src, dest, user, url, http_content_type, http_method, http_user_agent, status, bytes | fieldformat Time = strftime(_time,"%m/%d/%Y %T")
    
    

    Step 2

    In the backdoor code, there is a check for specific parameters that will tell the malicious script what action to perform. Looking for the specific string of this request could be used to detect attempts to exploit the MOVEit Vulnerability. Search for web requests that contain any of the request or response headers listed below:

    Parameters to Detect
    X-siLock-Step1
    X-siLock-Comment
    X-siLock-Step2
    X-siLock-Step3

    SPL

    | tstats `summariesonly` sum("Web.bytes") as bytes,values("Web.http_content_type") as http_content_type,values("Web.http_method") as http_method,values("Web.http_user_agent") as http_user_agent,values("Web.status") as status from datamodel="Web"."Web" where Web.url = "*X-siLock-Step1*" OR Web.url = "*X-siLock-Comment*" OR Web.url = "*X-siLock-Step2*" OR Web.url = "*X-siLock-Step3*" by "Web.src", "Web.dest", "Web.user", "Web.url", _time | fields _time src, dest, user, url, http_content_type, http_method, http_user_agent, status, bytes | fieldformat Time = strftime(_time,"%m/%d/%Y %T")

    Step 3

    As mentioned above, depending on the parameters supplied, the malicious script can do multiple actions. Some include creating a backdoor user or deleting it. The account is called “Health Check Service” and doing searches for the existence of the user in a MOVEit database, or any account activity would help in detecting the exploit.

    Activity to Detect
    IF X-siLockStep1 = -2
    A backdoor user called Health Check Service is removed from the users table, potentially as a method to cover tracks.

    IF X-siLockStep1 = null AND X-siLock-Step2 = null AND X-siLock-Step3 = null
    The malicious script creates an administrative user named Health Check Service in the users table. It also creates and inserts a new active session for this user into the application.

    SPL

    | tstats `summariesonly` latest(_time) as _time from datamodel="Change"."All_Changes" where nodename="All_Changes.Account_Management" (All_Changes.user="Health Check Service" OR All_Changes.src_user="Health Check Service") by "All_Changes.action", "All_Changes.src", "All_Changes.Account_Management.src_user", "All_Changes.dest", "All_Changes.user"  | fields _time, action, src, src_user, dest, user
    | fieldformat Time = strftime(_time,"%m/%d/%Y %T")
    

    Step 4

    Like the above, with different parameters, the malicious script looks to enumerate information about the targeted MOVEit instances. It uses a malformed Azure account that can be detected.

    Activity to Detect

    IF X-siLockStep1 = -1
    The script will attempt to leak Azure information via the response header and return a GZIP stream of all files, file owners and file sizes, and institution data present in MOVEit instance. Account to Detect- azureAccout

    SPL

    index=azure (sourcetype="azure:aad:audit" "initiatedBy.user"=" azureAccout") OR (sourcetype="azure:aad:signin" userPrincipalName=" azureAccout ")

    Step 5

    The posting of the malicious file “human2.aspx” will add the file to the C:MOVEitTransferwwwroot directory on the MOVEit instance. This filesystem path is based on install locations and can vary (for example it can be E drive). The detections here are to detect any files that are created in these vulnerable locations.

    File and File Location to Monitor

    :MOVEitTransferwwwroot
     human2.aspx
     App_Web_*.dll

    SPL

    | tstats `summariesonly` latest(_time) as _time, latest(Filesystem.file_create_time) as file_create_time, latest(Filesystem.file_modify_time) as file_modify_time, latest(Filesystem.file_access_time) as file_access_time from datamodel="Endpoint"."Filesystem", values(Filesystem.dest) as dest, values(Filesystem.action) as action, values(Filesystem.file_name) as file_name, values(Filesystem.file_hash) as file_hash, values(Filesystem.file_path) as file_path, values(Filesystem.file_size) as file_size where (Filesystem.file_name = "*human2.aspx" OR Filesystem.file_name = "*App_Web_*.dll" OR Filesystem.file_path = "*:MOVEitTransferwwwroot*") | fields _time, dest, action, file_name, file_hash, file_path, file_size, file_create_time, file_modify_time, file_access_time
    | fieldformat Time = strftime(_time,"%m/%d/%Y %T")
    

    Step 6

    Detecting the exfiltration of data is another way to find out if a bad actor is exploiting the MOVEit vulnerability. Examine firewall logs for large outbound network transfers from the MOVEit environment. 

    IPs and Volume to Detect

    IPs – these will be your MOVEit Instance IPs
    Volume in bytes – this will depend on time (defaulted to 1 hour in this detection) and what is considered abnormally high volume in your environment (default to 1MB in this detection).

    SPL

    | tstats `summariesonly` values(_time) as _time, sum("All_Traffic.bytes") as bytes, values("All_Traffic.src_port") as src_port, values("All_Traffic.transport") as transport, values("All_Traffic.dest_port") as dest_port from datamodel="Network_Traffic"."All_Traffic", values("All_Traffic.action") as action where All_Traffic.src="[INSERT MOVEit INSTANCES IPS]” AND All_Traffic.action !=blocked AND All_Traffic.dest_category !=internal AND All_Traffic.bytes > 1000
     by  "All_Traffic.dest" , "All_Traffic.user", "All_Traffic.src", _time span=1h
    | rename "All_Traffic.dest" as dest, "All_Traffic.user" as user, "All_Traffic.src" as src
    | table_time, action, src, src_port, dest, transport, dest_port, user, bytes
    | fieldformat Time = strftime(_time,"%m/%d/%Y %T") 

    Step 7

    There are several IP addresses that have been associated with the exploitation of the MOVEit vulnerability. TekStream has consolidated a list of these IOCs from numerous sources on the internet. These IOCs can be added to a lookup table and used in the detection below.

    TekStream MOVEit IOC List

    This CSV has the list of the IOCs at the time of this blog post being written – for a more updated version and/or information on how to build the lookup in the detection, please contact a TekStream consultant below.

    Search firewall and MOVEit IIS logs for requests from any of the IP addresses specified within the IOCs below.

    IPs To Detect

    In this case, you will look for any and all of the IP’s on the TekStream MOVEit IOC List

    SPL

    | tstats `summariesonly` values(_time) as _time, sum("All_Traffic.bytes") as bytes, values("All_Traffic.src_port") as src_port, values("All_Traffic.transport") as transport, values("All_Traffic.dest_port") as dest_port from datamodel="Network_Traffic"."All_Traffic", values("All_Traffic.action") as action
     by  "All_Traffic.dest" , "All_Traffic.user", "All_Traffic.src"
    | rename "All_Traffic.dest" as dest, "All_Traffic.user" as user, "All_Traffic.src" as src
    | eval allips = mvappend(src, dest)
    | inputlookup TS_MOVEit_IPs_List.csv | fields ip | rename ip as allips
    | table_time, action, src, src_port, dest, transport, dest_port, user, bytes
    | fieldformat Time = strftime(_time,"%m/%d/%Y %T")

    Step 8

    There is a domain associated with the MOVEit vulnerability and it is detectable with the logic below.

    Domain to Detect

    dojustit[.]mooo[.]com

    SPL

    | tstats `summariesonly` latest(_time) as _time  values("DNS.dest") as dest, values("DNS.query") as query, values("DNS.query_count") as query_count, values("DNS.message_type") as message_type, values("DNS.answer") as answer, values("DNS.reply_code") as reply_code from datamodel="Network_Resolution"."DNS" where DNS.query="dojustit[.]mooo[.]com" | table _time, dest, query, query_count, message_type, answer, reply_code | fieldformat Time = strftime(_time,"%m/%d/%Y %T")

    IOC List

    Below is an aggregate of IOCs found related to the MOVEit vulnerability. It has been presented here for you to have it consolidated in one spot and made easier to export to a lookup for notable detections.

    TekStream MOVEit IOC List

    Conclusion

    Ideally, you could make scheduled searches like what is shown above with lookup tables for matching more specific and new detections. These can be set to run on a continuous schedule to ensure the monitoring of your assets from new vulnerabilities. Old vulnerabilities that have been patched (and applied) can also be aged out of this lookup table to ensure it is timely and efficient. For questions on how to build such a process that is dynamic and customizable for your environment, ask one of our consultants by filling in the form below.

    References

    Articles referenced and used for this post: Trusted SEC, Huntress, Progress Community

    Disclaimer: The approaches recommended herein have not been tested broadly across the TekStream customer base. They are preliminary in nature and come without any certification of efficacy.

    We are available to assist if you have any questions, just contact us here:

  • Release Notes: What We Know About The Splunk Enterprise 9.1 Release

    Release Notes: What We Know About The Splunk Enterprise 9.1 Release

    By Zubair Rauf, Team Lead, Professional Services

    The world of data analytics is constantly evolving, now at a faster pace than ever as new technology is being introduced to process and analyze data faster and better than before. With the latest Splunk 9.1 release, Splunk is committed to helping organizations turn their raw data into actionable intelligence with new features and improvements. In this blog post we will recap some of those features and how they can help organizations turn data into action!

    UI and UX Features

    With every new release, Splunk focuses on improving their user experience for users. Some notable changes are recapped below:

    Redesigned Home Page

    The new home page has a tabular layout with a side bar. The updated sidebar will allow users to pin frequently used apps to the top of the sidebar and be able to search apps by name for easy access to apps. There are five new tabs which help with better organization. Now users can start where they left off with recently viewed knowledge objects, access Quick Links for commonly tasks and resources, view a home dashboard, view knowledge objects created by them and view knowledge objects that are shared with them.

    Screenshot of the Splunk Enterprise 9.1 home dashboard displaying the Quick Links tab. Options include adding data, searching, visualizing, managing permissions, and accessing learning resources.

    This is what the new home page looks like in Splunk v9.1

    Dashboard Studio Updates

    The new version comes with several Dashboard Studio updates to improve user experience for interacting with dashboards. Some notable changes included here are:

    • Export data of visualizations to CSV files
    • Base and Chain behavior is updated – now base searches do not need to update if the chain search SPL changes, and users can now also create up to TEN chain searches. This translates to improved performance for dashboards.
    • Events viewer visualization is available on dashboard studio, with workflow actions which help users take predefined actions on events/fields.
    • Inputs are available on the canvas, making user inputs be closer to the panels they impact, making them easier to interact with.
    • Users can now choose to show or hide panels in Absolute layout based on availability of data to display
    • Map visualizations also have Choropleth map layers added
    • Configuration UI introduced for axes charts which were previously only available via source code
    • Trellis is now available for single value visualizations

    Health Report Enhancements

    The health report has introduced new enhancements which will allow users to:

    • Disable individual features in distributed health report to remove noise
    • Track user modified threshold values and restore defaults
    • New built-in validation for indicator thresholds and feature names.

    Splunk 9.1 has also introduced these UI features:

    • Dark and light mode for the Search & Reporting app
    • Search history is preserved across search heads in search head clusters now by leveraging KV Store
    • Triggered Alerts page has a new backend framework to improve accessibility
    • Classic dashboards will also warn users if a script is detected in the XML before running it
    • Admins can also control how searches are shared through Splunk web

    Under The Hood

    Splunk 9.1 comes with a lot of new features and enhancements under the hood that will greatly improve Splunk capabilities for data ingestion, search, disaster recovery and more.

    Ingest Actions

    Ingest actions has been phenomenal since it was launched, and it has allowed customers to improve their data ingestion process and allows filtering, masking and routing data. It allows users to configure this without having to tinker with the .conf files. Some improvements for ingest actions we took note of are:

    • Multiple S3 destinations are now supported for routing. There can be a maximum of 8 destinations per provider
    • Using a combination of sourcetype name and timestamp, users can now partition S3 outputs so that all logs do not end up in the same S3 bucket folder. It looks like this:
    Screenshot showing event partitioning configuration in Splunk 9.1, including a sample S3 bucket schema path organized by year, month, and day with optional source type as a secondary key.
    • Cross-account KMS encryption is supported
    • Outputs can be customized for better federated search performance and there is more control over batch size, compression type and JSON output. This is what we saw:
    Splunk 9.1 interface for configuring output format, fields, compression type, and batch parameters. Dropdown shows ‘New line delimited JSON’ selected as the default format.

    Federated Search

    Federated search originally introduced in Splunk Enterprise 8.2 allows users to execute unified search across multiple Splunk environments. These can include Splunk Cloud and on-prem. Splunk 9.1 brings some much-needed enhancements to the federated search experience.

    • New remote dataset types introduced for standard mode federated search. These include
      • Metrics Index datasets which allow users to use mstats command in federated search for remote metrics indexes
      • Last job datasets convert last jobs run by remote scheduled searches into datasets that are searchable
    • Splunk Admins can now deactivate federated providers so users can’t search those datasets, deactivate federated indexes, and deactivate the ability of users to run transparent federated searches
    • Standard mode will now also allow wildcard searches to search across multiple indexes
    • Support for accelerated data models has been improved
    • Better access control on federated providers to control which federated indexes can users search in transparent mode

    License Manager

    Splunk 9.1 now supports a highly available license manager architecture to alleviate. Now customers with unlimited license can deploy multiple license managers in (can be in different regions) behind a load balancer.

    Search Head Cluster

    Search Head Clusters running Splunk Enterprise 9.1 now support automated rolling upgrades and this reduces complexity of the upgrade process for admins.

    Search

    A notable improvement in search is the support for parallel reduction for lookup command. Now searches using the lookup command can now leverage the processing power of indexers to return results. This helps improve search efficiency especially for high cardinality data.

    Version 1 of the stats command has been deprecated and users will see a warning banner for that. This command is replaced with version 2 of the stats command.

    Our Assessment

    Splunk Enterprise 9.1 has introduced a lot of new features and improved on existing features that will help users understand their data faster and better. We are pleased with what we see, and it reinforces our belief that Splunk continually improves to make our journey more effective. We think it is worthy of upgrading to the newest version as soon as possible.

    There are a lot of other features and enhancements introduced with Splunk Enterprise 9.1 for improving performance and user experience. Details on the additional features can be found here.

    If your organization is thinking about buying Splunk to start your data journey or upgrading an older version of Splunk to 9.1 to benefit from the latest features, reach out to me or another of our Splunk experts by filling the form below.

  • Creating Splunk Cloud Architecture Diagrams Using Lucidchart

    Creating Splunk Cloud Architecture Diagrams Using Lucidchart

    By Kamal Dorairaj, Senior Splunk Consultant

    Knowledge is valuable, and in the case of the Splunk installation at your firm a visual representation of the platform configuration becomes a key asset. The diagram gives better understanding of the Splunk Cloud Implementation and is useful for internal training as well as documentation needs at your company. In this blog, we will offer a step by step process for creating a Splunk cloud architecture diagram using Lucidchart.

    The architecture diagram is best created in Lucidchart, which has all Splunk shapes, icons and images. It also has a library of shapes for all of the leading products you may be using, like AWS, Google Cloud Platform (GCP), Azure and other security products. You can also import shapes from external sources and use it for the diagram. Lucidchart provides options to export the diagram in various formats including pdf, Visio, jpeg, png and csv.

    Discovery

    In the discovery phase you will gather all the information required for the architecture diagram. Ask yourself these questions to ensure you include the essential materials:

    • Which Splunk systems are being used in the environment? Examples include UF, HF, DS, etc.
    • Where do the UFs forward to? Heavy Forwarders, Indexers, or a mix?
    • What kind of data collection is taking place? Ex: Syslog, HEC, API.
    • What is the list of data sources per HF? This will include the vendor/product lists.
    • Which host has what type of Apps/Data collection?
    • What are the IP, host name, cpu/memory/disk spaces of each HF/UF/DS?
    • Are you using Splunk Premium Products in addition to Splunk Enterprise? These might include enterprise security, UBA or ITSI.

    Diagram Creation Process

    The diagram should be closely associated to the Splunk Validated Architecture based on the environment.

    Architecture Layers
    Login: Users access Splunk Cloud Search Head through ‘https 443’ via the internet.

    Splunk Cloud Search Head Tier and Indexing Tier: The Search Head on the cloud got an Adhoc SH (customer.splunkcloud.com) and SH for the premium product if there is one. Ex: ES SH (escustomer.splunkcloud.com). The SH on the Cloud talks to the Indexing Cluster Tier through port 8089. Splunk does not allow to put any indexers or search head host details in the diagram.

    Getting Data thru HEC and API: Apps or data that send through HEC (http event collector) token-based to Splunk Cloud Platform is a fast and efficient way. The HEC data flows to Splunk Cloud through port ‘https 443’. Getting Data in through APIs to Splunk Indexing layer by configuring the API inputs through an authentication type.

    On-Prem Collection Tier: This part of the architecture lives on the customer network side. We have Heavy Forwarder and Universal Forwarder. The instances could be on unix or windows. Both the HFs and UFs forward the data to the Splunk Indexing tier thru port ‘TCP 9997”.

    On-Prem Management Tier: The DS has all the apps and config files which pushes the changes thru ‘TCP 8089” to the HFs and UFs. Many times, the license master is installed in the same DS server instances.

    Syslog Sources: There could be single or multiple syslog sources that send data thru ‘TCP UDP 514’ in a network load balancer to the UFs or HFs. The syslog can also configure to flows thru SC4S.

    PORT Details:
    TCP 8089 -> Splunk Management Port
    TCP 9997 -> Splunk Data
    HTTPS 443 -> Splunk Web
    TCP UDP 514 -> Syslog
    TCP 8191 -> KV Store Replication
    TCP 9777 -> SHC Replication
    TCP 9887 -> IDX Replication

    This is what a typical Splunk cloud architecture diagram will look like:

    Detailed architecture diagram of a Splunk Cloud deployment created in Lucidchart. The image shows multiple tiers: users connecting via HTTPS, the Splunk Cloud search tier, indexing tier, and on-premises tiers for collection and management. Data flow is represented with color-coded lines for different protocols, such as TCP 9997 for data and HTTPS 443 for web. Components include forwarders, heavy forwarders, syslog sources, SC4S, deployment servers, and AWS CloudTrail.

    Have fun creating diagrams of your own. As always, we are here if you have any questions. Contact us here:

  • Splunk for Monitoring: Pinger APP!

    Splunk for Monitoring: Pinger APP!

    By Bryan Bollou, Splunk Consultant

    One of the many uses for Splunk is monitoring an environment and its assets. This can be done in different ways and this article highlights two of them.

    The first is through monitoring of the logs the machines are supposed to be sending to Splunk. If a log successfully gets to Splunk this shows the log generation, Splunk forwarding and Splunk service are working/running. If a host stops sending logs, it can be an indication that the machine is down. In some environments, however, logs may stop due to system restarts, configuration changes, low traffic times, etc. Here the host is up but is not sending logs (at the moment). This means the simplest way of checking if a machine is up can still be useful – ping. This will be the second method discussed in this blog post to monitor assets reporting a Splunk environment.

    Monitoring Hosts with Logging

    Monitoring hosts with logging involves first understanding what logs are expected and establishing a time threshold for when they are “stopped”. This threshold can differ as some logs are expected to be constantly noisy such as firewalls, while others could be based on user activity and/or time of day such as transaction logs.

    The following SPL searches can be used to get visibility on the current indexes and whether they have received logs after a certain period of time:

    Find and List all Indexes

    | eventcount summarize=false index=* index=_* 
    | dedup index 
    | fields index
    

    Look at indexes in the last 24 hours, if they have not sent logs in the last 5 minutes, list them out.

    | tstats latest(_time) as latest where index=* earliest=-24h by index
    | eval recent = if(latest > relative_time(now(),"-5m"),1,0), realLatest = strftime(latest,"%c")
    | where recent=0
    
    Splunk search interface showing a tstats query that evaluates data activity by index over the past 24 hours. The query flags inactive indexes by checking if their latest event is older than 5 minutes. The table includes index names, timestamps, and activity status.

    The results of this search could be used to make an alert for when an index stops receiving logs. This, however, could be too general if you have multiple hosts sending to a particular index. Thus, splitting the search by host could yield more specific and useful results.

    Look at hosts in the last 24 hours, if they have not sent logs in the last 5 minutes, list them out.

    | tstats latest(_time) as latest where index=* earliest=-24h by host
    | eval recent = if(latest > relative_time(now(),"-5m"),1,0), realLatest = strftime(latest,"%c")
    | where recent=0
    
    Splunk dashboard displaying a tstats search segmented by host, highlighting systems that stopped sending data in the last 24 hours. Hosts are listed with timestamps and an inactivity flag, indicating potential connectivity or service issues.

    This SPL can be saved as an alert with the parameters below to get an alert that tells a customer whenever one of their hosts stops sending logs to Splunk for X amount of time (5 minutes in this example).

    Splunk alert configuration panel for setting up a scheduled alert titled “Host Stopped Sending Alert.” The alert runs every 10 minutes, triggers if result count is greater than zero, and suppresses repeated notifications for the same host within 60 minutes.

    An email alert action would look something like this:

    Email alert from Splunk titled “Host Stopped Sending Alert” showing that a host (10.8.0.6) stopped sending data. Includes event timestamp details and a direct link to view results in Splunk. Attached is a CSV export of the alert result.

    To expand on the above alert, we can use Splunk to find out if machine is up or down based on ping status. For this, I will go over an app I created to ping machines in a lookup file and send the results in an event format to Splunk.

    A prerequisite for this app and the script below to work is for the machine (where the script resides) to be able to ping all other machines it targets. For larger and segregated environments, the script can be deployed to multiple machines that have different “ping access” in order to have more coverage.

    Below is the commented bash script that looks at the lookup tables in the pinger app directory and pings them one by one. Note: depending on if it is a full Splunk install or Splunk Universal forwarder the LOOKUP_LOCATION variable will be different. Line 6 needs to be uncommented for the former (full) and Line 5 for the latter (universal forwarder). Machines that are pinged and respond will print an “up” status log and those that don’t will print a “down” status log.

    Screenshot of a shell script (ping.sh) that loops through CSV lookup files to ping host IPs and echo their status (up or down) with associated Splunk fields like host, index, and sourcetype. The script reads CSV headers and performs a 5-ping test on each IP address.

    The script currently looks for a csv with the headers, “ip”, “host”, “index” and “sourcetype” – in that order. This can be changed by modifying line 20. An example of lookup file this script would work with is here:

    Spreadsheet showing a sample lookup file used by the Pinger app, listing columns for IP address, host, index, and sourcetype. Each row defines a system to be monitored via the script

    Along with the script, an inputs configuration is needed to point to the script above and run it on at an interval. In this example the interval is 240 seconds or 4 minutes. The results of the script will then be forwarded to the index main and have the sourcetype pinger.

    Configuration snippet from inputs.conf that schedules the ping.sh script to run every 240 seconds in Splunk. Specifies the script path, interval, index name (main), and sourcetype (pinger).

    To ensure the logs that are sent to Splunk come in a good format, a props configuration needs to be created. In the below configuration, the sourcetype pinger disables line merging and has the default newline line breaker. The logs do not have a time stamp and will take the time the script is ran on the machine.

    Configuration file (props.conf) defining how events from the Pinger app are parsed in Splunk. Includes settings for line breaking, truncation limit, timestamp lookahead, and placeholders for time prefix and format.

    This props configuration needs to go on the first full instance of Splunk the pinger app’s logs will touch. For example, let’s say the pinger app is on a universal forwarder that forwards its logs to a heavy forwarder before being sent to an indexer in a Splunk Cloud instance. In this case, the props.conf would be needed on the heavy forwarder. If the universal forwarder sent logs straight to Splunk Cloud, the props.conf would need to be on the Splunk Cloud Indexers. If the pinger app is installed directly on a heavy forwarder as opposed to a universal forwarder, the props.conf app needs to be on the heavy forwarder instance.

    Below is an example of the structure of the pinger app. The script goes into the app_name/bin directory. Lookup tables with the hostnames and ip addresses to ping will go under the app_name/lookups directory. The configuration files will go under the app_name/default directory.

    Terminal output showing the directory structure of a custom Splunk app named pingerapp, including subfolders like bin, default, lookups, and metadata, and configuration files like inputs.conf, props.conf, and a ping.sh script.

    The app will reside in the $SPLUNK_HOME/etc/apps, for example:

    Terminal view displaying the path /Applications/Splunk/etc/apps and a list of installed Splunk apps including pingerapp, search, sample_app, and several third-party or custom add-ons.

    To check if the app will work for the machine it is installed on, you can navigate to the $SPLUNK_HOME/etc/apps/pingerapp/bin directory and run the script manually.

    Terminal output from executing the ping.sh script, showing simulated ping results with status (up or down), IP addresses, and hostnames such as local, google, nowhere, and opendns.

    Once the app is properly installed and the Splunk instance is restarted, the script will start generating logs and forwarding them to the appropriate index. The logs would appear like below:

    Splunk event viewer showing log data ingested from the ping.sh script, with fields like status, IP, host, source path to the script, index, and sourcetype indicating the data came from a custom pinger app.

    These logs can be then used to discover the machines with the latest status of “down” (their last ping test did not return results as per the script). This represents a machine that is not currently pingable in an environment.

    Splunk SPL search that filters for status=down events and uses stats, rename, and fields commands to list IP addresses of hosts currently reported as down, based on 25,808 matching events.

    To get the best of both “monitoring” worlds, a combined search can be used. A prerequisite for this to work is that the hostnames and/or ip addresses for the machine sending the logs and how it’s pinged, need to match. A joined search like the one below can then be used to get a list of the hosts that stopped sending logs then feed it into a search looking for hosts that are not pingable.

    Advanced SPL search in Splunk Cloud using a join with tstats to detect hosts that are down and also not sending logs, highlighting one host (10.100.0.4) meeting the condition of “no logs” in the past 24 hours.

    This can be made into an alert like this:

    Splunk “Save As Alert” configuration panel titled “Host Not Pingable and Stopped Sending Logs,” with settings to run every 10 minutes, trigger when results are greater than zero, and send email notifications.
    Splunk alert configuration for email notifications, showing message details including dynamic variables like $name$ in the subject and message body, with options selected to include links and attach CSV results.

    Tools like this alert and the customizable pinger app can be used to enhance the monitoring capabilities of Splunk. For questions on how to make this script more customizable for your environment or how to use Splunk to monitor your assets, ask one of our consultants by filling in the form below. Happy Splunking!

  • Splunk x ChatGPT for Security Teams

    Splunk x ChatGPT for Security Teams

    by Zubair Rauf, Team Lead Professional Services and Bruce Johnson, Sr. Director Enterprise Security

    Splunk is the premier SIEM/Big Data platform in the cybersecurity industry. There are several extensions to the Splunk platform to incorporate machine learning, natural language processing, threat graphing, statistical computing, and Security Orchestration, Automation, and Response (SOAR). They take advantage of the fact that Splunk, as a big data platform, allows for the crunching and correlation of large quantities of data over extended search timeframes in near real-time. The latest obvious trend is to marry this capability with recent advances in AI utilities. Splunk has multiple premium product offerings, two of which are security focused.

    • Splunk Enterprise Security offers additional features over the standard Splunk platform. These include real-time threat identification, advanced analytics, and automated response (with Splunk SOAR).
    • Splunk SOAR is a tool that can be used to automate threat response workflows. These can help with incident response, remediation, and reporting.

    ChatGPT is a generative AI model trained by OpenAI that can generate human-like responses to a wide range of queries by the users. It can also analyze and generate code, allowing users to:

    • Create code faster by generating code snippets based on natural language input.
    • Analyze code snippets for security vulnerabilities by identifying potential security issues in code.
    • Interpret code for better understanding by providing explanations of code logic and behavior.

    In the context of security ChatGPT has been used to attack GitHub repositories, generate malicious code stubs, insertion of proprietary information into the ChatGPT data model, and AI-Generated phishing campaigns (side note: grammar is no longer a prevalent phishing threat indicator as verbiage can be generated). It is only a matter of time until ChatGPT tasking is married together with malicious script libraries and attack techniques to devise batteries of generated, dynamic, morphing threat chains.

    As always with cybersecurity threats, creative uses for utilities and techniques start with hackers and quickly demands a response from blue teamers. As cybersecurity professionals we are on our back feet coming up with ways to leverage AI to defend against AI-generated attacks.

    Entering the fray are Splunk extensions to SIEM and SOAR platforms to enable extension of search and automation to incorporate AI algorithms. It is a rudimentary but important beginning.

    ChatGPT Access

    Analysts can access ChatGPT or the underlying language models using the ChatGPT web interface or by using OpenAI’s API.

    There are also Splunk Technical Add-ons (TAs) that have been developed for ChatGPT/Splunk integration. These TAs let you interact with ChatGPT directly from your Splunk search through custom search commands and other actions. One notable Technical Add-on (TA) was built by Michael Camp Bentley from Splunkable LLC, a TekStream partner, and is available on Github.

    Microsoft Azure OpenAI Service also provides organizations to run OpenAI models in a secure environment. Organizations can use datasets to fine-tune models for more accurate results and tap into more use cases with their data. However before using this service to train and fine-tune models, please read the Data, privacy and security documentation for the service.

    Splunk x ChatGPT Applications

    Creating Splunk searches with ChatGPT

    One of the most used use-cases that I have tested out and have seen other people leverage ChatGPT is to create simple and complex Splunk queries for customized security detections. ChatGPT does a decent job when given the right prompts and can build the underlying logic for an acceptable query. I have seen that you will have to modify the search to filter correctly for your data.

    I have tested ChatGPT to create queries for common detections and while it is not 100% accurate in generating the query that you want (it is an AI after all, and the clarity of your prompt matters!), it provides you with some innovative ideas and a great starting point to play around with your search.

    ChatGPT also interprets the Splunk query to provide users a foundational understanding of how to build out a dynamic query for a detection/correlation search.

    Integrating Splunk Search and ChatGPT

    There are many TAs that the Splunk community has made that integrates ChatGPT with Splunk search. A notable one I already mentioned above, built by Splunkable (available here) enables users to directly send prompts and get responses from ChatGPT through a Splunk search command.

    This opens numerous possibilities for dynamic prompt generation through eval statements based on your use case. Some use cases I can think of are:

    • Based on a detected threat, you can pass MITRE metadata, with the threat to ChatGPT prompt and it can suggest the next potential threat that may come your way
    • ChatGPT can automate responses to users about identified phishing threats to users, encourage them to study security topics based on prompts generated from search results. These responses can be sent to users using Splunk email alerts.

    Creating Splunk SOAR automation scripts with ChatGPT

    ChatGPT can also help Splunk SOAR users create SOAR automation scripts that can be modified to work with the environment and deployed to Splunk SOAR. Splunk SOAR is built on Python, so ChatGPT can be used to generate Python code to perform actions using Splunk SOAR. The generated scripts will provide users with a good starting point and can make modifications before deploying scripts in their environment.

    Analyze Scripts and Code

    Analysts can use ChatGPT to quickly analyze and interpret a script. This can help analysts quickly triage a malicious script and contain the threat. This can be programmatically done using an integration with ChatGPT. You can pass the script to ChatGPT by using the API integration with Splunk (see Splunkable, LLC Splunk TA for OpenAI) and depending on the response you can determine how critical the alert should be so that it can be prioritized accordingly for analysts. ChatGPT can also provide a detailed analysis of what a script/code-snippet is going to do and provide recommendations for remediation.

    Preemptively, ChatGPT can also help security teams running OpenAI in a secure environment determine security vulnerabilities in code before it is deployed to production. This will help ensure that no malicious code is introduced during the development process and identify any security vulnerabilities that need to be addressed.

    Building governance and detections using the MITRE ATT&CK framework

    If you are starting out on your Splunk security journey and want to dive deeper into building detections using the MITRE ATT&CK® framework, you can leverage ChatGPT to understand different MITRE Tactics. ChatGPT is well trained on the MITRE framework and can help you understand the different MITRE tactics and techniques associated with a variety of common and uncommon attacks.

    These techniques/tactics would help a user determine what data would be required for creating detections around the use case and accompanying remediation steps. You can also use this with fine-tuned models through the Azure OpenAI Service to have results tailored to your environment.

    Enhance Purple Team Findings

    ChatGPT can also help compliance teams efficiently understand purple team findings, map them to MITRE framework, and get insights on remediation tactics. ChatGPT can also recommend what indicators of compromise (IOCs) to focus on, data required to monitor these and common Splunk detections that can help address the vulnerabilities.

    Summary

    This is obviously just the tip of the iceberg. TekStream is constantly working on improving the safety and security of our MDR customers and the focus for everyone in the cybersecurity industry is squarely on leveraging AI to enhance cybersecurity posture (or attack it). It’s not quite Terminator vs. Skynet yet, but AI is certainly a powerful and evolving approach to generate and defend against threats. We’d be interested in how you are using AI in the context of cybersecurity. For more information, and to keep the conversation going, contact us below:

    Special thank you to Michael Camp Bentley and Splunkable LLC for their contributions to this article.

    *Just for fun, we created the image on this blog post using ChatGPT’s sister image site Dall-E!

  • Regex v. Rex Commands in Splunk SPL

    Regex v. Rex Commands in Splunk SPL

    by Alex Trejo, Splunk Consultant

    A regular expression is used to capture a pattern of characters in text. This can be become very useful when either filtering data or extracting new fields in Splunk. The SPL commands Splunk provide us with for regular expressions are the ‘regex’ and ‘rex’ commands. They are both regular expression commands but are utilized in different way. When used together, we can make the most out of regular expressions with just the search bar in Splunk.

    Regex

    regex [<field>=<regular expression>]

    The regex command is primarily used for filtering data. The command can filter for both data that does or does not match the regular expression. The regex command can be applied to specified fields otherwise the default is _raw.

    Rex

    rex [field=<field>] [regular expression]

    The rex command can be used for search-time field extractions and string replacement. The rex command can be applied to specified fields otherwise the default is _raw.

    Here we have a set of customer transactions with no predefined field extractions. We will be responsible for pulling in customer IDs, names, transactions, Ips, and statuses.

    Screenshot of a Splunk search displaying results for a regex test index, including timestamps, source file paths, and customer transaction IDs.

    To begin we will want to use the rex command to extract the fields we are looking for. Since we do not have any predefined fields to work off, we will have to use the default _raw field for the rex command. Since we are using the default field of _raw we do not need to define field in the command.

    To extract the CustomerId field we will use the following rex command:

    rex “CustomerId(?<CustomerId>w+_d+)”

    We will follow the same format for the following fields of transaction, IP, and STATUS.

    Splunk search screen illustrating the use of multiple rex commands to extract structured fields like CustomerId, IP address, and STATUS codes from raw event logs, progressing field enrichment using named capture groups.

    Next, we will extract the customers’ names. Since the CustomerId field already contains the customers’ names we will use that field in our rex command instead of the default _raw.

    To extract the CustomerName field we will use the following rex command:

    rex field=CustomerId “(?<CustomerName>w+)_d+”

    We will follow the same format for the CustomerNum field.

    A refined Splunk search leveraging rex field= syntax to extract CustomerName and CustomerNum fields, showing how to apply regex on specific fields rather than the raw event data.

    Next, we will display the fields in table for better visibility.

    Splunk statistics view showing tabular output of extracted fields: CustomerId, CustomerName, transaction, IP, and STATUS. Demonstrates successful field extraction and table formatting after multiple rex applications.

    Now, we will use the regex command to filter out IP addresses that start with 3 digits. Since we are targeting the IP field here, we will have to specify that field within the command to override the default _raw field.

    regex IP!=d{3}.d+.d+.d+
    Splunk SPL search that introduces a regex command to filter results by IP format. The output table shows a narrowed list of customer transactions matching specific regex criteria.

    If we wanted to filter for the IPs that began with 3 digits, we would simply remove the ‘!’ before the ‘=’ in the command.

    regex IP=d{3}.d+.d+.d+
    Search results in Splunk using regex to include only matching IP patterns. The filtered dataset displays customers like Cat and Will whose IP addresses meet the criteria.

    Another interesting feature of the rex command we did not touch on before is its ability to replace strings. Using the mode=sed option, the command can replace strings within a field. Note, this does not change the data in any form. Here we will use the command to mask the beginning of IP addresses that begin with 3 digits.

    rex  field=IP mode=sed "s/(d{3}.)/x./g"
    Splunk SPL using regex with mode=sed to mask portions of IP addresses, replacing the third octet with an “x” (e.g., 197.0.0.2 becomes x.0.0.2), illustrating regex replacement techniques for data redaction.

    There you have it – a short comparison of Regex vs. Rex in Splunk SPL. I hope this was helpful, and am happy to answer any questions using the request here:

  • Using Splunk to Search LDAP & Monitor for Last Time Password Was Set by Active Users on Windows OS

    Using Splunk to Search LDAP & Monitor for Last Time Password Was Set by Active Users on Windows OS

    by Patricia Orea-Arebun, Splunk Consultant II

    This use case helps to monitor active user accounts on Windows OS that have not updated their passwords in the client system in more than “n” number of days. The “n” number of days depends on organizational policy. Using your Splunk instance is the best way to search for changes and monitor active updates.

    Risk

    The risk involved in having active user accounts with passwords not changed is that the organization might be susceptible to brute force attacks. A brute force attack is where an attacker will be trying to access a company’s network by trying all possible passwords until they get lucky (dangerous!!!!).

    Control

    Using LDAP can help set monitoring in place for active users whose passwords are yet to be changed or nearing expiration (based on organization policy). LDAP, or Lightweight Directory Access Protocol, is a communication protocol that provides the ability to access and maintain distributed directory information services over a network. LDAP is used in Microsoft’s Active Directory but can also be used in other tools. Querying the LDAP directory requires using the Supporting Add-on for Active Directory (SA-ldapsearch) from Splunkbase in order to use the ldapsearch command. The ldapsearch command will display the users, their respective organizational units, lastLogonTime, created date, pwdLastset and so on.

    SPL Query

    Begin your query like this:

    |ldapsearch domain=<**your company domain**> search="(&(objectClass=user)(!(objectClass=computer)))" 
    | search userAccountControl!=ACCOUNTDISABLE 
    | rex "OU=(?<OU>[a-zA-Zs]+),DC" 
    | eval lasttime=strptime(pwdLastSet,"%Y-%m-%dT%H:%M:%S.%6N")
    |eval diff=round(((now() - lasttime)/86400),2)  
    | eval timediff = n - diff 
    | stats values(whenCreated) as "Created Date" latest(lastLogonTimestamp) as "LastLogonTime" values(OU) as OU values(sAMAccountName) as sAMAccountName values(pwdLastSet) as PWDLastSet values(timediff) as "Time left to change password"  by displayName
    SPL Analysis
    | ldapsearch domain=<**your company domain**>   search="(&(objectClass=user)(!(objectClass=computer)))" 

    This is querying the ldap tree for users, service accounts and not computers.

    | search userAccountControl!=ACCOUNTDISABLE

    This is searching for the active users and service accounts and ignoring disabled accounts

    | rex "OU=(?<OU>[a-zA-Zs]+),DC" 

    This is optional and depends on the use case. This is a field extraction for the list of “Organizational Unit” that each user or service accounts belongs to in the ldap tree.

    | eval lasttime=strptime(pwdLastSet,"%Y-%m-%dT%H:%M:%S.%6N")

    Converts the “pwdLastSet” timestamp field to current Unix epoch time to allows make further comparisons by creating a field “lasttime”.

    |eval diff=round(((now() - lasttime)/86400),2)  

    Converts the “lasttime” (the last time password was set in days) by creating a new field called “diff”.

    | eval timediff = n - diff

    Assuming your organizational policy for password change is “90 days” where n = number of days. This will calculate the “the time left to change password after n days”.

    | stats values(whenCreated) as "Created Date" latest(lastLogonTimestamp) as "LastLogonTime" values(OU) as OU values(sAMAccountName) as sAMAccountName values(pwdLastSet) as PWDLastSet values(timediff) as "Time left to change password" by displayName

    This search will tabulate resulting fields by the User’s displayname.

    Result

    Any user/service account that is non-compliant or has not changed the password within the Organization’s policy will have a negative sign (-) before the accrued number of days, signifying the number of days their password has been not being changed. The user accounts that are compliant will have a positive sign (+) before the number of days, signifying the number of days left to change their password.

    Example of a dashboard panel of an active user accounts list.
    Example: Dashboard Panel of Active User Accounts

    This can be turned into the following knowledge objects.

    Alert
    Splunk will send an email alert to the admin with list of user/service accounts with negative sign (-) to take action and user/service accounts with the number days left to change password.

    Dashboard Panel
    This can form part of a Splunk dashboard that will be constantly monitored by an Admin.

    Report
    Splunk can be set to send a report to the admin on a monthly or quarterly basis with the list of active user accounts and how much time left to change their password.

    That will do it! Now you’ll equip your team with brute force security monitoring for passwords using Splunk. If you would like more details, please contact us using the form below. Happy Splunking!

  • Slice And Dice: Comparing Values Over Specific Times With Splunk Dashboards — Part Two

    Slice And Dice: Comparing Values Over Specific Times With Splunk Dashboards — Part Two

    By Marvin Martinez, Team Lead – Security Operations

    Part Two: Isolate and Compare

    Welcome back to our series discussing some unique ways to visualize data across specific points in time with Splunk SPL! In Part One, we created a dashboard chart to show day over week values over multiple weeks. In this segment, we will expand on our previous chart and isolate and compare one day from a specific week to the same day from the current week and show the percentage change between the two values across the day in a new area chart visualization.

    Using our sales example from our first installment (shown below), we showed a full day across 4 weeks, overlaid in one line chart visualization. Now, what if, after analyzing this at a high level, you wanted to display percentage changes between the latest Thursday (red line) and the Thursday 3 weeks back (blue line)?

    Time series comparison graph in Splunk displaying multiple Thursdays across different weeks, labeled by date and color-coded to show trends over a single day.

    Once we’re done, our visualization will look as shown below. In the image below, a dropdown input is populated with the options for the last 3 weeks and is passing a value of 1-3 to send as a token to the panel search in order to determine which week to compare with the day from the current week. The panel itself consists of an area chart visualization that will be formatted with the week values as chart overlays to highlight the percentage change.

    Splunk dashboard chart showing percentage change between Current Week and Compared Week using an area overlay and dual-axis line graph.

    Since the search is a little extensive and consists of various parts, let’s view the complete search first and then break it down to its various steps to make it easier to digest. This is the search that was used for the panel above. The field being used for the chart is the TotalSales field.

    index=test …
    | eval Date = strftime(_time,"%m/%d"), Day = strftime(_time,"%A"), Hour=strftime(_time,"%H"), TotalSales = round(TotalSales,2)
    | fields  _time, "TotalSales", Hour, Day, Date
    | where Day = "Thursday"
    | sort 0 - _time
    | streamstats dc(Date) as WeekNum current=true
    | eval WeekNum = WeekNum - 1
    | where WeekNum = 0 OR WeekNum = 3
    | stats values(LatestWeek) as CurrentWeek, values(PriorWeek) as PriorWeek, values(eval(if(WeekNum=0,Date,NULL()))) AS Date by Hour
    | eval CurrentWeek = IF(ISNULL(Date),"",CurrentWeek), Delta_Percentage = round(((CurrentWeek - PriorWeek)/PriorWeek) * 100,2)
    | eval xAxis = "Hour (" . Date . ")"
    | eval {xAxis} = Hour
    | rename CurrentWeek AS "Current Week", PriorWeek as "Compared Week", Delta_Percentage AS "% Change"
    | fields "Hour *" "% Change" "Current Week" "Compared Week"
    
    

    Let’s break this search down and explain what is going on here. The first 4 lines are setting up our data. We create fields to store the specific Date, Day, and Hour for our values as well as filter out only the information for the specific day we are looking to compare. In this case, Thursday is the selected day but this could easily be replaced with a token here to allow dynamic selection of any day of the week.

    | sort 0 - _time
    | streamstats dc(Date) as WeekNum current=true
    | eval WeekNum = WeekNum - 1
    | where WeekNum = 0 OR WeekNum = 3

    These next 4 lines of the search allow us to filter for the day of the current week and the day of the selected week. A quick way to do that here is to sort the result set in descending date order, then running a streamstats command to get the distinct number of weeks. Using this strategy, it makes it much easier to be able to configure a dropdown input to easily allow someone to simply select any previous week with just a number. In this case, the where command is filtering for WeekNum = 0 or WeekNum = 3, which will isolate only the values for the Thursday of the current week or the Thursday 3 weeks back. This “3” value is where you could instead use a token from a dropdown to allow for dynamic selection of different weeks back. At this point, we have now isolated our result set to solely the two days we are looking to compare.

    | stats values(LatestWeek) as CurrentWeek, values(PriorWeek) as PriorWeek, values(eval(if(WeekNum=0,Date,NULL()))) AS Date by Hour
    | eval CurrentWeek = IF(ISNULL(Date),"",CurrentWeek), Delta_Percentage = round(((CurrentWeek - PriorWeek)/PriorWeek) * 100,2)

    Now that we have isolated our data, we can use stats to perform our aggregation and group our values according to each hour of the day into their own separate fields. Since our result set is now only from the current week and the selected week in the past then, logically, the “latest” value will be from the current week and the “earliest” value will be from the previous, selected week. We group these by Hour of the day and each event will now have the value for each hour from both days. Crucially, this is what we need in order to be able to calculate the percentage delta between periods. Note that the Date field is pulled so we can have the latest date reflected in our x-axis for reference, as we’ll see later. The following eval command nulls out any CurrentWeek values when the Date field is also null to avoid any issues with the charting if Date values are null but those CurrentWeek values are not. Additionally, we calculate the Delta_Percentage between the two values.

    At this point, if you ran the search up to our latest command, your results should return a table with the Hour of the day, a CurrentWeek and PreviousWeek value for each of the days being compared, the date of the day of the current week, and the delta percentage between the day from the current week and the week being compared.

    Tabular view in Splunk displaying hour-by-hour comparison between CurrentWeek and PriorWeek values with calculated delta percentage changes.

    Now, all that remains is to get all the fields named in a more presentable fashion before we prepare our chart. That’s what the last 4 lines in our SPL achieve.

    | eval xAxis = "Hour (" . Date . ")"
    | eval {xAxis} = Hour
    | rename CurrentWeek AS "Current Week", PriorWeek as "Compared Week", Delta_Percentage AS "% Change"
    | fields "Hour *" "% Change" "Current Week" "Compared Week"

    The first line above assigns a field (xAxis) with the string “Hour” followed by the date of the “current day” being compared in parentheses. In this example, that text will read “Hour (12/16)”. Then, in the second line, that text is used to create a field by that name (the field label in braces) and is assigned the value of the Hour. In the last two lines, we just rename our fields to be more presentable and then leave only the Hour (using the “Hour *” wildcard to allow for the date in the field label), % Change, Current Week and Compared Week.

    Finally, we can configure our visualization! Format the panel/visualization as an area chart. Assign Current Week and Compared Week as Chart Overlay fields and set them to be on their own axis.

    Full view of Splunk’s Chart Overlay configuration panel, highlighting overlay selection, axis toggles, and optional settings like interval, min/max values, and scale.

    This will show the two values as lines on the chart and leave the % Change field as the shaded area between them to help visualize the percentage difference between the Thursday this week and the Thursday 3 weeks ago, across every hour of the day. Until next time!

    Repeated Splunk dashboard showing percentage change area chart comparing 3 weeks back with the current week on a 24-hour time axis.

    Stay tuned for our next installment in this series on unique Splunk Dashboard panels, when we will discuss how to pick one single value from the day (i.e. a specific hour value) and plot it back across the same hour and day from previous weeks in one line! A sample image is shown below.

    Line chart comparing metrics from the past four weeks and current week, plotting values over time using a “WeeksBefore” x-axis label and highlighting trends across dates.

    Contact Marvin below to ask questions or share ideas. Happy Splunking!