Monday, November 16, 2009

How to Reset Sansa Mp3 Player when it Freezes

I got 2GB Sansa Mp3 player, as a complementary accessaries with Nikon CoolPix L20.
My Mp3 Player freezes, when I am charging it and accedentally unplug it, witout ejecting it. Some time it hungs while plying Song.

After couple of try I found few solutions that can reboot Sansa MP3 Player, and it works with my Sansa MP3 player.

1.  Turn ON the Hold switch. (move hold button to Hold Position)
2.  Press and hold Menu and Rec buttons at the same time until the Sansa MP3 player reboots.

Alternate Solution is :
Hold Menu (Power) button for atleast 20 seconds. Sometimes this trick works.

Hard Reset
To perform hardware reset on the Sansa Express, press and hold the "Select" button while pressing the Volume UP (+) buttons simultaneously once.

How to use ClamAv Antivirus on Ubuntu?

This tutorial will explain you, how to Install and use ClamAv Antivirus on Ubuntu. ClamAv antivirus is a free antivirus, available in ubuntu repository.

To install ClamAv antivirus and GUI to manage it on ubuntu 9.10,  use Ubuntu Software Center to install "KlamAV".  KlamAV is an anti-virus manager for the KDE desktop. It allows virus scanning, software/update databases, etc.

I am using "KlamAV" as a GUI tool to manage and use ClamAV antivirus.  You can also use "clamtk" as a GUI to use CLAMAV in Gnome or KDE.
Use following command to install "clamtk"
sudo apt-get install clamtk

Once it is installed on your machine,  then install anti-virus updater, so that you can get  latest update of ClamAV from Internet.
sudo apt-get install clamav-freshclam

Use command "sudo freshclam" to update ClamAV database. 
To check the version of ClamAV use following Command:
clamdscan -V


To do command line scanning:
1.  To scan specific folder:
     sudo clamscan -r /home/directoryname/subdirectory
     Above command will display the name of files in subdirectory on the screen. You can use -i parameter to display only infected files. 
2.  To scan all files on your computer
      sudo clamscan  -r   --bell  -i   /
     Above command will display only infected files and will bell the ring when virus found.
3. To remove infected file from your computer
    sudo clamscan -r -remove /









Friday, November 13, 2009

Lambda Calculus Type inference examples

1] \ x -> x
 Above function takes one argument and returns the same argument as result, therefore type of argument and return value must be same.

type: a - > a

2] \ x y -> x
Above function takes two arguments and returns the first argument as result, therefore type of first argument and return value must be same.

type: a -> b -> a

3] \f g -> g (f g)
Above function takes two parameter f and g.

To solve this, my algorithm is as follows:

First look at function body from right-to-left. Function body is g(f g)

Assume type of g is t1. That is,  ( g = t1).

Now, take next variable from function body, which is ff is a function that take g as argument and return value of any type, say return type is a. So far, there is no restriction of return value of f.  assume type of f is t1-> a. That is,  (f = t1 -> a).

Now, take next variable, which is gg is a function that takes return value of function f as a argument (a), and returns value of any type, say return type is b. So far there is no restriction of type of value return by g.  But we already assume g is of type t1.  Now, we found that g is function so, t1 is a - > b.
That is, (g = gt1 = a -> b).

Now replace t1 in f with (a -> b). So f becomes f = (a -> b ) -> a

we have done with function body. Now look at function declaration syntax. It takes two arguments f and g, and f is first argument, g is second argument, and return value is of same type of return value of g.

So type of function \f g -> g (f g) is as follows:

((a -> b) -> a) -> ( a -> b) -> b


4] \ x f g -> f g (x g)

 Above function accepts three arguments x, f and g
 Assume g is of type a. that is, (g = a).
 Now, x takes g as a argument and returns any type of value. So far there is no restriction on type of value returned by x, say return type of value is b
Therefore, x = a -> b


Now, f takes two argument g and return type of x. Return type of f has no restriction, so say it is of type c
Therefore, f = a -> b -> c

(Note: For simplicity as assume g as a variable. And is of type a. However, you can consider it g as a function then you have to unify a = d->e and replace all occurrences of a with d->e)

  Return type of f is the return type of this function.



Now look at function definition and arrange its type accordingly.


\ x f g -> f g (x g) type is as follows:

(a -> b) -> (a -> b -> c) -> a - > c 




5] \ f g x -> f ( g x)

Above function takes three arguments, namely, f , g ,and x.

Assume x is of type a., That is ( x = a)

Now g takes x as argument and returns a value. Assume return type of g is b.
Therefore, (g = a -> b)

Now f takes return value of g as argument (that is, b) and returns a value.
Therefore, ( f = b -> c)


So type of \f g x -> f (g x) is:
Now, look at function declaration: \f g x

(b -> c) -> (a -> b) -> a ->c


