Secure Programming – ABAP

May 30, 2016 | Author: zsbaranyai | Category: Types, Brochures
Share Embed Donate


Short Description

Secure Programming – ABAP SAP R/3 4.6C TOC PASSWORD SECURITY SECURE STORE AND FORWARD MECHANISM (SSF) SECU...

Description

SAP NetWeaver Developer’s Guide Release: SAP NetWeaver 2004s

Secure Programming – ABAP

Document Version 1.0 – May 2006

SAP AG Dietmar-Hopp-Allee 16 69190 Walldorf Germany T +49/18 05/34 34 24 F +49/18 05/34 34 20 www.sap.com

© Copyright 2005 SAP AG. All rights reserved. No part of this publication may be reproduced or

SAP, R/3, mySAP, mySAP.com, xApps, xApp, SAP

transmitted in any form or for any purpose without the

NetWeaver, and other SAP products and services

express permission of SAP AG. The information

mentioned herein as well as their respective logos are

contained herein may be changed without prior notice.

trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the

Some software products marketed by SAP AG and its

world. All other product and service names mentioned

distributors contain proprietary software components of

are the trademarks of their respective companies. Data

other software vendors.

contained in this document serves informational purposes only. National product specifications may vary.

Microsoft, Windows, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.

These materials are subject to change without notice. These materials are provided by SAP AG and

IBM, DB2, DB2 Universal Database, OS/2, Parallel

its affiliated companies ("SAP Group") for informational

Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390,

purposes only, without representation or warranty of any

OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP,

kind, and SAP Group shall not be liable for errors or

Intelligent Miner, WebSphere, Netfinity, Tivoli, and

omissions with respect to the materials. The only

Informix are trademarks or registered trademarks of IBM

warranties for SAP Group products and services are those

Corporation in the United States and/or other countries.

that are set forth in the express warranty statements accompanying such products and services, if any.

Oracle is a registered trademark of Oracle Corporation.

Nothing herein should be construed as constituting an additional warranty.

UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group. Disclaimer Citrix, ICA, Program Neighborhood, MetaFrame,

Some components of this product are based on Java™.

WinFrame, VideoFrame, and MultiWin are trademarks or

Any code change in these components may cause

registered trademarks of Citrix Systems, Inc.

unpredictable and severe malfunctions and is therefore expressively prohibited, as is any decompilation of these

HTML, XML, XHTML and W3C are trademarks or

components.

®

registered trademarks of W3C , World Wide Web Consortium, Massachusetts Institute of Technology.

Any Java™ Source Code delivered with this product is only to be used by SAP’s Support Services and may not

Java is a registered trademark of Sun Microsystems, Inc.

be modified or altered in any way.

JavaScript is a registered trademark of Sun

Documentation on SAP Developer Network

Microsystems, Inc., used under license for technology

You can find this documentation at

invented and implemented by Netscape.

https://www.sdn.sap.com/irj/sdn/devguide2004s

MaxDB is a trademark of MySQL AB, Sweden.

Secure Programming – ABAP

2 / 50

Contents

Secure Programming – ABAP .........................................................................................4 PURPOSE .............................................................................................................................................................. 4 TARGET GROUP ................................................................................................................................................... 4 ABOUT THIS DOCUMENT ..................................................................................................................................... 4 DISCLAIMER ........................................................................................................................................................ 5

Secure Programming ........................................................................................................6 PASSWORD SECURITY.......................................................................................................................................... 6 SECURE STORE AND FORWARD MECHANISM (SSF) ............................................................................................ 9 SECURITY LOGGING .......................................................................................................................................... 11 SAP VIRUS SCAN INTERFACE ............................................................................................................................ 15

Secure User Interface ....................................................................................................21 CROSS-SITE SCRIPTING (XSS)........................................................................................................................... 21 SQL INJECTION ................................................................................................................................................. 30 INPUT VALIDATION ........................................................................................................................................... 35 CANONICALIZATION .......................................................................................................................................... 38 DIRECTORY TRAVERSAL ................................................................................................................................... 40 URL ENCODING AND MANIPULATION ............................................................................................................... 43 COOKIE MANIPULATION .................................................................................................................................... 46

Further Information .........................................................................................................49 Disclaimer ..........................................................................................................................50

Secure Programming – ABAP “Security is like adding brakes to cars. The purpose of brakes is not to stop you: it’s to enable you to go fast!” ---Gene Spafford

Purpose This documentation provides an overview about developing secure applications based on the SAP NetWeaver platform. It describes common security errors and weaknesses to watch out for as well as approved procedures so that your application functions “securely”. Target Group The target group of this documentation are ABAP developers who are developing applications based on the SAP NetWeaver platform. This guide is primarily aimed at developers in the IT departments of customers, consulting houses, and partners. About this Document This documentation is divided into the following sections: •



Secure Programming o

Password Security

o

Secure Store & Forward Mechanism (SSF)

o

Security Logging

o

SAP Virus Scan Interface

Secure User Interface o

Cross-Site Scripting (XSS)

o

SQL Injection

o

Input Validation

o

Canonicalization

o

Directory Traversal

o

URL Encoding and Manipulation

o

Cookie Manipulation

For each topic mentioned above the security vulnerability is described. Then any standard solutions that exist from the SAP NetWeaver platform are presented, including functions and interfaces that need to be used. If no solution is available from the SAP NetWeaver platform, recommendations are provided about appropriate security measures to take. In addition, example code is provided where appropriate and links to existing documentation are given.

Secure Programming – ABAP

4 / 50

Disclaimer All description of secure programming and all sample code (for the purposes of this clause hereinafter referenced together as the "Examples") contained in this document are for illustrative purposes only. These Examples have not been thoroughly tested under all conditions. SAP, therefore, cannot guarantee or imply reliability, serviceability, or function of these Examples. Any use of these Examples is at your own risk and responsibility and SAP shall not be liable for any damages caused by the use of such Examples unless such damages have been caused by SAP's gross negligence or willful misconduct.

Secure Programming – ABAP

5 / 50

Secure Programming Implementing Security Developers common problem is a lack of time, they usually struggle with design, functionality, performance, usability and so one. Therefore, they spend less of time to think about security aspects and possible insecure software design or insecure programming techniques. The attackers on the other hand have all the time to find out the software vulnerabilities. Although a clever design is certainly a good starting point, it’s not enough to achieve secure software: Implementation has tricks of its own. In the following sections we’ll give you support to secure your code. In particular this guide addresses common errors and weaknesses and describes approved procedures.

Password Security Description Passwords are a familiar way to verify the identity of users and systems. Passwords are simpler and cheaper than other, more secure forms of authentication like smart cards or biometric scanners. They provide a simple, direct means of protecting a system or an account. However, there are also known weaknesses. Password cracking is the process of figuring out or breaking passwords in order to gain unauthorized access to a system or an account. Many passwords are not random but trivial to guess. A more technical way of cracking passwords is through network sniffers, which look at the raw data transmitted across the network and decipher its contents, including passwords. Furthermore, attackers can try to crack passwords offline when they can access the hashed password string during transmission or in an insecure password store. The password-based approach of authentication can be used to protect applications when the following advices are taken into consideration.

What Do I Get from the SAP NetWeaver Platform? The overall process of password-based identification and authentication is as follows. First, the application asks for the user identification, usually the user’s account name. Then the password is read and a hash-value of the password is calculated. Often a salt, that is a random string of data, is added in order to prevent an attacker from testing known dictionary words. Some password components also wipe the memory in which the password was stored. Finally, it has to be checked, whether the hashed user input and the stored hash value of the password match. If yes, the user is successfully authenticated. The SAP NetWeaver platform provides such an authentication mechanism as described above. Generally, it is recommended to use the existing password authentication mechanism provided by the SAP NetWeaver platform instead of implementing something on your own.

Secure Programming – ABAP

6 / 50

What Do I Need to Do? The issues described above necessitate that you handle user IDs and passwords carefully. The following recommendations may help to prevent that an unauthorized person will gain access to your system: 1. Are no passwords displayed in plaintext? •

Do not display passwords in plaintext, use asterisk instead.

2. Are no passwords saved or transmitted in plaintext? •

Passwords transmitted in plain text can be intercepted, rendering the user ID and password method of identification insecure. It is better to transmit passwords using the Secure Network Communications (SNC) protocol.



Do not save passwords in plaintext.



Avoid the administrator to gain access to the password. Use secure hash functions to prevent password recovery. → The SAP NetWeaver platform uses secure hash values to store passwords.



