Saturday, August 23, 2014

ViennaMesh Mesh Optimization Project Proposal (Google Summer of Code 2014)


This is the project proposal I submitted for the organization computational science and engineering department of TU Wien University. Basically in this project proposal I have proposed several mesh optimization algorithms and how they can be applied to ViennaMesh Meshing library.

You can visit the ViennaMesh at http://viennamesh.sourceforge.net/

Here is the project proposal I have submitted for GSOC 2014. This project proposal got accepted in GSOC2014 and I have managed to successfully complete the Google Summer of Code 2014 program.





Above is the proposal that I proposed for Computational Science and Engineering at TU Wien University. The Following document contains the final code documentation and descriptions on the algorithms that I have implemented. I thought of sharing that document as well.




I would like to express my gratitude to my mentor Florian Rudolf who has guided me thorough out the Google Summer of Code program to successfully finish the program.


Wednesday, March 5, 2014

How to Build an simple Opencascade Program using Visual C++

What is Opencascade?

Opencascade is an open source software development platform which provides easy interface to build CAD, CAM Software. It contains the optimized data structures and algorithms to perform the required geometric operations efficiently. You might wonder what I meant by geometric operations?
For example in CAD software you might want to find the intersection points of two 3D curves or you need to cut some shape off from a solid shape etc.
For that you don't need to write code from the scratch. You can use the generic geometric operations provided in the Opencascade library.
For further details you can visit the Opencascade official website: http://www.opencascade.org/

How to Install Opencascade in your computer?

I hope now you have some picture about the Opencascade. Best way to learn Opencascade is to try it out and play with it. In Order to work with Opencascade first you have to install Opencascde in your computer. You can download the latest revision of the Opencascade from http://www.opencascade.org/getocc/download/occarchives/. (Note: At the time I’m writing this blog Opencascade 6.7.0 is released. But in this tutorial all will use Opencascade 6.6.0. There is nothing to worry, Opencascade 6.6.0 and the Opencascade 6.7.0 are pretty much the same.)
Go to the link specified above and select Opencascade 6.6.0 version to download. Select the Opencascade 6.6.0.exe to start downloading Opencascade 6.6.0.
After downloading Opencascade 6.6.0.exe run the setup file with administrative privilages in order to install it correctly.
After you have successfully installed the Opencascade you can go to the installation location and see the installed files and folders.




How to Configure visual studio to use Opencascade ?

Configuring Opencascade in Visual Studio is extremely easy. Before configuring Opencascade in Visual Studio we need to configure some environment variables in the windows.
For that Right Click of My Computer =>Properties => Advanced System Settings=> Environment Variables. Then Select Environment variable named “Path” and add Openascade bin folder path to it. In Opencascde installation location you have a folder named “3rdParty”. In this folder it contains all the 3rd party dll files needed by Opencascade. In 3rdparty folder go to each and every folder and find the path to bin and add that path to the environment variable “Path”. Ok. Now we have finished configuring environment variables in windows for Opencascade.
Now it is time to configure Visual Studio to use Opencascade. In Visual Studio Will need to Configure the following project properties for any created project in order to use Opencascade in that project. To change these properties, Right Click on your project => Properties

·         Include Files Path    (C++ =>General => Additional Include Directories) (Include folder path of the Opencascde)
·         
      Preprocessor Definitions (C++ => Preprocessor)  (Add WNT, WNT_WINDOW)
·        
      Library Files Path (Linker => General => Additional Library Directories) (Add Lib folder path of the Opencascade)