6] \x y f -> f (x (\w -> f w)) (y f x)

Above function takes three arguments, x y and f.

Now look at Function body, and assume type for each variable.
Let w = a
       x = t1
       y = t2
       f  = t3

 Observe the function body, f will be applied to on first argument (x (\w -> f x)),  and then it will be applied on second argument (y f x).

Go inside \w function,

 f = t3 = a - > b

Therefore, x = t1 = (a -> b) -> c

Return type of x is c, which will become the argument of f, therefore unification is possible here, and c = a;

Hence, x = t1 = (a->b) ->a

Now we examine ( y f x) part,

y = t2 = (a -> b) -> (a->b->a) -> d

d is the return type of y.

After applying the first argument (x(\w->f w)), f returns b.

Therefore, d is parameter of b.

b should take d as argument and return a value, That is, b = d -> e

Now replace each occurrence of b with d -> e

f = a -> b = a -> d -> e

x = (a ->b -> a ) = ((a -> d -> e)- > a)

y = (a ->d -> e) -> ( a -> d -> e) -> a) -> d

Hence type of entire expression is, (arrenge according to function definition:

((a -> d -> e)- > a) ->
 (a ->d -> e) -> ( a -> d -> e) -> a) -> d ->
(a -> d -> e) -> e

e is the return type of entire expression which is also the return type of f.











 

Wednesday, November 4, 2009

Plugins Vs Extension

Extension and plugins often confused people. And Mostly people believe both are same.
However, there is subtle difference between Extension and Plugin.  Extensions are mostly written in JavaScript and/or XUL and relies on XPCOM APIs to access resources. Whereas, plugins are binary applications and they make use of operating system and can do interaction with operating system or access events from OS.

Securing plugins is more complex than extension.  Extension are individual identity so one extension needs one set of privileges, whereas plugins are more complicated and needs to identify privileges for each application runs plugins rather than a whole plugin.

Tuesday, October 13, 2009

JavaScript Call Stack

This post explains how to get JavaScript Calls stack in Mozilla extension. You can also use jsdI interface hooks to get JS call stack. Pls refer jsdIDebuggerService on MDC.

You need to call the function callstack( ) to get the JSCall stack. From where to call this function is depend on need of user.  You can call this function wherever you want to get JS call stack.

function callstack( ){
/* stackFrameStrings holds entire JS calls stack in string format */

var stackFrameStrings = new Error().stack.split('\n');

/* remove first two stack frames because they are frames of callstack() and error() functions */
stackFrameStrings.splice(0,2);

  for (var i in stackFrameStrings) {
      /*
        A stack frame string split into parts. (example of stack frame string is:
        href("http://www.comp.nus.edu.sg")@:0)   Note 0 indicates native function call in Mozilla firefox, and 1 is for onclick, onmouseover functions, ie. JS event functions, otherwise the number is line number in source file and contains URL of source file. Anothe rexample of stack frame string is :
 onclick([object MouseEvent])@file:///home/patilkr/Desktop/Html%20Test/js_http_test.html:1
      */
      var stackFrame = stackFrameStrings[i].split('@');

    if (stackFrame && stackFrame.length == 2) {
                dump("\n stackFrame[0]=" + stackFrame[0] + " stackFrame[1]=" + stackFrame[1] );
   } // end of if loop

 }//end of for loop
} //end of callstack function
 

Wednesday, October 7, 2009

Mozilla Firefox about:config Tweaks

Accessing your about:config page
In your Firefox, type about:config in the address bar.

Disable Delay Time When Installing Add-on 

Config name: security.dialog_enable_delay
Default: 2000 (in msec)
Modified value:
  • 0 – start installation immediately 
  • any other value (in msec) 
View Source in Your Favorite Editor 
There are two configuration need to be made:
Config name: view_source.editor.external
Default: False
Modified value: True ( enable view source using external text editor)

Config name: view_source.editor.path
Default: blank
Modified value: insert the file path to your editor here.

Autohide Toolbar in Fullscreen mode  
Config name: browser.fullscreen.autohide
Default: True (always autohide)
Modified value: False (always show the toolbar)




 

Friday, October 2, 2009

90/10 and Self assement Principals

This is a non-technical post. It is about, how to improve yourself. How to improve your thinking and your life. Principals describe here, if you applied in your life then, they will surely help you to feel satisfaction.

First principal is 90/10 Rule:
What is 90/10 Principal? Well, it is very simple. 10% of life is made of what happens to you and 90% of life is decided by how you react to things happens in your day to day life.

Let me explain this in more detail:
We really have NO control over 10% of incidences that happens to us.
For example, We cannot stop plane from arriving late, we cannot stop mechanical devices from breaking down.  We cannot control this 10% of incidences happens to us, However, over the 90% of incidences we have control and our reaction to the situation is the key factor which plays an important role in deciding 90% of our life.