Do not invent your own coding to encrypt the original password.

3. Are no passwords hard-coded in the source code? •

Use a technology such as one-time passwords.



Apply a changeable password in a central function, such as transaction SM59.



Do not invent your own encryption algorithm.

4. Are no passwords recorded in log/protocol/trace files? •

Do not use HTTP GET-requests since all parameters will be found in the URL. Use HTTP POST-requests instead. In general, you should avoid transmitting passwords, in particular with every request you send. Use secure mechanisms instead, such as digital certificates for example.



Take into account that the Web Server logs all the URLs.



Passwords may also be displayed in readable form when tracing, depending on the trace settings.

5. Are passwords in plaintext overwritten in memory once they are no longer used? •

Do overwrite passwords in memory, otherwise they might still exist in memory even after completion of the application and could thus be read by a malicious application.

6. Are user ID and password neither preconfigured nor callable through a pull down menu at the start of the application? •

Better avoid to use any pull down menu for the user ID/password entry. This is in particular important for the password.

7. Can all passwords, IDs and user names be changed? •

Non-changeable IDs and passwords often form the starting point for attacks on an application’s security.

Secure Programming – ABAP

7 / 50

Further Information 1. Checklist for secure programming (section “Password Security”) https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/4ab8b3bb-06010010-7b82-e392df20392a

Secure Programming – ABAP

8 / 50

Secure Store and Forward Mechanism (SSF) Description You can use digital signatures and document encryption in your application to provide for document security. These documents are then protected as independent objects using Secure Store and Forward (SSF) mechanisms. This means that the documents are secured irregardless of where they are stored or how they are transported. You can apply a digital signature to any digital document or message, which is comparable to a handwritten signature on a paper document. The digital signature uniquely identifies the signer of the document or message. It is not forgeable and also protects the integrity of the document. If the document is changed after being signed, then the digital signature is no longer valid. Also, the signer of such a document cannot deny having signed the document at a later time. In addition, you can encrypt documents so that only intended recipients can view their contents. The functions for digital signatures and document encryption use public-key technology. Public-key technology is based on the use of a key pair; one of which is a private key and the other is a public key. The private key is to be kept secret; the public key is to be distributed as desired. More detailed information on public-key technology is provided in Public-Key Technology [SAP Library].

What Do I Get from the SAP NetWeaver Platform? The SAP NetWeaver platform provides Secure Store & Forward (SSF) mechanisms as internal means to protect arbitrary data in the SAP system. SAP applications can use the SSF mechanisms to secure data integrity, authenticity and confidentiality. By using SSF functions, you can "wrap" data and digital documents in secure formats before they are saved on data carriers or transmitted over (possibly) insecure communication links. The data must not remain within the SAP System; if you save the data in a secure format in the SAP System, it remains in its secured format even if you export it out of the system. More detailed information on the Secure Store and Forward Mechanism (SSF) is provided in Secure Store & Forward Mechanisms (SSF) and Digital Signatures [SAP Library].

Restrictions SSF requires the use of a third-party security product to provide its functions. As the default provider, we deliver the SAP Security Library (SAPSECULIB) with SAP Systems. The SAPSECULIB, however, is limited to providing digital signatures only. For digital envelopes, encryption, or crypto hardware (for example, smart cards or crypto boxes), you need to use a external security product. SAP provides the SAP Cryptographic Library free of charge, or you can use a certified partner product. The SAP Cryptographic Library is available for download on the SAP Service Marketplace at http://service.sap.com/download. Note however, that this library underlies German export regulations and is therefore not available to all customers. For information about supported partner products, see the SAP-certified partners (http://www.sap.com/softwarepartner).

Secure Programming – ABAP

9 / 50

There are also laws in various countries that regulate the use of cryptography and digital signatures. These laws are currently controversial and may change. You need to keep yourself informed on the impact these laws may have on your applications, and make sure that you are aware of any further developments.

What Do I Need to Do? The SSF Library for the ABAP Stack is used in applications that are written in ABAP. It supports the functions for creating and verifying digital signatures (PKCS#7), and functions for encrypting and decrypting documents. The SSF Library for the ABAP stack is available as of SAP Basis 4.0. SSF provides the following ABAP function modules from the SSFG function group: ¾ SSF_SIGN / SSF_KRN_SIGN

Creating digital signatures

¾ SSF_VERIFY / SSF_KRN_VERIFY

Checking digital signatures

¾ SSF_ENVELOPE / SSF_KRN_ENVELOPE

Encrypting documents

¾ SSF_DEVELOPE / SSF_KRN_DEVELOPE

Decrypting documents

For a detailed description about these SSF function modules as well as example code about how to call the appropriate function modules see the Secure Store and Forward (SSF) Programmer's Guide. For further guidelines regarding digital signatures please also see Digital Signatures in SAP Applications.

Further Information 1. Digital Signatures and Encryption [SAP Library] 2. Secure Store & Forward Mechanisms (SSF) and Digital Signatures [SAP Library] 3. Guideline: Digital Signatures in SAP Applications https://service.sap.com/~form/sapnet?_SHORTKEY=01100035870000668332&_SCENA RIO=01100035870000000112&_OBJECT=011000358700000952762004E 4. Secure Storage and Forward (SSF) Programmers’ Guide https://service.sap.com/~sapdownload/011000358700003611992003E/SSFProgrammers Guide.pdf 5. Secure Storage & Forward / Digital Signatures User’s Guide http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/icc/Secur e%20Store%20and%20ForwardDigital%20Signatures%20User%20Guide.pdf 6. Secure Store & Forward (SSF) API Specifications http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/icc/Secur e%20Store%20and%20Forward%20SSF%20API%20Specifications.pdf

Secure Programming – ABAP

10 / 50

Security Logging Description SAP Systems keep a variety of logs for system administration, monitoring, problem solving, and auditing purposes. Audits and logs are important for monitoring the security of your system and to track events in case of problems.

What Do I Get from the SAP NetWeaver Platform? Depending on the data type SAP Systems offer different frameworks for logging data changes. In addition, several frameworks exist for logging events. For an overview of the different frameworks provided, please see the following table:

Data Type / Events

Framework

1. Events

Security Audit Log, System Log, Application Log

2. Repository Data

Version Management

3. Customizing Data

Table Protocols

4. Master Data

Standard Change Documents

5. Transaction Data

(Note: No framework is provided. It is not useful to log transaction data.)

What Do I Need to Do? Every time a log is required to trace data changes or system events, verify, whether a logging mechanism is already provided by the SAP System which fulfills your demands. The use of standard functionality should be preferred. In this case, you automatically inherit all functions from the framework (for example, archive routines for change documents). a) Security Audit Log The Security Audit Log is available on the SAP Web Application Server. The tool is designed for auditors who need to take a detailed look at what security-related events have occurred in the SAP System. The Security Audit Log may be activated or deactivated. By activating the audit log, the system keeps a record of those activities the customer considers relevant for auditing. The information may be evaluated by an audit analysis report. The Security Audit Log enables insight in the daily work processes and system events, such as failed logon attempts or transaction starts. The audit log's main objective is to record: •

Security-related changes to the SAP System environment For example: ¾ Changes to user master records ¾ Changes to the audit configuration

Secure Programming – ABAP

11 / 50



Information that provides more transparency For example: ¾ Successful and unsuccessful dialog logon attempts ¾ Successful and unsuccessful RFC logon attempts ¾ Application server start and stop ¾ Download of files



Information that enables tracing of a series of events For example: ¾

Successful and unsuccessful transaction starts

¾

Successful and unsuccessful report starts

¾

RFC calls to function modules

More information is provided in Security Audit Log [SAP Library]. b) System Log Beyond the Security Audit Log the ‘normal’ System Log is written in the SAP system too. The System Log provides a more technical view on the events in a system, such as rollbacks, database read errors, dumps etc. The System Log is written on a continuous basis and may not be deactivated. Each event is recorded as a system log message under the system log numbers AU (or BU or CU since Release 6.10). More information is provided in System Log [SAP Library]. c) Application Log The Application Log is a tool that collects messages, exceptions, and errors. This information is organized and displayed in a log. Application logs are useful to bring situations, that occur at runtime of an application program, to user’s attention. In standard SAP Systems you will find application logs in QM, for example. If you provide the Application Log (events) as an infrastructure in your own programs, take into account, that it is used to temporarily store messages. Data that, for reasons of revision security, have to be available for a long period of time, should not be stored with the application log but with the Change Documents [SAP Library] (changed data). Developers who want to integrate the Application Log in their applications will find a detailed documentation on all function modules and archiving techniques using archiving object BC_SBAL and an overview of callback routines executing the report SBAL_DOCUMENTATION in transaction SA38. More information is provided in Application Log – Guidelines for Developers (BC-SRV-BAL). d) Audit Info System (AIS) The Security Audit is not to be confused with the Audit Info System (AIS). The Audit Info System (AIS) [SAP Library] is designed to facilitate and improve the audits performed by external auditors as well as internal auditors. The system is designed for Business Auditors, System Auditors and Security Administrators; even many System Administrators find it a useful tool.

