Print sequence of number using multiple threads (java)

output :

 

Thread 1: 1
Thread 2: 2
Thread 3: 3
Thread 1: 4
Thread 2: 5
Thread 3: 6
Thread 1: 7
Thread 2: 8
Thread 3: 9
Thread 1: 10

 

 

 

 

 

package snippet;

public class PrintSequenceMultiThreaded {

	public static class Printer {
		private Integer printNumber;
		private Integer maxCount;
		private Integer currentThread;
		private Integer threadCount;
		private boolean stop = false;

		public Printer(Integer printNumber, Integer maxCount, Integer currentThread, Integer threadCount) {
			super();
			this.printNumber = printNumber;
			this.maxCount = maxCount;
			this.currentThread = currentThread;
			this.threadCount = threadCount;
		}

		public synchronized void print(int threadNumber) throws InterruptedException {
			while (true) {

				while (!stop && !this.currentThread.equals(threadNumber)) {
					this.wait(1000);
				}
				if (stop) {
					this.notifyAll();
					return;
				}

				if (printNumber > maxCount) {
					stop = true;
					return;
				}
				   
                                Thread.sleep(100);
				System.out.println(Thread.currentThread().getName() +": "+ printNumber);
				printNumber++;
			
				currentThread = (currentThread + 1) % threadCount;
				this.notifyAll();
			}
		}
	}

	static class PrinterTask implements Runnable {

		private Printer printer;
		private int task;

		public PrinterTask(Printer printer, int task) {
			super();
			this.printer = printer;
			this.task = task;
		}

		@Override
		public void run() {
			try {
				printer.print(task);
			} catch (InterruptedException e) {
				System.out.println("Stopping: " + Thread.currentThread().getName());
			}

		}

	}

	public static void main(String[] args) {
		Printer printer = new Printer(1, 10, 0, 3);
		PrinterTask task1 = new PrinterTask(printer, 0);
		PrinterTask task2 = new PrinterTask(printer, 1);
		PrinterTask task3 = new PrinterTask(printer, 2);

		new Thread(task1,"Thread 1").start();
		new Thread(task2,"Thread 2").start();
		new Thread(task3,"Thread 3").start();


	}

}

3 threads to print alternate values in sequence (java)

Print sequence from 1 to n using three threads.

Output should be like below:

Printing output for Thread: 0 1
Printing output for Thread: 1 2
Printing output for Thread: 2 3
Printing output for Thread: 0 4
Printing output for Thread: 1 5
Printing output for Thread: 2 6
Printing output for Thread: 0 7
Printing output for Thread: 1 8
Printing output for Thread: 2 9
Printing output for Thread: 0 10

Solution is using atomic variables , without using synchronization:

package snippet;

import java.util.concurrent.atomic.AtomicInteger;

/**
Threads are busy looping, which will lead to 100% CPU usage. You should synchronize the threads instead.
**/
public class ThreeThreadsOrderedLockLess {

	AtomicInteger sharedOutput = new AtomicInteger(0);

	public static void main(String args[]) {

		ThreeThreadsOrderedLockLess t = new ThreeThreadsOrderedLockLess();

		ThreadTasks t1 = t.new ThreadTasks(0);
		ThreadTasks t2 = t.new ThreadTasks(1);
		ThreadTasks t3 = t.new ThreadTasks(2);

		Thread ts1 = new Thread(t1);
		Thread ts2 = new Thread(t2);
		Thread ts3 = new Thread(t3);
		ts1.start();
		ts2.start();
		ts3.start();

	}

	private class ThreadTasks implements Runnable {

		private final int threadPosition;

		public ThreadTasks(int threadPosition) {
			super();

			this.threadPosition = threadPosition;
		}

		@Override
		public void run() {

			while (sharedOutput.get() < 10) {

				if (sharedOutput.get() % 3 == this.threadPosition) {

					int value = sharedOutput.get() + 1;
					System.out.println("Printing output for Thread: " + this.threadPosition + "  " + value);
					sharedOutput.incrementAndGet();
				}
			}

		}
	}

}

MongoDB Tutorial for beginners

Why MongoDB ?

MongoDB (from humongous) is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