If someone says something negative about you,  do not be a sponge or do not lose your tamper.
Let the attack roll off like water on glass. You do not have to let the negative comments affect you.

React properly and it will not ruin your day. A wrong reaction could result in losing a friend, or getting stressed out.

Remember the 90/10 Principle and don’t worry about life.

You are told you lost your job. Why lose sleep and get irritated?  It will work out.

Use your worrying energy and time to find a new job.

Millions of people are suffering from stress,  problems and headaches.

We all must understand and apply the 90/10 Principle.
It can change your life! You will lose nothing if you apply it.


Second Principal is Self Assessment:
Self assessment means do a regular review of your daily activity/reaction/behavior  at the end of day.  It helps to make judgment about our own actions.

If you apply this two principals in your life, you will surely be get benefited from it, without lossing anything. You will observe its good effect in you life by yourself.

Friday, September 18, 2009

How to access other VMs and Internet on VirtualBox

VirtualBox supports NAT, host-only, Internal network and Bridged network options.
When Network card of VirtualBox VM is configured with "NAT" option then VM can access host machine and can access Internet, but cannot access other VMs. When I looked at IP address of VM's, I found that they all have same IP address.

VirtualBox assigns same IP to all virtual machine (for example, 10.0.2.15) when NAT is configured.  That is, it treats all VM as they on different physical network.

When Network Card of VirtualBox VM is configured with "Internal Network" option then VM can access other VMs but cannot access Internet.  In this case, all VM are on same physical network.

If you want to access other VMs as well as Internet, then the simplest solution is install two network cards in VM and assign one to NAT and another to internal network.  Then login to all VMs and assign unique address to internal network card of each VM. Note that, you have to assign address to network card which is configured for "Internal Network"  in VirtualBox.

That's it. Done. Now you can access Internet as well as other VMs.

Object Oriented Programming

Struct is use to define data types and group them into one object. Struct does not contain methods or functions, and its data members are all public. Struct are useful when we want sets of element with different data types.  Struct is a group of data elements grouped under one name. Those data elements are know as members and can have differnet type and different lengths.  Struct creates a new type. Once a struct is created a new type with the name of struct is created. It can be used later on in the program to create objects of struct.

A Class have both data members and functions/methods associated with it. A class can contain sever variables and functions/methods, those are called members of class. Bydefault all its members are private.

Class can define its member as private, protected, public.  Protected has a special meaning to inheritance. Protected members are accessible in the class that defines them as well as in the classes that inherit from that base class or friend of it.
 Class can contain special member functions called as constructors or destructors. Constructors cannot be explicitly called like regular member functions. They are automatically executed when new object of class is created. 

In principal, private and protected members of a class cannot be accessed from outside the scope of the same class in which they are declared.  However this rule does not affect friends. Friendship is no transitive and it is not bidirectional.

Inheritance is a key feature of C++ class. It allows to create a class which is derived from other classes, so it can automatically include/inherit members of base class.  When class inhertis from another class the members of derived class can access only the public/protected members of  base class, but cannot access private members of base class.
In principal, a derived class inherits every member of base class except its constructor, destructor, and its friends.

Virtual function/member: A member of class can be redefined in its derived classes is know as a virtual member.
When the type of pointer is pointer to base class but it is pointing to an object of th derived class, virtual keyword in-front of member functions allows a member function of a derived class with the same name as one in base class to be called from base class pointer to derived class object.

A class that declares or inherits a virtual function/member  is called a polymorphic class.

Abstract base class is a class that lacks implementation of atleast one member. Therefore, we cannot create object of that class (cannot create object of ABC - Abstract Base Class). These are the main differences between abstract class and a regular polymorphic class.   The function which lacks implementation is called as pure virtual function. for example, virtual int function_name() = 0; However, pointers of ABC (Abstract Base Class) can be used to point to objects of derived classes.

 Templates are special types that can operate with generic types. Templates allows us to create a function template whose functionality can be adapted to more than one type without repeating the entire code. That is, we don't need to write the same functionality code for different types such as int, float, char, etc. This allows generic programming, bocz it access any type object.

Vector better than Array and works as Array

Vector is a template class and it allows programmers to create a dynamic array of elements of one type per instance.
  Vector is conceptually same as arrays in C. However, vector size can expand to hold more elements and can shrink when fewer will suffice.

Note: Accessing members of vector or appending elements does not depend on vector size and takes fixed amount of time, however, locating a specific value element or inserting value element into vector takes the amount of time directly proportional to its location in vector.

//////////////////////////////////////////////////////////////////////
// Standard Template Library  (STL)
//
// Vector Functions:
//
// vector::push_back - Appends (inserts) an element to the end of a
// vector, allocating memory for it if necessary.
//
// vector::pop_back -  Erases the last element of the vector.
//
// vector::size - Returns number of elements in the vector.
//
//////////////////////////////////////////////////////////////////////


