Escaping Special Characters for SQL Queries in ABAP
Subject: SAP-ABAP (Security and Prevention of Injection Attacks)
In SAP ABAP development, constructing SQL queries dynamically is a common practice for flexible data retrieval and manipulation. However, when user inputs or external data are concatenated directly into SQL statements without proper handling, the application becomes vulnerable to SQL Injection attacks—a serious security threat that can lead to data breaches, unauthorized access, or corruption.
This article focuses on the importance of escaping special characters in SQL queries within ABAP programs to prevent injection-based crimes and ensure secure data processing.
SQL statements rely on special characters like single quotes ('), double quotes ("), semicolons (;), and backslashes (\) to delimit strings, identifiers, or commands. If user input contains these characters and is inserted directly into SQL, it can alter the intended query logic.
Example of risky dynamic SQL:
DATA lv_query TYPE string.
DATA lv_username TYPE string VALUE 'O''Reilly'; " User input with single quote
lv_query = |SELECT * FROM users WHERE username = '{ lv_username }'|.
EXEC SQL.
EXECUTE IMMEDIATE :lv_query
ENDEXEC.
If lv_username is not properly escaped, the embedded single quote in "O'Reilly" may break the SQL syntax or worse, be exploited to inject malicious SQL code.
| Character | Purpose in SQL |
|---|---|
' |
String delimiter |
" |
Identifier delimiter |
; |
Statement terminator |
\ |
Escape character |
ABAP Open SQL supports host variables that automatically handle escaping and parameter binding.
DATA: lv_username TYPE string VALUE 'O''Reilly'.
SELECT * FROM users INTO TABLE @DATA(lt_users)
WHERE username = @lv_username.
This approach prevents injection and escaping issues because SAP’s SQL engine manages parameters safely.
Dynamic SQL (string concatenation of SQL commands) is prone to injection risks. Use static or parameterized Open SQL statements instead.
If dynamic SQL must be used, explicitly escape special characters.
Example function to escape single quotes by doubling them:
FUNCTION escape_sql_string.
IMPORTING
iv_input TYPE string
RETURNING
VALUE(rv_escaped) TYPE string.
rv_escaped = REPLACE ALL OCCURRENCES OF '''' IN iv_input WITH ''''''.
ENDFUNCTION.
Usage:
DATA lv_escaped_username TYPE string.
lv_escaped_username = escape_sql_string( iv_input = lv_username ).
lv_query = |SELECT * FROM users WHERE username = '{ lv_escaped_username }'|.
Properly escaping special characters in SQL queries is a critical security step to prevent injection attacks in SAP ABAP applications. The best defense is to avoid dynamic SQL and use ABAP’s native Open SQL with host variables. When dynamic SQL cannot be avoided, carefully sanitize inputs by escaping special characters like single quotes. Combining these techniques with rigorous input validation and security best practices protects SAP systems from SQL injection-related crimes.
Further Reading: