krabka-security 0.7.0

TLS, SASL, SCRAM, OAuth, and Kerberos security utilities for Krabka
Documentation
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
//! `sspi`-rs-backed implementations of [`GssAcceptor`] and [`GssInitiator`].
//!
//! Both the acceptor and the initiator authenticate from a keytab. The
//! acceptor uses the service key to decrypt incoming AP-REQs. The initiator
//! uses the client principal's long-term key, supplied through
//! [`sspi::KeytabIdentity`], to drive the AS/TGS exchange with no password.
use std::sync::Mutex;

use krabka_units::{Time, convert::TimeExt as _};
use sspi::{
    BufferType, ClientRequestFlags, CredentialUse, Credentials, CredentialsBuffers,
    DataRepresentation, EncryptionFlags, Kerberos, KerberosConfig, KeytabIdentity, Secret,
    SecurityBuffer, SecurityBufferRef, SecurityStatus, ServerRequestFlags, Sspi, SspiImpl,
    Username,
    kerberos::{DEFAULT_ENCRYPTION_TYPE, ServerProperties},
};

use super::{
    AcceptStep, GssAcceptor, GssError, GssInitiator, InitStep,
    keytab::{ENCTYPE_AES256_CTS_HMAC_SHA1_96, load_service_key, load_service_keys},
};

/// Default KDC URL for when `SSPI_KDC_URL` is unset.
///
/// The accept path does not touch the network, but `KerberosConfig::new` needs
/// a URL string.
const DEFAULT_KDC_URL: &str = "tcp://localhost:88";

fn kdc_url_from_env() -> String {
    std::env::var("SSPI_KDC_URL").unwrap_or_else(|_| DEFAULT_KDC_URL.to_string())
}

/// Map an sspi context error to [`GssError::Context`].
fn ctx_err(e: impl std::fmt::Display) -> GssError {
    GssError::Context(e.to_string())
}

/// Map an sspi wrap/unwrap error to [`GssError::Wrap`].
fn wrap_err(e: impl std::fmt::Display) -> GssError {
    GssError::Wrap(e.to_string())
}

fn keytab_username(principal: &str) -> Result<Username, GssError> {
    if let Some((account, realm)) = principal.rsplit_once('@') {
        Username::new_down_level_logon_name(account, realm).map_err(ctx_err)
    } else {
        Username::parse(principal).map_err(ctx_err)
    }
}

/// GSS wrap (`encrypt_message`) with confidentiality disabled, per RFC 4752.
///
/// This function returns `token || data`.
fn gss_wrap(ctx: &mut Kerberos, plaintext: &[u8]) -> Result<Vec<u8>, GssError> {
    let trailer_len = ctx
        .query_context_sizes()
        .map_err(wrap_err)?
        .security_trailer as usize;
    let mut token = vec![0u8; trailer_len];
    let mut data = plaintext.to_vec();
    let mut wrap_buf = [
        SecurityBufferRef::token_buf(token.as_mut_slice()),
        SecurityBufferRef::data_buf(data.as_mut_slice()),
    ];
    ctx.encrypt_message(EncryptionFlags::WRAP_NO_ENCRYPT, &mut wrap_buf)
        .map_err(wrap_err)?;
    let mut out = wrap_buf[0].data().to_vec();
    out.extend_from_slice(wrap_buf[1].data());
    Ok(out)
}

/// GSS unwrap (`decrypt_message`). Input is the `token || data` stream.
fn gss_unwrap(ctx: &mut Kerberos, token_bytes: &[u8]) -> Result<Vec<u8>, GssError> {
    let mut stream = token_bytes.to_vec();
    let mut unwrap_buf = [
        SecurityBufferRef::stream_buf(stream.as_mut_slice()),
        SecurityBufferRef::data_buf(&mut []),
    ];
    ctx.decrypt_message(&mut unwrap_buf).map_err(wrap_err)?;
    Ok(unwrap_buf[1].data().to_vec())
}

