Skip to main content

SSLStream support added to Npgsql!

Yesterday I merged a pull request which adds support to .Net SSLStream in Npgsql.

When Npgsql development started, in 2002, there was no SSL support in .net 1.0 and 1.1. It was added later in .net 2.0 but the support to SSLStream was never added to Npgsql.

This all changed a few weeks ago when Dave G created a patch which adds support to .Net SSLStream in Npgsql. He also said that one of the motivations was the fact that the current SSL support was returning error when using client certificate authentication. (I'll post a tutorial about how to use client certificates later)

There is a very old feature request (like since 2005!) to somehow create a single Npgsql.dll which incorporates Mono.Security.dll assembly. This would easy the deployment of Npgsql and version control. This feature request generated a discussion about the removal of Mono.Security dependency and possible impact in current user code. 

In order to get the lowest impact by this change, instead of immediately remove the callbacks and break a lot of user code, I asked Dave to keep the callbacks and mark them obsolete. This way,  users will be warned about those callbacks instructed to use the SSLStream RemoteCertificateValidationCallback instead.

In order to use the new SSL code, you just need to add a callback to ValidateRemoteCertificateCallback.
It can be as simple as:

NpgsqlConnection conn = new NpgsqlConnection(CONNSTRING);
conn.ValidateRemoteCertificateCallback += (abc=> { return true; };


This callback simply returns true indicating you are accepting the server certificate. Obviously, returning true without doing any validation should be done for testing purposes only.

Please, give it a try and let me know if you have any problems. 

Comments

Unknown said…
Hi Francisco.

Please, tell me how to connect to PostgreSQL database with SSL encryption and client certificate. May be you have some example on VB.NET or C#.

I try to use the following code for Npgsql:

'=======================================================
Imports System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography
Imports Npgsql

Public Class Form1

Private WithEvents cnn As NpgsqlConnection

Private Sub cmdConnection_Click(sender As Object, e As EventArgs) Handles cmdConnection.Click
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf bypassAllCertificateStuff)
cnn = New NpgsqlConnection
cnn.ConnectionString = "Server=serveraddress.ru;Port=5432;Database=documents;Userid=ArchiveUser;Password=mypassword;SSL=true;SslMode=Require;"
cnn.Open()
'test connection only
cnn.Close()
MsgBox("OK")
End Sub

'callback for client's certificate
Private Sub cnn_ProvideClientCertificatesCallback(certificates As X509CertificateCollection) Handles cnn.ProvideClientCertificatesCallback
Dim cert As X509Certificate2 = New X509Certificate2("C:\Users\programmer\Documents" & "\client.pfx", "mypassword")
certificates.Add(cert)
End Sub

'callback for server's certificate
Friend Function bypassAllCertificateStuff(ByVal sender As Object, ByVal cert As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal [error] As System.Net.Security.SslPolicyErrors) As Boolean
'trust any certificate
Return True
End Function
End Class
'=======================================================

I have two certificates on client: "client.crt" and "client.key". This certificates can work properly with ODBC driver.
Then I make "client.pfx" from "client.crt" and "client.key" by this command:

openssl pkcs12 -inkey client.key -in client.crt -export -out client.pfx

VB.NET can load this pfx container and show information about this certificate and it's private key (HasPrivateKey property is True).

Also I can load this pfx to Windows store and get it back with private key from there. Npgsql also cannot work with this certificate from store.

I always recieve the error "28000 connection requires a valid client certificate". PostgreSQL writes log "SSL connection from (anonymous)".

CN in certificate is the same as Userid in connection string.

What is wrong?

Maxim Sitnikov.
Hi, Maxim!

Why are you using this line:
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf bypassAllCertificateStuff)

You should pass this callback to NpgsqlConnection. I think this may be your problem.

I don't know vb.net very well and I may be missing somethig, but I think that as long as you set the callback to NpgsqlConnection, you should get it working as this callbacks makes use of your client certificate.

I hope it helps.
conan said…
J'ai eu la chance de rattraper un peu le chef Gillespie. En fait, sa passion pour les montres a causé quelques ennuis sur le tournage du spectacle.rolex pas cher En répondant à son désir de porter ses Pelagos à l'antenne, Gillespie a déclaré: "J'ai littéralement dû mendier de récupérer ma montre des producteurs! Personne n'est censé pouvoir porter une montre parce que de nos jours,fausse montre la plupart des gens ont des montres numériques qui pourrait être utilisé pour obtenir des informations autres que le temps. Je devais leur prouver que ma montre était "démodée" et simplement dire l'heure. "

Popular posts from this blog

UUID datatype and COPY IN/OUT support added to cvs

Hi all! It was just added support to uuid datatype in cvs head. This type will be available in next Postgresql release 8.3. Thanks to David Bachmann for his patch! You can get more info about this patch in this mailing list post . Also was added support for copy in and copy out operations. Now, users can provide streams which can be copied directly to and from Postgresql tables! Thanks to Kalle Hallivuori for providing a patch! Thanks to Truviso for giving support to Kalle. More info about that including a demo and ready to use compiled Npgsql.dll versions can be found here . That's it! As soon as we get more features added, I will post info about them here. Stay tuned! :)

Using Entity Framework 6 with Npgsql 2.1.0

UPDATE (2014-05-19): Marek Beneš noticed a problem in the default connection factory config. It is fixed now. Thanks, Marek! UPDATE (2014-02-20): I created a new post explaining how to get Npgsql 2.1.0. Although this post is about EF 6, I'd like to talk about our current situation to support both EF 6 and EF4.x which explain why there are some subtle changes between EF 4.x and EF 6.x App.config settings.  Support for EF versions 4.x and 6.x Sometime after we started to work on Npgsql 2.1.0, we started to add code to support EF6 and decided to reorganize our Entity Framework support code. Shay created a pull request to organize this change and isolate the EF code out of core Npgsql code. The result was the creation of two separated assemblies: Npgsql.EntityFramework.dll for EF6 and above; Npgsql.EntityFrameworkLegacy.dll for EF4.x. Only when using Npgsql with EF6 you will need to reference Npgsql.EntityFramework.dll assembly. This is needed because the EF

Initial EF-6 support added to Npgsql

In my last post , I said there is a pull request by Pēteris Ņikiforovs to add support for EF-6 to Npgsql. Yesterday, I merged this pull request to the master branch of Npgsql . With this merge, Npgsql has officially initial support for EF-6! How to compile For now, in order to compile Npgsql to use EF-6, you have to open the solution file NpgsqlEF6.sln. Later,  as suggested by Pēteris Ņikiforovs , the idea is that we create a new configuration inside main project solution instead of maintain 2 separated projects. Another thing you will need to compile Npgsql is the latest release of EntityFramework assembly through NuGet: PM> Install-Package EntityFramework -Pre That's it! Now you will be able to play with Npgsql and EF-6. Check out my previous post about how to use Npgsql with EntityFramework. I'd like to thank Pēteris Ņikiforovs for his patch. And maxbundchen for his patch about Open/Close events needed for EF-6. Please, give it a try and let me know how it