SecureProgramming_LogFileNames

Embed Size (px)

Citation preview

  • 8/12/2019 SecureProgramming_LogFileNames

    1/18

    Secur e Prog ramming ABA P -D i rec to r y Traversa l

    SAP NETWEAVER 7 .02

    HELP.NW

    _D

    EVGUIDE_

    SEC

  • 8/12/2019 SecureProgramming_LogFileNames

    2/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 2

    Copyright

    Copyright 2010 SAP AG. All rights reserved.

    No part of this publication may be reproduced or transmitted in any form or for any purposewithout the express permission of SAP AG. The information contained herein may be

    changed without prior notice.Some software products marketed by SAP AG and its distributors contain proprietarysoftware components of other software vendors.

    Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of MicrosoftCorporation.

    IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x,System z, System z10, System z9, z10, z9, iSeries, pSeries, xSeries, zSeries, eServer, z/VM,z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM,Power Architecture, POWER6+, POWER6, POWER5+, POWER5, POWER, OpenPower,PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2Connect, RACF, Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner,WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of IBM

    Corporation.

    Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.

    Adobe, the Adobe logo, Acrobat, PostScript, and Reader are either trademarks or registeredtrademarks of Adobe Systems Incorporated in the United States and/or other countries.

    Oracle is a registered trademark of Oracle Corporation.

    UNIX, X/Open, OSF/1, and Motif are registered trademarks of the Open Group.

    Citrix, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, and MultiWin aretrademarks or registered trademarks of Citrix Systems, Inc.

    HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, WorldWide Web Consortium, Massachusetts Institute of Technology.

    Java is a registered trademark of Sun Microsystems, Inc.

    JavaScript is a registered trademark of Sun Microsystems, Inc., used under license fortechnology invented and implemented by Netscape.

    SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, Clear Enterprise, SAPBusinessObjects Explorer and other SAP products and services mentioned herein as well astheir respective logos are trademarks or registered trademarks of SAP AG in Germany andother countries.

    Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, CrystalDecisions, Web Intelligence, Xcelsius, and other Business Objects products and servicesmentioned herein as well as their respective logos are trademarks or registered trademarks ofSAP France in the United States and in other countries.

    All other product and service names mentioned are the trademarks of their respectivecompanies. Data contained in this document serves informational purposes only. Nationalproduct specifications may vary.

    These materials are subject to change without notice. These materials are provided by SAPAG and its affiliated companies ("SAP Group") for informational purposes only, withoutrepresentation or warranty of any kind, and SAP Group shall not be liable for errors or

  • 8/12/2019 SecureProgramming_LogFileNames

    3/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 3

    omissions with respect to the materials. The only warranties for SAP Group products andservices are those that are set forth in the express warranty statements accompanying suchproducts and services, if any. Nothing herein should be construed as constituting anadditional warranty

  • 8/12/2019 SecureProgramming_LogFileNames

    4/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 4

    Icons in Body Text

    Icon Meaning

    Caution

    ExampleNote

    Recommendation

    Syntax

    Additional icons are used in SAP Library documentation to help you identify different types of

    information at a glance. For more information, see Help on Help General InformationClasses and Information Classes for Business Information Warehouse on the first page of anyversion ofSAP Library.

    Typographic Conventions

    Type Style Description

    Example text Words or characters quoted from the screen. These include fieldnames, screen titles, pushbuttons labels, menu names, menu paths,and menu options.

    Cross-references to other documentation.

    Example text Emphasized words or phrases in body text, graphic titles, and tabletitles.

    EXAMPLE TEXT Technical names of system objects. These include report names,program names, transaction codes, table names, and key concepts of a

    programming language when they are surrounded by body text, forexample, SELECT and INCLUDE.

    Exampl e t ext Output on the screen. This includes file and directory names and theirpaths, messages, names of variables and parameters, source text, andnames of installation, upgrade and database tools.

    Example text Exact user entry. These are words or characters that you enter in thesystem exactly as they appear in the documentation.

    Variable user entry. Angle brackets indicate that you replace thesewords and characters with appropriate entries to make entries in thesystem.

    EXAMPLE TEXT Keys on the keyboard, for example, F2orENTER.

  • 8/12/2019 SecureProgramming_LogFileNames

    5/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 5

    Directory Traversal ................................................................................................................ 6

    Validating Physical File Names Entered by the User ........................................................ 10

    Using File Name Aliases .................................................................................................. 13

    Validating Logical File Names Entered By the User .......................................................... 15

  • 8/12/2019 SecureProgramming_LogFileNames

    6/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 6

    Directory Traversal

    Description for a Web Server Environment

    Web servers are generally 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 aURL in such a way that the Web server executes or reveals the contents of a file anywhere onthe server, residing outside of the Web server's root directory. Path traversal attacks takeadvantage of special character sequences in URL input parameters, cookies, and HTTPrequest headers.

    A common path traversal attack uses the "../" character sequence to alter the document orresource location requested in a URL. Although most Web servers prevent this method byescaping sequences, alternate encodings of the "../" sequence can bypass basic securityfilters. Even if a Web server properly restricts path traversal attempts in the URL path, anyapplication that exposes an HTTP-based interface is also potentially vulnerable to suchattacks.

    These method variations include valid and invalid Unicode-encoding of:

    The forward slash character, such as"..%u2216"or"..%c0%af".

    The backslash characters, such as URL encoded characters"%2e%2e%2f", or

    double URL encoding"..%255c".

    Examples for a Web Server Environment

    Several typical path traversal attacks are shown below:

    Path Traversal At tacks Against a Web Server

    Example Code 1

    ht t p: / / exampl e. tes t / . . / . . / . . / secret / f i l e

    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 manyapplications running under Windows might also be vulnerable to the '..\' character string(backslash instead of slash).

    Example Code 2

    ht t p: / / exampl e. t est / . . %5c. . %5c. . %5csecret/ f i l e

    The second attack uses escaped encoding ('%5c' translates to '\'). It relies on the assumptionthat the target application either has no relevant security checks for path traversal in place orthat those checks are done before the translation of the escaped characters.

    Example Code 3

    ht t p: / / exampl e. t est / . . %255c. . %255c. . %255csecret / f i l e

    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 checkswere done only after the first conversion. As '%25' translates to '%' after the first conversionthe third attack looked exactly like the second attack but was not detected by the securitychecks in place. After the second conversion the '%5c' were replaced by '/' and the attackstring was complete.

    http://example.test/secret/filehttp://example.test/..%5c..%5c..%5csecret/filehttp://example.test/..%255c..%255c..%255csecret/filehttp://example.test/..%255c..%255c..%255csecret/filehttp://example.test/..%5c..%5c..%5csecret/filehttp://example.test/secret/file
  • 8/12/2019 SecureProgramming_LogFileNames

    7/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 7

    Note that the string "%5c" within the URL is a Web server escape code. Escape codes areused to represent normal characters in the form %nn, where nn stands for a two-digit number.The escape code "%5c" represents the character "\". The problem is that the IIS root directoryenforcer did not check for escape codes and allowed that request to execute. The Webserver's operating system understands escape codes and executes the command.

    This example demonstrates how 'creative' exploitable programming errors can be. Multipledecoding of masked characters is a common problem for many applications.

    Path Traversal Attacks Against a Web Application

    Original URL

    ht t p: / / exampl e. t est / cgi - bi n/ i ndex. cgi ?web/ web. ht ml

    Example of a Path Traversal Attack

    ht t p: / / exampl e. t est/ cgi - bi n/ i ndex. cgi ?. . / cgi - bi n/ i ndex. cgi

    Obviously, the Web pages on this Web server are not addressed directly. Rather this work isdone by a script called i ndex. cgi . The script evaluates the parameter (web/ web. ht ml )included in the URL after the question mark and outputs the designated file, probably doingsome standard extra work like adding header and footer. If the attacker guessed the directory

    structure and the script did not perform appropriate input validation, the script would probablydisplay its source code to the attacker in a Web page, thus giving away valuable hints forfurther attacks.

    Path Traversal Attacks Using Special Characters

    Original URL

    ht t p: / / exampl e. t est / cgi - bi n/ i ndex. cgi ?web/ web. ht ml

    Example of a Path Traversal Attack

    ht t p: / / exampl e. t est / cgi - bi n/ i ndex. cgi ?. . / cgi - bi n/ i ndex. cgi %00. ht ml

    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 'ht ml ' or '. t xt ' thus

    preventing the application from displaying, for example, script code. The attack above usesthe escaped encoded NULL character ('%00') creating a URL that ends with '. html ' to passthis validation step. However, it is likely that the script - when using the parameter - will stopevaluating the parameter string as soon as it reaches the NULL character and once againmight be tricked into displaying its source code to the attacker.

    Possible ASCII Characters Used in Path Traversal Attacks

    ASCII Escapedencoding

    NULL %00

    Space %20

    % %25

    . %2e

    / %2f

    : %3a

    \ %5c

    http://example.test/cgi-bin/index.cgi?web/web.htmlhttp://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgihttp://example.test/cgi-bin/index.cgi?web/web.htmlhttp://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgi%00.htmlhttp://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgi%00.htmlhttp://example.test/cgi-bin/index.cgi?web/web.htmlhttp://example.test/cgi-bin/index.cgi?../cgi-bin/index.cgihttp://example.test/cgi-bin/index.cgi?web/web.html
  • 8/12/2019 SecureProgramming_LogFileNames

    8/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 8

    Description for an AS ABAP Environment

    Some SAP programs access file on the application server using the ABAP command OPENDATASETor related statements. For some of these programs, the user can enter the filename in the user interface, for example, in a selection screen.

    The OPEN DATASETcommand uses the application server directory that isspecified in the DIR_HOME profile parameter as the default directory.

    In this context, if the user input is not restricted, a user can enter any physical file name,including the same or similar cahracter sequences as described before. The user can also

    enter an absolute file name (for example, / usr / et c/ pwd/ orC: \ Wi ndows\ ).

    The AS ABAP does allow for a mapping of physical path and file names to a logical file name.Also in this case, the user input should be restricted to prevent the user from selecting orentering a logical file name that provides access to a part of the file system that does notbelong to the application's context.

    What Do I Get from the SAP NetWeaver Platform

    When accessing the file system, the AS ABAP automatically performs the following authority

    checks:

    When accessing all files, an authority check for the authorization object S_DATASETis performed.

    When accessing files whose physical file names are stored in table SPTH, an authoritycheck for the authorization object S_PATH is performed, if the field FS_BRGRU (userauthorization group) is filled.

    When accessing physical file names that end with . PSE, an authority check for theauthorization object S_RZL_ADM is performed. (These files are system security fileswhere keys used for digital signatures and encryption are stored.)

    In addition, logical file names can be used to specify platform-independent path and filenames that map to the actual physical path and file name. These logical file names can also

    be used to prevent directory traversal by building a whitelist of valid paths and file names. If auser attempts to access a location in the file system that is not included in the whitelist for acertain context, access is denied.

    To use the whitelist for access protection:

    Programs that access files in the application server file system have to call the functionmodule FILE_VALIDATE_NAME explicitly before performing the file access.

    The program provides the function module with the physical file name for which accessis being requested and a hard-coded logical file name. This logical file name is used tovalidate the physical file name.

    For the validation to be successful, the system administrator must maintain themapping between the physical path and file name to the hard-coded logical file name.

    The combination of these steps allows the system administrator to restrict access to theapplication server file system.

  • 8/12/2019 SecureProgramming_LogFileNames

    9/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 9

    What Do I Need to Do?

    To prevent path traversal attacks in ABAP programs:

    Do not implement file access functionality that is based on user input, unless there isno other alternative.

    Call FILE_VALIDATE_NAME prior to accessing the file system (for example, withOPEN DATASET) to ensure that the file being accessed is in a valid directory asspecified in the logical file name mapping table. For more information, see UsingFILE_VALIDATE_NAME [Page 10]and Using Aliases in the User Interface [Page 15].

    In the context of a Web server environment, you should also ensure that:

    A codepage (such as char set = I SO- 8859- 1) is defined to clearly decide whichcharacters are problematic.

    The given input is filtered for malicious metacharacters.

    In addition to the aspects mentioned above for preventing path traversal attacks, the Webserver provides two main security mechanisms:

    The root directory, which limits users' access to a specific directory in the Web server'sfile system.

    The administrators access control list, which limits users' access to specific files withinthe root directory.

    Addit ional Information

    For more information, see:

    SAP Library: Logical File Names [SAP Library]

    SAP NetWeaver AS ABAP Security Guide: Protecting Access to the File System UsingLogical Path and File Names [SAP Library]

  • 8/12/2019 SecureProgramming_LogFileNames

    10/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 10

    Validating Physical File Names Entered by theUserThere are several steps involved in implementing the complete recommendation for validatingphysical file names entered by the user.

    These steps are primarily relevant for validating physical file paths and filenames that are provided using the user interface. There may be RFCs or otherinterfaces that also accept a physical file name as part of APIs. For these cases,implement steps 1 and 4.

    The steps to perform are:...

    1. Define a constant to use for the logical file name. (Mandatory)

    2. Create a default value for the physical file name, if applicable. (Recommended)

    3. Validate the input, if suitable. (Recommended)

    4. Validate the file name. (Mandatory)

    See the following sections.

    Step 1. Define a Constant Logical File Name to be Used forFile Name Validation (Mandatory)

    For each parameter for a physical file name in your application create one constant of typeFI LEI NTERN(logical file name). Depending on the context of the file access, this constantcan be a global constant within a program, local within a specific part of a program, or definedin a type pool for use across multiple programs.

    Set the value of this constant to the logical file name used for file name validation in thiscontext.

    CONSTANTS gc_f name TYPE f i l ei nter n VALUE ' EXAMPLE_FI N1' .

  • 8/12/2019 SecureProgramming_LogFileNames

    11/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 11

    Step 2: Create a Default Value for the Physical File Name, ifSuitable (Recommended)

    Create a default value for the physical file name, if applicable, by calling the function moduleFILE_GET_NAME with the parameterI NCLUDI NG_DI Rset to ' X' (for example, duringI NI TI ALI ZATI ON).

    I NI TI ALI ZATI ON. CALL FUNCTI ON ' FI LE_GET_NAME' EXPORTI NG l ogi cal _f i l e name = gc_f name* any parameter s def i ned f or t hat l ogi cal f i l e name i ncl udi ng_di r = ' X' I MPORTI NG f i l e_name = pa_f i l e EXCEPTI ONS OTHERS = 1. I F sy- subr c 0. MESSAGE I D sy- msgi d TYPE ' I ' NUMBER sy- msgno

    WI TH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4. ENDI F.

    You need to catch the exception and change the message type to avoid theprogram aborting with a message. (FILE_GET_NAME will raise the exceptionwith message type E, which is converted to message type A during PBO.)

    When to Create a Default File Name

    There are cases where it is not suitable to create a default file name. Use the followingguidelines to determine if it is suitable:

    If the user is required to enter a file name in the user interface, create a default filename.

    If it is optional for the user to enter the file name and an entry would affect the programlogic in a misleading way, do not create a default file name. Otherwise, the user mustdelete the default file name from the field in order to keep the appropriate programlogic in place.

    If it is optional for the user to enter the file name, but there is a parameter available tospecify that a file should be created (for example, a checkbox item named Create File),then create the default file name.

    Example for Creating a Default Value

    * Paramet er PA_FI LE must be speci f i ed by t he user .* >>CREATE a defaul t val uePARAMETERS pa_f i l e TYPE f i l eext ern OBLI GATORY.

  • 8/12/2019 SecureProgramming_LogFileNames

    12/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 12

    Example for Not Creating a Default Value

    * Parameter PA_FI LE2 does not have t o be speci f i ed by t he* user. I f t he f i l e i s creat ed l at er , f or exampl e, t he f i l e* name i s speci f i ed f or t hi s par amet er l at er i n t he codi ng,*DO NOT creat e a def aul t f i l e name. Thi s pr event s t he* pr ogr amf r om cr eat i ng a f i l e when t he user di d not* necessar i l y want t hi s.

    PARAMETERS pa_f i l e2 TYPE f i l eext ern.

    Example for Creating a File Name Based on a Parameter

    * Parameter PA_FI LE3 does not have t o be speci f i ed by t he* user , but the pr ograml ogi c wi l l onl y creat e t he f i l e i f * t he checkbox PA_CHECK was checked by t he user. I n thi s* case,CREATE a def aul t val ue. I f t he user does not check* t he checkbox, no f i l e wi l l be creat ed. NOTE: i f t he* def aul t val ue for t he checkbox i s t hat i t i s checked,* you shoul d al so creat e a def aul t val ue.

    PARAMETERS pa_check AS CHECKBOX.

    PARAMETERS pa_f i l e3 TYPE f i l eext ern.

    Step 3: Validate Input (Recommended)

    Validate the physical file name supplied by the user on the screen where the file name wasentered (for example, during AT SELECTI ON- SCREEN). This ensures that the programreturns an error if the file name is invalid immediately and the user can adjust the file name asnecessary. If the program performs a lot of its logic before the file name is validated, and thevalidation returns an error, the processing time and the use of system resources wasunnecessary.

    AT SELECTI ON- SCREEN. CALL FUNCTI ON ' FI LE_VALI DATE_NAME' EXPORTI NG l ogi cal _f i l ename = gc_f name* any parameter s def i ned f or t hat l ogi cal f i l e name CHANGI NG physi cal _f i l ename = pa_f i l e EXCEPTI ONS OTHERS = 1.

    I F sy- subr c 0. MESSAGE I D sy- msgi d TYPE sy- msgt y NUMBER sy- msgno WI TH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4.

    ENDI F.

  • 8/12/2019 SecureProgramming_LogFileNames

    13/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 13

    Step 4: Validate the File Name (Mandatory)

    Validate the file name again directly before the OPEN DATASETor related statement.

    If you skipped step 3, for example, because OPEN DATASETis one of the first

    statements in the program logic, you must be careful about how you processerror messages from FILE_VALIDATE_NAME. For example, the recommendedprocedure for handling error messages for a report is to show the message asan I or an S message and then exit the program in such a way that the user isreturned to the selection screen, if possible. If you send an E or a W message,the program aborts and the user has to start over by calling the correspondingtransaction or program again.

    CALL FUNCTI ON ' FI LE_VALI DATE_NAME' EXPORTI NG l ogi cal _f i l ename = gc_f name* any parameter s def i ned f or t hat l ogi cal f i l e name CHANGI NG

    physi cal _f i l ename = pa_f i l e EXCEPTI ONS OTHERS = 1.

    I F sy- subr c 0.* I mpl ement sui t abl e err or handl i ng here, f or exampl e,* MESSAGE I D sy- msgi d TYPE sy- msgt y NUMBER sy- msgno* WI TH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4. ENDI F.

    OPEN DATASET pa_f i l e FOR I NPUT I N TEXT MODE ENCODI NG DEFAULT. I F sy- subr c 0.* . . . ENDI F.

    Using File Name Aliases

    To give the system administrator more flexibility and to enable the reuse of existing logical filenames, the logical file name concept was extended to support the use of aliases in the logicalfile name validation context.

    The system administrator can maintain aliases for a logical file name using the viewV_FILEALIA. (In Releases

  • 8/12/2019 SecureProgramming_LogFileNames

    14/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 14

    The first table shows the assignment of the two alias logical file names to the logical file nameused by the application, EXAMPLE_FIN1. The second table shows the Customizing table thatmaps the logical file name to the resulting physical file name.

    Logical File Name and A lias

    Logical File Name FromApp licat ion

    Sequential Number Alias Logical File Name

    EXAMPLE_FIN1 001 ZZ_LOGFILE1

    EXAMPLE_FIN1 010 ZZ_LOGFILE2

    The program EXAMPLE_FILE_ACCESS uses the logical file name EXAMPLE_FIN1 tovalidate the input of a physical file name. The program is used by two different groups ofbusiness users. The system administrator and the business team agreed upon two differentdirectories in the application server file system where the users should create their files. Thesystem administrator creates two new logical file names and defines each as an alias forEXAMPLE_FIN1.

    Customizing

    Logical File Resulting Physical File Name

    EXAMPLE_FIN1

    ZZ_LOGFILE1 / usr / SAP/ PRD_100/ home/ FI N/EXAMPLE_FI LE_ACCESS/ group1/

    ZZ_LOGFILE2 / usr / SAP/ PRD_100/ home/ FI N/EXAMPLE_FI LE_ACCESS/ group2/

    Example Program Run

    Program EXAMPLE_FILE_ACCESS calls the function module FILE_VALIDATE_NAME,providing the physical file name entered by the user as well as the hard-coded logical filename EXAMPLE_FIN1. The function module logic will determine all defined aliases andcompare the physical file name with that provided for each alias.

    The profile parameterDI R_HOMEis specified as / usr / SAP/ PRD_100/ home/ .This is the default directory used forOPEN DATASETand related statements ifno path is specified when the command is executed.

    Validation Result

    The following table shows the validation results for the corresponding user input.

    User Input Validation Result

    Fi l e1. asc Access is denied because the normalizedphysical file name would be/ usr / SAP/ PRD_100/ home/ Fi l e1. asc.

    . . / etc/ pwd/ Fi l e1. asc Access is denied because the normalizedphysical file name would be/ usr / SAP/ PRD_100/ et c/ pwd/ Fi l e1. asc.

    FI N/ EXAMPLE_ACCESS/ group1/ Fi l e. asc Access is granted because the path is correctaccording to the alias entry ZZ_LOGFILE1.The validation check for alias ZZ_LOGFILE2 isnot processed.

  • 8/12/2019 SecureProgramming_LogFileNames

    15/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 15

    In the above example it is still possible for the users from the two differentgroups to overwrite each others files. You may have scenarios where this mustbe avoided (for example, because a file with the wrong content in the wrongdirectory could disrupt the business process). In such a scenario, the systemadministrator would need to find a way to distinguish between the users of the

    user groups, for example, by using exit function modules or by providingparameter values from the selection screen to be included in the file name.

    Validating Logical File Names Entered By the UserThere are several steps involved in implementing the complete recommendation for validatingphysical file names entered by the user.

    The steps to perform are:...

    1. Define a constant to use for the logical file name. (Mandatory)

    2. During PBO, call the function module FILE_LOGFILE_ALIAS_PBO. (Mandatory)

    3. During PAI, call the function module FILE_LOGFILE_ALIAS_PAI. (Mandatory)

    4. Add a call to function module FILE_LOGFILE_ALIAS_F4. (Mandatory)

    5. Validate the file name. (Recommended)

    See the following sections.

    Step 1. Define a Constant Logical File Name to be Used for File NameValidation (Mandatory)

    For each parameter for a physical file name in your application create one global constant oftype FI LEI NTERN(logical file name). Set the value of this constant to the logical file nameused for file name validation in this context.

    CONSTANTS gc_f name TYPE f i l ei nter n VALUE ' EXAMPLE_FI N1' .

    Step 2: During PBO, Call Function Module FILE_LOGFILE_ALIAS_PBO.(Mandatory)

    During PBO, call the function module FILE_LOGFILE_ALIAS_PBO. This function moduleperforms the following:

    It checks whether validation for your logical file name is active.

    If validation is active, it will attempt to change the parameter on your screen to be a listbox. It fills the list box with the logical file names allowed in this context.

    Validation for a logical file name is defined as active if the system administratorhas set up the logical file name whitelist to use for validation or maintainedaliases.

  • 8/12/2019 SecureProgramming_LogFileNames

    16/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 16

    AT SELECTI ON- SCREEN OUTPUT. CALL FUNCTI ON ' FI LE_LOGFI LE_ALI AS_PBO' EXPORTI NG ed_l ogf i l e_appl = gc_l ogf i l e ed_paramet er _name = ' PA_FI LE'

    CHANGI NG cd_l ogf i l e_param = pa_f i l e.

    Some programs provide an input field that can be used for either a physical filename or a logical file name. In such a scenario, you may have to adjust the callabove depending on the context. For example, if you do not provide a field

    name in ed_par amet er _name, the field will not be converted to a list box. Ifcd_l ogf i l e_par amis empty, the function module will set the hard-codedlogical file name as a default.

    Step 3: During PAI, Call Function Module FILE_LOGFILE_ALIAS_PAI.(Mandatory)

    During PAI, call the function module FILE_LOGFILE_ALIAS_PAI. This function moduleperforms the following:

    It checks whether validation for your logical file name is active.

    If validation is active, and if the user specified or selected a logical file name, thefunction module checks whether the specified logical file name is allowed in this

    context. If it is not allowed, it raises the exception EXC_I NVALI D_FI LENAMEwith acorresponding error message. You have to handle this error message according to thecontext of your application. In most cases, you can use the error message as is.

    This call is necessary when loading a variant. In this case, the UI willautomatically add an entry to the list box containing the value from the variant.Therefore, even when using a list box, it is possible that the user will select alogical file name which has not been defined as a valid alias.

    AT SELECTI ON- SCREEN. CALL FUNCTI ON ' FI LE_LOGFI LE_ALI AS_PAI ' EXPORTI NG ed_l ogf i l e_appl = gc_l ogf i l e CHANGI NG cd_ l ogf i l e = pa_ f i l e EXCEPTI ONS

    OTHERS = 1. I F sy- subr c 0. MESSAGE I D sy- msgi d TYPE sy- msgt y NUMBER sy- msgno WI TH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4. ENDI F.

  • 8/12/2019 SecureProgramming_LogFileNames

    17/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7.02 17

    If the parameterpa_ f i l ecan be used for either physical and logical file namesyou, only have to call this function module if the specified file name is a logicalfile name. The recommended procedure is to call the function moduleFILE_GET_NAME first.

    If the result from FILE_GET_NAME is that the content ofpa_ f i l eis a logicalfile name, call the function module FILE_LOGFILE_ALIAS_PAI as illustratedabove.

    If the result from FILE_GET_NAME is that the content ofpa_ f i l eis not alogical file name, call the function module FILE_VALIDATE_NAME and provide

    the hard-coded logical file name in the EXPORTparameterl ogi cal _f i l enameand the content ofpa_ f i l efor the CHANGI NGparameterphysi cal _f i l ename.

    Step 4: Add a Call to Function Module FILE_LOGFILE_ALIAS_F4(Mandatory)

    This call is to be used in case the user tries to use the value help for entering a logical file

    name. This function module performs the following:

    If the validation for your logical file name is active, only the logical file names allowed inthis context will be available with the value help. The user will not be able to select alogical file name that he or she is not allowed to use when executing the program.

    If the validation for your logical file name is not active, the function module will start adialog which allows the user to select any logical file name defined in the system.

    AT SELECTI ON- SCREEN ON VALUE- REQUEST FOR pa_f i l e. CALL FUNCTI ON ' FI LE_LOGFI LE_ALI AS_F4' EXPORTI NG ed_l ogf i l e_appl = gc_l ogf i l e ed_paramet er _name = ' PA_FI LE' CHANGI NG cd_ l ogi cal _ f i l e = pa_ f i l e.

    If the parameterpa_ f i l ecan be used for either physical and logical file names,you need to decide whether you want to provide value help for a logical filename (in that case use FILE_LOGFILE_ALIAS_F4) or a physical f ile name (for

    example, by using cl _gui _f r ont end_servi ces=>f i l e_open_di al og).

  • 8/12/2019 SecureProgramming_LogFileNames

    18/18

    Secure Programming - ABAP December 2010

    Directory Traversal SAP NetWeaver 7 02 18

    Step 5: Validate the File Name. (Recommended)

    Validate the physical file name directly before the OPEN DATASETor related statement.

    CALL FUNCTI ON ' FI LE_GET_NAME'

    EXPORTI NG l ogi cal _f i l ename = pa_f i l e* any parameter s def i ned f or t hat l ogi cal f i l e name CHANGI NG physi cal _f i l ename = l d_physf i l e.

    CALL FUNCTI ON ' FI LE_VALI DATE_NAME' EXPORTI NG l ogi cal _f i l ename = gc_f name* any parameter s def i ned f or t hat l ogi cal f i l e name CHANGI NG physi cal _f i l ename = l d_physf i l e EXCEPTI ONS OTHERS = 1.

    I F sy- subr c 0.* I mpl ement sui t abl e err or handl i ng here, f or exampl e,* MESSAGE I D sy- msgi d TYPE sy- msgt y NUMBER sy- msgno* WI TH sy- msgv1 sy- msgv2 sy- msgv3 sy- msgv4. ENDI F.

    OPEN DATASET l d_physf i l e FOR I NPUT I N TEXT MODE ENCODI NG DEFAULT. I F sy- subr c 0.* . . .

    ENDI F.