Secure Programming – ABAP

12 / 50

e) Version Management You use the version management function for Repository objects when making modification adjustments. The aim of version management is to keep track of all changes made to a Repository object. Therefore, the system automatically creates versions. More detailed information is provided in Version Management [SAP Library]. f) Table Protocols The analysis of logged customizing objects allows the customer to answer the following questions: ¾ Who has changed customizing settings? ¾ When and what has been changed? For further information refer to Logging Customizing Objects [SAP Library]. Log files are written, in case the following prerequisites are met: ¾ The rec/client parameter in the system profile is set to allow data logging. ¾ Logging is active for the table. For technical settings see Activate/Deactivate Table Change Logging [SAP Library]. When developing your application, you have to decide for which tables you want to activate logging. You can activate table change logging in the technical settings of the table using transaction SE11. g) Standard Change Documents Many business objects are changed frequently. Therefore, it is often useful and even necessary to be able to trace the changes made. This logging is carried out with change documents. Detailed information is provided in Change Documents [SAP Library] and Creation of Events When Change Documents are Written [SAP Library].

How to Use a Logging Framework? When using a logging framework, the following advice may help: 1. Keep in mind, that the aim of a log should always be the traceability of events on the business object of interest. 2. All data and documents must be assigned to the relevant transactions. 3. Never log passwords in clear text. 4. Logs should not contain potentially confidential data such as credit card numbers or social security numbers. Instead, log such sensitive data in specially protected logs with authorization checks.

How Not to Do It? As mentioned before, don’t create your own logging framework! Instead, use a logging mechanism already provided by the SAP System. If no standard functionality is provided that fulfills your demands, try to get your required features included into the existing standard frameworks. All existing standard logging frameworks provided by the SAP System offer the following features that are required by a good logging framework: Secure Programming – ABAP

13 / 50

1. Logging and archiving should be customizable, because every customer has different requirements. Even writing of log entries may be activated and deactivated in the system. 2. Logs should only be readable and never be changeable, due to traceability. Make sure, that there is a check implemented to deny unauthorized access to logs. 3. Logs should contain information about: ¾ The reason for logging. ¾ The user, who has created the log entry. ¾ Date and time, when the log entry has been written. ¾ System and client where the log entry occurred. 4. Consider how logs should be handled, i.e. whether they can be deleted or be archived. 5. Take into account that log file creation alters performance. Secondly, many users access this log table in parallel. This could cause lock situations even though the users are working with different application tables.

Further Information 1. SAP Web Application Server Security Guide (Chapter 6.4 Auditing and Logging) https://service.sap.com/~form/sapnet?_FRAME=CONTAINER&_OBJECT=01100035870 0001994272004E 2. SAP documentation about BAL_* Application Log Function modules Execute program SBAL_DOCUMENTATION in transaction SE38 within the mySAP ERP 2005

Secure Programming – ABAP

14 / 50

SAP Virus Scan Interface Description Virus scanning should be performed every time potentially polluted data is imported via input channels into the SAP system. Possible input channels are: ¾ File upload from front-end PC’s or file system on the application server ¾ File upload via Internet ¾ Document exchange via RFC, XML, XI

What Do I Get from the SAP NetWeaver Platform? The architecture of the Virus Scan Interface (VSI) allows you to combine different products, systems, and platforms to scan your applications for viruses. On the SAP side, different VSILIB layers are used to include the ABAP and Java worlds, and to deal with platform dependencies in the integration of the virus scan interface. For further information see Architecture of the Virus Scan Interface [SAP Library].

Figure 1: Elements of the Virus Scan Interface

The graphic below clarifies the layer structure of the SAP Virus Scan Interface (SAP VSI API) and shows which parts are delivered by SAP, and which by the relevant partners.

Secure Programming – ABAP

15 / 50

Figure 2: Software Layers of the Virus Scan Interface

The SAP Virus Scan Interface (SAP VSI API): •

Is accessed by partner products directly with the scan engine or indirectly using a separate virus scan adapter.



Contains the functions required to configure and to initialize the scan engine.



Provides the parameters and data for every virus scan.



Processes the check result.

ABAP or Java application programs start virus scans with dedicated classes and methods of the SAP virus scan interface, which, in turn, call a virus scan server or the J2EE Engine directly using RFC.

What Do I Need to Do? To be able to use SAP’s Virus Scan Server, you must maintain data in the Implementation Guide. 1. Scanner Groups Scanner groups bundle together one to many Virus Scan Servers or Business Add-In implementations (BADI VSCAN_INSTANCE) of scan engines. On this level, a set of configuration parameters can be maintained that contain initialization parameters for the Virus Scan Servers. Be aware that customizing settings are cross-client as the controlled entities (Virus Scan Servers or BADIs) are cross-client. Detailed information is available in Defining Scanner Groups [SAP Library]. 2. Virus Scan Servers The Virus Scan Server is an RFC-Server, that holds the connection to the scan engine using the certified Virus Scan Adapter. It is running either as part of the application server as separately started executable or as standalone program and Secure Programming – ABAP

16 / 50

communicates over RFC with the application servers. A Virus Scan Server entry always belongs to a single scanner group. The detail screen of the Virus Scan Server maintenance shows a summary of the scan engine type and the supported features. The Server may be manually started, stopped and re-initialized from the customizing. To set up customizing see Defining Virus Scan Servers [SAP Library]. The Virus Scan Interface may be integrated into own developments using the methods out of class CL_VSI. For detailed information refer to Integrating the Virus Scan Interface into Customer Developments [SAP Library]. Furthermore, the following SAP notes may help to clarify questions concerning the Virus Scan Interface: SAP Note 817623, SAP Note 786179. 3. Virus Scan Profiles For each application own Virus Scan Profiles may be created in customizing, mapping Scanner Groups to Virus Scan Servers or customer defined Business AddIns. Profiles have to be its own namespace delivered by SAP // Profiles can be: ¾ marked as Default Profile ¾ activated or deactivated ¾ assigned to reference profiles. More information is supplied in Defining Virus Scan Profiles [SAP Library]. If customizing is set up for the active Virus Scan Interface, you may integrate the VSI in your application using the class CL_VSI. In order to perform a virus scan for a byte sequence check in an ABAP program, the following steps are required: 1. Use the static method GET_INSTANCE to generate an instance of the virus scan interface, which is based on the specified virus scan profile. Every application that implements VSI should use its own virus scan profiles so that the virus scan functions can be activated and deactivated for each application. Examples * Retrieve scanner instance for my application DATA: lo_scanner TYPE REF TO cl_vsi. CALL METHOD cl_vsi=>get_instance EXPORTING if_profile = '/MYPACKAGE/MYFUNCTION' IMPORTING eo_instance = lo_scanner EXCEPTIONS profile_not_active = 1 OTHERS = 2. CASE sy-subrc. WHEN 0. "OK

Secure Programming – ABAP

17 / 50

WHEN 1. * The system administrator has disabled virus scanning * for * my application '/MYPACKAGE/MYFUNCTION'. * What must happen now depends on whether virus scanning * is optional or mandatory for your application. * In the first case, you can ignore it, in the second * case * you must react with an error. This exception has a * SY-Message that leads the user to the right place in * customizing. WHEN OTHERS. * This situation is always an error (misconfiguration) * of the Virus Scan Interface. It must be reported. * Use the SY-Message that always accompanies the * exception. ENDCASE. 2. Now you can perform virus scanning of data that are present in XSTRING objects. Examples * Retrieve scanner instance CALL METHOD lo_scanner->scan_bytes EXPORTING if_data

= lf_data

if_do_clean

= ‘ABAP_TRUE’

IMPORTING ef_scanrc

= lf_scanrc

EXCEPTIONS OTHERS

= 1.

