Get Demo

How to Build Custom SAP Security Monitoring Scripts

A guide to building custom ABAP scripts for SAP security monitoring, covering audit log extraction, SoD detection, SIEM integration, and maintenance best practi

📅 Published: June 2026 🔐 Cybersecurity • SIEM ⏱️ 8–12 min read

To build custom SAP security monitoring scripts, you need to write ABAP reports that interface with the SAP Security Audit Log (SM19/SM20), extract user authorization data from tables like USR02 and AGR_1251, and apply a rule engine for transaction risk analysis. These scripts typically pull session activity, detect authorization misuse, and flag deviations from baseline usage patterns — all without relying on commercial GRC suites. For enterprise teams seeking an integrated monitoring layer that correlates these script outputs with broader IT security telemetry, CyberSilo SAP Guardian provides a purpose-built platform that ingests, normalizes, and alerts on custom SAP monitoring data alongside SIEM workflows.

SAP environments are notoriously opaque to standard security monitoring tools. Native logging is often incomplete, audit logs are rotated aggressively by default, and the complexity of authorization objects makes manual oversight impractical at enterprise scale. Custom monitoring scripts bridge this gap — they give Basis teams and security architects the ability to inspect specific transaction activity, measure segregation of duties compliance, and generate forensic evidence for incident response. This guide covers the full methodology: planning the monitoring scope, writing the ABAP code, scheduling execution, integrating results with alerting infrastructure, and maintaining the scripts across system upgrades.

Understanding SAP Security Monitoring Requirements

Before writing a single line of ABAP, you must define what you are monitoring and why. SAP security monitoring scripts generally fall into five functional categories:

SAP Basis administrators and IT security managers responsible for ERP environments should prioritize monitoring the highest-risk areas first: production system access, sensitive authorization objects (S_TABU_DIS, S_TCODE), and RFC gateway activity. These areas represent the most common attack vectors in real-world SAP compromises documented by the SAP Security Response Team.

Critical security note: Custom monitoring scripts must not interfere with SAP's own security audit logging mechanisms. Running aggressive polling intervals (less than 30 seconds) on tables like USR41 (user logon info) or SM19 (audit configuration) can degrade system performance. SAP strongly recommends querying the static security audit log (table SM20_CACHE) rather than the active write buffer.

Core ABAP Techniques for Security Scripting

Effective SAP security scripts rely on a standard set of ABAP development patterns. You are not building a full application — you are building targeted, reusable data extraction and analysis routines.

Accessing the Security Audit Log

The primary data source for transaction-level monitoring is the SAP Security Audit Log, which records auditable events based on your audit configuration (SM19). To extract records programmatically, use function module SM20_GET_LOG_DATA:

DATA: lt_audit_log TYPE sm20_tab,
      lv_date_from TYPE sm20_date VALUE '20250101',
      lv_time_from TYPE sm20_time VALUE '000000'.

CALL FUNCTION 'SM20_GET_LOG_DATA'
  EXPORTING
    date_from = lv_date_from
    time_from = lv_time_from
  TABLES
    sm20_tab  = lt_audit_log.

This returns a list of all audit records matching your filter criteria. You can then loop over lt_audit_log and evaluate fields like USERNAME, TCODE, EVENTID, and MESSAGE to detect unauthorized transaction execution. For sustained monitoring, schedule this report via SM36 with a frequency of 10–15 minutes in production systems.

User Authorization and Role Analysis

To check current user authorizations programmatically, you can call the ABAP authorization check function modules directly:

DATA: lv_user(12) TYPE c VALUE 'DEVELOPER01',
      lv_tcode(20) TYPE c VALUE 'SE16'.

CALL FUNCTION 'AUTHORITY_CHECK_TCODE'
  EXPORTING
    user  = lv_user
    tcode = lv_tcode
  EXCEPTIONS
    no_authority = 1
    user_does_not_exist = 2
    OTHERS = 3.

IF sy-subrc = 1.
  " User lacks authorization — log for monitoring
ENDIF.

For role composition analysis, query tables AGR_USERS (user-to-role assignment), AGR_1251 (role-to-authorization object mapping), and AGR_TEXTS (role descriptions). Joining these tables lets you reconstruct effective authorizations per user, critical for SoD scanning.

RFC and Gateway Monitoring

RFC abuse is a common vector in SAP attacks. Monitor RFC destinations using table RFC_DEST and logon attempts via table USR41 for current sessions. The function module RFC_GET_CLIENT_INFORMATION provides real-time connection data. For historical RFC activity, query the security audit log filtered by event class RFC_LOGON.

Building a Script Framework for SoD Detection

Segregation of duties violations remain one of the most common findings in SAP security audits under SOX and ISO 27001. A custom SoD detection script follows a three-step process:

1

Define Conflicting Authorization Pairs

Create a configuration table (ZCONF_SOD) that stores pairs of authorization objects and field values representing incompatible duties. For example: activity A (create purchase order) paired with activity B (goods receipt posting) for authorization object M_BEST_BSART. Maintain this table as a customizing cross-client table to avoid hardcoding rules.

2

Extract User Authorizations

Loop over all active users (from USR02 where USTYP = 'A') and retrieve their full authorization set. Use SUGM_COMPUTE_USER_AUTHORIZATIONS or direct table reads from UST04 and UST12. Store results in a temporary internal table — this is typically the most resource-intensive step, so batch users in groups of 50.

3

Cross-Reference Against SoD Rules

For each user, compare their authorization set against each conflict rule from ZCONF_SOD. If a user possesses both sides of a conflicting pair, flag the violation with user, role name, and authorization detail. Output results to a custom monitoring table (ZMON_SOD_VIO) and optionally trigger an alert via function module SO_NEW_DOCUMENT_ATT_SEND_API1 for email notification.

This framework runs efficiently when scheduled as a weekly background job via SM36. In environments with more than 5,000 users where performance becomes a concern, consider using SAP's bundled AIS (Access Intelligence Service) or evaluating dedicated tools like CyberSilo SAP Guardian, which pre-packages SoD rules for common SAP modules and runs risk analysis without heavy ABAP development.

Stop Fighting ABAP — Let SAP Guardian Handle SoD and Audit Monitoring

Writing and maintaining custom ABAP scripts for segregation of duties, transaction monitoring, and audit log analysis works — but it diverts your Basis team from higher-value work. CyberSilo SAP Guardian ships with pre-built monitoring rules for SAP ECC, S/4HANA, and BTP that cover the OWASP Top 10 for SAP and common SoD conflict matrices.

Integrating Custom Scripts with SIEM and Alerting

Raw script output is only useful if it reaches the security operations center (SOC) in a timely, parsable format. There are three integration approaches that enterprise teams typically use:

File-Based Export to SIEM

Write monitoring results to a dedicated application server directory using ABAP's OPEN DATASET statement in Unicode mode. Format the output as structured JSON or syslog-compatible CEF (Common Event Format). The SIEM's file collector can then ingest these flat files on a cron schedule. This method works for any SIEM platform — Splunk, QRadar, or Microsoft Sentinel — but introduces latency equal to your collection interval.

RFC-Based Push to SOAR or SIEM

For near-real-time alerting, write a BAPI or RFC-enabled function module that your SIEM or SOAR platform can call. For example, configure ThreatHawk SIEM to pull SAP monitoring records via RFC every 60 seconds. This approach reduces latency but places more load on the SAP application server — limit the data volume by pushing only delta changes rather than full extracts.

Integration via Asynchronous Messaging

For organizations using SAP's own eventing infrastructure, publish monitoring alerts as IDocs or XML messages to an integration middleware layer (SAP PI/PO or third-party ESB). The middleware then transforms and forwards alerts to the SOC. This pattern is the most scalable for large deployments but requires significant infrastructure setup.

