Vous êtes sur la page 1sur 26

2016-02-16

Securing Java Applications with XML Hardener


Content

1 Securing Java Applications with XML Hardener. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


1.1 Supported Parsers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Using XML Hardener in SAP NetWeaver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5


2.1 XML Hardener Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Creating Dependencies to the XML Hardener Extension Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2 Using XML Hardener in SAP NetWeaver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Securing parsers, schema validation and transformer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
Securing a DOM Parser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Securing a SAX Parser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13
Securing XML Schema Validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Securing a Transformer Factory. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4 Enabling XML Hardener for Application Server Java. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.5 External Configuration Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.6 Learning Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Securing Java Applications with XML Hardener


2 2016 SAP SE or an SAP affiliate company. All rights reserved. Content
1 Securing Java Applications with XML
Hardener

The XML specification allows a lot of freedom and flexibility in creating XML documents. They can be created and
modified in a way that the XML parsers can be abused for attacking an application or even the server it is running
on.

An XML attack is a type of system security attack that might lead to:

Denial of Service (DoS) by causing high consumption of resources (e.g. memory, CPU usage) on the server
for a long period of time done deliberately and with the purpose to block other services from execution.
Disclosure of Data by retrieving data, which normally would not be accessible.
Remote System Access by opening connections to remote systems, possibly also from a server behind the
DMZ (Demilitarized Zone where the XML parser might be running).
Breaking the application logic.

These attacks are often referred to as XML External Entity (XXE) attacks, XML bombs or XML injection

XML parsers do not provide prevention from such attacks by default. It is the responsibility of the application
developers to configure the parser to use only that functionality which is necessary and forbid the potentially
dangerous one.

For the purpose of preventing XXE attacks or XML bombs in SAP Java applications, you can use the new
component developed - XML Hardener. It acts as a wrapper around the standard parsers. The component
intercepts and overrides, where necessary, calls to DocumentBuilderFactory/SAXParserFactory/
TransformerFactory/SchemaFactory.

Note
XML Hardener is not an XML parser itself.

The other main purpose of the tool is to be easy for adoption and to imply as least as possible code changes in
applications that will use it. Therefore, only one code line and import of a class is enough to secure your parser.

Securing Java Applications with XML Hardener


Securing Java Applications with XML Hardener 2016 SAP SE or an SAP affiliate company. All rights reserved. 3
1.1 Supported Parsers

Supported Parsers

There are various types of XML parsers and XML Hardener supports the following of the most commonly used
ones:

DOM and SAX parsing when using Xerces-J, SAPXMLToolkit and Crimson
XSLT transformations when using Xerces-J, SAPXMLToolkit
Schema validation for Xerces-J

Securing Java Applications with XML Hardener


4 2016 SAP SE or an SAP affiliate company. All rights reserved. Securing Java Applications with XML Hardener
2 Using XML Hardener in SAP NetWeaver

2.1 XML Hardener Components

XML Hardener adopters in SAP NetWeaver could be applications, services or libraries.

XML Hardener consists of two components in SAP NetWeaver. These are the XML Hardener library extension,
which is the primary library and XML Hardener Service. The XML Hardener library extension is wrapping the
release independent XML Hardener core functionality. There is some SAP NetWeaver specific logic added in it.

Figure 1: XML Hardener Components

To use the XML Hardener, you have to create a dependency to the SAP NetWeaver XML Hardener extension
library.

For more information on how to do that, see: Creating Dependencies to the XML Hardener Extension Library
[page 6]

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 5
2.1.1 Creating Dependencies to the XML Hardener Extension
Library

Context

Depending on the location where your application is stored, you have the following options for creating
dependencies to the XML Hardener extension library.

Procedure

1. When the application is stored in SAP NetWeaver Development Infrastructure, you need to:
2. Create a build-time dependency from the application to the API public part and
3. Create a runtime dependency to the whole xmlhardener development component from ENGINEAPI.SCA

Example
You have a Java Enterprise Application (EAR), which contains one or more modules, one of which is an
Enterprise JavaBeans (EJB) module, which uses XML parsing.

If you want to adopt the XML Hardener you have to:

Add a build-time dependency from the EJB development component to the API public part xmlhardener
development component, because in the EJB development component you will use the Java code from the
XML Hardener
Add a runtime dependency from your EAR development component to the whole xmlhardener
development component, because your application will need the classes of XML Hardener loaded at
runtime on the server while executing the actual parsing.

2.2 Using XML Hardener in SAP NetWeaver

To start working with XML Hardener in SAP NetWeaver, you need to have information about its library parts
location and the parsers supported by the tool.

XML Hardener Components Location