MongoDB provides below features:

  • Document Database
    • Documents (objects) map nicely to programming language data types.
    • Embedded documents and arrays reduce need for joins.
    • Dynamic schema makes polymorphism easier.
  • High Performance
    • Embedding makes reads and writes fast.
    • Indexes can include keys from embedded documents and arrays.
    • Optional streaming writes (no acknowledgments).
  • High Availability
    • Replicated servers with automatic master failover.
  • Easy Scalability
    • Automatic sharding distributes collection data across machines.
    • Eventually-consistent reads can be distributed over replicated servers.
  • Advanced Operations

Installing MongoDB 

Visit official mongoDB website https://www.mongodb.org/ and click on download button and select operating system to download for. We will here download for windows 7 platform and setup.

1_download

Install MongoDB for Windows.

In Windows Explorer, locate the downloaded MongoDB .msi file, which typically is located in the default Downloads folder. Double-click the .msi file. A set of screens will appear to guide you through the installation process.

You may specify an installation directory if you choose the “Custom” installation option.

These instructions assume that you have installed MongoDB to C:\mongodb.

Set up the MongoDB environment.

To start a MongoDB instance using this configuration file, issue a command in the following form:

mongod --config C:/mongodb/mongo.conf
mongod -f C:/mongodb/mongo.conf

Modify the values in the mongod.conf file on your system to control the configuration of your database instance.

 mongo.conf
##store data here
dbpath=C:\mongodb\data

##all output go here
logpath=C:\mongodb\log\mongo.log

##log read and write operations or  verbose level logging
diaglog=3

dbpath is config where our data files are saved.

logpath is config where logs are created.

Now Run MongoDB service by writing in cmd where config is location of the mongo.config file

C:\Program Files\MongoDB\Server\3.0\bin>mongod --config C:\mongodb\mongo.config

Now mongoD service is up. Now we can connect to mongo console by using mongo.exe

C:\Program Files\MongoDB\Server\3.0\bin>mongo

When you connect to mongo then by default db selected is test. You can change the db using use command.

> use mydb
switched to db mydb

Inserting documents 

 db.collection.insert()

Inserts a document or documents into a collection.

The insert() method has the following syntax:

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

Here we will insert products in form of json. Since documents don’t have any specific structure we can directly inserty usin command below.

 > db.products.insert({"name": "SILVER NITRATE",
 "description": "Curabitur convallis.",
 "category": "Argentum Nitricum Kit Refill",
 "price": 5.12,
 "images": "https://assets.entrepreneur.com/content/16x9/822/201503032306
04-trifecta-triangle-selling-products.jpeg"
 });
WriteResult({ "nInserted" : 1 })
>

We can confirm that products has been inserted by query for all products.

For query operations, MongoDB provides a db.collection.find() method. The method accepts both the query criteria and projections and returns a cursor to the matching documents. You can optionally modify the query to impose limits, skips, and sort orders.

> db.products.find()
{ "_id" : ObjectId("560c25e711cfe572863303a9"), "name" : "SILVER NITRATE", "desc
ription" : "Curabitur convallis.", "category" : "Argentum Nitricum Kit Refill",
"price" : 5.12, "images" : "https://assets.entrepreneur.com/content/16x9/822/
20150303230604-trifecta-triangle-selling-products.jpeg" }
>

Note: A default _id field is added to each document which is unique and is indexed by mongo automatically.

The following diagram highlights the components of a MongoDB query operation:

crud-annotated-mongodb-find

The next diagram shows the same query in SQL:

crud-annotated-sql-select

EXAMPLE

> db.products.find( { price: { $gt: 5 } }, { name: 1, price: 1 } ).limit(5)

{ "_id" : ObjectId("560c3424f2924ebfac8bb947"), "name" : "Apis Mellifica, Arnica
 Montana, Calcarea Carbonica, Fucus Vesiculosus, Gambogia, Hepar Suis, Phosphori
cum Acidum, Pituitaria Glandula, Thuja Occidentalis, Thyroidinum Suis,", "price"
 : 38 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb948"), "name" : "Antimonium tartaricum,
 Bromium, Bryonia, Carbo vegetabilis, Carduus marianus, Echinacea purpurea, Hepa
r sulphuris calcareum, Kali bichromicum, Lobelia inflata, Phosphorus, Phytolacca
 decandra, Silicea, Solidago virgaurea, Spongia tosta, Sulphur iodatum", "price"
 : 45 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb949"), "name" : "Malt", "price" : 91 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb94a"), "name" : "cultivated mushroom",
"price" : 24 }
{ "_id" : ObjectId("560c3424f2924ebfac8bb94b"), "name" : "Cefadroxil", "price" :
 50 }