The result of the scan is any of the three situations: ¾ The return code LF_SCANRC has the value CL_VSI=>CON_SCANRC_OK. This indicates that the scan task was successfully performed and no infection was found. ¾ The return code LF_SCANRC has another value. Some most prominent error codes are present as CON_SCANRC_… attributes in class CL_VSI. Using method CL_VSI=>GET_SCANRC_TEXT a short explanation can be retrieved for an error code. In general, this situation must be treated as failed scan.

Secure Programming – ABAP

18 / 50

¾ An exception is thrown: This indicates a configuration error or severe problem during virus scanning. It must always be reported, and the virus scan is to be considered as failed. If the parameter IF_DO_CLEAN is set with the value ABAP_TRUE, a cleanup should be performed. In case of successful cleanup , the parameter EF_DATA returns EF_SCANRC = CON_SCANRC_CLEAN_OK. If the parameter IF_DO_CLEAN has the value ABAP_FALSE, it should only be checked. Beside the above mentioned method SCAN_BYTES, two other methods for virus scanning are available within the class CL_VSI: ¾ Method SCAN_FILE for scanning a local file on the application server. ¾ Method SCAN_ITAB for scanning an internal table with row type X or C. For further information about DDIC objects, tables, views, search helps, messages, function modules, class library reports and transactions of the Virus Scan Interface see the online documentation in the ABAP-Workbench. Information on integrating the Virus Scan Interface into customer developments are available in Integrating the Virus Scan Interface into Customer Developments [SAP Library] . A commented source code for the application of the VSI for scanning files that are uploaded from a workstation is accessible in Commented Example Program [SAP Library] .The report RSVSCANTEST contained in the system performs this task in an appropriate form and can also be used as a demonstration object.

Be aware of the following problems If an input channel does not implement the Virus Scan Interface itself, then a successive application may implement its own VSI. But it should be avoided that a document is scanned multiple times during its way into the system, in case the component delivering the data has performed a virus scan already.

Security Audit Log triggered by VSI Class CL_VSI automatically creates entries in the Security Audit Log for found infections and scan errors, together with the following information: ¾ about the profile, ¾ the profile step, which allows the detection of the scanner-group, ¾ the kind of virus, that was found (if available with internal virus ID of the scan engine), ¾ the user name and timestamp. The logged messages are located in message class VSCAN, using the System Log messages BU8 and BU9 (created in SE92). The severities are set to “High” and “Medium” respectively, for the Audit class it is set to “Miscellaneous”.

Secure Programming – ABAP

19 / 50

Further Information 1. SAP Tutor, Configuration of the RFC destination http://service.sap.com/~sapidb/011000358700003298652004E.sim SAP Tutor, Configuration of the Virus Scan Server http://service.sap.com/~sapidb/011000358700003298672004E.sim SAP Tutor, Virus Scan Trace http://service.sap.com/~sapidb/011000358700003298692004E.sim 2. SAP Note 786179 (Data security products: Application in the antivirus area) 3. SAP Note 817623 (Integrating a virus scan in SAP applications) 4. SAP NetWeaver Virus Scan Interface (NW-VSI) http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/icc/NWVSI%20Interface%20Documentation.pdf

Secure Programming – ABAP

20 / 50

Secure User Interface The trouble with Web applications is that you want users to come to your site and interact with the application. If the user makes unexpected entries (such as script commands) that the application does not handle correctly, an attacker could cause the server or the client/browser to perform unintended actions. Therefore, the first guideline for developing a secure Web application is: ‘Never trust any information coming from the outside, and never assume anything about it’. All security decisions must have the underlying assumption that anything that can theoretically be manipulated by someone or something will be manipulated in reality. For example, if an attacker makes entries like manipulated SQL statements and the application does not filter the entries, he can get access to the internal database (SQL Code Injection). The following sections describe examples for different vulnerabilities in Web applications and explain how to prevent them with secure programming.

Cross-Site Scripting (XSS) Description Cross-Site Scripting (XSS) attacks are set out to manipulate HTML pages by injection of malicious script code or by other indirect techniques, such as redirection to another server, logical attacks e.g. replacing images or changing style sheets. Attackers look out for HTML pages, where user input is written back to the HTML page, e.g. during a logon failure the logon screen is displayed a second time. These examples demonstrate the potential security vulnerabilities for XSS attacks, if user’s input is written back to the HTML page. Due to the fact that HTML is based on tags the browser may even interpret and execute Javascript or ActiveX controls, which might contain malicious SCRIPT commands. Those commands are executed by someone else opening this manipulated HTML page. The consequences of ActiveX attacks are as follows: ¾ The hacker might read/change/delete files on some other user’s local drives. ¾ Application actions might be executed under some other user’s privileges. ¾ The hacker might install other applications like Trojan horses. In case of Java- or VBscript potential attacks may be: ¾ To send the browser in an endless loop. ¾ To redirect the browser to a document.location.href property.

different

page

by

overwriting

the

¾ To access all user’s inputs (credit card numbers, etc.) and to send it to a rogue server. ¾ To access the user’s cookies (session hijacking, cookie manipulation). ¾ To insert new Script tags as output between tags, which for example create new event handlers that are executed when certain events occur.

Secure Programming – ABAP

21 / 50

Examples Example Code 1:

Click me! Example Code 2:

Example Code 3:



What Do I Need to Do? The basic rules to avoid XSS attacks are: ¾ Constrain Input. •

Define a codepage (e.g. charset = ISO-8859-1) to clearly decide which characters are problematic.



Filter metacharacters file system etc.).



Restrict variables to those characters that are explicitly allowed.

depending

on

the

interpreter

(HTML,

browser,

¾ Canonicalization, i.e. before validating input you first have to bring it to an appropriate standard form. For more details on this topic please refer to the chapter “Canonicalization”. ¾ Validate Input. All external input should be validated: •

for field length,



for data type,



for range (e.g. date, postcode),



and for a white list, to accept only known unproblematic characters.



If users are allowed to enter a URL within the input field, do restrict the domain of the URL and permit only the selection of approved URL’s.



Always enclose input values on HTML pages in quotation marks. This ensures, that attacks are only possible, if hackers leave the ‘input value context’ (e.g. “HUGO”) embedded in quotation marks using another ‘"’. Malicious code can be detected with a simple manner filtering for ‘"’. Example:

Omitting the quotation mark will make an XSS attack easier, because attackers do not have to leave the context setting any ‘"’. Therefore, it is much more difficult to filter malicious code out of such HTML pages.

Secure Programming – ABAP

22 / 50

Bad example:

¾ Encode Output. •

Encode user supplied output so that any inserted scripts are prevented from being transmitted to users in an executable form.



Convert metacharacters, e.g. “” to > , and “”” to " depending on the output context.



Use the Output Encoding Framework, which is provided by the SAP NetWeaver platform.

Examples Example Code 1:



Part of the company’s intranet application: public void doContent(...) { ... String s; if ((s = getUsernameByID("userid")) != null) { response.write("Applicant:" + s + ""); } ... }

Supposed output: Applicant:Smith



Cross-Site Scripting (XSS) example attack: Data entered in the field "user name": document.write(' '); document.hack.submit(); Smith



Cross-Site Scripting (XSS) attack result: HTML output containing the applicant’s input, rendered in the company’s intranet: Applicant:

Secure Programming – ABAP

23 / 50

document.write(‘ '); document.hack.submit(); Smith

Visible output: Applicant: Smith



Cross-Site Scripting (XSS) secure code: Security enhanced function: public void doContent(...) { ... String s; if ((s = getUsernameByID("userid")) != null) { s = StringUtils.encodeToHTML(s, 50); response.write("Applicant:" + s + ""); } ... }

What Do I Get from the SAP NetWeaver Platform? a) Using SAP Output Encoding Framework: You can use the SAP Output Encoding Framework in order to prevent cross-site scripting attacks. This applies if you as application developer generate your HTML code. By manually encoding user supplied output before rendering it, any inserted scripts are prevented from being transmitted to users in an executable form. The functions are generally available as of (see SAP Note 866020): •

SAP NetWeaver ’04, SP14. For ABAP, kernel patch 87 or higher should be used.



SAP NetWeaver 2004s, SP5. For ABAP, kernel patch 21 or higher should be used.

For ABAP you can use the utility functions in class CL_HTTP_UTILITY as described in the following sections. Basically four different cases for XSS-attacks have to be distinguished:

Secure Programming – ABAP

24 / 50

¾ CASE 1 XSS-attacks can occur as output BETWEEN tags: [CASE1] Username [CASE1] Example for XSS-attack: alert(); Username Utility function ESCAPE_HTML of ABAP class CL_HTTP_UTILITY has to be applied for output encoding: Data: i_unescaped type string, e_escaped type string. call method cl_http_utility=>escape_html exporting unescaped = i_unescaped keep_num_char_ref = '-' receiving escaped = e_escaped.

The optional exporting parameter KEEP_NUM_CHAR_REF prevents numeric characters to be escaped. ¾ CASE 2 XSS-attacks can occur as output INSIDE tags, but output is not a URL or style:

Secure Programming – ABAP

25 / 50

Example for XSS-attack: ...

Utility function ESCAPE_HTML of ABAP class CL_HTTP_UTILITY has to be applied for output encoding: Data: i_unescaped type string, e_escaped type string. call method cl_http_utility=>escape_html exporting unescaped = i_unescaped keep_num_char_ref = '-' receiving escaped = e_escaped.

The optional exporting parameter KEEP_NUM_CHAR_REF prevents numeric characters to be escaped.

¾ CASE 3 XSS-attacks can occur as output which is a URL or style: Example for XSS-attack: Utility function ESCAPE_URL of ABAP class CL_HTTP_UTILITY has to be applied for output encoding: Data: url_i type string, url_e type string. call method cl_http_utility=>escape_url exporting unescaped = url_i receiving escaped = url_e.

Secure Programming – ABAP

26 / 50

¾ CASE 4 XSS-attacks can occur as output inside a SCRIPT context: var a = '[CASE4]'; alert("[CASE4]"); var a = [CASE4]; [CASE4] Example for XSS-attack: var a = ''; alert(); a=''; alert("");document.forms[0].submit();//"); var a = alert(); alert(); Utility function ESCAPE_JAVASCRIPT of ABAP class CL_HTTP_UTILITY has to be applied for output encoding: Data: i_unescaped type string, e_escaped type string. call method cl_http_utility=>escape_javascript exporting unescaped = i_unescaped inside_html = ' ' receiving escaped = e_escaped.

The optional exporting parameter INSDE_HTML indicates, if the Javascript string to be encoded lies within HTML tags or outside of them. If Javascript is not embedded within an HTML document and has to be escaped, the parameter INSDE_HTML has to be set initial. Further information about the ABAP class CL_HTTP_UTILITY is provided in IF_HTTP_UTILITY [SAP Library] and Methods for the Interface IF_HTTP_UTILITY [SAP Library].

b) Using BSP-Extensions (HTMLB, XHTMLB and PHTMLB): In general all BSP-Extensions (such as HTMLB, XHTMLB and PHTMLB) that accept input parameters via HTTP requests, dynamically generate HTML based on this input and then return this dynamically generated content as response to the client (browser), are potentially vulnerable to cross-site scripting attacks. To protect the BSP-Extensions against XSSattacks, an encode attribute is available on the HTMLB content-tag. For BSP HTMLB library you have to set the attribute forceEncode to “ENABLED”, because it is set to disabled per default.

