forked from confluentinc/schema-registry
/
FieldEncryptionExecutor.java
567 lines (515 loc) · 19.2 KB
/
FieldEncryptionExecutor.java
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*
* Copyright 2022 Confluent Inc.
*
* Licensed 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 io.confluent.kafka.schemaregistry.encryption;
import com.google.crypto.tink.Aead;
import com.google.crypto.tink.KmsClient;
import com.google.protobuf.ByteString;
import io.confluent.dekregistry.client.CachedDekRegistryClient.DekId;
import io.confluent.dekregistry.client.CachedDekRegistryClient.KekId;
import io.confluent.dekregistry.client.DekRegistryClient;
import io.confluent.dekregistry.client.DekRegistryClientFactory;
import io.confluent.dekregistry.client.rest.entities.Dek;
import io.confluent.kafka.schemaregistry.encryption.tink.Cryptor;
import io.confluent.kafka.schemaregistry.encryption.tink.DekFormat;
import io.confluent.dekregistry.client.rest.entities.Kek;
import io.confluent.kafka.schemaregistry.client.rest.entities.RuleMode;
import io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException;
import io.confluent.kafka.schemaregistry.encryption.tink.KmsDriverManager;
import io.confluent.kafka.schemaregistry.rules.FieldRuleExecutor;
import io.confluent.kafka.schemaregistry.rules.FieldTransform;
import io.confluent.kafka.schemaregistry.rules.RuleContext;
import io.confluent.kafka.schemaregistry.rules.RuleContext.FieldContext;
import io.confluent.kafka.schemaregistry.rules.RuleContext.Type;
import io.confluent.kafka.schemaregistry.rules.RuleException;
import io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.kafka.common.config.ConfigException;
/**
* In envelope encryption, a user generates a data encryption key (DEK) locally, encrypts data with
* the DEK, sends the DEK to a KMS to be encrypted (with a key managed by KMS - KEK), and then
* stores the encrypted DEK. At a later point, a user can retrieve the encrypted DEK for the
* encrypted data, use the KEK from KMS to decrypt the DEK, and use the decrypted DEK to decrypt
* the data.
*/
public class FieldEncryptionExecutor implements FieldRuleExecutor {
public static final String TYPE = "ENCRYPT";
public static final String ENCRYPT_KEK_NAME = "encrypt.kek.name";
public static final String ENCRYPT_KMS_KEY_ID = "encrypt.kms.key.id";
public static final String ENCRYPT_KMS_TYPE = "encrypt.kms.type";
public static final String ENCRYPT_DEK_ALGORITHM = "encrypt.dek.algorithm";
public static final String ENCRYPT_PRESERVE_SOURCE = "encrypt.preserve.source";
public static final String KMS_TYPE_SUFFIX = "://";
public static final byte[] EMPTY_AAD = new byte[0];
public static final String CACHE_EXPIRY_SECS = "cache.expiry.secs";
public static final String CACHE_SIZE = "cache.size";
private Map<DekFormat, Cryptor> cryptors;
private Map<String, ?> configs;
private Boolean preserveSource;
private int cacheExpirySecs = -1;
private int cacheSize = 10000;
private DekRegistryClient client;
public FieldEncryptionExecutor() {
}
public boolean isPreserveSource() {
return Boolean.TRUE.equals(preserveSource);
}
@Override
public boolean addOriginalConfigs() {
return true;
}
@Override
public void configure(Map<String, ?> configs) {
this.configs = configs;
Object preserveSourceConfig = configs.get(ENCRYPT_PRESERVE_SOURCE);
if (preserveSourceConfig != null) {
this.preserveSource = Boolean.parseBoolean(preserveSourceConfig.toString());
}
Object cacheExpirySecsConfig = configs.get(CACHE_EXPIRY_SECS);
if (cacheExpirySecsConfig != null) {
try {
this.cacheExpirySecs = Integer.parseInt(cacheExpirySecsConfig.toString());
} catch (NumberFormatException e) {
throw new ConfigException("Cannot parse " + CACHE_EXPIRY_SECS);
}
}
Object cacheSizeConfig = configs.get(CACHE_SIZE);
if (cacheSizeConfig != null) {
try {
this.cacheSize = Integer.parseInt(cacheSizeConfig.toString());
} catch (NumberFormatException e) {
throw new ConfigException("Cannot parse " + CACHE_SIZE);
}
}
Object url = configs.get(AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG);
if (url == null) {
throw new ConfigException("Missing schema registry url!");
}
List<String> baseUrls = Arrays.asList(url.toString().split("\\s*,\\s*"));
this.client = DekRegistryClientFactory.newClient(
baseUrls, cacheSize, cacheExpirySecs, configs, Collections.emptyMap());
this.cryptors = new ConcurrentHashMap<>();
}
@Override
public String type() {
return TYPE;
}
@Override
public FieldTransform newTransform(RuleContext ctx) throws RuleException {
FieldTransform transform = new FieldEncryptionExecutorTransform();
transform.init(ctx);
return transform;
}
@Override
public Object preTransformMessage(RuleContext ctx, FieldTransform transform, Object message)
throws RuleException {
if (isPreserveSource()) {
try {
// We use the target schema
message = ctx.target().copyMessage(message);
} catch (IOException e) {
throw new RuleException("Could not copy source message", e);
}
}
return message;
}
private Cryptor getCryptor(RuleContext ctx) {
String algorithm = ctx.getParameter(ENCRYPT_DEK_ALGORITHM);
DekFormat dekFormat = algorithm != null
? DekFormat.valueOf(algorithm)
: DekFormat.AES256_GCM;
return getCryptor(dekFormat);
}
private Cryptor getCryptor(DekFormat dekFormat) {
return cryptors.computeIfAbsent(dekFormat, k -> {
try {
return new Cryptor(dekFormat);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("Invalid format " + dekFormat, e);
}
});
}
// Visible for testing
public Map<DekFormat, Cryptor> getCryptors() {
return cryptors;
}
private static byte[] toBytes(Type type, Object obj) {
switch (type) {
case BYTES:
if (obj instanceof ByteBuffer) {
return ((ByteBuffer) obj).array();
} else if (obj instanceof ByteString) {
return ((ByteString) obj).toByteArray();
} else if (obj instanceof byte[]) {
return (byte[]) obj;
} else {
throw new IllegalArgumentException(
"Unrecognized bytes object of type: " + obj.getClass().getName());
}
case STRING:
return obj.toString().getBytes(StandardCharsets.UTF_8);
default:
return null;
}
}
private static Object toObject(Type type, byte[] bytes) {
switch (type) {
case BYTES:
return bytes;
case STRING:
return new String(bytes, StandardCharsets.UTF_8);
default:
return null;
}
}
@Override
public void close() throws RuleException {
if (client != null) {
try {
client.close();
} catch (IOException e) {
throw new RuleException(e);
}
}
}
class FieldEncryptionExecutorTransform implements FieldTransform {
private Cryptor cryptor;
private String kekName;
private KekInfo kek;
public void init(RuleContext ctx) throws RuleException {
cryptor = getCryptor(ctx);
kekName = getKekName(ctx);
kek = getKek(ctx, kekName);
if (FieldEncryptionExecutor.this.preserveSource == null) {
String preserveValueConfig = ctx.getParameter(ENCRYPT_PRESERVE_SOURCE);
if (preserveValueConfig != null) {
FieldEncryptionExecutor.this.preserveSource = Boolean.parseBoolean(preserveValueConfig);
}
}
}
protected String getKekName(RuleContext ctx) throws RuleException {
String name = ctx.getParameter(ENCRYPT_KEK_NAME);
if (name == null) {
throw new RuleException("No kek name found");
}
int length = name.length();
if (length == 0) {
throw new RuleException("Empty kek name");
}
char first = name.charAt(0);
if (!(Character.isLetter(first) || first == '_')) {
throw new RuleException("Illegal initial character in kek name: " + name);
}
for (int i = 1; i < length; i++) {
char c = name.charAt(i);
if (!(Character.isLetterOrDigit(c) || c == '_' || c == '-')) {
throw new RuleException("Illegal character in kek name: " + name);
}
}
return name;
}
protected KekInfo getKek(RuleContext ctx, String kekName) throws RuleException {
KekId kekId = new KekId(kekName, ctx.ruleMode() == RuleMode.READ);
String kmsType = ctx.getParameter(ENCRYPT_KMS_TYPE);
String kmsKeyId = ctx.getParameter(ENCRYPT_KMS_KEY_ID);
KekInfo kek = retrieveKekFromRegistry(ctx, kekId);
if (kek == null) {
if (ctx.ruleMode() == RuleMode.READ) {
throw new RuleException("No kek found for " + kekName + " during consume");
}
if (kmsType == null) {
throw new RuleException("No kms type found for " + kekName + " during produce");
}
if (kmsKeyId == null) {
throw new RuleException("No kms key id found for " + kekName + " during produce");
}
kek = new KekInfo(kmsType, kmsKeyId, false);
kek = storeKekToRegistry(ctx, kekId, kek);
if (kek == null) {
// Handle conflicts (409)
kek = retrieveKekFromRegistry(ctx, kekId);
}
if (kek == null) {
throw new RuleException("No kek found for " + kekName + " during produce");
}
}
if (kmsType != null && !kmsType.equals(kek.getKmsType())) {
throw new RuleException("Found " + kekName + " with different kms type: "
+ kek.getKmsType());
}
if (kmsKeyId != null && !kmsKeyId.equals(kek.getKmsKeyId())) {
throw new RuleException("Found " + kekName + " with different kms key id: "
+ kek.getKmsKeyId());
}
return kek;
}
private KekInfo retrieveKekFromRegistry(RuleContext ctx, KekId key) throws RuleException {
try {
Kek kek = client.getKek(key.getName(), key.isLookupDeleted());
if (kek == null) {
return null;
}
return new KekInfo(kek.getKmsType(), kek.getKmsKeyId(), kek.isShared());
} catch (RestClientException e) {
if (e.getStatus() == 404) {
return null;
}
throw new RuleException("Could not get kek", e);
} catch (IOException e) {
throw new RuleException("Could not get kek", e);
}
}
private KekInfo storeKekToRegistry(RuleContext ctx, KekId key, KekInfo kekInfo)
throws RuleException {
try {
Kek kek = client.createKek(
key.getName(), kekInfo.getKmsType(), kekInfo.getKmsKeyId(),
null, null, kekInfo.isShared());
return new KekInfo(kek.getKmsType(), kek.getKmsKeyId(), kek.isShared());
} catch (RestClientException e) {
if (e.getStatus() == 409) {
return null;
}
throw new RuleException("Could not store kek", e);
} catch (IOException e) {
throw new RuleException("Could not store kek", e);
}
}
protected DekInfo getDek(RuleContext ctx, String kekName, KekInfo kek)
throws RuleException, GeneralSecurityException {
DekId dekId = new DekId(
kekName, ctx.subject(), cryptor.getDekFormat(), ctx.ruleMode() == RuleMode.READ);
Aead aead = null;
DekInfo dek = retrieveDekFromRegistry(ctx, dekId);
if (dek == null) {
if (ctx.ruleMode() == RuleMode.READ) {
throw new RuleException("No dek found for " + kekName + " during consume");
}
if (!kek.isShared()) {
aead = getAead(configs, kek);
// Generate new dek
byte[] rawDek = getCryptor(dekId.getDekFormat()).generateKey();
byte[] encryptedDek = aead.encrypt(rawDek, EMPTY_AAD);
dek = new DekInfo(rawDek, encryptedDek);
}
// dek may be passed as null if kek is shared
dek = storeDekToRegistry(ctx, dekId, dek);
if (dek == null) {
// Handle conflicts (409)
dek = retrieveDekFromRegistry(ctx, dekId);
}
if (dek == null) {
throw new RuleException("No dek found for " + kekName + " during produce");
}
}
if (dek.getRawDek() == null) {
if (aead == null) {
aead = getAead(configs, kek);
}
byte[] rawDek = aead.decrypt(dek.getEncryptedDek(), EMPTY_AAD);
dek.setRawDek(rawDek);
}
return dek;
}
private DekInfo retrieveDekFromRegistry(RuleContext ctx, DekId key) throws RuleException {
try {
Dek dek = client.getDek(
key.getKekName(), key.getSubject(), key.getDekFormat(), key.isLookupDeleted());
if (dek == null) {
return null;
}
byte[] rawDek = dek.getKeyMaterial() != null
? Base64.getDecoder().decode(toBytes(Type.STRING, dek.getKeyMaterial()))
: null;
byte[] encryptedDek = dek.getEncryptedKeyMaterial() != null
? Base64.getDecoder().decode(toBytes(Type.STRING, dek.getEncryptedKeyMaterial()))
: null;
return encryptedDek != null ? new DekInfo(rawDek, encryptedDek) : null;
} catch (RestClientException e) {
if (e.getStatus() == 404) {
return null;
}
throw new RuleException("Could not get dek", e);
} catch (IOException e) {
throw new RuleException("Could not get dek", e);
}
}
private DekInfo storeDekToRegistry(RuleContext ctx, DekId key, DekInfo dekInfo)
throws RuleException {
try {
String encryptedDekStr = dekInfo != null && dekInfo.getEncryptedDek() != null
? (String) toObject(Type.STRING, Base64.getEncoder().encode(dekInfo.getEncryptedDek()))
: null;
Dek dek = client.createDek(
key.getKekName(), key.getSubject(), key.getDekFormat(), encryptedDekStr);
byte[] rawDek = dek.getKeyMaterial() != null
? Base64.getDecoder().decode(toBytes(Type.STRING, dek.getKeyMaterial()))
: null;
byte[] encryptedDek = dek.getEncryptedKeyMaterial() != null
? Base64.getDecoder().decode(toBytes(Type.STRING, dek.getEncryptedKeyMaterial()))
: null;
return new DekInfo(rawDek, encryptedDek);
} catch (RestClientException e) {
if (e.getStatus() == 409) {
return null;
}
throw new RuleException("Could not store dek", e);
} catch (IOException e) {
throw new RuleException("Could not store dek", e);
}
}
public Object transform(RuleContext ctx, FieldContext fieldCtx, Object fieldValue)
throws RuleException {
try {
if (fieldValue == null) {
return null;
}
DekInfo dek = getDek(ctx, kekName, kek);
byte[] plaintext;
byte[] ciphertext;
Object result;
switch (ctx.ruleMode()) {
case WRITE:
plaintext = toBytes(fieldCtx.getType(), fieldValue);
if (plaintext == null) {
throw new RuleException(
"Type '" + fieldCtx.getType() + "' not supported for encryption");
}
ciphertext = cryptor.encrypt(dek.getRawDek(), plaintext, EMPTY_AAD);
if (fieldCtx.getType() == Type.STRING) {
ciphertext = Base64.getEncoder().encode(ciphertext);
}
return toObject(fieldCtx.getType(), ciphertext);
case READ:
ciphertext = toBytes(fieldCtx.getType(), fieldValue);
if (ciphertext == null) {
return fieldValue;
}
if (fieldCtx.getType() == Type.STRING) {
ciphertext = Base64.getDecoder().decode(ciphertext);
}
plaintext = cryptor.decrypt(dek.getRawDek(), ciphertext, EMPTY_AAD);
return toObject(fieldCtx.getType(), plaintext);
default:
throw new IllegalArgumentException("Unsupported rule mode " + ctx.ruleMode());
}
} catch (Exception e) {
throw new RuleException(e);
}
}
@Override
public void close() {
}
}
private static Aead getAead(Map<String, ?> configs, KekInfo kek)
throws GeneralSecurityException, RuleException {
String kekUrl = kek.getKmsType() + KMS_TYPE_SUFFIX + kek.getKmsKeyId();
KmsClient kmsClient = getKmsClient(configs, kekUrl);
if (kmsClient == null) {
throw new RuleException("No kms client found for " + kekUrl);
}
return kmsClient.getAead(kekUrl);
}
private static KmsClient getKmsClient(Map<String, ?> configs, String kekUrl)
throws GeneralSecurityException {
try {
return KmsDriverManager.getDriver(kekUrl).getKmsClient(kekUrl);
} catch (GeneralSecurityException e) {
return KmsDriverManager.getDriver(kekUrl).registerKmsClient(configs, Optional.of(kekUrl));
}
}
static class KekInfo {
private final String kmsType;
private final String kmsKeyId;
private final boolean shared;
public KekInfo(String kmsType, String kmsKeyId, boolean shared) {
this.kmsType = kmsType;
this.kmsKeyId = kmsKeyId;
this.shared = shared;
}
public String getKmsType() {
return kmsType;
}
public String getKmsKeyId() {
return kmsKeyId;
}
public boolean isShared() {
return shared;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
KekInfo kek = (KekInfo) o;
return shared == kek.shared
&& Objects.equals(kmsType, kek.kmsType)
&& Objects.equals(kmsKeyId, kek.kmsKeyId);
}
@Override
public int hashCode() {
return Objects.hash(kmsType, kmsKeyId, shared);
}
}
static class DekInfo {
private byte[] rawDek;
private final byte[] encryptedDek;
public DekInfo(byte[] rawDek, byte[] encryptedDek) {
this.rawDek = rawDek;
this.encryptedDek = encryptedDek;
}
public byte[] getRawDek() {
return rawDek;
}
public void setRawDek(byte[] rawDek) {
this.rawDek = rawDek;
}
public byte[] getEncryptedDek() {
return encryptedDek;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DekInfo dek = (DekInfo) o;
return Arrays.equals(rawDek, dek.rawDek)
&& Arrays.equals(encryptedDek, dek.encryptedDek);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(rawDek);
result = 31 * result + Arrays.hashCode(encryptedDek);
return result;
}
}
}