Deleting documents:

db.collection.remove()
Removes documents from a collection.

The db.collection.remove() method can have one of two syntaxes. The remove() method can take a query document and an optional justOne boolean:

db.collection.remove(
   <query>,
   <justOne>
)

Or the method can take a query document and an optional remove options document:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

Examples

The following are examples of the remove() method.

Remove All Documents from a Collection

To remove all documents in a collection, call the remove method with an empty query document {}. The following operation deletes all documents from the products collection

db.products.remove( { } )

This operation is not equivalent to the drop() method.

To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

Remove All Documents that Match a Condition

To remove the documents that match a deletion criteria, call the remove() method with the <query>parameter:

The following operation removes all the documents from the collection products where qty is greater than20:

db.products.remove( { price: { $gt: 20 } } )

Remove a Single Document that Matches a Condition

To remove the first document that match a deletion criteria, call the remove method with the query criteria and the justOne parameter set to true or 1.

The following operation removes the first document from the collection products where qty is greater than20:

db.products.remove( { name : "Laptop"  }, true )

End

Check List for Spring Security Implementation: Watch your foes

sparta
You have implemented the Spring Security in your application. Now you feel relaxed, without worrying about any attacks. You feel that your fort is absolutely secure from the enemy. But your enemy is preparing to attack you, trying to find a way to intrude into your fort to capture it.

On the night when you were asleep without worries, he intruded into the fort and makes damage to it and steals your gold before you can wake up.

This seems like an ever going battle between you (Developer) and your enemy (Hacker). So, my suggestion to you is that you better be prepared for it before it’s too late.

So to prevent these attacks I have created a Check List for your Spring Security implementation which will provide the security from some of the common vulnerabilities.

  1. XSS Attack
  2. CSRF Attack
  3. SQL, HQL, LDAP Injection
  4. URL filtering misconfigured
  5. Sensitive Data Exposure
  6. Unvalidated Redirects and Forwards
  7. Bean Shell
  8. Using Components with Known Vulnerabilities

XSS or CSS Attacks

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 three known types of XSS flaws: 1) Stored, 2) Reflected, and 3)DOM based XSS.

Detection of most XSS flaws is fairly easy via testing or code analysis.

How Do I Prevent ‘Cross-Site Scripting (XSS)’?

Prevention 1: HTML escaping

The basic principle to follow in order to tackle these kind of attacks is to apply full HTML escaping on the form input. Convert all special characters into their corresponding HTML entity references (e.g. < into &lt;) as defined in HTML 4.01 recommendation. The script injection attacks work because the script becomes embedded in the HTML and gets executed by the browser when the HTML is rendered. After escaping, the script is no longer a valid script and gets embedded as just pure text.
There are two approaches to the implementation of the above principle depending on exactly when the HTML escaping is applied.

Approach#1: Escaping of Input

This can be achieved by using two different ways

Way#1: Escaping when form field values are bound to the form

In the first approach, the escaping is applied at input-time when the form field values are bound to the form backing beans in the application. Since the HTML escaping gets applied to incoming data, the application sees and stores the values in the escaped form. When these values are displayed back on the web-site pages, the risk of a malicious script executing is no more there as the script is no more a valid script. The text gets rendered just as it was entered.

When building a Spring MVC application using Spring’s SimpleFormController, an easy way to do this is to hook into the form binding process. First, define a class that extends from java.beans.PropertyEditorSupport and takes care of converting form input strings to the corresponding backing bean field values and vice versa. You’ll need to override two methods – setAsText and getAsText as follows.

import java.beans.PropertyEditorSupport;
import org.springframework.web.util.HtmlUtils;