Secure Programming – ABAP

27 / 50

... •

ENABLED: Always encode everything. This overwrites all other encode attributes, and they don't have to be set anymore.



BACKWARDS_COMPATIBLE: Default value. The usual encode attributes are active as previously defined.

Furthermore, a page directive does exist for a new BSP compiler change that supports HTML encoding of all print statements on the page. In the following example, all print statements are effectively to support HTML encoding while printing. This only affects print statements on BSP pages, and does not have anything to do with tag parameter passing that uses the same syntax, but have a different semantics. Example get_form_field( 'x' ). %>

For further information see the following SAP notes and links: •

822881 XSS Support for BSP-Extensions HTMLB, XHTMLB and PHTMB



887168 BSP Page directive



891232 BSP Security Relevant Changes

c) ITS and BusinessHTML (BHTML) The Internet Transaction Server (ITS) offers the following BusinessHTML functions in order to prevent XSS attacks: ¾ xss_url_escape ¾ xss_html_escape ¾ xss_wml_escape ¾ xss_js_escape The functions above all take a string as input parameter and return correspondingly escaped strings. See also SAP Note 916255. In addition, all ITS versions offer the following functions, which may also be used for XSS attack prevention:

Secure Programming – ABAP

28 / 50

¾ strmask

(similar to new xss_html_escape)

¾ strmaskext

(similar to new xss_html_escape)

¾ strenc

(similar to xss_url_escape)

¾ jsmaskstring (similar to xss_js_escape) See the documentation about HTML Business functions [SAP Library].

d) For Web Dynpro ABAP: Due to the architecture of Web Dynpro, automatic integration of output encoding functionality is available. Therefore, no further output encoding functionality has to be implemented manually.

Further Information 1. A short story about Cross-Site Scripting https://weblogs.sdn.sap.com/pub/wlg/2422 2. Writing Secure Web Applications / Presentation http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/events/sa p-teched-04/Writing%20Secure%20Web%20Applications.pdf 3. SAP encoding functions in the Web environment (SAP Note 866020) 4. BSP Security Relevant Changes (SAP Note 891232) 5. XSS Support for BSP-Extensions HTMLB, XHTMLB and PHTMLB (SAP Note 822881) 6. BSP Page directive (SAP Note 887168) 7. Security Aspects for BSP http://help.sap.com/saphelp_nw2004s/helpdata/en/1c/db8d3f7057eb0ce10000000a1140 84/frameset.htm 8. Security Issues in Web Dynpro for ABAP http://help.sap.com/saphelp_nw04s/helpdata/en/af/0489ce55002f44a8c927371bedf719/fr ameset.htm

Secure Programming – ABAP

29 / 50

SQL Injection Description Today all Web applications are accessed by Internet and so face the risk of being exposed to manipulation. Most of the Web applications rely on RDBMS (Relational Database Management System) servers representing a possible vulnerability to SQL injection attacks arising from direct integration of user input into SQL statements without appropriate validation or filtering. The basis of this vulnerability lies in the creation of SQL commands with character strings. Attackers are successful if they are able to change the semantics of an SQL statement for their benefits or are able to insert own statements into the application. Entry points can be for instance input boxes in Web forms or URLs. The results could be unauthorized information access, information disclosure, unauthorized data modification or data loss. Several main categories of SQL injection attacks are distinguished: ¾ SQL Manipulation: •

Using the operation UNION.



Changing the WHERE clause.

Example Code 1:

Original SQL statement: SELECT fieldlist FROM table1 WHERE field = 'userinput'. Examples for SQL injection attack: SELECT fieldlist FROM table1 WHERE field = 'UNION ALL SELECT other_field FROM other_table WHERE '='. Example Code 2:

Original SQL statement: SELECT fieldlist FROM table WHERE field = 'userinput'. Examples for SQL injection attack: SELECT fieldlist FROM table WHERE field = 'anything' OR 'x'='x''. SELECT fieldlist FROM table WHERE field = 'x' AND email IS NUL; --'.

Secure Programming – ABAP

30 / 50

¾ Code Injection: •

Inserting new database commands into the vulnerable code.



Append a SQL server EXECUTE command to the malicious code. Example Code 1:

Original SQL statement: SELECT * FROM table WHERE name = 'userinput'. Examples for SQL injection attack: SELECT * FROM table WHERE name = ' a'; DROP TABLE users; SELECT * FROM table1 WHERE name = '%''.

¾ Functional Call Injection: •

Insertion of various database function calls into a vulnerable SQL code.

Several known attack strings listed in the table below may be a part of the SQL injection code to manipulate the original query. Hackers try various input combinations to enforce SQL statements into an error message. The following list of malicious inputs may or may not give the same results depending on the server. Therefore, it will be good to try all the inputs. Possible attack strings are: ‘

Badvalue’

‘ OR ‘

‘ OR

;

9,9,9

...; SELECT

^\n

exec()

' or 0=0 --

" or 0=0 --

or 0=0 --

' or 0=0 #

" or 0=0 #

or 0=0 #

' or 'x'='x

" or "x"="x

') or ('x'='x

' or 1=1--

" or 1=1--

or 1=1--

" or "a"="a

') or ('a'='a ") or ("a"="a hi" or "a"="a hi" or 1=1 -- hi' or 1=1 --

Attention has to be paid to the different output of possible vulnerable metacharacters in SQL statements. Characters could be displayed as ASCII, HEX, escaped ASCII, and escaped HEX. These four potential notations reveal the complexity of such SQL injection attacks.

Secure Programming – ABAP

31 / 50

Possible Characters to be used in SQL Code Injection: ASCII SPACE

HEX %20

