Search in sources :

Example 6 with SQLServerColumnEncryptionAzureKeyVaultProvider

use of com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider in project mssql-jdbc by microsoft.

the class JDBCEncryptionDecryptionTest method testAkvNameWithTokenCredential.

@ParameterizedTest
@MethodSource("enclaveParams")
@Tag(Constants.reqExternalSetup)
public void testAkvNameWithTokenCredential(String serverName, String url, String protocol) throws Exception {
    setAEConnectionString(serverName, url, protocol);
    ClientSecretCredential credential = new ClientSecretCredentialBuilder().tenantId(tenantID).clientId(applicationClientID).clientSecret(applicationKey).build();
    try {
        SQLServerColumnEncryptionAzureKeyVaultProvider akv = new SQLServerColumnEncryptionAzureKeyVaultProvider(credential);
        String keystoreName = "keystoreName";
        akv.setName(keystoreName);
        assertTrue(akv.getName().equals(keystoreName));
    } catch (SQLServerException e) {
        fail(TestResource.getResource("R_unexpectedException") + e.getMessage());
    }
}
Also used : ClientSecretCredentialBuilder(com.azure.identity.ClientSecretCredentialBuilder) SQLServerException(com.microsoft.sqlserver.jdbc.SQLServerException) ClientSecretCredential(com.azure.identity.ClientSecretCredential) SQLServerColumnEncryptionAzureKeyVaultProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource) Tag(org.junit.jupiter.api.Tag)

Example 7 with SQLServerColumnEncryptionAzureKeyVaultProvider

use of com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider in project mssql-jdbc by microsoft.

the class JDBCEncryptionDecryptionTest method testAkvBadEncryptColumnEncryptionKeyWithAuthCallback.

@ParameterizedTest
@MethodSource("enclaveParams")
@Tag(Constants.reqExternalSetup)
public void testAkvBadEncryptColumnEncryptionKeyWithAuthCallback(String serverName, String url, String protocol) throws Exception {
    setAEConnectionString(serverName, url, protocol);
    SQLServerColumnEncryptionAzureKeyVaultProvider akv = null;
    try {
        akv = new SQLServerColumnEncryptionAzureKeyVaultProvider(authenticationCallback);
    } catch (SQLServerException e) {
        fail(TestResource.getResource("R_unexpectedException") + e.getMessage());
    }
    // null encryptedColumnEncryptionKey
    try {
        akv.encryptColumnEncryptionKey(keyIDs[0], Constants.CEK_ALGORITHM, null);
        fail(TestResource.getResource("R_expectedExceptionNotThrown"));
    } catch (SQLServerException e) {
        assertTrue(e.getMessage().matches(TestUtils.formatErrorMsg("R_NullColumnEncryptionKey")));
    }
    // empty encryptedColumnEncryptionKey
    try {
        byte[] emptyCek = new byte[0];
        akv.encryptColumnEncryptionKey(keyIDs[0], Constants.CEK_ALGORITHM, emptyCek);
        fail(TestResource.getResource("R_expectedExceptionNotThrown"));
    } catch (SQLServerException e) {
        assertTrue(e.getMessage().matches(TestUtils.formatErrorMsg("R_EmptyCEK")));
    }
}
Also used : SQLServerException(com.microsoft.sqlserver.jdbc.SQLServerException) SQLServerColumnEncryptionAzureKeyVaultProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource) Tag(org.junit.jupiter.api.Tag)

Example 8 with SQLServerColumnEncryptionAzureKeyVaultProvider

use of com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider in project mssql-jdbc by microsoft.

the class AESetup method createCEK.

/**
 * Create column encryption key
 *
 * @param storeProvider
 * @param certStore
 * @throws SQLException
 */
