Security and Privacy on the U3 Platform

Be Smart with U3

Programming Custom Hardware for Windows – Points of Interest

Points of Interest

  • Short is a 16-bit integer in Win32 C++ whereas int is 32-bit integer in Win32 C++ use (short) to force returning 16-bit integer back to VB. So as you’ll notice in the function InPort and OutPort I’ve used this convention.
  • There exist similar functions to _inp( ) and _outp( ) that have capacity to read words and double words from the specified port. Maybe if you’re writing an I/O intensive application, for instance, a Data Acquisition card you might consider using them by changing the code in DLL appropriately.
  • If direct I/O is not achieved through the giveio driver there are other system APIs that’ll allow you to do so but the process becomes very slow (approximately 20 times) so it’s worth considering the use of GiveIO driver.
The VB Client Program
The sample program to use this DLL is developed using Visual Basic 6.0 and with a quick look at the source you’ll know how can you perform I/O using this DLL. You’ll see the exports InPort, OutPort, GetDriverStatus, and GetDLLStatus in action with their usage.
Conclusion
So finally we’ve developed a library that’ll ease development of hardware accessing applications in VB and other RAD application development tools that may consume a DLL. I would not say that it’s the most efficient way but certainly the most straightforward to understand and implement. Any comments and suggestions can be forwarded to me at editor@onsmartcards.com .
References
  1. Direct Port I/O and Windows NT by Dale Roberts(http://www.ddj.com/documents/s=961/ddj9605a/)
  2. LoadDrv program and source code by Paula Tomlinson

November 11, 2006 Posted by | Uncategorized | Leave a comment

Programming Custom Hardware for Windows – The Code

Here is the easy part!
Once we know what exactly what we need to do, the rest becomes easy. So I’ll now take you on a quick walkthrough of the DLL code that I’ve written.
You can always modify it for better performance or anything that you find suitable. For details about the device driver you’ll need to read the article that I just mentioned above. The code in the DLL takes some code from the LOADDRV program by Paula Tomlinson.
Even if you’re not concerned how it works and you just intend to use the DLL in your application I’d recommend browsing through the code once so that you’d be able to use it better in your own code.
The DLL contains a total of 11 Functions of which only 5 are exported (made available to applications using the DLL). First we’ll discuss the functions that are not exported and later the exported ones. I’ve named the DLL and the workspace as RADHWLib a short name for Rapid Application Development for Hardware Library. The functions that are not exported are listed below with their descriptions.
DllMain This function is special because this allows us to perform DLL specific initialization/cleanup, as the DLL is loaded/unloaded. This is basically the first function that is invoked when the DLL is loaded and we use it to determine if the hosting OS is of NT family by using the GetVersion( ) API. If it is then we install the GiveIO driver and allow for unrestricted I/O which otherwise would not allow applications to execute I/O instructions. But now the task of I/O resides with our DLL. We should allow our DLL to use the I/O instructions by using the GiveIO driver by making a call to CreateFile( ) API. This will allow our DLL to execute privileged instructions and effectively will make the application written on top of it to access hardware directly.
InitSCM This function initializes the Service Control Manager using the OpenSCManager API. This returns a handle (a 32Bit value) that we use later to perform different operations regarding driver installation and service creation/deletion. This return value is stored in a global variable in the DLL.
ShutDownSCM This function just closes the handle we obtained in the InitSCM function using the CloseServiceHandle API.
AttachDrv If Windows NT is hosting the DLL this function is invoked and this opens the giveio device just created by the device driver in it’s initialization routine. This will modify the IOPM (Input Output Port Map) so that our application, which is using our DLL, has unrestricted I/O even under Windows NT family of operating systems. This function tries to open the giveio device through the CreateFile( ) API and that in turn allows the driver to do a IoGetCurrentProcess( ) in order to access the address apace of the application using the DLL and modify the IOPM.
DriverInstall This function installs the giveio driver and returns 0(Zero) on success. You’ll notice a magic value of 0x00000431 in the DllMain code. That is because of the fact that GetLastError( ) returns this value if the driver is already installed. It returns meaningful values as documented in the header file.
DriverRemove This function removes the giveio driver provided no applications are using our DLL. You’ll notice a global variable nNumberOfApplications in the code. I’ve put this variable in a shared segment in the DLL so that this is not private to any application and holds the total number of applications that use our DLL. This can be useful if you write some code to manipulate the giveio driver.
Now we’ll take a look at the functions that are exported from the DLL. These are of real concern to the developers because if a function is not exported it can’t be invoked by any application that uses it.
OutPort This function is used to output a byte to a port. It takes two arguments the port number and the value to write to port. It internally uses the C run-time library _outp routine to do the real I/O and returns the value it gets back from it. As per the MSDN, the value that _outp returns is the data written to the port and that there is no error code.
InPort Just as with OutPort( ) this function reads a byte from a port specified in the function argument and returns it. It doesn’t return any error code. It uses the CRT function _inp( ) for its implementation. The input value can be any unsigned short integer in the range 0 to 65,535 because the function _inp( ) is capable of reading byte, word, or double word from the specified port. (See points of interest for details)
DoDriverAction This function takes DDA_LOAD or DDA_UNLOAD as it’s single argument and does the job of Installing or Uninstalling the giveio driver on request. It returns several meaningful values as documented in the header file. For making it clear I’d list them again here in a format like:
Return Value
Value
Meaning
DRIVER_ALREADY_INSTALLED
100
Driver is already installed
DRIVER_INSTALL_SUCCESS
101
Driver installed successfully
DRIVER_INSTALL_FAILURE
102
Driver installation failed
DRIVER_ALREADY_UNINSTALLED
103
Driver already Uninstalled
DRIVER_UNINSTALL_SUCCESS
104
Driver uninstalled successfully
DRIVER_ININSTALL_FAILURE
105
Driver uninstallation failed
DRIVER_NOT_INSTALLED
106
Unknown ERROR: Driver not installed
DRIVER_IN_USE
108
Driver is in use and nNumberOfApplications is not zero

GetDriverStatus This function returns TRUE or FALSE depending on whether it is loaded or not. 0 implies not loaded and 1 implies that it is loaded.

GetDLLStatus This function returns the number of active applications that are using our DLL. As this returns a value that is kept in a shared section in DLL the value is transparent to all applications when this function is called.

November 11, 2006 Posted by | Uncategorized | Leave a comment

Programming Custom Hardware for Windows – The Design

In order to meet all the requirements above and to get all the questions answered we need to design one solution that we can reuse on application-by-application basis. In the figure below (Figure 1) you can see the conceptual representation of the link between a DLL and a process using it. What we need to do is to exploit this flexible architecture!

What happens behind the scene is that the DLL is loaded as a separate module in the memory and is mapped in the address space of each process that loaded it. There can be n number of processes using a DLL at the same time. So what advantage do we get? Trust me its more than just one!

  • First, by careful design of the DLL we can make it reusable by different application. For example if we place the basic functionality of Just Reading and Writing to ports we can use it probably in any application in Visual Basic if required.

  • Secondly, if somehow we can make the DLL execute I/O instructions correctly It’s not possible to execute I/O instructions (or, I should say, any of the instructions marked privileged in a user mode process on NT family of systems), then any of the applications that link to our DLL for performing I/O would be able to perform I/O as they’d do on Windows 95/98 operating systems without generating an exceptions.

On the x86 CPU (above 386) family the instruction set contains a set of instruction marked privileged and the hardware also provides four different privilege levels in which code can execute, generally known as Ring0 through Ring3. Windows 95 and 98 doesn’t make use of these advanced features because the design goal of Windows 95 was not robustness and security but to get the system running with minimal resources. On the contrary, the Windows NT or any member of NT family uses these privilege levels for secure execution of code and defines two modes for code execution namely, the user mode and the kernel mode. The Kernel mode is implemented using the Ring0 and the User mode is implemented using the Ring3. As the applications we create run in the user mode or as Ring3 code it doesn’t have the permission to execute I/O instruction and if an attempt is made a privileged instruction execution exception is raised terminating the program. For more details you can refer to the article by Dale Roberts on Direct Port I/O and Windows NT published in DDJ may 1996 issue.

November 11, 2006 Posted by | Uncategorized | Leave a comment

A bit of Background …

Anyone who has programmed in basic and used the INPUT and OUTPUT statements would expect them to run in the Visual Basic environment too, but fortunately or unfortunately it is not the case.
The Visual Basic language doesn’t support for direct hardware access and if the application (no matter what language is used to develop it) won’t be able to access hardware directly if it’s running on a secure system from the Windows NT family (i.e. NT, 2000, XP etc).
These functions are crucial for PC hardware developers and programmers because they allow you to read and write to ports in environments like DOS or Windows 95 and 98. Thus without INPUT or OUPUT you can’t read from or write to your device.
Fortunately the concept of dynamic link libraries or DLLs comes to rescue. DLLs allow VB to link to them (you can write a DLL in any language like Delphi, Borland C++ or Microsoft’s Visual C++) during run-time (dynamically).
VC++ has port I/O (input and output) read/write functions. Also VC++ compiler allows you to create DLLs apart from executable EXE files. Thus you can
  • Write VC++ code that uses these read/write functions
  • Compile it into a DLL (instead of an executable EXE file) file
  • Call your functions from VB
  • Make use of the facilities that a DLL provides; Like notifying you and providing you with a place to put your code that executes when a process loads it or unloads it.
  • Modify the DLL to make any desirable changes to the behavior of functions and you need not build the whole application again.

The list is very long and for more details on features of DLLs you can refer to DLLs, Processes, and Threads section in the MSDN library.

Now lets suppose that you’re a developer willing to develop an application that needs to communicate to a hardware port, say for acquisition card, or perhaps a motor controller or even a robotic arm that you’ve just created! And you’ve never written an application that does so. Futher you just have programmed in Visual Basic.

At this point the major challenges that you have are:

  • How do I access these ports?
  • What should I do so that my applications run on Windows NT family of operating systems, as they’d do on Windows 95 or 98?

I’m emphasizing on the difference between the two operating system families because they’ve a very different way to treat port I/O, as we’ll see shortly.

So now we know that what we intend to develop and more importantly why. So let’s get started!
Before you get started, you’ll probably want to download the support files/sample code from www.onsmartcards.com articles section.

-The Editor (editor@onsmartcards.com)
http://www.onsmartcards.com/

November 11, 2006 Posted by | Uncategorized | Leave a comment

Programming Custom Hardware for Windows

Programming Custom Hardware for Windows

The task of developing custom applications that access custom hardware can be daunting for even the most seasoned application developer and especially for someone who has just learned developing applications using Visual Basic and similar RAD tools.

Here in this blog I present an alternative way that may help even the non-programmers to do what they want; That is to develop a custom UI and then access a specific piece of hardware that is connected to their machine.

I don’t assume the reader to be aware of Port Access in Windows NT/2000/XP or even Windows 98 but I do assume that he knows what he’s trying to do.

The First step would be to understand that why such a framework that allows one to support accessing hardware from RAD tools is needed and then later see what advantages it has got.

Finally we would get into developing such a Framework.

-The Editor (editor@onsmartcards.com)
http://www.onsmartcards.com/

November 11, 2006 Posted by | Uncategorized | Leave a comment

Java Card Technology and Smart Cards

With Java Card technology, smart card programming is finally entering the mainstream of application development. One of the major problem in smart card programming is the consitancy and interoperabilty among different vendors and standards.
With Java Card technology, smart card programming is finally entering the mainstream of application development for it provides a unified interface to develop relally portable applications on Smart Card. A first principal characteristic of smart card programming is its security system, which undoubtedly is the best among the ones available today.
Smart card programming is characterized by two system requirements; data security and data integrity. When smart card programming is done one will always have to design and write software that the user will interface with to go through the key authorization process and other realted taks that the card holder needs to perform.

European smart card standards are most widespread in the industry for its their birthplace. There are several smart card standards – too many to discuss here.

until next blog,
– Editor (editor@onsmartcards.com)
http://www.onsmartcards.com/

November 7, 2006 Posted by | Uncategorized | Leave a comment

Writing a Smart Card Library – The Approach

Let’s first talk about how one writes an application with just the WinSCard.dll raw APIs and then we’ll move to writing the OO Wrapper. As mentioned above the core of the Win32 Smart Card subsystem is the WinSCard.dll, which exposes a number of APIs for Smart Card access and Reader Configuration.

The typical steps to access a Smart Card with the raw API’s would be as under:

  • Use the SCardEstablishContext API to get a Context Handle associated with a reader. You need this because the other APIs need you to pass a context handle as parameter.
  • Later using the SCardConnect API you obtain hCard that is handle to a card. Just like above you need this handle to communicate with the Card.
  • You may then use SCardStatus with the above hCard value to get the status of the card before you actually start with some transaction.
  • You then use SCardTransmit API to send APDU to the associated card and retrieve the response at the same time. You’ll need the hCard value here too.
  • After you’re done using the Card you use the SCardDisconnect API to disconnect from the Card using the hCard value associated with the card. Then this hCard value is no longer valid and you should do a SCardConnect call again to retrieve a new handle in case you want to reconnect again
  • Finally when you don’t need the connection with the reader device you just call the SCardReleaseContext API to release the Context handle associated with the reader.

It’s fine as long as you’re writing a small application but as your business logic grows so would be the calls and references to the WinSCard APIs and it’s really not advisable even for a medium project going over 3000LOC.

Moreover it’s solely up to the programmer to put the data in a format that is dictated by the WinSCard APIs. It was a lot of hit and trial the first time I wrote an application in this way. Sooner or later you find that you’re not writing good code if you follow this approach.Compare this approach to the object oriented approach where in you’ve a number of class like in the diagram below that encapsulate one or more Smart Card objects.

The CPSCSCReader class encapsulates a Reader object, which is responsible for managing reader connections, keeping the status updated internally and sending/receiving data to/from the card. There are a few helper classes too like CPCSCCommand, which encapsulates an APDU (Application Protocol Data Unit) object and CRegListDlg, which enables you to select a reader from those connected to your machine. You can skim through the code for these classes or run the demo application to see them in action.

until next blog,
– Editor (editor@onsmartcards.com)
http://www.onsmartcards.com/

November 1, 2006 Posted by | Uncategorized | Leave a comment