Monday, August 23, 2021

Late Binding Client Code Generator for COM Components

Let's suppose you have a C# class that acts as a server and you need clients to consume it across network.
There are two options:
  1. DCOM via COM+
  2. WCF
Presently .NET framework provides RCW (Remote callable wrapper) mechanism for .NET code to interface with COM components. However it does not support late binding and has following limitations notably:
  1. Early bound requires tlb or dll to be part of the project for unmanaged dlls
  2. Managed com dlls cannot be consumed using tlb by managed client
  3. Don't support  remote activation to work across network.
Late Binding Client Code Generator tries to address as below:
  • Generate C# based late binding client code 
  • Generate VBScript based late binding client code 
  • Generate remote registration files
  • Supports .Net framework 3.5
  • Generate code that can be deployed as a WCF Server using COM+ Integration
  • Generate code to start and stop COM+ application
Example
WSC COM component
As described in the previous post, use sillycalc.wsc. Load  the wsc file as shown below and generate the wrapper code.



COM+ services offers features such as thread pooling, object pooling, just in time activation, security etc. These services can be availed by hosting COM components in a COM+ application.
This also allows the COM component to be consumed across the network using DCOM.

Add the component in a COM+ application by executing the command

ComAppHelper.exe  -ins -app:testcalc -reg  D:\Github\TechBlog\COM+\WSC\server\sillycalc.wsc

This will create a COM+ application called calctest and hosts SillyCalc.WSC  as shown below

C# client
The outputfile.cs contains a class COM_LB_SillyCalc_WSC_1 which can be instantiated to create a proxy for the server. This class also contains wrapper code for calling the methods and properties defined in the server.
Below is an example:
       
class Program
{
        public static void Main()
        {
            var lbclient = new COM_LB_SillyCalc_WSC_1("127.0.0.1");
            Console.WriteLine("40+6={0}", lbclient.add(40, 6));
        }
}	

 
 

The output

VBScript client
outputfile.vbs contains a class COM_LB_SillyCalc_WSC_1 which can be instantiated to create a proxy for the server. This class also contains wrapper code for calling the methods and properties defined in the server.
Add following at the bottom of outputfile.vbs, Edit add function to remove set.
       
	   
set x = new COM_LB_SillyCalc_WSC_1
x.createcomobject("127.0.0.1")
msgbox (x.add(10,2))

 
 
Execute as shown below:
cscript  outputfile.vbs

The output


Managed COM component
As described in the previous post, use CalcServer.Calucalator. Load  the dll file as shown below and generate the wrapper code.


Add the component in a COM+ application by executing the command:

ComAppHelper.exe -ins -app:calctest  -reg -runforever  D:\Github\TechBlog\COM+\Managed\server\bin\CalcServer.dll

This will create a COM+ application called calctest and hosts CalcServer.dll as shown below

C# client
The outputfile.cs contains a class COM_LB_CalcServer_Calucalator which can be instantiated to create a proxy for the server. This class also contains wrapper code for calling the methods and properties defined in the server.
Below is an example:
       
	   
class Program
{
        public static void Main()
        {
            var lbclient = new                     COM_LB_CalcServer_Calucalator("127.0.0.1");
            Console.WriteLine("40+6={0}", lbclient.add(40, 6));
        }
}

 
 

The output

VBScript client
outputfile.vbs contains a class COM_LB_CalcServer_Calucalator which can be instantiated to create a proxy for the server. This class also contains wrapper code for calling the methods and properties defined in the server.
Add following at the bottom of outputfile.vbs, Edit add function to remove set.
       
	   
set remoteclient = new COM_LB_CalcServer_Calucalator
remoteclient.CreateComObject "127.0.0.1"
msgbox remoteclient.add(10,2)

 
 
Execute as shown below:
cscript  outputfile.vbs

The output

Debugging a Component in COM+ Application
To debug, simply attach to the dllhost process in visual studio. 


Make sure correct pdb files are copied.

Set breakpoint and debugger breaks.


Source and Binaries can be found here.


Monday, August 9, 2021

APITester - Test any COM component using its typelibrary


 COM components are often used in backend, require elaborate workflows, complex GUIs. For ad hoc testing at for example customer site with specific inputs, separate test application needs to be created.

APITester tries to solve this problem, It reads the typelibrary and presents a simple user interface that lists  exposed apis and their parameters as shown below.  Further more the executed functions are saved and restored reducing the burden of reentering details. Also the logging shows previously executed apis.



components can be selected from COM+ application as shown below.

 or manually from typelibrary as below

After selecting the component the drop down lists all possible APIS. For VARIANT data types, a specific data type can be selected from the dropdown list. Data can be entered in the value column.

Upon executing by clicking ! button, the results are added to the log.

The source and executables can be found here.

Note:- 
TLILib.dll is used for reading typelibrarry. it should be registered on the machine where used.
MSFLEXGRID.OCX  is used for presentation and inputs. it should be registered on the machine where used.

Source and Binaries can be found here.




Sunday, August 1, 2021

Enabling Bitlocker with pre-provisioned Encryption in the installers.


In a regulated environments data theft  can be a costly an ordeal. Disk encryption helps to safeguard the data when it reaches wrong hands.
In Windows environment, bitlocker enables full volume encryption. When coupled with TPM, it's almost ensured that the data will be accessible on the same hardware.

