dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.01k stars 4.67k forks source link

Cannot correctly use LdapSessionOptions.StopTransportLayerSecurity without tracking state locally #49726

Open AnthonyMastrean opened 3 years ago

AnthonyMastrean commented 3 years ago

Description

It's obvious that we should always dispose of an LdapConnection instance via a using statement (or similar).

using (var connection = new LdapConnection(...))
{
    ...
}

To use LDAP with TLS, we're supposed to call the relevant "start" method on the session options instance. I assume, but it's not documented, that we should attempt to stop TLS if we started it. I'm thinking a try...finally block?

using (var connection = new LdapConnection(...))
{
    try
    {
        connection.SessionOptions.StartTransportLayerSecurity(null);
        // use the connection instance... 
    }
    finally
    {
        connection.SessionOptions.StopTransportLayerSecurity();
    }
}

However, if, for whatever reason, it's the start method call that fails leading to the stop method call in the finally block, the stop method will throw a TlsOperationException, which is documented. But, that means, I need to either wrap that call or track a local Boolean.

using (var connection = new LdapConnection(...))
{
    var startedTls = false;
    try
    {
        connection.SessionOptions.StartTransportLayerSecurity(null);
        startedTls = true;
        // use the connection instance... 
    }
    finally
    {
        try
        {
            if (startedTls)
            {
                connection.SessionOptions.StopTransportLayerSecurity();
            }
        }
        catch (TlsOperationException)
        {
            // this catch block intentionally left blank
        }
    }
}

This is kind of a hot mess, right? Is there any way to get a bool returned by the start/stop methods? or for the session options to track this state like it does for "secure socket layer" (if that is, in fact, what is happening there)?

Configuration

.NET 5.0 on Windows 10 and Debian Linux.

Regression?

Other information

dotnet-issue-labeler[bot] commented 3 years ago

I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

AnthonyMastrean commented 3 years ago

A related issue #54274 discusses adding some of the same state tracking I was thinking about.