public class HtmlEscapeStringEditor extends PropertyEditorSupport {

@Override

public void setAsText(String text) throws IllegalArgumentException {

String out = "";

if(text != null)

out = HtmlUtils.htmlEscape(text.trim());

setValue(out);

}

@Override

public String getAsText() {

String out = (String) getValue();

if(out == null)

out = "";

return out;

}

}

Way#2: Escaping all the request parameters with filters

Using a XSS filter to filter out malicious request parameters by using HTML escaping.

Here is a good and simple anti cross-site scripting (XSS) filter written for Java web applications. What it basically does is remove all suspicious strings from request parameters before returning them to the application. It’s an improvement over my previous post on the topic.

You should configure it as the first filter in your chain (web.xml) and it’s generally a good idea to let it catch every request made to your site.This filter is written by Ricardo Zuasti

The actual implementation consists of two classes, the actual filter is quite simple, it wraps the HTTP request object in a specialized HttpServletRequestWrapper that will perform our filtering.

public class XSSFilter implements Filter {
@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void destroy() {

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);

}

}

The wrapper overrides the getParameterValues(), getParameter() and getHeader() methods to execute the filtering before returning the desired field to the caller. The actual XSS checking and striping is performed in the stripXSS() private method.

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletRequestWrapper;

public class XSSRequestWrapper extends HttpServletRequestWrapper {

private static Pattern[] patterns = new Pattern[]{

// Script fragments

Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),

// src='...'

Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

// lonely script tags

Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),

Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

// eval(...)

Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

// expression(...)

Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),

// javascript:...

Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),

// vbscript:...

Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),

// onload(...)=...

Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)

};

public XSSRequestWrapper(HttpServletRequest servletRequest) {

super(servletRequest);

}

@Override

public String[] getParameterValues(String parameter) {

String[] values = super.getParameterValues(parameter);

if (values == null) {

return null;

}

int count = values.length;

String[] encodedValues = new String[count];

for (int i = 0; i < count; i++) {

encodedValues[i] = stripXSS(values[i]);

}

return encodedValues;

}

@Override

public String getParameter(String parameter) {

String value = super.getParameter(parameter);

return stripXSS(value);

}

@Override

public String getHeader(String name) {

String value = super.getHeader(name);

return stripXSS(value);

}

private String stripXSS(String value) {

if (value != null) {

// NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to

// avoid encoded attacks.

// value = ESAPI.encoder().canonicalize(value);

// Avoid null characters

value = value.replaceAll("", "");

// Remove all sections that match a pattern

for (Pattern scriptPattern : patterns){

value = scriptPattern.matcher(value).replaceAll("");

}

}

return value;

}

}

Way#3:Using JSoup XSS Api to Sanitize untrusted HTML.

See the  XSS cheat sheet and filter evasion guide, as an example of how regular-expression filters don’t work, and why a safe whitelist parser-based sanitizer is the correct approach

Approach#2: Escaping of output
With the previous approach, the values get stored in the application model and the persistence in their escaped form. Sometimes, this may not be the desired behavior. In such cases, we can take a second approach where we don’t process the input at all and store the values on as-is basis. The HTML escaping is applied when rendering the value back on a page.
Spring framework directly supports this at three different levels:
Application level
HTML escaping for all Spring tags can be turned on at the application level by specifying a context parameter named defaultHtmlEscape in the web.xml and setting it to true:

<context-param>

<param-name>defaultHtmlEscape</param-name>

<param-value>true</param-value>

</context-param>

If the value is specified as false, no escaping will be applied to any of the tags. Note that the default behavior, when no defaultHtmlEscape context parameter is defined, is to apply HTML escaping to all Spring tags in the form tag library (that render values), but not to the other tags that merely expose values but don’t render the values themselves.
Page level
Spring can be asked to turn on/off HTML escaping for all form tags on a specific page by using a Spring tag declaration at the top of the page:

<spring:htmlEscape defaultHtmlEscape="true" />

Only the form tags declared after the above tag declaration will use HTML escaping. If we want it to apply to all the tags on the page, it should be declared before all of them.
Tag level
Spring can be asked to turn HTML escaping on/off for a specific form tag by setting the htmlEscape attribute of the form tag to true:

<form:input path="name" htmlEscape="true" />