·        
      Additional Dependencies (Linker => Input => Additional Dependencies) ( Add the Following Lib Names
TKOpenGl.lib;TKernel.lib;TKGeomBase.lib;TKTopAlgo.lib;TKOffset.lib;TKBool.lib;TKPrim.lib;TKFillet.lib;TKMath.lib;TKService.lib;TKV3d.lib;TKBrep.lib;TKIGES.lib;PTKernel.lib;TKSTL.lib;TKVRML.lib;TKSTEP.lib;TKShapeSchema.lib;TKG3d.lib;TKG2d.lib;TKXSBase.lib;TKPShape.lib;TKShHealing.lib;TKBO.lib


Congratulations!!! Now you have configured Visual Studio to use Opencascade library.

Our First Application

Ok. Let’s Start Coding. What would be our first application? I have decided to create a simple MFC application. I use Opencascade to draw some 3d object and rotate that object according to mouse movement.
If you don’t know anything about MFC applications don’t worry. I will explain briefly about the MFC application. If you are familiar with the MFC applications skip reading the below passage on MFC. People who are new to MFC I highly recommend reading the below passage or do your own research on MFC and get little bit familiar with the MFC applications in order to continue this tutorial.
What is MFC? MFC stands for Microsoft Foundation Class. In a MFC application there are 3 objects that are essential. MFC application can’t survive without those 3 objects. Those are

  • Application Class
  • Document Class
  • Viewer Class
Application Class: This is the class with contains all the initializations of the application. Windows start to run our application from this class. There can be only one application class for an MFC application.
Document Class: This Class contains the data which we need to show and interact with the user. Note that this class contains only the data. There is no way to show these data without using the viewer class.
Viewer Class: To Show a data in the document Class we need the Viewer Class. Without the Viewer Class we can’t show the data in the document.
For Application there can be multiple instances of documents. For each document there is a bound viewer object.
For More information http://msdn.microsoft.com/en-us/library/9es9d1k4.aspx

Ok Back to Opencascade,
I hope now you have created the MFC Application. In stdafx.h file copy the following includes. These are the mainly used includes in Opencascade. (You can include the specific header file when you need that file. But following approach is easy for beginners. So they can directly write code without wondering what files to include.)
 #include <BRepTools.hxx>  
 #include <Standard_DefineHandle.hxx>  
 #include <DsgPrs_LengthPresentation.hxx>  
 #include <GCPnts_TangentialDeflection.hxx>  
 #include <Geom_Axis2Placement.hxx>  
 #include <Geom_CartesianPoint.hxx>  
 #include <Geom_Line.hxx>  
 #include <Geom_Surface.hxx>  
 #include <BRepAdaptor_Surface.hxx>  
 #include <GeomAbs_CurveType.hxx>  
 #include <GeomAdaptor_Curve.hxx>  
 #include <GeomTools_Curve2dSet.hxx>  
 #include <gp_Vec.hxx>  
 #include <Graphic3d_NameOfMaterial.hxx>  
 #include <MMgt_TShared.hxx>  
 #include <OSD_Environment.hxx>  
 #include <Precision.hxx>  
 #include <Prs3d_IsoAspect.hxx>  
 #include <Prs3d_LineAspect.hxx>  
 #include <Prs3d_Projector.hxx>  
 #include <Prs3d_Text.hxx>  
 #include <Quantity_Factor.hxx>  
 #include <Quantity_Length.hxx>  
 #include <Quantity_NameOfColor.hxx>  
 #include <Quantity_PhysicalQuantity.hxx>  
 #include <Quantity_PlaneAngle.hxx>  
 #include <Quantity_TypeOfColor.hxx>  
 #include <SelectBasics_BasicTool.hxx>  
 #include <SelectBasics_ListOfBox2d.hxx>  
 #include <SelectMgr_EntityOwner.hxx>  
 #include <SelectMgr_SelectableObject.hxx>  
 #include <SelectMgr_Selection.hxx>  
 #include <SelectMgr_SelectionManager.hxx>  
 #include <SelectMgr_ListOfFilter.hxx>  
 #include <Handle_SelectMgr_Filter.hxx>  
 #include <SelectMgr_Filter.hxx>  
 #include <StdSelect_EdgeFilter.hxx>  
 #include <StdSelect_ShapeTypeFilter.hxx>  
 #include <ShapeSchema.hxx>  
 #include <Standard_Boolean.hxx>  
 #include <Standard_CString.hxx>  
 #include <Standard_ErrorHandler.hxx>  
 #include <Standard_Integer.hxx>  
 #include <Standard_IStream.hxx>  
 #include <Standard_Macro.hxx>  
 #include <Standard_NotImplemented.hxx>  
 #include <Standard_OStream.hxx>  
 #include <Standard_Real.hxx>  
 #include <StdPrs_Curve.hxx>  
 #include <StdPrs_Point.hxx>  
 #include <StdPrs_PoleCurve.hxx>  
 #include <TCollection_AsciiString.hxx>  
 #include <TColgp_Array1OfPnt2d.hxx>  
 #include <TColgp_HArray1OfPnt2d.hxx>  
 #include <TCollection_AsciiString.hxx>  
 #include <TColStd_HSequenceOfTransient.hxx>  
 #include <TColStd_MapIteratorOfMapOfTransient.hxx>  
 #include <TColStd_MapOfTransient.hxx>  
 #include <TopExp_Explorer.hxx>  
 #include <TopoDS.hxx>  
 #include <TopoDS_Compound.hxx>  
 #include <TopoDS_Shape.hxx>  
 #include <TopoDS_Solid.hxx>  
 #include <TopoDS_Vertex.hxx>  
 #include <TopExp.hxx>  
 #include <TopTools_HSequenceOfShape.hxx>  
 #include <UnitsAPI.hxx>  
 #include <V3d_View.hxx>  
 #include <V3d_Viewer.hxx>  
 #include <WNT_Window.hxx>  
 #include <Handle_AIS_Drawer.hxx>  
 #include <AIS_Drawer.hxx>  
 #include <Prs3d_PointAspect.hxx>  
 #include <AIS_Point.hxx>  
 #include <BRep_Tool.hxx>  
 #include <BRepAlgoAPI_Fuse.hxx>  
 #include <BRepBuilderAPI_MakeEdge.hxx>  
 #include <BRepBuilderAPI_MakeFace.hxx>  
 #include <BRepBuilderAPI_MakeWire.hxx>  
 #include <BRepBuilderAPI_MakeVertex.hxx>  
 #include <BRepBuilderAPI_Transform.hxx>  
 #include <BRepPrimAPI_MakeCone.hxx>  
 #include <BRepPrimAPI_MakeRevol.hxx>  
 #include <BRepFilletAPI_MakeFillet.hxx>  
 #include <BRepBuilderAPI_Copy.hxx>  
 #include <BRepBuilderAPI_MakePolygon.hxx>  
 #include <BRepLib.hxx>  
 #include <BRepOffsetAPI_MakeThickSolid.hxx>  
 #include <BRepOffsetAPI_ThruSections.hxx>  
 #include <BRepPrimAPI_MakeCylinder.hxx>  
 #include <BRepPrimAPI_MakePrism.hxx>  
 #include <BRepPrimAPI_MakeTorus.hxx>  
 #include <BRepAlgoAPI_Section.hxx>  
 #include <BRepPrimAPI_MakeSphere.hxx>  
 #include <BRepFeat_SplitShape.hxx>  
 #include <TColgp_HArray1OfPnt.hxx>  
 #include <GeomAPI_Interpolate.hxx>  
 #include <GC_MakeArcOfCircle.hxx>  
 #include <GC_MakeSegment.hxx>  
 #include <GC_MakeCircle.hxx>  
 #include <GCE2d_MakeSegment.hxx>  
 #include <gp.hxx>  
 #include <gp_Ax1.hxx>  
 #include <gp_Ax2.hxx>  
 #include <gp_Ax2d.hxx>  
 #include <gp_Dir.hxx>  
 #include <gp_Dir2d.hxx>  
 #include <gp_Pnt.hxx>  
 #include <gp_Pnt2d.hxx>  
 #include <gp_Trsf.hxx>  
 #include <gp_Vec.hxx>  
 #include <Geom_CylindricalSurface.hxx>  
 #include <Geom_Plane.hxx>  
 #include <Geom_Surface.hxx>  
 #include <Geom_TrimmedCurve.hxx>  
 #include <Geom2d_Ellipse.hxx>  
 #include <Geom2d_TrimmedCurve.hxx>  
 #include <TopExp_Explorer.hxx>  
 #include <TopoDS.hxx>  
 #include <TopoDS_Edge.hxx>  
 #include <TopoDS_Face.hxx>  
 #include <TopoDS_Wire.hxx>  
 #include <TopoDS_Shape.hxx>  
 #include <TopoDS_Compound.hxx>  
 #include <GCPnts_AbscissaPoint.hxx>  
 #include <BRepAdaptor_Curve.hxx>  
 #include <GeomLib.hxx>  
 #include <GeomConvert_CompCurveToBSplineCurve.hxx>  
 #include <TopTools_ListOfShape.hxx>  
 #include <TopTools_ListIteratorOfListOfShape.hxx>  
 #include <TopTools_DataMapOfShapeInteger.hxx>  
 #include <TopTools_DataMapOfShapeReal.hxx>  
 #include <TopTools_IndexedDataMapOfShapeAddress.hxx>  
 #include <V3d_PositionalLight.hxx>  
 #include <V3d_DirectionalLight.hxx>  
 #include <V3d_AmbientLight.hxx>  
 #include <IGESControl_Controller.hxx>  
 #include <IGESControl_Writer.hxx>  
 #include <Interface_Static.hxx>  
 #include <OpenGl_GraphicDriver.hxx>  
 #include <Graphic3d_GraphicDriver.hxx>  

Opencascade is a CAD geometry library. To show 3d objects on the screen Opencascade needs some link to the computers graphic card. So the First thing that we have to is the making a link between the Opencascade and the computer graphic card.

I use the Application class to keep that link. In application Class header file declare the variable

 Handle(Graphic3d_GraphicDriver) m_GraphicDriver;                 // To Keep the Initialized graphic driver...  

What is the best time to create the link between Opencascade and the Graphic driver. I think it is good and recommended if we can create that link at the start of the application. So I initialize the header file declared variable in the Application Constructor Class.

      
 try{ 
        m_GraphicDriver=new OpenGl_GraphicDriver("TKOpenGl");  
     }catch(Standard_Failure){  
          AfxMessageBox("_T(Error Ocured in Initializing the Opencascade graphic variable.)");     
     }  

So now we have created the link between Opencascade and the graphic card. Add a getter method to App class header file in order to return this variable.

 Handle(Graphic3d_GraphicDriver) GetGraphicDriver(){return m_GraphicDriver;}  

Ok. Now let’s move on to the Document Class. In the document class header file we need to declare two variables. Those are
 Handle(AIS_InteractiveContext) myAISContext;  
 Handle(V3d_Viewer) myViewer;  

AIS_InteractiveContext is the one which manages the user interaction with the displayed objects. Those interactions may be rotating, panning, zooming, selecting shapes etc.
V3d_Viewer Contains all the required variables about the Openacsacade viewer.  You really don’t want to worry about that now.  We need the Viewer to create a Opencascade View. (Read Carefully.)
To Initialize these variables we add code to the Document Class Constructor.
 Handle(Graphic3d_GraphicDriver) theGraphicDriver=((CCADViewerApp*)AfxGetApp())->GetGraphicDriver();  
     theGraphicDriver->Begin(new Aspect_DisplayConnection());  
     TCollection_ExtendedString aNameOfViewer("Visu3d");  
     //Initializing V3d_Viewer  
     myViewer = new V3d_Viewer (theGraphicDriver, aNameOfViewer.ToExtString());  
     myViewer->Init();  
     myViewer->SetLightOn();  
     myViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);  
     // create a new window or a wrapper over the existing window,  
     myAISContext=new AIS_InteractiveContext(myViewer);  
 myAISContext->SetDisplayMode(AIS_Shaded);  
     myAISContext->SetAutomaticHilight(Standard_False);  