private static void createCEK(String cmkName, String cekName, SQLServerColumnEncryptionKeyStoreProvider storeProvider) throws SQLException {
    try (SQLServerConnection con = (SQLServerConnection) PrepUtil.getConnection(AETestConnectionString + ";sendTimeAsDateTime=false", AEInfo);
        SQLServerStatement stmt = (SQLServerStatement) con.createStatement()) {
        byte[] valuesDefault = Constants.CEK_STRING.getBytes();
        String encryptedValue;
        if (storeProvider instanceof SQLServerColumnEncryptionJavaKeyStoreProvider) {
            byte[] key = storeProvider.encryptColumnEncryptionKey(javaKeyAliases, Constants.CEK_ALGORITHM, valuesDefault);
            encryptedValue = "0x" + TestUtils.bytesToHexString(key, key.length);
        } else if (storeProvider instanceof SQLServerColumnEncryptionAzureKeyVaultProvider) {
            byte[] key = storeProvider.encryptColumnEncryptionKey(keyIDs[0], Constants.CEK_ALGORITHM, valuesDefault);
            encryptedValue = "0x" + TestUtils.bytesToHexString(key, key.length);
        } else {
            encryptedValue = Constants.CEK_ENCRYPTED_VALUE;
        }
        String sql = "if not exists (SELECT name from sys.column_encryption_keys where name='" + cekName + "')" + " begin" + " CREATE COLUMN ENCRYPTION KEY " + cekName + " WITH VALUES " + "(COLUMN_MASTER_KEY = " + cmkName + ", ALGORITHM = '" + Constants.CEK_ALGORITHM + "', ENCRYPTED_VALUE = " + encryptedValue + ") end;";
        stmt.execute(sql);
    }
}
Also used : SQLServerConnection(com.microsoft.sqlserver.jdbc.SQLServerConnection) SQLServerStatement(com.microsoft.sqlserver.jdbc.SQLServerStatement) SQLServerColumnEncryptionAzureKeyVaultProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider) SQLServerColumnEncryptionJavaKeyStoreProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider)

Example 9 with SQLServerColumnEncryptionAzureKeyVaultProvider

use of com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider in project mssql-jdbc by microsoft.

the class FedauthWithAE method setupKeyStoreProvider_AKVOld.

private SQLServerColumnEncryptionKeyStoreProvider setupKeyStoreProvider_AKVOld() throws SQLServerException {
    ExecutorService service = Executors.newFixedThreadPool(2);
    SQLServerKeyVaultAuthenticationCallback authenticationCallback = new SQLServerKeyVaultAuthenticationCallback() {

        @Override
        public String getAccessToken(String authority, String resource, String scope) {
            AuthenticationResult result = null;
            try {
                AuthenticationContext context = new AuthenticationContext(authority, false, service);
                ClientCredential cred = new ClientCredential(applicationClientID, applicationKey);
                Future<AuthenticationResult> future = context.acquireToken(resource, cred, null);
                result = future.get();
                return result.getAccessToken();
            } catch (Exception e) {
                fail(e.getMessage());
                return null;
            }
        }
    };
    return new SQLServerColumnEncryptionAzureKeyVaultProvider(authenticationCallback);
}
Also used : ClientCredential(com.microsoft.aad.adal4j.ClientCredential) AuthenticationContext(com.microsoft.aad.adal4j.AuthenticationContext) ExecutorService(java.util.concurrent.ExecutorService) SQLServerKeyVaultAuthenticationCallback(com.microsoft.sqlserver.jdbc.SQLServerKeyVaultAuthenticationCallback) SQLException(java.sql.SQLException) SQLServerException(com.microsoft.sqlserver.jdbc.SQLServerException) SQLServerColumnEncryptionAzureKeyVaultProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider) AuthenticationResult(com.microsoft.aad.adal4j.AuthenticationResult)

Example 10 with SQLServerColumnEncryptionAzureKeyVaultProvider

use of com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider in project mssql-jdbc by microsoft.

the class AbstractTest method setup.

/**
 * This will take care of all initialization before running the Test Suite.
 *
 * @throws Exception
 *         when an error occurs
 */
@BeforeAll
public static void setup() throws Exception {
    // Invoke fine logging...
    invokeLogging();
    // get Properties from config file
    try (InputStream input = new FileInputStream(Constants.CONFIG_PROPERTIES_FILE)) {
        configProperties = new Properties();
        configProperties.load(input);
    } catch (FileNotFoundException | SecurityException e) {
    // no config file used
    }
    connectionString = getConfiguredPropertyOrEnv(Constants.MSSQL_JDBC_TEST_CONNECTION_PROPERTIES);
    connectionStringNTLM = connectionString;
    applicationClientID = getConfiguredProperty("applicationClientID");
    applicationKey = getConfiguredProperty("applicationKey");
    tenantID = getConfiguredProperty("tenantID");
    javaKeyPath = TestUtils.getCurrentClassPath() + Constants.JKS_NAME;
    keyIDs = getConfiguredProperty("keyID", "").split(Constants.SEMI_COLON);
    windowsKeyPath = getConfiguredProperty("windowsKeyPath");
    String prop;
    prop = getConfiguredProperty("enclaveServer", null);
    if (null == prop) {
        // default to server in connection string
        String serverName = (connectionString.substring(Constants.JDBC_PREFIX.length()).split(Constants.SEMI_COLON)[0]).split(":")[0];
        enclaveServer = new String[1];
        enclaveServer[0] = new String(serverName);
    } else {
        enclaveServer = prop.split(Constants.SEMI_COLON);
    }
    prop = getConfiguredProperty("enclaveAttestationUrl", null);
    enclaveAttestationUrl = null != prop ? prop.split(Constants.SEMI_COLON) : null;
    prop = getConfiguredProperty("enclaveAttestationProtocol", null);
    enclaveAttestationProtocol = null != prop ? prop.split(Constants.SEMI_COLON) : null;
    clientCertificate = getConfiguredProperty("clientCertificate", null);
    clientKey = getConfiguredProperty("clientKey", null);
    clientKeyPassword = getConfiguredProperty("clientKeyPassword", "");
    trustStorePath = getConfiguredProperty("trustStore", "");
    Map<String, SQLServerColumnEncryptionKeyStoreProvider> map = new HashMap<String, SQLServerColumnEncryptionKeyStoreProvider>();
    if (null == jksProvider) {
        jksProvider = new SQLServerColumnEncryptionJavaKeyStoreProvider(javaKeyPath, Constants.JKS_SECRET.toCharArray());
        map.put(Constants.CUSTOM_KEYSTORE_NAME, jksProvider);
    }
    if (null == akvProvider && null != applicationClientID && null != applicationKey) {
        File file = null;
        try {
            file = new File(Constants.MSSQL_JDBC_PROPERTIES);
            try (OutputStream os = new FileOutputStream(file)) {
                Properties props = new Properties();
                // Append to the list of hardcoded endpoints.
                props.setProperty(Constants.AKV_TRUSTED_ENDPOINTS_KEYWORD, ";vault.azure.net");
                props.store(os, "");
            }
            akvProvider = new SQLServerColumnEncryptionAzureKeyVaultProvider(applicationClientID, applicationKey);
            map.put(Constants.AZURE_KEY_VAULT_NAME, akvProvider);
        } finally {
            if (null != file) {
                file.delete();
            }
        }
    }
    if (!isKspRegistered) {
        SQLServerConnection.registerColumnEncryptionKeyStoreProviders(map);
        isKspRegistered = true;
    }
    // if these properties are defined then NTLM is desired, modify connection string accordingly
    String domain = getConfiguredProperty("domainNTLM");
    String user = getConfiguredProperty("userNTLM");
    String password = getConfiguredProperty("passwordNTLM");
    if (null != domain) {
        connectionStringNTLM = TestUtils.addOrOverrideProperty(connectionStringNTLM, "domain", domain);
    }
    if (null != user) {
        connectionStringNTLM = TestUtils.addOrOverrideProperty(connectionStringNTLM, "user", user);
    }
    if (null != password) {
        connectionStringNTLM = TestUtils.addOrOverrideProperty(connectionStringNTLM, "password", password);
    }
    if (null != user && null != password) {
        connectionStringNTLM = TestUtils.addOrOverrideProperty(connectionStringNTLM, "authenticationScheme", "NTLM");
        connectionStringNTLM = TestUtils.addOrOverrideProperty(connectionStringNTLM, "integratedSecurity", "true");
    }
    // MSI properties
    msiClientId = getConfiguredProperty("msiClientId");
    keyStorePrincipalId = getConfiguredProperty("keyStorePrincipalId");
    keyStoreSecret = getConfiguredProperty("keyStoreSecret");
    ds = updateDataSource(connectionString, new SQLServerDataSource());
    dsXA = updateDataSource(connectionString, new SQLServerXADataSource());
    dsPool = updateDataSource(connectionString, new SQLServerConnectionPoolDataSource());
    try {
        Assertions.assertNotNull(connectionString, TestResource.getResource("R_ConnectionStringNull"));
        Class.forName(Constants.MSSQL_JDBC_PACKAGE + ".SQLServerDriver");
        if (!SQLServerDriver.isRegistered()) {
            SQLServerDriver.register();
        }
        if (null == connection || connection.isClosed()) {
            connection = getConnection();
        }
        isSqlAzureOrAzureDW(connection);
        checkSqlOS(connection);
    } catch (Exception e) {
        throw e;
    }
}
Also used : SQLServerConnectionPoolDataSource(com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource) HashMap(java.util.HashMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ISQLServerDataSource(com.microsoft.sqlserver.jdbc.ISQLServerDataSource) SQLServerDataSource(com.microsoft.sqlserver.jdbc.SQLServerDataSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) SQLException(java.sql.SQLException) FileNotFoundException(java.io.FileNotFoundException) SQLServerXADataSource(com.microsoft.sqlserver.jdbc.SQLServerXADataSource) SQLServerColumnEncryptionKeyStoreProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider) FileOutputStream(java.io.FileOutputStream) File(java.io.File) SQLServerColumnEncryptionAzureKeyVaultProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider) SQLServerColumnEncryptionJavaKeyStoreProvider(com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider) BeforeAll(org.junit.jupiter.api.BeforeAll)

Aggregations

SQLServerColumnEncryptionAzureKeyVaultProvider (com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider)24 SQLServerException (com.microsoft.sqlserver.jdbc.SQLServerException)18 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)18 MethodSource (org.junit.jupiter.params.provider.MethodSource)18 Tag (org.junit.jupiter.api.Tag)14 SQLServerColumnEncryptionJavaKeyStoreProvider (com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionJavaKeyStoreProvider)4 SQLException (java.sql.SQLException)4 ClientSecretCredential (com.azure.identity.ClientSecretCredential)2 ClientSecretCredentialBuilder (com.azure.identity.ClientSecretCredentialBuilder)2 AuthenticationContext (com.microsoft.aad.adal4j.AuthenticationContext)2 AuthenticationResult (com.microsoft.aad.adal4j.AuthenticationResult)2 ClientCredential (com.microsoft.aad.adal4j.ClientCredential)2 ISQLServerDataSource (com.microsoft.sqlserver.jdbc.ISQLServerDataSource)2 SQLServerColumnEncryptionKeyStoreProvider (com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionKeyStoreProvider)2 SQLServerConnection (com.microsoft.sqlserver.jdbc.SQLServerConnection)2 SQLServerConnectionPoolDataSource (com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource)2 SQLServerDataSource (com.microsoft.sqlserver.jdbc.SQLServerDataSource)2 SQLServerKeyVaultAuthenticationCallback (com.microsoft.sqlserver.jdbc.SQLServerKeyVaultAuthenticationCallback)2 SQLServerStatement (com.microsoft.sqlserver.jdbc.SQLServerStatement)2 SQLServerXADataSource (com.microsoft.sqlserver.jdbc.SQLServerXADataSource)2