question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to connect via client certificate?

See original GitHub issue

I have postgresql cluster from https://cloud.yandex.ru. For connection via psql util, firstly I should download certificate from yandex:

mkdir ~/.postgresql && \
wget "https://storage.yandexcloud.net/cloud-certs/CA.pem" -O ~/.postgresql/root.crt && \
chmod 0600 ~/.postgresql/root.crt

And then I should use the following command:

psql "host=xxx.mdb.yandexcloud.net \
      port=6432 \
      sslmode=verify-full \
      dbname=MY_DATABASE \
      user=MY_USERNAME \
      target_session_attrs=read-write"

I try to connect via npgsql with the following connection string:

Host=rc1a-xxx.mdb.yandexcloud.net;Port=6432;SSL Mode=Require;Trust Server Certificate=true;Database=MY_DATABASE;Username=MY_USERNAME

and it fails with the following error:

info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.2.3-servicing-35854 initialized 'ApplicationContext' using provider 'Npgsql.EntityFrameworkCore.PostgreSQL' with options: None
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (00000005, 6): No such device or address
   at System.Net.Dns.InternalGetHostByName(String hostName)
   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
   at Npgsql.NpgsqlConnector.Connect(NpgsqlTimeout timeout) in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 663
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 555
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 414
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 273
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.NpgsqlConnection.Open() in C:\projects\npgsql\src\Npgsql\NpgsqlConnection.cs:line 153
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists() in C:\projects\npgsql-entityframeworkcore-postgresql\src\EFCore.PG\Storage\Internal\NpgsqlDatabaseCreator.cs:line 190
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No such device or address

My dotnet info:

dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   2.2.105
 Commit:    7cecb35b92

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  18.04
 OS Platform: Linux
 RID:         ubuntu.18.04-x64
 Base Path:   /usr/share/dotnet/sdk/2.2.105/

Host (useful for support):
  Version: 2.2.3
  Commit:  6b8ad509b6

.NET Core SDKs installed:
  2.2.105 [/usr/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.2.3 [/usr/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.2.3 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.2.3 [/usr/share/dotnet/shared/Microsoft.NETCore.App]

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
rusrccommented, Aug 8, 2019

So I use the yandex cloud too. And was getting error too. Here you are my test connection looks like this.

First install the certificate on my VM mkdir -p ~/.postgresql &&
wget “https://storage.yandexcloud.net/cloud-certs/CA.pem” -O ~/.postgresql/root.crt &&
chmod 0600 ~/.postgresql/root.crt

Then the code example:

public async Task<ActionResult<bool>> CanConnect()
        {
            const string host = "rc4c-blablablablabla.mdb.yandexcloud.net";
            var connection =
                $"Host={host};Port=6432;SSLMode=Require;TrustServerCertificate=true;Database=YOUR_DB_NAME;Username=YOUR_DB_USERNAME;Password=*******";

            var optionsBuilder = new DbContextOptionsBuilder<DbAppContext>();
            optionsBuilder.UseNpgsql(connection, builder =>
            {
                builder.RemoteCertificateValidationCallback((s, c, ch, sslPolicyErrors) =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                    {
                        return true;
                    }
                    _logService.Error($@"Certificate error: {sslPolicyErrors}, 
                    Do not allow this client to communicate with unauthenticated servers");
                    return false;
                });

                builder.ProvideClientCertificatesCallback(clientCerts =>
                {
                    var clientCertPath = "/home/username/.postgresql/root.crt";
                    // To avoid permission ex run: "sudo chmod -R 777 /home/username/.postgresql/root.crt"
                    var cert = new X509Certificate2(clientCertPath);
                    clientCerts.Add(cert);
                });
            });

            using (var ctx = new DbAppContext(optionsBuilder.Options))
            {
                return await ctx.Database.CanConnectAsync();
            }
        }
1reaction
YohDeadfallcommented, Mar 14, 2019

Sorry, fixed the link. The issue is in the main repo.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Client Certificate Mapping Authentication ...
On the taskbar, click Start, and then click Control Panel. · In Control Panel, click Programs and Features, and then click Turn Windows...
Read more >
Configuring client certificates for server connections
Procedure · Click Window > Manage Connections to open the Host Connections view. · Click Add in the Credentials section and select Certificate...
Read more >
What Is Client Certificate Authentication?
Users can securely access a server or other remote device, such as a computer, by exchanging a Digital Certificate. This process is called ......
Read more >
Authentication using HTTPS client certificates
Configuring the Node.​​ For now, we sign client certificates with our own server key, so it will be the same as our server...
Read more >
Howto connect to MySQL using a client certificate
It's possible to use X509 certificates (self-signed or not) to connect to MySQL. With or without a password. This method is working with...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found