Ok Now Let’s Move on to the Viewer Class in MFC.  Viewer Class Contains the Opencascade View Variable. (View at particular point of the Opencascade viewer.)
 Handle(V3d_View) myView;  

Viewer class we need to override method On InitialUpdate. This is run at the first update of the window viewer. To override the method add following to the header file.
 virtual void OnInitialUpdate();  

Add this Overridden code to the Viewer OnInitialUpdate Method.
 void CCADViewerView::OnInitialUpdate(){  
  myView=GetDocument()->GetViewer()->CreateView();  
  myView->SetShadingModel(V3d_GOURAUD);  
  Handle(Graphic3d_GraphicDriver) theGraphicDriver = ((CCADViewerApp*)AfxGetApp())->GetGraphicDriver();  
  Aspect_Handle aWindowHandle = (Aspect_Handle)GetSafeHwnd();  
  Handle(WNT_Window) aWntWindow=new WNT_Window(GetSafeHwnd());  
  myView->SetWindow(aWntWindow);  
  if(!aWntWindow->IsMapped()){  
  aWntWindow->Map();  
  }  
  Standard_Integer w=100;  
  Standard_Integer h=100;  
  aWntWindow->Size(w,h);  
  ::PostMessage(GetSafeHwnd(),WM_SIZE,SIZE_RESTORED,w+h*65536);  
  myView->FitAll();  
 myView->ZBufferTriedronSetup(Quantity_NOC_RED,Quantity_NOC_GREEN,Quantity_NOC_BLUE1,0.8,0.05,12);  
   myView->TriedronDisplay(Aspect_TOTP_LEFT_LOWER,Quantity_NOC_WHITE,0.2,V3d_ZBUFFER);  
 }  

