Tag Archives: Windows

Signing Windows 7 x64 drivers

For security reasons, 64-bit versions of Windows Vista and newer require the drivers to be digitally signed to load. This strict driver signing policy leads to one of the following:

  • The driver must contain an embedded driver signature.
  • The driver must be distributed together with an INF file and a signed catalog file.

For development and test purposes, the signing requirement can be bypassed using several methods. This tutorial focus on using a test certificate and the Test Mode to install and load self-signed drivers.

Prerequisites

  • Windows 7 x64.
  • WDK version 7.1.0 (free download from the Microsoft Download Center).

Once you are familiar with driver signing tools and requirement, you can update the previous configuration to target other platforms.

Download the WDK’s ISO file, extract it to your hard drive (I recommend using 7-Zip) then run KitSetup.exe to install it into C:\WinDDK\7600.16385.1\ (default folder).

My working folder is C:\Briolidz\MyDrivers.

Windows Test Mode

The Test Mode allow loading any type of test-signed kernel-mode code by adding the TESTSIGNING boot configuration option.

To activate Test Mode you need to start a command prompt with administrator rights then execute the following command (use off switch to disable it):

C:\Windows\system32> bcdedit /set testsigning on

Restart the computer for the change to take effect.

Upon reboot you will notice that the Test Mode watermark is present on the desktop. If you can’t stand seeing this watermark you can use Remove Watermarks to remove it. I highly recommend backing up the original user32.dll.mui file on your system before it gets patched.

Create certificate

– Open with administrator rights the WDK command prompt : Start -> Windows Driver Kits -> WDK 7600.16385.1 -> Build Environments -> Windows 7 -> x64 Free Build Environment. Then move to the working folder:

C:\WinDDK\7600.16385.1> cd C:\Briolidz\MyDrivers

– Create a certificate and install it into the Trusted Root Certification Authorities store:

C:\Briolidz\MyDrivers> makecert.exe -$ individual -r -pe -ss "Briolidz Certificate Store" -n CN="Briolidz Certificate" "Briolidz Certificate.cer"

C:\Briolidz\MyDrivers> certmgr.exe /add "Briolidz Certificate.cer" /s /r localMachine root

C:\Briolidz\MyDrivers> certmgr.exe /add "Briolidz Certificate.cer" /s /r localMachine trustedpublisher

– Verify that the certificate is correctly installed in “Briolidz Certificate Store” -> Certificates:

C:\Briolidz\MyDrivers> %WINDIR%\system32\certmgr.msc

Driver without an INF file

– Sign the driver (for instance MyDriverNoInf.sys) with the certificate:

C:\Briolidz\MyDrivers> signtool.exe sign /v /s "Briolidz Certificate Store" /n "Briolidz Certificate" /t http://timestamp.verisign.com/scripts/timestamp.dll MyDriverNoInf.sys

– Verify the signed driver validity:

C:\Briolidz\MyDrivers> signtool.exe verify /pa /v MyDriverNoInf.sys

– Install the driver.

Driver with INF file(s)

– Move to the working folder and open your INF file (for instance MyDriverWithInf.inf) in a text editor:

Ensure that under the [version] section you have an entry specifying a .cat file (see “CatalogFile” key).  Also make sure that the date format is correct. Below a sample:

[version]
Signature   = "$Windows NT$"
Class       = NetService
ClassGUID = {4D36E974-E325-11CE-BFC1-08002BE10318}
Provider  = %Msft%
DriverVer = 01/01/2012,7.0.5019.0
CatalogFile = MyDriverWithInf.cat

– Create .cat (catalog) file:

CAT files are catalogue files that contain the information about the driver package. These need to be generated from the INF files to allow the signing to be done.

C:\Briolidz\MyDrivers> Inf2cat /driver:"C:\Briolidz\MyDrivers" /os:7_x64

Running this successfully will generate MyDriverWithInf.cat (Note that the CAT file specify Windows 7 x64 for installation). Update “/os” switch to target other operating systems.

– Sign the catalog file:

C:\Briolidz\MyDrivers> signtool.exe sign /v /s "Briolidz Certificate Store" /n "Briolidz Certificate" /t http://timestamp.verisign.com/scripts/timestamp.dll MyDriverWithInf.cat

– Some drivers have several INF files. They can be located in driver’s folder or in its subfolders. In this case, you MUST REPEAT PREVIOUS COMMANDS for each INF file.

– Install the driver.

Advertisements

VBScript: Recursively Search and Replace in Windows

Recently I needed a command-line tool to perform recursive search and replacement inside text files located in a directory and its subfolders under Windows platforms. Several Open Source and proprietary tools exist but I ended by writing my own VBScript for simplicity, customization and portability reasons.

