Pages

Wednesday, 26 September 2012

VPN IPSEC and its implemention on Fortigate

Configuration overview

In a gateway-to-gateway configuration, two FortiGate units create a VPN tunnel between two separate private networks. All traffic between the two networks is encrypted and protected by FortiGate security policies.
Figure 120: Example gateway-to-gateway configuration

General configuration steps

The FortiGate units at both ends of the tunnel must be operating in NAT mode and have static public IP addresses.
When a FortiGate unit receives a connection request from a remote VPN peer, it uses IPsec phase 1 parameters to establish a secure connection and authenticate that VPN peer. Then, if the security policy permits the connection, the FortiGate unit establishes the tunnel using IPsec phase 2 parameters and applies the IPsec security policy. Key management, authentication, and security services are negotiated dynamically through the IKE protocol.
To support these functions, the following general configuration steps must be performed by both FortiGate units:
Define the phase 1 parameters that the FortiGate unit needs to authenticate the remote peer and establish a secure connection.
Define the phase 2 parameters that the FortiGate unit needs to create a VPN tunnel with the remote peer.
Create security policies to control the permitted services and permitted direction of traffic between the IP source and destination addresses. 
To create phase 1 to establish a secure connection with the remote peer
1
Go to VPN > IPsec > Auto Key (IKE).
2
Select Create Phase 1.
3
Enter the following information, and select OK.

Name
Enter peer_1.
A name to identify the VPN tunnel. This name appears in phase 2 configurations, security policies and the VPN monitor.
Remote Gateway
Select Static IP Address.
IP Address
Enter 172.20.0.2 when configuring FortiGate_1.
Enter 172.18.0.2 when configuring FortiGate_2.
The IP address of the remote peer public interface.
Local Interface
Select wan1.
The FortiGate unit’s public interface.
This interface cannot be a loopback interface.
Enable IPsec Interface Mode
Select Advanced to see this setting.
Enable IPsec Interface Mode to have the FortiGate unit create a virtual IPsec interface for a route-based VPN.
Disable this option to create a policy-based VPN. For more information, see “Comparing policy-based or route-based VPNs”.
After you select OK to create the phase 1 configuration, you cannot change this setting.
The basic phase 2 settings associate IPsec phase 2 parameters with the phase 1 configuration and specify the remote end point of the VPN tunnel. Before you define the phase 2 parameters, you need to reserve a name for the tunnel. See “Phase 2 configuration”.
To configure phase 2 settings
1
Go to VPN > IPsec > Auto Key (IKE).
2
Select Create Phase 2.
3
Enter the following information, and select OK.

Enter peer_1_p2.
Select peer_1.
The name of the phase 1 configuration.

Select Finance_network when configuring FortiGate_1.
Select HR_network when configuring FortiGate_2.
Destination Interface/Zone
Select HR_network when configuring FortiGate_1.
Select Finance_network when configuring FortiGate_2.
The address name that you defined in Step  for the private network behind the remote peer.
Select IPSEC.
Select peer_1.
Select Allow inbound to enable traffic from the remote network to initiate the tunnel.
Select Allow outbound to enable traffic from the local network to initiate the tunnel.








Wednesday, 19 September 2012

Design Pattern - Adapter Pattern

What is it?

The adapter pattern can be described as follows. When you have to implement an interface, but you want to use another class’ (or interface’s) methods in order to implement it you are using the Adapter Pattern. An example will illustrate this much better than this definition.

Example Problem

Lets say I have an AddressBook, and I wish to display this AddressBook to a JTable. One solution (without using the Adapter Pattern) is to have my AddressBook implement the TableModel. This is not such a good idea, because I don’t want my AddressBook class (or object model) to be tied to Swing.

Solution (design)

I can provide a nice solution to this problem by using the Adapter Pattern. Instead of implementing the TableModel directly on the AddressBook, I instead create an intermediary adapter class. This adapter class actually uses the AddressBook methods in order implement the TableModel. So I would call this class the AddressBookTableAdapter. Review the code snippets below to get an idea of how this is implemented.
There is no need for an Adapter to subclass the AddressBook class. In fact, you should use the Delegation Pattern, instead of using subclass. The example below uses the Delegation Pattern instead of subclassing.

