Tag Archives: Security

HTTPS – the first line of defence

In today’s world when our online interactions are increasing every day, the security of our online transactions becomes very important. If you are an end-user to a website that is required to handle important financial or informational transactions like bank sites, eCommerce sites, email sites, etc, the very basic thing you should check is that protocol for the transaction being used is HTTPS. HTTPS stands for HyperText Transfer Protocol Secure, or Secure appended at the end of the HTTP protocol. For example, if you are using a chrome browser you can see a symbol of a lock at the start of the website name in the address bar indicating the site uses HTTPS. If you click on the lock symbol you will see more details about the certificate provided by the website claiming that it is secure.

Let’s try to understand how HTTPS works.

Step 1: Browser sends a request for an https secured page, like https://google.com

Step 2: The website will need to send back an SSL certificate confirming that it is secured. SSL certificate is provided by certifying authorities like Godaddy which can be verified by the browser. Along with the certificate, the website would send the browser its public key.

Step 3: Once the browser receives the certificate and public key from the website, it will authenticate the certificate, and if satisfied, it will use the public key from the browser to create a symmetric key.

Step 4: The browser generates a symmetric key, encrypts it using the public key provided by the website server and sends it back to the server. The web server receives the encrypted symmetric key, decrypts it using its private key.

Step 5: For any further communication, the server and the browser both use this symmetric key.

Now to understand the concept completely we need to understand how public-private key encryption is different from symmetric key encryption. In the case of symmetric key encryption, the key that encrypts the message can be used to decrypt the message. Whereas in the case of Public key – Private Key encryption, a message encrypted by Public key can only be decrypted by the private key. Symmetric key encryption is faster but not as secured as public-private key encryption.

If you are interested in understanding how each step mentioned above assures security in communication, read on.

Let’s look at each step and try to understand how each step is secured.

Step 1: The browser is just sending a request for website contents at this point, the actual transfer of information is not started.

Step 2: The server is only sharing its public key in this step, so not worried about security.

Step 3: Browser decrypts the SSL certificate which needs to be provided by an authorized Certification Authority (CA). The browsers come packaged with details of all major CAs and can validate the certificate against its local cache or can confirm with the certification authority. Browser matches the URL being addressed and the certificate received, this way it makes sure that no fake website or server is trying to send the data.

Step 4: The browser has encrypted the symmetric key with the public key provided by the server. So in case even if the packet is compromised and received by a fake server, it will not be able to decrypt the message as only the original server has the private key.

Step 5: By this step, only the browser and the intended server have the symmetric key. Any communication happening can be decrypted by only these two parties, so even if there is a leak, the message content remains safe.

How to check if a port is open on a server?

I wanted to check if the service I am trying to access on a server is actually listening on the port I am hitting. I tried to look for a ping variant which could tell me if the port is listening and required service is up and running.

Found nmap command as answer.

nmap -p 80 google.com