On Initial Update of the MFC Viewer Class we initially update the Opencascade View , Setting up the window sizes of the view etc.

In Addition to that we need to draw the 3D axis System on the screen We Should add the Following Code to the bottom of the On Initial Update Method.

 myView->ZBufferTriedronSetup(Quantity_NOC_RED,Quantity_NOC_GREEN,Quantity_NOC_BLUE1,0.8,0.05,12);  
 myView->TriedronDisplay(Aspect_TOTP_LEFT_LOWER,Quantity_NOC_WHITE,0.2,V3d_ZBUFFER);  

Now it time to update the OnDraw  method in MFC Viewer Class. This method is called by MFC automatically when window viewer needs to update. (Like Resizing the window, Moving the window etc). When the window viewer needs to be updated the Opencascade View also needs to be updated.
So Add the Following code to MFC Viewer Class OnDraw method.
 myView->MustBeResized();  
 myView->Update();  

Ok. Congratulations!!! Now you have completed building your first app using Opencascade. If it compiled without an error then when you run your application you should see a view with the 3D Axis on the left bottom of the Screen.


Creating a Geometric Object using Opencascade?

Ok. Now let’s draw some object on the Opencascade viewer. Opencascade is a very rich robust geometric library. You can perform very complicated geometric operations using Opencascade.
For now we will just create a Sphere. (I will write my next post on how to create complicated shapes using Opencascade.)
Let’s add a function to draw a sphere in the Document Class.

 void CCADViewerDoc::DrawSphere(double Radius){  
     BRepPrimAPI_MakeSphere mkSphere(Radius);  
     TopoDS_Shape Sphere=mkSphere.Shape();  
     myAISContext->Display(new AIS_Shape(Sphere));  // Draw the Sphere on the Screen  
     myViewer->ActiveView()->FitAll();           // Focus to the View to the Drawn Shape.  
 }  

