Posts belonging to Category Tutorials



Security using AspectJ

Security using AspectJ

Today I will explain how I will be using AspectJ for security in my Ozkey Photo Album.
If you don’t know what aspects are I recommend you read about Aspect Oriented Programming first.

To explain why and how I will use aspects for security first I need to explain what ZK framework is and how the ZK framework actually works. In a nutshell ZK is the leading open source Ajax framework and in it’s core it has an event-driven engine. I will use a simple example to illustrate how it works.

We create the user interface a bit like HTML (but it is not HTML)

<?page title="Login" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="Login" border="normal" width="400px" apply="security.LoginFowardComposer">
    <grid>
        <rows>
            <row>Login: <textbox id="login"/></row>
            <row>Password: <textbox id="password"/></row>
        </rows>
    </grid>
    <button label="Login" id="loginBTN" />
    <button label="Send money" id="sendMoneyBTN" />
</window>
</zk>

This is how it will look like

We then implement the “LoginFowardComposer” that extends the ZK “GenericForwardComposer”. This Class will be responsible for the definition and registration of the event listener for the “Login” and “Send money” button.

package security;
import ...

public class LoginFowardComposer  extends GenericForwardComposer{
    private static final long serialVersionUID = 1L;
    private Textbox login;
    private Textbox password;
    private Button loginBTN;
    private Label sendMoneyBTN;

    public void onClick$loginBTN(Event event) throws Exception{
    	//check login and set the user
    	System.out.println("Login");
    }

    public void onClick$sendMoneyBTN(Event event) throws Exception{
    	// Send the money
    	System.out.println("$$$ send money $$$");
    }
}

As you can see the there is nothing stopping the user from pressing the “send money” button at the moment. The correct thing to do would be to only enable the button after the user has logged in but in some cases disabling the button only looks like the function is disabled but the listener is still listening for the event so a hacker could send an Ajax request and trigger the event so we want to enforce security using aspects.

I will also use annotations so that we defined what events require no security e.g. login and what events require an “admin” role or an “owner” role.

Below is the enum for security roles:

public enum Role {ADMIN,OWNER,PUBLIC,MEMBER,NONE}

Below is the annotation interface that we will use to specify what role is needed for the event:

package security.aspect;

import java.lang.annotation.*; 

public interface Security {
	@Retention(RetentionPolicy.RUNTIME)
	public @interface SecurityCheck {
		Role level();
	}
}

Now that we defined the roles and the annotation interface we can annotate each method in the login composer with the new annotations.

package security;
import ...

public class LoginFowardComposer  extends GenericForwardComposer{

    private static final long serialVersionUID = 1L;
    private Textbox login;
    private Textbox password;
    private Button loginBTN;
    private Label sendMoneyBTN;

    @SecurityCheck(level=Role.NONE)
    public void onClick$loginBTN(Event event) throws Exception{
    	//check login and set the user's role
    	if(login.getValue().equalsIgnoreCase(password.getValue())){
    		Sessions.getCurrent().setAttribute("ROLE",Role.OWNER);
    	}

    }

    @SecurityCheck(level=Role.OWNER)
    public void onClick$sendMoneyBTN(Event event) throws Exception{
    	// Send the money
    	System.out.println("$$$ send money $$$");
    }
}

As you can see the login event requires no security and once you login it assigns you a role. in this example you are assigned the “OWNER” role. this role needs to be checked for the “sendMoney” event and this check will be done in an aspect.

