SslStream Finalizer Throws NullReferenceException After Constructor Failure

Environment

Hardware: GHI SCM20260D

Affected TinyCLR version: 3.0.3.1000 (with matching packages)

Problem Description

The bug was originally discovered while using GHI’s MQTT library, but was narrowed down to the uderlying SslStream implementation.

We noticed the exception while implementing some MQTT connection recovery logic. Upon a failed connection attempt, subsequent garbage collection would result in an unhandled NullReferenceException originating from the SslStream Finalizer.

Steps To Reproduce
  1. Configure and establish an Ethernet connection on the SCM20260D
  2. Create a TCP socket
  3. Do NOT connect the TCP socket
  4. Construct an SslStream using the Non-Connected Socket
  5. Catch the exeption thrown by the base NetworkStream constructor
  6. Trigger garbage collection and wait for pending finalizers
  7. Observe the unhandled NullReferenceException

The files in “Supporting Materials” contain a minimal reproduction of this issue.

Expected vs Actual Behavior

Expected

The SslStream constructor should throw an exception when given a non-connected socket. Once the exception is caught, garbage collection and finalization should complete without any more exceptions.

Actual

The constructor exception is caught successfully, but subsequent finalization results in this unhandled exeption:

System.NullReferenceException - CLR_E_NULL_REFERENCE

System.Net.Security.SslStream::Dispose
System.Net.Security.SslStream::Finalize

An unhandled exception of type
'System.NullReferenceException' occurred in
GHIElectronics.TinyCLR.Networking.dll
Possible Cause?

The available GitHub source code gives some clues about the possible cause.

The constructor for SslStream’s base class, NetworkStream, is expected to throw if the socket is not connected, among other conditions. The problem is that this might leave SslStream’s constructor body un-executed.

Specifically, SslStream’s constructor sets the following fields after calling the base constructor:

this._isServer = false;        
this.sslHandle = -1;
this.ni = Socket.DefaultProvider;

Since the base constructor throws, those fields are left to their default values, these being false, 0, and null respectively.

When the finalizer is called, it invokes Dispose(false), which eventually checks:

if (this.sslHandle != -1) {
                    this.ni.Close(this.sslHandle);
                    this.sslHandle = -1;
                }

At this point, sslHandle is not the expected value of -1 and is instead the default value of 0. This allows the Finalizer to attempt to close the handle through the uninitialized ni object, which is still null.

This appears to be the cause of the NullReferenceException, but I haven’t tested a rebuilt version of the library that addresses this. So it’s just speculation.

It might be possible to solve this problem by setting the value of sslHandle to -1 in the declaration rather than in the constructor. Similarly, guards against uninitialized or partially initialized fields in the finalizer/disposal logic can help mitigate it. Just suggestions tho.

Impact

This bug manifests as an uncaught null reference exception after failed connection attempts.

Our project implements an exponential backoff system to ensure connectivity of our IoT device, which means there can potentially be several failed connections before a successful connection occurs.

Although the original connection exceptions can be caught by the application, the finalizer exception happens outside the connection attempt’s call stack. So it makes it a little more difficult to guarantee reliable connection.

Supporting Materials

Attached is a link to an example project containing a minimal reproduction of the bug. It might help narrow down the cause.

https://drive.google.com/file/d/10tSWlbCNqZ3NH6gaIPvw3cYBuCjojxOu/view?usp=sharing

If the link isn’t working, this is what its Program.cs file looks like:

Minimal Reproduction
using GHIElectronics.TinyCLR.Devices.Gpio;
using GHIElectronics.TinyCLR.Devices.Network;
using GHIElectronics.TinyCLR.Pins;
using System;
using System.Diagnostics;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading;

namespace Ssl_FailedConstructor
{
    internal class Program
    {
        static void Main()
        {
            try
            {
                // Setting up Ethernet Controller before messing with sslStream.
                var netController = SetupEthernet();
                netController.Enable();
                netController.SetAsDefaultController();
                DateTime dhcpDeadline = DateTime.UtcNow.AddSeconds(10);

                // Waiting for DHCP to assign an IP address
                while (!netController.GetLinkConnected() || netController.GetIPProperties().Address.ToString() == "0.0.0.0")
                {
                    if (DateTime.UtcNow >= dhcpDeadline)
                    {
                        throw new Exception("DHCP address assignment timed out.");
                    }

                    Thread.Sleep(100);
                }
                Debug.WriteLine("\n\nDHCP Address Assigned.\n");

                // Minimal Bug Reproduction
                TestSslStreamFinalizer();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("TEST FAILED:");
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
            }
        }

        private static void TestSslStreamFinalizer()
        {
            Debug.EnableGCMessages(true);
            Debug.WriteLine("[TEST] Creating unconnected TCP socket.");

            using (var socket = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp))
            {
                SslStream sslStream = null;

                try
                {
                    Debug.WriteLine("[TEST] Constructing SslStream.");

                    // We are intentionally passing a Non-Connected Socket into sslStream constructor
                    // This causes the base NetworkStream constructor to throw, preventing the SslStream 
                    // constructor from fully executing.
                    //
                    // Because of this, the internal sslHandle and ni fields retain default values of 
                    // 0 and null respectively.
                    sslStream = new SslStream(socket);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("[CAUGHT] Constructor exception:");
                    Debug.WriteLine(ex.GetType().FullName);
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }

                if (sslStream != null)
                {
                    Debug.WriteLine("[UNEXPECTED] Constructor succeeded.");

                    sslStream.Dispose();

                    return;
                }

                Debug.WriteLine("[TEST] Constructor failure handled.");
            }

