COD219
COD219
Narration
In this course, you will learn about best practices and techniques for secure SAP application development using Java and
ABAP.
After completing this course, you will be able to describe important application security principles and best practices,
and describe how to remediate common application security vulnerabilities, protect data, and conduct security code reviews
for your SAP application.
On Screen Text
In this course, you will learn about best practices and techniques for secure SAP application development using Java and
ABAP.
Course Objectives:
After completing this course, you will be able to do the following for your Java application:
Page 1 of 171
Creating Secure Code SAP ABAP Foundations
Narration
This module reviews several important application security principles, and provides a discussion of input validation in SAP
applications.
When implemented together, these can greatly reduce the risk from application security vulnerabilities.
After completing this module, you will be able to identify important application security principles and identify how to
implement input validation with Java and ABAP.
On Screen Text
This module reviews several important application security principles, and provides a discussion of input validation in SAP
applications. When implemented together, these can greatly reduce the risk from application security vulnerabilities.
Module Objectives:
After completing this module, you will be able to:
Page 2 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s review some important application security principles that you must incorporate into your development process to help
ensure that your Java applications are secure.
The first principle is attack surface reduction. When you deploy your production applications, enable only the functionality
required for correct operation, and disable the other features.
This reduces the number of areas that require defending and simplifies your security task. Keep in mind that you must
defend against all possible ways to compromise a system,
whereas attackers only need to find one area that was overlooked.
The secure defaults principle states that you should deploy applications using the most secure settings by default.
Users are often unaware of certain features and do not configure them with the most secure settings.
Deploying with secure defaults reduces the likelihood that an attacker can exploit insecure settings left in place by users. In
addition, this reduces the attack surface of the application.
The principle of least privilege says that, to reduce the impact of potential exploits, you must deploy your Java application
using the minimal set of privileges required for the application
to function correctly. You can elevate privileges when needed, and release the elevated privileges when they are no longer
required.
The next principle, defense in depth, is based on the assumption that, at some point, any defense can fail.
Therefore, you should layer many defenses and best practices together to form a comprehensive defense strategy. With this
approach, if one layer of defense fails,
the other layers continue to protect your application, reducing the chance of a successful attack.
Page 3 of 171
Creating Secure Code SAP ABAP Foundations
On Screen Text
Let’s review some important application security principles that you must incorporate into your development process to help
ensure that your Java applications are secure.
Attack Surface Reduction. Deploy with only the functionality required for correct operation. Disable all other features.
Secure Defaults. Deploy applications using the most secure settings by default.
Least Privilege. Deploy with the minimal set of privileges required for the application to function.
Defense in Depth. Implement many layers of defense together. If one layer fails, the others continue to protect your
application.
Page 4 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
You should implement several layers of security controls so that if one fails, the others continue to protect your application.
This principle is known as:
Least privilege
Attack surface reduction
Secure defaults
Defense in depth
Page 5 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s now take a look at input validation, a critical component of any application security strategy.
Input validation verifies that input is in a correct and safe format before it is used by your Java application.
When properly implemented, it is the most effective method for mitigating risk from nearly every known application
vulnerability (with a few exceptions, which we’ll discuss later).
Let’s review some of the basics of input validation:
Your application may receive untrusted input from many sources, including users and various application components.
Consider all input to be untrusted, and have your Java application validate all input.
The two main approaches to input validation are whitelist and blacklist validation. Whitelisting allows known good input, and
rejects everything else.
It validates input for type, range, format, and length.
Blacklisting rejects only known bad input, and allows everything else. Its inherent weakness is that the set of all bad inputs is
potentially infinite and cannot be completely blocked.
Therefore, always use whitelist validation, and use blacklisting only as a supplementary measure.
Be sure to implement input validation that is well tailored to the needs of your application.
Always perform validation on the server side, because the client side is vulnerable—it can be bypassed or manipulated by
an attacker. You can still validate on the client for performance,
and as a supplementary security measure. If input passes both client and server validation checks, it is probably safe. If it
passes the client check but fails on the server side,
it is likely a sign of an attack.
Page 6 of 171
Creating Secure Code SAP ABAP Foundations
On Screen Text
Input validation verifies that input is in a correct and safe format before it is used by your application.
Consider all input from all sources to be untrusted, and validate all input using your Java application. Click here to
see some sources of untrusted input.
Whitelist validation allows known good input and rejects everything else. Always use whitelisting.
Blacklist validation rejects only known bad input, and allows everything else. Use it only as a supplement to
whitelisting.
Implement input validation that is well tailored to the needs of your application.
Always perform validation on the server side.
Page 7 of 171
Creating Secure Code SAP ABAP Foundations
Narration
We’ve pointed out the inherent weakness of blacklist validation. Let’s illustrate it with a Java code example.
This example evaluates string input to verify that it is a valid year. To do this, it checks the string against a predefined list of
bad inputs.
For example, the code checks that the string is not “a”, “b”, or “hack”, none of which are valid years.
Now, the word “attack” is also not a valid year—but it was not included in the predefined blacklist. Therefore, the code
erroneously accepts “attack” as a valid year.
You could extend the blacklist to include “attack”, but what about other invalid inputs, such as “50,000” or “car”?
The set of all invalid inputs is potentially infinite. Therefore, an attacker could compromise your application by simply entering
bad input that has not been accounted for in your blacklist.
So, use blacklisting only as a supplementary security measure to whitelisting, but never use it on its own.
On Screen Text
Page 8 of 171
Creating Secure Code SAP ABAP Foundations
Page 9 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Now, let’s illustrate the robust nature of whitelist validation, using a Java code example.
This code example checks input against a set of finite, well-defined patterns to see if it is a valid year.
It verifies that the type is only integers, the range is between zero and 9,999, the format is four consecutive digits, and the
length is exactly four characters.
On Screen Text
Now, let’s illustrate the robust nature of whitelist validation, using a Java code example.
Page 10 of 171
Creating Secure Code SAP ABAP Foundations
Page 11 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Next, let’s explore whitelist validation using regular expressions.
Regular expressions provide a structured method for concise pattern matching that you can use with whitelist input
validation.
Both Java and ABAP provide built-in support for regular expressions, making it easy for you to incorporate regular
expressions into your applications.
To use regular expressions, you first define a regular expression that describes expected input data types, ranges, formats,
and lengths.
Next, you compare the input received by your application against the regular expression. If the input does not match the
regular expression, it should be considered bad and rejected.
If the input matches the regular expression, it can be processed by your application.
On Screen Text
Page 12 of 171
Creating Secure Code SAP ABAP Foundations
ABAP allows regular expression matching using the FIND REGEX statement as well as the CL_ABAP_REGEX and
CL_ABAP_MATCHER classes.
1. Define a regular expression that describes expected input data types, ranges, formats, and lengths.
If the input does not match the regular expression, reject the input.
If the input matches the regular expression, the input can be processed.
Page 13 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s see some sample code that validates input using regular expressions.
Going back to our year example, our sample code defines a regular expression for a valid year. The regular expression is
defined in the pattern variable in the IsYear method, which states that a valid year is exactly four consecutive characters
long, contains only digits, and can range from zero to 9,999.
The first input is not a valid year, so IsYear returns false.
The other two inputs are valid years, and IsYear returns true for both.
Click each tab to view sample code that validates input using regular expressions.
On Screen Text
Click each tab to view sample code that validates input using regular expressions.
Java
Page 14 of 171
Creating Secure Code SAP ABAP Foundations
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Output is:
// a2014: false
// 2014: true
// 1980: true
}
return(m.matches());
}
ABAP
DATA: text TYPE string,
matcher type REF TO cl_abap matcher.
matcher = cl abap_matcher=>create(
pattern = '(^\d{4}$)'
text = p_input3
).
IF matcher->match( ) = abap_false.
MESSAGE e000 with 'Only letters are allowed. No numbers or special characters'.
ENDIF.
FIND FIRST OCCURRENCE OF REGEX '^\d{4}$' IN p_input3.
IF sy-subrc = 0.
MESSAGE 'There is some non-letter in your input.' TYPE 'E'.
ENDIF.
Page 15 of 171
Creating Secure Code SAP ABAP Foundations
Narration
You can use pre-written input validation methods provided by various Java frameworks, such as JSF, SpringMVC, Struts 1,
and Struts 2.
These technologies and libraries perform and facilitate appropriate input validation.
On Screen Text
You can use pre-written input validation methods provided by various Java libraries, such as JSF, SpringMVC, Struts 1, and
Struts 2.
Page 16 of 171
Creating Secure Code SAP ABAP Foundations
Narration
When correctly implemented, input validation is one of the most effective countermeasures against malicious input, but it is
not a silver bullet.
It is only effective for input that has a defined structure or character composition, such as phone numbers, dates, and credit
card numbers.
For unstructured input, or where the definition of valid data is very broad, you need to use additional security measures for
defense in depth.
These measures include output encoding and data parameterization, which we’ll discuss later in this course.
In addition, input validation does not protect against many other vulnerabilities,
such as those caused by use of weak cryptographic algorithms or race conditions (in which an attacker accesses or modifies
a resource ahead of your application).
Cryptographic issues and race conditions are discussed later in this course.
On Screen Text
Input validation is one of the most effective countermeasures against malicious input, but it is not a silver bullet.
For a comprehensive defense strategy, you need to use additional security measures such as output encoding and
data parameterization.
Page 17 of 171
Creating Secure Code SAP ABAP Foundations
Input validation does not protect against many other vulnerabilities, such as those caused by weak cryptographic
algorithms or race conditions.
Page 18 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
Acme.com encrypts sensitive customer financial data stored on their servers. An audit showed that the encrypted data was
at risk because the encryption algorithm they used was weak. Acme.com can mitigate this risk by implementing whitelist
input validation.
True
False
Page 19 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
java.util.regex provides built-in support for regular expressions in Java. Regular expressions are useful for whitelist
validation because:
Page 20 of 171
Creating Secure Code SAP ABAP Foundations
Module Summary
Narration
On Screen Text
Module Summary
Input Validation
In this topic, you reviewed the basic principles of input validation and then explored implementing SAP input validation using
Java or ABAP.
You looked at a blacklist and whitelist validation example, learned about performing whitelist validation using regular
expressions in Java, and learned why whitelist validation is a critical security measure for your application, but is not
sufficient by itself to protect against all vulnerabilities.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Page 21 of 171
Creating Secure Code SAP ABAP Foundations
Narration
This module describes ways to remediate common application security vulnerabilities in your SAP ABAP or Java application.
After completing this module, you will be able to mitigate risk from SQL injection, integer overflows, canonicalization issues,
information disclosure, and race conditions vulnerabilities.
On Screen Text
This module describes ways to remediate common application security vulnerabilities in your Java application.
Module Objectives:
After completing this module, you will be able to mitigate risk from the following vulnerabilities:
SQL injection
Integer overflows
Canonicalization issues
Information disclosure
Race conditions
Page 22 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The first vulnerability we’ll discuss is SQL injection. Let’s review the basics of this vulnerability.
SQL injection vulnerabilities are created when an application concatenates input into dynamic SQL statements.
These vulnerabilities can also occur in stored procedures that construct dynamic SQL queries using unvalidated, untrusted
user input.
A successful SQL injection attack can have a very serious impact, particularly with SAP because the entire application--
including user accounts, application code,
and logfiles--exists in the database. SQL injection allows the attacker to execute unauthorized queries and commands on
databases, with the full privileges of the exploited application.
To reduce the risk from SQL injection vulnerabilities in your application, validate all untrusted input used to construct
dynamic SQL statements, use parameterized APIs for all database access,
and use least privileged database accounts.
Click each tab to review the basics of SQL injection vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of SQL injection vulnerabilities, their impact, and remediation techniques.
Vulnerability
Page 23 of 171
Creating Secure Code SAP ABAP Foundations
SQL injection vulnerabilities occur when an application concatenates input into dynamic SQL statements.
These vulnerabilities can also occur in stored procedures that construct dynamic SQL queries using unvalidated,
untrusted user input.
Impact
A successful SQL injection attack allows the attacker to execute unauthorized queries and commands on databases,
with the full privileges of the application being exploited.
Remediation
To protect against SQL injection:
Use least privileged database accounts. This does not prevent SQL injection vulnerabilities, but it helps limit the
potential damage from SQL injection attacks.
Page 24 of 171
Creating Secure Code SAP ABAP Foundations
ABAP/Open SQL
Narration
The majority of data access with ABAP makes use of SAP’s database-independent Open SQL, or OSQL, standard.
Open SQL is integrated with ABAP and provides a standard subset of SQL that will work with any underlying database.
Queries sent via Open SQL pass through an interface that translates Open SQL statements to the native SQL for that
particular database.
Open SQL provides security features that limit exposure to SQL injection attacks.
Some of these security features include:
Restricting queries to a limited number of commands.
Enforcing client separation for database tables.
Internal conversion to prepared statements.
SQL statements cannot be dynamically executed within the clause of another statement.
Integrated logging of database access.
On Screen Text
ABAP/Open SQL
Page 25 of 171
Creating Secure Code SAP ABAP Foundations
Dynamic SQL
Narration
Simple Open SQL statements in ABAP are internally converted to prepared statements, where data is separated from SQL
instructions.
This type of query, as shown here, prevents exposure to SQL injection attacks.
However, when building a dynamic query string based on concatenating user input, as seen here,
you introduce SQL injection vulnerabilities and you must take additional steps to validate user input.
On Screen Text
Dynamic SQL
This query is vulnerable to SQL injection if the user controls the value of p_custid:
Page 26 of 171
Creating Secure Code SAP ABAP Foundations
WHERE (s_cond).
Page 27 of 171
Creating Secure Code SAP ABAP Foundations
Narration
While input sanitization and validation can vary depending on the type of data, the most essential step is to properly escape
quotes.
The dynamic programming utility class allows you to do this using the ESCAPE_QUOTES, ESCAPE_QUOTES_STR,
QUOTE, and QUOTE_STR methods.
Note that while ESCAPE_QUOTES and ESCAPE_QUOTES_STR are commonly used for sanitizing input, QUOTE and
QUOTE_STR are more effective because they also enclose the value in quotes.
For data validation, the dynamic programming utility class also includes methods for checking integer values, table and
column names, and comparing values against a whitelist of values.
On Screen Text
CL_ABAP_DYN_PRG Class
Page 28 of 171
Creating Secure Code SAP ABAP Foundations
Native SQL
Narration
At times you may find Open SQL too limiting, or you may need to access unique features or specific SQL syntax of the
underlying database.
For these situations, SAP provides Native SQL that you can access via ADBC or by placing the SQL between the EXEC
SQL and ENDEXEC commands.
Native SQL queries are sent largely unchanged to the underlying database, but in doing so they lose the security features
enforced with Open SQL.
For this reason, you must be extra careful to validate and escape input. Use the dynamic programming utility class shown on
the previous screen.
On Screen Text
Native SQL
Page 29 of 171
Creating Secure Code SAP ABAP Foundations
Narration
When using Native SQL, do not concatenate user input to build a query string. Instead, use host variables as parameters to
separate user input from the SQL commands.
Host variables are data objects statically embedded in a native SQL statement, escaped with the colon character, as shown
in this example.
Note that because native SQL bypasses automatic client separation, you should always include a WHERE clause to match
the client column to SY-MANDT, which contains the current client.
When accessing Native SQL with ADBC the process is similar, except that you would use the question mark as a
placeholder instead of host variables.
On Screen Text
Page 30 of 171
Creating Secure Code SAP ABAP Foundations
Narration
SAP will limit exposure to SQL injection when using Open SQL/JDBC and Open SQL/SQLJ.
However, like ABAP, you should use host variables whenever possible with dynamic SQL queries in Java.
When using JDBC, you do not get that automatic protection. You must implement protection from SQL injection yourself.
Let’s explore some of these SQL injection remediation techniques using a Java code example.
This sample Java code uses Java Database Connectivity, or JDBC, to query a database.
Observe that the dbProcessEmail method is vulnerable to an SQL injection attack. An attacker only needs to pass in an
email parameter that contains malicious SQL commands.
In the examples that follow, we’ll look at techniques to modify this code to help mitigate the risk from an SQL injection attack.
On Screen Text
This sample Java code uses Java Database Connectivity (JDBC) to query a database. The dbProcessEmail method is
vulnerable to SQL injection if an attacker passes in an email parameter with malicious SQL commands.
Page 31 of 171
Creating Secure Code SAP ABAP Foundations
Page 32 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The first mitigation technique we’ll look at is whitelist input validation. Let’s see how whitelisting can mitigate the SQL
injection vulnerability in our sample Java code.
As shown, the dbProcessEmail method has been modified. It now calls the isValidEmail method to check if the Email
parameter is a valid email address.
isValidEmail uses a whitelist approach to validate Email input values. A regular expression for email addresses is defined.
isValidEmail compares the input parameter against the regular expression, returning true if they match and false if they do
not.
dbProcessEmail inspects the value returned by isValidEmail. If the value is true, dbProcessEmail constructs and executes a
dynamic SQL query using the Email input.
Otherwise, an exception is thrown to help mitigate potential risk from an SQL injection attack.
On Screen Text
Whitelist input validation is an effective way to reduce the risk from SQL injection.
Let’s see how whitelist validation can mitigate the SQL injection vulnerability in our sample Java code.
Page 33 of 171
Creating Secure Code SAP ABAP Foundations
Page 34 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The second mitigation technique to reduce risk from SQL injection is to use prepared statements. They prevent
concatenation of untrusted data and SQL query syntax,
and thus remove the root cause of SQL injection.
To do this in Java, follow these steps:
First, identify dynamic SQL queries in your code that are constructed with untrusted input. Then, replace all references to the
Statement class with the PreparedStatement class.
Next, inspect each query to identify untrusted input parameters, and replace them with a question-mark placeholder.
Set the parameter types and values for each placeholder by referencing its parameter index. Finally, execute the prepared
statement.
Let’s see how to modify our sample code to use the Java PreparedStatement class.
First, you identify dynamically generated SQL queries in your code.
Next, replace references to the Statement class with the PreparedStatement class.
Then, replace untrusted input parameters with a question mark to mark it as a placeholder.
Set the placeholder’s parameter type and value. In this example, the parameter is a string type,
so the setString method with the index value 1 is used because this parameter is the first placeholder in the modified query.
Finally, execute the prepared statement and parse the results.
On Screen Text
Page 35 of 171
Creating Secure Code SAP ABAP Foundations
Prepared statements prevent concatenation of untrusted data and SQL query syntax, and thus remove the root cause of
SQL injection.
3. Identify untrusted parameters in each query, and replace with a “?” placeholder.
4. Specify the parameter type and value by referencing the placeholder index.
Let’s take a look at how to modify the sample code to use the Java PreparedStatement class.
Page 36 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The third approach to reducing SQL injection risk is to use type-safe parameters with stored procedures.
This technique provides the following benefits:
First, stored procedures provide automated input filtering. With whitelist or blacklist input validation, you could miss a use
case that an attacker can exploit.
But when you parameterize and type-enforce untrusted data, the data is filtered very effectively. This significantly reduces
the likelihood of a successful SQL injection attack.
Second, stored procedures can be configured to execute under different security privileges than the calling database user.
You can restrict the privileges of a potential attacker to the limited privileges of the stored procedure.
Finally, stored procedures are typically cached by databases, so using them can lead to noticeable performance
improvement.
Let’s see how to implement parameterized stored procedures in our sample Java code.
Here we’ve configured our original dynamic SQL query as a stored parameter on the database.
Next, the original Statement object was replaced with the CallableStatement object.
The stored procedure to call is specified with a parameter placeholder, and the parameter is set as a string with the value
contained in Email.
Finally, the code executes the query.
On Screen Text
Page 37 of 171
Creating Secure Code SAP ABAP Foundations
Another effective approach to reducing SQL injection risk is to use type-safe parameters with stored procedures.
Benefits include:
3. Performance improvement.
Let’s see how to implement parameterized stored procedures in our sample Java code.
Page 38 of 171
Creating Secure Code SAP ABAP Foundations
Narration
In addition to the remediation techniques discussed so far, you should also implement the principles of least privilege and
defense-in-depth to help protect against SQL injection attacks.
In this context, least privilege means to deploy back-end databases with only the privileges required to properly execute your
application.
For example, do not deploy your application with full System rights if NetworkService or LocalService rights suffice.
This way, if an attacker executes arbitrary commands against a database engine, the engine may not have the permissions
required to successfully execute those commands.
In addition, configure database users to have the least privileges required for access to individual databases, tables, and
other database resources.
Note that implementing the principle of least privilege helps to limit potential damage, but it does not correct or prevent SQL
injection vulnerabilities in code.
To implement defense in depth, you should layer the many remediation techniques that we’ve discussed so far to help
protect your application against SQL injection.
Never rely on one defense alone.
On Screen Text
In addition to the remediation techniques discussed, you should also implement these security principles:
Least privilege:
Page 39 of 171
Creating Secure Code SAP ABAP Foundations
Configure database users to have the least privileges required for access to individual databases, tables, and
other database resources.
Defense in depth:
Combine input validation, prepared statements, and type-safe parameters in stored procedures, and deploy with
least privileges.
Page 40 of 171
Creating Secure Code SAP ABAP Foundations
Narration
As you try to defend against SQL injection, you need to be aware of a number of common pitfalls.
You might make the mistake of attempting to blacklist SQL attack signatures. Attackers use several publicly known
obfuscation techniques to evade detection,
which makes it virtually impossible to detect all attacks. Never rely on blacklisting, although you can use it as a
supplementary measure to whitelist validation.
A common misconception is that using stored procedures alone—without type-safe parameters—can make your code
immune to SQL injection.
Actually, moving a dynamically constructed SQL statement into a stored procedure simply moves the point of exploitation to
a different area of the application,
and does not reduce the risk from an SQL injection attack. You must use parameterized stored procedures to protect against
this risk.
As a developer, you might often use one remediation technique or another, but fail to combine them in a defense-in-depth
approach. Input validation, prepared statements,
and parameterized stored procedures are all essential for reducing risk from SQL injection attacks.
Ensure that your application performs a sanity check on all output SQL data. Although attackers often use SQL injection to
execute commands, they might also use it to enumerate table data.
For example, they can gather data for all users, not just the rows that pertain to their own account. So, if your application
expects only a single row of output from a select command,
your code should check that only one row of output was returned. If more or less data than expected was returned, it could
be an indication of an SQL injection attack.
Page 41 of 171
Creating Secure Code SAP ABAP Foundations
Finally, SQL injection vulnerabilities have a broad scope beyond Microsoft SQL Server. Keep in mind that any database
management system that supports the SQL language,
such as MySQL, Oracle, and Microsoft SQL Server, is susceptible to SQL injection attacks.
On Screen Text
Page 42 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
If you use a stored procedure without type-safe parameters, the dynamic SQL statements in the stored
procedure:
Could be exploited by an injection attack.
Are protected from all injection attacks.
Contain no untrusted or unvalidated input.
Can greatly limit the damage from an injection attack.
Page 43 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The next vulnerability we’ll discuss is integer overflows. Let’s review the basics of this vulnerability.
Integer overflows occur whenever an application performs an arithmetic operation in which the result of the operation
exceeds the maximum and minimum range of the destination type.
This vulnerability is most dangerous to applications that perform critical integral calculations, and unmanaged applications,
where an integer overflow can result in code execution.
The impact of this vulnerability can vary, depending on how the integral calculation is used. In general, impacts can include
denial of service, code execution, and logic errors.
To detect and remediate integer overflow vulnerabilities in Java, you should use precondition testing, upcasting, or
BigInteger objects.
Click each tab to review the basics of integer overflow vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of integer overflow vulnerabilities, their impact, and remediation techniques.
Vulnerability
Integer overflow vulnerabilities occur when arithmetic operations are performed and result in a value that exceeds
the range of the destination type.
Page 44 of 171
Creating Secure Code SAP ABAP Foundations
This vulnerability is most dangerous to applications that perform critical integral calculations, and unmanaged
applications, where an integer overflow can result in code execution.
Impact
Denial of service: Integer overflows and underflows can cause applications to crash.
Code execution: Integer overflows can result in incorrect indexing into memory regions, resulting in potential code
execution.
Logic errors: Integer overflows in application logic can result in undesirable application-specific behavior.
Remediation
To remediate or reduce the risk from integer overflow vulnerabilities in your application, use the following techniques:
Precondition testing
Upcasting
BigInteger objects
Page 45 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Although ABAP detects and catches integer overflow errors, Java does not have built-in detection for integer overflows.
They must be prevented manually using precondition testing, upcasting, and BigInteger.
Precondition testing checks each arithmetic operation to see if an overflow occurs or not. If not, the operation is performed;
otherwise, an exception is thrown.
Upcasting casts the inputs to the next largest primitive type to perform the arithmetic. The result is checked to see if an
overflow occurs in the smaller original primitive type.
With BigInteger, inputs are converted into the BigInteger object types that do not overflow to perform operations. A range
check is done before converting the result back to the smaller type.
We’ll explore each of these techniques more thoroughly using Java code examples.
On Screen Text
Java does not have built-in platform protections for detecting integer overflows.
Precondition testing
Upcasting
BigInteger
Page 46 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The first method of detecting integer overflow vulnerabilities is precondition testing, which checks to see if the result of an
arithmetic operation causes an overflow or not.
Detection code must be written for every arithmetic operation in which an overflow could occur, including addition,
subtraction, multiplication, and division.
The code shown performs precondition checking for the addition operation. Given two integer values, it checks to see if an
integer overflow results from the addition,
and throws an ArithmeticException if it would. Otherwise, it returns the sum of the two integers.
On Screen Text
Approach: Before performing an arithmetic operation, check to see if an overflow would occur.
Note: Precondition testing code must be written for each arithmetic operation (including addition, subtraction, multiplication,
and division)
Page 47 of 171
Creating Secure Code SAP ABAP Foundations
Page 48 of 171
Creating Secure Code SAP ABAP Foundations
Remediation 2: Upcasting
Narration
The next remediation approach is called Upcasting. Upcasting converts the inputs to the next largest primitive type to
perform the arithmetic operation.
The result is checked to see if an overflow occurs in the smaller original primitive type.
Upcasting cannot be used with long types or 64-bit integers, because longs are the largest primitive integral type.
Similar to the precondition testing approach, upcasting code must be written for each arithmetic operation.
The code shown performs upcasting for the addition operation. Given two integer values, it checks to see if an integer
overflow would result from the addition
and throws an ArithmeticException if it would. Otherwise, it returns the sum of the two integers.
On Screen Text
Remediation 2: Upcasting
Approach: Convert the inputs to the next largest primitive type to perform the arithmetic operation.
The result is checked to see if an overflow occurs in the smaller original primitive type.
Upcasting code:
Page 49 of 171
Creating Secure Code SAP ABAP Foundations
Page 50 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Another approach to handle integer overflows in Java is to use BigInteger objects. With this approach, inputs are converted
into BigInteger object types that do not overflow.
Before the result of the operation is returned, it is checked to see if an overflow occurs in the original type.
Like the techniques that we’ve discussed earlier, using BigInteger objects to detect integer overflows requires you to write
code for each arithmetic operation.
Because multiple objects must be created, using BigInteger objects can be slower than using primitive types.
The code shown uses BigInteger objects to perform an addition operation of two integers.
The operation is performed and the result is checked to see if overflow occurs in the original integral type. If it does, an
ArithmeticException is thrown; otherwise,
the sum of the two integers is returned.
On Screen Text
Approach: Convert the inputs into java.math.BigInteger objects to perform the arithmetic operation.
After the operation is performed, the result is checked to see if an overflow occurs in the smaller type.
Page 51 of 171
Creating Secure Code SAP ABAP Foundations
The code shown uses BigInteger objects to perform an addition operation of two integers.
Page 52 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Avoid the following common pitfalls with integer overflows:
Don’t assume that integer overflows apply to only 32-bit integers. Integer overflows can occur with other integral types,
such as 16-bit integers (referred to as a short) and 64-bit integers (referred to as a long).
Next, don’t assume that integer overflows apply only to signed integral types. Integer overflows can also occur with unsigned
integers.
Overflows simply wrap from the maximum positive unsigned integer value to 0, and back in the other direction from 0 to the
maximum positive range.
Finally, keep in mind that, unlike ABAP, the Java platform does not have built-in integer overflow detection or protection.
You are responsible for detecting and preventing integer overflows in applications.
On Screen Text
Common integer overflow pitfalls result when you assume that integer overflows:
Apply only to 32-bit integers.
Page 53 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
True or False:
The Java platform automatically detects integer overflow conditions.
True
False
Page 54 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
Page 55 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Now let’s look at security issues related to canonicalization. These common issues occur whenever your application makes
a security decision based on the form of an input,
such as a filename, without first resolving it to a standard, or canonicalized, form.
A successful exploit of a canonicalization vulnerability can impact your application in several ways.
Attackers can gain unauthorized access to resources, bypass security checks for restricted resources, and elevate their
privileges on a system.
To reduce canonicalization-related risks in your application, select a standard representation for input that is used to make
any security decision.
To perform the canonicalization, be sure to use standard, well-tested libraries. Also, after untrusted data is properly
canonicalized, validate the data.
Click each tab to review the basics of canonicalization issues, their impacts, and remediation techniques.
On Screen Text
Click each tab to review the basics of canonicalization issues, their impacts, and remediation techniques.
Vulnerability
Page 56 of 171
Creating Secure Code SAP ABAP Foundations
Canonicalization issues occur when your application makes a security decision based on untrusted input that has not been
canonicalized, or translated into a standard form.
Applications that handle URLs, hostnames, and filenames are commonly susceptible to this type of attack, because these
inputs can reference the same resource in different ways.
Impact
Unauthorized access: Attackers could traverse into unauthorized file system directories.
Information disclosure: Attackers might bypass checks for specific or restricted resources.
Elevation of privilege: Attackers could redirect file system operations to unintended resources.
Remediation
Page 57 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Canonicalization issues are very common in applications that make security decisions based on untrusted filenames.
Make sure that you canonicalize any untrusted file path before you validate a filename.
To do this, use the java.io.File.getCanonicalPath or the java.io.File.getCanonicalFile method.
The sample code shown demonstrates how to use getCanonicalFile to canonicalize untrusted file paths.
The canonicalizePath method uses the getCanonicalFile method to return a File object that contains the canonical form of
the given path.
After the untrusted filepath data is canonicalized, the application validates the untrusted data.
On Screen Text
When using untrusted file names, canonicalize the file path before you validate the file name.
To do this, use one of the following methods:
java.io.File.getCanonicalPath
java.io.File.getCanonicalFile
The sample code shown demonstrates how to use getCanonicalFile to canonicalize untrusted file paths.
Page 58 of 171
Creating Secure Code SAP ABAP Foundations
Page 59 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Similar to Java, ABAP code needs to canonicalize file paths and URLS to prevent unauthorized file access and other
attacks.
When accessing the file system using OPEN DATASET, READ DATASET, TRANSFER, or DELETE DATASET, the system
automatically performs the following authority checks:
It performs an authorization check against the S_DATASET object, it checks file names against the SPTH table for entries
with a FS_BRGRU value using the S_PATH object,
and, when applicable, it checks for system administration authorization using the S_RZL_ADM object.
In addition to these automatic checks, you should manually perform the following: Use FILE_VALIDATE_NAME before
accessing the file system,
validate input to check for malicious metacharacters, and use logical file names for file system access.
On Screen Text
Automatic Checks:
Checks file names against the SPTH table for entries with a FS_BRGRU value using the S_PATH object.
When applicable, checks for system administration authorization using the S_RZL_ADM object.
Page 60 of 171
Creating Secure Code SAP ABAP Foundations
Manual Checks:
Page 61 of 171
Creating Secure Code SAP ABAP Foundations
Narration
To properly canonicalize URLs, ABAP provides a number of helper methods in the CL_HTTP_UTILITY class including:
IS_VALID_URL, which verifies that a URL is valid; NORMALIZE_URL, which will remove path traversals to return a fully
canonicalized path; and UNESCAPE_URL, DECODE_BASE64,
and DECODE_UTF8 which will eliminate any attempt to encode path traversal characters.
Although the process of validation and normalization is important, this is still a blacklist approach.
After obtaining a proper URL you should use the CHECK_HTTP_WHITELIST method to verify that the final URL exists in
the HTTP_WHITELIST table.
On Screen Text
Page 62 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Some common canonicalization pitfalls include the following:
Avoid creating your own canonicalization methods. It is very difficult to know all possible expressions for resources.
Whenever possible, leverage built-in methods from the Java or SAP platforms.
Canonicalize before you validate input, not after. Although input validation is usually the first step to perform on untrusted
input, when canonicalization issues can occur,
always canonicalize before validating input.
Whenever possible, use absolute paths, not relative paths to reference resources. Relative paths often contain characters
that make it possible for attackers to reference restricted resources.
On Screen Text
Some common canonicalization pitfalls include, but are not limited to, the following:
Page 63 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
Page 64 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Now, let’s examine information disclosure vulnerabilities. These occur when an application reveals too much information,
whether through improper handling of exceptions;
embedding sensitive information in error messages, source code, or comments; or using inconsistent error messages.
Information disclosure vulnerabilities vary from application to application. The following best practices help mitigate the risk
from information disclosure:
Avoid hard-coding secrets in your application code.
Use language-specific comments. These are automatically removed by compilers and are not visible to clients.
Use short, generic error messages that do not reveal sensitive information, and never return direct error messages from
backend systems.
Use the principle of open design.
Encrypt sensitive data. We’ll discuss this more later in this course.
Click each tab to review the basics of information disclosure vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of information disclosure vulnerabilities, their impacts, and remediation techniques.
Page 65 of 171
Creating Secure Code SAP ABAP Foundations
Vulnerability
Information disclosure vulnerabilities occur when an application reveals sensitive or extraneous information to an attacker.
Common causes of information disclosure include:
Impact
Information disclosure vulnerabilities can impact data confidentiality.
Attackers might use the disclosed information to gain access to sensitive data, or simply to aid in attacks against the
application. For example, an attacker can use information about the underlying database schema revealed in an error
message to conduct an SQL injection attack.
Remediation
Follow these best practices to help mitigate the risk of information disclosure:
Avoid hard-coding secrets.
Use language-specific comments, as these will be automatically removed by compilers and will not be visible to
clients.
Use generic error messages, and never return direct error messages from back-end systems such as databases.
Use the principle of open design: Assume that an attacker has access to all information. This means you must
design and implement your application so that, even with this information, it is still difficult for the attacker to launch a
successful exploit.
Encrypt sensitive data. Ensure that all sensitive information managed by your application remains encrypted until
accessed.
Page 66 of 171
Creating Secure Code SAP ABAP Foundations
Narration
It is a common myth that it is safe to hard-code secrets and intellectual property in applications.
Here is a simple Java application in which a username and password have been hardcoded in the application source.
It would be easy for an attacker to manually inspect the class for sensitive strings.
Or, they could, use the “javap” command with the –c flag to disassemble the compiled class file and look for hard-coded
secrets.
An attacker could even decompile the class file and extract the source code.
Obfuscation tools provide a partial remedy that can make an attacker’s job much more difficult, but not impossible.
On Screen Text
An attacker can:
Inspect the class for suspicious strings.
Disassemble the class to inspect the logic.
Decompile the class to read your source.
Page 67 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s look further into each of the three methods that an attacker can use to uncover hard-coded secrets.
First, we see a screenshot of inspecting a Java class manually.
Next we see using a disassembler to extract Java opcode.
It is even easier for an attacker to decompile a Java class file back to source code than it is to manually inspect or
disassemble it. There are several public decompiler tools,
such as JAD and JD. Shown here is a screenshot of an online decompiler in which attackers can drag a Java class onto a
Web page and the source code is returned.
Click each tab to see screenshots of the three methods that an attacker can use to uncover hard-coded secrets.
On Screen Text
Let’s look further into each of the three methods that an attacker can use to uncover hard-coded secrets.
Click each tab to see screenshots of the three methods that an attacker can use to uncover hard-coded secrets.
Inspecting Java Classes
Screenshot: Inspecting a Java class manually.
Often by just dumping the contents of a class file, an attacker can obtain information about any hard-coded values in the
class, such as passwords.
Page 68 of 171
Creating Secure Code SAP ABAP Foundations
The standard “javap” tool was used to disassemble the HardCodedSecrets class file to extract hard-coded strings in the
class.
Shown is an online Decompiler that attackers use to drag a Java class onto a Web page, and the source code is returned.
Page 69 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Now, let’s look at information disclosure through exception information. In this simple example, the code performs an action
and catches exceptions.
However, the application prints the entire error stack to the console, which can potentially reveal too much information to a
user or attacker.
To find and fix information disclosure vulnerabilities in exception information, follow these steps:
First, review your application to identify all exception handlers and error-handling code. You can do this by searching for
keywords such as try, catch, finally, and throw.
Next, add logging code to handle and log detailed error information. Ensure that the log data is never exposed to
unprivileged users.
Also, as a best practice, never log sensitive information such as passwords in logs.
Finally, ensure that error messages are simple and generic so that you do not disclose information about the error condition.
For example, if a user login fails, use the same generic error message whether it fails because of an incorrect password or
an incorrect username.
On Screen Text
Following are the steps to find and fix information disclosure vulnerabilities through exception information:
Page 70 of 171
Creating Secure Code SAP ABAP Foundations
Page 71 of 171
Creating Secure Code SAP ABAP Foundations
Narration
This table shows insecure error messages that contain too much information, along with recommended alternatives.
The first message, “Invalid password for user: jsmith,” is dangerous, because it confirms that username “jsmith” exists on the
system and can be targeted for attack.
The second message is dangerous because it confirms that the specified user does not exist on the system.
This saves time for the attacker and allows him to focus effort on finding users that do exist.
Now, take a look at the recommended alternative to the first two error messages. It does not indicate if the username exists,
or if it was the username or password that was incorrect.
Finally, the third error message is typical of errors from back-end databases, where there may be a syntax error from a failed
SQL injection attack.
This error message lets the attacker know where the attack is failing, allowing him to refine the attack.
The recommended message provides a better alternative and offers no specific information to the attacker as to why the
request failed.
Remember that the less you disclose to an attacker, the less likely the attack will be successful.
On Screen Text
This table shows insecure error messages that contain too much information, along with recommended alternatives.
Page 72 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Follow these secure-development best practices to reduce the risk from information disclosure vulnerabilities in your
application:
Handle all exceptions. Always use try/catch blocks whenever an exception can be thrown. Configure a global exception
handler that catches any exception that accidentally is not caught.
Do not expose exception stack trace information to users. In some instances, this could be useful to a malicious user.
When returning an error message to a user, be as generic as possible to avoid disclosing the specifics of the error condition.
For example, if an SQL error occurs, the message “There was an error accessing the database” is all you need to disclose.
Ensure that error messages reporting the same condition are exactly the same. For example, use the same generic
message whether a login fails due to a wrong username
or a wrong password. For Web applications, always redirect the user to a generic error page.
For example, redirect to the same generic “An error was encountered” error page whether the Web application encountered
an error accessing a database resource or reading a file on disk.
Avoid details whenever possible. This is especially important for Web applications, because they are more easily accessible
and susceptible to attack.
Instead of returning detailed information to end users, log the information so that the application can be debugged later.
On Screen Text
Follow these secure-development best practices to reduce the risk from information disclosure vulnerabilities in your
application:
Page 73 of 171
Creating Secure Code SAP ABAP Foundations
Return generic error messages that do not disclose too much information.
Use the same error message to report the same condition, regardless of the cause.
Page 74 of 171
Creating Secure Code SAP ABAP Foundations
Narration
It is important to handle exceptions properly.
First, handle specific exception types before handling exceptions generically.
Avoid returning entire stack trace trees, and always use generic error messages when dealing with users.
On Screen Text
When handling exceptions, be sure to catch specific exceptions before catching exceptions generically.
Page 75 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
You should provide as much technical information as possible in an error message so that the user has the facts they need
to diagnose and correct the error condition.
True
False
Page 76 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s now take a look at race condition vulnerabilities.
All applications perform a series of steps to accomplish a function. For example, an application that downloads a file from the
Internet and executes it might open a network socket,
request a file, read the data, save the data, and then execute or open the file. Sometimes the timing of these steps has
security implications, and the opportunity for a race condition is created.
(Unlike other application security vulnerabilities, race conditions are not caused by failing to validate untrusted input.)
Race conditions are specific to individual applications, but a common type of race condition is called Time of Check Time of
Use.
This occurs when, between the time a resource is checked and the time it is used, some condition of the resource is
changed that circumvents the initial check.
A TOCTOU race condition can cause denial of service, or it can result in escalation of privileges.
To help remediate risk from race conditions, use random resource names, apply ACLs to enforce proper privileges on
resources before use, use the resource immediately after checking it,
and check that the origin of a resource is trusted.
Click each tab to review the basics of race conditions, their impacts, and remediation techniques.
On Screen Text
Page 77 of 171
Creating Secure Code SAP ABAP Foundations
Click each tab to review the basics of race conditions, their impacts, and remediation techniques.
Vulnerability
Race conditions can occur when the timing of certain events in an application has security implications for the application.
A common race condition is called Time of Check Time of Use (TOCTOU). Between the time a resource is checked and the
time it is used, a resource condition changes and circumvents the initial check.
Impact
A TOCTOU race condition can have the following impacts:
Denial of service: An attacker can make a resource unavailable after an application checks for the resource, but before it
uses it. This can cause the application to crash or become unresponsive while it waits for that resource.
Escalation of privilege: An attacker can redirect an application to another resource if the time between check and use is
sufficient.
Remediation
Whenever possible, use a random name when creating a resource that is used by your application.
Apply access control lists (ACLs) to enforce proper privileges when accessing resources, such as temporary files, before
using them. Enforce exclusive rights on resources, ensuring that your application properly acquires locks on resources
before using them.
Use the resource immediately after checking it. Check the resource each time it is used, and minimize the amount of
time between checking the resource and using it.
Check the origin of a resource whenever possible to ensure that it was created by your application or by a trusted
source.
Page 78 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Let’s take a close look at a sample Java application with a race condition. The downloadAndOpenURL method downloads a
file from a URL, saves it locally as “tempfile,”
and then opens or executes the downloaded file. A race condition exists in this code because between saving the file locally
and opening it for execution,
the application has no guarantee that the saved file has not been modified or replaced with a malicious file.
An attacker could easily exploit this race condition to execute an escalation of privilege attack on the system. To make
matters worse, because the temporary file name is constant,
it would be trivial for an attacker to monitor for the local file and switch it with malicious content, such as malware.
Now let’s examine some practical techniques for mitigating risk from the race condition in this Java application. Keep in mind
that race conditions are specific to individual applications,
so the exact remediation may not apply to your application. However, the general principles still apply.
On Screen Text
Let’s take a close look at a sample Java application with a race condition. The downloadAndOpenURL method downloads a
file from a URL, saves it locally as “tempfile,” and then opens or executes the downloaded file.
A race condition exists in this code because between saving the file locally and opening it for execution, the application has
no guarantee that the saved file has not been modified or replaced with a malicious file.
Page 79 of 171
Creating Secure Code SAP ABAP Foundations
Page 80 of 171
Creating Secure Code SAP ABAP Foundations
Narration
To remediate our sample race condition, let’s use a random temporary file name.
The java.io.File.createTempFile method is useful for creating random temporary files that can be used by your application at
run time.
You simply pass a prefix and an extension to createTempFile, and it creates a random temporary file for your application.
Creating a random temporary file name makes it difficult for most attackers to exploit this temporary file race condition.
However, this approach might not be effective against highly skilled attackers.
To further reduce risk from this race condition, set ACLs on resources before use. Let’s see how to do this.
On Screen Text
Page 81 of 171
Creating Secure Code SAP ABAP Foundations
Page 82 of 171
Creating Secure Code SAP ABAP Foundations
Narration
To further mitigate the risk of a race condition attack, apply ACLs to resources before using them.
First, create a temporary resource, such as a temporary file.
Second, apply and verify ACLs on the resource to prevent unauthorized access to that resource.
Third, after the proper ACLs on the resource have been acquired, use the resource.
A modified version of the random temporary file creator is shown here.
After the temporary file is created, all default permissions on the temporary file are removed.
Permissions are set on the file so that only the owner is able to read, write, and execute the temporary file. The code checks
that it can set these permissions.
If not, it throws an exception that prevents the temporary file from being used.
On Screen Text
To further mitigate the risk of a race condition attack, apply ACLs to resources before using them:
Page 83 of 171
Creating Secure Code SAP ABAP Foundations
Page 84 of 171
Creating Secure Code SAP ABAP Foundations
Narration
Finally, when remediating TOCTOU vulnerabilities, always check the validity of the resource being accessed just before use,
even if a previous check has been performed or if it seems redundant.
If a validation error is detected, always exit.
On Screen Text
Page 85 of 171
Creating Secure Code SAP ABAP Foundations
Putting It Together
Narration
Let’s return to the original Java application that was susceptible to a race condition.
Instead of hardcoding a temporary file, a random secure temporary file handle is created. The file handle is checked for
validity to ensure that a secure temporary file was created.
The downloadAndOpenURL method can now download the file from the source URL, save it locally, and safely open or
execute the downloaded file.
On Screen Text
Putting It Together
Let’s now view the original Java application that had a race condition, using the new secure temporary file method:
Page 86 of 171
Creating Secure Code SAP ABAP Foundations
Page 87 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
Page 88 of 171
Creating Secure Code SAP ABAP Foundations
Module Summary
Narration
On Screen Text
Module Summary
SQL Injection
In this topic, you learned about remediating SQL injection vulnerabilities in your Java application. Remediation techniques
include using input validation, prepared statements, and type-safe parameters with stored procedures, as well as
implementing the security principles of least privilege and defense-in-depth.
You also learned about common pitfalls to avoid when protecting against SQL injection.
Integer Overflows
In this topic, you learned about remediating integer overflow vulnerabilities in your Java application. Remediation techniques
include using precondition testing, upcasting, and BigInteger objects.
You also learned about common pitfalls to avoid when protecting against integer overflows.
Page 89 of 171
Creating Secure Code SAP ABAP Foundations
Canonicalization Issues
In this topic, you learned about remediating canonicalization issues in your Java application. Remediation techniques
included canonicalizing file paths in Java and URL unescaping.
You also learned about common pitfalls to avoid when protecting against canonicalization issues.
Information Disclosure
In this topic, you learned about remediating information disclosure vulnerabilities in your Java application.
Remediation techniques include using generic error messages, proper exception handling, and encrypting sensitive data in
transit and at rest.
Race Conditions
In this topic, you learned about remediating race conditions in your Java application.
Remediation techniques include using random resource names, applying ACLs to enforce proper privileges on resources
before use, using the resource immediately after checking it, and checking that the origin of a resource is trusted.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Page 90 of 171
Creating Secure Code SAP ABAP Foundations
Narration
This module discusses ways to remediate common Web application security vulnerabilities in your Java application.
After completing this module, you will be able to identify ways to remediate vulnerabilities including direct object reference,
cross-site scripting, cross-site request forgery, URL redirection, and XPath injection.
On Screen Text
This module discusses ways to remediate common Web application security vulnerabilities in your Java application.
Module Objectives:
After completing this module, you will be able to identify ways to remediate the following vulnerabilities:
Direct object reference
Cross-site scripting (XSS)
Cross-site request forgery (CSRF)
URL redirection
XPath injection
Page 91 of 171
Creating Secure Code SAP ABAP Foundations
Narration
The first vulnerability we’ll discuss is direct object reference. Let’s review the basics of this vulnerability.
Direct object reference vulnerabilities occur when an application exposes direct references to resource objects such as files
or directories.
An attacker could take advantage of this to bypass authorization controls and directly access any resource that the
application can access, including those outside the application domain.
To reduce the risk from direct object reference vulnerabilities, restrict the application to access only those resources that are
necessary.
In addition, use a reference map, also called a lookup table, that uses an index to look up resources. This helps prevent
attackers from being able to access objects and resources directly.
Finally, validate access to resources by performing an authorization check every time a resource is accessed from an
untrusted source.
Click each tab to review the basics of direct object reference vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of direct object reference vulnerabilities, their impact, and remediation techniques.
Vulnerability
Page 92 of 171
Creating Secure Code SAP ABAP Foundations
Direct object reference vulnerabilities occur whenever an application exposes a direct reference to a resource object such as
a file or directory.
Attackers might try to bypass authorization controls and directly access sensitive resource objects.
For example:
A Web application specifies an image filename on the host server to load as a URL parameter.
https://www.yourserver.com/index.html?imagename=logo.png
An attacker could potentially bypass authorization controls by substituting a more sensitive file in place of logo.png.
https://www.yourserver.com/index.html?imagename=/etc/passwd
Impact
An attacker might gain access to any resource the application can access, including those outside the application domain.
Remediation
To remediate or reduce the risk from direct object reference vulnerabilities in your Java application, you should:
Page 93 of 171
Creating Secure Code SAP ABAP Foundations
Narration
You can use reference maps to mitigate the risk from direct object reference vulnerabilities.
Reference maps allow you to map indirect object indexes to actual direct objects. The indirect indexes are safe to expose to
users, and the direct references are kept hidden.
For example, a user requesting a resource from an application references the resource ID “0.” The application uses a
reference map to resolve the indirect reference to “filename.txt”
and then serves the file to the user.
Or if an end user provides an indirect reference, such as “2,” the reference map returns the corresponding direct reference.
However, if a user tries to reference an unknown indirect reference or an object directly that is not in the mapping, such as
during a direct object reference attack,
the mapping throws an exception to block the attack.
On Screen Text
Page 94 of 171
Creating Secure Code SAP ABAP Foundations
Narration
This code example shows one way to implement a reference map: you can store direct object references using integer-
based indirect references.
However, with integer-based reference maps, attackers can easily guess the map indexes.
Let’s learn a more secure mapping method on the next screen.
On Screen Text
The following code example shows how to implement an integer-based reference map. However, with integer-based maps,
attackers can easily guess the map indexes.
Page 95 of 171
Creating Secure Code SAP ABAP Foundations
Page 96 of 171
Creating Secure Code SAP ABAP Foundations
Narration
To make it more difficult for an attacker to guess indirect reference indexes, use random-string indexed reference maps, as
shown in this code example.
Instead of returning integers as indirect references, return random character indirect reference strings that map to direct
references.
On Screen Text
The following code example shows how to use random-string indexed reference maps. This makes it difficult for an attacker
to guess the reference indexes.
Page 97 of 171
Creating Secure Code SAP ABAP Foundations
Page 98 of 171
Creating Secure Code SAP ABAP Foundations
Narration
When developing secure Java applications, here are some common direct object reference pitfalls to avoid.
Don’t use database keys as indirect references. Although database keys appear to be indirect integer keys,
they are in fact direct references to database table rows and could be exploited by attackers.
Avoid using blacklist mappings to detect potential attacks. When creating your resource mappings, only map to authorized
resources.
Then, if an indirect reference is provided that does not appear in the resource map, reject it as a potential attack.
Another pitfall to avoid is using global reference maps that load all possible direct references into a reference map.
Whenever possible, only load authorized direct reference objects on a per user basis.
Be sure to verify authorization to referenced resources. Resource maps provide a way to mask direct resource access from
untrusted users;
however, they do not necessarily validate authorization. Therefore, whether you use resource maps or not, remember to
always verify resource authorization on each access.
On Screen Text
When developing secure Java applications, avoid the following common direct object reference pitfalls.
Page 99 of 171
Creating Secure Code SAP ABAP Foundations
Knowledge Check
Narration
On Screen Text
Knowledge Check
True or False:
Identify whether the following statement is True or False:
Database table primary keys are safe to use as indirect references.
True
False
Knowledge Check
Narration
On Screen Text
Knowledge Check
Narration
The next vulnerability we’ll discuss is cross-site scripting.
Cross-site scripting vulnerabilities occur whenever untrusted input is not properly validated, and when it is embedded in Web
output without proper encoding.
A successful attacker could subvert application logic in a variety of ways with huge impact, such as account compromise,
disclosure of credentials and information,
execution of malicious code on client systems, and elevation of privileges.
To help prevent cross-site scripting vulnerabilities, use whitelist input validation, context-sensitive encoding, and sanitization
libraries.
Click each tab to review the basics of cross-site scripting vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of XSS vulnerabilities, their impact, and remediation techniques.
Vulnerability
XSS vulnerabilities occur whenever untrusted input is not properly validated, and when it is embedded in Web output without
proper encoding. Under these conditions, an attacker embeds malicious code into Web output, which is then output by the
application and executed in the browser. Because the malicious code is delivered by a trusted site, the browser treats the
code as legitimate.
Persistent XSS - The malicious code is stored (or persists) in a data store in the vulnerable Web application or resource,
and is delivered when a user accesses the site or resource.
Non-persistent XSS - The malicious code uses a reflective aspect of the application, and the user is coerced into
performing an action, such as clicking a link, to initiate the attack.
Impact
The attacker can subvert application logic in a variety of ways, such as:
Compromise of accounts
Elevation of privileges
Remediation
To remediate or reduce the risk from XSS vulnerabilities, you should:
Use context-sensitive encoding for untrusted output before embedding it in Web responses.
Narration
The techniques you use to prevent cross-site scripting in SAP depend on the technologies you use.
For example, you may use AS ABAP with Web Dynpro or Business Server Pages on the presentation layer or AS Java with
Web Dynpro, Java Servlets, or JSPs.
Although cross-site scripting is typically a presentation layer issue, you still need to consider how you encode and escape
data at both the business and presentation layers.
Let’s see some of the cross-site scripting protection methods you can use in your own applications.
On Screen Text
Narration
SAP provides a library for encoding data for use with AS Java code. You can access it by including the tc_sec_csi.jar file.
This library provides the XSSEncoder class with methods for encoding output for different contexts. These methods are
encodeHTML, encodeXML, encodeJavaScript, encodeURL,
and encodeCSS. Always use the encoding method that matches the context and remember that some contexts might exist
with others such as JavaScript within HTML.
Note that WebDynpro for both Java and ABAP handles output encoding automatically, and you do not need to manually
encode this output.
On Screen Text
Narration
SAP provides the Output Encoding Framework to ensure that ABAP code will properly produce safe HTML output.
As of SAP NetWeaver Release 7.0 enhancement package 3, the predefined function ESCAPE is available that deprecates
the ESCAPE methods of classes CL_HTTP_UTILITY,
CL_HTTP_SERVER, and CL_HTTP_CLIENT.
See also: SAP Notes 1582867 and 1582870.
On Screen Text
Narration
For versions of NetWeaver older than SAP_BASIS 731, you can use the CL_ABAP_DYN_PRG class which provides
methods for escaping the most common contexts,
although it does not provide the same level of protection as the newer predefined function ESCAPE().
On Screen Text
Narration
With business server pages, you can use page directives to encode all dynamic output handled by the BSP compiler. The
value set for forceEncode--which can be html, url, css,
or javascript--determines the default context used for encoding all fields on the page.
Because some fields might have different contexts, you can override the context used for any particular field by specifying
the context override value.
In this example, the page uses html as the default context, but for the user_url field it uses URL encoding. After outputting
that field, BSP will revert back to the default encoding.
On Screen Text
BSP Extensions
Narration
When you use BSP extensions such as HTMLB, XHTMLB, or PHTMLB, you must specify the encoding as an attribute to the
element tag.
Because a BSP extension must encode input data internally out of the context of the parent BSP page, the page directive
does not encode the attributes of BSP extensions.
To do this, you need to set the forceEncode attribute to either ENABLED or BACKWARDS_COMPATIBLE. You should
always set this value to ENABLED.
Although both the page directive and the BSP extension both use the forceEncode attribute name, it is important to
understand that they are not the same nor do they accept the same values.
In this example, the username value is encoded by the forceEncode=html attribute of the page directive.
However, the userID value is controlled by the forceEncode=Enabled attribute of the htmlb element.
On Screen Text
BSP Extensions
HTML5
Narration
The SAP UI Development Kit for HTML5 (SAPUI5) provides cross-site scripting protection for the client-side of your web
application.
For that purpose, SAPUI5 performs input validation for all typed element properties and properly encodes output for all
controls, with the exception of HTML-control and XMLView,
which are meant to handle unencoded data.
For other situations where you must manually encode output, SAPUI5 provides the jquery.sap.encoder.js library with the
encodeHTML, encodeXML, encodeJS, encodeURL,
and encodeCSS functions.
On Screen Text
HTML5
Narration
As you defend against cross-site scripting, you need to be aware of a number of common pitfalls.
Using blacklisting to detect cross-site scripting attacks can be difficult, because there are many Web data representations to
consider.
Instead, focus on implementing proper whitelist input validation and data encoding.
Custom encoding libraries can be prone to error. Whenever possible, use libraries that have already been developed and
thoroughly tested.
Do not rely on a single line of defense for reducing risk from cross-site scripting attacks. Use defense-in-depth—implement
at least two cross-site scripting risk reduction strategies,
such as encoding and input validation.
Be sure to select the correct encoding method or context. Whether you use the OWASP ESAPI library, JSP encoding tags,
or the OWASP Java Encoding Project, for encoding to be effective,
applications need to select the correct encoding method by response context.
On Screen Text
Knowledge Check
Narration
On Screen Text
Knowledge Check
Your application embeds untrusted data as a URL link text in a Web response. The link redirects users to a Web page that
uses a significant amount of JavaScript. Which encoding context should you use?
HTML encoding
URL encoding
JavaScript encoding
Narration
Cross-site request forgery, or CSRF, attacks occur when an attacker tricks a victim into loading a Web page that contains a
malicious request,
which is able to perform a sensitive operation on behalf of the user. Because the request is sent in the context of the victim,
the Web application sees the request as legitimate and executes it.
When exploited, a cross-site request forgery vulnerability can lead to elevation of privileges in which an attacker can execute
commands in the context of the victim.
You can use several approaches to protect against cross-site request forgery vulnerabilities.
They can be loosely categorized into those that use a synchronizer token pattern and those that do not.
Click each tab to review the basics of cross-site request forgery vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of CSRF vulnerabilities, their impact, and remediation techniques.
Vulnerability
A CSRF attack occurs when an attacker tricks a victim into loading a page that contains a malicious request, which is able to
perform a sensitive operation on behalf of the user. The request is then sent in the context of the victim, and might be able to
change the state of the Web application.
For many sites, each request automatically sends the victim's credentials, such as the session cookie or authentication
credentials. Therefore, the false request cannot be distinguished from a legitimate request.
CSRF attacks are sometimes called XSRF, session riding, and one-click and zero-click attacks. A one-click attack refers to a
link that causes a malicious action to be performed when a victim clicks on it. A zero-click attack is automatically executed
when the page loads.
Impact
When exploited, a CSRF vulnerability can lead to elevation of privileges in which an attacker can execute commands in the
context of the victim.
Remediation
To reduce the risk from CSRF vulnerabilities, use the following techniques:
Narration
Most SAP technologies automatically include tokens to prevent CSRF attacks. However, there are some cases where you
must do this manually,
such as when using AJAX requests that directly communicate with a Java application.
To implement CSRF protection with AS Java, you must configure a servlet filter in the filter chain of the application.
You specify this filter in the application's web.xml file inside the <filter> element, along with a corresponding <filter-mapping>
tag, to map the filter to a request pattern.
Once you have the filter mapping in place, a client can request a token as shown here. In this example,
the client sends a non-modifying GET request with the X-CSRF-Token set to the value Fetch. This will trigger the Java filter
to respond with an X-CSRF-Token header the client can parse.
With this token, the client can now send a modifying request that is protected from CSRF attacks.
On Screen Text
Narration
Here are some common CSRF pitfalls to avoid.
Don’t perform client-side validation of synchronizer tokens. An attacker could potentially manipulate and bypass token
validation processes on the client-side, nullifying any CSRF protection.
Always perform token validation on the server-side.
Never assume that CSRF vulnerabilities only affect GET requests.
POST requests are susceptible to CSRF attacks, and can easily be triggered by methods such as those that leverage
malicious JavaScript.
And, don’t assume that multistep transactions are immune to attack. It is harder to exploit multistep transactions with CSRF,
but not impossible.
On Screen Text
Knowledge Check
Narration
On Screen Text
Knowledge Check
Match each action with the proper step in the order of the recommended synchronizer token pattern workflow.
Narration
The next vulnerability we’ll discuss is URL redirection.
Web applications often redirect users to alternative URLs, typically on the same site. An attacker might try to exploit this
feature to redirect users to malicious Websites,
where they could be tricked into exposing highly sensitive information such as account credentials, personal identifying
information, and more.
To reduce the risk from URL redirection vulnerabilities, you should avoid URL redirection if possible. If you use redirection,
alert users when they are being redirected,
validate all redirection URLs, and use mapping values for redirects and forwards to help prevent attackers from forcing
redirections to malicious sites.
Click each tab to review the basics of URL redirection vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of URL redirection vulnerabilities, their impact, and remediation techniques.
Vulnerability
URL redirection, often to a page on the same site, is commonly found on login pages that redirect users after successful
authentication. If the redirection code is vulnerable, it can be abused to send the user to an attacker-controlled site.
An attacker might leverage this technique to trick users into entering sensitive information on a malicious Website that
appears to be a trusted site. Phishers often use this type of attack.
Impact
When exploited, a URL redirection vulnerability can lead to Website forgery. A victim might not notice the redirection and
could potentially expose sensitive information, such as their credentials, to a malicious Website.
Remediation
To reduce the risk from URL redirection vulnerabilities in your applications:
Avoid using URL redirection if possible. If you use it, alert the user that redirection is occurring and provide a choice to
proceed or not.
Validate all redirection URLs to help ensure that they point to authorized destinations.
Use mapping values for redirects and forwards to help prevent attackers from forcing redirections to malicious Websites.
Narration
An easy way to mitigate the risk from URL redirection vulnerabilities is to use a reference map of valid URL redirect
destinations.
In the code shown here, a HashMap is used to load valid URL redirect destinations. An index, such as 1, 2, and 3, is
provided via the redirIndex parameter,
and the JSP file checks to see if a mapping for that index exists. If the index exists, the direct reference URL is retrieved and
the user is redirected to that URL.
Otherwise, the JSP file rejects that index as a possible attack.
On Screen Text
To mitigate the risk from URL redirection vulnerabilities, use a reference map of valid URL redirect destinations, as shown in
the following code example.
Narration
Let’s review the countermeasures against URL redirection vulnerabilities:
Avoid using redirects and forwards in your Java Web application whenever possible. If you use them, alert users whenever
they are being redirected, and allow them to proceed or not.
When calculating redirects and forwards, avoid using untrusted data in the calculation.
Use reference maps, and ensure that your application redirects and forwards only to valid URLs.
When using untrusted data as part of your redirect and forward calculations, validate destinations before redirecting or
forwarding.
On Screen Text
Avoid redirects and forwards if possible. If you use them, alert users when they are being redirected.
Knowledge Check
Narration
On Screen Text
Knowledge Check
True or False:
Avoid using redirects and forwards when possible, but if you must use them, encode the URL to help mitigate the risk from a
malicious redirection.
True
False
Narration
Next we’ll discuss XPath injection vulnerabilities, which occur when an application uses unvalidated input to construct an
XPath statement to access XML tables.
This can allow an attacker to run malicious commands in XML databases.
XPath injection is similar to, but more damaging than, SQL injection, because permissions are not enforced and the
attacker’s query can access every part of the XML document.
When exploited, XPath vulnerabilities can affect the confidentiality, authentication, authorization, and integrity of your
application.
The attacker can retrieve, manipulate, and destroy any data stored in the XML document.
To reduce the risk from XPath injection vulnerabilities, perform whitelist validation on all inputs, use parameterized XPath
expressions, use escaping or encoding routines,
and avoid disclosing too much information in XQuery error messages.
Click each tab to review the basics of XPath injection vulnerabilities, their impact, and remediation techniques.
On Screen Text
Click each tab to review the basics of XPath injection vulnerabilities, their impact, and remediation techniques.
Vulnerability
XPath injection vulnerabilities occur when an application uses unvalidated input to construct an XPath statement to access
XML tables, enabling attackers to run arbitrary commands in XML-based databases.
Impact
The attacker can retrieve, manipulate, and destroy any data stored in the XML document. This can impact the application in
the following ways:
Remediation
Perform whitelist input validation on untrusted data that might be part of an XQuery command.
Use parameterized XPath and XQuery interfaces. Avoid XQuery commands with concatenated untrusted data, and
use parameterized XPath expressions.
Use escaping or encoding routines. If parameters cannot be used, use escaping or encoding routines to neutralize
special characters that might enable an attacker to perform an XPath injection attack.
Do not echo XQuery errors. Avoid disclosing too much information to an attacker by returning generic error messages
to the client.
Narration
To reduce risk from XPath injection vulnerabilities, use XPath expressions with type-safe parameters, if the XML framework
used in your Java application supports it.
Type-safe parameters indicate to the XPath query engine that the data bound to those parameters should not be executed.
This greatly reduces the risk that attackers could elevate their privileges during XPath injection attacks.
The code shown demonstrates how to use type-safe parameters using the Nux Java XML toolkit. This is veL toolkit. This is
very similar to prepared statements,
the technique used to mitigate risk from SQL injection. Data placeholders are inserted into XPath queries, or XQuery, and
then untrusted data is mapped to those placeholders as parameters.
On Screen Text
To reduce risk from XPath injection vulnerabilities, use XPath expressions with type-safe parameters if the XML framework
used in your Java application supports it.
Knowledge Check
Narration
On Screen Text
Knowledge Check
Permissions are not enforced, so an attacker’s query can access every part of the XML document.
Whitelist input validation can help protect against SQL injection, but not against XML injection.
Escaping can help protect against SQL injection, but not against XPath injection.
Module Summary
Narration
On Screen Text
Module Summary
You also learned about common pitfalls to avoid when protecting against direct object reference vulnerabilities.
You also learned about common pitfalls to avoid when protecting against XSS.
In this topic, you learned about remediating CSRF vulnerabilities in your Java application. Techniques included using
synchronizer and non-synchronizer token approaches.
You also learned about common pitfalls when protecting against CSRF and how to avoid them.
URL Redirection
In this topic, you learned about remediating URL redirection vulnerabilities in your Java application. Techniques included
avoiding redirects, not calculating redirects and forwards with untrusted data, using mapping values, and validating
calculated destinations of redirects and forwards.
XPath Injection
In this topic, you learned about remediating XPath injection vulnerabilities in your Java application. Techniques included
validating input, using parameterized XPath expressions, using escaping or encoding routines, and not disclosing too much
information in XQuery error messages.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Narration
This module discusses how to use cryptography for data protection in AS Java applications.
After completing this module, you will be able to:
Identify the tools and services necessary to enable data encryption in your AS Java applications.
Understand how to establish and use secure encryption keys.
Be able to encrypt data using the Secure Storage API.
On Screen Text
This module discusses how to use cryptography for data protection in AS Java applications. This module will focus
specifically on data encryption.
Module Objectives:
After completing this module, you will be able to identify the tools and services necessary to enable data encryption in your
AS Java applications, including:
Narration
When you work with encryption on AS Java, you must have the SAP Java Cryptographic Toolkit. Due to export restrictions,
this toolkit is not installed by default.
Once you install the toolkit that corresponds to your J2EE version, you’ll have access to the cryptographic libraries
necessary for digital signatures, TLS, and data encryption.
On Screen Text
To enable encryption on AS Java, you need the SAP Java Cryptographic Toolkit. Once you install the toolkit that
corresponds to your J2EE version, you’ll have access to the cryptographic libraries necessary for digital signatures, TLS,
and data encryption.
Narration
Let’s look at how Java works with the Secure Storage service.
When your J2EE application registers with the Secure Storage service, the service designates a context area in the
database specifically for that application.
At that time, the Keystore service will generate a unique secret key for your application and store that key on the server’s file
system in a file named SecStore.key.
Once the context has been established and your application has obtained a secret key, you can encrypt data from your Java
code.
The classes and interfaces for working with Secure Storage are located in these packages.
On Screen Text
Encrypted Storage
Narration
When you encrypt data, you have two options for storage: centralized or decentralized.
With centralized storage, your application obtains the secret key from the Keystore service and then uses the Secure
Storage API to encrypt the data.
The Secure Storage service will then store your encrypted data in the application’s context in the database and assign an
object ID.
Later you can use that object ID and the secret key to retrieve and decrypt the data from the database.
On Screen Text
Encrypted Storage
Narration
The second option is decentralized storage, where you store your data in an external database. In this situation, you need to
maintain and manage a storage area for the encrypted data,
although you would still use the Secure Storage and Keystore services to handle encryption and manage secret keys.
Like centralized storage, with decentralized storage your application obtains the secret key from the Keystore service and
then uses the Secure Storage API to encrypt the data.
However, with decentralized storage, the Secure Storage service returns the encrypted data that you then store in the main
database or in an external database.
The advantage of decentralized storage is that while it requires you to manually manage data storage, it also gives you
flexibility in how and where you store sensitive data.
On Screen Text
Narration
The Key Storage allows management of certificates and credentials on the server, and generation of keys and certificates.
These keys and certificates can be used for encryption, identification, and verification.
The Key Storage entries are stored in a distributed database and can be assigned particular access rights. The service is
compatible with the Java Cryptography Architecture.
The Key Storage management functions of the SAP NetWeaver Administrator allow management of AS Java certificates
and keys.
You can access the server credentials from Java via multiple virtual key stores called Keystore views.
The Key Storage functions of the SAP NetWeaver Administrator are supported by the AS Java Keystore service and
interface.
The AS Java Keystore service represents an enhanced implementation of the java.security.Keystore interface.
On Screen Text
Manage credentials
Knowledge Check
Narration
On Screen Text
Knowledge Check
Module Summary
Narration
On Screen Text
Module Summary
The Secure Storage and the difference between centralized and decentralized storage.
The Key Storage service and how it works in conjunction with Secure Storage to encrypt sensitive data.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Narration
This module discusses best practices for conducting security code analysis and code reviews for your SAP application.
After completing this module, you will be able to identify the differences between static and binary code analysis and manual
review of your Java and ABAP code.
You will also be able to identify the benefits and limitations of each security code review method. Finally, you will be able to
identify the steps required to perform a well-structured code review.
On Screen Text
This module discusses best practices for conducting security code analysis and code reviews for your SAP application.
Module Objectives:
After completing this module, you will be able to:
Identify the differences between static and binary code analysis and manual review of your Java and ABAP code.
Identify the benefits and limitations of each security code review method.
Identify the steps required to perform a well-structured code review.
Narration
Let’s begin with an overview of code analysis and code review.
Code analysis is performed with software tools that inspect compiled and non-compiled source code for known defects.
For example, code analysis tools can be used to detect instances of known SQL injection patterns in your Java code.
Code analysis can be categorized into static code analysis and binary analysis, both of which will be discussed in depth.
Code review is the manual inspection of application source code by a security analyst.
Both code analysis and code review are important components of any secure application development strategy.
They allow you to detect and correct vulnerabilities in legacy applications, and to find vulnerabilities in current applications
early in the development lifecycle, when the cost of fixing them is low.
On Screen Text
Code analysis is performed with software tools that inspect compiled and non-compiled application code for known
defects.
Code review is the manual inspection of application source code for known defects.
Narration
Let’s focus our attention on static and binary code analysis. To understand the difference between the two, consider how
SAP handles ABAP and Java code.
With ABAP, SAP stores your source code in the database.
When first activated—or executed—the ABAP system compiles this source into a byte code called the ABAP load,
and saves this back to the database for direct execution. The compilation process is handled automatically in the
background,
and produces code that is optimized for each server running the code.
With Java, you compile and link your source code into a binary and machine-independent class file that a Java VM can
execute.
This binary file is what you will distribute to each system that will execute the code.
For both ABAP and Java you can use static code analysis tools to identify potential security issues.
For Java, you can also make use of binary analysis tools.
Static and binary analysis tools each have benefits and weaknesses, which we’ll discuss next.
On Screen Text
Understanding Code Analysis
Narration
Let’s take a look at some of the benefits and limitations of static analysis tools.
Compared to manual code reviewers, static analysis tools can scale fairly easily to analyze large amounts of code, and they
are objective and unbiased.
Compared to binary analysis tools, static analysis tool technology is generally more mature, and tends to find more
vulnerabilities.
In addition, issues identified by static analysis tools are easier to debug because they work with human-readable source
code instead of compiled code.
Static analysis tools do have limitations, though. They are language specific, so organizations that use many programming
languages might require many static analysis tools.
In addition, they might produce false positives by flagging items that are not vulnerabilities, and produce false negatives by
missing actual vulnerabilities,
which can degrade confidence in these tools. Finally, static analysis tools can only find implementation flaws, revealing
specific coding patterns that lead to vulnerabilities.
They cannot necessarily detect flaws related to the business logic of the application.
For example, a static analysis tool might not detect if an application incorrectly assigns excessive rights to a user,
or if it contains a bug in which certain operations are performed out of order, contrary to the intended design.
On Screen Text
Let’s take a look at some of the benefits and limitations of static analysis tools.
PROS:
Scales easily
Objective
Mature technology
CONS:
Narration
Let’s now take a look at some pros and cons of binary analysis tools.
Like static analysis tools, binary analysis tools can scale to review large amounts of code, and are more objective and
unbiased than human reviewers.
Binary analysis tools are often more accurate than static analysis tools because they operate on the actual code that gets
executed. Static analysis tools operate on source code,
which might get optimized and rearranged by compilers.
However, binary analysis tools do have limitations. They are far less mature compared to static analysis tools, so the breadth
of vulnerabilities that they can detect is limited.
In addition, the bugs identified by binary analysis tools are difficult to fix because developers have to interpret compiled code.
Finally, binary analysis tools suffer from some of the same limitations as static analysis tools. They are language-specific,
they produce false positives and false negatives;
and they can only detect implementation flaws.
On Screen Text
Let’s now take a look at some pros and cons of binary analysis tools.
PROS:
Scales easily
Objective
More accurate
CONS:
Less mature
Narration
Let’s turn our attention back to the application compilation lifecycle to understand code review.
Recall that applications are first expressed as source code,
and that source code is processed by a compiler and linker to produce binary code.
Code review, like static code analysis tools, utilizes human-readable source code to detect implementation flaws.
However, the analysis is performed by a human and not a software tool.
On Screen Text
Narration
Manual code review has benefits and limitations of its own.
Manual code reviews have the distinct advantage over code analysis of generally producing fewer false negatives and false
positives.
And, human code reviewers can find not only implementation flaws, but also flaws in design and in business logic.
Although manual code review provides some great benefits, it does have certain limitations. Manual code review is very time
consuming and does not scale well.
Reviewers can become fatigued from examining large amounts of code, which diminishes their ability to accurately identify
vulnerabilities.
In addition, different reviewers have different areas of expertise, so different vulnerabilities might be overlooked, depending
on who reviews the code.
On Screen Text
PROS:
CONS:
Knowledge Check
Narration
On Screen Text
Knowledge Check
Binary analysis tools are not susceptible to false positives because they analyze the actual compiled binaries.
True
False
Narration
To conduct a well-structured security code review, you need to identify your objectives, perform a preliminary scan, review
your code for common security issues,
and review your code for security issues unique to your application’s architecture. Let’s discuss each step in detail.
In Step 1, set objectives and constraints for your code review.
Do not spend too much time on this, but do not begin reviewing a large body of code without knowing what you’re looking
for. You might get overwhelmed by the code,
and this can decrease your chances of identifying security issues.
In Step 2, scan for initial security issues and for hot spots where additional issues are likely to be found later. You can
perform an automatic scan using a static analysis tool,
and/or a manual scan, depending on your time limits and review objectives. The goal is to find the areas that require further
analysis in Step 3.
In Step 3, manually review the code to look for common security vulnerabilities that are not unique to your application's
architecture.
Trace those paths through the code that are most likely to reveal security issues. You can use a question-driven approach,
along with techniques such as control flow and dataflow analysis.
In Step 4, return to your list of code review objectives and examine anything that has not yet been addressed.
Use this final code-review pass to verify the security features that are unique to your application architecture. A question-
driven approach produces the best results.
Click each step to learn more about the security code review process.
On Screen Text
To conduct a well-structured security code review, you need to follow four steps:
Click each step to learn more about the security code review process.
• Make sure that all untrusted input to the component is passed to a validation routine before it is used.
• Check error handling to make sure that exceptions are caught consistently and close to their source.
• Check calculations in which results are used for memory allocation or buffer access for numeric overflow or underflow.
• Automatic scan: Use a static analysis tool to perform an automatic scan of your code to find security issues that could
be missed during a manual review. However, an automated scan can result in a large number of false positives, and
does not find every security issue that you might find in a manual review.
• Manual scan: Complete a manual scan of your code to better understand the code and to recognize patterns that assist
you in Step 3. This should be a quick scan that takes no more than 10 percent of your total code-review time.
Narration
On Screen Text
Click each step to learn more about the security code review process.
• Use a question-driven approach, along with control flow and dataflow analysis.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this
material.
Narration
Here are some tips to help you perform security code reviews:
Instead of waiting until the end of a project to review everything at once, review your code each time it changes significantly.
This allows you to focus on what has changed instead of trying to identify all of the security issues at once.
When possible, use peer review to improve code reviews. This brings a fresh pair of eyes to help identify potential issues
that were overlooked.
Set a time limit for your review. It’s best to conduct many short reviews on small pieces of code, for example at check-in
time.
Reviewing code is detailed, tiring, time-consuming work, and it’s easy to make mistakes after many hours.
Without a time limit, you might also become too deeply engrossed in the details of a particular implementation. A time limit
will help you move on to find high-value issues elsewhere.
Understand the external components that your code depends on. Look for known vulnerabilities in the version of the
components you’re using.
Often these external components can quietly introduce vulnerabilities into your code.
Finally, before you conduct your code review, determine the patterns of bad code that you want to eliminate. You can then
review your code with a clear idea of what you are looking for.
On Screen Text
As you perform security code reviews, remember these general code-review tips:
Narration
When performing a manual code review, you don’t need to know every possible way that a vulnerability can manifest.
For example, you don’t need to memorize every possible manifestation of an SQL injection vulnerability in Java applications.
Instead, you can look for general coding patterns in your Java application that can lead to various vulnerabilities.
Click each tab to learn more about bad coding patterns related to various vulnerabilities.
On Screen Text
For manual code reviews, you can simplify your job and improve overall accuracy by looking for general coding patterns that
commonly lead to vulnerabilities.
Click each tab to learn more about bad coding patterns related to various vulnerabilities.
SQL Injection
Look for coding patterns where untrusted input data is used to construct and execute dynamic SQL statements.
Integer Overflows
Look for coding patterns where untrusted input data is used during arithmetic integral operations, such as financial
transactions.
Information Disclosure
Information disclosure vulnerabilities vary from application to application. However, you can generally look for instances
where too much information is disclosed to users:
• Areas where there are connections to the application and sensitive data, such as credentials, are transmitted.
• Areas where cryptography is used. In particular, look for coding patterns that use weak cryptographic algorithms like
DES and MD5.
Narration
On Screen Text
For manual code reviews, you can simplify your job and improve overall accuracy by looking for general coding patterns that
commonly lead to vulnerabilities.
Click each tab to learn more about bad coding patterns related to various vulnerabilities.
Race Conditions
Look for coding patterns where external critical resources, such as files, are used by – but are not in direct control of -- your
application. For example, your Java application may depend on a critical file on the file system. Because your application
does not control the file system, an attacker may be able to modify that file between the time that your application checked
the file and actually used the file.
Cross-site Scripting
For reflected XSS, look for coding patterns where untrusted input data is read by Web applications and embedded in Web
responses without prior input validation or data encoding.
For persistent XSS, look for coding patterns where Web applications store untrusted input data in persistent storage
mediums, such as databases and files, and where that data is later embedded in Web responses without prior input
validation or data encoding.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Narration
On Screen Text
Click each tab to learn more about bad coding patterns related to various vulnerabilities.
URL Redirection
Look for coding patterns where redirection URLs are specified in user-controlled parameters such as, but not limited to,
query string parameters, input fields, or even hidden HTML input fields.
XPath Injection
Look for coding patterns where untrusted input is used to construct XPath queries used to search and return data from XML
files.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Narration
OWASP has an initiative called the OWASP Code Review Project, which has produced a guide that documents how to
review code for a large number of vulnerability types.
It includes many Java code examples.
On Screen Text
The OWASP Code Review Project documents techniques for reviewing code, with most code examples in Java.
Narration
A number of free code analysis tools are available to help you analyze your Java code.
FindBugs is a University of Maryland program used to perform Java static source code analysis.
LAPSE+ is OWASP’s static source code analysis tool aimed at detecting vulnerabilities in Java Enterprise Edition
applications and can be integrated into the Eclipse IDE.
VisualCodeGrepper is an automated code security review tool for Java and other application languages, such as C++, C#,
and Visual Basic.
Click each tool name for more information.
On Screen Text
For ABAP code, the best solution for automated source code review is to use SAP’s NetWeaver Application Server Add-On
for Code Vulnerability Analysis.
For Java, there are many tools available, including the following free code analysis tools:
FindBugs:
A University of Maryland program used to perform Java static source code analysis.
OWASP LAPSE+
A static source code analysis tool used to detect vulnerabilities in Java Enterprise Edition (Java EE) applications, and
can be integrated into the Eclipse IDE.
VisualCodeGrepper
An automated code security review tool for Java and other application languages, such as C++, C#, and Visual Basic.
Knowledge Check
Narration
On Screen Text
Knowledge Check
Which of the following is a best practice when conducting a security code review?
Ensure that the developer who wrote the code is the only expert who reviews the code.
Avoid biasing reviewers with predetermined objectives for the security code review.
Perform security code reviews over long continuous sessions.
Look for vulnerabilities that might have been unknowingly introduced by external components used by your application.
Narration
Since code analysis offers the benefits of scalability, objectivity, and immunity to human fatigue and bias,
you might be tempted to replace code review entirely with code analysis.
However, aside from the limitations of each that we have already discussed,
there is another important reason why code analysis cannot replace code review, or vice versa.
It concerns intra-method versus inter-method vulnerabilities.
Security vulnerabilities can manifest in application code on an intra-method, or per-method or function, basis.
That is, vulnerabilities can be isolated to the scope of an individual method or function.
Code analysis tools are very effective at finding these types of vulnerabilities.
Code review is not as effective as code analysis in this case.
Another way that security vulnerabilities can manifest in application code is on an inter-method or function basis.
These more complicated vulnerabilities are created only when data traverses certain code paths.
These types of vulnerabilities are more easily found by expert human code reviewers than by current code analysis tools.
Both code analysis and code review are essential to address these different vulnerability categories.
On Screen Text
Narration
Let’s look at the common pitfalls associated with code analysis and code review and how to avoid them.
Don’t use code analysis to replace code review, or vice versa.
Using one in place of the other creates gaps in your overall security strategy that can introduce security vulnerabilities into
production code.
As a best practice, incorporate both code analysis and code review as part of your overall strategy.
In addition, don’t use code analysis or code review to replace secure coding best practices. Although code analysis and
review are effective in identifying many types of security vulnerabilities,
neither can detect all vulnerabilities in code. Incorporate secure development practices along with your code analysis and
review.
On Screen Text
Avoid the following common pitfalls associated with code analysis and code review:
Using code analysis and review to replace secure coding best practices
Code analysis and review cannot find all security vulnerabilities.
Code analysis and review should be part of your overall secure application development strategy.
Knowledge Check
Narration
On Screen Text
Knowledge Check
True
False
Module Summary
Narration
On Screen Text
Module Summary
In this topic, you learned about intra-method vs. inter-method vulnerabilities, as well as common code analysis and code
review pitfalls.
Note - This slide does not contain audio. Please continue to the next section once you have finished reviewing this material.
Thank you
sss
Narration
On Screen Text
Thank You
This concludes the Creating Secure Code SAP ABAP Foundations course. Please close this window to finish the course.
Thank you.