-
Notifications
You must be signed in to change notification settings - Fork 507
Expand file tree
/
Copy pathInMemoryKeystore.java
More file actions
334 lines (297 loc) · 10.8 KB
/
InMemoryKeystore.java
File metadata and controls
334 lines (297 loc) · 10.8 KB
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
/*
* 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.orc;
import org.apache.orc.impl.HadoopShims;
import org.apache.orc.impl.KeyProvider;
import org.apache.orc.impl.LocalKey;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
/**
* This is an in-memory implementation of {@link KeyProvider}.
* <p>
* The primary use of this class is for when the user doesn't have a
* Hadoop KMS running and wishes to use encryption. It is also useful for
* testing.
* <p>
* The local keys for this class are encrypted/decrypted using the cipher
* in CBC/NoPadding mode and a constant IV. Since the key is random, the
* constant IV is not a problem.
* <p>
* This class is not thread safe.
* @since 1.5.0
*/
public class InMemoryKeystore implements KeyProvider {
/**
* Support AES 256 ?
*/
public static final boolean SUPPORTS_AES_256;
static {
try {
SUPPORTS_AES_256 = Cipher.getMaxAllowedKeyLength("AES") >= 256;
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Unknown algorithm", e);
}
}
private final Random random;
/**
* A map that stores the 'keyName@version'
* and 'metadata + material' mapping.
*/
private final TreeMap<String, KeyVersion> keys = new TreeMap<>();
/**
* A map from the keyName (without version) to the currentVersion.
*/
private final Map<String, Integer> currentVersion = new HashMap<>();
/**
* Create a new InMemoryKeystore.
*/
public InMemoryKeystore() {
this(new SecureRandom());
}
/**
* Create an InMemoryKeystore with the given random generator.
* Except for testing, this must be a SecureRandom.
*/
public InMemoryKeystore(Random random) {
this.random = random;
}
/**
* Build a version string from a basename and version number. Converts
* "/aaa/bbb" and 3 to "/aaa/bbb@3".
*
* @param name the basename of the key
* @param version the version of the key
* @return the versionName of the key.
*/
private static String buildVersionName(final String name,
final int version) {
return name + "@" + version;
}
/**
* Get the list of key names from the key provider.
*
* @return a list of key names
*/
@Override
public List<String> getKeyNames() {
return new ArrayList<>(currentVersion.keySet());
}
/**
* Get the current metadata for a given key. This is used when encrypting
* new data.
*
* @param keyName the name of a key
* @return metadata for the current version of the key
*/
@Override
public HadoopShims.KeyMetadata getCurrentKeyVersion(final String keyName) {
String versionName = buildVersionName(keyName, currentVersion.get(keyName));
KeyVersion keyVersion = keys.get(versionName);
if (keyVersion == null) {
throw new IllegalArgumentException("Unknown key " + keyName);
}
return keys.get(versionName);
}
/**
* Create a local key for the given key version.
*
* @param key the master key version
* @return the local key's material
*/
@Override
public LocalKey createLocalKey(final HadoopShims.KeyMetadata key) {
final String keyVersion = buildVersionName(key.getKeyName(), key.getVersion());
final KeyVersion secret = keys.get(keyVersion);
if (secret == null) {
throw new IllegalArgumentException("Unknown key " + key);
}
final EncryptionAlgorithm algorithm = secret.getAlgorithm();
byte[] encryptedKey = new byte[algorithm.keyLength()];
random.nextBytes(encryptedKey);
byte[] iv = Arrays.copyOf(encryptedKey, algorithm.getIvLength());
Cipher localCipher = algorithm.createCipher();
try {
localCipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(secret.getMaterial(),
algorithm.getAlgorithm()), new IvParameterSpec(iv));
} catch (final InvalidKeyException e) {
throw new IllegalStateException(
"ORC bad encryption key for " + keyVersion, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new IllegalStateException(
"ORC bad encryption parameter for " + keyVersion, e);
}
try {
byte[] decryptedKey = localCipher.doFinal(encryptedKey);
return new LocalKey(algorithm, decryptedKey, encryptedKey);
} catch (final IllegalBlockSizeException e) {
throw new IllegalStateException(
"ORC bad block size for " + keyVersion, e);
} catch (final BadPaddingException e) {
throw new IllegalStateException(
"ORC bad padding for " + keyVersion, e);
}
}
/**
* Create a local key for the given key version and initialization vector.
* Given a probabilistically unique iv, it will generate a unique key
* with the master key at the specified version. This allows the encryption
* to use this local key for the encryption and decryption without ever
* having access to the master key.
* <p>
* This uses KeyProviderCryptoExtension.decryptEncryptedKey with a fixed key
* of the appropriate length.
*
* @param key the master key version
* @param encryptedKey the unique initialization vector
* @return the local key's material
*/
@Override
public Key decryptLocalKey(HadoopShims.KeyMetadata key,
byte[] encryptedKey) {
final String keyVersion = buildVersionName(key.getKeyName(), key.getVersion());
final KeyVersion secret = keys.get(keyVersion);
if (secret == null) {
return null;
}
final EncryptionAlgorithm algorithm = secret.getAlgorithm();
byte[] iv = Arrays.copyOf(encryptedKey, algorithm.getIvLength());
Cipher localCipher = algorithm.createCipher();
try {
localCipher.init(Cipher.DECRYPT_MODE,
new SecretKeySpec(secret.getMaterial(),
algorithm.getAlgorithm()), new IvParameterSpec(iv));
} catch (final InvalidKeyException e) {
throw new IllegalStateException(
"ORC bad encryption key for " + keyVersion, e);
} catch (final InvalidAlgorithmParameterException e) {
throw new IllegalStateException(
"ORC bad encryption parameter for " + keyVersion, e);
}
try {
byte[] decryptedKey = localCipher.doFinal(encryptedKey);
return new SecretKeySpec(decryptedKey, algorithm.getAlgorithm());
} catch (final IllegalBlockSizeException e) {
throw new IllegalStateException(
"ORC bad block size for " + keyVersion, e);
} catch (final BadPaddingException e) {
throw new IllegalStateException(
"ORC bad padding for " + keyVersion, e);
}
}
@Override
public HadoopShims.KeyProviderKind getKind() {
return HadoopShims.KeyProviderKind.HADOOP;
}
/**
* Function that takes care of adding a new key.<br>
* A new key can be added only if:
* <ul>
* <li>This is a new key and no prior key version exist.</li>
* <li>If the key exists (has versions), then the new version to be added should be greater than
* the version that already exists.</li>
* </ul>
*
* @param keyName Name of the key to be added
* @param algorithm Algorithm used
* @param masterKey Master key
* @return this
*/
public InMemoryKeystore addKey(String keyName, EncryptionAlgorithm algorithm,
byte[] masterKey) throws IOException {
return addKey(keyName, 0, algorithm, masterKey);
}
/**
* Function that takes care of adding a new key.<br>
* A new key can be added only if:
* <ul>
* <li>This is a new key and no prior key version exist.</li>
* <li>If the key exists (has versions), then the new version to be added should be greater than
* the version that already exists.</li>
* </ul>
*
* @param keyName Name of the key to be added
* @param version Key Version
* @param algorithm Algorithm used
* @param masterKey Master key
* @return this
*/
public InMemoryKeystore addKey(String keyName, int version,
EncryptionAlgorithm algorithm,
byte[] masterKey) throws IOException {
/* Test weather platform supports the algorithm */
if (!SUPPORTS_AES_256 && (algorithm != EncryptionAlgorithm.AES_CTR_128)) {
algorithm = EncryptionAlgorithm.AES_CTR_128;
}
final byte[] buffer = new byte[algorithm.keyLength()];
if (algorithm.keyLength() > masterKey.length) {
System.arraycopy(masterKey, 0, buffer, 0, masterKey.length);
/* fill with zeros */
Arrays.fill(buffer, masterKey.length, buffer.length - 1, (byte) 0);
} else {
System.arraycopy(masterKey, 0, buffer, 0, algorithm.keyLength());
}
final KeyVersion key = new KeyVersion(keyName, version, algorithm,
buffer);
/* Check whether the key is already present and has a smaller version */
Integer currentKeyVersion = currentVersion.get(keyName);
if (currentKeyVersion != null && currentKeyVersion >= version) {
throw new IOException(String
.format("Key %s with equal or higher version %d already exists",
keyName, version));
}
keys.put(buildVersionName(keyName, version), key);
currentVersion.put(keyName, version);
return this;
}
/**
* This class contains the meta-data and the material for the key.
*/
static class KeyVersion extends HadoopShims.KeyMetadata {
private final byte[] material;
KeyVersion(final String keyName, final int version,
final EncryptionAlgorithm algorithm, final byte[] material) {
super(keyName, version, algorithm);
this.material = material;
}
/**
* Get the material for the key
*
* @return the material
*/
private byte[] getMaterial() {
return material;
}
}
}