Executive insight: Many CISOs we speak with report that custom scripts create a blind spot in their overall security monitoring posture. Scripts run in isolation — they don't correlate SAP activity with Active Directory authentication logs, network flow data, or endpoint telemetry. A dedicated SAP security monitoring solution bridges that gap by feeding SAP audit data directly into the SIEM correlation engine, enabling detection of attacks that jump across SAP and non-SAP systems.

Scheduling and Maintenance Best Practices

Custom ABAP scripts require ongoing care. SAP system upgrades, support package installations, and authorization object changes can all break your monitoring logic silently. Follow these operational guidelines:

Comparing Custom Scripts vs. Dedicated SAP Security Solutions

Organizations evaluating whether to build or buy SAP security monitoring capabilities should consider this comparison across key decision criteria:

Capability
Custom ABAP Scripts
Dedicated Solution (e.g., SAP Guardian)
Deployment speed
2–4 weeks to develop basic scripts
Days to configure for standard use cases
SoD rule coverage
Requires manual rule definition per module
Pre-built rule libraries for FI, CO, MM, SD
SIEM correlation
Manual file export or custom RFC
Native integration with ThreatHawk SIEM and major platforms
Maintenance overhead
Quarterly reviews; breaks on transport
Vendor-managed updates; SAP H2 releases
S/4HANA & BTP ready
Scripts need rework for CDS views
Native support for ABAP Platform Cloud

Custom scripts remain a viable option for organizations with dedicated ABAP development capacity and relatively small SAP landscapes (under 1,000 users). For larger enterprises across financial services cybersecurity, manufacturing cybersecurity, or regulated sectors with multiple SAP instances, a dedicated monitoring solution reduces long-term operational risk. Teams that already use top 10 SIEM tools will find that SAP Guardian integrates directly with their existing SOC workflow, eliminating the need for custom middleware bridges.

Reduce Your ABAP Script Maintenance by 80% — Without Sacrificing Visibility

If your team spends more than 40 hours per quarter maintaining custom SAP monitoring scripts, a shift to CyberSilo SAP Guardian will deliver immediate ROI. Get out-of-the-box audit log parsing, real-time SoD detection, and seamless integration with your existing security operations — all without touching a single ABAP line.

Extending Scripts with Threat Intelligence and Behavioral Analytics

Advanced monitoring scripts can incorporate threat intelligence feeds and behavioral baseline comparisons to detect sophisticated attacks that static rule checks miss. For example, you can cross-reference RFC source IPs against known malicious indicators from a ThreatSearch TIP. While custom scripting makes this possible, it requires ongoing feed maintenance and integration development.

Behavioral baselines are more straightforward to implement in ABAP. Collect historical usage data per user and transaction over a 30-day window, compute standard deviation thresholds, and flag sessions that exceed three standard deviations from the mean. Store baseline results in a periodic table like ZMON_BASELINE and refresh it weekly via an SM36 scheduled job.

For organizations monitoring specifically for insider threats, consider combining download activity logs (table SM04 for active sessions, table USR02 for last logon timestamp) with HR master data to detect users accessing the system after their last employment date — a classic indicator of terminated employee account abuse.

Compliance Implications for SOX and ISO 27001

Custom monitoring scripts must satisfy the same audit requirements as any other security control. For SOX compliance, your script inventory should include:

Under ISO 27001 Annex A.9 (Access Control), your scripts must demonstrate that monitoring covers both logical access controls (user ID management, privilege review) and physical separation of duties. Ensure your script outputs are timestamped and immutable — write results to tables that prohibit direct updates by application users.

Migrating from Custom Scripts to Enterprise-Grade Monitoring

At some threshold of SAP landscape complexity, custom scripts become a liability. Common pain points include scripts failing silently, alert fatigue from unvalidated false positives, and inability to correlate SAP activity with network or endpoint telemetry. Leaders across government and defense cybersecurity and energy sectors have shared that the breaking point is typically around three SAP instances or 2,000 users — beyond that, dedicated monitoring infrastructure is more cost-effective than ABAP maintenance.