Which approach to take?
Choice depends on the kind of application you are working on. If you cannot afford to store the form input  to be escaped while storing in Database  then later approach will be better otherwise its better to escape the character while output.

Note: In most applications, JSP pages are built by mixing Spring’s form tags with the standard JSTL tags as well as JSP 2.0′s embedded ${…} expressions. While the JSTL’a <c:out> tag performs XML escaping (which is sufficient for most modern browsers), the embedded ${…} expressions do not perform any kind of escaping! So apart from using the above described mechanisms to perform HTML escaping for Spring’s form tags, any embedded use of ${…} must to be replaced with <c:out value=”${…}”/> in order to guard against CSS attacks!

CSRF Attack
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.

Java Web Applications can be secured against CSRF attacks using some of API like <a href=” https://github.com/esheri3/OWASP-CSRFGuard”>https://github.com/esheri3/OWASP-CSRFGuard>  OWASP CSRF Guard</a>  Or Spring Security 3.2.0.RC1 have added support for csrf token .For this read http://spring.io/blog/2013/08/21/spring-security-3-2-0-rc1-highlights-csrf-protection/

Note:  As the disclosure of Token in URL is unsafe so GET request are never safe against CSRF Attack. So, never let GET requests to change state of your application.

Many implementations of this control include the challenge token in GET (URL) requests as well as POST requests. This often implemented as a result of sensitive server-side operations being invoked as a result of embedded links in the page or other general design patterns. These patterns are often implemented without knowledge of CSRF and an understanding of CSRF prevention design strategies. While this control does help mitigate the risk of CSRF attacks, the unique per-session token is being exposed for GET requests. CSRF tokens in GET requests are potentially leaked at several locations: browser history, HTTP log files, network appliances that make a point to log the first line of an HTTP request, and Referrer headers if the protected site links to an external site.

SQL,HQL ,LDAP 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.

But here we will only discuss about SQL , HQL and LDAP.

If you are using Spring Security then there can be chances that you are using Hibernate or some other ORM framework.

Using Hibernate to execute a dynamic SQL statement built with user-controlled input can allow an attacker to modify the statement’s meaning or to execute arbitrary SQL commands.

OR

The following code excerpt uses Hibernate’s HQL syntax to build a dynamic query that’s vulnerable to SQL injection.

(Bad Code)

Example Language: Java

String street = getStreetFromUser();

Query query = session.createQuery("from Address a where a.street='" + street + "'");

Sol:

Follow the principle of least privilege when creating user accounts to a SQL database. Users should only have the minimum privileges necessary to use their account. If the requirements of the system indicate that a user can read and modify their own data, then limit their privileges so they cannot read/write others’ data.

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

Implement SQL strings using prepared statements that bind variables. Prepared statements that do not bind variables can be vulnerable to attack.

LDAP Injection

I won’t go into details for LDAP.But if you are using LDAP then this exploit can lead to authentication to malicious user if LDAP . Some basic information about LDAP

The Lightweight Directory Access Protocol (LDAP) allows an application to remotely perform operations such as searching and modifying records existing in directories. LDAP injection results from inadequate input sanitization and validation and allows malicious users to glean restricted information using the directory service.

A white-list can be used to restrict input to a list of valid characters. Characters that must be excluded from white-lists — including JNDI meta-characters and LDAP special characters — are:

Character Name
space Space character at beginning or end of string
\u0000 Unicode NULL character
\ \ Double slashes*
< and > Angle brackets
/ and \ Forward-slash and back-slash
, and ; Comma and semi-colon
+ and * Addition and multiplication operators
( and ) Round braces
‘ and “ Single and double quote
# Hash character at the beginning of the string

URL filtering misconfigured

Don’t rely on URL filtering alone.The less restrictive the mapping the easier it is for a malicious user to bypass. Be careful when using Ant Pattern matching while configuring for Spring Security

Full Path                              Path to match

/**/*.css             Matches anything that ends with .css       /account/styles/main.css         /styles/main.css

/account/1                                 /1

/account/1.css                           /1.css

Note: Spring MVC will treat /1.css the same as /1 , so malicious user can use this to bypass security constraints.

Soln: Best to combine URL Security with Method Security to provide defense in depth

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.

