Skip to content

Implement verify server cert on linux#125157

Draft
JasonDebug wants to merge 4 commits intodotnet:mainfrom
JasonDebug:Implement-VerifyServerCert-on-Linux
Draft

Implement verify server cert on linux#125157
JasonDebug wants to merge 4 commits intodotnet:mainfrom
JasonDebug:Implement-VerifyServerCert-on-Linux

Conversation

@JasonDebug
Copy link
Contributor

In an attempt to address #60972, I've implemented VerifyServerCertificate for Linux using OpenSSL and OpenLDAP. I have confirmed via network trace that returning false from the callback will sever the connection with a RST on the wire.

Copilot AI review requested due to automatic review settings March 4, 2026 00:23
@dotnet-policy-service dotnet-policy-service bot added the community-contribution Indicates that the PR has been added by a community member label Mar 4, 2026
@dotnet-policy-service
Copy link
Contributor

@JasonDebug please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@dotnet-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@dotnet-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@dotnet-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement ( “Agreement” ) is agreed to by the party signing below ( “You” ),
and conveys certain license rights to the .NET Foundation ( “.NET Foundation” ) for Your contributions to
.NET Foundation open source projects. This Agreement is effective as of the latest signature date below.

1. Definitions.

“Code” means the computer software code, whether in human-readable or machine-executable form,
that is delivered by You to .NET Foundation under this Agreement.

“Project” means any of the projects owned or managed by .NET Foundation and offered under a license
approved by the Open Source Initiative (www.opensource.org).

“Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
Project, including but not limited to communication on electronic mailing lists, source code control
systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
discussing and improving that Project, but excluding communication that is conspicuously marked or
otherwise designated in writing by You as “Not a Submission.”

“Submission” means the Code and any other copyrightable material Submitted by You, including any
associated comments and documentation.

2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
Project. This Agreement covers any and all Submissions that You, now or in the future (except as
described in Section 4 below), Submit to any Project.

3. Originality of Work. You represent that each of Your Submissions is entirely Your
original work. Should You wish to Submit materials that are not Your original work,
You may Submit them separately to the Project if You (a) retain all copyright and
license information that was in the materials as you received them, (b) in the
description accompanying your Submission, include the phrase "Submission
containing materials of a third party:" followed by the names of the third party and any
licenses or other restrictions of which You are aware, and (c) follow any other
instructions in the Project's written guidelines concerning Submissions.

4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
Submission is made in the course of Your work for an employer or Your employer has intellectual
property rights in Your Submission by contract or applicable law, You must secure permission from Your
employer to make the Submission before signing this Agreement. In that case, the term “You” in this
Agreement will refer to You and the employer collectively. If You change employers in the future and
desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
and secure permission from the new employer before Submitting those Submissions.

5. Licenses.

a. Copyright License. You grant .NET Foundation, and those who receive the Submission directly
or indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable
license in the Submission to reproduce, prepare derivative works of, publicly display, publicly perform,
and distribute the Submission and such derivative works, and to sublicense any or all of the foregoing
rights to third parties.

b. Patent License. You grant .NET Foundation, and those who receive the Submission directly or
indirectly from .NET Foundation, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license
under Your patent claims that are necessarily infringed by the Submission or the combination of the
Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
import or otherwise dispose of the Submission alone or with the Project.

c. Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
granted by implication, exhaustion, estoppel or otherwise.

6. Representations and Warranties. You represent that You are legally entitled to grant the above
licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
have disclosed under Section 3 ). You represent that You have secured permission from Your employer to
make the Submission in cases where Your Submission is made in the course of Your work for Your
employer or Your employer has intellectual property rights in Your Submission by contract or applicable
law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
EXPRESSLY STATED IN SECTIONS 3, 4, AND 6 , THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.

7. Notice to .NET Foundation. You agree to notify .NET Foundation in writing of any facts or
circumstances of which You later become aware that would make Your representations in this
Agreement inaccurate in any respect.

8. Information about Submissions. You agree that contributions to Projects and information about
contributions may be maintained indefinitely and disclosed publicly, including Your name and other
information that You submit with Your Submission.

9. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
defenses of lack of personal jurisdiction and forum non-conveniens.

10. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
supersedes any and all prior agreements, understandings or communications, written or oral, between
the parties relating to the subject matter hereof. This Agreement may be assigned by .NET Foundation.

.NET Foundation dedicates this Contribution License Agreement to the public domain according to the Creative Commons CC0 1.