/// Whether a status means "context established" and not "another round trip".
fn is_established(status: SecurityStatus) -> bool {
    matches!(
        status,
        SecurityStatus::Ok | SecurityStatus::CompleteNeeded | SecurityStatus::CompleteAndContinue
    )
}

/// Server-side GSSAPI acceptor backed by sspi + a keytab-extracted service key.
pub struct SspiAcceptor {
    server: Mutex<Kerberos>,
}

impl SspiAcceptor {
    /// Build an acceptor from a keytab file and the SPN's first component.
    ///
    /// This function reads `keytab_path` and extracts the highest-kvno aes256
    /// key for `service_name`. It then reconstructs the SPN components and
    /// builds the sspi server context.
    ///
    /// # Errors
    ///
    /// Returns [`GssError::Keytab`] if the keytab cannot be read or has no
    /// matching key, or [`GssError::Context`] if sspi rejects the server config.
    // GSSAPI server-context establishment from a keytab. skip_all keeps the
    // extracted service-key material (loaded into locals) out of span fields;
    // only the non-sensitive mechanism + service name are recorded. `err`
    // surfaces keytab/context failures (Debug).
    #[tracing::instrument(
        level = "info",
        skip_all,
        fields(mechanism = "GSSAPI", service = %service_name),
        err
    )]
    pub fn new(
        keytab_path: &str,
        service_name: &str,
        max_time_skew: Time,
    ) -> Result<Self, GssError> {
        let bytes = std::fs::read(keytab_path)
            .map_err(|e| GssError::Keytab(format!("reading {keytab_path}: {e}")))?;
        // A keytab may hold keys for several host SPNs of this service (e.g.
        // `kafka/localhost` and `kafka/host.docker.internal`). Load them all so
        // the acceptor honors whichever SPN an incoming ticket names, matching
        // the JVM broker.
        let mut keys = load_service_keys(&bytes, service_name, ENCTYPE_AES256_CTS_HMAC_SHA1_96)
            .map_err(|e| GssError::Keytab(e.to_string()))?;
        if keys.is_empty() {
            return Err(GssError::Keytab(format!(
                "no aes256 key for service '{service_name}' in keytab {keytab_path}"
            )));
        }
        let primary = keys.remove(0);

        // sname = SPN components WITHOUT realm, e.g. ["kafka", "localhost"].
        let primary_sname: Vec<&str> = primary.components.iter().map(String::as_str).collect();
        let mut server_properties = ServerProperties::new(
            &primary_sname,
            None,
            max_time_skew.to_std(),
            Some(Secret::new(primary.key)),
        )
        .map_err(ctx_err)?;
        for extra in keys {
            let sname: Vec<&str> = extra.components.iter().map(String::as_str).collect();
            server_properties
                .add_service_key(&sname, Secret::new(extra.key))
                .map_err(ctx_err)?;
        }

        let server = Kerberos::new_server_from_config(
            KerberosConfig::new(&kdc_url_from_env(), "krabka-broker".to_string()),
            server_properties,
        )
        .map_err(ctx_err)?;

        Ok(Self {
            server: Mutex::new(server),
        })
    }
}

impl GssAcceptor for SspiAcceptor {
    fn accept(&mut self, client_token: &[u8]) -> Result<AcceptStep, GssError> {
        let server = self.server.get_mut().expect("acceptor mutex poisoned");

        let mut input = vec![SecurityBuffer::new(
            client_token.to_vec(),
            BufferType::Token,
        )];
        let mut output = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];
        let mut cred_handle: Option<CredentialsBuffers> = None;

        let builder = server
            .accept_security_context()
            .with_credentials_handle(&mut cred_handle)
            .with_context_requirements(ServerRequestFlags::empty())
            .with_target_data_representation(DataRepresentation::Native)
            .with_input(&mut input)
            .with_output(&mut output);
        let result = server
            .accept_security_context_impl(builder)
            .map_err(ctx_err)?
            .resolve_to_result()
            .map_err(ctx_err)?;