Code

 1: //AddressBook
 2: public class AddressBook{
 3:     List personList;
 4:
 5:     public int getSize(){…}
 6:     public int addPerson(…){…}
 7:     public Person getPerson(…){…}
 8:
 9: }
 1: //AddressBookTableAdapter
 2: public class AddressBookTableAdapter
 3: implements TableModel
 4: {
 5:      AddressBook ab;
 6:      public AddressBookTableAdapter( AddressBook ab ){
 7:         this.ab = ab;
 8:      }
 9:
 10:      //TableModel impl
 11:      public getRowCount(){
 12:          ab.getSize();
 13:      }
 14:
 15: }
 1: //Test
 2: public class Test{
 3:      public static void main( String[] args ){
 4:          AddressBook ab = //get reference to AddressBook somehow
 5:          AddressBookTableAdaptermodel =
 6:              new AddressBookTableAdapter( ab );
 7:          JTable table = new JTable( model );
 8:      }
 9: }

Why?

Now that you have seen the Adapter pattern, you ask why use it? Well, the answer to this question has already been provided in the example problem definition. You don’t want your object models implementing JavaVM specific interfaces becuase they might change in the future. Also, by implementing Swing interfaces directly into your object models, you make your code messy by introducing Swing event handling code there.
It’s a better idea to use the Adapter pattern. It will make it so that you can get the most out of your object model by limiting direct dependencies on interfaces (and perhaps classes) that you can’t control.

Design Pattern - Delegation Pattern

What is it?

Chances are if you have used AWT1.1 or Swing, you have already used the delegation pattern, you just didn’t know you were doing it. The delegation pattern can be defined as follows. When you are creating a class that does everything another class does and more, then instead of subclassing the other class, you have to declare it as a data member or property of your class.

Example Problem

Lets say you are writing a class (ClassA) that does what another class (ClassB) does. ClassA also has to do more things (have more methods) than what ClassB does. You might be tempted to simply have ClassA subclass ClassB. Resist this temptation, becuase it is the wrong thing to do. Inheritance is inherently slow, and is a very strong linkage in your design. As a rule you want to create loosely coupled, but strongly coherent systems.

Solution (design)

The correct design involves defining a data member of type ClassB in ClassA. This way, you have eliminated the need for subclassing and reduced the coupling strength. In fact, ClassB might just be an interface, which is even better for loose coupling.

Code

 1: //ClassA
 2: public class ClassA{
 3:     //data
 4:     private ClassB classB;
 5:
 6:     //methods
 7:     public void doThis(){classB.doThis();}
 8:     public void doThat(){…}
 9: }
 1: //ClassB
 2: public class ClassB{
 3:     public void doThis(){…}
 4: }

Why?

The delegation pattern allows your code to be loosely coupled, which is a very important goal of any object oriented system. It is easy to get this pattern confused with the adapter pattern, they are similar, but completely different. Study both patterns carefully and you will see how they are totally different (yet similar).



 Delegation pattern 

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


In software engineering, the delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. There is an Inversion of Responsibility in which a helper object, known as a delegate, is given the responsibility to execute a task for the delegator. The delegation pattern is one of the fundamental abstraction patterns that underlie other software patterns such as composition (also referred to as aggregation), mixins and aspects.

Examples

[edit] Java examples

[edit] Simple

In this Java example, the Printer class has a print method. This print method, rather than performing the print itself, delegates to class RealPrinter. To the outside world it appears that the Printer class is doing the print, but the RealPrinter class is the one actually doing the work.
Delegation is simply passing a duty off to someone/something else. Here is a simple example:
 class RealPrinter { // the "delegate"
     void print() { 
       System.out.println("something"); 
     }
 }
 
 class Printer { // the "delegator"
     RealPrinter p = new RealPrinter(); // create the delegate 
     void print() { 
       p.print(); // delegation
     } 
 }
 
 public class Main {
     // to the outside world it looks like Printer actually prints.
     public static void main(String[] args) {
         Printer printer = new Printer();
         printer.print();
     }
 }