The library part of XML Hardener is part of ENGINEAPI.SCA and the service part is located in SERVERCORE.SCA in
SAP NetWeaver releases 7.1x and higher. The library and the service parts of the XML Hardener are part of
SAPJEECOR.SCA in SAP NetWeaver 7.0x releases.

Securing Java Applications with XML Hardener


6 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
Note
SAP XML Toolkit is deprecated as of SAP NetWeaver 7.2 and higher releases but is still supported even in SAP
NetWeaver 7.5.

2.3 Securing parsers, schema validation and transformer

XML Hardener allows you to secure your parser, schema validation and transformer.

All securexxx() methods are available at com.sap.security.hardener.nw.facade.HardenerFacade from the SAP


NetWeaver XML Hardener extension library.

Note
DTD declaration is not allowed either in the XML or in external DTD document, e.g.http://apache.org/xml/
features/disallow-doctype-decl feature is set to true.

1. Securing a DOM Parser [page 7]


2. Securing a SAX Parser [page 13]
3. Securing XML Schema Validation [page 17]
4. Securing a Transformer Factory [page 19]

2.3.1 Securing a DOM Parser

Securing a DOM Parser

If your Java application is using DocumentBuilderFactory and DocumentBuilder classes for XML parsing,
you can get a secured DocumentBuilderFactory implementation by calling a method from the XML Hardener
Facade right before the XML Parser is instantiated.

The returned implementation HardenedDocumentBuilderFactory overrides the methods from


DocumentBuilderFactory and secures the XML parser without further interaction from the application.

However, if there are more specific needs for a particular application, there are some additional features and
attributes not available in the standard DocumentBuilderFactory and provided by
HardenedDocumentBuilderFactory. They allow changes to the behavior of the XML Hardener.

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 7
To secure your DOM parser, proceed as follows:

1. Import the following code to the place where your application code uses XML parsing:

import com.sap.security.hardener.nw.facade.HardenerFacade;

2. Locate code lines within the application, which instantiate the DocumentBuilderFactory. This would be a
line similar to this:

Sample Code

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

3. Add one more line that will secure your DocumentBuilderFactory

dbFactory = HardenerFacade.secureDocumentBuilderFactory(dbFactory);

Upon calling the secureDocumentBuilderFactory method, the XML Hardener immediately secures the XML
parser. As a result, the application will start to use the new secured HardenedDocumentBuilderFactory class.

The method with parameters DocumentBuilderFactory and String namespace is used for external
configuration file. The second parameter identifies which exactly configuration file to be used.

public static DocumentBuilderFactory secureDocumentBuilderFactory(final


DocumentBuilderFactory factory, final String callerNamespace)
throws ParserConfigurationException

Note
Call as less as possible the secureDocumentBuilderFactory method because there are some resource
consuming operations, which might affect the performance of your application. Try to reuse the
DocumentBuilderFactory instance across classes instead.

Immediate Effects of Calling the secureDocumentBuilderFactory() method

The parser will be set up to prevent XML bombs


The parser will set up an EntityResolver, which throws an exception if any external entity is used within a
DTD
Validation will be disabled
Changing any settings (attributes, features or methods) of DocumentBuilderFactory is no longer possible
An application may not alter any settings and an exception will be thrown if the application tries this.

New Features Provided by HardenedDocumentBuilderFactory

Depending on the application need, it may be sufficient simply to call secureDocumentBuilderFactory


method from the HardenedDocumentBuilderFactoryFacade class. This way, the parser will be immediately
secured and no more changes are required.

Securing Java Applications with XML Hardener


8 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
However, it may be necessary for the application to utilize the new set of features provided by the
HardenedDocumentBuilderFactory.

Possible interactions with the class


General

HardenerConstants.FACTORYACCESS_FEATURE - If the value of the feature is set to true, the application


will be granted full access to the DocumentBuilderFactory, and the normal restrictions will not be
applicable. However, none of the initial settings during the securing are reverted
HardenerConstants.FACTORY_RESET_PARSER - If the value of the feature is set to true, the parser will be
reset to the state right after securing it.
HardenerConstants.REMOVE_EXT_ENTITIES_FEATURE - any External Entity will be replaced with a
blank entity instead of causing an exception

White List

HardenerConstants.USE_PSE_WHITELIST_FEATURE - Set the white list to be used by EntityResolver


during DocumentBuilder instantiation

Mapper List

HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE - Set the mapper list to be used by


EntityResolver during DocumentBuilder instantiation

Learning Mode

HardenerConstants.USE_PSE_LEARNINGLIST_FEATURE - activates learning mode

Take Over Full Control of the XML parser