Starting Nmap 6.40 ( http://nmap.org ) at 2016-03-02 16:05 IST
Nmap scan report for google.com (216.58.197.78)
Host is up (0.050s latency).
rDNS record for 216.58.197.78: maa03s21-in-f14.1e100.net
PORT STATE SERVICE
80/tcp open http

It checks the port state and also what service is listening at the port.

Spring Security- with Java Configuration

Recently I wrote about getting started with Spring Security. In that, I used XML configurations for spring security. As a Java developer, I normally prefer Java configuration with Spring than XML. So here is how we can move from XML configuration to Java configuration.

Firstly I tell my web.xml that I want to use Java file based configuration and provide configuration class.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>javaee</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.myapp.config.MyConfig</param-value>
    </context-param>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.myapp.config.MyConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>

</web-app>

Here is a simple contoller path which I need to secure

package com.myapp.test;

import java.io.IOException;

import javax.servlet.ServletException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/sample")
public class SampleService {
	@RequestMapping(method = RequestMethod.GET, value = "/hello")
	public ModelAndView LepService(@PathVariable("id") String id)
			throws ServletException, IOException {

		ModelAndView mv = new ModelAndView("hello");
		// Do something here
		return mv;
	}
}

As you can see this simply redirects to hello view (hello.jsp).

And here the configuration file.

@Configuration
@EnableWebMvc
@EnableWebSecurity
@ComponentScan(basePackages = "com.myapp.test")
public class MyConfig extends WebSecurityConfigurerAdapter {

	@Bean
	public UrlBasedViewResolver urlBasedViewResolver() {
		UrlBasedViewResolver res = new InternalResourceViewResolver();
		res.setViewClass(JstlView.class);
		res.setPrefix("/WEB-INF/");
		res.setSuffix(".jsp");

		return res;
	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		web.ignoring().antMatchers("/resources/**");
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.inMemoryAuthentication().withUser("user").password("password")
				.roles("USER");
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").permitAll()
				.antMatchers("/sample/**").hasRole("USER").anyRequest().authenticated()
				.and().formLogin();
	}
}

Spring Security- Getting started

In last post I wrote about implementing a simple authentication and authorization code using filters to provide security to your web application.

Well, Spring security is there to make our life easier.

Lets take a very simple example of hello world application.

Simply create a new web application (in eclipse dynamic web application, cover to maven application to use maven).

Modify Web.xml

<servlet>
<servlet-name>controlServlet</servlet-name>
<servlet-class>com.spring.test.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>controlServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

And create HelloWorld.java

package com.spring.test;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet (urlPatterns ={"/hello" } )
public class HelloWorld extends HttpServlet {

@Override
public void doGet (HttpServletRequest request , HttpServletResponse response){
try {
response.getWriter( ).write( "Hello World" ) ;
} catch(IOException e) {
e.printStackTrace( ) ;
}
}
}

Only dependency added to maven

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>

Build using maven and execute on any webserver. The /hello url will show a Hello World Message.

Lets add some security to this application now using Spring Security.

Tell your maven about Spring Jars

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

Add to web.xml

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

And create spring-security.xml inside WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/hello" access="ROLE_ADMIN" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_ADMIN" name="kamal" password="kamal" />
<security:user authorities="ROLE_ADMIN" name="admin" password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>

Web Application Security- Authorization and Authentication

For any web application, 2 type of checks are very important.

Authentication: Is this the right user? Can he access the system? Does he has right credentials?

Authorization: Now we know that user has access to the system, but does he has access to given resource. For example, a normal user should not be able to add or delete another user from the system, only admin (has authority) should be able to do this.

How can we implement Authorization and Authentication checks in Java?

The answer is through filters. Actually you can add checks in your controllers of inside the application, but it is easier to implement url based Authentication through filters.

For authentication, it is easier. Just add a filter on any incoming request, and inside the filter check if a valid session is set for the user (Assuming that we set a session for user as soon as he logs in).

<filter-mapping>
        <filter-name>AuthenticationFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping> 

 

In AutheticationFilter (Assuming you are setting session “user”)

//add a check somewhere 
// Getting the current user information
		MyUser myUser = (MyUser) session.getAttribute("user");

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

One we have authenticated the user, we need to know if the user is actually authorized to do the action he has requested. In this case we will tackle this through url being triggered by user and validate if the user has access to the url.

<filter-mapping>
            <filter-name>AuthorizationFilter</filter-name>
            <url-pattern>/admin/*</url-pattern>
        </filter-mapping>

Any url that starts with /admin, will need to get authorized through this. Now similar to AuthenticationFilter, my authorization filter will first read user from session, then fetch role for user. You will need to keep a mapping of roles that have a permission for a url. Or you can add it to web.xml where you are defining AuthorizationFilter.

<filter>
        <filter-name>AuthorizationFilter</filter-name>
        <filter-class>com.test.filters.AuthorizationFilter</filter-class>
        <init-param>
            <param-name>rolesAllowed</param-name>
            <param-value>ADMIN, SUPERADMIN</param-value>
        </init-param>
    </filter>

Controlling System Access with IPTables

There might be times when you want to control outgoing or incoming traffic from a linux machine. Iptables is answer to that.

To check current settings

sudo iptables -L

To Add a rule

iptables -A OUTPUT -p tcp –dport 8000 -j DROP

Lets get into details

iptables: command

-A: Add the rule

OUTPUT: Type of rule, OUTPUT or INPUT

-p: protocol tcp/ udp

–dport: port number (8000 here)

-j: DROP or ACCEPT

So Above command tell system to not allow any outgoing traffic on port 8000.

iptables -A OUTPUT -p tcp –dport 1935 -s 1.2.1.0 -j ACCEPT

-s: source

-d: destination

The above rule states to allow outgoing packets on port 1935 to a specific IP.

If we have centos based system

Edit rules

sudo vi /etc/sysconfig/iptables

Restart

sudo /etc/init.d/iptables restart

Core Dump files slowing down website

For last few days, or rather weeks, my blog was really slow. Infact the site was throwing resource limit error at times. I contacted my webhosting provider, but they just replied they cannot find anything. So I decided to do some investigation on my own.

First step was to check memory and CPU usage, which turned out to be very high, almost 100%. The fishy thing I figured out was disk space usage, which was way above data I have, so I checked the file system. I figured out hundreds of core.XXXXX files. A little googling showed that these were dump files created by Apache for memory dump, in case some error / crash occured. Deleting these extra files did solve the issue.

More info on the topic

https://wordpress.org/support/topic/hacked-with-strange-core-files

https://wordpress.org/support/topic/arrrg-so-many-core-files

http://en.wikipedia.org/wiki/Core_dump

Getting rid of Babylon virus

Well, it is not exactly a virus, but babylon plugin can impose itself on your browser in form of search toolbars or default search setting. It has happened to me more than once now, so sharing some quick steps of getting rid of it here. Please note that at times this app/ toolbar will be stored as any other name, so look out for anything suspicious and out of place.

1. Remove the app: Check if a program is shown under add/ remove program (go to control panel-> uninstall program) with name babylon. Remove it.

2. Remove toolbar: Check if toolbar exists under browser toolbars, and remove it.

Firefox: Go to Add Ons->look for babylon

IE: Go to Manage Add Ons->Toolbars and extensions->look for babylon

3. Remove as default search engine: For IE Manage Add Ons-> Search providers->babylon (in my case it was named just default)

More info www.pcmag.com/article2/0,2817,2418379,00.asp