Command-line:


{CScript [/nologo]|WScript} /Path/to/SearchReplaceInFiles.vbs {Folder Path} {String} {ReplaceStringWith} {*.Extension}

Where:

Folder Path: Folder and its subfolders to find files
String: The string to be searched
ReplaceStringWith: The replacement string
*.Extension: File(s) extension. It can be *.*, *.txt …

Below a sample command-line:


C:\> CScript /nologo C:\Briolidz\Dev\Tools\SearchReplaceInFiles.vbs C:\Briolidz\Dev "My Word 1" "My Word 2" *.txt

SearchReplaceInFiles.vbs forces to run in CScript to prevent a separate popup for each WScript.Echo line.

SearchReplaceInFiles.vbs source code:

'
' Recursive search and replacement inside text files located in a directory and
' its subfolders under Windows platforms.
'
' {CScript [/nologo]|WScript} /Path/to/SearchReplaceInFiles.vbs {Folder Path} {String} {ReplaceStringWith} {*.Extension}
'

' Force script to run in CScript to avoid WScript.Echo messages pop-up box
ForceCScript()

Dim Args, FolderPath, FindString, ReplaceStringWith, FSO

' Check arguments
Args = WScript.Arguments.Count
If Args <> 4 then
 WScript.Echo
 WScript.Echo "Usage : {CScript [/nologo]|WScript} /Path/to/SearchReplaceInFiles.vbs {Folder Path} {String} {ReplaceStringWith} {*.Extension}"
 WScript.Echo
 WScript.Echo " Folder Path: Folder and its subfolders to find files"
 WScript.Echo " String: The string to be searched"
 WScript.Echo " ReplaceStringWith: The replacement string"
 WScript.Echo " *.Extension: file(s) extension. Can be *.*, *.txt ..."
 WScript.Echo
 WScript.Quit(1)
end If

' Get arguments
FolderPath = WScript.Arguments(0)
FindString = WScript.Arguments(1)
ReplaceStringWith = WScript.Arguments(2)
Extension = WScript.Arguments(3)

' Creating File System Object
Set FSO = CreateObject("Scripting.FileSystemObject")

' Check extension format
If Not Left(Extension, 2) = "*." Then
 WScript.Echo("Invalid extension " & Extension)
 WScript.Quit(1)
End If

' Check destionation folder
If Not FSO.FolderExists(FolderPath) Then
 WScript.Echo("Folder " & FolderPath & " does not exist !")
 WScript.Quit(1)
End If

' Files extension
Extension = LCase(Mid(Extension, 3))

' Call the GetFiles function to get all files
WScript.Echo
WScript.Echo("Searching for *." & Extension & " files in " & FolderPath & " folder ...")
GetFiles FolderPath, Extension
WScript.Echo("Completed")

Set FSO = Nothing

