Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6378575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:01:33+00:00 2026-05-25T02:01:33+00:00

I am getting access violation exceptions when running the code below when the CertFreeCertificateContext

  • 0

I am getting access violation exceptions when running the code below when the CertFreeCertificateContext method is invoked.

I imagine it is because of the way the pServerCert argument is being Mashalled on the LdapServerCertDelegate but have been unable to find a solution.

using System;
using System.Runtime.InteropServices;

namespace ldaptest
{
    class Program
    {
        static void Main(string[] args)
        {
            new LdapAuthenticationProvider().AuthenticateUser("a.qas", "a", "administrator", "test123");
        }
    }

    public class LdapAuthenticationProvider
    {
        public void AuthenticateUser(string server, string domain, string username, string password)
        {
            IntPtr ld = ldap_sslinit(server, LDAP_SSL_PORT, 1);
            if (IntPtr.Zero == ld) throw new Exception("ldap_sslinit");

            var version = new IntPtr(LDAP_VERSION3);
            var ret = ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, version);
            if (ret != LDAP_SUCCESS) throw new Exception(string.Format("LDAP_OPT_PROTOCOL_VERSION 0x{0:X}", ret));

            var ldapOn = new IntPtr(LDAP_OPT_ON);
            ret = ldap_set_option(ld, LDAP_OPT_SSL, ldapOn);
            if (ret != LDAP_SUCCESS) throw new Exception(string.Format("LDAP_OPT_SSL 0x{0:X}", ret));

            // note the necessity to convert the delegate to a function pointer
            var callback = new LdapServerCertDelegate(AcceptAnySslCertificate);
            IntPtr pFn = Marshal.GetFunctionPointerForDelegate(callback);
            ret = ldap_set_option(ld, LDAP_OPT_SERVER_CERTIFICATE, pFn);
            if (ret != LDAP_SUCCESS) throw new Exception(string.Format("LDAP_OPT_SERVER_CERTIFICATE 0x{0:X}", ret));

            var tv = new l_timeval();
            ret = ldap_connect(ld, ref tv);
            if (ret != LDAP_SUCCESS) throw new Exception(string.Format("ldap_connect 0x{0:X}", ret));

            string login = string.Format(@"{0}\{1}", domain, username);
            ret = ldap_bind_s(ld, login, password, LDAP_AUTH_SIMPLE); // triggers the callback
            if (ret != LDAP_SUCCESS) throw new Exception(string.Format("ldap_bind_s 0x{0:X}", ret));

            ldap_unbind_s(ld);
            Console.WriteLine("Success");
            Console.Read();
        }

        private delegate bool LdapServerCertDelegate(IntPtr connection, IntPtr pServerCert);

        private bool AcceptAnySslCertificate(IntPtr connection, IntPtr pServerCert)
        {
            CertFreeCertificateContext(pServerCert); // << System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
            return true;
        }

        #region crypt32.dll functions

        [DllImport("crypt32.dll", CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CertFreeCertificateContext(IntPtr pCertContext);

        #endregion

        #region Winldap.h definitions

        private const int LDAP_PORT = 389;
        private const uint LDAP_SSL_PORT = 636;
        private const int LDAP_VERSION3 = 3;
        private const int LDAP_OPT_PROTOCOL_VERSION = 17;
        private const int LDAP_OPT_SSL = 10;
        private const int LDAP_OPT_ON = 1;
        private const int LDAP_AUTH_SIMPLE = 128;
        private const int LDAP_OPT_SERVER_CERTIFICATE = 129;
        private const uint LDAP_SUCCESS = 0;

        [StructLayoutAttribute(LayoutKind.Sequential)]
        private struct l_timeval
        {
            private int tv_sec;
            private int tv_usec;
        }

        #endregion

        #region wldap32.dll functions

        /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ldap/ldap/ldap_sslinit.asp?frame=true
        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_sslinitW",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern IntPtr ldap_sslinit(string hostName, uint portNumber, int secure);

        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern uint ldap_set_option([In] IntPtr ldapHandle, int option, IntPtr invalue);

        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_unbind_s",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern uint ldap_unbind_s([In] IntPtr ldapHandle);

        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_connect",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern uint ldap_connect([In] IntPtr ld, [In] ref l_timeval timeout);

        [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW",
            SetLastError = true, CharSet = CharSet.Unicode)]
        private static extern uint ldap_bind_s([In] IntPtr ld, string dn, string cred, uint method);

        #endregion
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:01:34+00:00Added an answer on May 25, 2026 at 2:01 am

    best bet turned out to be avoiding PInvoke and using C++/CLI.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm getting an Access Violation in DBEXPSDA40.DLL (Dev Art MS SQL Server dbexpress driver)
I'm running into a scenario where at random times I am getting Access Denied
I am getting an 'Access to the path is denied error message when running
I'm getting a NoMethodError when trying to access a method defined in one of
I am getting an error: Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You
Im getting the following Access violation at address 00404340 in module 'test.exe'. Read of
I'm getting a weird access violation at the end of my main whose cause
Hi I am getting an access violation error..... What might be the problem in
I am getting Access violation error from the debugger, but I really have no
I'm having trouble getting access to my WPF UserControl DependencyProperty values through the UI

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.