Below is the aspects that will enforce the security defined in the annotation.

	pointcut checkSecurityLevel(security.aspect.Security.SecurityCheck annotation ):
		execution(@SecurityCheck * *..*(..)) &&
		@annotation(annotation);

	void around( security.aspect.Security.SecurityCheck annotation):
		checkSecurityLevel(annotation){
		Role role = (Role) Sessions.getCurrent().getAttribute("ROLE");
		if(role==null)role=Role.NONE;
		System.out.println(">level Required:"+annotation.level());
		System.out.println(">level actual:" + role.toString() );

		if(Role.NONE.toString().equalsIgnoreCase(annotation.level().toString())){
			proceed(annotation);
		}else{
			if(role== annotation.level()){
				System.out.println("LOGIN TRUE");
				proceed(annotation);
			}else{
				System.out.println("LOGIN FALSE");
			}
		}

As you can see above unless your ROLE is the same as the role needed the code will not execute. the problem with this method is that in the future a developer who does not know about how all this works could write a new event and not put a security annotation.

Security using AspecJ

Today I will explain how I will be using AspecJ for security in my Ozkey Photo Album.

If you don’t know what aspects are I recommend you read about Aspect Oriented Programming http://ozkey.com/notes/2010/aop101/ first.

To explain why and how I will use aspects for security first I need to explain what ZK framework is and how the ZK framework actually works. In a nutshell ZK is the leading open source Ajax framework and in it’s core it has an event-driven engine. I will use a simple example to illustrate how it works.

We create the user interface a bit like HTML (but it is not HTML)

<?page title=”Login” contentType=”text/html;charset=UTF-8″?>

<zk>

<window title=“Login” border=“normal” width=“300px” apply=“security.LoginFowardComposer”>

<grid>

<rows>

<row>Login: <textbox id=“login”/></row>

<row>Password: <textbox id=“password”/></row>

</rows>

</grid>

<button label=“Login” id=“loginBTN” />

<button label=“Show me the money” id=“showMoneyBTN” />

</window>

</zk>

We then implement the “LoginFowardComposer” that extends the ZK “GenericForwardComposer”. This Class will be responsible for the definition and registration of the event listener.

As you can see the there is nothing stopping the user from pressing the “send money” button at the moment. The correct thing to do would be to only enable the button after the user has logged in but in some cases disabling the button only looks like the function is disabled but the listener is still listening for the event so a hacker could send an Ajax request and trigger the event so we want to enforce security using aspects.

I will also use annotations so that we defined what events require no security e.g. login and what events require an “admin” role or an “owner” role.

Below is the enum for security roles:

Below is the annotation interface:

Below is the login composer with the new annotations.

Below is the aspects that will enforce the security defined in the annotation

the problem with this method is that in the future a developer who does not know about how all this works could write a new event and not put a security annotation.

AOP102 – AspectJ

In our previous post we showed how to insert additional logging using Apects. In this example we will expand the previous example by using annotations to log additional information about the method.

First we will define our annotation (Download source code).

package com.ozkey.aop;
import java.lang.annotation.*; 

@Retention(RetentionPolicy.RUNTIME)
public @interface LogMe {
	String info();
}

Now we can attach some extra information to our methods using the annotation the code is as follows (Download source code):

package com.ozkey.aop;

public class App {

	public static void main(String[] args) {
		App myApp = new App();
		int result = myApp.add(myApp.getRandomNumber() , myApp.getRandomNumber());
		System.out.println("Result:"+result);
	}

	@LogMe(info="Geting a random number")
	public int getRandomNumber(){
		return (new java.util.Random()).nextInt(10)	;
	}
	@LogMe(info="Add numbers")
	public int add(int a,int b){

		return a+b;

	}
}

The point cut is the execution of any method that uses the @LogMe annotation (Download source code)

pointcut LogMePointCut(): execution(@LogMe * com.ozkey.aop..*(..));

The Advice looks for the annotation to log the information (Download source code).

Object around(): LogMePointCut(){
		LogMe logMe = null;
		MethodSignature methodSignature = ((MethodSignature)  thisJoinPointStaticPart.getSignature());
		Annotation[] annotations = methodSignature.getMethod().getAnnotations();
		for(int i=0 ; i < annotations.length ; i++){
			if (annotations[0] instanceof LogMe) {
				logMe = (LogMe) annotations[0];
			}
		}
		Object obj = proceed();
		if(obj!= null &&logMe!=null)	{
			System.out.println("+	info:" + logMe.info()+":" + obj.toString());
		}

		return obj;
	}

The output

+	info:Geting a random number:1
+	info:Geting a random number:8
+	info:Add numbers:9

(Download source code)

AOP101 – AspectJ

“We can view a complex software system as a combined implementation of multiple concerns. A typical system may consist of several kinds of concerns, including business logic, performance, data persistence, logging and debugging, authentication, security, multithread safety, error checking, and so on.” 1

Aspect Oriented Programming (AOP) Isolates secondary or supporting functions from the main program’s business logic by allowing the separation of cross-cutting concerns.

Terminology used in Aspect-oriented programming:

  • Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
  • Join points: Points in a running program where additional behaviour can be usefully joined (like method call, object instantiation, or variable access).
  • Pointcut: The specific join points determined by an expression where additional behaviour needs to be applied.
  • Advice: This is the additional code that you want to code to run at a join point matched by a pointcut. The actions can be performed before, after, or around  the specified join point
  • Aspect: The combination of the pointcut and the advice is termed an aspect.

The most common example is the use of an Aspect for logging. I will show how Aspects, joinpoints, pointcuts, and advices come together to achieve this:
The example code below function is to get two random numbers and add them (Download source code). The result is then displayed. If we want to know what the original two random numbers are then we will have to add some extra logging.

package com.ozkey.aop;

public class App {

	public static void main(String[] args) {
		App myApp = new App();
		int result = myApp.add(myApp.getRandomNumber() , myApp.getRandomNumber());
		System.out.println("Result:"+result);
	}

	public int getRandomNumber(){
		return (new java.util.Random()).nextInt(10)	;
	}
	public int add(int a,int b){
		return a+b;
	}
}

The application output is

Result:6

Fist we define where we need to add extra logging. There are a few places where we could insert additional code. this points are called “joint points” (for example: method call, object instantiation, or variable access) but to keep it close to our goal and simple we will define or “point cut” as the join points of execution of any public method call with in our app and we will call this point cut “publicMethods”. The point cut expression is as follows:

pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

Now we can inset additional code “before” and “after” every joint point defined in our point cut. This additional code is called “advice”. The combination of the pointcut and the advice is termed an aspect. Below is what our aspect looks like (Download source code):

package com.ozkey.aop;

public aspect LogitAspect {

	pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

	before() : publicMethods(){
		/* before advice (additional code) */
	}
	after() : publicMethods(){
		/* after advice (additional code) */
	}
}

Since our goal is to log the two random numbers generated we will log value being returned but we might also want to log the arguments being passed to the methods calls to find if the correct arguments are being passed. The before advice will log the arguments being passed and the “after” advice will log the object being returned (Download source code).

package com.ozkey.aop;

public aspect LogitAspect {

	pointcut publicMethods() : execution(public * com.ozkey.aop..*(..));

	before() : publicMethods(){
		/*before advice (additional code)*/
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(">	Class:" + thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
		System.out.println(">	Method:" + thisJoinPointStaticPart.getSignature().getName());

		Object[] args = thisJoinPoint.getArgs();
		for(int i = 0; i<args.length;i++){
			System.out.println(">	Arg" +i + ":" + args[i].toString() );
		}
		System.out.println(">	");
	}
	after() returning (Object obj):  publicMethods(){
		/* after advice (additional code) */
		if(obj!=null)
			System.out.println("<	Returned:" + obj.toString());
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
	}
}

The application’s output should look like the lines below:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:main
>	Arg0:[Ljava.lang.String;@6ca1c
>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:getRandomNumber
>
<	Returned:2
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:getRandomNumber
>
<	Returned:3
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>	Class:com.ozkey.aop.App
>	Method:add
>	Arg0:2
>	Arg1:3
>
<	Returned:5
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result:5
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Another possible way of writing the same advice would have been to use the “around” advice. Around advice can perform custom behavior before and after the method invocation but it is also responsible for choosing if and when to proceed to the join point advised and what object to return. the around advice looks like this (Download source code):

	Object around(): publicMethods(){
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		System.out.println(">	Class:" + thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
		System.out.println(">	Method:" + thisJoinPointStaticPart.getSignature().getName());

		Object[] args = thisJoinPoint.getArgs();
		for(int i = 0; i<args.length;i++){
			System.out.println(">	Arg" +i + ":" + args[i].toString() );
		}
		System.out.println(">	");

		Object obj = proceed();

		if(obj!= null)
			System.out.println("<	Returned:" + obj.toString());
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
		return obj;
	}

The around advice is very powerful as it allows you to modify behavior by either changing the original arguments,  not proceeding to the joint point and/or returning a different Object

(Download source code)

Continue to AOP102

See also

http://www.eclipse.org/aspectj/doc/next/progguide/semantics-advice.html

1 – http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html?page=2

Javascript 101

This is a tutorial I created about a year ago. Not the best but it helps me remember some of the basics

PDF. javascript101

Creating JavaScript objects 101

To create an object of class myClass:

function myClass() {
	this.property = "value1";
	this.otherProperty = "value2";
}
var myObject = new myClass();
//myObject is an instance of class myClass
//and it has the following properties
alert(myObject.property); //display "value1"
alert(myObject.otherProperty); //display "value2"

Creating an object with methods

Below is an example of an object with a private an a public method,

function myClass(vlaueX,vlaueY) {
	this.x = vlaueX;
	this.y = vlaueY;
	this.XandY = myPrivateFunction(this.x,this.y);
	this.myPublicFunction = function (){
		return this.XandY;
	}; // a semicolon at the end is the correct practice.
	//the value x and y are not reachable
        //unless pased as parameters
	function myPrivateFunction(x,y) {
		return x + "-" + y;
	}
}
//create the object
var myObject = new myClass("ValueX","ValueY");
alert(myObject.y); //display “setValueY”
alert(myObject.myPublicFunction()); //displays “ValueX – ValueY”

The ‘toString’ method

All objects have the ‘toString’ method. The method returns a string representing the object, and it is called
whenever a string representation of the object is needed. For example alert(myObject);
Example to define the ‘toString’ method:

this.toString = function () {
	return "X:" + this.x + " Y:" + this.y;
};

Advanced object techniques

Quick way of creating an object

myObject1 = { property: "value1", otherProperty: "value2"};
alert(myObject1.property); //display "value1"
myObject2 = { property: "value1", insideObject:{x:"valueX" , y:"valueY"} };
alert(myObject2. insideObject.x); //display "valueX"

If we want to add a new property to our object (an instance of the class):

myObject.newProperty = 'propertyValue';

If we want all objects of class “myClass” to have a new property.

myObject.prototype.newProperty = 'propertyValue';

All instances of class myClass will have the property newProperty with value “propertyValue’”.
We can add new methods the same way:

myClass.prototype.setX = function (valueForX) {
	this.x = valueForX;
};
myObject.setX("valueForX");
alert(myObject.x);

This works on all object classes, such as String, Number and Boolean.
For example, we will add a method on all strings called ‘reverse’ that will return the string in reverse order

String.prototype.reverse = function() {
	for(var oStr='', x=this.length-1, oTmp; oTmp=this.charAt(x); x--){
		oStr += oTmp;
	}
	return oStr;
};
text = "hello";
alert(text.reverse()); //display olleh

Efficiency considerations

(http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Functions)
It is recommended that methods be declared outside the class using prototype (as shown above) or as the
example below:

function myClass(valueX){
	this.x = valueX
	this.addOne = myClass_addOne;
}
function myClass_addOne(){
	return this.x + 1;
}
var myObject = new myClass(5);
y = myObject.addOne();
alert(y); //display 6
//Declaring a class this way means a function
//can be called outside of the calss
x = 1;
alert(myClass_addOne()); //display 2

Public and private properties

function myClass() {
	this.property1 = 'value1'; //this creates a public property
	var property2 = 'value2'; //this creates a private property
	this.method1 = function () { alert( property2 ); };
}
var myObject = new myClass ();
alert(myObject.property1); // display 'value1'
alert(myObject.property2); // display undefined (private property)
myObject.method1(); // display 'value2'

Public and private methods

function myClass() {
	var secretProperty = "";
	function cantBeSeen() {
		alert(secretProperty);
	}
	this.method1 = function () {
		secretProperty = "myValue";
		cantBeSeen();
	};
	//makes a private function into a public function
	this.method2 = cantBeSeen;

}
var myObject = new myClass();
myObject.method1(); //alerts "myValue"
myObject.method2(); //alerts "myValue"

Inheritance

Create a new type of object, based on the mycircle

function mysphere(x,y,z,r) { ... constructor code ... }
mysphere.prototype = new mycircle();

Create a mycircle then assign that to the mysphere constructor prototype. As a result, the mysphere constructor
has the mycircle object added to its prototype chain.