After securing DocumentBuilderFactory, you can still change some features and attributes. Changing a single
feature or attribute may result in automatically changing several others. Features and attributes, which are
considered related to the security, can only be changed with your explicit consent and awareness, and after
changing the value of the XML Hardener feature HardenerConstants.FACTORYACCESS_FEATURE.

Example

Sample Code

dbFactory.setFeature(HardenerConstants.FACTORYACCESS_FEATURE, true);
// change other security related features and attributes

Reset Changes Done During Securing DocumentBuilderFactory


In case you want to undo the changes done to the XML parser after securing the DocumentBuilderFactory,
execute the following code line:

dbFactory.setFeature (HardenerConstants.FACTORY_RESET_PARSER, true);

Identifying External Entities


External parsed entities refer to data that an XML processor has to parse. They are useful for creating common
references that you can share between multiple documents. Any changes that are made to external entities are
automatically updated in the documents they are referenced to.

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 9
There are two types of external entities: private and public.

Private external entities are identified by the keyword SYSTEM, and are intended for use by a single author or
group of authors.
Public external entities are identified by the keyword PUBLIC and are intended for broad use.

<!ENTITY name SYSTEM "URI">


<!ENTITY name PUBLIC "public_ID" "URI">

The following entity is a private one and is identified by its name "c" and the URL to the entity definition, e.g. its
system id http://www.xmlwriter.net/copyright.xml.

Sample Code

<!ENTITY c SYSTEM "http://www.xmlwriter.net/copyright.xml">

The following entity is a public one and is identified by its name "c", its public id -//W3C//TEXT
copyright//EN and the URL to the entity's definition, e.g. its system id http://www.w3.org/xmlspec/
copyright.xml.

Sample Code

<!ENTITY c PUBLIC "-//W3C//TEXT copyright//EN" "http://www.w3.org/xmlspec/


copyright.xml">

In XML Hardener there are two classes used for entities identifiers depending on the EntityResolver used.

Sample Code

public EREntityIdentifier(final String name, final String publicId, final String


baseURI, final String systemId)

