Writing Clients That Include SSL SupportMySQL includes SSL support as of version 4.0, and you can use it to write your own programs that access the server over secure connections. To show how this is done, this section describes the process of modifying stmt_exec to produce a similar client named stmt_exec_ssl that outwardly is much the same but allows encrypted connections to be established. For stmt_exec_ssl to work properly, MySQL must have been built with SSL support, and the server must be started with the proper options that identify its certificate and key files. You'll also need certificate and key files on the client end. For more information, see "Setting Up Secure Connections," in Chapter 12, "MySQL and Security." The sampdb distribution contains a source file, stmt_exec_ssl.c, from which the client program stmt_exec_ssl can be built. The following procedure describes how stmt_exec_ssl.c is created, beginning with stmt_exec.c:
If you follow the preceding procedure, the usual load_defaults() and handle_options() routines will take care of parsing the SSL-related options and setting their values for you automatically. The only other thing you need to do is pass SSL option information to the client library before connecting to the server if the options indicate that the user wants an SSL connection. Do this by invoking mysql_ssl_set() after calling mysql_init() and before calling mysql_real_connect(). The sequence looks like this: /* initialize connection handler */ conn = mysql_init (NULL); if (conn == NULL) { print_error (NULL, "mysql_init() failed (probably out of memory)"); exit (1); } #ifdef HAVE_OPENSSL /* pass SSL information to client library */ if (opt_use_ssl) mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); #endif /* connect to server */ if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password, opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL) { print_error (conn, "mysql_real_connect() failed"); mysql_close (conn); exit (1); } This code doesn't test mysql_ssl_set() to see if it returns an error. Any problems with the information you supply to that function will result in an error when you call mysql_real_connect(). Compile stmt_exec_ssl.c to produce the stmt_exec_ssl program and then run it. Assuming that the mysql_real_connect() call succeeds, you can proceed to issue statements. If you invoke stmt_exec_ssl with the appropriate SSL options, communication with the server should occur over an encrypted connection. To determine whether that is so, issue the following statement: SHOW STATUS LIKE 'Ssl_cipher' The value of Ssl_cipher will be non-blank if an encryption cipher is in use. (To make this easier, the version of stmt_exec_ssl included in the sampdb distribution actually issues the statement for you and reports the result.) |