#include <iostream>
#include <vector >

using namespace std ;

int main()
{
    // Dynamically allocated vector begins with 0 elements.
    vector<int> theVector;


    // Add one element to the end of the vector, an int with the value 1.
    // Allocate memory if necessary.
    theVector.push_back(1) ;

    // Add two more elements to the end of the vector.
    // theVector will contain [ 1, 2, 3 ].
    theVector.push_back(2) ;
    theVector.push_back(3) ;

    int tmp;

    cout << "\n Enter new element on new line. press Ctrl +D to terminate " <
    while (cin >> tmp)
      theVector.push_back(tmp);

    // Erase last element in the vector.
    theVector.pop_back();
    theVector.pop_back();

    // Print contents of theVector. 

    cout << "theVector [" ;
    for (int k =0; k < theVector.size(); k++)
      cout <<" " << theVector[k];
   
    cout << " ]" << endl ;
}

Friday, September 11, 2009

Who calls main() function in C

The run-time environment calls the main function to begin program execution.
On Linux operating system, C runtime file can be found in either /usr/lib directory or /lib directory. 
crt0 (or crt0.o, gcrt0.o, mcrt0.o) is a set of execution startup routines  that are platform-dependent, and is required in order to compile using the GCC and other GNU tools.
crt stands for 'C runtime'.
Let me explain you the life cycle of c program:
1. Create a C program
2. Compile C program to generate object file.
3. Link object files (s)
4. execute the program
During compilation, compiler generates the object code for the program and for standard  C library functions used in program such as printf(), scanf (), etc, it puts the  entry in object file saying that "unresolved reference". 

Linking can be static or dynamic.  During static linking,
the static linker (ld) sees the unresolved reference to printf(), scanf(), and searches the available libraries for an implementation for printf(), scanf(), etc. In general this will be found in the C library (for example, libC ). Now, the linker has two options:

  1. Linker can take the printf(), scanf(), implementation from the library and copy it into the final executable accordingly. The linker then  searches the printf(), scanf() implementation for other unresolved references, and again consult the libraries for resolution. This  process will be performed iteratively until all references to the symbols were resolved. This is known as static linking.
     

  2. If the C library is realized as a `shared library', the linker can simply put a reference to the C library into the final  executable. This is known as dynamic linking.
     
      
    A statically linked executable is self contained. It is loaded into memory. The entry point, whose designation is system  dependent (for eg, the `__main' symbol) is found and called.
    In a dynamically linked executable, after loading the executable binary into memory, the dynamic linker (ld.so.1) takes control first. It reads the library references to dynamic libraries produced by the static linker, and loads them into memory. It then performs symbol resolution and updates all references to symbols in the shared library to point to their actual location, which can only be determined at runtime, because the shared libraries might be loaded to different memory locations each time the executable binary gets executed.
     
    
 

Thursday, September 10, 2009

C++ pointer

Pointers
Reference Operator (&)
The address that locates a variable within memory is what we call a reference to that variable.
A variable which stores a reference to another variable is called a pointer.
& is the reference operator and can be read as "address of"
* is the dereference operator and can be read as "value pointed by"
The declaration of pointers follows this format:
type * name;
 where type is the data type of the value that the pointer is intended to point to. This type is not the type of the pointer itself! but the type of the data the pointer points to.
For example:
int * number;
char * character;
float * realnumber;
These are three declarations of pointers. Each one is intended to point to a different data type, but in fact all of them are pointers and all of them will occupy the same amount of space in memory. Nevertheless, the data to which they point to do not occupy the same amount of space nor are of the same type: the first one points to an int, the second one to a char and the last one to a float.
Void Pointer
The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type.

Thursday, September 3, 2009

Makefile

Compiling the source code of your program/project on Linux/UNIX system is tedious, specially when program/project has several source files and you have to type command every time you want to compile it.

There is a utility called make to build the applications.   Make looks for a text file in the current directory called "makefile" or "Makefile" to execute.  Makefile is a file that instructs the program make how to compile and link a program. In this post I will explain, how to use GNU make utility with Makefiles. 

How to write comments in the makefile:
The comment in the Makefile is indicated by the comment character “#”. All text from the comment character to the end of the line is ignored.
Example:
# This is the comment in the Makefile
# Comment

How to define Variable in the Makefile:
You can define variable in the makefile.  Variable definition format is as follows:
VARNAME = Value
For example, Lets define a variable and set it to the compiler which I want to use to compile my program code.
CC = g++
CC is the variable name and g++ is the compiler I want to use to compile my program. 
 
How to use the variable:
We have define the variable CC above, now let me explain you, how to use it.
To use the variable syntax is as follows:
$(VARNAME)
In our example, we define CC variable, we can access the variable as follows:
$(CC) 
 
How to compile program using command line:
Suppose my program name is myprog.cpp. To compile it, I have to type following command:
g++ -o myexe myprog.cpp
 
