Archive for the ‘Codes & Utilities’ Category


After almost one year after the announcement of the Java Card 3.0, Sun finally releases it!
Java Card technology enables smart cards and other devices with very limited memory to run small applications, that employ Java technology. It provides smart card manufacturers with a secure and interoperable execution platform that can store and update multiple applications on a single device.

Deployed in markets as diverse as Telecommunications (SIM applications), Finance (EMV) and Citizen ID (Passports and ID Cards), Java Card technology is the most pervasive open platform for secure devices, with over 3.5 Billion Java Powered smart cards deployed worldwide.

Sun Microsystems
has now released the latest specifications of its market leading Java Card technology, and industry experts believe it will revolutionize the way smart card services are conceived and deployed.

Next Generation Java Card technology will be available in two separate, yet coherent editions.

Java Card technology, Classic Edition is based on an evolution of the Java Card Platform, Version 2.2.2 and targets more resource-constrained devices that support traditional applet-based applications. It introduces several incremental changes to the previous version to ensure alignment with smart card and security standards.

Java Card technology, Connected Edition features a significantly enhanced execution environment and a new virtual machine. It includes new network-oriented features, such as support for web applications, and support for applets with extended and advanced capabilities.

Both Editions are compatible with applications written for previous versions. They also share key security features and build on the trust and expertise derived from ten years of deploying secure Java Card products.

The specifications can be downloaded from here.

Blogged with the Flock Browser

If you are interested in robotics, wireless sensors, java, or embedded systems programming and you have not heard of SunSPOTs yet, you really live somewhere on Mars.

Sun SPOT (stands for Small Programmable Object Technology) are very powerful and sophisticated little devices, perfect for sensor-based applications, and pervasive computing.

It is a battery-operated (USB charged) platform for development of radio-controlled sensor networks, robotics, and personal consumer electronics. Each kit comes with a base station and two Spot devices, each of which, in turn, includes a processor, a radio, a sensor board, and battery. You can also add servo motors and your own sensors on top of the acceleration, temperature, and light sensors that come with each Spot. You program and build the Java VM-based Spots to do whatever it is you want to build; examples of Spot applications developed so far include microwave detection, robotic-arm control, and slot-car control.

sun-spot-ceo_small.jpg

Sun SPOT

Technically a Sun SPOT has the following:

  • a 3-axis accelerometer (with two range settings: 2G or 6G)
  • a temperature sensor
  • a light sensor
  • 8 tri-color LEDs
  • 6 analog inputs readable by an ADC
  • 2 momentary switches
  • 5 general purpose I/O pins and 4 high current output pins

Sun has also introduced a Sun SPOT Open Grant Program and a Request for Proposal is currently open. For details go here.

Sun Labs staff engineer, David G. Simmons, has an extremely helpful Sun SPOT blog that is worth checking out. And even YouTube has some 40 Sun SPOT videos with slot cars, a pumpkin that screams and talks when shaken, video games and more to check out. Also, for more on Sun SPOTs check out Roger Meike’s blog; he’s senior director of area 51 and director of operations at Sun Labs.

Blogged with the Flock Browser

The world celebrated the Software Freedom Day on 15th September 2007. We had some 100+ countries and more than 300 groups covering the free software world in different form of activities, presentations and events. The webmasters of FAST-NU Karachi also organized an event and talk series on the day and I felt really honored and delighted when I got an invitation to speak before the undergraduates of what open source is and how it is used in the industry.

I chose the topic “Open Source in the enterprise” picking up the best open source projects I use frequently and have known to be used as solid, industry standard applications in different domains. It was a wonderful experience going back to my university and meeting with a bunch of brilliant future computer scientists.

The slides of the presentation can be found here.


A pretty common task these days at work is migration and upgrading of older 1.1 framework code to the 2.0 framework. Some of the code is really straight forward to port to for example the System.Management Namespace based classes. However to leverage the new features of 2.0 a few changes must be made.