[edit] Complex

By using interfaces, delegation can be made more flexible and typesafe. "Flexibility" here means that C need not refer to A or B in any way, as the switching of delegation is abstracted from C. Needless to say, toA and toB don't count as references to A and B. In this example, class C can delegate to either class A or class B. Class C has methods to switch between classes A and B. Including the implements clauses improves type safety, because each class must implement the methods in the interface. The main tradeoff is more code.
interface I {
    void f();
    void g();
}
 
class A implements I {
    public void f() { System.out.println("A: doing f()"); }
    public void g() { System.out.println("A: doing g()"); }
}
 
class B implements I {
    public void f() { System.out.println("B: doing f()"); }
    public void g() { System.out.println("B: doing g()"); }
}
 
class C implements I {
    // delegation
    I i = new A();
 
    public void f() { i.f(); }
    public void g() { i.g(); }
 
    // normal attributes
    public void toA() { i = new A(); }
    public void toB() { i = new B(); }
}
 
public class Main {
    public static void main(String[] args) {
        C c = new C();
        c.f();     // output: A: doing f()
        c.g();     // output: A: doing g()
        c.toB();
        c.f();     // output: B: doing f()
        c.g();     // output: B: doing g()
    }
}

Design Pattern - Factory Pattern

From: http://developerlife.com/tutorials/?p=21

 

Problem

When using interfaces, it is important NOT to access the implementation classes (which implement these interfaces) directly.
Here is a simple example of what NOT to do:
   1: public interface LogEntryIF{
   2:      public setUserId( String s );
   3:      public setSessionId( String s );
   4:  }
   5:  
   6: public class LogEntry implements LogEntryIF{
   7:      private String userId, session;
   8:      public setUserId( String s ){ userId = s; }
   9:     public setSessionId( String s ){ sessionId = s; }
  10: }
Don’t do this:
   1: LogEntryIF le = new LogEntry();
   2: le.setUserId( “boo” );
   3: le.setSessionId( “sessionboo” );
So in this simple case, even having the ability to instantiate the LogEntry class is undesirable. There must be a way to instantiate objects of implementation classes:
  • without directly accessing the implemenation classes themselves
  • by relying entirely on the interfaces to access these objects.
Sounds impossible? Not really, by using the Factory pattern it can be done.

Solution

The Factory pattern involves creating a static class which has at least one method to do the following:
  • create an instance of an implementation classes, but return this object reference as the interface.
   1: public interface LogEntryIF{
   2:      public setUserId( String s );
   3:      public setSessionId( String s );
   4: }
   5:  
   6: public class LogEntry implements LogEntryIF{
   7:      private String userId, session;
   8:      public setUserId( String s ){ userId = s; }
   9:      public setSessionId( String s ){ sessionId = s; }
  10: }
  11:  
  12: public class LogFactory{
  13:      public static LogEntryIF getLogEntryInstance(
  14:          String userId ,
  15:          String sessionId ){
  16:          LogEntry le = new LogEntry();
  17:          le.setUserId( userId );
  18:          le.setSessionId( sessionId );
  19:          return le;
  20:      }
  21: }
Usage:
   1: LogEntryIF le = LogFactory.getLogEntryInstance( “boo” , “sessionboo” );
In the solution above, the user does not have to directly access the implementation class (LogEntry) in order to get an instance of it. Also, the factory class returns this instance of the implementation class as an instance of interface.

Date

Date to epoch

The current date and time

 [root@localhost scripts]# date
Wed Sep 19 11:13:38 PDT 2012


The current date in terms of epoch. The --date="Wed Sep 19 11:13:38 PDT 2012" is copied from the output of date command.

[root@localhost scripts]# date --date="Wed Sep 19 11:13:38 PDT 2012" +%s
1348078418


Other acceptable format