or for DOM Level 2 (http://www.w3.org/TR/2004/PR-DOM-Level-3-LS-20040205/load-save.html).

Sample Code

public LSResourceIdentifier(final String type, final String namespaceURI, final


String publicId, final String systemId, final String baseURI)

White Listing

White lists are used when you want to specify trusted URIs for external entities within the DTD in your application.
All URIs added in the white list will be treated as secure and access to them will be allowed. It is up to you to define
this list in your application.

By default, the feature HardenerConstants.USE_PSE_WHITELIST_FEATURE is set to true so there is no need


to set it before the configuration of your white list.

White list can be configured from a configuration file or programmatically as in the following example:

Securing Java Applications with XML Hardener


10 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
Sample Code

Set<EREntityIdentifier> whitelist = new HashSet<EREntityIdentifier>();


EREntityIdentifier entityIdentifier = new EREntityIdentifier("entityName", null,
"http://www.xyz.com/example.xml", "external.dtd");
whiteList.add(entityIdentifier);
dbFactory.setAttribute(HardenerConstants.PSE_WHITELIST_PROPERTY, whiteList);

Entity Mapping
In your application, you can specify a set of URIs, which are accepted within a DTD as external entities but will be
mapped to a different URIs using a mapper list. For example, if the incoming URI http://www.xyz.com/my.dtd
is mapped to C:/dtd/xyz_com_my.dtd, your application will accept the incoming DTD http://www.xyz.com/
my.dtd and will replace it with the local version to which it is mapped C:/dtd/xyz_com_my.dtd. You can also
add a list of Entity Resolvers to each entity mapping entry.

By default, the feature HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE is set to false so, you


have to set it to true before start configuring your mapper list.

Mapper list can be configured from a configuration file or programmatically as in the following example:

Sample Code

dbFactory.setFeature(HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE, true);
.....
Map<EREntityIdentifier, EREntityIdentifier> replacementMap = new
HashMap<EREntityIdentifier, EREntityIdentifier>();
EREntityIdentifier externalEntityIdentifier = new
EREntityIdentifier("entityName", null, "http://www.xyz.com/my.dtd ", "my.dtd");
EREntityIdentifier localEntityIdentifier = new EREntityIdentifier("entityName",
null, "C:/dtd/xyz_com_my.dtd" , "xyz_com_my.dtd");
replacementMap.put(externalEntityIdentifier, localEntityIdentifier);
dbFactory.setAttribute(HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE,
replacementMap);

Entity Resolvers
Entity Resolvers are basically callbacks. If the XML parser finds an external entity during parsing of the document,
the parser will check if an Entity Resolver has been specified and if so call it. The primary purpose of these Entity
Resolvers is to make the application more robust against failures. For example, the external entity could point to a
network URI - which will not work if the network is not available. However, the application should still process this
document. Or the URI is a relative path which might also not work for the executing application, and again should
not cause a failure.

All XML parsers are using entity resolvers to find external entities like DTDs or
XSDs.HardenedDocumentBuilderFactory supports different entity resolvers. It depends on the use case
which one to be used.

Note
If the Entity Resolver returns a "null" string, this is interpreted as "valid" by the parser and will allow the URI to
be used.

Entity Resolvers from Parsers

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 11
The default entity resolvers do not check the external entities. The resolvers try to resolve the location of the
entities directly. It means the parser will try to access everything entered as value using the URL class (all its
supported features and protocols).
Default Entity Resolver from XML Hardener
There are two default implementations for both interfaces org.xml.sax.EntityResolver and
org.xml.sax.ext.EntityResolver2 in XML Hardener, correspondingly HardenedEntityResolver and
HardenedEntityResolver2.

Figure 2: Hardened Entity Resolver diagram

Note
org.xml.sax.EntityResolver resolves entities only by their public and system ids.

Failed Parsing due to External Entities


There are different ways for the application to react to failed parsing due to External Entities. One option is to
throw an exception and stop if the cause was an untrusted (unspecified) URI, or to add the URI to a list for a later
evaluation by administrator.

Parent topic: Securing parsers, schema validation and transformer [page 7]

Next: Securing a SAX Parser [page 13]

Securing Java Applications with XML Hardener


12 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
2.3.2 Securing a SAX Parser

Securing a SAX Parser

Securing SAXParserFactory is similar to DocumentBuilderFactory. You can get a secured


SAXParserFactory by calling a method from the XML Hardener Facade right before the XML Parser is
instantiated. The returned implementation HardenedSAXParserFactory overrides the methods from
SAXParserFactory and secures the XML parser without further interaction from the application.

To secure your SAX parser, proceed as follows:

1. Import the following code to the place where your application code uses XML parsing:

import com.sap.security.hardener.nw.facade.HardenerFacade;

2. Locate code lines within the application, which instantiate the SAXParserFactory. This would be a line
similar to this:

Sample Code

SAXParserFactory saxFactory = SAXParserFactory.newInstance();

3. Add one more line that will secure your SAXParserFactory

saxFactory = HardenerFacade.secureSAXParserFactory(saxFactory);

Upon calling the secureSAXParserFactory method, the XML Hardener immediately secures the XML parser.
Further on, the application will use the new secured HardenedSAXParserFactory class.

The method with parameters SAXParserFactory and String namespace is used for external configuration file.
The second parameter identifies which exactly configuration file to be used.

public static SAXParserFactory secureSAXParserFactory(final SAXParserFactory


factory, final String callerNamespace)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException

Note
Call as less as possible the secureSAXParserFactory method because there are some resource consuming
operations which might affect the performance of your application. Try to reuse the SAXParserFactory
instance across classes instead.

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 13
New Features Provided by HardenedSAXParserFactoryFacade

Depending on the application need, it may be sufficient simply to call secureSAXParserFactory method from
the HardenedSAXParserFactoryFacade class. This way, the parser will be immediately secured and no more
changes are required.

However, it may be necessary for the application to utilize the new set of features provided by the
HardenedSAXParserFactoryFacade.

Possible interactions with the class


General

HardenerConstants.FACTORYACCESS_FEATURE - If the value of the feature is set to true, the application


will be granted full access to the SAXParserFactory, and the normal restrictions will not be applicable.
However, none of the initial settings during the securing are reverted
HardenerConstants.FACTORY_RESET_PARSER - If the value of the feature is set to true, the parser will be
reset to the state right after securing it.
HardenerConstants.REMOVE_EXT_ENTITIES - any External Entity will be replaced with a blank entity
instead of causing an exception

White List

HardenerConstants.USE_PSE_WHITELIST_FEATURE - Set the white list to be used by EntityResolver


during SAXParser instantiation

Mapper List

HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE - Set the mapper list to be used by


EntityResolver during SAXParser instantiation

Learning Mode

HardenerConstants.USE_PSE_LEARNINGLIST_FEATURE - activates learning mode

Take Over Full Control of the XML SAX Parser

After securing HardenedSAXParserFactory, you can still change some features and attributes. Changing a
single feature or attribute may result in changing several others automatically.

Features and attributes, which are considered relevant to the security, can only be changed with your explicit
consent and awareness, and after changing the value of the XML Hardener feature
HardenerConstants.FACTORYACCESS_FEATURE.

Example

Sample Code

saxFactory.setFeature(HardenerConstants.FACTORYACCESS_FEATURE, true);
// change other security related features and attributes

Securing Java Applications with XML Hardener


14 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
Reset Changes Done During Securing SAXParserFactory

In case you want to undo the changes done to the XML parser after securing the SAXParserFactory, execute
the following code line:

Example

Sample Code

saxFactory.setFeature(HardenerConstants.FACTORY_RESET_PARSER, true);

White Listing

White lists are used when you want to specify trusted URIs for external entities within the DTD in your application.
All URIs added in the white list will be treated as secure and access to them will be allowed. It is up to you to define
this list in your application.

By default, the feature HardenerConstants.USE_PSE_WHITELIST_FEATURE is set to true so there is no need


to set it before the configuration of your white list.

White list can be configured from a configuration file or programmatically as in the follwoing example:

Sample Code

Set<EREntityIdentifier> whitelist = new HashSet<EREntityIdentifier>();


EREntityIdentifier entityIdentifier = new EREntityIdentifier("entityName", null,
"http://www.xyz.com/example.xml", "external.dtd");
whiteList.add(entityIdentifier);
SAXParser saxParser = saxFactory.newSAXParser();
parser.setProperty(HardenerConstants.PSE_WHITELIST_PROPERTY, whiteList);

Entity Mapping

In your application, you can specify a set of URIs, which are accepted within a DTD as external entities but will be
mapped to a different URIs using a Mapping List. For example, if the incoming URI http://www.xyz.com/
my.dtd is mapped to C:/dtd/xyz_com_my.dtd, your application will accept the incoming DTD http://
www.xyz.com/my.dtd and will replace it with the local version to which it is mapped C:/dtd/xyz_com_my.dtd.
You can also add a list of Entity Resolvers to each entity mapping entry.

By default, the feature HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE is set to false so, so you


have to set it to true before start configuring your mapper list.

Mapper list can be configured from a configuration file or programmatically as in the following example:

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 15
Sample Code

dbFactory.setFeature(HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE, true);
.....
Map<EREntityIdentifier, EREntityIdentifier> replacementMap = new
HashMap<EREntityIdentifier, EREntityIdentifier>();
EREntityIdentifier externalEntityIdentifier = new
EREntityIdentifier("entityName", null, "http://www.xyz.com/my.dtd ", "my.dtd");
EREntityIdentifier localEntityIdentifier = new EREntityIdentifier("entityName",
null, "C:/dtd/xyz_com_my.dtd" , "xyz_com_my.dtd");
replacementMap.put(externalEntityIdentifier, localEntityIdentifier);
dbFactory.setAttribute(HardenerConstants.USE_PSE_REPLACEMENTMAP_FEATURE,
replacementMap);

Entity Resolvers

Entity Resolvers are basically callbacks. If the XML parser finds an external entity during parsing of the document,
the parser will check if an Entity Resolver has been specified and if so call it. The primary purpose of these Entity
Resolvers is to make the application more robust against failures. For example, the external entity could point to a
network URI - which will not work if the network is not available. However, the application should still process this
document. Or the URI is a relative path which might also not work for the executing application, and again should
not cause a failure.

All XML parsers are using entity resolvers to find external entities like DTDs or
XSDs.HardenedDocumentBuilderFactory supports different entity resolvers. It Which one to be used depends
on the use case.

Note
If the Entity Resolver returns a "null" string, this is interpreted as "valid" by the parser and will allow the URI to
be used.

Entity Resolvers from Parsers


The default entity resolvers do not check the external entities. The resolvers try to resolve the location of the
entities directly. It means the parser will try to access everything entered as value using the URL class (all its
supported features and protocols).
Default Entity Resolver from XML Hardener
There are two default implementations for both interfaces org.xml.sax.EntityResolver and
org.xml.sax.ext.EntityResolver2 in XML Hardener, correspondingly HardenedEntityResolver and
HardenedEntityResolver2.

Parent topic: Securing parsers, schema validation and transformer [page 7]

Previous: Securing a DOM Parser [page 7]

Next: Securing XML Schema Validation [page 17]

Securing Java Applications with XML Hardener


16 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
2.3.3 Securing XML Schema Validation

Securing XML Schema Validation

You can use XML Schema to validate an XML document against a pre-defined set of rules. It is often referred to as
XML Schema Definition (XSD). Since the document produced after parsing varies depending on the XML parser, it
is recommended to use parser specific XML Schema for validation.

There are two approaches to validate XML documents against XSD.

The first one allows you to use a Validatior, which is available since JRE/JDK 1.5. This is a processor that
checks the XML document against a XML Schema after the initial parsing of the document.
The second one enables you to use setSchema(Schema schema) method. As a result the validation
happens during the parsing of the document.

Securing Schema Validation when Using a Validator


When you use a Validatior, the XML Schema Validation happens on the resulting document (created after the
parsing), and thus it can be used independently by the XML parser.

Example

Sample Code

Document document = dbFactory.newDocumentBuilder().parse(xmlFile);


SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

You have to use the schema validation having in mind that:

There is a performance impact depending on the size of the document and the XSD.
The document created after the parsing can differ depending on the type of the XML Parser in use. Therefore,
the result of parsing one and the same XML document may be different when parsed with different parsers.
You can activate secure XML validation by using HardenedFacade and Validator class like in the example
below:

Example

Sample Code

SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory = HardenedFacade.secureSchemaFactory(schemaFactory);

Schema schema = schemaFactory.newSchema(new File(xsdFile));


Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 17
The returned schemaFactory is an instance of HardenedSchemaFactory, which is already secured. No further
features or properties need to be set.

Validation During Parsing


You can also use HardenedFacade to validate your XML document against an XML Schema during parsing.

Note
Method setSchema(Schema schema) of DocumentBuilderFactory really sets the schema to a factory that
is instance of HardenedDocumentBuilderFactory only if the schema parameter is instance of
HardenedSchema. This is the only way to ensure secure schema validation.

Example

Sample Code

DocumentBuilderFactory dbFactory =
HardenedFacade.secureDocumentBuilderFactory(dbFactory);
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory = HardenedFacade.secureSchemaFactory(schemaFactory);
Schema schema = schemaFactory.newSchema(xsdFile);
dbFactory.setSchema(schema);

The method with parameters SchemaFactory and String namespace is used for external configuration file. The
second parameter identifies which exactly configuration file to be used.

public static SchemaFactory secureSchemaFactory(final SchemaFactory factory, final


String callerNamespace)
throws SAXNotRecognizedException, SAXNotSupportedException

Note
Call as less as possible the secureSchemaFactory method because there are some resource consuming
operations, which might affect the performance of your application. Try to reuse the SchemaFactory instance
across classes instead.

Parent topic: Securing parsers, schema validation and transformer [page 7]

Previous: Securing a SAX Parser [page 13]

Next: Securing a Transformer Factory [page 19]

Securing Java Applications with XML Hardener


18 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
2.3.4 Securing a Transformer Factory

Securing Transformer Factory

The use of XML Hardener for securing TransformerFactory is analogical to the other factories for DOM and
SAX parsing

To secure the TransformerFactory, import the following facade:

Example

Sample Code

import com.sap.security.hardener.nw.facade.HardenerFacade;
........
transformerFactory =
HardenerFacade.secureTransformerFactory(transformerFactory);

As a result, the returned TransformerFactory is immediately secured and is instance of


HardenedTransformerFactory.

Tip
There are also white and mapper lists, as well as features for factory access, resetting the factory and switching
it to learning mode.

Example

Sample Code

DocumentBuilder builder = this.dbFactory.newDocumentBuilder();


Source xsltSource = new DOMSource(builder.parse(new File(CURRENT_WORK_FOLDER,
rootXsl)));
Source source = new DOMSource(builder.parse(new File(CURRENT_WORK_FOLDER,
xmlFile)));
securedTrFactory =
HardenedFacade.secureTransformerFactory(this.transformerFactory);
transformerFactory.setFeature(HardenerConstants.USE_WHITELIST_FEATURE,
true);
try {
Utils.addToWhiteListForXslt(transformerFactory, importXsl1, rootXsl);
Utils.addToWhiteListForXslt(transformerFactory, importXsl2, rootXsl);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Transformer transformer = transformerFactory.newTransformer(xsltSource);
StringWriter writer = new StringWriter();
Result output = new StreamResult(writer);
transformer.transform(source, output);

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 19
The method with parameters TransformerFactory and String namespace is used for external configuration
file. The second parameter identifies which exactly configuration file to be used.

public static TransformerFactory secureTransformerFactory(final TransformerFactory


factory, final String callerNamespace)
throws TransformerConfigurationException

Note
Call as less as possible the secureTransformerFactory method because there are some resource
consuming operations, which might affect the performance of your application. Try to reuse the
TransformerFactory instance across classes instead.

Parent topic: Securing parsers, schema validation and transformer [page 7]

Previous: Securing XML Schema Validation [page 17]

2.4 Enabling XML Hardener for Application Server Java

Context

You can enable or disable XML Hardener through SAP NetWeaver Administrator.

To do so, follow the steps below:

Note
Please note that XML Hardener is enabled by default.

Procedure

1. Go to http://<host>:<port>/nwa to log on to SAP NetWeaver Administrator

2. Navigate to Configuration Infrastructure Java System Properties Services


3. Find XML Hardener Service from the list
4. Under the Properties section, choose Modify
a. In the Modify Property Value pop-up window, set the custom value for enable.xml.hardener property
to true
b. Choose Set

Securing Java Applications with XML Hardener


20 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
5. Choose Save to enable the XML Hardener

If you want to disable XML Hardener, set the custom value for enable.xml.hardener property to false
as per step 4.

2.5 External Configuration Files

You can further configure the different factories after they are secured by the XML Hardener. Depending on your
the personal decision, you can allow some features. You can also create white lists and mapper lists. You can do
all these configurations programmatically by adding one code line in your application.

You manage the external configuration files for the different XML Hardener clients, which might be applications,
services and other libraries via the Config Tool in SAP NetWeaver.

Tip
The Config Tool is available at usr\sap\<SID>\<instance number>\j2ee\configtool
\configtool.bat on the system where it is installed.

Creating Configuration Node for a Client and Uploading the Configuration File

External configuration files are stored under the XMLHardener node, which is directly under theConfigurations
node in the configurations tree.

You can upload the configuration files via the Config Tool. The files are identified by their path in the tree and their
name.

Recommendation
Create a separate sub-node of the XMLHardener for each client and use a unique name. This way the
configurations will be better organized. Under the client sub-node, you can upload the necessary configuration
files.

To create configuration node and upload the configuration file, proceed as follows:

1. Open the Config Tool and go to the Tools tab


2. Choose Configuration Editor from the drop-down menu
3. Find XMLHardener node
4. From the context menu of XMLHardener choose Create sub-node
A pop-up window with the configuration node parameters appears.
5. Insert the name of the configuration node. For example, myAppNamespace
6. Choose Create and close the window
7. From the context menu of the newly created configuration node, choose Create sub-node
A pop-up window with the configuration file parameters appears.
8. Choose File-entry

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 21
9. Insert the configuration file name. For example, test.xml
10. Paste the content of the configuration into the text area or upload an already existing file on the system
11. Choose Create and close the window

Changing Existing Configuration

If you want to update an existing configuration, you can download it from the Config Tool or start from scratch.

You can perform the changes either manually or using the XML Hardener UI Tool for External Configurations.

1. From the context menu of an existing configuration file (located under the XML Hardener node), choose
Change
A pop-up window with the parameters of the existing configuration file appears.
2. Choose Download and then OK
3. Change the configuration file
4. Go to the context menu of the existing configuration file and choose Change
A pop-up window with the parameters of the existing configuration file appears.
5. Upload the changed file and choose OK

Note
When you upload a configuration file or change the content of an existing one, you have to refresh the
configurations cached in the XML Hardener Extension. To do so, you need to restart the XML Hardener Service
as follows:

1. Go to SAP NetWeaver Administrator (http://<host>:<port>/nwa)


2. Navigate to Operations Start & Stop Java Services Services
3. Find XML Hardener Service and choose Restart.

Transporting Configurations between the Systems

When you configure external files on one system you may need to transport them to another system. For
example, from development to a test system. You can do this via the Config Tool as follows:

1. Open Config Tool (Configuration Editor) and select XMLHardener configuration node or a sub-node, which
contains the files to be transported.
The selected node may include a hierarchy of configuration nodes containing file entries
2. From the toolbar menu choose Export or from the node context menu choose the Export action
3. Enter a file name with .zip extension and choose Start export button
A zip file will be created in the selected folder
4. Copy the exported zip file to the target system
5. In the target system open Config Tool (Configuration Editor) and switch to Edit Mode
6. Select the XMLHardener configuration node and choose Import from the toolbar menu, or from the node
context menu choose the Import action
7. Select the zip file

Securing Java Applications with XML Hardener


22 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
8. Select Import content directly into the selected configuration.
9. Choose Start import.
The configuration files including their node hierarchy (if any) will be imported into the XMLHardener node
10. Choose Close to view the updated configuration tree

Default Configuration

This is the default content of default.xml configuration provided by XML Hardener Service.

<?xml version="1.0" encoding="UTF-8"?>


<xmlHardener>
<enabled>false</enabled>
<features/>
<properties/>
<whiteList/>
<mapperList/>
</xmlHardener>

Configuration Manager Cache

It is possible the external configuration file to exist under XMLHardener node but to be not found during runtime
due to inconsistency in AS Java Configuration Manager cache. Therefore, you need to restart the server.

As a workaround you could use telnet command "cfg_cache -c".

For more information, see: SAP Note 2259873.

2.6 Learning Mode

Most applications are expected to adopt the XML Hardener and continue with the successful parsing of XML
documents in a secure way without any problems. However, there might be cases in which some XML documents
will not be parsed because of blocked external entities. Or there may be trusted external entities, which can be
allowed. These entities can be added to white lists or mapped to another trusted entities. In order to list all the
external entities in one log file and to review them, and add them to a white list, Learning Mode is introduced in the
XML Hardener.

1. You can enable the Learning mode by setting the feature


HardenerConstants.USE_LEARNINGLIST_FEATURE to the secured factory in your Java code or by using
an external configuration file. You can create such a file manually or enable the Learning Mode using the XML
Hardener UI Tool for External Configurations.
1. To create the external configuration file manually, you need to add the following line inside the
<features> tag:

<xmlHardener>
<enabled>true</enabled>

Securing Java Applications with XML Hardener


Using XML Hardener in SAP NetWeaver 2016 SAP SE or an SAP affiliate company. All rights reserved. 23
<features>
<feature name = "http://sap.com/security/hardener/xml/features/
entities/useLearningList">true</feature>
............
</features>
......

2. To enable the Learning Mode through the XML Hardener UI Tool for External Configurations, select the
Learning Mode check-box.
2. After you save the configuration file you have to upload it in the Config Tool and restart the XML Hardener
Service. This will enable the Learning mode. The log records are written in a separate log file
xml_learning_mode.log, which can be found at usr\sap\<SID>\<instance number>\j2ee\cluster
\server? <number>\log.
3. Afterwards, you can load the log file via the XML Hardener UI Tool for External Configurations and use it to
change the configuration by adding or removing the logged entities in the white or mapper lists.
4. You can also use the XML Hardener UI Tool for External Configurations to add and remove features and
properties.

Caution
When running your applications in Learning Mode, the XML Hardener does not secure the parser. After finishing
the configuration of white and mapper lists, you have to disable the Learning Mode.

Tip
If you encounter problems enabling the Learning Mode in SAP NetWeaver 7.0x releases, go to the Config Tooll
(usr\sap\<SID>\<instance number>\j2ee\configtool\configtool.bat on the system where it is
installed) and check if Logging Category Applications/XMLHardener/LearningMode exists. If not, create
it with severity Info.

Securing Java Applications with XML Hardener


24 2016 SAP SE or an SAP affiliate company. All rights reserved. Using XML Hardener in SAP NetWeaver
Important Disclaimers and Legal Information

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

Accessibility
The information contained in the SAP documentation represents SAP's current view of accessibility criteria as of the date of publication; it is in no way intended to be a
binding guideline on how to ensure accessibility of software products. SAP in particular disclaims any liability in relation to this document. This disclaimer, however, does
not apply in cases of wilful misconduct or gross negligence of SAP. Furthermore, this document does not result in any direct or indirect contractual obligations of SAP.

Gender-Neutral Language
As far as possible, SAP documentation is gender neutral. Depending on the context, the reader is addressed directly with "you", or a gender-neutral noun (such as "sales
person" or "working days") is used. If when referring to members of both sexes, however, the third-person singular cannot be avoided or a gender-neutral noun does not
exist, SAP reserves the right to use the masculine form of the noun and pronoun. This is to ensure that the documentation remains comprehensible.

Internet Hyperlinks
The SAP documentation may contain hyperlinks to the Internet. These hyperlinks are intended to serve as a hint about where to find related information. SAP does not
warrant the availability and correctness of this related information or the ability of this information to serve a particular purpose. SAP shall not be liable for any damages
caused by the use of related information unless damages have been caused by SAP's gross negligence or willful misconduct. All links are categorized for transparency
(see: http://help.sap.com/disclaimer).

Securing Java Applications with XML Hardener


Important Disclaimers and Legal Information 2016 SAP SE or an SAP affiliate company. All rights reserved. 25
go.sap.com/registration/
contact.html

2016 SAP SE or an SAP affiliate company. All rights reserved.


No part of this publication may be reproduced or transmitted in any
form or for any purpose without the express permission of SAP SE
or an SAP affiliate company. The information contained herein may
be changed without prior notice.
Some software products marketed by SAP SE and its distributors
contain proprietary software components of other software
vendors. National product specifications may vary.
These materials are provided by SAP SE or an SAP affiliate company
for informational purposes only, without representation or warranty
of any kind, and SAP or its affiliated companies shall not be liable for
errors or omissions with respect to the materials. The only
warranties for SAP or SAP affiliate company products and services
are those that are set forth in the express warranty statements
accompanying such products and services, if any. Nothing herein
should be construed as constituting an additional warranty.
SAP and other SAP products and services mentioned herein as well
as their respective logos are trademarks or registered trademarks
of SAP SE (or an SAP affiliate company) in Germany and other
countries. All other product and service names mentioned are the
trademarks of their respective companies.
Please see http://www.sap.com/corporate-en/legal/copyright/
index.epx for additional trademark information and notices.

Vous aimerez peut-être aussi