Self-signed code signing certificates


Some setup and application executables need to be signed so that they are not flagged as a security risk by security software on Windows. Especially those that have virus-like behavior such as embedded executable resources that are extracted, and executed.

The following steps were performed on Windows, from the Developer Command Prompt installed by Visual Studio.

To generate self-signed certificate for code signing, run

makecert.exe -n CN=Test.org(Test) -r -h 0 -eku "1.3.6.1.5.5.7.3.3,1.3.6.1.4.1.311.10.3.13" -e 12/31/2017 -pe -sv Test.pvk Test.cer

Here’s a brief overview of the command line
-n subject name
-r create self-signed certificate
-h max height of tree below this cert
-eku comma separated enhanced key usage ids
-e expiration date
-pe private key is exportable
-sv private key file name

You may specify a password or leave it empty.

To convert self-signed certificate to PFX format for usage with SignTool, run

Pvk2Pfx -pvk Test.pvk -spc Test.cer -pfx Test.pfx

To use SignTool to sign an executable, run

SignTool sign /fd SHA256 /a /f Test.pfx filepath.exe

Install certificate (Test.cer) to local machine before running executable.Screen Shot 2017-02-23 at 09.17.03.png

Signing a Wix Toolset setup bundle

You cannot just sign the setup bundle executable and get it to work, because the embedded executable (engine.exe) remains unsigned and will be flagged as a security risk. Use the following steps to prepare setup bundle for installation without being flagged as a security risk.

First, detach the engine from setup as follows

insignia -ib setup.exe -o engine.exe

Sign engine.exe with your certificate using SignTool

SignTool sign /fd SHA256 /a /f Test.pfx engine.exe

Re-attach the signed engine.exe to the bundle

insignia -ab engine.exe setup.exe -o setup.exe

Sign setup.exe with your certificate

SignTool sign /fd SHA256 /a /f Test.pfx setup.exe

I2C with Bus Pirate v4.0 on Windows 10


In this post, I learn to use a Bus Pirate v4.0 to retrieve raw linear acceleration data from a Tilt Compensated Compass Breakout (LSM303DLMTR), over the I2C bus (also referred to as TWI – two wire interface).

I’ve had a Bus Pirate v4.0 for three years now, but it has seen limited use because I’ve never really paused to use it in earnest.

I first used it on Windows 8 which had pretty stringent requirements for installing unsigned drivers, that I circumvented using a self-signed driver. Fortunately, Windows 10 does not require any driver installation.

The only thing you need to start using the Bus Pirate is a terminal emulation software such as Tera Term.

tera-term-bus-pirate.png
Tera Term version 4.93

Once you have Tera Term installed and connected to Bus Pirate’s serial port, you can start using the latter’s command line interface to issue commands.

To view help information

HiZ>?
General                                 Protocol interaction
---------------------------------------------------------------------------
?       This help                       (0)     List current macros
=X/|X   Converts X/reverse X            (x)     Macro x
~       Selftest                        [       Start
o       Set output type                 ]       Stop
$       Jump to bootloader              {       Start with read
&/%     Delay 1 us/ms                   }       Stop
a/A/@   AUXPIN (low/HI/READ)            "abc"   Send string
b       Set baudrate                    123     Send integer value
c/C/k/K AUX assignment (A0/CS/A1/A2)    0x123   Send hex value
d/D     Measure ADC (once/CONT.)        0b110   Send binary value
f       Measure frequency               r       Read
g/S     Generate PWM/Servo              /       CLK hi
h       Commandhistory                  \       CLK lo
i       Versioninfo/statusinfo          ^       CLK tick
l/L     Bitorder (msb/LSB)              -       DAT hi
m       Change mode                     _       DAT lo
e       Set Pullup Method               .       DAT read
p/P     Pullup resistors (off/ON)       !       Bit read
s       Script engine                   :       Repeat e.g. r:10
v       Show volts/states               ;       Bits to read/write e.g. 0x55;2
w/W     PSU (off/ON)            <x>/<x= >/<0>   Usermacro x/assign x/list all

To run a self test (connect ADC to +3.3V)

HiZ>~
Disconnect any devices
Connect (ADC to +3.3V)
Space to continue
Ctrl
AUX OK
MODE LED OK
PULLUP H OK
PULLUP L OK
VREG OK
EEPROM
SCL OK
SDA OK
WP OK
READ&WRITE OK
ADC and supply
Vusb(5.03) OK
5V(5.02) OK
5V VPU(4.89) OK
ADC(3.25) OK
3.3V(3.22) OK
3.3V VPU(3.23) OK
Bus high
MOSI OK
CLK OK
MISO OK
CS OK
Bus Hi-Z 0
MOSI OK
CLK OK
MISO OK
CS OK
Bus Hi-Z 1
MOSI OK
CLK OK
MISO OK
CS OK
MODE, VREG, and USB LEDs should be on!
Any key to exit
Found 0 errors.

Use the m command to select I2C mode

HiZ>m
1. HiZ
2. 1-WIRE
3. UART
4. I2C
5. SPI
6. 2WIRE
7. 3WIRE
8. KEYB
9. LCD
10. PIC
11. DIO
x. exit(without change)