Now we needs to call this function in order to draw the shape. For now I will call this function in OnDraw method.



How to interact with the Opencascade viewer?

We can interact with the drawn object very easily. Let’s add functionality to rotate any object drawn in the viewer using move movement plus left mouse button down. To do that you need to add mouse movement hander to our application. We will add mouse movement handler function to the Viewer Class of Our application. (you can add mouse event automatically by visual studio.)

 void CCADViewerView::OnMouseMove(UINT nFlags, CPoint point)  
 {  
     // TODO: Add your message handler code here and/or call default  
     CView::OnMouseMove(nFlags, point);  
     if(nFlags && MK_LBUTTON){  
            myView->Rotate(point.x,point.y);  
            myView->Rotation(point.x,point.y);  
     }  
 }  


So we have reached to the end of this tutorial. I hope you took some knowledge from this. If You have any questions regarding this tutorial or Opencascade please comment below or mail me (milindasf@gmail.com) and I will try my best to answer those questions.

Thursday, September 5, 2013

Logical Agents for Language & Action


This is the paper presentation that Our Group (Me, Tharindu Rusira and Chamara Phillips) has done for the Intelligent System Subject.

This paper presentation basically describes how Augmented Natural Deduction Intelligence can be use to develop Non- Player Characters in computer games.

This presentation is basically based on the research paper written by Martin Magnusson & Patrick Dohetry on Logical agents for language and action.

You can get the research paper from here.






Tuesday, August 27, 2013

Introduction to NoSQL and Neo4j graph database


What is NoSQL?