For anyone developing in .Net 2.0, Generics are definitely a great tool, allowing cleaner and more type-safe code. I was interested in how the use of Microsoft’s provided Generic classes in System.Collections.Generics performed relative to their non-generic alternatives.

I am often running into a question of whether or not I should bother changing out liberal use of the Systems.Collections classes in older code to use Generics. So I ran some tests….

Probably the most common collection used in pre-2.0 code is the ArrayList, so in these test I have compared the System.Collections.ArrayList class to the System.Collections.Generic.List class.

I created a c# console app in Visual Studio 2005, that ran a set of common operations against the two collections.The Complete code listing can be found at the end of the post.

I did a worst-case load for both generics and collections, letting the collection dynamically resize for random integer insertion, which is followed by a sort, and a traversal using the Contains() method. All of the items are 32bit Integers.

The test for Arraylist is exactly the same as the List test, with the obvious exception of the collection declaration. I ran the series of operations against the two collections with increasing item counts, and programatically timed them.

Result Output:

Size: 10000
Time taken by Collection: 15.6042 ms
Time taken by Generic: 0.002 ms

Size: 100000
Time taken by Collection: 187.2504 ms
Time taken by Generic: 15.6042 ms

Size: 250000
Time taken by Collection: 546.147 ms
Time taken by Generic: 62.4168 ms

Size: 500000
Time taken by Collection: 1263.9402 ms
Time taken by Generic: 218.4588 ms

It’s pretty clear who the winner is here. The Generic.List collection comes out substantially ahead of the ArrayList.

Not only is the Generic class faster, but it appears to scale substantially more linearly than the ArrayList, and handles the 10 million items in <1 second, compared to the 21+ seconds of the ArrayList.

From running a few more tests, I learnt that the real bottleneck on the Arraylist was during sorting and traversing the list. Each item is stored as an object, so it must be typed runtime, and then compared for sorting/searching. On the other side, the Generic List had all its items typed compile time, which saves alot of workload during sorting and searching.

So the first thing that comes to my mind, was that perhaps the collection logic was improved for the List, and it was dynamically resizing in a smarter fashion, which helped give it such a substantial speed increase. So I ran an interesting test…. I modified my code to use a List<object> instead of List<int>, so in theory, it would perform just as the ArrayList unless some other collection logic had changed.

The results were surprising. A List<object> performed within 5 ticks of ArrayList on any number of items.

This confirms that the performance gain of Generic Collections is entirely due to dropping the Object wrapper, and ridding us from the need to use Reflection on each object. So in conclusion, I can’t imagine wherein you would EVER want to use an Arraylist or SortedList in your .Net 2.0 code.

Happy coding.

using System;
using System.Collections;
using System.Collections.Generic;

namespace GenericCollectionComparison
{
internal class Program
{
public static int Length = 100000; //Int32.MaxValue;
private ArrayList arrayList;
private List genericList;
public static DateTime startTime;
public static DateTime endTime;
public static TimeSpan timeSpan;
public Random randomNumber = new Random();

public void fillCollection()
{
arrayList = new ArrayList();

for (int i = 0; i < Length; i++)
{
arrayList.Add(randomNumber.Next());
}

arrayList.Sort();
arrayList.Contains(randomNumber.Next());
}

public void fillGenerics()
{
genericList = new List();

for (int i = 0; i < Length; i++)
{
genericList.Add(randomNumber.Next());
}

genericList.Sort();
genericList.Contains(randomNumber.Next());
}

private void Run()
{
Console.Out.WriteLine(“Size: ” + Length);
startTime = DateTime.Now;
fillCollection();
endTime = DateTime.Now;
timeSpan = endTime.Subtract(startTime);
Console.Out.WriteLine(“Time taken by Collection: ” + timeSpan.TotalMilliseconds + ” ms”);

startTime = DateTime.Now;
fillGenerics();
endTime = DateTime.Now;
timeSpan = endTime.Subtract(startTime);
Console.Out.WriteLine(“Time taken by Generic: ” + timeSpan.TotalMilliseconds + ” ms”);

Console.WriteLine(“”);
}

private static void Main()
{
Program program = new Program();
for (int i = 10000; i < Int32.MaxValue; i = i + 10000)
{
Length = i;
program.Run();
}
}
}
}


