I know that I know nothing

https test using certificate & keystore

clock June 13, 2014 20:58 by author Administrator





public class HttpsTest {
    public static void main(String[] args) {
        System.setProperty("", "pass");

        // full log for debugging
        System.setProperty("", "all");

        try {
            try {
                            public boolean verify(String hostname,
                           sslSession) {
                                if (hostname.equals("ansarrootca")) {
                                    return true;
                                return false;
                URL url = new URL("https://site:3443");
                InputStream is = url.openStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                String inputLine = null;
                while ((inputLine = in.readLine()) != null)
            } catch (MalformedURLException e) {

        } catch (Exception e) {


using keystore & trust store in java

clock June 13, 2014 20:51 by author Administrator


add this code for run application that use  keystore


System.setProperty("", "pass");
System.setProperty("", "all");




disable java check for subject alternative names in certificate

clock June 13, 2014 20:41 by author Administrator

when i want to invoke https webservice by certificate(keystore.jks) .

i get this exception No subject alternative names present

ip of webservice is but certificate is created for

java check this in client and throw this exception 

i add host for  in my os and add this line in application

this code disable this check
                    public boolean verify(String hostname,
                   sslSession) {
                        if (hostname.equals("azizkhanihost")) {
                            return true;
                        return false;


Import PKCS12 private keys into JKS keystores using Java Keytool

clock June 8, 2014 20:31 by author Administrator
  1. Create an empty JKS store
    keytool -genkey -alias alice -keystore alice.jks
    keytool -delete -alias alice -keystore alice.jks
  2. Import alice.p12 into alice.jks
    keytool -v -importkeystore -srckeystore alice.p12 -srcstoretype PKCS12 
    -destkeystore truststore.jks -deststoretype JKS

managing and examining keystores by (Portecle software)

clock June 8, 2014 20:24 by author Administrator

Portecle is a user friendly GUI application for creating, managing and examining keystores, keys, certificates, certificate requests, certificate revocation lists and more.

  • Create, load, save, and convert keystores.
  • Generate DSA and RSA key pair entries with self-signed version 1 X.509 certificates.
  • Import X.509 certificate files as trusted certificates.
  • Import key pairs from PKCS #12 and PEM bundle files.
  • Clone and change the password of key pair entries and keystores.
  • View the details of certificates contained within keystore entries, certificate files, and SSL/TLS connections.
  • Export keystore entries in a variety of formats.
  • Generate and view certification requests (CSRs).
  • Import Certificate Authority (CA) replies.
  • Change the password of key pair entries and keystores.
  • Delete, clone, and rename keystore entries.
  • View the details of certificate revocation list (CRL) files.

create trustStore from .cert file

clock June 8, 2014 20:09 by author Administrator


keytool -import -file C:\certificate.cert -alias firstCA -keystore myTrustStore


Cross-Site Request Forgery (CSRF)

clock February 5, 2013 23:26 by author Administrator

Nowadays, web application security is one of the most important issues in the information system development process. According to Gartner [1] the 75% of the attacks performed nowadays are aimed to web applications, because operative system security and net level security have increased considerably. As a result, it is considered that the 95% of the web applications are vulnerable to a certain type of attack [2]. In the following chart we can see the list of the most important vulnerabilities published by OWASP (Open Web Application Security Project)


Cross-site request forgery, also known as one click attack or session riding and abbreviated as CSRF (Sea-Surf) or XSRF, is a type of malicious exploit of websites. Although this type of attack has similarities to cross-site scripting (XSS), cross-site scripting requires the attacker to inject unauthorized code into a website, while cross-site request forgery merely transmits unauthorized commands from a user the website trusts.

The attack works by including a link or script in a page that accesses a site to which the user is known (or is supposed) to have authenticated.

Example: One user, Bob, might be browsing a chat forum where another user, Mallory, has posted a message. Suppose that Mallory has crafted an HTML image element that references a script on Bob's bank's website (rather than an image file), e.g.,


If Bob's bank keeps his authentication information in a cookie, and if the cookie hasn't expired, then Bob's browser's attempt to load the image will submit the withdrawal form with his cookie, thus authorizing a transaction without Bob's approval.

A cross-site request forgery is a confused deputy attack against a Web browser. The deputy in the bank example is Bob's Web browser which is confused into misusing Bob's authority at Mallory's direction.

The following characteristics are common to CSRF:

  • Involve sites that rely on a user's identity
  • Exploit the site's trust in that identity
  • Trick the user's browser into sending HTTP requests to a target site
  • Involve HTTP requests that have side effects

At risk are web applications that perform actions based on input from trusted and authenticated users without requiring the user to authorize the specific action. A user that is authenticated by a cookie saved in his web browser could unknowingly send an HTTP request to a site that trusts him and thereby cause an unwanted action.

CSRF attacks using images are often made from Internet forums, where users are allowed to post images but not JavaScript.


This attack relies on a few assumptions:

  • The attacker has knowledge of sites the victim has current authentication on (more common on web forums, where this attack is most common)
  • The attacker's "target site" has persistent authentication cookies, or the victim has a current session cookie with the target site
  • The "target site" doesn't have secondary authentication for actions (such as form tokens)

While having potential for harm, the effect is mitigated by the attacker's need to "know his audience" such that he attacks a small familiar community of victims, or a more common "target site" has poorly implemented authentication systems (for instance, if a common book reseller offers 'instant' purchases without re-authentication).


Applications must ensure that they are not relying on credentials or tokens that are automatically submitted by browsers. The only solution is to use a custom token that the browser will not ‘remember’ and then automatically include with a CSRF attack.

The following strategies should be inherent in all web applications:

  • Ensure that there are no XSS vulnerabilities in your application.
  • Insert custom random tokens into every form and URL that will not be automatically submitted by the browser. For example,

    CSRF protection

    and then verify that the submitted token is correct for the current user. Such tokens can be unique to that particular function or page for that user, or simply unique to the overall session. The more focused the token is to a particular function and/or particular set of data, the stronger the protection will be, but the more complicated it will be to construct and maintain.

  • For sensitive data or value transactions, re-authenticate or use transaction signing to ensure that the request is genuine. Set up external mechanisms such as e-mail or phone contact in order to verify requests or notify the user of the request.

  • Do not use GET requests (URLs) for sensitive data or to perform value transactions. Use only POST methods when processing sensitive data from the user. However, the URL may contain the random token as this creates a unique URL, which makes CSRF almost impossible to perform.

  • POST alone is insufficient a protection. You must also combine it with random tokens, out of band authentication or re-authentication to properly protect against CSRF.

While these suggestions will diminish your exposure dramatically, advanced CSRF attacks can bypass many of these restrictions. The strongest technique is the use of unique tokens, and eliminating all XSS vulnerabilities in your application.

It should be noted that preventing CSRF requires that all XSS problems are removed first. An XSS flaw can be used to retrieve the form, then grab the random tokens before submitting the CSRF request. XSS may also be able to spoof the user into entering their credentials, which would allow the CSRF to bypass re-authentication as well.

CSRF has been called the "sleeping giant" of web application security flaws, because it has yet to be exploited widely. It is only a matter of time, web programmers should be making the changes needed to ensure that their sites are not vulnerable.




and now ......    :D

Simple Cross Site Scripting (XSS) Servlet Filter

clock January 12, 2013 16:42 by author Administrator

Ran into some issues on some of our Java sites today and needed a quick fix to protect the sites from malicious Cross Site Scripting (XSS) attempts. If you're not aware of what XSS is and have websites that have sensitive user data, you may want to read up, you're probably vulnerable, which means your users are vulnerable. I'm not claiming this is a perfect solution, but it was easy to implement and corrected the vulnerabilities with form and url injection. We basically have a Servlet Filter that's going to intercept every request sent to the web application and then we use an HttpServletRequestWrapper to wrap and override the getParameter methods and clean any potential script injection.

Here's the Filter:

package com.greatwebguy.filter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class CrossScriptingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    public void destroy() {
        this.filterConfig = null;
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);

Here's the wrapper:


package com.greatwebguy.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public final class RequestWrapper extends HttpServletRequestWrapper {
    public RequestWrapper(HttpServletRequest servletRequest) {
    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] = cleanXSS(values[i]);
      return encodedValues;
    public String getParameter(String parameter) {
          String value = super.getParameter(parameter);
          if (value == null) {
                 return null;
          return cleanXSS(value);
    public String getHeader(String name) {
        String value = super.getHeader(name);
        if (value == null)
            return null;
        return cleanXSS(value);
    private String cleanXSS(String value) {
                //You'll need to remove the spaces from the html entities below
        value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
        value = value.replaceAll("script", "");
        return value;


Add this to the top of your web.xml:


I'm sure the cleanXSS replacements aren't the most efficient way of doing this, you could replace it StringEscapeUtils.escapeHtml from commons lang to simplify it a little, it's up to you, it all depends on what your site is doing and whether it's going to be a pain having all the html escaped, you could also adjust the url-pattern of the filter to be more specific to your application urls, so that everything under your app isn't running through the filter.

Some things to be aware of with this approach, you'll need to account for what you've encoded or in some cases you'll end up with weird characters in your database and possibly in validation of your input boxes. Some would recommend a more positive validation rather than negative validation and only allow a certain range of characters, it's up to you, but it is something to think about.



retrieve currently logged-in users using the SessionRegistry

clock December 28, 2012 17:04 by author Administrator


clock October 25, 2012 19:21 by author Administrator


here might be special rows in a database which should only visible and accessible by users with special privileges. To avoid unnecessary round-trips, we currently modify the SQL queries to join with our authorization data to get only the visible rows for the current user.

But this concepts doesn't feel 'right' to me, because we mix business code with security related code which should be orthogonal and independent from each other.


  • What solutions are available/possible?
  • How do you implement row-level security (especially in combination with hibernate)?

The idea is that you can implement row level functionality in two ways: directly setting restrictions in your repository or binding the restrictions via AOP. The latter is preferred because security layer should be separated from business logic (orthogonal concerns).


In Hibernate you can use the concept of filters which are applied transparently and repository doesn't know about them. You can add such filters via AOP. The other way is intercepting session.createCriteria() and adding Restrictions to the Criteria transparently using AOP.


About the author

 Welcome to this web site . This page has two purposes: Sharing information about my professional life such as articles, presentations, etc.
This website is also a place where I would like to share content I enjoy with the rest of the world. Feel free to take a look around, read my blog

Java,J2EE,Spring Framework,JQuery,

Hibernate,NoSql,Cloud,SOA,Rest WebService and Web Stack tech...


Month List

Sign In