        let out_token = output[0].buffer.clone();
        if is_established(result.status) {
            Ok(AcceptStep::Established(
                (!out_token.is_empty()).then_some(out_token),
            ))
        } else {
            Ok(AcceptStep::Continue(out_token))
        }
    }

    fn wrap(&self, plaintext: &[u8], _confidential: bool) -> Result<Vec<u8>, GssError> {
        let mut server = self.server.lock().expect("acceptor mutex poisoned");
        gss_wrap(&mut server, plaintext)
    }

    fn unwrap(&self, token: &[u8]) -> Result<Vec<u8>, GssError> {
        let mut server = self.server.lock().expect("acceptor mutex poisoned");
        gss_unwrap(&mut server, token)
    }

    fn src_principal(&self) -> Result<String, GssError> {
        let mut server = self.server.lock().expect("acceptor mutex poisoned");
        let names = server
            .query_context_names()
            .map_err(|_| GssError::NoSrcPrincipal)?;
        Ok(names.username.inner().to_string())
    }
}

/// Client-side GSSAPI initiator backed by sspi + a keytab-extracted client key.
///
/// The initiator is keytab-based and uses no password. It loads the client
/// principal's long-term key from a keytab and injects it through
/// [`sspi::KeytabIdentity`]. The client context and the credentials handle must
/// persist across [`GssInitiator::step`] calls, so they live in this struct.
pub struct SspiInitiator {
    client: Mutex<Kerberos>,
    cred_handle: Mutex<<Kerberos as SspiImpl>::CredentialsHandle>,
    target_spn: String,
}

impl SspiInitiator {
    /// Build a keytab-based initiator.
    ///
    /// This function reads `keytab_path` and extracts the aes256 key for the
    /// first component of `client_principal`. It then builds an sspi client
    /// that authenticates as `client_principal`, for example
    /// `"alice@KRABKA.TEST"` or `"kafka/host@KRABKA.TEST"`.
    ///
    /// `target_spn` is the service SPN without the realm, for example
    /// `"kafka/localhost"`. `kdc_url` is the KDC endpoint, for example
    /// `"tcp://localhost:88"`.
    ///
    /// # Errors
    ///
    /// Returns [`GssError::Keytab`] if the keytab cannot be read or has no
    /// matching key, or [`GssError::Context`] if sspi rejects the principal,
    /// credentials, or client configuration.
    // GSSAPI client-credentials acquisition from a keytab. skip_all keeps the
    // extracted client-key material (loaded into locals) out of span fields;
    // only the non-sensitive mechanism + principal + target SPN are recorded.
    // `err` surfaces keytab/context failures (Debug).
    #[tracing::instrument(
        level = "info",
        skip_all,
        fields(mechanism = "GSSAPI", principal = %client_principal, target = %target_spn),
        err
    )]
    pub fn new(
        keytab_path: &str,
        client_principal: &str,
        target_spn: &str,
        kdc_url: &str,
    ) -> Result<Self, GssError> {
        let principal = keytab_username(client_principal)?;
        // The keytab is keyed by the principal's first component.
        let first_component = principal
            .account_name()
            .split('/')
            .next()
            .unwrap_or_else(|| principal.account_name());

        let bytes = std::fs::read(keytab_path)
            .map_err(|e| GssError::Keytab(format!("reading {keytab_path}: {e}")))?;
        let entry = load_service_key(&bytes, first_component, ENCTYPE_AES256_CTS_HMAC_SHA1_96)
            .map_err(|e| GssError::Keytab(e.to_string()))?;

        let mut client = Kerberos::new_client_from_config(KerberosConfig::new(
            kdc_url,
            "krabka-broker".to_string(),
        ))
        .map_err(ctx_err)?;

        let identity = KeytabIdentity {
            principal,
            key: Secret::new(entry.key),
            key_enctype: DEFAULT_ENCRYPTION_TYPE,
        };
        let creds: Credentials = identity.into();
        let cred_handle = client
            .acquire_credentials_handle()
            .with_credential_use(CredentialUse::Outbound)
            .with_auth_data(&creds)
            .execute(&mut client)
            .map_err(ctx_err)?
            .credentials_handle;

        Ok(Self {
            client: Mutex::new(client),
            cred_handle: Mutex::new(cred_handle),
            target_spn: target_spn.to_string(),
        })
    }
}

