Category Archives: Security

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

Are my online transactions secured? HTTPS to rescue

You must have wondered at times that how can my data be secured over the internet when using a website that needs sensitive data like bank account details (or how secured is a banking site).

The protocol that comes to rescue is HTTPS. Whenever we are working on a website where we want ourselves to be secure, we should make sure the url starts with https://www.mysite.com instead of http. http is hyper text transfer protocol which just specifies some rules as to how the data needs to be transferred and understood on the internet. https is http + secure or http over SSL (Secured socket layer).

If I ask you, how can I secure the data? The obvious answer is encryption. The most common type of encryption is symmetric encryption which uses a single key to encrypt and decrypt the data. That is the same key that encrypts the data will decrypt it. The problem with this kind of encryption is that if someone gets access to this key, he can create or read the data using the key. To solve this problem, there is concept of 2 key encryption. In this we have a private and public key. the beauty of this approach is that data encrypted using one key can be decrypted using second key only. On the downside this approach is a bit slow because of added complexity.

Lets quickly talk about concept of certificates as well. There are various certification authorities (CA) which can provide a certificate of authentication to a website. Whenever you are on a https website, you will see a small icon of a lock (may vary from browser to browser), on which when you click, will show you the certificate details. This will guarantee that the website is indeed what it claims to be. So for example you misspelt a link or opened a link from a spam email, looking for https and certificate will be sufficient for you to ensure authenticity of the website.

Now lets go behind the scenes and see how my websites are secured because of https.

Step 1: You click a secured url or type into your browser.

Step 2: The server listens to your request and returns back a certificate and a public key (server will never share the private key for security reasons)

Step 3: Your browser will verify this certificate (shows error in case of some doubt)

Step 3a: After verifying certificate, browser will generate a symmetric key and encrypt it using “the public key” sent by server.

Step 3b: Browser then sends this encrypted symmetric key to web server.

Step 4: Web server decrypts the data sent by browser using its private key (as this was encrypted using public key). The decrypted data is symmetric key from browser.

Step 5: Now this symmetric key will be used by both parties (browser and web server) to transfer the data (remember public/ private key is time consuming, so it is used only to initially transfer the symmetric key).

The above steps ensure that the communication between server and browser is always secured and hence you can do the online shopping or banking without fear.