Monday, December 29, 2014

Command Design Pattern

Design Pattern > Behavioral Design Pattern > Command Design Pattern

In Command design pattern a request is pass to an invoker as an Object, here invoker does not knows to serve the request but uses the command to perform an action.

Benefits of Using Command Pattern :
. it hides the details of the actions that needs to be performed, so that the client code does not need to be concerned about the details when it needs to execute the actions. The client code just needs to tell the application to execute the command that was stored.
. It's easy to add new comands without changing the existing classes.

Key Terms :
Command - Interface with concrete method declaration
ConcreteCommand -

  • Implements Command
  • Set Receiver in it's method or constructor
  • Call Receiver's method in execute()

Receiver -

  • Define Actions to be performed

Invoker - Command Object passed to Invoker and it instructs the command to perform an action.

  • Set Command object in it's method or constructor
  • Call execute on Command object

Client -

  • Create Receiver object
  • Create Concreate Command object(s)
  • Create invoker object and call it's method


Java Implementation :
     In the above key terms you have already seen the Pseudocode. Now, we will see the complete implementation in Java

// Command Interface
public interface Order {

void execute();
}

// ConcreteCommand
public class StockBuy implements Order {

private StockTrade stock;
public StockBuy(StockTrade trade){
stock = trade;
}
@Override
public void execute() {
// call receiver's method
stock.buy();
}

}

// ConcreteCommand
public class StockSell implements Order {

private StockTrade stock;
public StockSell(StockTrade trade){
stock = trade;
}
@Override
public void execute() {
// call receiver's method
stock.sell();
}

}

// Receiver class
public class StockTrade {

public void buy() {
System.out.println("buying stock");
}

public void sell() {
System.out.println("selling stock");
}

}

// Invoker Class
public class Broker {
Order order;
public Broker(Order odr){
order = odr;
}
void placeOrder(){
order.execute();
}
}

// Client Class
public class Client {

public static void main(String[] args) {
// Create Receiver object
StockTrade st = new StockTrade();
// Create Concreate Command object(s)
StockBuy sb = new StockBuy(st);
StockSell ss = new StockSell(st);
// Create invoker object
Broker bbuy = new Broker(sb);
Broker bsell = new Broker(ss);
// call invoker method
bbuy.placeOrder();
bsell.placeOrder();
}

}

is Invoker Optional In Command Pattern ?
As we know, java.lang.Runnable is one of the examples of command pattern where Thread class works as an invoker. We pass object of a Runnable class to Thread class and say start/run.

But we never create a client class which can invoke main thread.

So an invoker is not optional but it is not tightly coupled to client.

Tuesday, December 2, 2014

Chain of Responsibility Design Pattern


Design Pattern > Behavioral Design Pattern > Chain of Responsibility Design Pattern

Chain of responsibility helps to decouple sender of a request and receiver of the request with some trade-offs. Chain of responsibility is a design pattern where a sender sends a request to a chain of objects, where the objects in the chain decide themselves who to honor the request. If an object in the chain decides not to serve the request, it forwards the request to the next object in the chain.

Responsibility is outsourced. In a chain of objects, the responsibility of deciding who to serve the request is left to the objects participating in the chains.
The most usual example of a machine using the Chain of Responsibility is the vending machine coin slot: rather than having a slot for each type of coin, the machine has only one slot for all of them. The dropped coin is routed to the appropriate storage place that is determined by the receiver of the command.

Having so many design patterns to choose from when writing an application, it's hard to decide on which one to use, so here are a few situations when using the Chain of Responsibility is more effective:

  • More than one object can handle a command
  • The handler is not known in advance
  • The handler should be determined automatically
  • It’s wished that the request is addressed to a group of objects without explicitly specifying its receiver
  • The group of objects that may handle the command must be specified in a dynamic way

Example Java Code

Digit.java

package com.kmingle.chainofresponsibility;

public class Digit {

private int digit;
public Digit(int digit){
this.digit = digit;
}

public int getDigit() {
return digit;
}
}