(1)>4
I2C mode:
1. Software
2. Hardware

(1)>2
Set speed:
1. 100KHz
2. 400KHz
3. 1MHz
(1)>1
Ready

Since the breakout is being powered using Bus Pirate, here’s how to disable/enable power output

I2C>w
POWER SUPPLIES OFF
I2C>W
POWER SUPPLIES ON

To check output voltages and I/O state

I2C>v
Pinstates:
#12     #11     #10     #09     #08     #07     #06     #05     #04     #03     #02     #01
GND     5.0V    3.3V    VPU     ADC     AUX2    AUX1    AUX     -       -       SCL     SDA
P       P       P       I       I       I       I       I       I       I       I       I
GND     5.02V   3.28V   0.00V   0.00V   L       L       L       L       L       L       L

To find the address of all devices in the breakout connected to the I2C bus, we can use Bus Pirate’s address search macro. Here’s how you can list all available macros, and run the address search macro

I2C>(0)
0.Macro menu
1.7bit address search
2.I2C sniffer
3.Connect to on-board EEPROM
4.Enable Writing the on-board EEPROM
I2C>(1)
Searching I2C address space. Found devices at:
0x30(0x18 W) 0x31(0x18 R) 0x3C(0x1E W) 0x3D(0x1E R)

For curiosity’s sake, here’s a partial waveform of the I2C bus when doing address search, analyzed using Saleae’s Logic Analyzer

logic-bus-pirate-i2c-macro.png
Address search waveform in Saleae Logic

Now that we know the address of the linear accelerometer (0x18), here’s how we can read register CTRL_REG1_A (note repeated START)

