File: DecryptDatabaseTest.java

package info (click to toggle)
derby 10.14.2.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,056 kB
  • sloc: java: 691,961; sql: 42,686; xml: 20,512; sh: 3,373; sed: 96; makefile: 60
file content (406 lines) | stat: -rw-r--r-- 15,386 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*

   Derby - Class
       org.apache.derbyTesting.functionTests.tests.store.DecryptDatabaseTest

   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
package org.apache.derbyTesting.functionTests.tests.store;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import junit.framework.Test;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.Decorator;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.TestConfiguration;

/**
 * Tests that database decryption works, and that various error conditions
 * are detected and dealt with.
 * <p>
 * NOTE: Care must be taken to shut down a database before testing the
 * various connection attributes that apply to cryptographic operations, as
 * they are typically ignored if the database has already been booted.
 */
public class DecryptDatabaseTest
    extends BaseJDBCTestCase {

    private static final String TABLE = "DECRYPTTABLE";
    private static final String BOOTPW = "Thursday";
    private static final String ALREADY_BOOTED = "01J17";
    /** Current encryption algorithm, used when re-encrypting during set up. */
    private static String encryptionAlgorithm;

    public DecryptDatabaseTest(String name) {
        super(name);
    }

    /** Makes sure that the database is encrypted. */
    public void setUp()
            throws Exception {
        super.setUp();

        // Connect.
        try {
            connect(false, BOOTPW, null).close();
        } catch (SQLException sqle) {
            assertSQLState("Did you change the boot password?", "XJ004", sqle);
            // Create the database and save the encryption algorithm.
            getConnection();
            saveEncryptionAlgorithm();
        }

        // Make sure the database is (still) encrypted.
        TestConfiguration tc = getTestConfiguration();
        tc.shutdownDatabase();
        try {
            connect(false, null, null);
            tc.shutdownDatabase();
            // Database has been decrypted. Encrypt it again.
            println("encrypting database (" + encryptionAlgorithm + ")");
            connect(false, BOOTPW, "dataEncryption=true;encryptionAlgorithm=" +
                    encryptionAlgorithm);
            tc.shutdownDatabase();
            connect(false, null, null);
            fail("database encryption failed");
        } catch (SQLException sqle) {
            assertSQLState("XBM06", sqle);
        }
    }

    /** Stashes away the encryption algorithm such that we can re-encrypt. */
    private void saveEncryptionAlgorithm()
            throws SQLException {
        Statement stmt = createStatement();
        ResultSet rs = stmt.executeQuery("values syscs_util." +
                "syscs_get_database_property('encryptionAlgorithm')");
        if (rs.next()) {
            String alg = rs.getString(1);
            if (alg != null && !alg.equals(encryptionAlgorithm)) {
                encryptionAlgorithm = alg;
            }
            assertFalse(rs.next());
        }
        rs.close();
        stmt.close();
    }

    /**
     * Tests that the encrypted database cannot be decrypted without the
     * boot password.
     */
    public void testDecryptDatabaseNegative()
            throws SQLException {
        // Boot with the wrong password, connection attempt should fail.
        try {
            connect(false, "verywrongpw", null);
            fail("connection succeeded with wrong password");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
        }
        // Boot without password, connection attempt should fail.
        try {
            connect(false, null, null);
            fail("connection succeeded without password");
        } catch (SQLException sqle) {
            assertSQLState("XBM06", sqle);
        }

        // Boot with the wrong password, connection attempt should fail.
        try {
            connect(true, "verywrongpw", null);
            fail("decryption succeeded with wrong password");
        } catch (SQLException sqle) {
            assertSQLState("XJ040", sqle);
        }
        // Boot without password, connection attempt should fail.
        try {
            connect(true, null, null);
            fail("decryption succeeded without password");
        } catch (SQLException sqle) {
            assertSQLState("XBM06", sqle);
        }
        try {
            connect(true, null, null);
        } catch (SQLException sqle) {
            assertSQLState("XBM06", sqle);
        }
        
        // Bad setting for decryptDatabase
        try {
            connect( false, BOOTPW, "decryptDatabase=fred" );
            fail( "bad decryptDatabase setting not detected" );
        } catch (SQLException sqle) {
            assertSQLState("XJ05B", sqle);
        }

        connect(false, BOOTPW, null);
    }

    /**
     * Tests that the encrypted database can be decrypted.
     * <p>
     * This is tested by first populating an encrypted database, and then
     * accessing the data in the end by booting the database without a boot
     * password. We verify that connection attempts with incorrect or missing
     * boot passwords before decryption fail.
     */
    public void testDecryptDatabase()
            throws SQLException {
        populateDatabase(true, 1000);
        getTestConfiguration().shutdownDatabase();

        // Connect to decrypt the database.
        Connection con = connect(true, BOOTPW, null);
        JDBC.assertNoWarnings(con.getWarnings());
        Statement stmt = con.createStatement();
        JDBC.assertDrainResults(
                stmt.executeQuery("select * from " + TABLE), 1000);
        stmt.close();
        con.close();
        getTestConfiguration().shutdownDatabase();

        // Boot again without boot password to verify that it works.
        con = connect(false, null, null);
        stmt = con.createStatement();
        JDBC.assertDrainResults(
                stmt.executeQuery("select * from " + TABLE), 1000);
        JDBC.assertFullResultSet(
                stmt.executeQuery("select * from " + TABLE +
                    " where id <= 6 order by id ASC"),
                new String[][] {{"1"},{"2"},{"3"},{"4"},{"5"},{"6"}});
        stmt.close();
        con.close();
    }

    /**
     * Tests that trying to decrypt an already booted database doesn't actually
     * decrypt the database.
     * <p>
     * The internal code isn't set up to deal with decryption/encryption while
     * other activities take place concurrently, so crypto operations are only
     * performed when booting a database.
     */
    public void testDecryptOnBootedDatabase()
            throws SQLException {
        getConnection();

        // These connection attempts should succeed but raise a warning
        // that encryption change is not possible while the database is booted.
        println( "Test warning " + ALREADY_BOOTED );
        vetChangeWarning( connect( false, BOOTPW, "dataEncryption=true" ) );
        vetChangeWarning( connect( false, BOOTPW, "newBootPassword=foo" ) );
        vetChangeWarning( connect( false, BOOTPW, "newEncryptionKey=foo" ) );
        vetChangeWarning( connect( false, BOOTPW, "decryptDatabase=true" ) );
        
        // Connect to decrypt the database. We expect this to fail since the
        // database is already booted. In this case fail means ignored...
        connect(true, BOOTPW, null).close();
        getTestConfiguration().shutdownDatabase();
        try {
            connect(false, null, null);
            fail("decrypted already booted database");
        } catch (SQLException sqle) {
            assertSQLState("XBM06", sqle);
        }
    }
    private void    vetChangeWarning( Connection conn )
        throws SQLException
    {
        assertWarning( conn, ALREADY_BOOTED );
        conn.close();
    }


    /**
     * Tests that asking to decrypt an un-encrypted doesn't fail.
     */
    public void testDecryptUnEncryptedDatabase()
            throws SQLException {
        // First decrypt the database.
        Connection con = connect(true, BOOTPW, null);
        JDBC.assertNoWarnings(con.getWarnings());
        con.close();

        // Shut down the database.
        getTestConfiguration().shutdownDatabase();

        // Specify the decrypt attribute again on the decrypted database.
        // We expect that this request is simply ignored.
        con = connect(true, null, null);
        con.close();
    }

    /**
     * Tests that conflicting connection attributes are detected and flagged.
     */
    public void testConflictingConnectionAttributes()
            throws SQLException {
        // Encryption attributes are typically ignored if the database has
        // already been booted.
        try {
            connect(true, BOOTPW, "newBootPassword=MondayMilk");
            fail("connected with conflicting attributes (newBootPassword)");
        } catch (SQLException sqle) {
            assertSQLState("XJ048", sqle);
        }
        try {
            connect(true, BOOTPW, "newEncryptionKey=6162636465666768");
            fail("connected with conflicting attributes (newEncryptionKey)");
        } catch (SQLException sqle) {
            assertSQLState("XJ048", sqle);
        }
        try {
            connect(true, BOOTPW, "createFrom=./nonexistdb");
            fail("connected with conflicting attributes (createFrom)");
        } catch (SQLException sqle) {
            assertSQLState("XJ081", sqle);
        }
        try {
            connect(true, BOOTPW, "restoreFrom=./nonexistdb");
            fail("connected with conflicting attributes (restoreFrom)");
        } catch (SQLException sqle) {
            assertSQLState("XJ081", sqle);
        }
        try {
            connect(true, BOOTPW, "rollForwardRecoveryFrom=./nonexistdb");
            fail("connected with conflicting attrs (rollForwardRecoveryFrom)");
        } catch (SQLException sqle) {
            assertSQLState("XJ081", sqle);
        }
        // Decrypt the database, then specify both encryption and decryption.
        connect(true, BOOTPW, null);
        getTestConfiguration().shutdownDatabase();
        try {
            connect(true, BOOTPW, "dataEncryption=true");
            fail("connected with conflicting attributes (dataEncryption)");
        } catch (SQLException sqle) {
            assertSQLState("XJ048", sqle);
        }
    }

    /**
     * Attempts to connect to the default database with the specified
     * attributes.
     *
     * @param decrypt whether or not to request database decryption
     * @param bootPassword boot password, may be {@code null}
     * @param otherAttrs additional boot attributes
     * @return A connection.
     * @throws SQLException if the connection cannot be established
     */
    private Connection connect(boolean decrypt,
                               String bootPassword,
                               String otherAttrs)
            throws SQLException {
        DataSource ds = JDBCDataSource.getDataSource();
        JDBCDataSource.clearStringBeanProperty(ds, "connectionAttributes");
        StringBuffer attrs = new StringBuffer();
        if (decrypt) {
            attrs.append("decryptDatabase=true").append(';');
        }
        if (bootPassword != null) {
            attrs.append("bootPassword=").append(bootPassword).append(';');
        }
        if (otherAttrs != null) {
            attrs.append(otherAttrs).append(';');
        }
        if (attrs.length() > 0) {
            JDBCDataSource.setBeanProperty(
                    ds, "connectionAttributes", attrs.toString());
        }
        println("connectionAttributes: " +
                (attrs.length() == 0 ? "<empty>" : attrs.toString()));
        return ds.getConnection();
    }

    /**
     * Populates the database (simple one-column table).
     *
     * @param init if {@code true} the table will be created or reset (the
     *      identity column will also be reset)
     * @param rows number of rows to insert
     */
    private void populateDatabase(boolean init, int rows)
            throws SQLException {
        setAutoCommit(false);
        DatabaseMetaData meta = getConnection().getMetaData();
        ResultSet rs = meta.getTables(null, null, TABLE, null);
        boolean hasTable = rs.next();
        assertFalse(rs.next());
        rs.close();
        if (init) {
            Statement stmt = createStatement();
            if (hasTable) {
                println("deleting rows from table " + TABLE);
                stmt.executeUpdate("delete from " + TABLE);
                println("resetting identity column");
                stmt.executeUpdate("ALTER TABLE " + TABLE + " ALTER COLUMN " +
                        "id RESTART WITH 1");
            } else {
                println("creating table " + TABLE);
                stmt.executeUpdate("create table " + TABLE + " (" +
                        "id int generated always as identity)");
            }
        }
        println("populating database");
        PreparedStatement ps = prepareStatement(
                "insert into " + TABLE + " values (DEFAULT)");
        for (int i=0; i < rows; i++) {
            ps.executeUpdate();
        }
        commit();
        setAutoCommit(true);
    }

    public static Test suite() {
        BaseTestSuite suite = new BaseTestSuite("DecryptDatabaseTest suite");
        suite.addTest(wrapTest());
        suite.addTest(wrapTest("AES/OFB/NoPadding"));
        return suite;
    }

    /** Wraps the default set of tests in the default encryption setup. */
    private static Test wrapTest() {
        return Decorator.encryptedDatabaseBpw(
                          TestConfiguration.embeddedSuite(
                              DecryptDatabaseTest.class),
                          BOOTPW);
    }

    /**
     * Wraps the default set of tests in the specified encryption setup.
     *
     * @param encryptionMethod encryption specification, for instance
     *      "AES/OFB/NoPadding"
     */
    private static Test wrapTest(String encryptionMethod) {
        return Decorator.encryptedDatabaseBpw(
                          TestConfiguration.embeddedSuite(
                              DecryptDatabaseTest.class),
                          encryptionMethod,
                          BOOTPW);
    }
}