Overview of TPM

  • Trusted Platform Module (TPM) is a cryptographic coprocessor embedded in the motherboard
  • TPM can be used for public key cryptography and also perform system integrity checks on critical early boot components.
  • TPM comes with Endorsement Key (EK) preconfigured by the hardware manufacturer.
  • When the TPM is owned with a secret password,  Storage Root Key (SRK) is generated and is encrypted by EK.
  • TPM collects and stores measurements from multiple early boot components and boot configuration data to create a system identifier in a 160-bit platform configuration register (PCR).
  • Win32_TPM WMI interface can be used to interact with TPM programmatically.

Overview of Bitlocker

  • Bitlocker was introduced in Vista; it can be used for full volume encryption (FVE) of the OS (C:) and Data volumes ( D: )
  • The BitLocker filter driver (Fvevol.sys), performs on-the-fly encryption and decryption of the volume.
  • The volume is encrypted with a full-volume encryption key (FVEK)
  • In turn, the FVEK is encrypted with a volume master key (VMK) and stored in a special metadata region of the volume.
  • Win32_EncryptedVolume WMI interface can be used to interact with bitlocker programmatically. Alternatively, manage-bde tool can also be used.

How does it work?

When bitlocker is used with TPM, the VMK is Sealed. When Sealed, the VMK is protected in two folds:
  1. VMK is encrypted by SRK.
  2. The measurements from multiple early boot components and boot configuration data are checked against tampering during boot.(However, the measurements are reset when the machine is powered off and then powered on.)

As OS volume (C:) is also encrypted, an additional primary partition, at least 100 MB in size and unencrypted needs to be created to store boot records and boot time system files.

Encryption is highly time consuming and requires several hours to encrypt a volume with data. Therefore, encryption is usually pre-provisioned on an empty hard disk. Alternatively it can be done passively when the system is idle as discussed here.

Deployment overview

A typical installation consists of three stages. For simplicity a new installation assumed. 

Stage 1: Configure TPM in BIOS
If the TPM is disabled in the BIOS, it needs to be enabled manually in the BIOS. It's necessary since when TPM is disabled, it's completely cut off from the OS and hence it cannot be manipulated programmatically in the next stage.

Stage 2: WinPE
The installation is kicked off by booting from WinPE via an USB drive. The WinPE should be version 3(Windows 8) and above to take advantage of "used" option during encryption. This stage has following steps.

Configure TPM's state
The first step is to set TPM's state to Enabled, Activated and Disowned.
If the TPM was previously owned and password is lost, it should be cleared first.
This process involves a reboot and the user needs to acknowledge a BIOS warning indicating clearing of TPM by typing  F12 key on the keyboard.

TPM's states can be altered programmatically. The following pseudo code should help.
       
if  isEnabled=false and isActivated = FALSE and isOwned  = FALSE then
  required_action = 10
else if isEnabled=FALSE and isActivated = FALSE and isOwned = TRUE then
  required_action = 6
else if isEnabled=TRUE and isActivated = TRUE and isOwned = FALSE then
  required_action = 8 
else if isEnabled=TRUE and isActivated = TRUE and IsisOwned = TRUE then
  required_action = 14
else
  Wscript.echo "TPM is in incorrect state. Check and correct it in BIOS"
  required_action = 0
end if

 retval = SetPhysicalPresenceRequest(required_action)
 if retval <> 0 then 
  Wscript.echo "SetPhysicalPresenceRequest action has failed"
  exit function
 end if
 retval = wmiObject.GetPhysicalPresenceTransition  (transition)
 if retval <> 0 then 
  Wscript.echo "GetPhysicalPresenceTransition query has failed"
  exit function
 end if

 ' 0= no action 1= warm restart 2=cold restart
 if transition = 1 or transition = 2 then 
  wscript.echo "GetPhysicalPresencetransitionsition returned value" & transition
  exit function
 end if
       
 

Create volumes
This step will first create volumes. As discussed, a dedicated primary partition of 100 MB or more is required. Following is an example.

Primary Partition 1
Volume 1
Name: Bitlocker  Drive: P Purpose: Store Boot records and system files

Primary Partition 2
Volume 1
Name:System Drive:Q Purpose:Store Application OS + Application Software

Primary Partition 3
Volume 1
Name:Data Drive:R Purpose:Store Application Data

Encrypt volumes
This step will encrypt volumes System and Data using manage-BDE tool as below:
manage-bde -on Q: -used 
manage-bde -on R: -used 

Load WIM image
This step will load Wim image to the System volume.
dism /apply-image /imagefile:installer.wim /index:1 /applydir:q:\

Add Boot record
This step will add boot records and system files to the Bitlocker volume.
bcdboot q:\windows /s p:

Stage 3: Application Installation
In this stage, the custom OS and the application gets installed. The following steps needs to be performed.

Own TPM
Note the following applies for Windows 7 OS or previous only. In Windows 10 and above, TPM is automatically owned by the OS so there is no need to take ownership.
In this step, the TPM is owned and this will generate a new SRK that will be used for encrypting VMKs. I the TPM is in Disowned state, the ownership can be acquired by calling "TakeOwnership" API. Otherwise "ChangeOwnerAuth" API needs to be called.

Add Protectors
In this step,  the System volume is added with  TPM protector
MANAGE-BDE -protectors -add c: -tpm
MANAGE-BDE -on c:
The Data volume is then added with an Autounlock protector.
MANAGEBDE -autounlock  d: -enable
MANAGE-BDE -on d:

Backup Recovery keys
In this step,  The recovery keys will be stored to an USB drive. Whenever TPM detects a system tampering, the OS will demand recovery keys during the boot.
In the case below, the usb drive is f: and the recvoery keys will be stored there.
manage-bde -protectors -add c: -rk f:
manage-bde -protectors -get d: -sek f:

Source and Binaries can be found here.