Im pleased to announce that My Remote Command Executor Project RemCom is now officially being used in Open Computer and Software Inventory  Next Generation Project , which is one of the most widely used and successful hardware / software inventory, configuration and patch management open source project on sourceforge. You can see the link on this page for credits.

Special Thanks to Emmanuel GUILLORY of the OCS Inv Project for her insightful suggestions, recommendations and help.

powered by performancing firefox

RCE Update

Posted: October 26, 2006 in Codes & Utilities, Programming

Just fixed a bug in RCE where the RunAs command wasnt working on a Windows 2000 Based System. The problem was with the LogonUser API call which on W2K based systems need an SE_TCB_NAME privilege to execute (which by default is only given to the SYSTEM account). Apparently Microsoft lifted the restriction with XP and Server 2003. More details about the issue can be found here:
The updated release can be found on the sourceforge here:

http://sourceforge.net/project/showfiles.php?group_id=174757

Thanks to Emmanuel for pointing the bug out.


Debugging through console watches is powerful where you step in each call and trace the code logic. However As systems evolve and grow more complex with increasing other dependencies (special frameworks, third party tools, environment / OS /patch dependencies) catching memory leaks and usage becomes a nightmare and the ability to peer into their inner workings becomes increasingly valuable.

Say for example you’re working on some component which is to be deployed on a terminal with limited memory and hardisk (POS / Self Service Machines for instance have real limitations in terms of systems resources and RAM). Many developers often overlook these scenarios which causes a problem in the long run.

This article describes some very useful techniques for debugging and profiling .NET based applications. Profiling is a technique used to analyze and determine the exact behavior of your managed applications in realtime (without the source code).

Profiling analyzes:

+ What is going on in the garbage collector heap (Useful for finding heap corruption bugs as well)
+ Method / Object memory allocations.
+ Which methods allocate which types of objects?
+ Which objects survive and time durations.
+ What is on the heap and who is accessing it.
+ What keeps objects alive (useful for determining orphan objects which could have been deallocated to save memory)
+ Call graphs let you see who is calling whom how often.
+ Which methods, classes, modules get pulled in by whom.

The profiler is a good tool to use when you want to find out what’s happening in memory. For instance, ASP.NET developers using InProc sessions state are always curious about how much memory they are using.

Below are some screenshots I took for profiling a sample application.

Application Startup:

Class Graph:

Heap Graph:

Timelines (How much memory is being used at what time)

Application Call Tree:

Resources:

The following sample application profile trace was taken with the CLR Profiler Tool by Microsoft. There are other commercial offerings such as Jetbrains dotTrace and ANTS Profiler with other enhanced functionalities, reporting and automation.

An excellent MSDN article with a sample application using .NET profiling API can be found here:

Blogged with Flock.


Microsoft just released a utility (ILMerge) merge multiple .NET assemblies into a single assembly. ILMerge takes a set of input assemblies and merges them into one target assembly. The first assembly in the list of input assemblies is the primary assembly.

When the primary assembly is an executable, then the target assembly is
created as an executable with the same entry point as the primary
assembly. Also, if the primary assembly has a strong name, and a .snk
file is provided, then the target assembly is re-signed with the
specified key so that it also has a strong name.

ILMerge is packaged as a console application. But all of its
functionality is also available programmatically. Starting with Visual
Studio 2005 it is allowed to add an executable as a reference, so you
can write a C# client that uses ILMerge as a library. If you are using
Visual Studio 2003, you must use the v1.1 version of ILMerge and rename
it to be a dll in order to use it as a reference.
ILMerge installer and documentation can be found here.

Blogged with Flock