Whereas myexe is an executable file name and myprog.cpp is the source file of my program.
If I want to compile my program multiple times then I have to issue this command multiple times.
Things become more complicated when I need to give some parameter to compile my program such as 
optimization parameters, library paths, etc.
 
Makefile comes for rescue here.  Create a new text file and named it as Makefile. Do not give any extension to it. 
Simply put the command (g++ -o myexe myprog.cpp) in the makefile, save the file, and at command
prompt type make
#Makefile
     g++ -o myexe myprog.cpp

Now suppose we have three source files namely mainprog.cpp, file1.cpp and file2.cpp.

Then you can create a makefile as follows:
g++ -c -o file1.o file1.cpp
g++ -c -o file2.o file2.cpp
g++ -o myexe mainprog.cpp file1.o file2.o
 
You can now make use of variables and can make the Makefile much simpler as shown below:
 
COMPILER=g++
OBJS=mainprog.o file1.o file2.o
default: myapp
myapp: $(OBJS)
 $(COMPILER) -o myexe $(OBJS)
 
You only need to issue only the make command everytime you want to compile you program, that's it.
If the source file in your project increses then you only have to add filename.o to 
OBJS variable list, that's it. Very simple. 

Wednesday, September 2, 2009

JavaScript Scramblers / Obfuscators Softwares and Techniques they used

There are many JavaScript Scrambling softwares/tools available on Internet.
All of them aims to scramble the JavaScript source code to prevent the theft of JavaScript Code.
Obfuscated code is a source code that is very hard to read and understand. 
Macro preprocessors are often used to create hard to read code by masking the standard language syntax and grammar from the main code.

How to create hard to read code (Obfuscated code)?
Take a JavaScript code in .JS files or in HTML files as a input  and replace descriptive variable and function names like Customer, Salary, FirstName... with meaningless names like x0de234f, III111000, oo00ooo... 
Also removes comments and unnecessary whitespace characters (space, tab, carriage return, line feed). The functionality of the code remains the same while source code changes dramatically. This process is called obfuscation, and the tool is called obfuscator.

I tried to find and collect under one roof information about JavaScript Obfuscators.

1. Stunnix JavaScript Obfuscator
 Stunnix JavaScript Obfuscator converts scripts in input files into highly mangled and obfuscated form, while fully retaining  functionality of the original code.
 It provides different encoding techniques such as MD5 (Message Digest version 5), set of o and 0, and set of I and 1 for identifiers/variables/function names. Similarly it provides different encoding technique such as Hex escapes, List of codes for strings. It uses regular expression to replace numbers. It gives freedom to the programmer to select encoding technique of there choice to make JavaScript code difficult to study and analyze. It is also possible to encode the code using one set of encoding techniques and again encode the encoded code using different set of encoding techniques supported by the tool. For example, first encode using a set {MD5, Hex escapes, regular expression} and then encode the encoded code using same or another set of supported techniques by the tool such as {set of o and 0, List of codes, regular expressions}.   
 Examples of Encoding techniques of Stunnix tool are given below:
 Encoding for Identifiers/variables/function name:
  1. MD5: Message Digest version 5, 
   It generates hash value for identifier/variable_name or function_name and replaces the occurrence of identifier/variable with its hash value. (for example every occurrence of FACTORIAL function name in the script is replaced with it hash value Z001C775808)
  2. set of I and 1
   It generates a unique set of I's and 1's for each identifier/variable_name ( for example every occurrence of      SHOW_TOP_RECORDS function name in the script is replaced by IlIlIIIllI)
  3. set of o and 0 
   It generates a unique set of o's and 0's for each identifier/variable_name ( for example every occurrence of      SHOW_TOP_RECORDS function name in the script is replaced by o0o0ooo00o)
 Encoding for strings in the script:
  1. Hex escapes
   It uses Hex encoding for strings (for example no entries is replaced with  \x3c\x62\x3e\x6e\x6f\x20\x65\x6e\x74\x72\x69\x65\x73\x3c\x2f\x62\x3e)
  2. List of Codes
   Adds some constant prefix such as ReplacementFor_ to every occurance of string. (for example  strcomputer variable is replaced with ReplacementFor_strcomputer)
 Encoding for numbers/digits
  It uses regular expression to encode numbers in the script. (For example every occurrence of number 232 is get replaced with 0x14b6+2119-0x1c15 in the script)

2. TagsLock Pro. 
 Replaces string characters (ASCII) with hexadecimal equivalent value and each preceded by a percent symbol. (For example, space character is hexadecimal 20, so the encoded version of a space character is %20)
 It uses JavaScript inbuilt function escape() to generate encoded version of string and uses inbuilt JavaScript function unescape() to decode it.

 For example:
   Original JavaScript:
      document.write("Hello, world!");    

    Scrambled JavaScript:

          document.write(unescape('%3cs%63ript%3e%3c%21%2d-%0d%0ado%63ument.write("%48%65llo%2c %77orld%21"); %0d%0a%2f%2f %2d%2d%3e%0d%0a%3c/s%63%72i'+'pt%3e %0d%0a%0d%0a'))      


3. iWeb Tool. 
 Similar to TagsLock Pro, iWeb tool uses escape() function to convert string (ASCII) into hex encoding.  But to make it more confusing it perform encoding on hex encoded string and converts hex encoded string into unicode. 
 To decrept it uses a inbuilt JavaScript function String fromCharCode() to convert it from Unicode to hex codes and then using unescape () function converts hex codes into a string (ASCII). 
 It keeps the Javascript inbuilt function name as it is, such as document.write in original source code will as it is appear in encoded code.
 For example:
 Original Code:
   document.write("Hello") 
 
Encrypted Code:
  var enkripsi="'1Aqapkrv'1Gfmawoglv,upkvg'0:'00Jgnnm'00'0;'1A-qapkrv'1G"; teks=""; teksasli="";var    panjang;panjang=enkripsi.length;for (i=0;i2) }teksasli=unescape(teks);document.write(teksasli);


4. Javascript Obfuscator v2.53. 
 It reads files with JavaScript code and replaces each occurance of descriptive
variable and function names like CHILDNODE, FIRSTNAME, LASTNAME... with meaningless names like Ia, g, m... 
It also removes comments and unnecessary whitespace characters (such as space, tab, carriage return, line feed).

5. Ajaxian JavaScript Obfucator. 
 It is same as JavaScript Obfuscator v2.53. 
 And Like a iWeb tool, it does not replace document.write() function name, that is the rule is not to replace the function name or vaiable name if it has ".". 

6. JavaScript Scrambler v1.11. 
 It is the simplest JavaScript Obfuscator, which removes comments and unnecessary whitespace characters. It keeps the variable names and Javascript code as it is; except only changes function names in the original code. (for example,  every occurance of function name "doTICKER" is get replaced with "x0822631")


References
1. Stunnix JavaScript Obfuscator. http://www.stunnix.com/prod/jo/
2. TagsLock Pro. http://www.aerotags.com/faq/tips-js-protection.php
3. iWeb Tool. http://www.virtualpromote.com/tools/javascript-encrypt/
4. Javascript Obfuscator v2.53. http://javascript-source.com/javascript-obfuscator.html
5. Ajaxian JavaScript Obfucator. http://ajaxian.com/archives/utility-javascript-obfuscator
6. JavaScript Scrambler v1.11. http://www.quadhead.de/jss.html

Obfuscated code examples

In this post I will give to some examples of JavaScript Obfuscation.
Example 1:
This following code is obfuscated using online JavaScript Obfuscator on http://www.javascriptobfuscator.com/
Plain text Code:
var a="Hello World!";
function MsgBox(msg)
{
    alert(msg+"\n"+a);
}
MsgBox("OK");
Obfuscated code:
var _0x8e48=["\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21","\x0A","\x4F\x4B"];var a=_0x8e48[0];function MsgBox(_0xab5dx3){alert(_0xab5dx3+_0x8e48[1]+a);} ;MsgBox(_0x8e48[2]);
 
You can apply multiple level of obfuscation by repeatedly obfuscating the obfuscated code.
Following obfuscated code is 2 level obfuscation of plain text code given above.  That is, obfuscation of obfuscated code.
Obfuscated code of the Obfuscated code given above:
var _0x1c08=["\x48\x65\x6C\x6C\x6F\x20\x57\x6F\x72\x6C\x64\x21","\x0A","\x4F\x4B"];var _0x1bae=[_0x1c08[0],_0x1c08[1],_0x1c08[2]];var a=_0x1bae[0];function MsgBox(_0xc9d7x4){alert(_0xc9d7x4+_0x1bae[1]+a);} ;MsgBox(_0x1bae[2]);

Example 2:
The following code is obfuscated using  online JavaScript Obfuscator. http://www.virtualpromote.com/tools/javascript-encrypt/
Plain text code:
document.write("hello, world");
 
Obfuscated code:
var enkripsi="'1Aqapkrv'1G'2Cfmawoglv,upkvg'0:'00jgnnm'0A'02umpnf'00'0;'1@'2C'1A-qapkrv'1G";
teks="";
teksasli="";
var panjang;
panjang=enkripsi.length;
for (i=0;i
  teks+=String.fromCharCode(enkripsi.charCodeAt(i)^2)
}
teksasli=unescape(teks);
document.write(teksasli);

In the second example, document.write is used. So during parsing of the code in the browser (for example, Firefox), DOM nodes will be get created for obfuscated code and for each level of  de-obfuscated code.

Saturday, August 29, 2009

Obfuscated Code