\SPACE \%20 \'

\%27

'

%27

\"

\%22

"

%22

--

%2D%2D

\-\-

\%2D\%2D

\=

\%3D

=

%3D

\;

\%3B

;

%3B

\#

\%23

#

%23

Examples for combinations of ASCII and HEX-characters used within malicious code: ASCII / HEX-characters

Explanation

\w*

Zero or more alphanumeric or underscore characters.

(\%27)|\'

The ubiquitous single-quote or its hex equivalent.

(\%6F)|o|(\%4F))((\%72)|r|(\%52) The word 'or' with various combinations of its upper and lower case hex equivalents. ((\%2F)|\/)*

The forward slash for a closing tag or its hex equivalent.

[a-z0-9\%]+

The alphanumeric string inside the tag, or hex representation of these.

(\%3C)|)

The closing angle bracket or hex equivalent.

(\%69)|i|(\%49))((\%6D)|m| (\%4D))((\%67)|g|(\%47)

The letters 'img' in varying combinations of ASCII, or upper or lower case hex equivalents.

Secure Programming – ABAP

32 / 50

What Do I Get from the SAP NetWeaver Platform? 1.) Open SQL for ABAP already offers some implicit protection against SQL code injection as follows: ¾ Since all statements are being prepared, it is not possible to insert malicious code snippets using host variables, as for example the comparison values of a WHERE clause. ¾ The SQL statements SELECT, MODIFY, UPDATE, INSERT, and DELETE may all have dynamic clauses. But: •

the leading keyword of a clause has to be static.



no SQL statement can be executed within a clause of another statement completely dynamically.



sub queries can contain dynamic clauses but the leading SELECT keyword is always static.

2.) Native SQL for ABAP is always static from the ABAP language point of view. There are no dynamic Native SQL statements at all. ¾ Due to its static nature, a source code scan may be done: •

For the following fields, e.g. MANDT or CLIENT and



for the statement EXECUTE PROCEDURE.

Regarding both ABAP-based SQL language concepts described above, please refer to the recommendations as explained in the sections “What Do I Need to Do?” and “How Not to Do It?” in order to prevent SQL injection attacks.

What Do I Need to Do? As mentioned above, the information in Relational Database Management Systems is stored and retrieved with SQL statements. Therefore the following general rules may be helpful to circumvent SQL injection attacks: ¾ Define a codepage (e.g. charset = ISO-8859-1) to clearly decide which characters are problematic. ¾ Do filter user input, while retrieving user information for your SQL statement. ¾ Filter your data with the following regular expression for numbers and letters. •

s/[^0-9a-zA-z]//g

¾ If the user is allowed to submit an email address, allow only “@”, “_”, “.” and “-“. ¾ Prepend and append a quote to all user input, even if it is numeric. ¾ Restrict the rights of the Web application user. ¾ Configure error reporting. •

Restrict error reporting (by server side and by application) so that internal system information cannot be shown to outside users. For hackers Cross-Site scripting (XSS) attacks are facilitated, if the full query is shown, pointing to the syntax error involved.

Secure Programming – ABAP

33 / 50

¾ Use the ABAP addition ‘CLIENT SPECIFIED’ in a restrictive way, e.g. for client copy. ¾ Restrict the dynamic program generation done with the ABAP key words •

INSERT REPORT



GENERATE SUBROUTINE POOL

to filtered user input only. How Not to Do It? Never include any coding like the following, unless you take full control over the content of the dynamic clauses: SELECT FROM WHERE GROUP ORDER

(select_clause) (from_clause) CLIENT SPECIFIED INTO (where_clause) BY (groupby_clause) HAVING (having_clause) BY (orderby_clause).

Otherwise, if a developer allows unfiltered user input values to be taken for such a SELECT statement, any attack may be possible to read almost the whole database.

Secure Programming – ABAP

34 / 50

Input Validation Description Whenever software processes input, it should make sure that this input is in the expected form. From a functional point of view, this will ensure a high data quality level. Form a security point of view, this will prevent unexpected data from altering the intended execution of the program. Software processes input from various sources: •

User input from a GUI



Parameters from a configuration file



Data from a database



Data from remote function calls



Etc.

Risk: If input is not validated sufficiently, the application processing the data might crash or could be tricked into performing unwanted tasks.

What Do I Get from the SAP NetWeaver Platform? Web Dynpro (ABAP and Java) performs type validation. Therefore applications don’t have to check for correct data type. Caveat: Note that ABAP and Java types are not necessarily identical.

What Do I Need to Do? Basically you should validate your input. To achieve that goal, you have to provide a validation function for each input variable. You might group the variables (e.g. all input strings) and write one validation function for each group (e.g. string validator), which increases your efficiency. The task of writing validation code can be described as a stepwise procedure. In case of Web Dynpro, the framework automatically does the type validation before you can even access a variable. So the first three steps of the following list have been already performed. Consequently, in Web Dynpro you have to start your additional input validation at the 4th step of the following input validation ‘to do’ list: 1. Existence and length check 2. Canonicalization 3. Type check 4. Range check 5. White list filter 6. Black list filter These steps will be explained further in the following: Secure Programming – ABAP

35 / 50

Step 1: Existence and length check It must not be possible to attack the application simply by omitting a necessary variable or feeding in data packets that are either too long or too short. So, first of all, your validation function shall check if the variable of interest exists and has the correct length. Step 2: Canonicalization Canonicalization means, the input variable’s content is transformed into its simplest and shortest representation. Many attack methods depend on the usage of ‘polymorph representation’, i.e. an unusual or overly complicated form that is designed to evade filter mechanisms. So the transformation in its simplest form is fundamental for successful filter mechanisms. Step 3: Type check Since attackers should not be able to harm the application by feeding input data of the wrong type to it (e.g. strings instead of dates), the validation function has to check the variable for its correct type. Step 4: Range check After that, you should check if the variable's values are in the correct range. Clearly, this is only possible for variables with a definable range of values (like numbers). It is imperative to define the limits exactly here. For all input you should think about where the boundaries lie. Step 5: ‘White list’ filter If a variable simply has no clear range of values (e.g. strings) a range check would be pointless. In this case your validation function should contain a list of allowed values and check the input against this instance. Such an instance is called a ‘white list’ filter. Step 6: ‘Black list’ filter There may be cases where you even can not implement a white list filter. In this situation, you should write a black list filter function at least. For this is better than doing no filtering at all. Doing nothing here regularly has detrimental effects for the security of your application. Black lists are fallbacks only! At this point, it is extremely important to acknowledge that black list filters are vulnerable by nature – and so can be only a fallback solution. Our advice here is very clear: Whenever possible, use a white list filter. If it is not feasible, work towards making it so. Only if it is still absolutely impossible, use a black list filter. In the later case, include this as vulnerability in the application's internal documentation.

How Not to Do It? Oftentimes input is not validated, for any one of the following reasons: •

Input is not recognizes as such



The source of input is trusted

Secure Programming – ABAP

36 / 50



The implicit assumption that someone else already did the validation



Performance is more important than security



Insufficient time in the project

Not validating input is a high security risk. Please make sure to precisely weigh the pros and cons whenever you have priorities other than security.

Secure Programming – ABAP

37 / 50

Canonicalization Description Canonicalization describes the mechanisms to trace back different polymorphic expressions to a canonical distinct expression. For example, within the context of a search engine the data file ‘Hello World.doc’ may be accessible by any one of the following polymorphic links: •

http://www.sap.com/Hello+World.doc



http://www.sap.com/hello+world.doc



http://www.sap.com/Hello%20World.doc

The canonical representation ensures that ‘strange’ but allowed forms of an expression (for example, URL encoding or Unicode) do not pass any filter mechanisms. A polymorph representation of data is not necessarily an attack in itself, but helps to slip malicious data past a filter by “disguising” it.

What Do I Need to Do? The figure below clarifies what you as a developer have to do: •

Unescape the input and bring it to its shortest or simplest form (canonicalization).



Validate the input dependent on the output (HTML, database or file system). o

Be aware of double encoded characters.

o

Check, if you work in the same character space (Unicode vs. ASCII).

o

Remember that combinations of ASCII and HEX characters may represent malicious code. See also chapter “SQL injection”.

o

Remember case sensitivity and try to find a ‘capitalized’ canonical form.



Check against a white list of allowed patterns instead of using a black list.



Pay attention to the interpreters’ operation mode, because different interpreters might handle the same data in different ways. Influence each other

Input: • File • GUI

• Database • etc.