Due to quite a decent response (Around 40% of the daily traffic i recieve) and quite a number of requests for source code over my Remote Command Execution Tool , i have opened up a project at sourceforge for it. The URL for the project is: http://rce.sourceforge.net or http://sourceforge.net/projects/rce/ .

Thanks for all those people who emailed me their valuable ideas and requests.

Blogged with Flock.


One of the biggest challenges faced by programmers, architects, testers, and security consultants is to understand the consequences of their applications when deployed into production. Even with access to source code, it is difficult to understand everything that will occur during execution due to a variety of dependencies (for example. Different OS platforms, multiple patch levels, multiple groups contributing to code or leveraging external components).

The Microsoft Application Verifier is a runtime verification tool for unmanaged code that assists in quickly finding subtle programming errors that can be extremely difficult to identify with normal application testing. It is designed specifically to detect and help debug memory corruptions and critical security vulnerabilities. It makes it easier to create reliable applications and on the other hand find potential vulnerabilities by monitoring an application’s interaction with the OS, profiling its use of objects, the registry, the file system, and Win32 APIs (including heaps, handles, locks, and more). It also includes checks to predict how well the application will perform under Least-privileged User Account operation.

Application Verifier Identifies whether the applicaion:

• Is using:
Unsafe TerminateThread APIs.
Correct use of Thread Local Storage (TLS) APIs.
Correct use of virtual space manipulations (for example, VirtualAlloc, MapViewOfFile).
• Is hiding access violations using structured exception handling.
• Is attempting to use invalid handles.
• Contains memory corruptions or issues in the heap.
• Runs out of memory under low resources.
• Usage of critical sections is correctly occurring.
• Will run well in an environment with less privilege.
• Has any potential problems when the application is running as a limited user.
• Has uninitialized variables in future function calls in a thread’s context.

Tests within AppVerifier :

The tests included in the Application Verifier are to help software developers avoid common mistakes by using verification layers to validate the usage of API families:

Basics Verification – These are the core set of tests that check for issues within heap, handles, locks, and more.
Low Resource Simulation Verification – This test simulates an environment under low resources for example, out of memory.
Limited User Account Predictor Verification – This test simulates an environment running as a user with a limited user account in either predictive or diagnostic mode and identifies potential problems accordingly.
Miscellaneous Verification – This consists of two checks: Dirty Stacks and Dangerous APIs.

Getting and Installing Application Verifier:

The latest version of Microsoft Application Verifier can be downloaded from here . The installation is pretty simple and a straightforward next next.

Using the Application Verifier Tests:

The AppVerifier can be run through either the User Interface and / or automated through the command line. I will describe both these process in detail. The expectation for these scenarios is that the application does not break into debugger and all tests pass with the same pass rate as when run without AppVerifier enabled.

The Basic Tests:

1. Enable verifier for the application(s) you wish to test using:
From the command line: appverif /verify ApplicationToTest.exe or from the user interface:

Add your application by right-clicking within the Applications area and clicking Add Application. Select Basics from the Tests area and click Save.

Note:
• /verify enables the basic tests.
• If you are testing a DLL Application, AppVerifier has to be enabled for the test .exe that is exercising the DLL. You cannot debug a standalone DLL.
• Run the verification layers separately.

2. Run ALL your test exercising the application.
3. Analyze any debugger breakpoints encountered. If a break occurs, you need to understand why and fix it. (The Help contents provide details on the breaks and how to investigate them.)

Finally from the command line: appverif /n ApplicationToTest.exe or from the user interface:
Remove your application by right-clicking within the Applications area and clicking Delete Application and click the Save button.


The Low Resource Simulation and Fault Injection :

The expectation for this scenario is that the application does not break into the debugger. This means that you have no errors that need to be addressed. The pass rate for the tests may decrease significantly since random fault injections are introduced into the normal operation.

1. Enable Application Verifier low resource simulation (fault injection) for the application(s):
From the command line: Appverif /verify ApplicationToTest.exe /faults or from the user interface: Select Low Resource Simulation from the Tests area and click save.