impl GssInitiator for SspiInitiator {
    fn step(&mut self, server_token: Option<&[u8]>) -> Result<InitStep, GssError> {
        let client = self.client.get_mut().expect("initiator mutex poisoned");
        let cred_handle = self
            .cred_handle
            .get_mut()
            .expect("initiator mutex poisoned");

        let mut input = vec![SecurityBuffer::new(
            server_token.map(<[u8]>::to_vec).unwrap_or_default(),
            BufferType::Token,
        )];
        let mut output = vec![SecurityBuffer::new(Vec::new(), BufferType::Token)];

        let mut builder = client
            .initialize_security_context()
            .with_credentials_handle(cred_handle)
            .with_context_requirements(ClientRequestFlags::MUTUAL_AUTH)
            .with_target_data_representation(DataRepresentation::Native)
            .with_target_name(&self.target_spn)
            .with_input(&mut input)
            .with_output(&mut output);
        let result = client
            .initialize_security_context_impl(&mut builder)
            .map_err(ctx_err)?
            .resolve_with_default_network_client()
            .map_err(ctx_err)?;

        let out_token = output[0].buffer.clone();
        if is_established(result.status) {
            Ok(InitStep::Established(
                (!out_token.is_empty()).then_some(out_token),
            ))
        } else {
            Ok(InitStep::Continue(out_token))
        }
    }

    fn wrap(&self, plaintext: &[u8], _confidential: bool) -> Result<Vec<u8>, GssError> {
        let mut client = self.client.lock().expect("initiator mutex poisoned");
        gss_wrap(&mut client, plaintext)
    }

    fn unwrap(&self, token: &[u8]) -> Result<Vec<u8>, GssError> {
        let mut client = self.client.lock().expect("initiator mutex poisoned");
        gss_unwrap(&mut client, token)
    }
}

#[cfg(test)]
mod tests {
    use assert2::check;

    use super::*;

    /// The KDC URL is read from the environment with a default, and this file
    /// had no tests at all: a function answering a constant string points every
    /// acceptor at the wrong KDC while still looking configured.
    ///
    /// Only the default branch is asserted. Setting the variable would need
    /// `unsafe` under the 2024 edition, which this workspace forbids, and the
    /// process environment is shared with every other test in the binary
    /// anyway.
    #[test]
    fn kdc_url_falls_back_to_the_default() {
        if std::env::var("SSPI_KDC_URL").is_ok() {
            return;
        }
        check!(kdc_url_from_env() == DEFAULT_KDC_URL);
    }

    /// `is_established` decides whether the handshake is finished or owes
    /// another round trip. Stuck at either answer it either hangs a completed
    /// handshake or accepts an unfinished one as authenticated.
    #[test]
    fn only_completing_statuses_count_as_established() {
        for status in [
            SecurityStatus::Ok,
            SecurityStatus::CompleteNeeded,
            SecurityStatus::CompleteAndContinue,
        ] {
            check!(is_established(status), "{status:?} completes the handshake");
        }
        check!(
            !is_established(SecurityStatus::ContinueNeeded),
            "ContinueNeeded owes another round trip"
        );
    }

    #[test]
    fn keytab_upn_uses_a_kerberos_principal_name() {
        let principal = keytab_username("alice@KRABKA.TEST").unwrap();
        check!(principal.inner() == "KRABKA.TEST\\alice");
    }

    #[test]
    fn keytab_down_level_name_is_unchanged() {
        let principal = keytab_username("KRABKA.TEST\\alice").unwrap();
        check!(principal.inner() == "KRABKA.TEST\\alice");
    }
}