Merge pull request #768 from david-puglielli/azure-key-vault-support
Azure key vault support
This commit is contained in:
commit
e0f9afae2f
|
@ -40,17 +40,20 @@ const char Server[] = "Server";
|
|||
const char APP[] = "APP";
|
||||
const char ApplicationIntent[] = "ApplicationIntent";
|
||||
const char AttachDBFileName[] = "AttachDbFileName";
|
||||
const char ConnectionPooling[] = "ConnectionPooling";
|
||||
const char Authentication[] = "Authentication";
|
||||
const char Driver[] = "Driver";
|
||||
#ifdef _WIN32
|
||||
const char ColumnEncryption[] = "ColumnEncryption";
|
||||
const char ConnectionPooling[] = "ConnectionPooling";
|
||||
#ifdef _WIN32
|
||||
const char ConnectRetryCount[] = "ConnectRetryCount";
|
||||
const char ConnectRetryInterval[] = "ConnectRetryInterval";
|
||||
#endif // _WIN32
|
||||
const char Database[] = "Database";
|
||||
const char Driver[] = "Driver";
|
||||
const char Encrypt[] = "Encrypt";
|
||||
const char Failover_Partner[] = "Failover_Partner";
|
||||
const char KeyStoreAuthentication[] = "KeyStoreAuthentication";
|
||||
const char KeyStorePrincipalId[] = "KeyStorePrincipalId";
|
||||
const char KeyStoreSecret[] = "KeyStoreSecret";
|
||||
const char LoginTimeout[] = "LoginTimeout";
|
||||
const char MARS_Option[] = "MultipleActiveResultSets";
|
||||
const char MultiSubnetFailover[] = "MultiSubnetFailover";
|
||||
|
@ -231,7 +234,6 @@ const connection_option PDO_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
driver_set_func::func
|
||||
},
|
||||
#ifdef _WIN32
|
||||
{
|
||||
PDOConnOptionNames::ColumnEncryption,
|
||||
sizeof(PDOConnOptionNames::ColumnEncryption),
|
||||
|
@ -241,6 +243,7 @@ const connection_option PDO_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
column_encryption_set_func::func
|
||||
},
|
||||
#ifdef _WIN32
|
||||
{
|
||||
PDOConnOptionNames::ConnectRetryCount,
|
||||
sizeof( PDOConnOptionNames::ConnectRetryCount ),
|
||||
|
@ -287,6 +290,33 @@ const connection_option PDO_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
conn_str_append_func::func
|
||||
},
|
||||
{
|
||||
PDOConnOptionNames::KeyStoreAuthentication,
|
||||
sizeof( PDOConnOptionNames::KeyStoreAuthentication ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_AUTHENTICATION,
|
||||
ODBCConnOptions::KeyStoreAuthentication,
|
||||
sizeof( ODBCConnOptions::KeyStoreAuthentication ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
PDOConnOptionNames::KeyStorePrincipalId,
|
||||
sizeof( PDOConnOptionNames::KeyStorePrincipalId ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID,
|
||||
ODBCConnOptions::KeyStorePrincipalId,
|
||||
sizeof( ODBCConnOptions::KeyStorePrincipalId ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
PDOConnOptionNames::KeyStoreSecret,
|
||||
sizeof( PDOConnOptionNames::KeyStoreSecret ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_SECRET,
|
||||
ODBCConnOptions::KeyStoreSecret,
|
||||
sizeof( ODBCConnOptions::KeyStoreSecret ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
PDOConnOptionNames::LoginTimeout,
|
||||
sizeof( PDOConnOptionNames::LoginTimeout ),
|
||||
|
@ -362,7 +392,7 @@ const connection_option PDO_CONN_OPTS[] = {
|
|||
{
|
||||
PDOConnOptionNames::TransparentNetworkIPResolution,
|
||||
sizeof(PDOConnOptionNames::TransparentNetworkIPResolution),
|
||||
SQLSRV_CONN_OPTION_TRANSPARANT_NETWORK_IP_RESOLUTION,
|
||||
SQLSRV_CONN_OPTION_TRANSPARENT_NETWORK_IP_RESOLUTION,
|
||||
ODBCConnOptions::TransparentNetworkIPResolution,
|
||||
sizeof(ODBCConnOptions::TransparentNetworkIPResolution),
|
||||
CONN_ATTR_STRING,
|
||||
|
|
|
@ -409,6 +409,26 @@ pdo_error PDO_ERRORS[] = {
|
|||
SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED,
|
||||
{ IMSSP, (SQLCHAR*) "Error converting a double (value out of range) to an integer.", -84, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_INVALID_AKV_AUTHENTICATION_OPTION,
|
||||
{ IMSSP, (SQLCHAR*) "Invalid option for the KeyStoreAuthentication keyword. Only KeyVaultPassword or KeyVaultClientSecret is allowed.", -85, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_AUTH_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The authentication method for Azure Key Vault is missing. KeyStoreAuthentication must be set to KeyVaultPassword or KeyVaultClientSecret.", -86, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_NAME_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The username or client Id for Azure Key Vault is missing.", -87, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_SECRET_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The password or client secret for Azure Key Vault is missing.", -88, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_KEYSTORE_INVALID_VALUE,
|
||||
{ IMSSP, (SQLCHAR*) "Invalid value for loading Azure Key Vault.", -89, false}
|
||||
},
|
||||
{ UINT_MAX, {} }
|
||||
};
|
||||
|
||||
|
|
|
@ -45,6 +45,9 @@ const int DEFAULT_CONN_STR_LEN = 2048;
|
|||
// length of buffer used to retrieve information for client and server info buffers
|
||||
const int INFO_BUFFER_LEN = 256;
|
||||
|
||||
// length for name of keystore used in CEKeyStoreData
|
||||
const int MAX_CE_NAME_LEN = 260;
|
||||
|
||||
// processor architectures
|
||||
const char* PROCESSOR_ARCH[] = { "x86", "x64", "ia64" };
|
||||
|
||||
|
@ -71,6 +74,9 @@ const char* get_processor_arch( void );
|
|||
void get_server_version( _Inout_ sqlsrv_conn* conn, _Outptr_result_buffer_(len) char** server_version, _Out_ SQLSMALLINT& len TSRMLS_DC );
|
||||
connection_option const* get_connection_option( sqlsrv_conn* conn, _In_ const char* key, _In_ SQLULEN key_len TSRMLS_DC );
|
||||
void common_conn_str_append_func( _In_z_ const char* odbc_name, _In_reads_(val_len) const char* val, _Inout_ size_t val_len, _Inout_ std::string& conn_str TSRMLS_DC );
|
||||
void load_azure_key_vault( _Inout_ sqlsrv_conn* conn TSRMLS_DC );
|
||||
void configure_azure_key_vault( sqlsrv_conn* conn, BYTE config_attr, const DWORD config_value, size_t key_size);
|
||||
void configure_azure_key_vault( sqlsrv_conn* conn, BYTE config_attr, const char* config_value, size_t key_size);
|
||||
}
|
||||
|
||||
// core_sqlsrv_connect
|
||||
|
@ -245,6 +251,8 @@ sqlsrv_conn* core_sqlsrv_connect( _In_ sqlsrv_context& henv_cp, _In_ sqlsrv_cont
|
|||
throw core::CoreException();
|
||||
}
|
||||
|
||||
load_azure_key_vault( conn );
|
||||
|
||||
// determine the version of the server we're connected to. The server version is left in the
|
||||
// connection upon return.
|
||||
//
|
||||
|
@ -932,6 +940,85 @@ void determine_server_version( _Inout_ sqlsrv_conn* conn TSRMLS_DC )
|
|||
conn->server_version = version_major;
|
||||
}
|
||||
|
||||
void load_azure_key_vault(_Inout_ sqlsrv_conn* conn TSRMLS_DC)
|
||||
{
|
||||
// If column encryption is not enabled simply do nothing. Otherwise, check if Azure Key Vault
|
||||
// is required for encryption or decryption. Note, in order to load and configure Azure Key Vault,
|
||||
// all fields in conn->ce_option must be defined.
|
||||
if (!conn->ce_option.enabled || !conn->ce_option.akv_required)
|
||||
return;
|
||||
|
||||
CHECK_CUSTOM_ERROR(conn->ce_option.akv_mode == -1, conn, SQLSRV_ERROR_AKV_AUTH_MISSING) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
CHECK_CUSTOM_ERROR(conn->ce_option.akv_id == NULL, conn, SQLSRV_ERROR_AKV_NAME_MISSING) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
CHECK_CUSTOM_ERROR(conn->ce_option.akv_secret == NULL, conn, SQLSRV_ERROR_AKV_SECRET_MISSING) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
char *akv_id = Z_STRVAL_P(conn->ce_option.akv_id);
|
||||
char *akv_secret = Z_STRVAL_P(conn->ce_option.akv_secret);
|
||||
unsigned int id_len = static_cast<unsigned int>(Z_STRLEN_P(conn->ce_option.akv_id));
|
||||
unsigned int key_size = static_cast<unsigned int>(Z_STRLEN_P(conn->ce_option.akv_secret));
|
||||
|
||||
configure_azure_key_vault(conn, AKV_CONFIG_FLAGS, conn->ce_option.akv_mode, 0);
|
||||
configure_azure_key_vault(conn, AKV_CONFIG_PRINCIPALID, akv_id, id_len);
|
||||
configure_azure_key_vault(conn, AKV_CONFIG_AUTHSECRET, akv_secret, key_size);
|
||||
}
|
||||
|
||||
void configure_azure_key_vault(sqlsrv_conn* conn, BYTE config_attr, const DWORD config_value, size_t key_size)
|
||||
{
|
||||
BYTE akv_data[sizeof(CEKEYSTOREDATA) + sizeof(DWORD) + 1];
|
||||
CEKEYSTOREDATA *pData = reinterpret_cast<CEKEYSTOREDATA*>(akv_data);
|
||||
|
||||
char akv_name[] = "AZURE_KEY_VAULT";
|
||||
unsigned int name_len = 15;
|
||||
unsigned int wname_len = 0;
|
||||
sqlsrv_malloc_auto_ptr<SQLWCHAR> wakv_name;
|
||||
wakv_name = utf16_string_from_mbcs_string(SQLSRV_ENCODING_UTF8, akv_name, name_len, &wname_len);
|
||||
|
||||
CHECK_CUSTOM_ERROR(wakv_name == 0, conn, SQLSRV_ERROR_CONNECT_STRING_ENCODING_TRANSLATE) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
pData->name = (wchar_t *)wakv_name.get();
|
||||
|
||||
pData->data[0] = config_attr;
|
||||
pData->dataSize = sizeof(config_attr) + sizeof(config_value);
|
||||
*reinterpret_cast<DWORD*>(&pData->data[1]) = config_value;
|
||||
|
||||
core::SQLSetConnectAttr(conn, SQL_COPT_SS_CEKEYSTOREDATA, reinterpret_cast<SQLPOINTER>(pData), SQL_IS_POINTER);
|
||||
}
|
||||
|
||||
void configure_azure_key_vault(sqlsrv_conn* conn, BYTE config_attr, const char* config_value, size_t key_size)
|
||||
{
|
||||
BYTE akv_data[sizeof(CEKEYSTOREDATA) + MAX_CE_NAME_LEN];
|
||||
CEKEYSTOREDATA *pData = reinterpret_cast<CEKEYSTOREDATA*>(akv_data);
|
||||
|
||||
char akv_name[] = "AZURE_KEY_VAULT";
|
||||
unsigned int name_len = 15;
|
||||
unsigned int wname_len = 0;
|
||||
sqlsrv_malloc_auto_ptr<SQLWCHAR> wakv_name;
|
||||
wakv_name = utf16_string_from_mbcs_string(SQLSRV_ENCODING_UTF8, akv_name, name_len, &wname_len);
|
||||
|
||||
CHECK_CUSTOM_ERROR(wakv_name == 0, conn, SQLSRV_ERROR_CONNECT_STRING_ENCODING_TRANSLATE) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
pData->name = (wchar_t *)wakv_name.get();
|
||||
|
||||
pData->data[0] = config_attr;
|
||||
pData->dataSize = 1 + key_size;
|
||||
|
||||
memcpy_s(pData->data + 1, key_size * sizeof(char), config_value, key_size);
|
||||
|
||||
core::SQLSetConnectAttr(conn, SQL_COPT_SS_CEKEYSTOREDATA, reinterpret_cast<SQLPOINTER>(pData), SQL_IS_POINTER);
|
||||
}
|
||||
|
||||
void common_conn_str_append_func( _In_z_ const char* odbc_name, _In_reads_(val_len) const char* val, _Inout_ size_t val_len, _Inout_ std::string& conn_str TSRMLS_DC )
|
||||
{
|
||||
// wrap a connection option in a quote. It is presumed that any character that need to be escaped will
|
||||
|
@ -1005,6 +1092,52 @@ void column_encryption_set_func::func( _In_ connection_option const* option, _In
|
|||
conn_str += ";";
|
||||
}
|
||||
|
||||
void ce_akv_str_set_func::func(_In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC)
|
||||
{
|
||||
SQLSRV_ASSERT(Z_TYPE_P(value) == IS_STRING, "Azure Key Vault keywords accept only strings.");
|
||||
|
||||
size_t value_len = Z_STRLEN_P(value);
|
||||
|
||||
CHECK_CUSTOM_ERROR(value_len <= 0, conn, SQLSRV_ERROR_KEYSTORE_INVALID_VALUE) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
|
||||
switch (option->conn_option_key)
|
||||
{
|
||||
case SQLSRV_CONN_OPTION_KEYSTORE_AUTHENTICATION:
|
||||
{
|
||||
char *value_str = Z_STRVAL_P(value);
|
||||
if (!stricmp(value_str, "KeyVaultPassword")) {
|
||||
conn->ce_option.akv_mode = AKVCFG_AUTHMODE_PASSWORD;
|
||||
} else if (!stricmp(value_str, "KeyVaultClientSecret")) {
|
||||
conn->ce_option.akv_mode = AKVCFG_AUTHMODE_CLIENTKEY;
|
||||
} else {
|
||||
CHECK_CUSTOM_ERROR(1, conn, SQLSRV_ERROR_INVALID_AKV_AUTHENTICATION_OPTION) {
|
||||
throw core::CoreException();
|
||||
}
|
||||
}
|
||||
|
||||
conn->ce_option.akv_required = true;
|
||||
break;
|
||||
}
|
||||
case SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID:
|
||||
{
|
||||
conn->ce_option.akv_id = value;
|
||||
conn->ce_option.akv_required = true;
|
||||
break;
|
||||
}
|
||||
case SQLSRV_CONN_OPTION_KEYSTORE_SECRET:
|
||||
{
|
||||
conn->ce_option.akv_secret = value;
|
||||
conn->ce_option.akv_required = true;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
SQLSRV_ASSERT(false, "ce_akv_str_set_func: Invalid AKV option!");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// helper function to evaluate whether a string value is true or false.
|
||||
// Values = ("true" or "1") are treated as true values. Everything else is treated as false.
|
||||
// Returns 1 for true and 0 for false.
|
||||
|
|
|
@ -1055,8 +1055,12 @@ struct stmt_option;
|
|||
// This holds the various details of column encryption.
|
||||
struct col_encryption_option {
|
||||
bool enabled; // column encryption enabled, false by default
|
||||
SQLINTEGER akv_mode;
|
||||
zval_auto_ptr akv_id;
|
||||
zval_auto_ptr akv_secret;
|
||||
bool akv_required;
|
||||
|
||||
col_encryption_option() : enabled( false )
|
||||
col_encryption_option() : enabled( false ), akv_mode(-1), akv_required( false )
|
||||
{
|
||||
}
|
||||
};
|
||||
|
@ -1106,14 +1110,17 @@ const char Authentication[] = "Authentication";
|
|||
const char Driver[] = "Driver";
|
||||
const char CharacterSet[] = "CharacterSet";
|
||||
const char ConnectionPooling[] = "ConnectionPooling";
|
||||
#ifdef _WIN32
|
||||
const char ColumnEncryption[] = "ColumnEncryption";
|
||||
#ifdef _WIN32
|
||||
const char ConnectRetryCount[] = "ConnectRetryCount";
|
||||
const char ConnectRetryInterval[] = "ConnectRetryInterval";
|
||||
#endif // _WIN32
|
||||
const char Database[] = "Database";
|
||||
const char Encrypt[] = "Encrypt";
|
||||
const char Failover_Partner[] = "Failover_Partner";
|
||||
const char KeyStoreAuthentication[] = "KeyStoreAuthentication";
|
||||
const char KeyStorePrincipalId[] = "KeyStorePrincipalId";
|
||||
const char KeyStoreSecret[] = "KeyStoreSecret";
|
||||
const char LoginTimeout[] = "LoginTimeout";
|
||||
const char MARS_ODBC[] = "MARS_Connection";
|
||||
const char MultiSubnetFailover[] = "MultiSubnetFailover";
|
||||
|
@ -1156,7 +1163,10 @@ enum SQLSRV_CONN_OPTIONS {
|
|||
SQLSRV_CONN_OPTION_CEKEYSTORE_PROVIDER,
|
||||
SQLSRV_CONN_OPTION_CEKEYSTORE_NAME,
|
||||
SQLSRV_CONN_OPTION_CEKEYSTORE_ENCRYPT_KEY,
|
||||
SQLSRV_CONN_OPTION_TRANSPARANT_NETWORK_IP_RESOLUTION,
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_AUTHENTICATION,
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID,
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_SECRET,
|
||||
SQLSRV_CONN_OPTION_TRANSPARENT_NETWORK_IP_RESOLUTION,
|
||||
#ifdef _WIN32
|
||||
SQLSRV_CONN_OPTION_CONN_RETRY_COUNT,
|
||||
SQLSRV_CONN_OPTION_CONN_RETRY_INTERVAL,
|
||||
|
@ -1219,6 +1229,10 @@ struct ce_ksp_provider_set_func {
|
|||
static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC );
|
||||
};
|
||||
|
||||
struct ce_akv_str_set_func {
|
||||
static void func( _In_ connection_option const* option, _In_ zval* value, _Inout_ sqlsrv_conn* conn, _Inout_ std::string& conn_str TSRMLS_DC );
|
||||
};
|
||||
|
||||
|
||||
// factory to create a connection (since they are subclassed to instantiate statements)
|
||||
typedef sqlsrv_conn* (*driver_conn_factory)( _In_ SQLHANDLE h, _In_ error_callback e, _In_ void* drv TSRMLS_DC );
|
||||
|
@ -1701,6 +1715,11 @@ enum SQLSRV_ERROR_CODES {
|
|||
SQLSRV_ERROR_BUFFER_LIMIT_EXCEEDED,
|
||||
SQLSRV_ERROR_INVALID_BUFFER_LIMIT,
|
||||
SQLSRV_ERROR_OUTPUT_PARAM_TYPES_NOT_SUPPORTED,
|
||||
SQLSRV_ERROR_INVALID_AKV_AUTHENTICATION_OPTION,
|
||||
SQLSRV_ERROR_AKV_AUTH_MISSING,
|
||||
SQLSRV_ERROR_AKV_NAME_MISSING,
|
||||
SQLSRV_ERROR_AKV_SECRET_MISSING,
|
||||
SQLSRV_ERROR_KEYSTORE_INVALID_VALUE,
|
||||
SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED,
|
||||
|
||||
// Driver specific error codes starts from here.
|
||||
|
|
|
@ -184,19 +184,22 @@ namespace SSConnOptionNames {
|
|||
const char APP[] = "APP";
|
||||
const char ApplicationIntent[] = "ApplicationIntent";
|
||||
const char AttachDBFileName[] = "AttachDbFileName";
|
||||
const char CharacterSet[] = "CharacterSet";
|
||||
const char Authentication[] = "Authentication";
|
||||
const char ConnectionPooling[] = "ConnectionPooling";
|
||||
const char Driver[] = "Driver";
|
||||
#ifdef _WIN32
|
||||
const char CharacterSet[] = "CharacterSet";
|
||||
const char ColumnEncryption[] = "ColumnEncryption";
|
||||
const char ConnectionPooling[] = "ConnectionPooling";
|
||||
#ifdef _WIN32
|
||||
const char ConnectRetryCount[] = "ConnectRetryCount";
|
||||
const char ConnectRetryInterval[] = "ConnectRetryInterval";
|
||||
#endif // _WIN32
|
||||
const char Database[] = "Database";
|
||||
const char DateAsString[] = "ReturnDatesAsStrings";
|
||||
const char Driver[] = "Driver";
|
||||
const char Encrypt[] = "Encrypt";
|
||||
const char Failover_Partner[] = "Failover_Partner";
|
||||
const char KeyStoreAuthentication[] = "KeyStoreAuthentication";
|
||||
const char KeyStorePrincipalId[] = "KeyStorePrincipalId";
|
||||
const char KeyStoreSecret[] = "KeyStoreSecret";
|
||||
const char LoginTimeout[] = "LoginTimeout";
|
||||
const char MARS_Option[] = "MultipleActiveResultSets";
|
||||
const char MultiSubnetFailover[] = "MultiSubnetFailover";
|
||||
|
@ -312,7 +315,6 @@ const connection_option SS_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
driver_set_func::func
|
||||
},
|
||||
#ifdef _WIN32
|
||||
{
|
||||
SSConnOptionNames::ColumnEncryption,
|
||||
sizeof(SSConnOptionNames::ColumnEncryption),
|
||||
|
@ -322,6 +324,7 @@ const connection_option SS_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
column_encryption_set_func::func
|
||||
},
|
||||
#ifdef _WIN32
|
||||
{
|
||||
SSConnOptionNames::ConnectRetryCount,
|
||||
sizeof( SSConnOptionNames::ConnectRetryCount ),
|
||||
|
@ -368,6 +371,33 @@ const connection_option SS_CONN_OPTS[] = {
|
|||
CONN_ATTR_STRING,
|
||||
conn_str_append_func::func
|
||||
},
|
||||
{
|
||||
SSConnOptionNames::KeyStoreAuthentication,
|
||||
sizeof( SSConnOptionNames::KeyStoreAuthentication ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_AUTHENTICATION,
|
||||
ODBCConnOptions::KeyStoreAuthentication,
|
||||
sizeof( ODBCConnOptions::KeyStoreAuthentication ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
SSConnOptionNames::KeyStorePrincipalId,
|
||||
sizeof( SSConnOptionNames::KeyStorePrincipalId ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_PRINCIPAL_ID,
|
||||
ODBCConnOptions::KeyStorePrincipalId,
|
||||
sizeof( ODBCConnOptions::KeyStorePrincipalId ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
SSConnOptionNames::KeyStoreSecret,
|
||||
sizeof( SSConnOptionNames::KeyStoreSecret ),
|
||||
SQLSRV_CONN_OPTION_KEYSTORE_SECRET,
|
||||
ODBCConnOptions::KeyStoreSecret,
|
||||
sizeof( ODBCConnOptions::KeyStoreSecret ),
|
||||
CONN_ATTR_STRING,
|
||||
ce_akv_str_set_func::func
|
||||
},
|
||||
{
|
||||
SSConnOptionNames::LoginTimeout,
|
||||
sizeof( SSConnOptionNames::LoginTimeout ),
|
||||
|
@ -443,7 +473,7 @@ const connection_option SS_CONN_OPTS[] = {
|
|||
{
|
||||
SSConnOptionNames::TransparentNetworkIPResolution,
|
||||
sizeof(SSConnOptionNames::TransparentNetworkIPResolution),
|
||||
SQLSRV_CONN_OPTION_TRANSPARANT_NETWORK_IP_RESOLUTION,
|
||||
SQLSRV_CONN_OPTION_TRANSPARENT_NETWORK_IP_RESOLUTION,
|
||||
ODBCConnOptions::TransparentNetworkIPResolution,
|
||||
sizeof(ODBCConnOptions::TransparentNetworkIPResolution),
|
||||
CONN_ATTR_STRING,
|
||||
|
@ -525,7 +555,7 @@ PHP_FUNCTION ( sqlsrv_connect )
|
|||
core::sqlsrv_zend_hash_init( *g_ss_henv_cp, ss_conn_options_ht, 10 /* # of buckets */,
|
||||
ZVAL_PTR_DTOR, 0 /*persistent*/ TSRMLS_CC );
|
||||
|
||||
// Either of g_ss_henv_cp or g_ss_henv_ncp can be used to propogate the error.
|
||||
// Either of g_ss_henv_cp or g_ss_henv_ncp can be used to propagate the error.
|
||||
::validate_conn_options( *g_ss_henv_cp, options_z, &uid, &pwd, ss_conn_options_ht TSRMLS_CC );
|
||||
|
||||
// call the core connect function
|
||||
|
|
|
@ -400,6 +400,26 @@ ss_error SS_ERRORS[] = {
|
|||
SQLSRV_ERROR_DOUBLE_CONVERSION_FAILED,
|
||||
{ IMSSP, (SQLCHAR*)"Error converting a double (value out of range) to an integer.", -109, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_INVALID_AKV_AUTHENTICATION_OPTION,
|
||||
{ IMSSP, (SQLCHAR*) "Invalid option for the KeyStoreAuthentication keyword. Only KeyVaultPassword or KeyVaultClientSecret is allowed.", -110, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_AUTH_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The authentication method for Azure Key Vault is missing. KeyStoreAuthentication must be set to KeyVaultPassword or KeyVaultClientSecret.", -111, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_NAME_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The username or client Id for Azure Key Vault is missing.", -112, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_AKV_SECRET_MISSING,
|
||||
{ IMSSP, (SQLCHAR*) "The password or client secret for Azure Key Vault is missing.", -113, false }
|
||||
},
|
||||
{
|
||||
SQLSRV_ERROR_KEYSTORE_INVALID_VALUE,
|
||||
{ IMSSP, (SQLCHAR*) "Invalid value for loading Azure Key Vault.", -114, false}
|
||||
},
|
||||
|
||||
// terminate the list of errors/warnings
|
||||
{ UINT_MAX, {} }
|
||||
|
|
|
@ -92,6 +92,13 @@ function getDSN($sqlsrvserver, $database, $keywords = '', $disableCE = false)
|
|||
if ($keystore != "none" && !$disableCE) {
|
||||
$dsn .= "ColumnEncryption=Enabled;";
|
||||
}
|
||||
if ($keystore == "akv" && !$disableCE) {
|
||||
if ($AKVKeyStoreAuthentication == "KeyVaultPassword") {
|
||||
$dsn .= "KeyStoreAuthentication=$AKVKeyStoreAuthentication;KeyStorePrincipalId=$AKVPrincipalName;KeyStoreSecret=$AKVPassword;";
|
||||
} else if ($AKVKeyStoreAuthentication == "KeyVaultClientSecret") {
|
||||
$dsn .= "KeyStoreAuthentication=$AKVKeyStoreAuthentication;KeyStorePrincipalId=$AKVClientID;KeyStoreSecret=$AKVSecret;";
|
||||
}
|
||||
}
|
||||
if ($keystore == "ksp" && !$disableCE) {
|
||||
$ksp_path = getKSPPath();
|
||||
$ksp_name = KSP_NAME;
|
||||
|
|
|
@ -44,4 +44,11 @@ $traceEnabled = false;
|
|||
$keystore = "none"; // key store provider, acceptable values are none, win, ksp, akv
|
||||
$dataEncrypted = false; // whether data is to be encrypted
|
||||
|
||||
// for Azure Key Vault
|
||||
$AKVKeyStoreAuthentication = 'TARGET_AKV_AUTH'; // can be KeyVaultPassword or KeyVaultClientSecret
|
||||
$AKVPrincipalName = 'TARGET_AKV_PRINCIPAL_NAME'; // for use with KeyVaultPassword
|
||||
$AKVPassword = 'TARGET_AKV_PASSWORD'; // for use with KeyVaultPassword
|
||||
$AKVClientID = 'TARGET_AKV_CLIENT_ID'; // for use with KeyVaultClientSecret
|
||||
$AKVSecret = 'TARGET_AKV_CLIENT_SECRET'; // for use with KeyVaultClientSecret
|
||||
|
||||
?>
|
196
test/functional/pdo_sqlsrv/pdo_ae_azure_key_vault_keywords.phpt
Normal file
196
test/functional/pdo_sqlsrv/pdo_ae_azure_key_vault_keywords.phpt
Normal file
|
@ -0,0 +1,196 @@
|
|||
--TEST--
|
||||
Test connection keywords for Azure Key Vault for Always Encrypted.
|
||||
--SKIPIF--
|
||||
<?php require('skipif.inc'); ?>
|
||||
--FILE--
|
||||
<?php
|
||||
// Skip for 32-bit PHP, as bug causes this test to fail when inserting a bigint
|
||||
if (PHP_INT_SIZE == 4) {
|
||||
echo "Done.\n";
|
||||
exit();
|
||||
}
|
||||
|
||||
require_once("MsCommon_mid-refactor.inc");
|
||||
require_once("MsSetup.inc");
|
||||
require_once('values.php');
|
||||
|
||||
// We will test the direct product (set of all possible combinations) of the following
|
||||
$columnEncryption = ['enabled', 'disabled', 'notvalid', ''];
|
||||
$keyStoreAuthentication = ['KeyVaultPassword', 'KeyVaultClientSecret', 'KeyVaultNothing', ''];
|
||||
$keyStorePrincipalId = [$AKVPrincipalName, $AKVClientID, 'notaname', ''];
|
||||
$keyStoreSecret = [$AKVPassword, $AKVSecret, 'notasecret', ''];
|
||||
|
||||
// Verify that the error is in the list of expected errors
|
||||
function checkErrors($errors, ...$codes)
|
||||
{
|
||||
$codeFound = false;
|
||||
|
||||
foreach ($codes as $code) {
|
||||
if ($code[0]==$errors[0] and $code[1]==$errors[1]) {
|
||||
$codeFound = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($codeFound == false) {
|
||||
echo "Error: ";
|
||||
print_r($errors);
|
||||
echo "\nExpected: ";
|
||||
print_r($codes);
|
||||
echo "\n";
|
||||
fatalError("Error code not found.\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Set up the columns and build the insert query. Each data type has an
|
||||
// AE-encrypted and a non-encrypted column side by side in the table.
|
||||
// If column encryption is not set in MsSetup.inc, this function simply
|
||||
// creates two non-encrypted columns side-by-side for each type.
|
||||
function formulateSetupQuery($tableName, &$dataTypes, &$columns, &$insertQuery)
|
||||
{
|
||||
$columns = array();
|
||||
$queryTypes = "(";
|
||||
$queryTypesAE = "(";
|
||||
$valuesString = "VALUES (";
|
||||
$numTypes = sizeof($dataTypes);
|
||||
|
||||
for ($i = 0; $i < $numTypes; ++$i) {
|
||||
// Replace parentheses for column names
|
||||
$colname = str_replace(array("(", ",", ")"), array("_", "_", ""), $dataTypes[$i]);
|
||||
$columns[] = new ColumnMeta($dataTypes[$i], "c_".$colname."_AE", null, "deterministic", false);
|
||||
$columns[] = new ColumnMeta($dataTypes[$i], "c_".$colname, null, "none", false);
|
||||
$queryTypes .= "c_"."$colname, ";
|
||||
$queryTypes .= "c_"."$colname"."_AE, ";
|
||||
$valuesString .= "?, ?, ";
|
||||
}
|
||||
|
||||
$queryTypes = substr($queryTypes, 0, -2).")";
|
||||
$valuesString = substr($valuesString, 0, -2).")";
|
||||
|
||||
$insertQuery = "INSERT INTO $tableName ".$queryTypes." ".$valuesString;
|
||||
}
|
||||
|
||||
$strsize = 64;
|
||||
|
||||
$dataTypes = array("char($strsize)", "varchar($strsize)", "nvarchar($strsize)",
|
||||
"decimal", "float", "real", "bigint", "int", "bit"
|
||||
);
|
||||
|
||||
$tableName = "akv_comparison_table";
|
||||
|
||||
// Test every combination of the keywords above.
|
||||
// Leave out good credentials to ensure that caching does not influence the
|
||||
// results. The cache timeout can only be changed with SQLSetConnectAttr, so
|
||||
// we can't run a PHP test without caching, and if we started with good
|
||||
// credentials then subsequent calls with bad credentials can work, which
|
||||
// would muddle the results of this test. Good credentials are tested in a
|
||||
// separate test.
|
||||
for ($i = 0; $i < sizeof($columnEncryption); ++$i) {
|
||||
for ($j = 0; $j < sizeof($keyStoreAuthentication); ++$j) {
|
||||
for ($k = 0; $k < sizeof($keyStorePrincipalId); ++$k) {
|
||||
for ($m = 0; $m < sizeof($keyStoreSecret); ++$m) {
|
||||
$connectionOptions = "sqlsrv:Server=$server;Database=$databaseName";
|
||||
|
||||
if (!empty($columnEncryption[$i])) {
|
||||
$connectionOptions .= ";ColumnEncryption=".$columnEncryption[$i];
|
||||
}
|
||||
if (!empty($keyStoreAuthentication[$j])) {
|
||||
$connectionOptions .= ";KeyStoreAuthentication=".$keyStoreAuthentication[$j];
|
||||
}
|
||||
if (!empty($keyStorePrincipalId[$k])) {
|
||||
$connectionOptions .= ";KeyStorePrincipalId=".$keyStorePrincipalId[$k];
|
||||
}
|
||||
if (!empty($keyStoreSecret[$m])) {
|
||||
$connectionOptions .= ";KeyStoreSecret=".$keyStoreSecret[$m];
|
||||
}
|
||||
|
||||
// Valid credentials getting skipped
|
||||
if (($i == 0 and $j == 0 and $k == 0 and $m == 0) or
|
||||
($i == 0 and $j == 1 and $k == 1 and $m == 1)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$connectionOptions .= ";";
|
||||
|
||||
try {
|
||||
// Connect to the AE-enabled database
|
||||
$conn = new PDO($connectionOptions, $uid, $pwd);
|
||||
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
createTable($conn, $tableName, $columns);
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = $conn->prepare($insertQuery);
|
||||
if ($stmt == false) {
|
||||
print_r($conn->errorInfo());
|
||||
fatalError("sqlsrv_prepare failed\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// Failure expected only if the keywords/credentials are wrong
|
||||
if ($stmt->execute($testValues) == false) {
|
||||
print_r($stmt->errorInfo());
|
||||
$stmt = null;
|
||||
} else {
|
||||
// The INSERT query succeeded with bad credentials, which
|
||||
// should only happen when encryption is not enabled.
|
||||
if (isColEncrypted()) {
|
||||
fatalError("Successful insertion with bad credentials\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
$stmt = null;
|
||||
$conn = null;
|
||||
} catch (Exception $e) {
|
||||
$errors = $e->errorInfo;
|
||||
|
||||
if (!isColEncrypted()) {
|
||||
checkErrors(
|
||||
$errors,
|
||||
array('CE258', '0'),
|
||||
array('CE275', '0'),
|
||||
array('IMSSP', '-85'),
|
||||
array('IMSSP', '-86'),
|
||||
array('IMSSP', '-87'),
|
||||
array('IMSSP', '-88'),
|
||||
array('08001', '0'),
|
||||
array('08001', '-1') // SSL error occurs in Ubuntu
|
||||
);
|
||||
} else {
|
||||
checkErrors(
|
||||
$errors,
|
||||
array('CE258', '0'),
|
||||
array('CE275', '0'),
|
||||
array('IMSSP', '-85'),
|
||||
array('IMSSP', '-86'),
|
||||
array('IMSSP', '-87'),
|
||||
array('IMSSP', '-88'),
|
||||
array('08001', '0'),
|
||||
array('08001', '-1'), // SSL error occurs in Ubuntu
|
||||
array('22018', '206')
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo "Done.\n";
|
||||
?>
|
||||
--EXPECT--
|
||||
Done.
|
|
@ -0,0 +1,207 @@
|
|||
--TEST--
|
||||
Test credentials for Azure Key Vault for Always Encrypted.
|
||||
--SKIPIF--
|
||||
<?php require('skipif.inc'); ?>
|
||||
--FILE--
|
||||
<?php
|
||||
// TODO: Fix the test on Ubuntu - right now it produces a SSL error on Ubuntu
|
||||
// The following skips Ubuntu to prevent a test failure
|
||||
$is_ubuntu = php_uname('v');
|
||||
if (strpos($is_ubuntu, 'buntu') !== false) {
|
||||
echo "Skipping test on Ubuntu\n";
|
||||
exit();
|
||||
}
|
||||
|
||||
require_once("MsCommon_mid-refactor.inc");
|
||||
require_once("MsSetup.inc");
|
||||
require_once('values.php');
|
||||
|
||||
// Set up the columns and build the insert query. Each data type has an
|
||||
// AE-encrypted and a non-encrypted column side by side in the table.
|
||||
function formulateSetupQuery($tableName, &$dataTypes, &$columns, &$insertQuery)
|
||||
{
|
||||
$columns = array();
|
||||
$queryTypes = "(";
|
||||
$queryTypesAE = "(";
|
||||
$valuesString = "VALUES (";
|
||||
$numTypes = sizeof($dataTypes);
|
||||
|
||||
for ($i = 0; $i < $numTypes; ++$i) {
|
||||
// Replace parentheses for column names
|
||||
$colname = str_replace(array("(", ",", ")"), array("_", "_", ""), $dataTypes[$i]);
|
||||
$columns[] = new ColumnMeta($dataTypes[$i], "c_".$colname."_AE", null, "deterministic", false);
|
||||
$columns[] = new ColumnMeta($dataTypes[$i], "c_".$colname, null, "none", false);
|
||||
$queryTypes .= "c_"."$colname, ";
|
||||
$queryTypes .= "c_"."$colname"."_AE, ";
|
||||
$valuesString .= "?, ?, ";
|
||||
}
|
||||
|
||||
$queryTypes = substr($queryTypes, 0, -2).")";
|
||||
$valuesString = substr($valuesString, 0, -2).")";
|
||||
|
||||
$insertQuery = "INSERT INTO $tableName ".$queryTypes." ".$valuesString;
|
||||
}
|
||||
|
||||
$strsize = 64;
|
||||
|
||||
$dataTypes = array("char($strsize)", "varchar($strsize)", "nvarchar($strsize)",
|
||||
"decimal", "float", "real", "bigint", "int", "bit"
|
||||
);
|
||||
|
||||
// Test data insertion and retrieval with username/password
|
||||
// and client Id/client secret combinations.
|
||||
$connectionOptions = "sqlsrv:Server=$server;Database=$databaseName";
|
||||
|
||||
$connectionOptions .= ";ColumnEncryption=enabled";
|
||||
$connectionOptions .= ";KeyStoreAuthentication=KeyVaultPassword";
|
||||
$connectionOptions .= ";KeyStorePrincipalId=".$AKVPrincipalName;
|
||||
$connectionOptions .= ";KeyStoreSecret=".$AKVPassword;
|
||||
$connectionOptions .= ";";
|
||||
|
||||
$tableName = "akv_comparison_table";
|
||||
|
||||
try {
|
||||
// Connect to the AE-enabled database
|
||||
$conn = new PDO($connectionOptions, $uid, $pwd);
|
||||
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
createTable($conn, $tableName, $columns);
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = $conn->prepare($insertQuery);
|
||||
if ($stmt == false) {
|
||||
print_r($conn->errorInfo());
|
||||
fatalError("sqlsrv_prepare failed\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// This should not fail since our credentials are correct
|
||||
if ($stmt->execute($testValues) == false) {
|
||||
print_r($stmt->errorInfo());
|
||||
fatalError("INSERT query execution failed with good credentials.\n");
|
||||
} else {
|
||||
// Get the data back and compare encrypted and non-encrypted versions
|
||||
$selectQuery = "SELECT * FROM $tableName";
|
||||
|
||||
$stmt1 = $conn->query($selectQuery);
|
||||
|
||||
$data = $stmt1->fetchAll(PDO::FETCH_NUM);
|
||||
$data = $data[0];
|
||||
|
||||
if (sizeof($data) != 2*sizeof($dataTypes)) {
|
||||
fatalError("Incorrect number of fields returned.\n");
|
||||
}
|
||||
|
||||
for ($n = 0; $n < sizeof($data); $n += 2) {
|
||||
if ($data[$n] != $data[$n + 1]) {
|
||||
echo "Failed on field $n: ".$data[$n]." ".$data[$n + 1]."\n";
|
||||
fatalError("AE and non-AE values do not match.\n");
|
||||
}
|
||||
}
|
||||
|
||||
echo "Successful insertion and retrieval with username/password.\n";
|
||||
|
||||
$stmt = null;
|
||||
$stmt1 = null;
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
$stmt = null;
|
||||
$conn = null;
|
||||
} catch (Exception $e) {
|
||||
echo "Unexpected error.\n";
|
||||
print_r($e->errorInfo);
|
||||
}
|
||||
|
||||
$connectionOptions = "sqlsrv:Server=$server;Database=$databaseName";
|
||||
|
||||
$connectionOptions .= ";ColumnEncryption=enabled";
|
||||
$connectionOptions .= ";KeyStoreAuthentication=KeyVaultClientSecret";
|
||||
$connectionOptions .= ";KeyStorePrincipalId=".$AKVClientID;
|
||||
$connectionOptions .= ";KeyStoreSecret=".$AKVSecret;
|
||||
$connectionOptions .= ";";
|
||||
|
||||
try {
|
||||
// Connect to the AE-enabled database
|
||||
$conn = new PDO($connectionOptions, $uid, $pwd);
|
||||
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
createTable($conn, $tableName, $columns);
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = $conn->prepare($insertQuery);
|
||||
if ($stmt == false) {
|
||||
print_r($conn->errorInfo());
|
||||
fatalError("sqlsrv_prepare failed\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// This should not fail since our credentials are correct
|
||||
if ($stmt->execute($testValues) == false) {
|
||||
print_r($stmt->errorInfo());
|
||||
fatalError("INSERT query execution failed with good credentials.\n");
|
||||
} else {
|
||||
// Get the data back and compare encrypted and non-encrypted versions
|
||||
$selectQuery = "SELECT * FROM $tableName";
|
||||
|
||||
$stmt1 = $conn->query($selectQuery);
|
||||
|
||||
$data = $stmt1->fetchAll(PDO::FETCH_NUM);
|
||||
$data = $data[0];
|
||||
|
||||
if (sizeof($data) != 2*sizeof($dataTypes)) {
|
||||
fatalError("Incorrect number of fields returned.\n");
|
||||
}
|
||||
|
||||
for ($n = 0; $n < sizeof($data); $n += 2) {
|
||||
if ($data[$n] != $data[$n + 1]) {
|
||||
echo "Failed on field $n: ".$data[$n]." ".$data[$n + 1]."\n";
|
||||
fatalError("AE and non-AE values do not match.\n");
|
||||
}
|
||||
}
|
||||
|
||||
echo "Successful insertion and retrieval with client ID/secret.\n";
|
||||
|
||||
$stmt = null;
|
||||
$stmt1 = null;
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
$stmt = null;
|
||||
$conn = null;
|
||||
} catch (Exception $e) {
|
||||
echo "Unexpected error.\n";
|
||||
print_r($e->errorInfo);
|
||||
}
|
||||
|
||||
?>
|
||||
--EXPECTREGEX--
|
||||
(Successful insertion and retrieval with username\/password\.\nSuccessful insertion and retrieval with client ID\/secret\.|Skipping test on Ubuntu)
|
|
@ -109,11 +109,7 @@ function testEncryptedWithODBC()
|
|||
$value = "ODBC Driver 13 for SQL Server";
|
||||
$connectionOptions = "Driver = $value; ColumnEncryption = Enabled;";
|
||||
|
||||
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
|
||||
$expected = "The Always Encrypted feature requires Microsoft ODBC Driver 17 for SQL Server.";
|
||||
} else {
|
||||
$expected = "An invalid keyword 'ColumnEncryption' was specified in the DSN string.";
|
||||
}
|
||||
|
||||
connectVerifyOutput($connectionOptions, $expected);
|
||||
}
|
||||
|
|
799
test/functional/pdo_sqlsrv/values.php
Normal file
799
test/functional/pdo_sqlsrv/values.php
Normal file
File diff suppressed because one or more lines are too long
|
@ -359,6 +359,17 @@ function connect($options = array(), $disableCE = false)
|
|||
if (isColEncrypted()) {
|
||||
$connectionOptions = array_merge($connectionOptions, array("ColumnEncryption" => "Enabled"));
|
||||
}
|
||||
if ($keystore == 'akv') {
|
||||
$akv_options = array("KeyStoreAuthentication"=>$AKVKeyStoreAuthentication);
|
||||
if ($AKVKeyStoreAuthentication == "KeyVaultPassword") {
|
||||
$akv_options["KeyStorePrincipalId"] = $AKVPrincipalName;
|
||||
$akv_options["KeyStoreSecret"] = $AKVPassword;
|
||||
} else if ($AKVKeyStoreAuthentication == "KeyVaultClientSecret") {
|
||||
$akv_options["KeyStorePrincipalId"] = $AKVClientID;
|
||||
$akv_options["KeyStoreSecret"] = $AKVSecret;
|
||||
}
|
||||
$connectionOptions = array_merge($connectionOptions, $akv_options);
|
||||
}
|
||||
}
|
||||
$conn = sqlsrv_connect($server, $connectionOptions);
|
||||
if ($conn === false) {
|
||||
|
|
|
@ -44,4 +44,11 @@ if (isset($_ENV['MSSQL_SERVER']) || isset($_ENV['MSSQL_USER']) || isset($_ENV['M
|
|||
$keystore = "none"; // key store provider, acceptable values are none, win, ksp, akv
|
||||
$dataEncrypted = false; // whether data is to be encrypted
|
||||
|
||||
// for Azure Key Vault
|
||||
$AKVKeyStoreAuthentication = 'TARGET_AKV_AUTH'; // can be KeyVaultPassword or KeyVaultClientSecret
|
||||
$AKVPrincipalName = 'TARGET_AKV_PRINCIPAL_NAME'; // for use with KeyVaultPassword
|
||||
$AKVPassword = 'TARGET_AKV_PASSWORD'; // for use with KeyVaultPassword
|
||||
$AKVClientID = 'TARGET_AKV_CLIENT_ID'; // for use with KeyVaultClientSecret
|
||||
$AKVSecret = 'TARGET_AKV_CLIENT_SECRET'; // for use with KeyVaultClientSecret
|
||||
|
||||
?>
|
||||
|
|
190
test/functional/sqlsrv/sqlsrv_ae_azure_key_vault_keywords.phpt
Normal file
190
test/functional/sqlsrv/sqlsrv_ae_azure_key_vault_keywords.phpt
Normal file
|
@ -0,0 +1,190 @@
|
|||
--TEST--
|
||||
Test connection keywords for Azure Key Vault for Always Encrypted.
|
||||
--SKIPIF--
|
||||
<?php require('skipif.inc'); ?>
|
||||
--FILE--
|
||||
<?php
|
||||
require_once('MsCommon.inc');
|
||||
require_once('values.php');
|
||||
|
||||
// We will test the direct product (set of all possible combinations) of the following
|
||||
$columnEncryption = ['enabled', 'disabled', 'notvalid', ''];
|
||||
$keyStoreAuthentication = ['KeyVaultPassword', 'KeyVaultClientSecret', 'KeyVaultNothing', ''];
|
||||
$keyStorePrincipalId = [$AKVPrincipalName, $AKVClientID, 'notaname', ''];
|
||||
$keyStoreSecret = [$AKVPassword, $AKVSecret, 'notasecret', ''];
|
||||
|
||||
$is_win = (strtoupper(substr(php_uname('s'), 0, 3)) === 'WIN');
|
||||
|
||||
function checkErrors($errors, ...$codes)
|
||||
{
|
||||
$codeFound = false;
|
||||
|
||||
foreach ($codes as $code) {
|
||||
if ($code[0]==$errors[0][0] and $code[1]==$errors[0][1]) {
|
||||
$codeFound = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($codeFound == false) {
|
||||
echo "Error: ";
|
||||
print_r($errors);
|
||||
echo "\nExpected: ";
|
||||
print_r($codes);
|
||||
echo "\n";
|
||||
fatalError("Error code not found.\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Set up the columns and build the insert query. Each data type has an
|
||||
// AE-encrypted and a non-encrypted column side by side in the table.
|
||||
function formulateSetupQuery($tableName, &$dataTypes, &$columns, &$insertQuery)
|
||||
{
|
||||
$columns = array();
|
||||
$queryTypes = "(";
|
||||
$queryTypesAE = "(";
|
||||
$valuesString = "VALUES (";
|
||||
$numTypes = sizeof($dataTypes);
|
||||
|
||||
for ($i = 0; $i < $numTypes; ++$i) {
|
||||
// Replace parentheses for column names
|
||||
$colname = str_replace(array("(", ",", ")"), array("_", "_", ""), $dataTypes[$i]);
|
||||
$columns[] = new AE\ColumnMeta($dataTypes[$i], "c_".$colname."_AE");
|
||||
$columns[] = new AE\ColumnMeta($dataTypes[$i], "c_".$colname, null, true, true);
|
||||
$queryTypes .= "c_"."$colname, ";
|
||||
$queryTypes .= "c_"."$colname"."_AE, ";
|
||||
$valuesString .= "?, ?, ";
|
||||
}
|
||||
|
||||
$queryTypes = substr($queryTypes, 0, -2).")";
|
||||
$valuesString = substr($valuesString, 0, -2).")";
|
||||
|
||||
$insertQuery = "INSERT INTO $tableName ".$queryTypes." ".$valuesString;
|
||||
}
|
||||
|
||||
$strsize = 64;
|
||||
|
||||
$dataTypes = array("char($strsize)", "varchar($strsize)", "nvarchar($strsize)",
|
||||
"decimal", "float", "real", "bigint", "int", "bit"
|
||||
);
|
||||
|
||||
$tableName = "akv_comparison_table";
|
||||
|
||||
// Test every combination of the keywords above.
|
||||
// Leave out good credentials to ensure that caching does not influence the
|
||||
// results. The cache timeout can only be changed with SQLSetConnectAttr, so
|
||||
// we can't run a PHP test without caching, and if we started with good
|
||||
// credentials then subsequent calls with bad credentials can work, which
|
||||
// would muddle the results of this test. Good credentials are tested in a
|
||||
// separate test.
|
||||
for ($i = 0; $i < sizeof($columnEncryption); ++$i) {
|
||||
for ($j = 0; $j < sizeof($keyStoreAuthentication); ++$j) {
|
||||
for ($k = 0; $k < sizeof($keyStorePrincipalId); ++$k) {
|
||||
for ($m = 0; $m < sizeof($keyStoreSecret); ++$m) {
|
||||
$connectionOptions = array("CharacterSet"=>"UTF-8",
|
||||
"database"=>$databaseName,
|
||||
"uid"=>$uid,
|
||||
"pwd"=>$pwd,
|
||||
"ConnectionPooling"=>0);
|
||||
|
||||
if (!empty($columnEncryption[$i])) {
|
||||
$connectionOptions['ColumnEncryption'] = $columnEncryption[$i];
|
||||
}
|
||||
if (!empty($keyStoreAuthentication[$j])) {
|
||||
$connectionOptions['KeyStoreAuthentication'] = $keyStoreAuthentication[$j];
|
||||
}
|
||||
if (!empty($keyStorePrincipalId[$k])) {
|
||||
$connectionOptions['KeyStorePrincipalId'] = $keyStorePrincipalId[$k];
|
||||
}
|
||||
if (!empty($keyStoreSecret[$m])) {
|
||||
$connectionOptions['KeyStoreSecret'] = $keyStoreSecret[$m];
|
||||
}
|
||||
|
||||
// Valid credentials getting skipped
|
||||
if (($i == 0 and $j == 0 and $k == 0 and $m == 0) or
|
||||
($i == 0 and $j == 1 and $k == 1 and $m == 1)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Connect to the AE-enabled database
|
||||
// Failure is expected when the keyword combination is wrong
|
||||
$conn = sqlsrv_connect($server, $connectionOptions);
|
||||
if (!$conn) {
|
||||
$errors = sqlsrv_errors();
|
||||
|
||||
checkErrors(
|
||||
$errors,
|
||||
array('08001','0'),
|
||||
array('08001','-1'), // SSL error occurs in Ubuntu
|
||||
array('IMSSP','-110'),
|
||||
array('IMSSP','-111'),
|
||||
array('IMSSP','-112'),
|
||||
array('IMSSP','-113')
|
||||
);
|
||||
} else {
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
$stmt = AE\createTable($conn, $tableName, $columns);
|
||||
if (!$stmt) {
|
||||
fatalError("Failed to create table $tableName.\n");
|
||||
}
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = sqlsrv_prepare($conn, $insertQuery, $testValues);
|
||||
if ($stmt == false) {
|
||||
print_r(sqlsrv_errors());
|
||||
fatalError("sqlsrv_prepare failed.\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// This is where we expect failure if the credentials are incorrect
|
||||
if (sqlsrv_execute($stmt) == false) {
|
||||
$errors = sqlsrv_errors();
|
||||
|
||||
if (!AE\isColEncrypted()) {
|
||||
checkErrors(
|
||||
$errors,
|
||||
array('CE258', '0'),
|
||||
array('CE275', '0')
|
||||
);
|
||||
} else {
|
||||
checkErrors(
|
||||
$errors,
|
||||
array('CE258', '0'),
|
||||
array('CE275', '0'),
|
||||
array('22018', '206')
|
||||
);
|
||||
}
|
||||
|
||||
sqlsrv_free_stmt($stmt);
|
||||
} else {
|
||||
// The INSERT query succeeded with bad credentials, which
|
||||
// should only happen when encryption is not enabled.
|
||||
if (AE\isColEncrypted()) {
|
||||
fatalError("Successful insertion with bad credentials\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo "Done.\n";
|
||||
?>
|
||||
--EXPECT--
|
||||
Done.
|
|
@ -0,0 +1,203 @@
|
|||
--TEST--
|
||||
Test credentials for Azure Key Vault for Always Encrypted.
|
||||
--SKIPIF--
|
||||
<?php require('skipif.inc'); ?>
|
||||
--FILE--
|
||||
<?php
|
||||
// TODO: Fix the test on Ubuntu - right now it produces a SSL error on Ubuntu
|
||||
// The following skips Ubuntu to prevent a test failure
|
||||
$is_ubuntu = php_uname('v');
|
||||
if (strpos($is_ubuntu, 'buntu') !== false)
|
||||
{
|
||||
echo "Skipping test on Ubuntu\n";
|
||||
exit();
|
||||
}
|
||||
|
||||
require_once('MsCommon.inc');
|
||||
require_once('values.php');
|
||||
|
||||
// Set up the columns and build the insert query. Each data type has an
|
||||
// AE-encrypted and a non-encrypted column side by side in the table.
|
||||
function formulateSetupQuery($tableName, &$dataTypes, &$columns, &$insertQuery)
|
||||
{
|
||||
$columns = array();
|
||||
$queryTypes = "(";
|
||||
$queryTypesAE = "(";
|
||||
$valuesString = "VALUES (";
|
||||
$numTypes = sizeof($dataTypes);
|
||||
|
||||
for ($i = 0; $i < $numTypes; ++$i) {
|
||||
// Replace parentheses for column names
|
||||
$colname = str_replace(array("(", ",", ")"), array("_", "_", ""), $dataTypes[$i]);
|
||||
$columns[] = new AE\ColumnMeta($dataTypes[$i], "c_".$colname."_AE");
|
||||
$columns[] = new AE\ColumnMeta($dataTypes[$i], "c_".$colname, null, true, true);
|
||||
$queryTypes .= "c_"."$colname, ";
|
||||
$queryTypes .= "c_"."$colname"."_AE, ";
|
||||
$valuesString .= "?, ?, ";
|
||||
}
|
||||
|
||||
$queryTypes = substr($queryTypes, 0, -2).")";
|
||||
$valuesString = substr($valuesString, 0, -2).")";
|
||||
|
||||
$insertQuery = "INSERT INTO $tableName ".$queryTypes." ".$valuesString;
|
||||
}
|
||||
|
||||
$strsize = 64;
|
||||
|
||||
$dataTypes = array ("char($strsize)", "varchar($strsize)", "nvarchar($strsize)",
|
||||
"decimal", "float", "real", "bigint", "int", "bit"
|
||||
);
|
||||
|
||||
// Test data insertion and retrieval with username/password
|
||||
// and client Id/client secret combinations.
|
||||
$connectionOptions = array("CharacterSet"=>"UTF-8",
|
||||
"database"=>$databaseName,
|
||||
"uid"=>$uid,
|
||||
"pwd"=>$pwd,
|
||||
"ConnectionPooling"=>0);
|
||||
|
||||
$connectionOptions['ColumnEncryption'] = "enabled";
|
||||
$connectionOptions['KeyStoreAuthentication'] = "KeyVaultPassword";
|
||||
$connectionOptions['KeyStorePrincipalId'] = $AKVPrincipalName;
|
||||
$connectionOptions['KeyStoreSecret'] = $AKVPassword;
|
||||
|
||||
$tableName = "akv_comparison_table";
|
||||
|
||||
// Connect to the AE-enabled database
|
||||
$conn = sqlsrv_connect($server, $connectionOptions);
|
||||
if (!$conn) {
|
||||
$errors = sqlsrv_errors();
|
||||
fatalError("Connection failed while testing good credentials.\n");
|
||||
} else {
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
$stmt = AE\createTable($conn, $tableName, $columns);
|
||||
if (!$stmt) {
|
||||
fatalError("Failed to create table $tableName\n");
|
||||
}
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = sqlsrv_prepare($conn, $insertQuery, $testValues);
|
||||
if ($stmt == false) {
|
||||
print_r(sqlsrv_errors());
|
||||
fatalError("sqlsrv_prepare failed\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// This should not fail since our credentials are correct
|
||||
if (sqlsrv_execute($stmt) == false) {
|
||||
$errors = sqlsrv_errors();
|
||||
fatalError("INSERT query failed with good credentials.\n");
|
||||
} else {
|
||||
// Get the data back and compare encrypted and non-encrypted versions
|
||||
$selectQuery = "SELECT * FROM $tableName";
|
||||
|
||||
$stmt1 = sqlsrv_query($conn, $selectQuery);
|
||||
$data = sqlsrv_fetch_array($stmt1, SQLSRV_FETCH_NUMERIC);
|
||||
|
||||
if (sizeof($data) != 2*sizeof($dataTypes)) {
|
||||
fatalError("Incorrect number of fields returned.\n");
|
||||
}
|
||||
|
||||
for ($n = 0; $n < sizeof($data); $n += 2) {
|
||||
if ($data[$n] != $data[$n + 1]) {
|
||||
echo "Failed on field $n: ".$data[$n]." ".$data[$n + 1]."\n";
|
||||
fatalError("AE and non-AE values do not match.\n");
|
||||
}
|
||||
}
|
||||
|
||||
echo "Successful insertion and retrieval with username/password.\n";
|
||||
|
||||
sqlsrv_free_stmt($stmt);
|
||||
sqlsrv_free_stmt($stmt1);
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
|
||||
$connectionOptions['ColumnEncryption'] = "enabled";
|
||||
$connectionOptions['KeyStoreAuthentication'] = "KeyVaultClientSecret";
|
||||
$connectionOptions['KeyStorePrincipalId'] = $AKVClientID;
|
||||
$connectionOptions['KeyStoreSecret'] = $AKVSecret;
|
||||
|
||||
// Connect to the AE-enabled database
|
||||
$conn = sqlsrv_connect($server, $connectionOptions);
|
||||
if (!$conn) {
|
||||
$errors = sqlsrv_errors();
|
||||
fatalError("Connection failed while testing good credentials.\n");
|
||||
} else {
|
||||
$columns = array();
|
||||
$insertQuery = "";
|
||||
|
||||
// Generate the INSERT query
|
||||
formulateSetupQuery($tableName, $dataTypes, $columns, $insertQuery);
|
||||
|
||||
$stmt = AE\createTable($conn, $tableName, $columns);
|
||||
if (!$stmt) {
|
||||
fatalError("Failed to create table $tableName\n");
|
||||
}
|
||||
|
||||
// Duplicate all values for insertion - one is encrypted, one is not
|
||||
$testValues = array();
|
||||
for ($n = 0; $n < sizeof($small_values); ++$n) {
|
||||
$testValues[] = $small_values[$n];
|
||||
$testValues[] = $small_values[$n];
|
||||
}
|
||||
|
||||
// Prepare the INSERT query
|
||||
// This is never expected to fail
|
||||
$stmt = sqlsrv_prepare($conn, $insertQuery, $testValues);
|
||||
if ($stmt == false) {
|
||||
print_r(sqlsrv_errors());
|
||||
fatalError("sqlsrv_prepare failed\n");
|
||||
}
|
||||
|
||||
// Execute the INSERT query
|
||||
// This should not fail since our credentials are correct
|
||||
if (sqlsrv_execute($stmt) == false) {
|
||||
$errors = sqlsrv_errors();
|
||||
fatalError("INSERT query execution failed with good credentials.\n");
|
||||
} else {
|
||||
// Get the data back and compare encrypted and non-encrypted versions
|
||||
$selectQuery = "SELECT * FROM $tableName";
|
||||
|
||||
$stmt1 = sqlsrv_query($conn, $selectQuery);
|
||||
$data = sqlsrv_fetch_array($stmt1, SQLSRV_FETCH_NUMERIC);
|
||||
|
||||
if (sizeof($data) != 2*sizeof($dataTypes)) {
|
||||
fatalError("Incorrect number of fields returned.\n");
|
||||
}
|
||||
|
||||
for ($n = 0; $n < sizeof($data); $n += 2) {
|
||||
if ($data[$n] != $data[$n + 1]) {
|
||||
echo "Failed on field $n: ".$data[$n]." ".$data[$n + 1]."\n";
|
||||
fatalError("AE and non-AE values do not match.\n");
|
||||
}
|
||||
}
|
||||
|
||||
echo "Successful insertion and retrieval with client ID/secret.\n";
|
||||
|
||||
sqlsrv_free_stmt($stmt);
|
||||
sqlsrv_free_stmt($stmt1);
|
||||
}
|
||||
|
||||
// Free the statement and close the connection
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
|
||||
?>
|
||||
--EXPECTREGEX--
|
||||
(Successful insertion and retrieval with username\/password\.\nSuccessful insertion and retrieval with client ID\/secret\.|Skipping test on Ubuntu)
|
|
@ -106,11 +106,7 @@ function testEncryptedWithODBC($msodbcsqlMaj, $server, $connectionOptions)
|
|||
$connectionOptions['Driver']=$value;
|
||||
$connectionOptions['ColumnEncryption']='Enabled';
|
||||
|
||||
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
|
||||
$expected = "The Always Encrypted feature requires Microsoft ODBC Driver 17 for SQL Server.";
|
||||
} else {
|
||||
$expected = "Invalid option ColumnEncryption was passed to sqlsrv_connect.";
|
||||
}
|
||||
|
||||
connectVerifyOutput($server, $connectionOptions, $expected);
|
||||
}
|
||||
|
|
|
@ -1,4 +1,13 @@
|
|||
<?php
|
||||
|
||||
// This file holds different data of many different types for testing
|
||||
// Always Encrypted. Currently, the tests that use this data are:
|
||||
// pdo__ae_azure_key_vault_keywords.phpt ($small_values)
|
||||
// pdo_ae_azure_key_vault_verification.phpt ($small_values)
|
||||
// sqlsrv_ae_fetch_phptypes.phpt ($values)
|
||||
// sqlsrv_ae_azure_key_vault_keywords.phpt ($small_values)
|
||||
// sqlsrv_ae_azure_key_vault_verification.phpt ($small_values)
|
||||
|
||||
$values = array();
|
||||
$values[] = array(array(("BA3EA123EA8FFF46A01"), null, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_BINARY(256)),
|
||||
array(("7BDD1C6794E0BA9556F63B93A"), null, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR), SQLSRV_SQLTYPE_VARBINARY(256)),
|
||||
|
@ -776,3 +785,15 @@ $values[] = array(array(("C0A0B025C680B0A23D7885F7C203AD211F679679F97F910F0F1A36
|
|||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
$small_values = array("qwerty",
|
||||
"wertyu",
|
||||
"ϕƆǀđIΩͰDZζ±Áɔd͋ǻĆÅũμ",
|
||||
52.7878,
|
||||
-1.79E+308,
|
||||
-3.4E+38,
|
||||
-987654321987654321,
|
||||
987654321,
|
||||
1,
|
||||
);
|
||||
|
Loading…
Reference in a new issue