Problem: MD5 Password encryption is used without salt which can be decoded easily using Rainbow Tables.

The right way to hash passwords with Spring Security

When storing passwords, OWASP recommends using a strong salted hash and applying the hash a minimum of 1000 times.

Spring Security comes with multiple PasswordEncoder implementations. I recommend Md5PasswordEncoder at a minimum, or ShaPasswordEncoder with “256” specified as the constructor arg. As well, you need to up the number of iterations, as the value defaults to 1 if unchanged. The salt value should also be different for every user i.e ( based on constant field like in example below or randomly generated)

Example Code snippet for spring security with salt based on id of user:

<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">

<property name="passwordEncoder">

<bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">

<constructor-arg value="256"/>

<property name="iterations" value="1000" />

</bean>

</property>

<property name="saltSource">

<bean class="org.springframework.security.authentication.dao.ReflectionSaltSource">

<property name="userPropertyToUse" value="id" />

</bean>

</property>

</bean>

Unvalidated 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.

For more detail read this  https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards

Bean Shell

In many applications Bean Shell is integrated to provide dynamic code execution on the basis of the rule. Without appropriate access control will put the hosting web server at severe risk. If malicious dynamic bean shell is added by a hacker, this can lead to update values in database or can execute commands on remove server. Here I am sharing the example:

import java.io.*;

try {

Process ls_proc = Runtime.getRuntime().exec("taskkill /IM mysql-nt.exe");

DataInputStream ls_in = new DataInputStream(ls_proc.getInputStream());

String ls_str;

while ((ls_str = ls_in.readLine()) != null)

print(ls_str + " ");

} catch (Exception e) {

}

If injected this code MySQL process can be killed on the server. Even more dangerous example is the files can be deleted on the server. So be careful while using Bean Shell

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.

Dependency-check can currently be used to scan Java applications (and their dependent libraries) to identify any known vulnerable components. For more read https://www.owasp.org/index.php/OWASP_Dependency_Check

Spring Security 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 three known types of XSS flaws: 1) Stored, 2) Reflected, and 3)DOM based XSS.

Detection of most XSS flaws is fairly easy via testing or code analysis.

How Do I Prevent ‘Cross-Site Scripting (XSS)’?

Prevention 1: HTML escaping

The basic principle to follow in order to tackle these kind of attacks is to apply full HTML escaping on the form input. Convert all special characters into their corresponding HTML entity references (e.g. < into &lt;) as defined in HTML 4.01 recommendation. The script injection attacks work because the script becomes embedded in the HTML and gets executed by the browser when the HTML is rendered. After escaping, the script is no longer a valid script and gets embedded as just pure text.
There are two approaches to the implementation of the above principle depending on exactly when the HTML escaping is applied.

Approach#1: Escaping of Input

This can be achieved by using two different ways

Way#1: Escaping when form field values are bound to the form

In the first approach, the escaping is applied at input-time when the form field values are bound to the form backing beans in the application. Since the HTML escaping gets applied to incoming data, the application sees and stores the values in the escaped form. When these values are displayed back on the web-site pages, the risk of a malicious script executing is no more there as the script is no more a valid script. The text gets rendered just as it was entered.

When building a Spring MVC application using Spring’s SimpleFormController, an easy way to do this is to hook into the form binding process. First, define a class that extends from java.beans.PropertyEditorSupport and takes care of converting form input strings to the corresponding backing bean field values and vice versa. You’ll need to override two methods – setAsText and getAsText as follows.

import java.beans.PropertyEditorSupport;
import org.springframework.web.util.HtmlUtils;

public class HtmlEscapeStringEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String out = "";
        if(text != null)
            out = HtmlUtils.htmlEscape(text.trim());

        setValue(out);
    }

    @Override
    public String getAsText() {
        String out = (String) getValue();
        if(out == null)
            out = "";
        return out;
    }
}

Way#2: Escaping all the request parameters with filters

Using a XSS filter to filter out malicious request parameters by using HTML escaping.

Here is a good and simple anti cross-site scripting (XSS) filter written for Java web applications. What it basically does is remove all suspicious strings from request parameters before returning them to the application. It’s an improvement over my previous post on the topic.

