Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails mysql2: how to verify mysql server's SSL certificate?

I'm trying to connect remotely to a mysql db over SSL, with the server's certificate verified to match the DNS domain used to connect to the server.

Using the command-line mysql tool, I can make such a connection using mysql --ssl-ca=/path/to/cacert.pem --ssl-verify-server-cert.

Using rails mysql2, I set sslca:¹, which causes a not-fully-verified SSL connection like mysql --ssl-ca= does. How do I do the equivalent of --ssl-verify-server-cert so that the connection fails if the server cert's domain is wrong?

I've tried adding the following which had no effect on this issue: flags: SSL_VERIFY_SERVER_CERT, flags: CLIENT_SSL_VERIFY_SERVER_CERT, flags: 1073741824, and secure_auth: true.

¹ either sslca: /path/to/cacert.pem in config/database.yml, or ?sslca=/path/to/cacert.pem in a mysql2:// URL

like image 319
idupree Avatar asked Sep 16 '25 06:09

idupree


2 Answers

With mysql2>=0.4.0, you can set sslverify: true and sslca: path/to/cert_chain.pem in your adapter configs to make the client verify the server identity.

like image 105
pkoch Avatar answered Sep 17 '25 23:09

pkoch


This is not one of the default connection flags in the Mysql2 gem, but the constant is available and can be bitwise OR-ed into the connection flags field before making a connection.

You can set the global default like this:

Mysql2::Client::default_query_options[:connect_flags] |=
    Mysql2::Client::SSL_VERIFY_SERVER_CERT

Or set the flags per connection:

client = Mysql2::Client.new(
    :connect_flags => (Mysql2::Client::default_query_options[:connect_flags]
                     | Mysql2::Client::SSL_VERIFY_SERVER_CERT)
    )

Hope that helps!

like image 41
sodabrew Avatar answered Sep 17 '25 23:09

sodabrew