SAP NetWeaver AS ABAP Release 740, ©Copyright 2014 SAP AG. All rights reserved.
ABAP Keyword Documentation → ABAP − Reference → Processing Internal Data → Character String and Byte String Processing → Expressions and Functions for String Processing → String Functions → Examples of String Functions →String Functions, escape for XSS
This example demonstrates the string function escape for preventing XSS.
Source Code
REPORT demo_xss.
CLASS demo DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
main,
class_constructor.
PRIVATE SECTION.
CLASS-DATA:
in TYPE REF TO if_demo_input,
host TYPE string,
port TYPE string.
ENDCLASS.
CLASS demo IMPLEMENTATION.
METHOD main.
CONSTANTS xss_demo TYPE string
VALUE `foo" onmouseover="alert('Gotcha!')`.
DATA: query TYPE string VALUE `ABAP Objects`,
esc_flag TYPE abap_bool VALUE abap_true,
xss_flag TYPE abap_bool VALUE abap_false.
DO.
in->add_field( EXPORTING text = 'Input'
CHANGING field = query
)->add_field( EXPORTING text = 'Escape'
CHANGING field = esc_flag
)->request( EXPORTING text = 'XSS-Demo'
CHANGING field = xss_flag ).
IF query IS INITIAL AND xss_flag = abap_false.
EXIT.
ENDIF.
IF to_upper( xss_flag ) = abap_true.
query = escape( val = xss_demo
format = cl_abap_format=>e_xss_ml ).
xss_flag = abap_false.
CONTINUE.
ENDIF.
IF to_upper( esc_flag ) = abap_true.
query = escape( val = query
format = cl_abap_format=>e_xss_ml ).
ELSEIF query <> xss_demo.
MESSAGE
`Without escaping only the prepared XSS-Demo is allowed.`
TYPE 'I'.
CONTINUE.
ENDIF.
DATA(html) =
`<html>` &&
`<body>` &&
`<p><a href="http://` && host && `:` && port &&
`/sap/public/bc/abap/docu?query=` &&
query && `">Search in ABAP Documentation</a></p>` &&
`<p><a href="http://www.google.com/search?q=` &&
query && `">Search with Google</a></p>` &&
`</body>` &&
`</html>` ##no_text.
cl_abap_browser=>show_html( html_string = html
buttons = abap_true
check_html = abap_false ).
ENDDO.
ENDMETHOD.
METHOD class_constructor.
in = cl_demo_input=>new( ).
CALL FUNCTION 'TH_GET_VIRT_HOST_DATA'
EXPORTING
protocol = 1
virt_idx = 0
local = 1
IMPORTING
hostname = host
port = port
EXCEPTIONS
OTHERS = 0.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
demo=>main( ).
Description
A search term can be entered in a dialog box. An output window provides a search function in the ABAP keyword documentation and with an external search engine. By default, the input is escaped using the function escape and the format cl_abap_format=>e_xss_ml. This prevents cross site scripting (XSS).
The function can be disabled for specific input, which demonstrates the effects of an XSS attack. The input makes the links on the output window and the following input field unusable. More harmful functions could be used instead of the JavaScript function alert, but are not permitted in this example.