[root@localhost scripts]# date --date="2012-09-19 11:13:38" +%s
1348078418


[root@localhost scripts]# date -d "2012-09-19 11:13:38" +%s
1348078418

If the time is omitted,  the time is implied as 00:00:00

[root@localhost scripts]# date --date="2012-09-19" +%s
1348038000


If the date is omitted, it is assumed to be the current date.

[root@localhost scripts]# date --date="10:57:04" +%s
1348077424

Add a number of seconds to a certain date in "YYYY-MM-DD HH:MM:SS"

[root@localhost scripts]# date -d  "2012-09-19 00:00:10 40 seconds"
Wed Sep 19 00:00:50 PDT 2012

[root@localhost scripts]# date -d  "2012-09-19 00:00:10 40 seconds" +%s
1348038050

Epoch to Date

Epoch time is the number of second from 1970-01-01 00:00:00 UTC
[root@localhost scripts]# date -d "1970-01-01 UTC 00:00:00 1348038050 seconds"
Wed Sep 19 00:00:50 PDT 2012



Todo: date diff, Timezone, Convert time for different TZ

Thursday, 13 September 2012

GWT UiBinder

From http://blog.jeffdouglas.com/2010/01/19/gwt-uibinder-hello-world-tutorial/




GWT UiBinder Hello World Tutorial

January 19th, 2010
I’ve been working on a new project the past couple of weeks that (fortunately) requires Google Web Toolkit (GWT) and I wanted to use the new UiBinder that was released with GWT 2.0 in early December for a number of reasons (clean separation of UI and code, easier collaboration with designers, easier testing, etc ). However, I was having a hard time getting my head wrapped around it given that the GWT site has very little documentation and only a few examples. I’ve combed through the message boards, the docs and the sample Mail application that comes with the SDK and after finally groking the new functionality, I put together a little Hello World app, the kind that would have helped me out originally.
So I’m making some assumptions that you already have the GWT SDK and Eclipse Plugin installed and are familiar with both of them. If you are not, take a look at the GWT site for more info.
To get started, create a new Web Application Project called “HelloUiBinder” in the package of your choice but do not check “Use Google App Engine”.

Now create a new UiBinder template and owner class (File -> New -> UiBinder). Choose the client package for the project and then name it MyBinderWidget. Leave all of the other defaults. When you click Finish the plugin will create a new UiBinder template and owner class.

Open the MyBinderWidget.ui.xml template and add the following code. With GWT you can define your styles either in your template where you need them or externally. I’ve added a small style inline that adds some pizzaz to the label. Notice the field name myPanelContent in the template. You can programmatically read and write to this field from the template’s owner class. So when the owner class runs, it construct a new VerticalPanel, does something with it (probably add some type of content) and then fill this field with it.
Attributes for the elements (the text attribute in the Label element for example) correspond to a setter method for the widget. Unfortunately there is no code completion to get a list of these attributes in Eclipse when you hit the space bar so you either have to know the setters or refer to the JavaDocs each time. A painful process.
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
     xmlns:g="urn:import:com.google.gwt.user.client.ui">
     <ui:style>
          .bolder { font-weight:bold; }
     </ui:style>
     <g:HTMLPanel>
          <g:Label styleName="{style.bolder}" text="This is my label in bold!"/>
          <g:VerticalPanel ui:field="myPanelContent" spacing="5"/>
     </g:HTMLPanel>
</ui:UiBinder>
For the owner class, MyBinderWidget.java, add the following code. In this class, a field with the same name, myPanelContent, is marked with the @UiField annotation. When uiBinder.createAndBindUi(this) is run, the content is created for the VerticalPanel and the template field is filled with the new instance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.jeffdouglas.client;
 
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
 
public class MyBinderWidget extends Composite {
 
     private static MyBinderWidgetUiBinder uiBinder = GWT
               .create(MyBinderWidgetUiBinder.class);
 
     interface MyBinderWidgetUiBinder extends UiBinder<widget, MyBinderWidget> { }
 
     @UiField VerticalPanel myPanelContent;
 
     public MyBinderWidget() {
          initWidget(uiBinder.createAndBindUi(this));
 
          HTML html1 = new HTML();
          html1.setHTML("<a href='http://www.google.com'>Click me!</a>");
          myPanelContent.add(html1);
          HTML html2 = new HTML();
          html2.setHTML("This is my sample <b>content</b>!");
          myPanelContent.add(html2);
 
     }
 
}
Now change the entry point class to look like the following.
1
2
3
4
5
6
7
8
9
10
11
12
package com.jeffdouglas.client;
 
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
 
public class HelloUiBinder implements EntryPoint {
 
     public void onModuleLoad() {
          MyBinderWidget w = new MyBinderWidget();
          RootPanel.get().add(w);
     }
}
Now open HelloUiBinder.html and remove all of the HTML content between the </noscript> and and </body> save it. Once you run the application, copy the development URL and run paste it into your favorite supported browser, you should see the following.

Now suppose you wanted to nest a widget inside your MyBinderWidget that did something when a button was clicked. We’ll create a small series of checkboxes that allows the user to select their favorite colors and display them when the button is clicked. Create a new UiBinder called FavoriteColorWidget in the client package. Add the following code to the FavoriteColorWidget.ui.xml template.
1
2
3
4
5
6
7
8
9
10
11
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
    xmlns:g='urn:import:com.google.gwt.user.client.ui'>
    <g:VerticalPanel>
      <g:Label ui:field="greeting"/>
      <g:Label>Choose your favorite color(s):</g:Label>
      <g:CheckBox ui:field="red" formValue="red">Red</g:CheckBox>
      <g:CheckBox ui:field="white" formValue="white">White</g:CheckBox>
      <g:CheckBox ui:field="blue" formValue="blue">Blue</g:CheckBox>
      <g:Button ui:field="button">Submit</g:Button>
    </g:VerticalPanel>
</ui:UiBinder>
Now add the click handler in the FavoriteColorWidget.java owner class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.jeffdouglas.client;
 
import java.util.ArrayList;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
 
public class FavoriteColorWidget extends Composite {
 
     private static FavoriteColorWidgetUiBinder uiBinder = GWT
               .create(FavoriteColorWidgetUiBinder.class);
 
     interface FavoriteColorWidgetUiBinder extends
               UiBinder<widget, FavoriteColorWidget> {
     }
 
     @UiField Label greeting;
     @UiField CheckBox red;
     @UiField CheckBox white;
     @UiField CheckBox blue;
     @UiField Button button;
 
     public FavoriteColorWidget() {
          initWidget(uiBinder.createAndBindUi(this));
 
          // add a greeting
          greeting.setText("Hello Jeff!!");
 
          final ArrayList<checkBox> checkboxes = new ArrayList<checkBox>();
          checkboxes.add(red);
          checkboxes.add(white);
          checkboxes.add(blue);
 
         // add a button handler to show the color when clicked
          button.addClickHandler(new ClickHandler() {
               public void onClick(ClickEvent event) {
                    String t = "";
                    for(CheckBox box : checkboxes) {
                         // if the box was checked
                         if (box.getValue()) {
                              t += box.getFormValue() + ", ";
                         }
                    }
                    Window.alert("Your favorite color/colors are: "+ t);
               }
          });
 
     }
 
}
The last thing we’ll need to do is add our new widget to the MyBinderWidget template. Open MyBinderWidget.ui.xml and add the custom namespace reference and the FavoriteColorWidget.
1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">;
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
     xmlns:g="urn:import:com.google.gwt.user.client.ui"
     xmlns:c="urn:import:com.jeffdouglas.client">
     <ui:style>
          .bolder { font-weight:bold; }
     </ui:style>
     <g:HTMLPanel>
          <g:Label styleName="{style.bolder}" text="This is my label in bold!"/>
          <g:VerticalPanel ui:field="myPanelContent" spacing="5"/>
          <c:FavoriteColorWidget/>
     </g:HTMLPanel>
</ui:UiBinder>
Now when you run the application it should look like the following.