I2C>[0x30 0x20 [ 0x31 r]
I2C START BIT
WRITE: 0x30 ACK
WRITE: 0x20 ACK
I2C START BIT
WRITE: 0x31 ACK
READ: 0x07
NACK
I2C STOP BIT

I configure the breakout to normal (power) mode by writing to register CTRL_REG1_A (address 0x20), and read it back

I2C>[0x30 0x20 0x27]
I2C START BIT
WRITE: 0x30 ACK
WRITE: 0x20 ACK
WRITE: 0x27 ACK
I2C STOP BIT
I2C>[0x30 0x20 [ 0x31 r]
I2C START BIT
WRITE: 0x30 ACK
WRITE: 0x20 ACK
I2C START BIT
WRITE: 0x31 ACK
READ: 0x27
NACK

Here’s how to make use of the autoincrement bit in register address, to read registers STATUS_REG_A (address 0x27) through OUT_Z_H_A (0x2D), in one go

I2C>[0x30 0xa7 [ 0x31 r:7]
I2C START BIT
WRITE: 0x30 ACK
WRITE: 0xA7 ACK
I2C START BIT
WRITE: 0x31 ACK
READ: 0xFF  ACK 0xA0  ACK 0xF9  ACK 0x30  ACK 0x05  ACK 0xF0  ACK 0xC2
NACK
I2C STOP BIT

Read WHO_AM_I_M register (address 0x0F)

I2C>[0x3c 0x0f [ 0x3d r]
I2C START BIT
WRITE: 0x3C ACK
WRITE: 0x0F ACK
I2C START BIT
WRITE: 0x3D ACK
READ: 0x3C
NACK
I2C STOP BIT

Bluetooth serial client using Windows socket API


This post shows how you can discover paired Bluetooth devices, and communicate with them, using Windows socket API. The Windows socket API is available in .NET through the excellent 32feet.NET library.

This is how you can discover Bluetooth devices paired with Windows

client = new BluetoothClient();
devices = client.DiscoverDevices(10, true, true, false);

This is how you can connect with a device, and obtain a NetworkStream to read from

Guid MyServiceUuid = new Guid("{00001101-0000-1000-8000-00805F9B34FB}");
client.Connect(devices[0].DeviceAddress, MyServiceUuid);
NetworkStream stream = client.GetStream();
ReadAsync(stream);

Here’s the implementation of ReadAsync

byte[] buffer = new byte[100];
while (true)
{
    try
    {
        int length = await stream.ReadAsync(buffer, 0, buffer.Length);
        // do something with buffer
    }
    catch
    {
        break;
    }
}

The application can send data at any time as follows

stream.Write(buffer, 0, buffer.Length);

The code above is available at GitHub as part of the Bluetooth Serial Client Tool.

bluetooth-serial-client-tool.PNG

Bluetooth serial server using Windows socket API


This post describes a means to simulate a Bluetooth serial device on Windows. This can be useful to test Bluetooth applications running on Android and Windows, that use a virtual serial port to communicate with devices.

Windows Bluetooth socket API can be used to create a server (listener). I use 32feet.NET here, a neat .NET library layered over the C/C++ socket APIs provided by Microsoft.

Here’s how you can create a Bluetooth listener on the primary adapter/radio

Guid MyServiceUuid = new Guid("{00001101-0000-1000-8000-00805F9B34FB}");
BluetoothListener listener = new BluetoothListener(MyServiceUuid); // Listen on primary radio
listener.Start();
listener.BeginAcceptBluetoothClient(acceptBluetoothClient, null);

The acceptBluetoothClient callback will be called when a client connects, and may be implemented as follows

if (listener == null) return;
client = listener.EndAcceptBluetoothClient(ar);
stream = client.GetStream();
ReadAsync(stream);

ReadAsync is an async method that continuously receives data over the Bluetooth socket, and does something useful with it

byte[] buffer = new byte[100];
while (true)
{
    try
    {
        int length = await stream.ReadAsync(buffer, 0, buffer.Length);
        // do something useful with data in buffer
    }
    catch
    {
        break;
    }
}

The application can send data at any time as follows

stream.WriteAsync(buffer, 0, buffer.Length);

As a bonus to the reader who’s come this far, the code above is available at GitHub as part of the Bluetooth Serial Server Tool.

bluetooth-spp-tool.PNG

View USB device descriptors on Windows


I have occasionally fired up a Linux virtual machine just to view USB descriptors of devices using lsusb -v. This post briefly describes a couple of tools for Windows that can be used to view descriptors of USB devices.

Thesycon USB Descriptor Dumper

This single purpose utility, from a German device driver development company, does what it proposes. It lists all connected USB devices and dumps the information for the selected device.

thesycon-usb-dd.PNG

USBView

This tool is part of the Windows Driver Kit (WDK) and Debugging Tools for Windows. Its source code is available as part of the Windows driver samples GitHub repo.

usbview.PNG

Inquire Bluetooth service record on Windows


Linux distros have excellent built-in support for inquiring characteristics of Bluetooth devices around you, using hcitool and sdptool. The closest thing on Windows is the Bluetooth Inquiry Record Verifier tool (sdpverify.exe) that ships with Windows Driver Kit (WDK). Beware, WDK is a rather large download.

Screen Shot 2016-12-06 at 10.27.36.png

Dealing with .NET’s messy WebBrowser control


I’ve been trying hard to coax .NET’s WebBrowser control to log in using PingFederate federation server. I particularly don’t want to mess with the registry to change Internet Explorer’s browser emulation settings due to a single application. Something that with Android is amazingly simple, requires a lot of extra effort with .NET for the Desktop.

The WebBrowser control defaults to IE7 emulation as seen by the following User-Agent header, discovered using Fiddler.

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729)

There’s a bug in the browser control that sends a trailing null character in POST data.

pf.username=xxx&pf.pass=xxx&pf.ok=clicked&pf.cancel=<NULL>

I had to extend the WebBrowser control, gain access to its internal ActiveX control, and use events of that control to modify the behavior just enough to be able to log in using PingFederate. The code that does that is reproduced below.

    public class ExtendedWebBrowser : WebBrowser
    {
        bool renavigating = false;

        public string UserAgent { get; set; }

        public delegate void BeforeNavigateDelegate(string url, ref bool cancel);

        public event BeforeNavigateDelegate HandleBeforeNavigate;

        public delegate void NavigateErrorDelegate(string url, ref bool cancel);

        public event NavigateErrorDelegate HandleNavigateError;

        public ExtendedWebBrowser()
        {
            DocumentCompleted += SetupBrowser;

            //this will cause SetupBrowser to run (we need a document object)
            Navigate("about:blank");
        }

        void SetupBrowser(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            DocumentCompleted -= SetupBrowser;
            SHDocVw.WebBrowser xBrowser = (SHDocVw.WebBrowser)ActiveXInstance;
            xBrowser.BeforeNavigate2 += BeforeNavigate;
            xBrowser.NavigateError += NavigateError;
        }

        private void NavigateError(object pDisp, ref object URL, ref object Frame, ref object StatusCode, ref bool Cancel)
        {
            if (HandleNavigateError != null)
                HandleNavigateError.Invoke((string)URL, ref Cancel);
        }

        void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
            ref object postData, ref object headers, ref bool cancel)
        {
            if (renavigating)
            {
                renavigating = false;
                if (HandleBeforeNavigate != null)
                {
                    HandleBeforeNavigate.Invoke((string)url, ref cancel);
                }
            }
            else
            {
                byte[] pSrc = (byte[])postData;
                byte[] p = pSrc;

                if (pSrc != null && pSrc[pSrc.Length - 1] == 0)
                {
                    // remove trailing null from POST data
                    p = new byte[((byte[])postData).Length - 1];
                    Array.Copy(((byte[])postData), p, p.Length);
                    renavigating = true;
                }

                if (!string.IsNullOrEmpty(UserAgent))
                {
                    headers += string.Format("User-Agent: {0}\r\n", UserAgent);
                    renavigating = true;
                }

                if (renavigating)
                {
                    Navigate((string)url, (string)targetFrameName, p, (string)headers);
                    cancel = true;
                }
            }
        }
    }

The authorization code returned by PingFederate can be obtained by registering for HandleNavigateError event. Using the HandleBeforeNavigate event handler does not work, because it is not invoked when the browser control is redirected after a 302 Not Found response.

            extendedWebBrowser1.HandleNavigateError += delegate (string url,
                ref bool cancel)
            {
                cancel = ExtractAuthorizationCode(url);
            };