@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-directoryservices
See info in area-owners.md if you want to be subscribed.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds Linux support for LdapSessionOptions.VerifyServerCertificate by wiring OpenLDAP’s TLS connect hook to an OpenSSL verify callback, aligning behavior more closely with the existing Windows implementation and addressing #60972.

Changes:

  • Refactors VerifyServerCertificate/callback plumbing into OS-specific partials and initializes the callback delegate per-platform.
  • Implements Linux TLS server-certificate verification via OpenLDAP LDAP_OPT_X_TLS_CONNECT_CB + OpenSSL SSL_set_verify.
  • Introduces new OpenLDAP/OpenSSL interop declarations and adds the OpenSSL interop file to the build.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs Moves server-cert verification wiring out to OS partials; calls per-OS initializer.
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Windows.cs Restores Windows VerifyServerCertificate property and callback implementation.
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs Implements Linux VerifyServerCertificate using OpenLDAP TLS connect callback + OpenSSL verify callback.
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Linux.cs Adjusts Linux PAL server-cert option setter to accept an IntPtr.
src/libraries/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj Includes the new OpenSSL interop file for linux/osx builds.
src/libraries/Common/src/Interop/Windows/Wldap32/Interop.Ldap.cs Relocates VERIFYSERVERCERT delegate definition into Windows interop.
src/libraries/Common/src/Interop/Linux/OpenSsl/Interop.OpenSsl.cs Adds OpenSSL P/Invokes for verify callback support.
src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ldap.cs Adds TLS connect callback delegate and a pointer-valued ldap_set_option P/Invoke.
src/libraries/Common/src/Interop/Interop.Ldap.cs Adds OpenLDAP TLS connect option enum values.
Comments suppressed due to low confidence (2)

src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs:194

  • The new VerifyServerCertificate implementation on Linux bypasses the PAL layer and calls Interop.Ldap.ldap_set_option_ptr_value directly. Please consider adding a dedicated LdapPal helper for setting the TLS connect callback (and using it here) to keep interop usage centralized and consistent with other options.
                if (value != null)
                {
                    IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(_serverCertificateRoutine);
                    int error = Interop.Ldap.ldap_set_option_ptr_value(_connection._ldapHandle, LdapOption.LDAP_OPT_X_TLS_CONNECT_CB, functionPointer);

                    ErrorChecking.CheckAndSetLdapError(error);
                }