Function ForceCScript()
 Dim StrArg, Str

 If Not LCase(Right(WScript.FullName, 12)) = "\cscript.exe" Then
  For Each StrArg In WScript.Arguments
   If InStr(StrArg, " ") Then StrArg = """" & StrArg & """"
   Str = Str & " " & StrArg
  Next

  StrCmd = "CScript //nologo """ & WScript.ScriptFullName & """" & Str
  Set WshShell = CreateObject("WScript.Shell")

  ' Rerun the script in CScript
  Set ObjExec = WshShell.Exec(StrCmd)

  ' Wait until the script exits
  Do While ObjExec.Status = 0
   WScript.Sleep 100
  Loop

  ' Exit with CScript's return code
  WScript.Quit ObjExec.ExitCode

  Set WshShell = Nothing
  Set ObjExec = Nothing
 End If
End Function

Function GetFiles(FolderPath, Extension)
 On Error Resume Next

 Dim ObjFolder, ObjSubFolders
 Dim ObjFiles, ObjFile

 Set ObjFolder = FSO.GetFolder(FolderPath)
 Set ObjFiles = ObjFolder.Files

 ' Write all files to output files
 For Each ObjFile In ObjFiles
  StrExtension = LCase(FSO.GetExtensionName(ObjFile))

  If Extension = "*" Or StrExtension = Extension Then
   ' Read source text file
   FileContents = GetFile(ObjFile)

   ' Replace all string In the source file
   NewFileContents = Replace(FileContents, FindString, ReplaceStringWith, 1, -1, 1)
   If NewFileContents <> FileContents Then
    ' Write result If different
    WScript.Echo(" Updating File: " & ObjFile.Path)
    WriteFile ObjFile, NewFileContents
   End If
  End If
 Next

 ' Getting all subfolders
 Set ObjSubFolders = ObjFolder.SubFolders

 ' Getting all Files from subfolder
 For Each ObjFolder In ObjSubFolders
  GetFiles ObjFolder.Path, Extension
 Next
End Function

' Read text file
function GetFile(FileName)
 If FileName <> "" Then
  Dim FS, FileStream

  Set FS = CreateObject("Scripting.FileSystemObject")

  on error resume Next
  Set FileStream = FS.OpenTextFile(FileName)
  GetFile = FileStream.ReadAll
 End If
End Function

' Write string As a text file
function WriteFile(FileName, Contents)
 Dim OutStream, FS

 on error resume Next
 Set FS = CreateObject("Scripting.FileSystemObject")
 Set OutStream = FS.OpenTextFile(FileName, 2, True)
 OutStream.Write Contents
End Function

Windows driver debugging with WinDbg and VMWare

Virtualization Software such as VMware Workstation enables driver and kernel-mode code developers to speed up development, debugging and testing resulting in faster time to deployment. Snapshots provide a fast and easy way to revert the virtual machine to a previous state. This feature greatly simplifies recreation of specific states or conditions to troubleshoot problems and system crashes.

WinDbg is a debugging tool from Microsoft for user and kernel mode debugging. WinDbg is a GUI interface and a console interface along with some debugging extensions. Using virtual machines, WinDbg can be used to debug kernel code without the need for two physical computers.

This tutorial shows how to debug a simple Windows driver running inside a VMware virtual machine with WinDbg using a single physical machine. The following typical debugging scenarios are covered:

    • Debugging host’s virtual machine: WinDbg runs inside a physical computer to debug a virtual machine.
    • Debugging between two virtual machines: WinDbg runs inside a virtual machine to debug the second one.

Basic familiarity with device driver development and kernel debugging is assumed.

Prerequisites

The working folder is C:\Briolidz\Dev\BriolidzSampDrv.

I assume that your host and guests root system partition is C:\. The kernel debugging setup will use a virtual serial port on COM2 at 115200 bps. The custom named pipe is called BriolidzDbgPipe.

These parameters can be changed to fit your own setup.

VMware machine configuration

In the first debugging scenario, you will debug a virtual machine directly over a named pipe from the host operating system. In the second scenario, you will connect two virtual machines to the same named pipe by creating a virtual null-modem cable. The following configuration steps can be easily adapted for other virtualization software such as VirtualBox and Virtual PC.

In both scenarios, you need to setup the guest virtual machine to debug as follows:

1. Powered off the virtual machine.
2. Open VM then select Settings in VMware Workstation menu.
3. In the VMware Machine Settings dialog box, click Add.
4. In the Add Hardware Wizard dialog box, select Serial Port and click Next.
5. On next page, select Output to named pipe and click Next.
6. Set Name pipe to \\.\pipe\BriolidzDbgPipe. Make sure you select This end is the server and The other end is virtual machine. Check Connect at power on then click Finish.
7. After clicking Finish, select the newly created serial port and check Yield CPU on poll.

You should have something similar to the following screenshot. Note that new serial port has number 2 which corresponds to COM2. If you get assigned another number then make sure to replace COM2 with COM<your assigned number> in the Virtual machine configuration section.

Skip this step, if you are going to use WinDbg on your host (physical computer).

So you decided to use a second virtual machine as a development and debugging machine to replace the host physical machine. In this case, do:

1. Powered off the virtual machine.
2. Open VM then select Settings in VMware Workstation menu.
3. In the VMware Machine Settings dialog box, click Add.
4. In the Add Hardware Wizard dialog box, select Serial Port and click Next.
5. On next page, select Output to named pipe and click Next.
6. Set Name pipe to \\.\pipe\BriolidzDbgPipe. Make sure you select This end is the client and The other end is virtual machine. Check Connect at power on then click Finish.
7. After clicking Finish, select the newly created serial port and check Yield CPU on poll.

You should have something similar to the following screenshot. Note that the new serial port has number 2 which corresponds to COM2. As stated earlier, if you get assigned another number then replace COM2 with COM<your number> in the Attaching WinDBG Debugger section.

Virtual machine configuration

To enable kernel debugging, you need to change Windows boot parameters. Your virtual machine will also be configured to use serial debugging on COM2 at 115200 bps. Power on your virtual machine, log in then apply the following modifications according to your operating system version.

1. Windows XP

Windows XP uses a configuration file called boot.ini on the root of the system partition (generally the C:\ drive) to control how the operating system is booted and any startup options.

The boot.ini file has the Hidden, System, and Read-Only attributes set by default. Open a command prompt, and change them:

attrib -s -h -r C:\boot.ini

The boot.ini file is a standard ASCII text editor. Double click it to edit and duplicate the matching default entry defined in boot loader section, change its title by adding [DEBUG] for instance, add /Debug, /debugport=com2 and /baudrate=115200 switches. Below, a modified sample for Windows XP professional:

[boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional [DEBUG]" /noexecute=optin /fastdetect /Debug /debugport=com2 /baudrate=115200
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional" /noexecute=optin /fastdetect

You can reduce the timeout value in order to speed up booting.

Restore the Read-Only, Hidden, and System attributes of the boot.ini file, type the following at a command prompt:

attrib +h +r +s C:\boot.ini

2. Windows Vista and 7

Windows Vista and 7 use the bcdedit command line tool to configure the boot menu. Start a command prompt with administrator privileges and run the following commands:

bcdedit /set {current} debug yes
bcdedit /set {current} debugtype serial
bcdedit /set {current} debugport 2
bcdedit /set {current} baudrate 115200

Set the operating system selection menu to be displayed when booting and loading the operating system.

bcdedit /set {bootmgr} displaybootmenu yes

You can reduce boot timeout as follows:

bcdedit /timeout 10

To view the current configuration, run:

bcdedit

Sample driver code

Depending on your debugging scenario, log in to your development machine: the host (the physical computer) or the virtual machine. You will write the necessary files to create a do-nothing sample driver called BriolidzSampDrv.sys. This driver has minimal DriverEntry and DriverUnload routines and will write some debug message.

In the working folder, create a file called BriolidzSampDrv.c containing the following source code:

#include <wdm.h>
 
void DriverUnload(PDRIVER_OBJECT pDriverObject)
{
    DbgPrint("BriolidzSampDrv: Driver unloading.\n");
}

NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath)
{
    DriverObject->DriverUnload = DriverUnload;
	
    DbgPrint("BriolidzSampDrv: DriverEntry.\n");
	
    return STATUS_SUCCESS;
}

There are two additional files required to build a device driver: sources and makefile.

Create sources file containing the following lines:

TARGETNAME=BriolidzSampDrv
TARGETTYPE=DRIVER
SOURCES=BriolidzSampDrv.c

The makefile file only needs to contain this line:

!INCLUDE $(NTMAKEENV)\makefile.def

To install the sample driver, you will use a basic method based on a registry file. Create InstallSampDrv.reg file containing the following lines:

Windows Registry Editor Version 5.00
  
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\BriolidzSampDrv]
"Type"=dword:00000001
"Start"=dword:00000000
"ErrorControl"=dword:00000001
"Group"="Base"
"ImagePath"="\\SystemRoot\\System32\\Drivers\\BriolidzSampDrv.sys"
"Description"="Briolidz - Sample Driver"
"DisplayName"="BriolidzSampDrv"

Building the sample driver

Download the Windows Driver Kit. Run the installer and make sure to select at least Build Environments and Debugging Tools for Windows. This will install WinDbg and the necessary environments to build drivers.

When writing this tutorial, I used WDK version is 7.1.0 which include WinDbg version 6.12.2.633. Under Windows 7 professional 64-bit, the default installation folder is C:\WinDDK\7600.16385.1 and the WDk’s start menu group is called Windows Driver Kits. WinDbg is installed in C:\WinDDK\7600.16385.1\Debuggers folder. In case you are using a different WDK version, you will just have to update paths in the following sections.

From the Windows Driver Kits start menu group, launch the command-line build environment for the desired target platform and architecture. Since The BriolidzSampDrv sample driver does not use platform specific code, you can safely use the x86 Checked Build Environment and x64 Checked Build Environment under Winows 7 submenu.

For both target platforms, open the command-line build environment, change to the working directory containing the sample driver source code and enter the command:

C:\Briolidz\Dev\BriolidzSampDrv> build

The 64-bit driver is built in C:\Briolidz\Dev\BriolidzSampDrv\objchk_win7_amd64\amd64\BriolidzSampDrv.sys and the 32-bit driver is built in C:\Briolidz\Dev\BriolidzSampDrv\objchk_win7_x86\i386\BriolidzSampDrv.sys.

Sample driver installation

Reboot the guest virtual machine to debug. When the boot menu is displayed, always choose the menu item containing [debugger enabled].

If you are planning to debug the x64 driver version on Windows Vista/7 (necessarily x64), then press F8 key and select Disable Driver Signature Enforcement from the menu. This operation must be done at every boot because 64-bit Windows systems will not allow drivers to be loaded unless they have a valid digital signature.

If you cannot digitally sign your driver, you can test-sign it and enable the TESTSIGNING mode using the bcdedit command to avoid manually disabling driver signature procedure at every boot time.

After logging in a session with administrator privileges, copy the BriolidzSampDrv.sys (from your working folder) to C:\Windows\System32\drivers. Also copy the InstallSampDrv.reg file to a location of your choice then double-click it to install the driver.

Changes will take effect after the next reboot.

Attaching WinDBG Debugger

At this point your debugging platform is ready to be used. These are the main steps to follow:

1. The WinDbg command line gives you the ability to use environment variables in order to create workspaces that contain your custom debugging settings.

In the following, if you are debugging the 32-bit driver then replace C:\Briolidz\Dev\BriolidzSampDrv\objchk_win7_amd64\amd64 with C:\Briolidz\Dev\BriolidzSampDrv\objchk_win7_x86\i386.

Inside the development machine (host or virtual machine), open a command prompt and type:

set _NT_EXECUTABLE_IMAGE_PATH= C:\Briolidz\Dev\BriolidzSampDrv\objchk_win7_amd64\amd64
set _NT_SOURCE_PATH=C:\Briolidz\Dev\BriolidzSampDrv

If you chose to debug a virtual machine from your host (physical computer):

"C:\WinDDK\7600.16385.1\Debuggers\windbg.exe" -b -k com:pipe,port=\\.\pipe\BriolidzDbgPipe,resets=0,reconnect

Otherwise:

"C:\WinDDK\7600.16385.1\Debuggers\windbg.exe" -b -k com:port=com2,resets=0,reconnect

WinDbg GUI will popup and display Waiting to reconnect message.

2. Start the target virtual machine.

3. While booting, WinDbg will halt the target system. In the WinDbg command pane, set a breakpoint in DriverEntry routine as follows:

bu BriolidzSampDrv!DriverEntry

By default, DbgPrint messages do not appear in WinDbg when the driver is running on Windows Vista/7 due to filtering reasons. You can clear this filtering using this simple call:

ed nt!Kd_DEFAULT_Mask 0x8

Press g or F5 key to continue.

After few seconds (or more depending on your computer speed), WinDbg will halt again. You should see something similar to this screenshot.

At this level, you can debug the driver by setting other breakpoints, stepping in the code, monitoring variables and expressions.

Compiling Qt with Visual Studio 2010

Qt is an object oriented C++ cross-platform GUI toolkit which can be used to build applications that run natively on several platforms including Windows, Linux, Mac OS, and embedded Linux without source code changes. Qt is available under GPL v3, LGPL v2 and a commercial license.

This tutorial is intended for Windows users preferring to stick to Visual Studio 2010 as a primary development environment instead of Qt Creator. It provides step-by-step instructions for compiling Qt from source using the open-source distribution.

Prerequisites

    • Visual Studio 2010 Professional with SP1.
    • Windows 7 Professional.
    • Qt 4.8.0 open-source distribution (or a recent Qt 4.7.x version).
    • Qt Visual Studio Add-in.
    • ActivePerl.

Setup Visual Studio 2010

1. Download and install Microsoft Visual Studio 2010 Service Pack 1.

2. For x64 users, it is recommended to download and install this patch for Visual Studio 2010, if it is not already up-to-date.

3. Download and install the Qt Visual Studio Add-In. After installation, a new menu called Qt is added to Visual Studio 2010.

Download and install ActivePerl

ActiveState provides a Perl distribution for Windows platforms. Download and install the latest x86 version from here. Stick to x86 unless you have any special reason for using 64-bit applications.

During installation, make sure that Add Perl to the PATH environment variable and Create Perl file extension association checkboxes are selected.

Download and compile Qt

1. Download the Qt source code as a .zip file. The Qt-everywhere package version 4.8.0 is located here.

2. Unzip the previous file into a location without spaces and special characters. I will use C:\Qt\4.8.0.

3. Open a Visual Studio Command Prompt: All programs -> Microsoft Visual Studio 2010 -> Visual Studio Tools -> Visual Studio Command Prompt (2010). Stick to x86 unless you have any special reason for using 64-bit applications.

4. Get Qt configured:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC> cd C:\Qt\4.8.0
C:\Qt\4.8.0> configure -debug-and-release -opensource -shared -platform win32-msvc2010

Type y and press Enter to accept the terms of the license agreement.

You can of course specify additional options to add or remove some features depending upon your requirements. Type configure -help to get more details.

5. Compile Qt:

C:\Qt\4.8.0> nmake

The compilation takes a long time. Be patient.

Create a new Qt project

1. Open Visual Studio 2010. Go to Qt –> Qt Options and add the folder C:\Qt\4.8.0.

 

 

2. Create a new Qt project (File -> New -> Project… then select Qt4 Projects) or open an existing .pro file.

Debug and Release versions of the Qt shared libraries (QtCore4.dll, QtGui4.dll, QtCore4d.dll, QtGui4d.dll …) are located in C:\Qt\4.8.0\bin folder.  You will need to distribute the relevant ones used by the application when deploying on other systems.

Network traffic filtering technologies for Windows

Network traffic Filtering techniques for Windows, either in user-mode or kernel-mode, falls into one of two categories: stream and packet methods. This document presents useful techniques to build robust security software products such as personal firewalls and VPN clients for Windows 2000 or higher.

Before going further with this article, I would personally recommend WPF for Vista and higher, and TDI filters + NDIS Hook for earlier versions to build a combined stream and packet filtering solutions.

Winsock Layered Service Provider

A Winsock Layered Service Provider (LSP) is a DLL that operates on the Winsock functions to inspect, modify and intercept the inbound and outbound Internet traffic as streams and not as packets. LSP also runs in the workspace of the process it intercepts making easy to filter streams based on caller PID, short name or full path.

LSP can be chained and are useful tool for data-monitoring, content filtering, stream based sniffers, Quality of Service (QoS), authentication, encryption … LSP technology is often exploited by spyware and adware programs to bombard users with advertisements and email spam.

There is one known limitation and one common issue with LSPs. On some Windows versions, LSP can be bypassed by calling TCP/IP stack directly via TDI making useless, for instance, Trojan or virus protections at this level. A bogus LSP or improper LSP removal/unregistration operation may break the whole TCP/IP stack or leave the machine without working network connection.

Windows 2000/XP Filter Hook Driver

A Filter Hook driver is supported on Windows 2000/XP only and is implemented as a kernel mode driver. It operates by registering a callback with the IP Filter Driver that gets called when sending a receiving a packet. Filtering rules are limited to pass, drop or forward decision based on IP addresses and ports information.

The callback registration process uses an IRP with IOCTL_PF_SET_EXTENSION_POINTER as an IO control code and a PF_SET_EXTENSION_HOOK_INFO structure filled with a pointer to the callback routine.

A Filter Hook driver is simple to implement but has three serious limitations. Only one callback routine can be installed each time on the system. It is not possible to filter Ethernet frames. Outgoing packets cannot be modified.

Windows 2000/XP Firewall Hook Driver

A Firewall Hook driver is very similar to a Filter-Hook driver but installs a callback in the IP driver. The callback registration process uses an IRP with IOCTL_IP_SET_FIREWALL_HOOK as an IO control code and an IP_SET_FIREWALL_HOOK_INFO structure filled with a pointer to the callback routine.

Although it is not well documented, writing a Firewall Hook driver requires few lines of code. The main limitation is the support of Windows 2000 and XP only.

NDIS Hook Driver

There are two approved techniques to write an NDIS Hook driver. The first one is based on interception of some NDIS wrapper functions at runtime by writing a kernel mode driver that patches NDIS.sys in memory to replace the addresses of NdisRegisterProtocol, NdisDeregisterProtocol, NdisOpenAdapter and NdisCloseAdapter functions with internal ones.

The second one is based on registering a fake NDIS Protocol driver just to get a pointer to an internal NDIS structure NDIS_PROTOCOL_BLOCK.

At this level, both methods have enough information to substitute all protocols and adapters handlers to getting full control over all network traffic.

Although these approaches use sophisticated hacking techniques and require good understanding of different NDIS versions internals, an NDIS Hook driver is easy to install and able to filter, inject or modify packets. Several security software products including personal firewalls and VPN clients use these techniques.

This approach is discouraged for Windows Vista and higher.

NDIS Intermediate Driver

An NDIS intermediate driver, also called NDIS IM driver, is inserted just above miniport drivers and just below transport protocols in the overall networking protocol stack allowing incoming and outgoing packets filtering, inspection or modification. An NDIS Intermediate driver is a documented alternative to NDIS Hook drivers and offers the same functionalities.

NDIS intermediate drivers should be digitally signed at Microsoft to allow silent installations. This technology is replaced by NDIS Lightweight Filter drivers on Vista and higher.

NDIS Lightweight Filter Driver

NDIS Lightweight Filter drivers (LWF drivers) are introduced in Windows Vista and higher to replace NDIS Intermediate driver technology. They offer the same packets filtering, inspection or modification capabilities.

NDIS Lightweight Filter drivers are easier to implement and are designed to improve overall performances.

TDI Filter Driver

The Transport Driver Interface (TDI) defines a kernel mode network interface that is exposed at the upper edge of all transport protocol stacks. TDI also provides standard methods for protocol addressing, sending and receiving datagrams, writing and reading streams, initiating connections, detecting disconnects making it the only socket interface in the kernel.

TDI Filter drivers sit between TDI clients (such as AFD.sys, NETBT.sys) and TDI transports (such as TCPIP.sys) and intercept the communication between them. In case of TCP/IP filtering, the technique consists in writing a kernel-mode driver that layers itself over devices created by TCPIP.sys driver (\Device\RawIp, \Device\Udp, \Device\Tcp, \Device\Ip and \Device\MULTICAST) using IoAttachDevice routine. A good understanding of how to handle and interact with IRPs is required.

It is recommended to stop using TDI filters and move to Windows Filtering Platform (WFP) on Vista and later platforms. Windows makes it possible for TDI filters to see TCP/IP traffic is just for compatibility reasons and it does not yield good performance.

Windows Filtering Platform

Windows Filtering Platform (WPF) is a new architecture available in Windows Vista and higher that was built to replace all existing packet filtering technologies such as Winsock LSP, TDI filter and NDIS Intermediate driver and to provide better performance and less development complexities. Callout drivers, Filter Engine, Base Filtering Engine and Shims are components of the WPF architecture.

The WFP API consists of a user-mode API and a kernel-mode API that interacts with the packet processing that takes place at several layers in the networking stack. With WFP, incoming and outgoing packets can be filtered and modified before they reach their destinations, making this architecture ideal for implementing various filtering applications or solutions (such as personal firewalls, intrusion detection systems, antivirus programs, network monitoring tools, and parental controls). WFP arbitration rules also minimize the risk that software components get affected by any future Service Pack release.

WPF is highly recommended for developing security related solutions on Vista and higher.

Dual boot Windows 7 Starter and Ubuntu

Recent netbooks come pre-installed with Windows 7 starter and support booting from USB/Removable storage devices. This tutorial describes the additional steps to dual boot with Ubuntu (10.04 or higher) and to tweak Grub2 configuration.

Prerequisites

The minimum requirements are:

    • BIOS support for booting from any removable devices.
    • USB flash drive with at least 2 Go of storage space.
    • Internet connexion.

In the next sections, I assure that your BIOS boot order is configured to try Removable Devices first (You need to enter the BIOS setup utility, locate and navigate to the Boot Order options then make and save changes).

Hard disk setup

Pre-installed Windows 7 Starter often occupies the entire disk space. That means you are not allowed to make any new partition to install Ubuntu without changing partitions layout. Although, Windows includes a built-in functionality in Disk Management to shrink and expand partitions, I present another method based on open-source tools that can be used for general disk partitioning purposes:

1. Download and install LinuxLive USB Creator.
2. Download the GParted Live iso file.
3. Create a Bootable Flash Drive: Run LinuxLive USB Creator to install the GParted Live on an USB flash drive.
4. Reboot your netbook using the newly created bootable media.
5. Partition your drive by making enough free space for the future Ubuntu installation (You can also create a Data partition for your needs).

Ubuntu installation

The installation requires the following steps:

1. Log on to Windows 7 Starter again, insert the USB flash drive then open Download Ubuntu.
2. Follow the instructions in Burn your CD or create a bootable USB stick section to create an Ubuntu USB flash drive based installer.
3. Reboot your netbook using the newly created bootable media.
4. Install Ubuntu in the free space previously created. At the end of the installation process, let it install GRUB boot loader to the MBR of the disk.

Grub2 tweaks

The purpose is to change the way titles are displayed on the Grub2 menu and to remove unwanted entries.

1. Backup original files.

$ sudo cp /etc/grub.d/10_linux /etc/grub.d/10_linux.bak
$ sudo cp /etc/grub.d/30_os-prober /etc/grub.d/30_os-prober.bak
$ sudo chmod -x /etc/grub.d/*.bak

2. Remove memtest entry.

$ sudo chmod -x /etc/grub.d/20_memtest86+

3. Customize entries.

The /etc/grub.d/40_custom file is used to place custom entries. It also does not get overwritten by Grub updates.

Remove from the file /boot/grub/grub.cfg the lines enclosed by the following delimiters and add them to /etc/grub.d/40_custom (our Windows and Ubuntu installations will likely not change). Rename the title following each menuentry keyword or remove its associated section to reflect your installation.

### BEGIN /etc/grub.d/30_os-prober ###
…
### END /etc/grub.d/30_os-prober ###

Disable automatic detection of installed operating systems.

$ sudo chmod -x /etc/grub.d/30_os-prober

4. Change the Boot Order and Default Timeout.

These parameters can be changed by altering the values of GRUB_DEFAULT and GRUB_TIMEOUT in the /etc/default/grub file.

5. Update the grub and reboot to see the new changes.

$ sudo update-grub && sudo reboot

PostgreSQL driver for Windows and Linux

Due to license incompatibilities with the GPL, the QPSQL plugin needed to connect to a PostgreSQL database is not provided with open source versions of Qt.

This tutorial is about setting up a compete Qt development environment with PostgreSQL support for Windows 7 and Ubuntu 11.10 (Oneiric Ocelot). It also describes all steps necessary to build the QPSQL plugin for Windows using Qt SDK with MinGW.

Windows 7

1. Download Qt SDK for Windows at http://qt.nokia.com/downloads and install it.

The current version is Qt_SDK_Win_offline_v1_1_4_en.exe and its default installation folder is C:\QtSDK.

2. Download the source code associated to your Qt SDK version at http://qt.nokia.com/downloads.

Qt SDK version 1.1.4 uses qt-everywhere-opensource-src-4.7.4.zip. Unzip its content into C:\Qt\4.7.4 folder for instance.

3. For Windows 7 x64 (64-bit) you need to download a 32-bit version since it is not possible, at the moment, to compile the 64-bit version of PostgreSQL plugin.

Download PostgreSQL at http://www.postgresql.org and install it.

The current version is postgresql-9.1.1-1-windows.exe. The default PostgreSQL installation folder is C:\Program Files (x86)\PostgreSQL\9.1 (short path is C:\Progra~2\PostgreSQL\9.1) for Windows 7 x64 (64-bit) and C:\Program Files\PostgreSQL\9.1 (short path is C:\Progra~1\PostgreSQL\9.1) for Windows 7 x86 (32-bit).

4. Open Start > All Programs > Qt SDK > Desktop > Qt 4.7.4 for Desktop (MinGW).

5. Run these commands to build the QPSQL plugin (change according to your environment and make sure you use short path type):

set QTSDK_SQLDRIVERS_PATH=C:\QtSDK\Desktop\Qt\4.7.4\mingw\plugins\sqldrivers
set QT_SRC_PATH=C:\Qt\4.7.4
set POSTGRES32=C:\Progra~2\PostgreSQL\9.1

cd %QT_SRC_PATH%\src\plugins\sqldrivers\psql

qmake "INCLUDEPATH+=%POSTGRES32%\include" "LIBS+=%POSTGRES32%\lib\libpq.lib" psql.pro

mingw32-make debug
mingw32-make release

copy release\libqsqlpsql4.a %QTSDK_SQLDRIVERS_PATH%
copy release\qsqlpsql4.dll %QTSDK_SQLDRIVERS_PATH%
copy debug\libqsqlpsqld4.a %QTSDK_SQLDRIVERS_PATH%
copy debug\qsqlpsqld4.dll %QTSDK_SQLDRIVERS_PATH%

These commands build a Release (qsqlpsql4.dll, libqsqlpsql4.a) and a Debug (qsqlpsqld4.dll, libqsqlpsqld4.a) versions of the QPSQL plugin. These 4 files are then copied into Qt SDK’s SQL drivers folder.

7. The QPSQL plugin uses additional DLLs located in bin folder under the PostgreSQL installation folder. You have to copy these DDLs to the same directory as your application binary.

iconv.dll
libeay32.dll
libiconv-2.dll
libintl-8.dll
libpq.dll
libxml2.dll
libxslt.dll
ssleay32.dll
zlib1.dll

Ubuntu 11.10 (Oneiric Ocelot)

1. Install Qt Creator.

$ sudo apt-get install qtcreator

2. Install PostgreSQL.

$ sudo apt-get install postgresql

3. Optionally, you can install pgAdmin III, a handy GUI for PostgreSQL administration.

$ sudo apt-get install pgadmin3

4. Install PostgreSQL plugin for Qt 4.

$ sudo apt-get install libqt4-sql-psql

Testing

Follow the following steps to check that everything is functional.

1. Create an empty Qt console application project.

2. Make sure you have QtSql Module in your project configuration file (.pro file) by adding this line:

QT += sql

3. Update the source code as follows:

#include <QtSql>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    qDebug() << "Has a valid QPSQL driver: " << (db.isValid() ? "YES" : "NO");

    return a.exec();
}

4. Compile and run the application (Under Windows, do not forget to copy the required DLLs from the bin folder located in the PostgreSQL installation folder). You should see:

Has a valid QPSQL driver: YES