Debian Codegraph @

src/main/org/h2/security/CipherFactory.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.security;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.io.OutputStream;
13 import java.net.InetAddress;
14 import java.net.InetSocketAddress;
15 import java.net.ServerSocket;
16 import java.net.Socket;
17 import java.security.KeyFactory;
18 import java.security.KeyStore;
19 import java.security.PrivateKey;
20 import java.security.Security;
21 import java.security.cert.Certificate;
22 import java.security.cert.CertificateFactory;
23 import java.security.spec.PKCS8EncodedKeySpec;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.HashSet;
27 import java.util.LinkedHashSet;
28 import java.util.LinkedList;
29 import java.util.List;
30 import java.util.Properties;
31
32 import javax.net.ServerSocketFactory;
33 import javax.net.ssl.SSLServerSocket;
34 import javax.net.ssl.SSLServerSocketFactory;
35 import javax.net.ssl.SSLSocket;
36 import javax.net.ssl.SSLSocketFactory;
37
38 import org.h2.api.ErrorCode;
39 import org.h2.engine.SysProperties;
40 import org.h2.message.DbException;
41 import org.h2.mvstore.DataUtils;
42 import org.h2.store.fs.FileUtils;
43 import org.h2.util.IOUtils;
44 import org.h2.util.StringUtils;
45
46 /**
47 * A factory to create new block cipher objects.
48 */
49 public class CipherFactory {
50
51 /**
52 * The default password to use for the .h2.keystore file
53 */
54 public static final String KEYSTORE_PASSWORD =
55 "h2pass";
56
57 /**
58 * The security property which can prevent anonymous TLS connections.
59 * Introduced into Java 6, 7, 8 in updates from July 2015.
60 */
61 public static final String LEGACY_ALGORITHMS_SECURITY_KEY =
62 "jdk.tls.legacyAlgorithms";
63
64 /**
65 * The value of {@value #LEGACY_ALGORITHMS_SECURITY_KEY} security
66 * property at the time of class initialization.
67 * Null if it is not set.
68 */
69 public static final String DEFAULT_LEGACY_ALGORITHMS = getLegacyAlgorithmsSilently();
70
71 private static final String KEYSTORE =
72 "~/.h2.keystore";
73 private static final String KEYSTORE_KEY =
74 "javax.net.ssl.keyStore";
75 private static final String KEYSTORE_PASSWORD_KEY =
76 "javax.net.ssl.keyStorePassword";
77
78
79 private CipherFactory() {
80 // utility class
81 }
82
83 /**
84 * Get a new block cipher object for the given algorithm.
85 *
86 * @param algorithm the algorithm
87 * @return a new cipher object
88 */
89 public static BlockCipher getBlockCipher(String algorithm) {
90 if ("XTEA".equalsIgnoreCase(algorithm)) {
91 return new XTEA();
92 } else if ("AES".equalsIgnoreCase(algorithm)) {
93 return new AES();
94 } else if ("FOG".equalsIgnoreCase(algorithm)) {
95 return new Fog();
96 }
97 throw DbException.get(ErrorCode.UNSUPPORTED_CIPHER, algorithm);
98 }
99
100 /**
101 * Create a secure client socket that is connected to the given address and
102 * port.
103 *
104 * @param address the address to connect to
105 * @param port the port
106 * @return the socket
107 * @throws IOException on failure
108 */
109 public static Socket createSocket(InetAddress address, int port)
110 throws IOException {
111 setKeystore();
112 SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
113 SSLSocket secureSocket = (SSLSocket) f.createSocket();
114 secureSocket.connect(new InetSocketAddress(address, port),
115 SysProperties.SOCKET_CONNECT_TIMEOUT);
116 secureSocket.setEnabledProtocols(
117 disableSSL(secureSocket.getEnabledProtocols()));
118 if (SysProperties.ENABLE_ANONYMOUS_TLS) {
119 String[] list = enableAnonymous(
120 secureSocket.getEnabledCipherSuites(),
121 secureSocket.getSupportedCipherSuites());
122 secureSocket.setEnabledCipherSuites(list);
123 }
124 return secureSocket;
125 }
126
127 /**
128 * Create a secure server socket. If a bind address is specified, the
129 * socket is only bound to this address.
130 * If h2.enableAnonymousTLS is true, an attempt is made to modify
131 * the security property jdk.tls.legacyAlgorithms (in newer JVMs) to allow
132 * anonymous TLS. This system change is effectively permanent for the
133 * lifetime of the JVM.
134 * @see #removeAnonFromLegacyAlgorithms()
135 *
136 * @param port the port to listen on
137 * @param bindAddress the address to bind to, or null to bind to all
138 * addresses
139 * @return the server socket
140 * @throws IOException on failure
141 */
142 public static ServerSocket createServerSocket(int port,
143 InetAddress bindAddress) throws IOException {
144 if (SysProperties.ENABLE_ANONYMOUS_TLS) {
145 removeAnonFromLegacyAlgorithms();
146 }
147 setKeystore();
148 ServerSocketFactory f = SSLServerSocketFactory.getDefault();
149 SSLServerSocket secureSocket;
150 if (bindAddress == null) {
151 secureSocket = (SSLServerSocket) f.createServerSocket(port);
152 } else {
153 secureSocket = (SSLServerSocket) f.createServerSocket(port, 0, bindAddress);
154 }
155 secureSocket.setEnabledProtocols(
156 disableSSL(secureSocket.getEnabledProtocols()));
157 if (SysProperties.ENABLE_ANONYMOUS_TLS) {
158 String[] list = enableAnonymous(
159 secureSocket.getEnabledCipherSuites(),
160 secureSocket.getSupportedCipherSuites());
161 secureSocket.setEnabledCipherSuites(list);
162 }
163 return secureSocket;
164 }
165
166 /**
167 * Removes DH_anon and ECDH_anon from a comma separated list of ciphers.
168 * Only the first occurrence is removed.
169 * If there is nothing to remove, returns the reference to the argument.
170 * @param list a list of names separated by commas (and spaces)
171 * @return a new string without DH_anon and ECDH_anon items,
172 * or the original if none were found
173 */
174 public static String removeDhAnonFromCommaSeparatedList(String list) {
175 if (list == null) {
176 return list;
177 }
178 List<String> algorithms = new LinkedList<>(Arrays.asList(list.split("\\s*,\\s*")));
179 boolean dhAnonRemoved = algorithms.remove("DH_anon");
180 boolean ecdhAnonRemoved = algorithms.remove("ECDH_anon");
181 if (dhAnonRemoved || ecdhAnonRemoved) {
182 String string = Arrays.toString(algorithms.toArray(new String[algorithms.size()]));
183 return (!algorithms.isEmpty()) ? string.substring(1, string.length() - 1): "";
184 }
185 return list;
186 }
187
188 /**
189 * Attempts to weaken the security properties to allow anonymous TLS.
190 * New JREs would not choose an anonymous cipher suite in a TLS handshake
191 * if server-side security property
192 * {@value #LEGACY_ALGORITHMS_SECURITY_KEY}
193 * were not modified from the default value.
194 * <p>
195 * NOTE: In current (as of 2016) default implementations of JSSE which use
196 * this security property, the value is permanently cached inside the
197 * ServerHandshake class upon its first use.
198 * Therefore the modification accomplished by this method has to be done
199 * before the first use of a server SSL socket.
200 * Later changes to this property will not have any effect on server socket
201 * behavior.
202 */
203 public static synchronized void removeAnonFromLegacyAlgorithms() {
204 String legacyOriginal = getLegacyAlgorithmsSilently();
205 if (legacyOriginal == null) {
206 return;
207 }
208 String legacyNew = removeDhAnonFromCommaSeparatedList(legacyOriginal);
209 if (!legacyOriginal.equals(legacyNew)) {
210 setLegacyAlgorithmsSilently(legacyNew);
211 }
212 }
213
214 /**
215 * Attempts to resets the security property to the default value.
216 * The default value of {@value #LEGACY_ALGORITHMS_SECURITY_KEY} was
217 * obtained at time of class initialization.
218 * <p>
219 * NOTE: Resetting the property might not have any effect on server
220 * socket behavior.
221 * @see #removeAnonFromLegacyAlgorithms()
222 */
223 public static synchronized void resetDefaultLegacyAlgorithms() {
224 setLegacyAlgorithmsSilently(DEFAULT_LEGACY_ALGORITHMS);
225 }
226
227 /**
228 * Returns the security property {@value #LEGACY_ALGORITHMS_SECURITY_KEY}.
229 * Ignores security exceptions.
230 *
231 * @return the value of the security property, or null if not set
232 * or not accessible
233 */
234 public static String getLegacyAlgorithmsSilently() {
235 String defaultLegacyAlgorithms = null;
236 try {
237 defaultLegacyAlgorithms = Security.getProperty(LEGACY_ALGORITHMS_SECURITY_KEY);
238 } catch (SecurityException e) {
239 // ignore
240 }
241 return defaultLegacyAlgorithms;
242 }
243
244 private static void setLegacyAlgorithmsSilently(String legacyAlgorithms) {
245 if (legacyAlgorithms == null) {
246 return;
247 }
248 try {
249 Security.setProperty(LEGACY_ALGORITHMS_SECURITY_KEY, legacyAlgorithms);
250 } catch (SecurityException e) {
251 // ignore
252 }
253 }
254
255 private static byte[] getKeyStoreBytes(KeyStore store, String password)
256 throws IOException {
257 ByteArrayOutputStream bout = new ByteArrayOutputStream();
258 try {
259 store.store(bout, password.toCharArray());
260 } catch (Exception e) {
261 throw DataUtils.convertToIOException(e);
262 }
263 return bout.toByteArray();
264 }
265
266 /**
267 * Get the keystore object using the given password.
268 *
269 * @param password the keystore password
270 * @return the keystore
271 * @throws IOException on failure
272 */
273 public static KeyStore getKeyStore(String password) throws IOException {
274 try {
275 // The following source code can be re-generated
276 // if you have a keystore file.
277 // This code is (hopefully) more Java version independent
278 // than using keystores directly. See also:
279 // https://bugs.openjdk.java.net/browse/JDK-4887561
280 // (1.4.2 cannot read keystore written with 1.4.1)
281 // --- generated code start ---
282
283 KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
284
285 store.load(null, password.toCharArray());
286 KeyFactory keyFactory = KeyFactory.getInstance("RSA");
287 store.load(null, password.toCharArray());
288 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
289 StringUtils.convertHexToBytes(
290 "30820277020100300d06092a864886f70d010101" +
291 "0500048202613082025d02010002818100dc0a13" +
292 "c602b7141110eade2f051b54777b060d0f74e6a1" +
293 "10f9cce81159f271ebc88d8e8aa1f743b505fc2e" +
294 "7dfe38d33b8d3f64d1b363d1af4d877833897954" +
295 "cbaec2fa384c22a415498cf306bb07ac09b76b00" +
296 "1cd68bf77ea0a628f5101959cf2993a9c23dbee7" +
297 "9b19305977f8715ae78d023471194cc900b231ee" +
298 "cb0aaea98d02030100010281810099aa4ff4d0a0" +
299 "9a5af0bd953cb10c4d08c3d98df565664ac5582e" +
300 "494314d5c3c92dddedd5d316a32a206be4ec0846" +
301 "16fe57be15e27cad111aa3c21fa79e32258c6ca8" +
302 "430afc69eddd52d3b751b37da6b6860910b94653" +
303 "192c0db1d02abcfd6ce14c01f238eec7c20bd3bb" +
304 "750940004bacba2880349a9494d10e139ecb2355" +
305 "d101024100ffdc3defd9c05a2d377ef6019fa62b" +
306 "3fbd5b0020a04cc8533bca730e1f6fcf5dfceea1" +
307 "b044fbe17d9eababfbc7d955edad6bc60f9be826" +
308 "ad2c22ba77d19a9f65024100dc28d43fdbbc9385" +
309 "2cc3567093157702bc16f156f709fb7db0d9eec0" +
310 "28f41fd0edcd17224c866e66be1744141fb724a1" +
311 "0fd741c8a96afdd9141b36d67fff6309024077b1" +
312 "cddbde0f69604bdcfe33263fb36ddf24aa3b9922" +
313 "327915b890f8a36648295d0139ecdf68c245652c" +
314 "4489c6257b58744fbdd961834a4cab201801a3b1" +
315 "e52d024100b17142e8991d1b350a0802624759d4" +
316 "8ae2b8071a158ff91fabeb6a8f7c328e762143dc" +
317 "726b8529f42b1fab6220d1c676fdc27ba5d44e84" +
318 "7c72c52064afd351a902407c6e23fe35bcfcd1a6" +
319 "62aa82a2aa725fcece311644d5b6e3894853fd4c" +
320 "e9fe78218c957b1ff03fc9e5ef8ffeb6bd58235f" +
321 "6a215c97d354fdace7e781e4a63e8b"));
322 PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
323 Certificate[] certs = { CertificateFactory
324 .getInstance("X.509")
325 .generateCertificate(
326 new ByteArrayInputStream(
327 StringUtils.convertHexToBytes(
328 "3082018b3081f502044295ce6b300d06092a8648" +
329 "86f70d0101040500300d310b3009060355040313" +
330 "024832301e170d3035303532363133323630335a" +
331 "170d3337303933303036353734375a300d310b30" +
332 "0906035504031302483230819f300d06092a8648" +
333 "86f70d010101050003818d0030818902818100dc" +
334 "0a13c602b7141110eade2f051b54777b060d0f74" +
335 "e6a110f9cce81159f271ebc88d8e8aa1f743b505" +
336 "fc2e7dfe38d33b8d3f64d1b363d1af4d87783389" +
337 "7954cbaec2fa384c22a415498cf306bb07ac09b7" +
338 "6b001cd68bf77ea0a628f5101959cf2993a9c23d" +
339 "bee79b19305977f8715ae78d023471194cc900b2" +
340 "31eecb0aaea98d0203010001300d06092a864886" +
341 "f70d01010405000381810083f4401a279453701b" +
342 "ef9a7681a5b8b24f153f7d18c7c892133d97bd5f" +
343 "13736be7505290a445a7d5ceb75522403e509751" +
344 "5cd966ded6351ff60d5193de34cd36e5cb04d380" +
345 "398e66286f99923fd92296645fd4ada45844d194" +
346 "dfd815e6cd57f385c117be982809028bba1116c8" +
347 "5740b3d27a55b1a0948bf291ddba44bed337b9"))), };
348 store.setKeyEntry("h2", privateKey, password.toCharArray(), certs);
349 // --- generated code end ---
350 return store;
351 } catch (Exception e) {
352 throw DataUtils.convertToIOException(e);
353 }
354 }
355
356 private static void setKeystore() throws IOException {
357 Properties p = System.getProperties();
358 if (p.getProperty(KEYSTORE_KEY) == null) {
359 String fileName = KEYSTORE;
360 byte[] data = getKeyStoreBytes(getKeyStore(
361 KEYSTORE_PASSWORD), KEYSTORE_PASSWORD);
362 boolean needWrite = true;
363 if (FileUtils.exists(fileName) && FileUtils.size(fileName) == data.length) {
364 // don't need to overwrite the file if it did not change
365 InputStream fin = FileUtils.newInputStream(fileName);
366 byte[] now = IOUtils.readBytesAndClose(fin, 0);
367 if (now != null && Arrays.equals(data, now)) {
368 needWrite = false;
369 }
370 }
371 if (needWrite) {
372 try {
373 OutputStream out = FileUtils.newOutputStream(fileName, false);
374 out.write(data);
375 out.close();
376 } catch (Exception e) {
377 throw DataUtils.convertToIOException(e);
378 }
379 }
380 String absolutePath = FileUtils.toRealPath(fileName);
381 System.setProperty(KEYSTORE_KEY, absolutePath);
382 }
383 if (p.getProperty(KEYSTORE_PASSWORD_KEY) == null) {
384 System.setProperty(KEYSTORE_PASSWORD_KEY, KEYSTORE_PASSWORD);
385 }
386 }
387
388 private static String[] enableAnonymous(String[] enabled, String[] supported) {
389 LinkedHashSet<String> set = new LinkedHashSet<>();
390 for (String x : supported) {
391 if (!x.startsWith("SSL") && x.contains("_anon_") &&
392 (x.contains("_AES_") || x.contains("_3DES_")) && x.contains("_SHA")) {
393 set.add(x);
394 }
395 }
396 Collections.addAll(set, enabled);
397 return set.toArray(new String[0]);
398 }
399
400 private static String[] disableSSL(String[] enabled) {
401 HashSet<String> set = new HashSet<>();
402 for (String x : enabled) {
403 if (!x.startsWith("SSL")) {
404 set.add(x);
405 }
406 }
407 return set.toArray(new String[0]);
408 }
409
410 }