src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ldap.cs:170

  • The ldap_set_option_ptr_value addition leaves behind commented-out P/Invoke declarations. Please remove the commented code to keep the interop surface clean and avoid confusion about which signature is correct.
        //[LibraryImport(Libraries.OpenLdap, EntryPoint = "ldap_set_option")]
        //public static partial int ldap_set_option_ptr(IntPtr ldapHandle, LdapOption option, ref IntPtr inValue);

}
finally
{
cert.Dispose();
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cert.Dispose() in the verify callback can leave user code holding a disposed X509Certificate instance if they capture it from the callback for later inspection/logging. Windows implementation doesn’t dispose the certificate passed to the delegate. To keep behavior consistent and avoid surprising ObjectDisposedExceptions, don’t dispose the certificate here (or pass a non-disposable clone).

Suggested change
cert.Dispose();

Copilot uses AI. Check for mistakes.
Comment on lines +120 to +124
internal static int SetServerCertOption(ConnectionHandle ldapHandle, LdapOption option, IntPtr inValue)
{
IntPtr functionPointer = inValue;
return Interop.Ldap.ldap_set_option_ptr(ldapHandle, option, ref functionPointer);
}
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LdapPal.SetServerCertOption now wraps ldap_set_option_ptr with a ref IntPtr, which passes a pointer-to-pointer. For options like LDAP_OPT_X_TLS_CONNECT_CB (function pointer value), the call sites in this PR use a different P/Invoke that passes the pointer value directly. To prevent future misuse, either remove SetServerCertOption on Linux if it’s unused, or implement it in terms of the correct setter (ldap_set_option_ptr_value) for callback-style options.

Suggested change
internal static int SetServerCertOption(ConnectionHandle ldapHandle, LdapOption option, IntPtr inValue)
{
IntPtr functionPointer = inValue;
return Interop.Ldap.ldap_set_option_ptr(ldapHandle, option, ref functionPointer);
}
internal static int SetServerCertOption(ConnectionHandle ldapHandle, LdapOption option, IntPtr inValue) =>
Interop.Ldap.ldap_set_option_ptr_value(ldapHandle, option, inValue);

Copilot uses AI. Check for mistakes.
Comment on lines +188 to +195
if (value != null)
{
IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(_serverCertificateRoutine);
int error = Interop.Ldap.ldap_set_option_ptr_value(_connection._ldapHandle, LdapOption.LDAP_OPT_X_TLS_CONNECT_CB, functionPointer);

ErrorChecking.CheckAndSetLdapError(error);
}

Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With Linux support added, VerifyServerCertificate is no longer Windows-only behavior, but existing tests currently validate set/get only on Windows. Please extend LdapSessionOptionsTests.VerifyServerCertificate_Set_GetReturnsExpected to run on Linux as well (and ideally validate that returning false aborts the handshake, if test infrastructure allows).

Suggested change
if (value != null)
{
IntPtr functionPointer = Marshal.GetFunctionPointerForDelegate(_serverCertificateRoutine);
int error = Interop.Ldap.ldap_set_option_ptr_value(_connection._ldapHandle, LdapOption.LDAP_OPT_X_TLS_CONNECT_CB, functionPointer);
ErrorChecking.CheckAndSetLdapError(error);
}
IntPtr functionPointer = value is not null
? Marshal.GetFunctionPointerForDelegate(_serverCertificateRoutine)
: IntPtr.Zero;
int error = Interop.Ldap.ldap_set_option_ptr_value(
_connection._ldapHandle,
LdapOption.LDAP_OPT_X_TLS_CONNECT_CB,
functionPointer);
ErrorChecking.CheckAndSetLdapError(error);

Copilot uses AI. Check for mistakes.
Comment on lines +12 to +13
private const string LibSsl = "libssl.so.3";
private const string LibCrypto = "libcrypto.so.3";
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interop.OpenSsl hardcodes libssl.so.3/libcrypto.so.3, which will fail on supported distros that still ship OpenSSL 1.1 (and it also won’t work on macOS). Please switch to a version-resilient loading strategy consistent with the repo (e.g., route through the existing OpenSSL shim in System.Security.Cryptography.Native, or introduce a shim export for the needed APIs) rather than binding directly to versioned .so names.

Suggested change
private const string LibSsl = "libssl.so.3";
private const string LibCrypto = "libcrypto.so.3";
private const string LibSsl = "libssl";
private const string LibCrypto = "libcrypto";

Copilot uses AI. Check for mistakes.
Comment on lines 85 to 89
<Compile Include="$(CommonPath)System\LocalAppContextSwitches.Common.cs" Link="Common\System\LocalAppContextSwitches.Common.cs" />
<Compile Include="$(CommonPath)Interop\Linux\OpenLdap\Interop.Ldap.cs" Link="Common\Interop\Linux\OpenLdap\Interop.Ldap.cs" />
<Compile Include="$(CommonPath)Interop\Linux\OpenLdap\Interop.Ber.cs" Link="Common\Interop\Linux\OpenLdap\Interop.Ber.cs" />
<Compile Include="$(CommonPath)Interop\Linux\OpenSsl\Interop.OpenSsl.cs" Link="Common\Interop\Linux\OpenSsl\Interop.OpenSsl.cs" />
</ItemGroup>
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new OpenSSL interop file is added to the linux or osx compile ItemGroup, but it P/Invokes Linux .so names. That means setting VerifyServerCertificate on macOS will likely throw DllNotFoundException. If the intent is Linux-only support, restrict inclusion to Linux; otherwise add an OS X-specific interop (or a shared shim-based approach) that resolves the correct library names.

Copilot uses AI. Check for mistakes.
Comment on lines +19 to +25
private void InitializeServerCertificateDelegate()
{
_verifyCallbackInvoked = 0;
_verifyCallbackResult = 0;
_serverCertificateRoutine = new LDAP_TLS_CONNECT_CB(SetOpenSslCallback);
_openSslVerifyRoutine ??= new Interop.OpenSsl.VerifyCallback(ProcessServerCertificate);
}
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_verifyCallbackInvoked/_verifyCallbackResult are only initialized in the constructor. If the same LdapConnection performs more than one TLS handshake over its lifetime (reconnect, StartTLS again, etc.), the callback result from the first handshake will be reused and the user delegate won’t run again. Consider resetting this per-handshake (e.g., when SetOpenSslCallback is invoked) rather than per LdapSessionOptions instance.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.DirectoryServices community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants