3

I need to communicate with PostgreSQL database from my Qt application, but the server uses "cert" authentication method, so I need to pass my certificates to the server.

The only solution I see for now is to obtain PGconn* like this:

QSqlDatabase db;
//.....
PGconn* conn = (PGconn*)db.driver()->handle()->data();

and do some work with it. Or even reject QSqlDatabase and use libpq directly.

Is there any other way to do this without using libpq from my code? For example, something like this:

//hypothetic QSqlDatabase methods:
QSqlDatabase db;
//.....
db.SetSslCert("/path/to/my/cert.crt");
db.SetSslKey("/path/to/my/cert.key");
//.....
1
  • 1
    QSqlDatabase is pretty limited - I wouldn't be surprised if there's no way to do this directly. Commented Nov 24, 2014 at 12:20

1 Answer 1

3

I need to pass my certificates to the server.

There's no function in Qt for that because there's no equivalent function in libpq for that either. It happens automatically, as described in Client Certificates inside SSL support from libpq documentation

Excerpt:

If the server requests a trusted client certificate, libpq will send the certificate stored in file ~/.postgresql/postgresql.crt in the user's home directory. The certificate must be signed by one of the certificate authorities (CA) trusted by the server. A matching private key file ~/.postgresql/postgresql.key must also be present

(in Windows, ~/.postgresql is going to be %APPDATA%\postgresql)

The same will happen for a Qt application since the Qt's QPSQL driver is built on top of libpq. The fact that the connection uses SSL and certificates is essentially transparent even for the driver itself.

EDIT: if ~/.posgresql is not convenient as when they are multiple certificates, alternatives exist:

The location of the certificate and key files can be overridden by the connection parameters sslcert and sslkey or the environment variables PGSSLCERT and PGSSLKEY

The connection parameters are set through QSqlDatabase::setConnectOptions. Despite its doc mentioning only an handful of postgresql-specific parameters, it actually will accept any parameter, so anything supported by libpq will work.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works. But what if I need to connect to the database under different roles, each has it's own *.crt and *.key file? Is there any solution except replacing files in ~/.postgresql/ before each connection?
@Sergey: this can be overwritten through environment variables or connection parameters, see my edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.