When source code in programming language is transform to human unreadable form then it is known as Obfuscated Code.  The software that performs obfuscation on code are called as obfuscators.
Obfuscation on the source code can be used for good purpose as well as for bad purpose. Programmers can obfuscate there code to conceal its purpose, to avoid theft of there code. This is also known as security through obscurity. On other hand, attackers can use obfuscator to hide malicious program. 
The code written in languages which can be obfuscated  includes but not limited to are C, C++, Perl, JavaScript, etc.
Obfuscation by code morphing  refers to obfuscating machine language code or object code rather than obfuscating the source code.

Obfuscated code makes it difficult to reverse engineer the code, but it is not impossible to reverse engineer the obfuscated code.  Obfuscated code makes it difficult to debug, because the variable names no longer make sense, and the structure of code is hard to recognize.

In this post I will mainly focus on the JavaScript Obfuscators, techniques used for JavaScript Obfuscation, and JavaScript Obfuscation used in malicious software.

Obfuscated JavaScript code is mostly used by spammers in spam messages.   The obfuscation makes it difficult for investigators to identify what exactly the JavaScript code does? or where the link goes?. Attackers used JavaScript Obfuscation to conceal an entire or some part of code that runs browser exploit. 


The good news about JavaScript source code obfuscation techniques  is, they are limited to number of techniques (de-obfuscation) supported by Web browser. However the bad news is, it is not limited to number of levels of obfuscation on source code.   

Friday, August 28, 2009

While mixing C and C++ code, how to avoid name mangling done by C++ compiler for C Code

C language does not have overloading, that's why C  function names are not mangled by C compiler (such as GCC), but C++ has overloading. Overloading means the same function name can appear for more than two functions in C++ with different parameters. That's why C++ complier do name mangling to identify the function names uniquely. 
You may encounter a problem while writing you own library by mixing C and C++ code. because you  have to compile it with C++ compiler and it will mangled the function names. If you want to avoid the mangling of function names done by C++ compiler then you can use extern "C" keyword in the code. This will tell C++ compiler that do not mangled function names, variable names, defined in extern "C" brackets.
For example:
extern "C"
{
   int functionx();
}
The name of functionx will not be get mangled by C++ compiler. 

Wednesday, August 26, 2009

Firefox-3.5 debugging problem on Ubuntu9.04

I and my colleague Xinshu are working on Firefox-3.5 web browser and from last few months since Firefox-3.5 is released we were searching for how to debug Firefox-3.5 with gdb on ubuntu v9.04. We are able to debug Firefox-3.0 with gdb on ubuntu v9.04, but we were not be able to debug Firefox-3.5. Whenever we tried to debug Firefox-3.5 with gdb debugger, GDB sometimes terminated by giving "Segmentation Fault" error , or sometimes terminated by giving memory leak error. So we developed a wrong impression that Firefox-3.5 cannot be debug with gdb in Ubuntu v9.04, because official version of Firefox-3.5 for ubuntu is not yet released. Ubuntu has Firefox v3.0.13 in its repository. However for Fedora and Windows, Firefox v3.5.2 is available. We searched on many blogs/forums, etc for the solution or does somebody faced/facing the same problem as we do. Many of them misdirected by saying some package is missing on your machine, which is required for Firefox-3.5 to debug on Ubuntu v9.04. We installed all the packages named on those forums, but had no luck, till today.
My colleague (Xinshu) finally discovered the caused of error. And the solution was very simple, but not convenient for users who has many Firefox profiles for different purpose .
When we looked into terminal window, we found that GDB terminated after Firefox creates a new process. And new process is created when you have multiple profiles on your system, and selecting the one out of them each time Firefox starts, was the source of error. Firefox creates a new process whenever we select the profile.
So we tried by deleting all profiles, and it was miracle, it really worked. The solution is very simple, delete all Firefox profiles and then try Firefox-3.5 to debug with GDB on Ubuntu. It works!.
Although it is not convenient to users who have many profiles.

DOS attack on Firefox

Denial of Service (DOS) Attack for Firefox
It is caused by consuming memory on user computer.
The main reason, why this attack is possible on Firefox is insufficient memory check at document.write function.
The parser first builds DOM tree on received input before it is displayed to user (or it is given to rendering unit). Following code consumes all available memory on your system, if you have quad-core processor with 4GB RAM then following code will terminate on that machine after few hours. (approx, 8 to 10 hrs)

The sample code is given below:
var a;
for (var i=0; i < 32000; i++) {
document.write(a+=i));
}
document.write("Terminated");
 

Backtrace is as follows:
nsScannerString::AppendBuffer()
nsScanner::AppendToBuffer()
nsScanner::Append()
nsParser::Parse()
nsHTMLDocument::WriteCommon()
nsHTMLDocument::ScriptWriteCommon()
nsHTMLDocument::Write()