unescape canonicalize

Process Filter for e.g. .asp .jsp

Interpreter: • Browser • XML Parser • File System • SQL-Interpreter • etc.

Figure 3: Dependencies of the Canonicalization Process

Secure Programming – ABAP

38 / 50

Example of a bad filter Example for the original file, that is allowed to be accessed: c:\sap\file\test.txt

Example for potentially malicious code: Example Code 1: c:\sap\file\test.asp

Access to the file will be denied by the filter of the process, due to the extension .asp. Such a filter does not accept any .asp or .jsp extensions. Example Code 2: c:\sap\file\test.asp::$data

The file ends with ‘data’, which is not interpreted as malicious ending such as ‘.asp’ or ‘.jsp’ by the process filter. Therefore, the file will be accessed by the interpreter. Example Code 3: c:\sap\file\test.asp%00de.doc

The file ends with ‘doc’, which is not interpreted as malicious ending such as ‘.asp’ or ‘.jsp’ by the process filter. The file will be opened, because the interpreter does not accept any information following the NULL (%00).

What Do I Get from the SAP NetWeaver Platform? For Web Dynpro ABAP and for BSP Applications: The method CL_HTTP_UTILITY=> IF_HTTP_UTILITY~CHECK_HTTP_WHITELIST is available in the Web Application Server/ABAP to check URL-like parameters against a white list of patterns in table HTTP_WHITELIST (table can be maintained in transaction SE16). This process verifies that the URL from external sources can be accepted. For more information see Security Risk List [SAP Library]. Please also refer to SAP Note 853878. For HTML Interpreters: The SAP NetWeaver platform offers several output encoding functions within the ABAP class CL_HTTP_UTILITY to circumvent cross-site scripting (XSS) attacks. See chapter “Cross-Site Scripting (XSS)” for further information.

Further Information 1. OWASP Guide Version 2.0.1 (Pages 185 -191) http://surfnet.dl.sourceforge.net/sourceforge/owasp/OWASPGuide2.0.1.pdf 2. Security Issues in Web Dynpro for ABAP http://help.sap.com/saphelp_nw04s/helpdata/en/af/0489ce55002f44a8c927371bedf719/fr ameset.htm 3. SAP Note 853878: HTTP WhiteList Check (security) Secure Programming – ABAP

39 / 50

Directory Traversal Description Web servers generally are set up to restrict public access to a specific portion of the Web server's file system. In a Directory Traversal or Path Traversal attack, an intruder manipulates a URL in such a way that the Web server executes or reveals the contents of a file anywhere on the server, residing outside of the Web server's root directory. Path Traversal attacks take advantage of special-characters sequences in URL input parameters, cookies and HTTP request headers. A common Path Traversal attack uses the "../" character sequence to alter the document or resource location requested in a URL. Although most Web servers prevent this method by escaping sequences, alternate encodings of the "../" sequence can bypass basic security filters. Even if a Web server properly restricts Path Traversal attempts in the URL path, any application that exposes an HTTP-based interface is also potentially vulnerable to such attacks. These method variations include valid and invalid Unicode-encoding of: ¾ The forward slash character, e.g. "..%u2216" or "..%c0%af". ¾ The backslash characters, e.g. URL encoded characters "%2e%2e%2f" , or double URL encoding "..%255c" . Examples Several typical Path Traversal attacks may be distinguished: ¾ Path Traversal attacks against a Web server: Examples for Path Traversal attack: Example Code 1:

http://example.test/../../../secret/file

This attack is the "classic" version of a Path Traversal attack. Most Web servers and applications will at least filter the '../' character string. However, it is worth noting that many applications running under Windows might also be vulnerable to the '..\' character string (backslash instead of slash). Example Code 2:

http://example.test/..%5c..%5c..%5csecret/file