Handler.java

package com.kmingle.chainofresponsibility;

public interface Handler {

public abstract void setNextHandler(Handler nextHandler);
public abstract void processRequest(Digit input);
}


NegativeHandler.java

package com.kmingle.chainofresponsibility;

public class NegativeHandler implements Handler{

private Handler nextHandler;

@Override
public void setNextHandler(Handler nxtHandler) {

nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {

if(input.getDigit() < 0){
System.out.println("handled by negative handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

PositiveHandler.java 

package com.kmingle.chainofresponsibility;

public class PositiveHandler implements Handler{

private Handler nextHandler;
@Override
public void setNextHandler(Handler nxtHandler) {
nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {
if(input.getDigit() > 0){
System.out.println("handled by positive handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

ZeroHandler.java 

package com.kmingle.chainofresponsibility;

public class ZeroHandler implements Handler{

private Handler nextHandler;
@Override
public void setNextHandler(Handler nxtHandler) {
nextHandler = nxtHandler;
}

@Override
public void processRequest(Digit input) {
if(input.getDigit() == 0){
System.out.println("handled by zero handler : "+ input.getDigit());
}
else {
nextHandler.processRequest(input);
}
}

}

Requester.java

package com.kmingle.chainofresponsibility;

public class Requester {
public static void main(String[] args) {
// configuration for request handler chains
Handler h1 = new Negativehandler();
Handler h2 = new Positivehandler();
Handler h3 = new Zerohandler();
h1.setNextHandler(h2);
h2.setNextHandler(h3);
// calling chain
h1.processRequest(new Digit(10));
h1.processRequest(new Digit(-10));
h1.processRequest(new Digit(0));
h1.processRequest(new Digit(20));
}

}

Output :

handled by positive handler : 10
handled by negative handler : -10
handled by zero handler : 0
handled by positive handler : 20

Sunday, November 30, 2014

Design Patterns

What is Design Pattern?
In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

Why study design patterns ? 
Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced software designers.
Moreover, the study of design patterns provides a common vocabulary for communication and documentation, and it provides a framework for evolution and improvement of existing patterns. As an analogy, consider that during a discussion among programmers, the words “stack” and “tree” can be used freely without explanation. Software developers understand fundamental data structures such as a “stack” because these data structures are well-documented in textbooks and are taught in computer science courses. The study of design patterns will have a similar (but more profound) effect by allowing designers to say “composite pattern” or “observer pattern” in a particular design context, without having to describe all classes, relationships, and collaborations which make up the pattern. Patterns raise the level of abstraction when discussing and documenting software designs.

How to study design patterns? 
Design patterns are best recognized as a high-level issue; one that is only relevant if you have the experience necessary to recognize them as useful. It's good that you recognize that they're useful, but unless you've seen situations where they would apply, or have applied, it's almost impossible to understand their true value.

Where they become useful is when you recognize design patterns in others' code, or recognize a problem in the design phase that fits well with a pattern; and then examine the formal pattern, and examine the problem, and determine what the delta is between them, and what that says about both the pattern and the problem.

How many types of design patterns ?
Design patterns are divided into three fundamental groups:
Behavioral,
Creational, and
Structural

Behavioral patterns :
Behavioral patterns describe interactions between objects.
They focus on how objects communicate with each other. They can reduce complex flow charts to mere interconnections between objects of various classes. Behavioral patterns are also used to make the algorithm that a class uses simply another parameter that is adjustable at runtime.
Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them.
These patterns characterize complex control flow that is difficult to follow at run-time. They shift your focus away from the flow of control to let you concentrate just on the way objects are interconnected. Behavioral class patterns use inheritance to distribute behavior between classes.

Creational patterns :
Creational patterns are used to create objects for a suitable class that serves as a solution for a problem. Generally when instances of several different classes are available. They are particularly useful when you are taking advantage of polymorphism and need to choose between different classes at runtime rather than compile time.
Creational patterns support the creation of objects in a system. Creational patterns allow objects to be created in a system without having to identify a specific class type in the code, so you do not have to write large, complex code to instantiate an object. It does this by having the subclass of the class create the objects. However, this can limit the type or number of objects that can be created within a system.

Structural patterns :
Structural patterns are concerned with how classes and objects are composed to form larger structures.
Structural class patterns use inheritance to compose interfaces or implementations. As a simple example, consider how multiple inheritance mixes two or more classes into one. The result is a class that combines the properties of its parent classes. This pattern is particularly useful for making independently developed class libraries work together.

in next blogs we will see these types in more details with examples.

Saturday, November 22, 2014

How to find security vulnerabilities in JAVA application libraries using Dependency Check

A web-application is never finished. Even when no new features are being developed new vulnerabilities may be found in the frameworks used in the application requiring a patch or an upgrade.Java is a very popular programming language. Two key reasons for its popularity are security and the availability of a huge ecosystem of libraries and components. Since most Java applications make use of a wide range of libraries, which in turn have dependencies on other libraries, it is difficult to ensure the integrity of these applications from a security perspective.

The OWASP Top 10 represents a broad consensus on the most critical web application security flaws.They are dangerous because they will frequently allow attackers to completely take over your software, steal data, or prevent your software from working at all
those are :
1. Injection : Injection flaws occur when an application sends untrusted data to an interpreter. Injection flaws are very prevalent, particularly in legacy code. They are often found in SQL, LDAP, Xpath, or NoSQL queries; OS commands; XML parsers, SMTP Headers, program arguments, etc. Injection flaws are easy to discover when examining code, but frequently hard to discover via testing. Scanners and fuzzers can help attackers find injection flaws.

2. Broken Authentication and Session Management (XSS) : Developers frequently build custom authentication and session management schemes, but building these correctly is hard. As a result, these custom schemes frequently have flaws in areas such as logout, password management, timeouts, remember me, secret question, account update, etc. Finding such flaws can sometimes be difficult, as each implementation is unique.

3. Cross Site Scripting (XSS) : XSS is the most prevalent web application security flaw. XSS flaws occur when an application includes user supplied data in a page sent to the browser without properly validating or escaping that content. There are two different types of XSS flaws: 1) Stored and 2)Reflected, and each of these can occur on the a) Serveror b) on the Client.
Detection of most Server XSS flaws is fairly easy via testing or code analysis. Client XSS is very difficult to identify.
4. Insecure Direct Object References : Applications frequently use the actual name or key of an object when generating web pages. Applications don’t always verify the user is authorized for the target object. This results in an insecure direct object reference flaw. Testers can easily manipulate parameter values to detect such flaws. Code analysis quickly shows whether authorization is properly verified.
5. Security Misconfiguration : Security misconfiguration can happen at any level of an application stack, including the platform, web server, application server, database, framework, and custom code. Developers and system administrators need to work together to ensure that the entire stack is configured properly. Automated scanners are useful for detecting missing patches, misconfigurations, use of default accounts, unnecessary services, etc.
6. Sensitive Data Exposure : The most common flaw is simply not encrypting sensitive data. When crypto is employed, weak key generation and management, and weak algorithm usage is common, particularly weak password hashing techniques. Browser weaknesses are very common and easy to detect, but hard to exploit on a large scale. External attackers have difficulty detecting server side flaws due to limited access and they are also usually hard to exploit.
7. Missing Function Level Access Control : Applications do not always protect application functions properly. Sometimes, function level protection is managed via configuration, and the system is misconfigured. Sometimes, developers must include the proper code checks, and they forget.
Detecting such flaws is easy. The hardest part is identifying which pages (URLs) or functions exist to attack
8. Cross Site Request Forgery (CSRF) : CSRF takes advantage the fact that most web apps allow attackers to predict all the details of a particular action.
Because browsers send credentials like session cookies automatically, attackers can create malicious web pages which generate forged requests that are indistinguishable from legitimate ones.
Detection of CSRF flaws is fairly easy via penetration testing or code analysis. 
9. Using Components with Known Vulnerabilities : Virtually every application has these issues because most development teams don’t focus on ensuring their components/libraries are up to date. In many cases, the developers don’t even know all the components they are using, never mind their versions. Component dependencies make things even worse.
10. Unvalidated Redirects and Forwards : Applications frequently redirect users to other pages, or use internal forwards in a similar manner. Sometimes the target page is specified in an unvalidated parameter, allowing attackers to choose the destination page.
Detecting unchecked redirects is easy. Look for redirects where you can set the full URL. Unchecked forwards are harder, because they target internal pages.

Now we will see how to find out security vulnerabilities in JAVA application libraries using Dependency Check,
dependency-check-ant is an Ant Task that uses dependency-check-core to detect publicly disclosed vulnerabilities associated with the project's dependencies. The task will generate a report listing the dependency, any identified Common Platform Enumeration (CPE) identifiers, and the associated Common Vulnerability and Exposure (CVE) entries.
Currently Java and .NET dependencies are supported. support for Node.JS, client side JavaScript libraries, etc. is planned.
Steps to follow :
Step 1 : Download dependency-check-ant from bintray here
Step 2 : To install dependency-check-ant place the dependency-check-ant-1.2.6.jar into the lib directory of your Ant instalation directory. Once installed you can add the taskdef to you build.xml and add the task to a new or existing target:
<'taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask"/'>
<'taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask"'>
<'classpath path="[path]/[to]/dependency-check-ant-x.x.x.jar"/'>
<'/taskdef'>
Step 3 : If you do not want to install dependency-check-ant into your ant’s lib directory when you define the task def you must add the classpath to the taskdef:
Step 4 : If you are behind proxy set proxy settings in you ant script as :
<'setproxy proxyhost="proxyIP/IURL" proxyport="proxyPort" /'>
That's it run you script to get the report
It is important to understand that the first time this task is executed it may take 20 minutes or more as it downloads and processes the data from the National Vulnerability Database (NVD) hosted by NIST: https://nvd.nist.gov

Source : www.owasp.org


Sunday, November 2, 2014

How to Scan Security Vulnerabilities in JavaScript Library using SecureJs

Javascript has been extensively used for several years ever since it was first developed by Netscape in 1995. It has virtually revolutionized the way the Internet and websites work by adding functionality that is lightweight yet feature-filled. Ad servers use javascript to display ads on websites, ads are virtually bread and butter to the website publisher and is thus responsible to several successful, established and useful websites. Apart from ads Javascript is also used to add graphical effects as well as several other functions to websites.
However, Javascript has been responsible for several security vulnerabilities over the years.
Securing client-side JavaScript is a problem that has started receiving attention. Third-party JavaScript issues from widgets, embedded code and JavaScript libraries are some of the vulnerable aspects of JavaScript that see active exploitation.
JavaScript security issues can be divided into three broad categories:
1.  DOM-based cross-site scripting (XSS) :
XSS is usually the result of insecurely written server-side code, DOM-based XSS is a kind of XSS occurring entirely on the client-side.
2.  Cross-domain information leakage : JavaScript has cross-domain functionality that allows sites to load multiple objects from various sources (widgets or iframes, among others). Until recently, JavaScript had restrictions on accessing/sending data to other domains. However, HTML5 has increased the level of cross-domain access that JavaScript enjoys with the cross-domain XML request function.

3.  Client-side logic and data storage : Initially, JavaScript performance and capabilities were very limited, receiving no significant focus from browser developers for improving performance. As JavaScript engines get faster with iterations of browser release, it is possible to perform substantial processing on the client-side.With HTML5, client-side storage mechanisms have gone beyond the cookie with newer options such as localStorage, Web SQL and IndexDB. Storage of sensitive data on the client side using these mechanisms fosters a huge security risk, bigger than cookies ever posed.

There are plenty of open source tools available SecureJs is one of them, let's see step by step how to scan your JavaScript libraries with SecureJs.

Step 1: Installing NodeJs : Download the Node.js source code from http://nodejs.org/download/ and install it in your system.

Step 2: Installing npm : npm (Node Package Manager) is the default package manager for Node.js. As of Node.js version 0.6.3, npm is bundled and installed automatically with the environment. npm runs through the command line and manages dependencies for an application. for Windows You can download a zip file from https://npmjs.org/dist/, and unpack it in the same folder where node.exe lives( Inside Program Files folder ).

Atep 3: Open Command Prompt and Install Retire JS using command "npm install -g retire" your Command Promt display will be like this :

C:\Users\satyendra.jaiswal\AppData\Roaming\npm\retire -> C:\Users\satyendra.jaiswal\AppData\Roaming\npm\node_modules\retire\b
in\retire
retire@0.3.1 C:\Users\satyendra.jaiswal\AppData\Roaming\npm\node_modules\retire
├── commander@2.0.0
├── underscore@1.4.4
├── walkdir@0.0.7
├── request@2.40.0 (forever-agent@0.5.2, oauth-sign@0.3.0, json-stringify-safe@5.0.0, aws-sign2@0.5.0, stringstream@0.0.4, tu
nnel-agent@0.4.0, qs@1.0.2, node-uuid@1.4.1, mime-types@1.0.2, http-signature@0.10.0, hawk@1.1.1, tough-cookie@0.12.1, form-d
ata@0.1.4)
└── read-installed@0.2.5 (graceful-fs@2.0.3, slide@1.1.6, semver@2.3.2, read-package-json@1.2.7)


Step 3 : Test if Retire is installed using retire command like : retire -h

Step 4 : Scan JS files of a specific folder using retire command : use retire -c to avoide local cache

If you are behind the proxy then use these steps :

Step 1: Set Proxy on command prompt :

npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:mypassword@proxyIPorAddress:8080
npm config set https-proxy http://myusername:mypassword@proxyIPorAddress:8080
npm config set strict-ssl false
set HTTPS_PROXY=http://myusername:mypassword@proxyIPorAddress:8080
set HTTP_PROXY=http://myusername:mypassword@proxyIPorAddress:8080
export HTTPS_PROXY=http://myusername:mypassword@proxyIPorAddress:8080
export HTTP_PROXY=http://myusername:mypassword@proxyIPorAddress:8080
export http_proxy=http://myusername:mypassword@proxyIPorAddress:8080

Step 2: Install Retire :

npm --proxy http://myusername:mypassword@proxyIPorAddress:8080 --without-ssl --insecure -g install retire

Step 3 : Test if Retire is installed using retire command like : retire -h

Step 4 : Scan JS files of a specific folder using retire command

Sunday, October 12, 2014

How To Add text editor(TinyMCE) in your web application

Hi,
     There are several open source editor available to use in your web application but i prefer to use TinyMCE editor because of it's simple to use and it has many features.
TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under LGPL.
TinyMCE has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.
In this post we are going to learn ho to use tinyMCE into your web application in JSP

Step 1 : Download TinyMCE editor from http://www.tinymce.com/download/download.php into your local drive.

Step 2 : Unzip and Add tinymce folder to your project root or in WebContent directory.

Step 3:  Add text area to JSP e.g. <textarea id="elm1" name="message">

Step 4: Add following  to your JSP to call tinymce editor :

<script type="text/javascript" src="tinymce/js/tinymce/tinymce.js"></script>

Step 5: Now as per your requirement add tiny mce script which will convert text area into editor:

e.g.:  tinymce
.init({
selector : "textarea",
theme : "modern",
width : 200,
height : 100,
});

By default tinymce converts all the textarea into text editor, if you like to change only specific textarea into text editor then specify it as given below
tinymce
.init({
selector : "textarea#elm1",
theme : "modern",
width : 200,
height : 100,
});
Here selector : textarea#elm1 , will only convert elm1 text area into editor and not the other text areas in your jsp page.

That's all , it's done. Now run your application to use text editor :-)

Total Pageviews