-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsecurity.rs
More file actions
488 lines (446 loc) · 18.7 KB
/
Copy pathsecurity.rs
File metadata and controls
488 lines (446 loc) · 18.7 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
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
use std::collections::BTreeMap;
use snafu::{ResultExt, Snafu};
use stackable_operator::{
builder::{
self,
pod::{
PodBuilder,
container::ContainerBuilder,
volume::{
SecretFormat, SecretOperatorVolumeSourceBuilder,
SecretOperatorVolumeSourceBuilderError, VolumeBuilder,
},
},
},
crd::listener,
k8s_openapi::{
api::core::v1::{ContainerPort, Probe, ServicePort, TCPSocketAction},
apimachinery::pkg::util::intstr::IntOrString,
},
shared::time::Duration,
};
use crate::crd::{
DruidRole, STACKABLE_TRUST_STORE_PASSWORD,
authentication::{self, AuthenticationClassesResolved},
v1alpha1,
};
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("failed to process authentication class"))]
InvalidAuthenticationClassConfiguration { source: authentication::Error },
#[snafu(display("failed to build the Secret operator Volume"))]
SecretVolumeBuild {
source: SecretOperatorVolumeSourceBuilderError,
},
#[snafu(display("failed to add needed volume"))]
AddVolume { source: builder::pod::Error },
#[snafu(display("failed to add needed volumeMount"))]
AddVolumeMount {
source: builder::pod::container::Error,
},
}
/// Helper struct combining TLS settings for server and internal tls with the resolved AuthenticationClasses
pub struct DruidTlsSecurity {
auth_classes: AuthenticationClassesResolved,
server_and_internal_secret_class: Option<String>,
}
// Ports
const ENABLE_PLAINTEXT_PORT: &str = "druid.enablePlaintextPort";
const PLAINTEXT_PORT: &str = "druid.plaintextPort";
const ENABLE_TLS_PORT: &str = "druid.enableTlsPort";
const TLS_PORT: &str = "druid.tlsPort";
// Port names
pub const PLAINTEXT_PORT_NAME: &str = "http";
pub const TLS_PORT_NAME: &str = "https";
// Client side (Druid) TLS
const CLIENT_HTTPS_KEY_STORE_PATH: &str = "druid.client.https.keyStorePath";
const CLIENT_HTTPS_KEY_STORE_TYPE: &str = "druid.client.https.keyStoreType";
const CLIENT_HTTPS_KEY_STORE_PASSWORD: &str = "druid.client.https.keyStorePassword";
const CLIENT_HTTPS_TRUST_STORE_PATH: &str = "druid.client.https.trustStorePath";
const CLIENT_HTTPS_TRUST_STORE_TYPE: &str = "druid.client.https.trustStoreType";
const CLIENT_HTTPS_TRUST_STORE_PASSWORD: &str = "druid.client.https.trustStorePassword";
const CLIENT_HTTPS_CERT_ALIAS: &str = "druid.client.https.certAlias";
const CLIENT_HTTPS_VALIDATE_HOST_NAMES: &str = "druid.client.https.validateHostnames";
const CLIENT_HTTPS_KEY_MANAGER_PASSWORD: &str = "druid.client.https.keyManagerPassword";
// Server side TLS
const SERVER_HTTPS_KEY_STORE_PATH: &str = "druid.server.https.keyStorePath";
const SERVER_HTTPS_KEY_STORE_TYPE: &str = "druid.server.https.keyStoreType";
const SERVER_HTTPS_KEY_STORE_PASSWORD: &str = "druid.server.https.keyStorePassword";
const SERVER_HTTPS_TRUST_STORE_PATH: &str = "druid.server.https.trustStorePath";
const SERVER_HTTPS_TRUST_STORE_TYPE: &str = "druid.server.https.trustStoreType";
const SERVER_HTTPS_TRUST_STORE_PASSWORD: &str = "druid.server.https.trustStorePassword";
const SERVER_HTTPS_CERT_ALIAS: &str = "druid.server.https.certAlias";
const SERVER_HTTPS_VALIDATE_HOST_NAMES: &str = "druid.server.https.validateHostnames";
const SERVER_HTTPS_KEY_MANAGER_PASSWORD: &str = "druid.server.https.keyManagerPassword";
const SERVER_HTTPS_REQUIRE_CLIENT_CERTIFICATE: &str = "druid.server.https.requireClientCertificate";
/// The alias of the certificate in the keystore used for TLS stuff.
/// All secret-op generated keystores have one entry with the alias "1".
/// (side node: I think technically they don't have an alias and the JVm counts them, but not sure)
const TLS_ALIAS_NAME: &str = "1";
pub const AUTH_TRUST_STORE_PATH: &str = "druid.auth.basic.ssl.trustStorePath";
pub const AUTH_TRUST_STORE_TYPE: &str = "druid.auth.basic.ssl.trustStoreType";
pub const AUTH_TRUST_STORE_PASSWORD: &str = "druid.auth.basic.ssl.trustStorePassword";
// Misc TLS
pub const TLS_STORE_PASSWORD: &str = "changeit";
pub const TLS_STORE_TYPE: &str = "pkcs12";
// directories
const STACKABLE_MOUNT_TLS_DIR: &str = "/stackable/mount_tls";
pub const STACKABLE_TLS_DIR: &str = "/stackable/tls";
// volume names
const TLS_VOLUME_NAME: &str = "tls";
const TLS_MOUNT_VOLUME_NAME: &str = "tls-mount";
pub const INTERNAL_INITIAL_CLIENT_PASSWORD_ENV: &str = "INTERNAL_INITIAL_CLIENT_PASSWORD";
// It seems this needs to be the same password for Druid to work, so we re-use the existing env variable from above.
pub const ESCALATOR_INTERNAL_CLIENT_PASSWORD_ENV: &str = INTERNAL_INITIAL_CLIENT_PASSWORD_ENV;
impl DruidTlsSecurity {
#[cfg(test)]
pub fn new(
auth_classes: &AuthenticationClassesResolved,
server_and_internal_secret_class: Option<String>,
) -> Self {
Self {
auth_classes: auth_classes.clone(),
server_and_internal_secret_class,
}
}
/// Create a `DruidTlsSecurity` struct from the Druid custom resource and resolve
/// all provided `AuthenticationClass` references.
pub fn new_from_druid_cluster(
druid: &v1alpha1::DruidCluster,
auth_classes: &AuthenticationClassesResolved,
) -> Self {
DruidTlsSecurity {
auth_classes: auth_classes.clone(),
server_and_internal_secret_class: druid
.spec
.cluster_config
.tls
.as_ref()
.and_then(|tls| tls.server_and_internal_secret_class.clone()),
}
}
/// Check if TLS encryption is enabled. This could be due to:
///
/// - A provided server `SecretClass`
/// - A provided client `AuthenticationClass` using tls
///
/// This affects init container commands, Druid configuration, volume mounts
/// and the Druid client port
pub fn tls_enabled(&self) -> bool {
// TODO: This must be adapted if other authentication methods are supported and require TLS
self.auth_classes.tls_authentication_enabled()
|| self.tls_server_and_internal_secret_class().is_some()
}
/// Retrieve an optional TLS secret class for external client -> server and server <-> server communications.
pub fn tls_server_and_internal_secret_class(&self) -> Option<&str> {
self.server_and_internal_secret_class.as_deref()
}
pub fn container_ports(&self, role: &DruidRole) -> Vec<ContainerPort> {
self.exposed_ports(role)
.into_iter()
.map(|(name, val)| ContainerPort {
name: Some(name),
container_port: val.into(),
protocol: Some("TCP".to_string()),
..ContainerPort::default()
})
.collect()
}
pub fn service_ports(&self, role: &DruidRole) -> Vec<ServicePort> {
self.exposed_ports(role)
.into_iter()
.map(|(name, val)| ServicePort {
name: Some(name),
port: val.into(),
protocol: Some("TCP".to_string()),
..ServicePort::default()
})
.collect()
}
pub fn listener_ports(
&self,
role: &DruidRole,
) -> Option<Vec<listener::v1alpha1::ListenerPort>> {
let listener_ports = self
.exposed_ports(role)
.into_iter()
.map(|(name, val)| listener::v1alpha1::ListenerPort {
name,
port: val.into(),
protocol: Some("TCP".to_string()),
})
.collect();
Some(listener_ports)
}
fn exposed_ports(&self, role: &DruidRole) -> Vec<(String, u16)> {
if self.tls_enabled() {
vec![(TLS_PORT_NAME.to_string(), role.get_https_port())]
} else {
vec![(PLAINTEXT_PORT_NAME.to_string(), role.get_http_port())]
}
}
/// Adds required tls volume mounts to image and product container builders
/// Adds required tls volumes to pod builder
pub fn add_tls_volume_and_volume_mounts(
&self,
prepare: &mut ContainerBuilder,
druid: &mut ContainerBuilder,
pod: &mut PodBuilder,
requested_secret_lifetime: &Duration,
listener_scope: Option<String>,
) -> Result<(), Error> {
// `ResolvedAuthenticationClasses::validate` already checked that the tls AuthenticationClass
// uses the same SecretClass as the Druid server itself.
if let Some(secret_class) = &self.server_and_internal_secret_class {
let mut secret_volume_source_builder =
SecretOperatorVolumeSourceBuilder::new(secret_class);
secret_volume_source_builder
.with_pod_scope()
.with_format(SecretFormat::TlsPkcs12)
.with_tls_pkcs12_password(TLS_STORE_PASSWORD)
.with_auto_tls_cert_lifetime(*requested_secret_lifetime);
if let Some(listener_scope) = &listener_scope {
secret_volume_source_builder.with_listener_volume_scope(listener_scope);
}
pod.add_volume(
VolumeBuilder::new(TLS_MOUNT_VOLUME_NAME)
.ephemeral(
secret_volume_source_builder
.build()
.context(SecretVolumeBuildSnafu)?,
)
.build(),
)
.context(AddVolumeSnafu)?;
prepare
.add_volume_mount(TLS_MOUNT_VOLUME_NAME, STACKABLE_MOUNT_TLS_DIR)
.context(AddVolumeMountSnafu)?;
druid
.add_volume_mount(TLS_MOUNT_VOLUME_NAME, STACKABLE_MOUNT_TLS_DIR)
.context(AddVolumeMountSnafu)?;
pod.add_volume(
VolumeBuilder::new(TLS_VOLUME_NAME)
.with_empty_dir(Option::<&str>::None, None)
.build(),
)
.context(AddVolumeSnafu)?;
prepare
.add_volume_mount(TLS_VOLUME_NAME, STACKABLE_TLS_DIR)
.context(AddVolumeMountSnafu)?;
druid
.add_volume_mount(TLS_VOLUME_NAME, STACKABLE_TLS_DIR)
.context(AddVolumeMountSnafu)?;
}
Ok(())
}
fn add_tls_port_config_properties(
&self,
config: &mut BTreeMap<String, Option<String>>,
role: &DruidRole,
) {
// no secure communication
if !self.tls_enabled() {
config.insert(ENABLE_PLAINTEXT_PORT.to_string(), Some("true".to_string()));
config.insert(ENABLE_TLS_PORT.to_string(), Some("false".to_string()));
config.insert(
PLAINTEXT_PORT.to_string(),
Some(role.get_http_port().to_string()),
);
}
// only allow secure communication
else {
config.insert(ENABLE_PLAINTEXT_PORT.to_string(), Some("false".to_string()));
config.insert(ENABLE_TLS_PORT.to_string(), Some("true".to_string()));
config.insert(
TLS_PORT.to_string(),
Some(role.get_https_port().to_string()),
);
}
}
/// Add required TLS ports, trust/key store properties
pub fn add_tls_config_properties(
&self,
config: &mut BTreeMap<String, Option<String>>,
role: &DruidRole,
) {
self.add_tls_port_config_properties(config, role);
if self.tls_enabled() {
Self::add_tls_encryption_config_properties(config, STACKABLE_TLS_DIR, TLS_ALIAS_NAME);
}
if self.auth_classes.tls_authentication_enabled() {
Self::add_tls_auth_config_properties(config, STACKABLE_TLS_DIR, TLS_ALIAS_NAME);
}
}
fn add_tls_encryption_config_properties(
config: &mut BTreeMap<String, Option<String>>,
store_directory: &str,
store_alias: &str,
) {
// We need a truststore in addition to a keystore here, because server and internal tls
// can only be enabled/disabled together
config.insert(
CLIENT_HTTPS_TRUST_STORE_PATH.to_string(),
Some(format!("{}/truststore.p12", store_directory)),
);
config.insert(
CLIENT_HTTPS_TRUST_STORE_TYPE.to_string(),
Some(TLS_STORE_TYPE.to_string()),
);
config.insert(
CLIENT_HTTPS_TRUST_STORE_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
config.insert(
SERVER_HTTPS_KEY_STORE_PATH.to_string(),
Some(format!("{}/keystore.p12", store_directory)),
);
config.insert(
SERVER_HTTPS_KEY_STORE_TYPE.to_string(),
Some(TLS_STORE_TYPE.to_string()),
);
config.insert(
SERVER_HTTPS_KEY_STORE_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
config.insert(
SERVER_HTTPS_CERT_ALIAS.to_string(),
Some(store_alias.to_string()),
);
// We also need to configure the truststore for authentication related stuff,
// such as verifying the LDAP server
config.insert(
AUTH_TRUST_STORE_PATH.to_string(),
Some(format!("{}/truststore.p12", store_directory)),
);
config.insert(
AUTH_TRUST_STORE_TYPE.to_string(),
Some(TLS_STORE_TYPE.to_string()),
);
config.insert(
AUTH_TRUST_STORE_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
}
fn add_tls_auth_config_properties(
config: &mut BTreeMap<String, Option<String>>,
store_directory: &str,
store_alias: &str,
) {
config.insert(
CLIENT_HTTPS_KEY_STORE_PATH.to_string(),
Some(format!("{store_directory}/keystore.p12")),
);
config.insert(
CLIENT_HTTPS_KEY_STORE_TYPE.to_string(),
Some(TLS_STORE_TYPE.to_string()),
);
config.insert(
CLIENT_HTTPS_KEY_STORE_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
// This is required because PKCS12 does not use any key passwords but it will
// be checked and would lead to an exception:
// java.security.UnrecoverableKeyException: Get Key failed: null
// Must be set to the store password or we get a bad padding exception:
// javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
config.insert(
CLIENT_HTTPS_KEY_MANAGER_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
config.insert(
CLIENT_HTTPS_CERT_ALIAS.to_string(),
Some(store_alias.to_string()),
);
// FIXME: https://github.com/stackabletech/druid-operator/issues/372
// This is required because the server will send its pod ip which is not in the SANs of the certificates
config.insert(
CLIENT_HTTPS_VALIDATE_HOST_NAMES.to_string(),
Some("false".to_string()),
);
// This will enforce the client to authenticate itself
config.insert(
SERVER_HTTPS_REQUIRE_CLIENT_CERTIFICATE.to_string(),
Some("true".to_string()),
);
config.insert(
SERVER_HTTPS_TRUST_STORE_PATH.to_string(),
Some(format!("{store_directory}/truststore.p12")),
);
config.insert(
SERVER_HTTPS_TRUST_STORE_TYPE.to_string(),
Some(TLS_STORE_TYPE.to_string()),
);
config.insert(
SERVER_HTTPS_TRUST_STORE_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
// This is required because PKCS12 does not use any key passwords but it will
// be checked and would lead to an exception:
// java.security.UnrecoverableKeyException: Get Key failed: null
// Must be set to the store password or we get a bad padding exception:
// javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
config.insert(
SERVER_HTTPS_KEY_MANAGER_PASSWORD.to_string(),
Some(TLS_STORE_PASSWORD.to_string()),
);
// FIXME: https://github.com/stackabletech/druid-operator/issues/372
// This is required because the client will send its pod ip which is not in the SANs of the certificates
config.insert(
SERVER_HTTPS_VALIDATE_HOST_NAMES.to_string(),
Some("false".to_string()),
);
}
pub fn build_tls_key_stores_cmd(&self) -> Vec<String> {
if !self.tls_enabled() {
return vec![];
}
vec![
// FIXME: *Technically* we should only add the system truststore in case any webPki usage is detected,
// wether that's in S3, LDAP, OIDC, FTE or whatnot.
format!(
"cert-tools generate-pkcs12-truststore --pkcs12 '{STACKABLE_MOUNT_TLS_DIR}/truststore.p12:{TLS_STORE_PASSWORD}' --pem /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem --out {STACKABLE_TLS_DIR}/truststore.p12 --out-password '{TLS_STORE_PASSWORD}'"
),
// We can copy the keystore as is.
format!("cp {STACKABLE_MOUNT_TLS_DIR}/keystore.p12 {STACKABLE_TLS_DIR}/keystore.p12"),
]
}
pub fn get_tcp_socket_probe(
&self,
initial_delay_seconds: i32,
period_seconds: i32,
failure_threshold: i32,
timeout_seconds: i32,
) -> Probe {
let port = if self.tls_enabled() {
IntOrString::String(TLS_PORT_NAME.to_string())
} else {
IntOrString::String(PLAINTEXT_PORT_NAME.to_string())
};
Probe {
tcp_socket: Some(TCPSocketAction {
port,
..Default::default()
}),
initial_delay_seconds: Some(initial_delay_seconds),
period_seconds: Some(period_seconds),
failure_threshold: Some(failure_threshold),
timeout_seconds: Some(timeout_seconds),
..Default::default()
}
}
}
/// Generate a bash command to add a CA to a truststore
pub fn add_cert_to_trust_store_cmd(
cert_file: &str,
destination_directory: &str,
store_password: &str,
) -> String {
let truststore = format!("{destination_directory}/truststore.p12");
format!(
"cert-tools generate-pkcs12-truststore --pkcs12 {truststore}:{store_password} --pem {cert_file} --out {truststore} --out-password {store_password}"
)
}
/// Generate a bash command to add a CA to the truststore that is passed to the JVM
pub fn add_cert_to_jvm_trust_store_cmd(cert_file: &str) -> String {
add_cert_to_trust_store_cmd(cert_file, "/stackable", STACKABLE_TRUST_STORE_PASSWORD)
}