            Debug.WriteLine("[TEST] Forcing garbage collection.");

            // Forcing the garbage collector calls SslStream's finalizer, which invokes Dispose(false)
            // Because sslHandle retains its default value of 0 rather than -1, the Dispose logic
            // appears to attempt to close the SSL handle through the 'ni' which is still NULL.
            //
            // This results in an unhandled NullReferenceException during finalization.
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Debug.WriteLine("[TEST] Finalization complete.");
        }

        private static NetworkController SetupEthernet()
        {
            // using GHI's reset pin code here
            var gpioController = GpioController.GetDefault();

            var resetPin = gpioController.OpenPin(SC20260.GpioPin.PG3);

            resetPin.SetDriveMode(GpioPinDriveMode.Output);

            resetPin.Write(GpioPinValue.Low);
            Thread.Sleep(100);

            resetPin.Write(GpioPinValue.High);
            Thread.Sleep(100);


            //initialize the communication and inteface settings
            var interfaceSettings = new EthernetNetworkInterfaceSettings
            {
                DhcpEnable = true,
                MacAddress = new byte[]
                {
                    0x02, 0x00, 0x00,
                    0x00, 0x00, 0x01
                }
            };
            var commSettings = new BuiltInNetworkCommunicationInterfaceSettings();

            // initialize the network controller and applying the settings
            var netController = NetworkController.FromName(SC20260.NetworkController.EthernetEmac);
            netController.SetCommunicationInterfaceSettings(commSettings);
            netController.SetInterfaceSettings(interfaceSettings);

            return netController;
        }
    }
}

And here is the debug output the minimal reproduction should produce:

Debug Output
DHCP Address Assigned.

[TEST] Creating unconnected TCP socket.
[TEST] Constructing SslStream.
    #### Exception System.InvalidOperationException - CLR_E_INVALID_OPERATION (1) ####
    #### Message: 
    #### GHIElectronics.TinyCLR.Devices.Network.Provider.NetworkControllerApiWrapper::GetRemoteAddress [IP: 0000] ####
    #### System.Net.Sockets.Socket::GetEndPoint [IP: 003d] ####
    #### System.Net.Sockets.NetworkStream::.ctor [IP: 0011] ####
    #### System.Net.Security.SslStream::.ctor [IP: 0006] ####
    #### Ssl_FailedConstructor.Program::TestSslStreamFinalizer [IP: 0023] ####
    #### Ssl_FailedConstructor.Program::Main [IP: 0069] ####
    #### Exception System.IO.IOException - 0x00000000 (1) ####
    #### Message: 0
    #### System.Net.Sockets.NetworkStream::.ctor [IP: 0032] ####
    #### System.Net.Security.SslStream::.ctor [IP: 0006] ####
    #### Ssl_FailedConstructor.Program::TestSslStreamFinalizer [IP: 0023] ####
    #### Ssl_FailedConstructor.Program::Main [IP: 0069] ####
Exception thrown: 'System.IO.IOException' in GHIElectronics.TinyCLR.Networking.dll
[CAUGHT] Constructor exception:
System.IO.IOException
0
System.Net.Sockets.NetworkStream::.ctor
System.Net.Security.SslStream::.ctor
Ssl_FailedConstructor.Program::TestSslStreamFinalizer
Ssl_FailedConstructor.Program::Main

[TEST] Constructor failure handled.
[TEST] Forcing garbage collection.
GC: 1msec 162304 bytes used, 345520 bytes available
Type 11 (STRING              ):    352 bytes
Type 13 (CLASS               ):   3040 bytes
Type 14 (VALUETYPE           ):    144 bytes
Type 15 (SZARRAY             ):   1344 bytes
  Type 03 (U1                  ):    336 bytes
  Type 04 (CHAR                ):    320 bytes
  Type 07 (I4                  ):    336 bytes
  Type 13 (CLASS               ):    352 bytes
Type 17 (FREEBLOCK           ): 345520 bytes
Type 18 (CACHEDBLOCK         ):     96 bytes
Type 19 (ASSEMBLY            ):  17856 bytes
Type 1B (REFLECTION          ):     64 bytes
Type 1D (DELEGATE_HEAD       ):    144 bytes
Type 1F (OBJECT_TO_EVENT     ):     64 bytes
Type 20 (BINARY_BLOB_HEAD    ): 136496 bytes
Type 21 (THREAD              ):    400 bytes
Type 22 (SUBTHREAD           ):     48 bytes
Type 23 (STACK_FRAME         ):    832 bytes
Type 29 (FINALIZER_HEAD      ):     96 bytes
Type 33 (IO_PORT             ):     96 bytes
Type 36 (APPDOMAIN_HEAD      ):     80 bytes
Type 38 (APPDOMAIN_ASSEMBLY  ):   1152 bytes
GC: performing heap compaction...
    #### Exception System.NullReferenceException - CLR_E_NULL_REFERENCE (3) ####
    #### Message: 
    #### System.Net.Security.SslStream::Dispose [IP: 001d] ####
    #### System.Net.Security.SslStream::Finalize [IP: 0005] ####
An unhandled exception of type 'System.NullReferenceException' occurred in GHIElectronics.TinyCLR.Networking.dll

 Uncaught exception 
[TEST] Finalization complete.
The thread '<No Name>' (1) has exited with code 0 (0x0).
The program '[1] TinyCLR application: Managed' has exited with code 0 (0x0).