The second attack uses escaped encoding ('%5c' translates to '\'). It relies on the assumption that the target application either has no relevant security checks for Path Traversal in place or that those checks are done before the translation of the escaped characters. Example Code 3:

http://example.test/..%255c..%255c..%255csecret/file

The third attack is a special version that is widely known for its use against a Web server that (unintentionally) translated escaped encoded characters twice. However, the security checks were done only after the first conversion. As '%25' translates to Secure Programming – ABAP

40 / 50

'%' after the first conversion the third attack looked exactly like the second attack but was not detected by the security checks in place. After the second conversion the '%5c' were replaced by '/' and the attack string was complete. Notice, the string "%5c" within the URL is a Web server escape code. Escape codes are used to represent normal characters in the form of %nn, where nn stands for a two-digit number. The escape code "%5c" represents the character "\". The problem is that the IIS root directory enforcer did not check for escape codes and allowed that request to execute. The Web server's operating system understands escape codes and executes the command. This example shows quite well how 'creative' exploitable programming errors can be. Multiple decoding of masked characters is a common problem for many applications. ¾ Path Traversal attacks against a Web application: Original URL: http://example.test/cgi-bin/index.cgi?web/web.html Example for Path Traversal attack: http://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgi

Obviously, the Web pages on this Web server are not addressed directly. Rather this work is done by a script called 'index.cgi'. The script evaluates the parameter ('web/web.html') included in the URL after the question mark and outputs the designated file, probably doing some standard extra work like adding header and footer. If the attacker guessed the directory structure and the script did not do appropriate input validation the script probably displays its source code to the attacker in a Web page thus giving away valuable hints for further attacks. ¾ Path Traversal attacks using special characters: Original URL: http://example.test/cgi-bin/index.cgi?web/web.html Example for Path Traversal attack: http://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgi%00.html

One input validation technique consists of checking the extension of a file name parameter. The underlying idea is to only display files with a 'correct' extension like 'html' or '.txt' thus preventing the application from displaying, e.g., script code. The attack above uses the escaped encoded NUL character ('%00') creating a URL that ends with '.html' to pass this validation step. However, chances are that the script when using the parameter - will stop evaluating the parameter string as soon as it reaches the NUL character and once again might be tricked into displaying its source code to the attacker.

Secure Programming – ABAP

41 / 50

Possible ASCII Characters to be used in Path Traversal attacks: ASCII

Escaped encoding

NUL

%00

Space

%20

%

%25

.

%2e

/

%2f

:

%3a

\

%5c

What Do I Need to Do? General recommendations to prevent Path Traversal attacks: ¾ Don’t implement file access functionality that is based on user input, unless there is no other alternative. ¾ If you must allow user input, try to constrain it to a list of allowed files/paths. Additionally you should ensure that: ¾ A codepage (e.g. charset = ISO-8859-1) is defined to clearly decide which characters are problematic. ¾ The given input is filtered for malicious metacharacters. Beside the above mentioned aspects to prevent Path Traversal attacks, the Web server provides two main security mechanisms: ¾ The root directory, which limits users' access to a specific directory in the Web server's file system. ¾ The administrators’ access control list, which limits users' access to specific files within the root directory.

Secure Programming – ABAP

42 / 50

URL Encoding and Manipulation Description Within literature URL encoding, UTF encoding, escape-encoding, percent-encoding and Web encoding are used interchangeably. For a better understanding of malicious attacks like XSS or SQL injection attacks it is required to gain insight of URL encoding techniques. Web applications transfer data between client and server using the HTTP or HTTPS protocols. Normally all user input may be passed to the server either in the HTTP headers (submitted through the cookie field, or the post data field) or included in the query portion of the requested URL. If the data is transferred by an URL, it has to be especially encoded to obey the proper syntax rules of URL’s. Two types of character cases have to be distinguished for the standard (RFC2396): ¾ The unreserved class comprises the characters: •

a-z, A-Z, 0-9 _ . ! ~ * # ( )

¾ The reserved class contains the following characters: •

;/?:@&=+$,

Characters out of the reserved class could conflict with the correct interpretation of a URL. Escape-encoding is the matter of choice to guarantee a correct syntax interpretation of these reserved characters. The URL encoding is achieved by a triplet sequence consisting of a percentage character “%” followed by the two hexadecimal digits representing the octet code of the original character. The percentage character has the purpose to be the escape indicator within an URL and therefore has to be escaped itself as "%25" in order to be used as data in an URL. For URI encoding it is recommended to ensure that not to escape or un-escape the same string more than once, since un-escaping an already un-escaped string might lead to misinterpreting a percent data character as another escaped character, or vice versa in the case of escaping an already escaped string. Multiple escape-encoding at different layers of an application may circumvent security checks on the initial decoding pass. An example of such a multiple escape-encoding should be given considering the character sequence “\” or “..\”. The backslash “\” may be described as “%5c” or the following permutations: •

%255c



%%35c



%%35%63



%25%35%63

These different escape-encoding sequences give an example of possible entry points for URL attacks, such as: ¾ URL attack in terms of a multiple decoding attack: Example for URL attack: http://TARGET/scripts/..%255c..%%35cwinnt/system32/cmd.exe?/ c+dir+c:\ Attack result: •

The directory list of C:\ is revealed.

Secure Programming – ABAP

43 / 50

¾ URL attack in terms of XSS attack: Example for URL attack: http://target/getdata.php?data=%3cscript%20src=%22http%3a%2f%2f www.badplace.com%2fnasty.js%22%3e%3c%2fscript%3e Attack result:

¾ URL attack in terms of SQL injection attack: Example for URL attack: http://target/login.asp?userid=bob%27%3b%20update%20logintable% 20set%20passwd %3d%270wn3d%27%3b--%00 Attack result: •

Executed database query: SELECT preferences FROM logintable WHERE userid=’bob’; update logintable set password=’0wn3d’;

Useful Hint:

¾ A reference table of ASCII characters in URL encoding form (hexadecimal format) is accessible at http://www.w3schools.com/tags/ref_urlencode.asp .

What Do I Get from the SAP NetWeaver Platform? For Web Dynpro ABAP: Due to the architecture of Web Dynpro, automatic integration of output encoding functionality is available. Therefore, no further output encoding functionality has to be implemented manually.

What Do I Need to Do? The different character encoding schemes and their variety of application offer an infinite number of malicious encoding. Thus, the developer has the responsibility to secure his application against such encoding attacks, considering the following rules: ¾ Read the ‘Request for Comments’ (RFC) 3986 on 'Uniform Resource Identifier (URI):generic syntax ' carefully for correct syntax processing of the URLs (search at http://www.rfc-editor.org). ¾ User input has to be regarded as potentially malicious code. ¾ Avoid to submit data using the ‘GET’ method, because the data is appended to the URL and may be easily manipulated. It is better to use the ‘POST’ method instead. ¾ Do not rely on client-side content checks. ¾ Do validate and sanitize all data on server side. Always restrict the type of acceptable data as much as possible using strict validation rules. ¾ Always perform independent validation and sanity checks of the supplied data. Secure Programming – ABAP

44 / 50

¾ Ensure, that the application does not repeat any character-decoding process. Decoding should be done by the operating system. Suppose, that the data remains encoded or contains unacceptable characters, treat the data as malicious one’s and deny the input. ¾ Thoroughly test your application for system behavior on encoded and incorrect data formats.

Further Information 1. Security Issues in Web Dynpro for ABAP http://help.sap.com/saphelp_nw04s/helpdata/en/af/0489ce55002f44a8c927371bedf719/fr ameset.htm

Secure Programming – ABAP

45 / 50

Cookie Manipulation Description HTTP is a stateless protocol. As a method for session tracking, Netscape in 1994 invented a mechanism called “Cookie”. A cookie is a small piece of information usually created by the Web server and stored in the Web browser. Each time the user contacts the Web server, this data is passed back to the server. The cookie contains information used by Web applications to persist and pass variables back and forth between the browser and the Web application. Two types of client-side cookies are known: ¾ Persistent cookies, which are stored in a file on the client until an expiry date. ¾ Session cookies,

which are kept in the memory of the client until the session is ended.

Examples Example Code (Cookies sent by the server, the first one being persistent):

HTTP/1.1 200 OK ... Set-Cookie: client=a5b35e36-b342-464b-a3a6-8e3718990af9; domain=.sap.com; expires=Wed, 18-Jan-2006 11:38:56 GMT; path=/ Set-Cookie: ASP.NET_SessionId=c12ylm55kp3uirruo4is5sm5; path=/ ...

Examples Example Code (Cookie sent by the client):

POST /index.epx HTTP/1.1 ... Cookie: GCUID01=452492715; GCCKVER=5; ASP.NET_SessionId=c12ylm55kp3uirruo4is5sm5; client=a5b35e36-b342-464ba3a6-8e3718990af9

As a result of the cookie structure and their usage, all data stored in a client-side cookie could be easily read and manipulated. The risk of tampering with data and even information disclosure is very high. Due to the fact that many cookies are Base64 encoded, no cryptographic protection is offered. The best practice to avoid cookie manipulation is to be suspicious of data stored in cookies.

What Do I Get from the SAP NetWeaver Platform? The ABAP class CL_BSP_SERVER_SIDE_COOKIE provides methods for setting, getting, deleting, and managing cookies on the server. Fur further information see Class CL_BSP_SERVER_SIDE_COOKIE [SAP Library]. Server-side cookies are persistent data, similar to the usual client-side cookies. While on the client-side there are restrictions that limit the size of cookies, a server-side cookie is stored on the database. And since they are stored on the server, server side cookies can’t be tampered with remotely by malicious users.

Secure Programming – ABAP

46 / 50

For technical reasons, each individual cookie can be stored in one of the following ways: ¾ as a field, ¾ as a structure, ¾ as a table.

What Do I Need to Do? Cookies should be used for the following purpose only: ¾ To maintain session IDs. ¾ To persist certain information on the browser. Dealing with cookies, the following security considerations have to be taken into account: ¾ Store all data in a server-side cookie. Do not store ANY data in a client cookie, unless you absolutely have to. Hackers can easily manipulate client-side cookies. ¾ Use the session management that the SAP NetWeaver platform provides. Don’t create your own. ¾ Never store any confidential data in a cookie, such as the non-public IP addresses of target servers, host names, or system IDs. If information of this type is important for control, you should use a hash procedure for one-way encryption of the data. ¾ Use idle timeouts for applications that expose private data or that may cause identity theft if left open. ¾ Offer a logout mechanism to the user, to manually shorten the time until a session timeout will end the session automatically. Using the methods of the ABAP class CL_BSP_SERVER_SIDE_COOKIE to set, get, delete and manage cookies, attention has to be paid to the parameters username and session_id within the appropriate methods. It is ambiguous to pass sy-user to the parameter username for applications started by an anonymous user stored on the server. It would be better to use session_id since runtime->session_id indicates the browser session. More information about this issue is provided in Class CL_BSP_SERVER_SIDE_COOKIE [SAP Library].

How Not to Do It? Sometimes cookies may contain personal information, if programmers do not pay attention to the advice never to store any confidential data in a cookie. The extent of cookie manipulation ranges from session tokens to arrays that make authorization decisions. Cookie poisoning can even lead to vulnerabilities such as SQL injection and cross-site scripting.

Secure Programming – ABAP

47 / 50

Examples Example Code 1:

(Original cookie) Cookie: lang=en-us; ADMIN=no; y=1; time=10:30GMT;

(Cookie modified by an attack) Cookie: lang=en-us; ADMIN=yes; y=1; time=12:30GMT;

Example Code 2:

Shopping carts used to store pricing information in cookies. (Part of a shopping cart applications' cookie) item1_ID=12369&item1_pr=27,95&item2_ID=10334&item2_pr=19,95 > Total Amount: $47,90

(Manipulated cookie) item1_ID=12369&item1_pr=0,95&item2_ID=10334&item2_pr=1,95 > Total Amount: $2,90

Further Information 1. OWASP Guide Version 2.0.1 (Pages 147 – 160) http://surfnet.dl.sourceforge.net/sourceforge/owasp/OWASPGuide2.0.1.pdf 2. Writing Secure Web Applications (Slides 50 – 51) http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/events/sa p-teched-04/Writing%20Secure%20Web%20Applications.pdf

Secure Programming – ABAP

48 / 50

Further Information Secure Programming Checklist You can find a checklist that lists the most important issues that you should pay attention to in order to develop secure applications here: https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/4ab8b3bb-0601-00107b82-e392df20392a

SAP NetWeaver Developer’s Guide You can find the SAP NetWeaver Developer’s Guide here: https://www.sdn.sap.com/irj/sdn/developersguide

Secure Programming – ABAP

49 / 50

Disclaimer Any software coding and/or code lines / strings ("Code") included in this documentation are only examples and are not intended to be used in a productive system environment. The Code is only intended better explain and visualize the syntax and phrasing rules of certain coding. SAP does not warrant the correctness and completeness of the Code given herein, and SAP shall not be liable for errors or damages caused by the usage of the Code, except if such damages were caused by SAP intentionally or grossly negligent.

Secure Programming – ABAP

50 / 50

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF