Debian Codegraph @

src/main/org/h2/tools/ChangeFileEncryption.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.tools;
7
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.io.OutputStream;
11 import java.nio.channels.Channels;
12 import java.nio.channels.FileChannel;
13 import java.sql.SQLException;
14 import java.util.ArrayList;
15 import java.util.concurrent.TimeUnit;
16 import org.h2.engine.Constants;
17 import org.h2.message.DbException;
18 import org.h2.mvstore.MVStore;
19 import org.h2.store.FileLister;
20 import org.h2.store.fs.FilePath;
21 import org.h2.store.fs.FileUtils;
22 import org.h2.store.fs.encrypt.FileEncrypt;
23 import org.h2.store.fs.encrypt.FilePathEncrypt;
24 import org.h2.util.Tool;
25
26 /**
27 * Allows changing the database file encryption password or algorithm.
28 *
29 * This tool can not be used to change a password of a user.
30 * The database must be closed before using this tool.
31 */
32 public class ChangeFileEncryption extends Tool {
33
34 private String directory;
35 private String cipherType;
36 private byte[] decryptKey;
37 private byte[] encryptKey;
38
39 /**
40 * Options are case sensitive.
41 * <table>
42 * <caption>Supported options</caption>
43 * <tr><td>[-help] or [-?]</td>
44 * <td>Print the list of options</td></tr>
45 * <tr><td>[-cipher type]</td>
46 * <td>The encryption type (AES)</td></tr>
47 * <tr><td>[-dir &lt;dir&gt;]</td>
48 * <td>The database directory (default: .)</td></tr>
49 * <tr><td>[-db &lt;database&gt;]</td>
50 * <td>Database name (all databases if not set)</td></tr>
51 * <tr><td>[-decrypt &lt;pwd&gt;]</td>
52 * <td>The decryption password (if not set: not yet encrypted)</td></tr>
53 * <tr><td>[-encrypt &lt;pwd&gt;]</td>
54 * <td>The encryption password (if not set: do not encrypt)</td></tr>
55 * <tr><td>[-quiet]</td>
56 * <td>Do not print progress information</td></tr>
57 * </table>
58 *
59 * @param args the command line arguments
60 */
61 public static void main(String... args) {
62 try {
63 new ChangeFileEncryption().runTool(args);
64 } catch (SQLException ex) {
65 ex.printStackTrace(System.err);
66 System.exit(1);
67 }
68 }
69
70 @Override
71 public void runTool(String... args) throws SQLException {
72 String dir = ".";
73 String cipher = null;
74 char[] decryptPassword = null;
75 char[] encryptPassword = null;
76 String db = null;
77 boolean quiet = false;
78 for (int i = 0; args != null && i < args.length; i++) {
79 String arg = args[i];
80 if (arg.equals("-dir")) {
81 dir = args[++i];
82 } else if (arg.equals("-cipher")) {
83 cipher = args[++i];
84 } else if (arg.equals("-db")) {
85 db = args[++i];
86 } else if (arg.equals("-decrypt")) {
87 decryptPassword = args[++i].toCharArray();
88 } else if (arg.equals("-encrypt")) {
89 encryptPassword = args[++i].toCharArray();
90 } else if (arg.equals("-quiet")) {
91 quiet = true;
92 } else if (arg.equals("-help") || arg.equals("-?")) {
93 showUsage();
94 return;
95 } else {
96 showUsageAndThrowUnsupportedOption(arg);
97 }
98 }
99 if ((encryptPassword == null && decryptPassword == null) || cipher == null) {
100 showUsage();
101 throw new SQLException(
102 "Encryption or decryption password not set, or cipher not set");
103 }
104 try {
105 process(dir, db, cipher, decryptPassword, encryptPassword, quiet);
106 } catch (Exception e) {
107 throw DbException.toSQLException(e);
108 }
109 }
110
111 /**
112 * Changes the password for a database. The passwords must be supplied as
113 * char arrays and are cleaned in this method. The database must be closed
114 * before calling this method.
115 *
116 * @param dir the directory (. for the current directory)
117 * @param db the database name (null for all databases)
118 * @param cipher the cipher (AES)
119 * @param decryptPassword the decryption password as a char array
120 * @param encryptPassword the encryption password as a char array
121 * @param quiet don't print progress information
122 * @throws SQLException on failure
123 */
124 public static void execute(String dir, String db, String cipher,
125 char[] decryptPassword, char[] encryptPassword, boolean quiet)
126 throws SQLException {
127 try {
128 new ChangeFileEncryption().process(dir, db, cipher,
129 decryptPassword, encryptPassword, quiet);
130 } catch (Exception e) {
131 throw DbException.toSQLException(e);
132 }
133 }
134
135 private void process(String dir, String db, String cipher,
136 char[] decryptPassword, char[] encryptPassword, boolean quiet)
137 throws SQLException {
138 dir = FileLister.getDir(dir);
139 ChangeFileEncryption change = new ChangeFileEncryption();
140 if (encryptPassword != null) {
141 for (char c : encryptPassword) {
142 if (c == ' ') {
143 throw new SQLException("The file password may not contain spaces");
144 }
145 }
146 change.encryptKey = FilePathEncrypt.getPasswordBytes(encryptPassword);
147 }
148 if (decryptPassword != null) {
149 change.decryptKey = FilePathEncrypt.getPasswordBytes(decryptPassword);
150 }
151 change.out = out;
152 change.directory = dir;
153 change.cipherType = cipher;
154
155 ArrayList<String> files = FileLister.getDatabaseFiles(dir, db, true);
156 FileLister.tryUnlockDatabase(files, "encryption");
157 files = FileLister.getDatabaseFiles(dir, db, false);
158 if (files.isEmpty() && !quiet) {
159 printNoDatabaseFilesFound(dir, db);
160 }
161 // first, test only if the file can be renamed
162 // (to find errors with locked files early)
163 for (String fileName : files) {
164 String temp = dir + "/temp.db";
165 FileUtils.delete(temp);
166 FileUtils.move(fileName, temp);
167 FileUtils.move(temp, fileName);
168 }
169 // if this worked, the operation will (hopefully) be successful
170 // TODO changeFileEncryption: this is a workaround!
171 // make the operation atomic (all files or none)
172 for (String fileName : files) {
173 // don't process a lob directory, just the files in the directory.
174 if (!FileUtils.isDirectory(fileName)) {
175 change.process(fileName, quiet, decryptPassword);
176 }
177 }
178 }
179
180 private void process(String fileName, boolean quiet, char[] decryptPassword) throws SQLException {
181 if (fileName.endsWith(Constants.SUFFIX_MV_FILE)) {
182 try {
183 copyMvStore(fileName, quiet, decryptPassword);
184 } catch (IOException e) {
185 throw DbException.convertIOException(e,
186 "Error encrypting / decrypting file " + fileName);
187 }
188 return;
189 }
190 }
191
192 private void copyMvStore(String fileName, boolean quiet, char[] decryptPassword) throws IOException, SQLException {
193 if (FileUtils.isDirectory(fileName)) {
194 return;
195 }
196 // check that we have the right encryption key
197 try {
198 final MVStore source = new MVStore.Builder().
199 fileName(fileName).
200 readOnly().
201 encryptionKey(decryptPassword).
202 open();
203 source.close();
204 } catch (IllegalStateException ex) {
205 throw new SQLException("error decrypting file " + fileName, ex);
206 }
207
208 String temp = directory + "/temp.db";
209 try (FileChannel fileIn = getFileChannel(fileName, "r", decryptKey)){
210 try (InputStream inStream = Channels.newInputStream(fileIn)) {
211 FileUtils.delete(temp);
212 try (OutputStream outStream = Channels.newOutputStream(getFileChannel(temp, "rw", encryptKey))) {
213 final byte[] buffer = new byte[4 * 1024];
214 long remaining = fileIn.size();
215 long total = remaining;
216 long time = System.nanoTime();
217 while (remaining > 0) {
218 if (!quiet && System.nanoTime() - time > TimeUnit.SECONDS.toNanos(1)) {
219 out.println(fileName + ": " + (100 - 100 * remaining / total) + "%");
220 time = System.nanoTime();
221 }
222 int len = (int) Math.min(buffer.length, remaining);
223 len = inStream.read(buffer, 0, len);
224 outStream.write(buffer, 0, len);
225 remaining -= len;
226 }
227 }
228 }
229 }
230 FileUtils.delete(fileName);
231 FileUtils.move(temp, fileName);
232 }
233
234 private static FileChannel getFileChannel(String fileName, String r,
235 byte[] decryptKey) throws IOException {
236 FileChannel fileIn = FilePath.get(fileName).open(r);
237 if (decryptKey != null) {
238 fileIn = new FileEncrypt(fileName, decryptKey,
239 fileIn);
240 }
241 return fileIn;
242 }
243
244 }