Chrome browser uses behavior analysis to detect unresponsive scripts/programs.
Function call analysis will not work correctly on such kind of examples, bcoz attacker can create the same effect (DOS attack) in many different ways.
Mozilla has dom.max_script_run_time variable which is set 10 by default. In debug mode, Firefox would prompt user with a warning against that unresponsive script; however, this warning does not appear in normal mode and the script hangs Firefox (or even the whole system) after some time. In another word, Firefox has built-in check for unresponsive script, but this mechanism somehow just won't work for this example in normal mode. 
I tested the above code in Internet Explorer, but IE show a pop-up window and ask user, he want to terminate the script  or want to continue the execution of script. I think that's the expected behaviour. 

Tuesday, August 25, 2009

Encrypted Virtual File System (EVFS): Building a encrypted Linux filesystem from an ordinary linux file

This tutorial will explain step-by-step process to create Encrypted Virtual Linux File System (EVFS).

First let me explain you, What are the advantages of EVFS:
1. You can take a disk file, format it as an vfat, ext3 filesystem, and then mount it, just like a physical drive. This is an excellent way to investigate different filesystems without hassle of reformatting a physical drive.

2. It protects unauthorized access to the information.

3. It is a single file which will acts as encrypted virtual disk, that will store files, directories inside it.

4. The big advantage is, it is Portable. The file we create here will open as encrypted virtual disk in windows, Linux, etc.


We will use LUKS (Linux Unified Key Setup) standard for creating encrypted virtual file system.
LUKS is a standard for hard disk encryption. Most disk encryption software implements different and incompatible formats, LUKS specifies a platform-independent standard on disk format for use in various tools on different operating systems such as Windows, Linux, etc

In this article, I will explain how to create encrypted virtual disk, how to use it on Linux and how to use it on windows.

A. How to create Encrypted Virtual Disk
  • Step1: Create a file with desired size. (The size you will specify here will be the size of your virtual disk.)
dd if=/dev/urandom of=disk.img bs=1M count=10

I used urandom to fill the file with random values. You can use if=/dev/zero instead of if=/dev/urandom to fill the file with zeros. Bydefault dd uses 512bytes as a size parameter. We define custom size using bs argument, as show in example (in blue colour). The bs argument accepts common suffixes (k, M, G) for large numbers. bs specifies the number of bytes read into memory with single read() system call and written out with s single write() system call. I created 10MB file in this example. (size = bs * count). You can tune the bs and count parameters according to your need.
  • Step 2: Make the file we created as a disk device
sudo losetup /dev/loop0 disk.img

Loop device makes a file accessible as a block device. losetup command associats the file (disk.img in our example) with loop device (loop0 in our example)
  • Step 3: Now we have a partition of 10MB. In this step we will encrypt that partition.
sudo cryptsetup luksFormat -c aes -s 256 /dev/loop0

-c parameter is used to specify cipher. I used AES (Advanced Encryption Standard) in this example.
-s parameter is used to specify keysize for cipher in bits. It must be multiple of 8 bits. In this example I used 256 bit cipher key.

(Note: You can tune above parameters according to ur need)

(Note: This will ask you for confirmation before proceeding, you have to type YES in uppercase, if you want to continue. Then it will ask you for password for EVFS. This password you have to use whenever you want to access EVFS).
  • Step4: Now tell Linux to treat the encrypted partition as a Disk Device.
sudo cryptsetup luksOpen /dev/loop0 krp

krp is the name of disk device. you can use any name there.
  • Step5: Now Format the file system on ths disk
sudo mkfs -t vfat /dev/mapper/krp
  • Step6: Done. Cleanup the system now.
sudo cryptsetup luksClose krp
sudo losetup -d /dev/loop0

Now we have a single file as a encrypted virtual file system. In that file we can store any data which we want to hide from others. And as it is a single file you can move it from one machine to another machine without hassle of reformatting and installation of OS.


B. How to use Encrypted Virtual File System on Linux

Step 1: Tell Linux to treat this file as a disk device

sudo losetup /dev/loop0 disk.img

Step2: Tell Linux to treat the encrypted partition as a disk device

sudo cryptsetup luksOpen /dev/loop0 kailas

Step3: Mount the disk

sudo mount /dev/mapper/kailas /mnt

Now you can access the files in directory /mnt
You can create new files there or copy files there. Those files will be stored in your encrypted Virtual FileSystem.

C. How to cleanup EVFS after using it on Linux

sudo umount /dev/mapper/kailas
sudo cryptsetup luksClose kailas
sudo losetup -d /dev/loop0


D. How to use Encrypted Virtual File System on Windows

To open/access the EVFS we created above on Windows, download a open source free software FreeOTFE.
Install the FreeOTFE software, then launch the FreeOTFE software.
Select "File-> Linux Volume -> Mount File"

Enter the password of EVFS. FreeOTFE will show the virtual drive. Done!.