When transitioning, keep your custom scripts running in parallel with the new solution for at least one full audit cycle. Compare findings to validate the new tool's coverage and tune its rule sensitivity. Retire scripts only after confidence in the replacement tool is established through two consecutive months of identical or superior detection results.

Many teams start with a hybrid approach: they deploy CyberSilo SAP Guardian to handle high-volume monitoring (audit log ingestion, SoD scanning, real-time alerts) while keeping one or two specialized custom scripts for niche requirements unique to their environment. This gives them the best of both worlds: enterprise-grade monitoring coverage and the flexibility to address edge cases without full ABAP dependency.

Our Conclusion & Recommendation

Custom SAP security monitoring scripts are a legitimate starting point for organizations with ABAP capability and limited budget, but they are not a long-term enterprise strategy. The scripts described in this guide — audit log extraction, SoD rule scanning, and transaction monitoring — are functional, but they require ongoing ABAP maintenance, separate SIEM integration effort, and manual tuning to avoid false positives. In a landscape where SAP attack surfaces expand with every S/4HANA migration and BTP adoption, relying on point ABAP scripts creates unacceptable gaps for CISOs managing compliance frameworks like SOX, ISO 27001, and PCI DSS.

We recommend that any organization with more than 1,500 SAP users, multiple production landscapes, or regulatory audit requirements evaluate a dedicated SAP security monitoring solution. CyberSilo SAP Guardian gives your team immediate access to pre-built monitoring rules for 50+ SAP transaction types, real-time correlation with your SIEM, and automated SoD reporting ready for external auditors. It eliminates the transport chain pain point of custom scripts and ensures your SAP security monitoring evolves with each S/4HANA release without your team writing a single line of ABAP.

Ready to Stop Writing ABAP for Security Monitoring?

Schedule a 30-minute technical assessment with our SAP security specialists. We will review your current monitoring coverage, identify gaps, and show you a live demo of CyberSilo SAP Guardian in a real S/4HANA environment.

📰 More from CyberSilo

Latest Articles

Stay ahead of evolving cyber threats with our expert insights

Privacy Compliance for US Online Retailers (CCPA & State Laws)
SIEM
Jun 23, 2026 ⏱ 17 min

Privacy Compliance for US Online Retailers (CCPA & State Laws)

See how CyberSilo helps you strengthen your security posture for US organizations. Practical guidance on privacy compliance for us online retailers (ccpa & s

Read Article
Holiday Season Cyber Threats for Retailers
SIEM
Jun 23, 2026 ⏱ 10 min

Holiday Season Cyber Threats for Retailers

Holiday Season Cyber Threats for Retailers explained for US organizations — clear, practical guidance to strengthen your security posture. Learn the essentia

Read Article
eCommerce Privacy in Canada: PIPEDA & Law 25
SIEM
Jun 23, 2026 ⏱ 10 min

eCommerce Privacy in Canada: PIPEDA & Law 25

See how CyberSilo helps you strengthen your security posture for Canadian organizations. Practical guidance on ecommerce privacy in canada with expert support.

Read Article
Cybersecurity Compliance for US Schools and Universities
SIEM
Jun 23, 2026 ⏱ 15 min

Cybersecurity Compliance for US Schools and Universities

See how CyberSilo helps you strengthen your security posture for US organizations. Practical guidance on cybersecurity compliance for us schools and universi

Read Article
Protecting Student Data: FERPA and COPPA for EdTech
SIEM
Jun 23, 2026 ⏱ 14 min

Protecting Student Data: FERPA and COPPA for EdTech

Protecting Student Data explained for US organizations — clear, practical guidance to strengthen your security posture. Learn the essentials with CyberSilo.

Read Article
Ransomware in K-12 and Higher Ed: Defense Strategies
SIEM
Jun 23, 2026 ⏱ 11 min

Ransomware in K-12 and Higher Ed: Defense Strategies

Ransomware in K-12 and Higher Ed explained for US organizations — clear, practical guidance to strengthen your security posture. Learn the essentials with Cy

Read Article
✅ Link copied!