<?php
<?php
('error_reporting', E_ALL);
('display_errors', '1');
(E_ALL|E_STRICT);
(ASSERT_ACTIVE, true);
(ASSERT_WARNING, true);
(ASSERT_BAIL, true);
$sMySqlHost = 'mysqlserver'; //TODO
$iMySqlPort = 3306;
$sMySqlUser = 'user'; //TODO
$sMySqlPassword = 'password'; //TODO
$iMySqlFlag = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
$sTlsKey = '/var/mysql/client-key.pem'; //TODO fix right value, null if not used
$sTlsCert = '/var/mysql/client-cert.pem'; //TODO fix right value, null if not used
$sTlsCa = '/var/mysql/ca.pem'; //TODO fix right value, null if not used
(($sTlsKey), 'Can\'t open SSL Key file');
(($sTlsCert), 'Can\'t open SSL Cert file');
(($sTlsCa), 'Can\'t open SSL CA file');
echo "Trying to connect using :\n host=$sMySqlHost, user=$sMySqlUser,
port=$iMySqlPort\n";
echo "TLS options :\n key=$sTlsKey\n cert=$sTlsCert\n ca=$sTlsCa\n";
$oMysqli = new mysqli();
$oMysqli->init();
$oMysqli->ssl_set($sTlsKey, $sTlsCert, $sTlsCa, NULL, NULL);
$oMysqli->real_connect($sMySqlHost, $sMySqlUser, $sMySqlPassword, null,
$iMySqlPort, NULL, $iMySqlFlag);
if ($oMysqli->connect_errno)
{
('Connect error (' . () . '): ' . () . "\n");
} else {
if (!IsOpenedDbConnectionUsingTls($oMysqli)) {
$oMysqli->close();
('The connection can be opened but is not TLS encrypted !');
}
echo "Successfully connected using TLS !\n";
$sTlsCipherValue = GetMySqlVarValue($oMysqli, 'ssl_cipher');
$sTlsVersionValue = GetMySqlVarValue($oMysqli, 'ssl_version');
echo "TLS cipher=$sTlsCipherValue\n";
echo "TLS version=$sTlsVersionValue\n";
$oMysqli->close();
}
/**
* <p>A DB connection can be opened transparently (no errors thrown) without being
encrypted, whereas the TLS
* parameters were used.<br>
* This method can be called to ensure that the DB connection really uses TLS.
*
* <p>We're using this object connection : {@link self::$m_oMysqli}
*
* @param \mysqli $oMysqli
*
* @return boolean true if the connection was really established using TLS
* @throws \MySQLException
*
* @uses IsMySqlVarNonEmpty
*/
function IsOpenedDbConnectionUsingTls($oMysqli)
{
$bNonEmptySslVersionVar = IsMySqlVarNonEmpty($oMysqli, 'ssl_version');
$bNonEmptySslCipherVar = IsMySqlVarNonEmpty($oMysqli, 'ssl_cipher');
return ($bNonEmptySslVersionVar && $bNonEmptySslCipherVar);
}
/**
* @param \mysqli $oMysqli
* @param string $sVarName
*
* @return bool
* @throws \MySQLException
*
* @uses GetMySqlVarValue
*/
function IsMySqlVarNonEmpty($oMysqli, $sVarName)
{
$sResult = GetMySqlVarValue($oMysqli, $sVarName);
return (!($sResult));
}
/**
* @param \mysqli $oMysqli
* @param string $sVarName
*
* @return string
* @throws \MySQLException
*
* @uses 'SHOW STATUS' queries
*/
function GetMySqlVarValue($oMysqli, $sVarName)
{
$oResults = $oMysqli->query("SHOW SESSION STATUS LIKE '$sVarName'", 1);
if ($oResults === false) {
return false;
}
$aResults = $oResults->fetch_array(MYSQLI_NUM);
$sResult = $aResults[1];
return $sResult;
}