Note: If you are testing a DLL, you can apply low resource simulation (fault injection) on a particular DLL instead of the whole process. The command line format would be:
appverif /verify TARGET [/faults [PROBABILITY [TIMEOUT [DLL …]]]]
Example: appverif /verify ApplicationToTest.exe /faults 5 1000 d3d9.dll

2. Run ALL your tests exercising the application.
3. When finished, delete all settings. Analyze any debugger break(s) encountered. If a break occurs, you will need to understand why and fix it.
4. When finished, delete all settings:

Running with and without fault injection exercises largely different code paths in an application and therefore both scenarios must be run in order to get the full benefit of AppVerifier.


Analyzing AppVerifier Data :

All data created during AppVerifier analysis is stored in the %ALLUSERSPROFILE%\AppVerifierLogs folder in a binary. These logs can then be converted to XML via the user interface or command line for further analysis. To view the XML files, use any: 1. Web Browser 2. Create an XSLT transformation to convert raw XML content 3. Import into Excel or any Database.



Some Key Points:

• AppVerifier is designed to test unmanaged applications (non-.NET Framework applications) on Microsoft (2000 and above) platforms.
• While running a full page heap, it is recommended to be at least 1 GB.
• It does not need access to the source code to execute its tests, although the availability of either the application’s symbols or debug information will make a dramatic difference in the quality and usefulness of the data collected.

How Does AppVerifier Work?

AppVerifier works by modifying the unmanaged DLLs Method Tables so that the required checks are performed before the real function is executed (“Function Hooking”). For example, the address of the Win32 API CreateFileA method is replaced with an internal AppVerifier method that will trigger a series of tests that when positive will be logged. When new processes are started, the use of AppVerifier’s Method Table Hooking techniques is controlled by entries made in specific registry keys. If the registry entry exists, then the AppVerifier DLL will be loaded in a newly created process that will handle the Method Table replacements in the existent and subsequently loaded DLLs. Since these hooks are made when the DLL is loaded, it is not possible to use AppVerifier on a process that is already running.

When a problem is identified a verifier stop will occur. The number provided is used to identify the exact nature and reason for its occurrence.

Detecting Heap Corruptions:

In order to detect heap corruptions (overflows or underflows), AppVerifier will modify the way memory is allocated by padding the requested memory with either full non-writable pages or with special tags before and after the allocated memory.

When padding the requested memory with full non-writable pages, AppVerifier will consume a large amount of virtual memory but has the advantage that heap corruption events are cached in real time when the overflow or underflow occurs. The heap check will place a guard page at the beginning or end of allocation depending on the Backward property. If Backward is set to False, which is the default, it will place a guard page at the end of the allocation to catch buffer overruns. If it is set to True, the guard page is placed at the beginning of the allocation to catch buffer underruns.

When padding the requested memory with special tags (enabled by clearing the “Full” check box item in the heap properties), AppVerifier will check and alert you when this memory is released. The main problem in using this technique is that there are some cases when the memory corruption will only be detected when the memory is released (the minimum amount of memory block is 8 bytes), so when on a 3-byte variable or a 5-byte overflow occurs it will not be immediately detected.

On an underflow event, an attempt will be made to write to a Read-Only page. This will trigger an exception. This exception is only be caught if the target application is being executed under a debugger. Note that the full page heap mode will also detect these errors as it uses padding + guard pages. The reason you would use light page heap is if your machine cannot tolerate the high memory constraints of full page heap.

For memory intensive applications, or when it is required to use AppVerifier during long periods of time (e.g. stress testing), it is better to run normal (light) heap tests instead of full mode due to the performance degradation. However, when you run into an issue turn on full page heap to investigate further.

References and Further Reading :

MSDN, Microsoft Application Verifier Help.
Function Hooking and Patching Articles: Detours
From Code Project: API hooking revealed Process-wide API spying – an ultimate hack
The Files used for reference can be downloaded from here.