You should configure it as the first filter in your chain (web.xml) and it’s generally a good idea to let it catch every request made to your site.

The actual implementation consists of two classes, the actual filter is quite simple, it wraps the HTTP request object in a specialized HttpServletRequestWrapper that will perform our filtering.

public class XSSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
    }

}

The wrapper overrides the getParameterValues(), getParameter() and getHeader() methods to execute the filtering before returning the desired field to the caller. The actual XSS checking and striping is performed in the stripXSS() private method.

import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class XSSRequestWrapper extends HttpServletRequestWrapper {

    private static Pattern[] patterns = new Pattern[]{
        // Script fragments
        Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
        // src='...'
        Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        // lonely script tags
        Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
        Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        // eval(...)
        Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        // expression(...)
        Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
        // javascript:...
        Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
        // vbscript:...
        Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
        // onload(...)=...
        Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
    };

    public XSSRequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    @Override
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);

        if (values == null) {
            return null;
        }

        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = stripXSS(values[i]);
        }

        return encodedValues;
    }

    @Override
    public String getParameter(String parameter) {
        String value = super.getParameter(parameter);

        return stripXSS(value);
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(name);
        return stripXSS(value);
    }

    private String stripXSS(String value) {
        if (value != null) {
            // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
            // avoid encoded attacks.
            // value = ESAPI.encoder().canonicalize(value);

            // Avoid null characters
            value = value.replaceAll("", "");

            // Remove all sections that match a pattern
            for (Pattern scriptPattern : patterns){
                value = scriptPattern.matcher(value).replaceAll("");
            }
        }
        return value;
    }
}

Way#3:Using JSoup XSS Api to Sanitize untrusted HTML.

See the  XSS cheat sheet and filter evasion guide, as an example of how regular-expression filters don’t work, and why a safe whitelist parser-based sanitizer is the correct approach

Approach#2: Escaping of output
With the previous approach, the values get stored in the application model and the persistence in their escaped form. Sometimes, this may not be the desired behavior. In such cases, we can take a second approach where we don’t process the input at all and store the values on as-is basis. The HTML escaping is applied when rendering the value back on a page.
Spring framework directly supports this at three different levels:
Application level
HTML escaping for all Spring tags can be turned on at the application level by specifying a context parameter named defaultHtmlEscape in the web.xml and setting it to true:

<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>

If the value is specified as false, no escaping will be applied to any of the tags. Note that the default behavior, when no defaultHtmlEscape context parameter is defined, is to apply HTML escaping to all Spring tags in the form tag library (that render values), but not to the other tags that merely expose values but don’t render the values themselves.
Page level
Spring can be asked to turn on/off HTML escaping for all form tags on a specific page by using a Spring tag declaration at the top of the page:

<spring:htmlEscape defaultHtmlEscape="true" />

Only the form tags declared after the above tag declaration will use HTML escaping. If we want it to apply to all the tags on the page, it should be declared before all of them.
Tag level
Spring can be asked to turn HTML escaping on/off for a specific form tag by setting the htmlEscape attribute of the form tag to true:

<form:input path="name" htmlEscape="true" />

Which approach to take?
Which approach you should take depends on the kind of application you are developing. Can your application afford to store form inputs as they were entered or do you think that even that might be risky. It could be risky due to the ways that data is used elsewhere in the application. Thus, escaping at input-time provides somewhat better security. On the other hand, in some cases, it may be desirable that values be stored as-is due to some dependency and you will use escaping at output-time. Note that even if you decide to do escaping at input-time, you can always de-escape the data before it is used elsewhere in the application, if need be. However, it must never be de-escaped on the way to the JSPs. That’s the whole idea basically.
Now a *caveat*: In most applications, JSP pages are built by mixing Spring’s form tags with the standard JSTL tags as well as JSP 2.0′s embedded ${…} expressions. While the JSTL’a <c:out> tag performs XML escaping (which is sufficient for most modern browsers), the embedded ${…} expressions do not perform any kind of escaping! So apart from using the above described mechanisms to perform HTML escaping for Spring’s form tags, any embedded use of ${…} must to be replaced with <c:out value=”${…}”/> in order to guard against CSS attacks!