NoSQL word is derived from the word SQL. SQL stands for Structured Query Language. Basically SQL is a special kind of programming language (actually it's a query language) which is used to manage data (retrieve data  data,insert data,update existing data) in relational database management system.

So What's a relational database? If I wrote a complete description about the relational database this post will be too long to read. :) Shortly relational database uses the relational schema as the data model of the database. In a relational database data is stored as collection of relations (tables). 

So again let's come to our question. NoSQL ? 

NoSQL doesn't means Not SQL or good bye SQL. It's simply means NOT ONLY SQL. There are several common characteristics for NoSQL databases. Those are

In relational database system the relational schema is the data model of the database. So what is the data model of the NoSQL database. Actually there are several data storing models for NoSQL database. Based on those data models the NoSQL databases can be catorgorized as follows.
  • Column
  • Document
  • Key-Value
  • Graph
Next part of this document contains detailed description of the Graph data model and how to implement a simple graph database using Neo4j graph database.

Graph data Model?

Graph is the most generic data structure that we can think of when representing/ storing the data. What is a graph? It is a collection of vertices and edges.


Here in this example graph we have three vertices. Let denotes the vertices set as V={a,b,c}. If we denotes the set of edges as E, we can write E={ab,ac, bc}. The graph in the image is not a directional graph. That means the direction of the edges actually doesn't matter. But in our graph data model we uses the directional graphs.





Let's consider the following graph,

Here in this graph we have several people and their relationships. Basically in a graph database data is stored in basically two places.  They are,

  • Vertices /Nodes
  • Edges / Relationships

In this graph "Peter" is a Node. This node might contain several properties. In this case it has only one property (that is name). The edge between Node Peter and Node Ray can be called as a relationship. Relationship must have some type and might contain other properties. In this case relationship type between Peter and Ray is Knows. But it might contain other properties such as Since when peter knows Ray. Note: In this scenario Peter knows Ray, but Ray does't know Peter because there is no directed edge going from Ray to Peter. 

Now let see how to build a simple graph database using Neo4j.

What is Neo4j?

Neo4j is a NoSQL database management system which uses a graph data as the NoSQL data model. For more details you can visit Neo4j home page: http://www.neo4j.org/

How to Install Neo4j?

Installation Neo4j is extremely simple. You first have to download the Neo4j from Neo4j homepage. Neo4j is available for both windows and Linux environments.
To download the Neo4j use the following Link.

After You have downloaded the zip file uncompressed it to any location you want. In Linux environment to run the Neo4j database server just follow the below steps.
  • First go to your neo4j folder using the cd command
  • Then go inside the bin folder
  • type ./neo4j start to start the neo4j database. You can type ./neo4j-shell to start the neo4j database and neo4j-shell in the same time.
Then in the terminal it will show a localhost port number where the neo4j server runs.










In terminal showing start up of the neo4j server 














Neo4j web admin interface.

Creating Our first graph database

So let's create a simple graph database. I will create a graph database for the graph shown in the figure above.

To create a node for peter. Like that we can create nodes for all other people.


 CREATE n={name:'peter', age:'21' ,sex:'male'};  
 CREATE n={name:'slimer', age:'22' ,sex:'male'};  
 CREATE n={name:'winston', age:'20' ,sex:'male'};  
 CREATE n={name:'egon', age:'20' ,sex:'male'};  
 CREATE n={name:'ray', age:'20' ,sex:'male'};  


Now we have to represent the Relationships between these friends.

To that we need to know particular nodes with their node id.

To find all nodes in your database


 START n=NODE(*) RETURN n;  

To Create a relation ship between peter and ray and other friends

 START a=NODE(20) ,b=NODE(21) CREATE a-[r:knows]->b RETURN r;  
 START a=NODE(24) ,b=NODE(23) CREATE a-[r:knows]->b RETURN r;  
 START a=NODE(24) ,b=NODE(22) CREATE a-[r:knows]->b RETURN r;  
 START a=NODE(22) ,b=NODE(21) CREATE a-[r:knows]->b RETURN r;  




That's it. It is that simple Now we have created our simple graph.





Now Let's do some queries. If we want to find all the friends of 'ray'

 START n=NODE(24) MATCH n-[:knows]-friend RETURN friend;  



If we want to find ray's friend's friends,

 START n=NODE(24) MATCH n-[:knows]-()-[:knows]->friend RETURN friend;  






This is a very small introduction on Neo4j. It is actually very powerful database management system which enables you to do large data processing very efficiently. If you want to learn more on Neo4j Please download and read the Neo4j manual. I hope this tutorial helped you to understand the basic knowledge on the graph databases and how to use Neo4j to create simple graph database. If you have any problems regarding graph databases or Neo4j Please send me an email or Comment you question on this article. I'll try my best to answer. :)

Tuesday, August 13, 2013

Steganography with images and histogram checks

What is Steganography ?

Steganography is the hiding of a secret message within an ordinary message and the extraction of it at its destination. Here we have used an image to hide some message in side it. After encrypting the message we will try to analyze the histograms of the original image and the encrypted image to detect the differences of the images.

For more details : http://en.wikipedia.org/wiki/Steganography

Tools


Mozaiq - Online steganography tool
Mozaiq is an online steganography tool which provides a simple interface for hide plain text messages in a given image. Wikipedia states that terrorists has used this tool to send secret messages via public forum avatar images.


Mozaiq decryption tool
This decryption tool can be used to find the text message hidden in an image.


MatLab- To get histograms of the images and calculate the difference between the histograms of the images.


GIMP - To obtain visual representations of image histograms


Message


This is the message we encrypted using steganography for this experiment.



I am happy to join with you today in what will go down in history as the greatest demonstration for freedom in the history of our nation.
Five score years ago, a great American, in whose symbolic shadow we stand today, signed the Emancipation Proclamation. This momentous decree came as a great beacon light of hope to millions of Negro slaves who had been seared in the flames of withering injustice. It came as a joyous daybreak to end the long night of their captivity.
But one hundred years later, the Negro still is not free. One hundred years later, the life of the Negro is still sadly crippled by the manacles of segregation and the chains of discrimination. One hundred years later, the Negro lives on a lonely island of poverty in the midst of a vast ocean of material prosperity. One hundred years later, the Negro is still languished in the corners of American society and finds himself an exile in his own land. And so we've come here today to dramatize a shameful condition.
In a sense we've come to our nation's capital to cash a check. When the architects of our republic wrote the magnificent words of the Constitution and the Declaration of Independence, they were signing a promissory note to which every American was to fall heir. This note was a promise that all men, yes, black men as well as white men, would be guaranteed the "unalienable Rights" of "Life, Liberty and the pursuit of Happiness." It is obvious today that America has defaulted on this promissory note, insofar as her citizens of color are concerned. Instead of honoring this sacred obligation, America has given the Negro people a bad check, a check which has come back marked "insufficient funds."
But we refuse to believe that the bank of justice is bankrupt. We refuse to believe that there are insufficient funds in the great vaults of opportunity of this nation. And so, we've come to cash this check, a check that will give us upon demand the riches of freedom and the security of justice.



Side by side image view

         

Original Image Image with encrypted message        

Histograms of the Images
Histograms are obtained from both Matlab and GIMP.


           

Histogram of the Original Image




Histogram of the Encrypted message inside the image.
                                                  


Matlab code for obtaining two histograms and finding the difference between two histograms is given below. This is useful in measuring the quantitative statistical difference two images.
GIMP provides a detailed graphical interpretation of the histograms.This graphical representation provides a good sense of quantitative differences between two images.


Subtle differences in histogram peaks can be observed by carefully analyzing the two histograms.


We have used MatLab to draw the histograms of the given images. Here are the histograms created using matlab.



Here the histogram of the original image is one the left and the encrypted image’s histogram is on right.



We have coded a matlab function to calculate the differences between the histograms.  We have got an answer of 3.812e-0.005. This figure proves that there two images that we have used to calculate histograms are same to the human naked eye but they are actually two different images.

Monday, August 12, 2013

Controlling a wheel chair according to the head movements of wheel chair user (Sheersha Yathra)



Sheersha Yathra is a project carried out by the department of computer science and engineering, University of Moratuwa Sri Lanka.

I'm proud to say that I was a member in this "Sheersha Yathra" Project Group.





Abstract


As a result of civil war which existed for three decades there are many soldiers who have been affected. So as engineering students we thought that it is our responsibility to utilize our knowledge and capabilities in a way that is beneficial to the country. The motivation behind this project is to support for such an officer who has not control below his neck.
At the moment he is staying at Mihindu Seth Madura. What we noticed was that he cannot do anything of his own. What he requested mainly was a way to move his wheel chair of his own.

So we came with up an idea to carry on a project which results in making a wheel chair which can be moved according to the head movements of the officer’s head.

Our Solution
To control the wheelchair according to the head movements of the user we have fixed a two dimensional tilt sensor in the user's head. According to the angle which the user's head is angled we will generate an analog signal and pass that analog signal to the main circuit board of the wheelchair. So the electric wheelchair main circuit board thinks that the signal is came from the joystick of the wheelchair. It will be a burden if the wheelchair is always controlled according to the head movements of the user. so user has given facility to activate and deactivate the head movement control of the wheelchair according to the voice commands of the user. We have use an arduino Mega board as the main control board of out project. We have connected a Voice recognition chip, R2R ladder to generate the analog signal. 


Here is a demo video of the Project




System Security Assessment of the Moddle


Moodle is an open source learning management System. Our university uses a some Open source version of this moodle.  In this article I try to explain some weakness currently present in the moodle.

Selected organization



LearnOrg moodle- University of Moratuwa



The tools we have used in this System security assessment are, 

  • metasploit 4.7
  • nmap
  • wireshark

Vulnerability identification



vulnerabilities are system defects that an attacker can use to launch an attack against the system. In the UOM moodle we have tried out some tests to detect vulnerabilities. All these tests were carried out using the current UOM moodle which is accessible at https://lms.uom.lk.


Test 1 Attempting Session Hijacking on the Same Machine



To see if session hijacking can be done two separate browsers were installed in the same machine. We have used Firefox and Google chrome browsers for this test. First we logged in to the moodle student account using Google chrome browser with cookies enabled. We can get the cookie values for the moodle session using the Google browser.

After using these cookie values we have created new cookies in Firefox using the cookie manager add-on. Then when we visit to the module in Firefox we will automatically redirected to the student account who logged in Google browser. So session hijacking is a one vulnerability in the UOM Moodle system.








Test 2 Attempting Session Hijacking over a network



Session values are not encrypted in http packets. Packet sniffing tool like wireshark can be easily used to track packets and get the session variables. Those can be copied into cookies in firefox and successfully login to the account.
We started wireshark and filtered to track ip packets. While it was running logged in to an user account in moodle.Then we stopped wireshark tracking packets. And analyze one by one packets.

Following is the ip packet with session variable.






Then we simply copied those variables into firefox and reloaded moodle. We successfully logged into the account. To perform this attack passive tampering is needed on the network connection which the target user machine is connecte



Test 3 identification of open/closed ports



nmap can be used to identify server details and its open and closed ports. A good security practice is hiding unused or security critical ports from the public. By this nmap search we discovered port 80, port 443 and port 631. So this is a good security move against attackers who are trying to launch DoS attacks on the server.


nmap -A lms.uom.lk


Starting Nmap 5.21 ( http://nmap.org ) at 2013-08-06 15:30 IST
Nmap scan report for lms.uom.lk (192.248.8.105)
Host is up (0.85s latency).
Not shown: 997 filtered ports
PORT STATE  SERVICE  VERSION
80/tcp  open   http Apache httpd 2.2.3 ((Red Hat))
|_html-title: Site doesn't have a title (text/html; charset=UTF-8).
443/tcp open   ssl/http Apache httpd 2.2.3 ((Red Hat))
|_html-title: Site doesn't have a title (text/html; charset=UTF-8).
631/tcp closed ipp


Service detection performed. Please report any incorrect results at http://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 69.74 seconds


Test 4 brute-force attacks to crack a password of a specific user



Number of attempts to login is stored in a cookie file. This is not a good security practice because an attacker can write a program to automatically reset the cookie file, he can continue to try new password values without being blocked.

So this introduces another security vulnerability which has to be addressed by the server end to ensure that no attacker is allowed to try a wrong password more than a certain number of times.









Threat identification



Following threats are present in the moodle system according to the tests that have been performed.


  • User account hacks
  • Server shutdowns and DoS attacks
  • User security policy violations



Attack identification



Attacks can be deployed by using the vulnerabilities.  


  • Session hijacking on the same machine.
  • Session hijacking through network interfaces.
  • automated user name- password brute force attacks.


Vulnerability-to-attack mapping



System vulnerabilities and respective attacks are listed below.


  • server port exposure - DoS attacks
  • inadequate security for cookie files - Session hijacking in same machine and through network interface.
  • session management by only using cookies - Brute force attacks by resetting cookies


Attack risk assessment



  • Identified risks are highly critical because an attacker can steal sensitive information or completely take down the system by gaining access to the system.
  • Data confidentiality and integrity is breached by such an attack and sensitive user data can be exposed to the public.
  • Availability of the service can also be compromised if an DoS attack is deployed.




Risk mitigation approaches/techniques covering software security



  • Decouple security options from cookie files because using cookies to control sessions is not a good security  practice and it could violate security policies. (attackers can easily use session variables in cookies to attack system)
  • Close all unused ports and block unauthorized access.
  • Increase security of the server center in order to increase physical security.


Physical security



  • Only authorized people are allowed to access the server rooms.  
  • Implementing a surveillance camera facility is recommended.



Data security



Sql injection threats are not found in the system. Databases should be kept securely so that no unauthorized access can be performed on the data.


User security

Session hijacking is present in the moodle system. So session management shall be improved to prevent this.


Server security


nmap can be used to identify open and closed ports on a remote server. If these details are known, an attacker may deploy a malicious application to a specific port.