libkrimes 0.1.0

A pure rust, minimal kerberos library
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
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
mod cc_dir;
mod cc_file;

#[cfg(feature = "keyring")]
mod cc_keyring;

use crate::asn1::constants::encryption_types::EncryptionType as Asn1EncryptionType;
use crate::asn1::constants::PrincipalNameType;
use crate::asn1::encrypted_data::EncryptedData as Asn1EncryptedData;
use crate::asn1::tagged_ticket::TaggedTicket as Asn1TaggedTicket;
use crate::asn1::tagged_ticket::Ticket as Asn1Ticket;
use crate::error::KrbError;
use crate::proto::KerberosCredentials;
use crate::proto::{EncTicket, EncryptedData, KdcReplyPart, Name, SessionKey};
use binrw::{binread, binwrite};
use der::asn1::OctetString;
use der::Encode;
use std::env;
use std::time::Duration;
use std::time::SystemTime;
use tracing::{debug, error, trace};
use uzers::get_current_uid;

/* TODO:
 *   - Handle cache conf entries. CredentialCache::new() could take a KV pair collection
 *   - Handle multiple credentials. The time offset is global, as the primary name. The
 *     there is a list of credentials, the primary name usually matches the first's
 *     credential 'client' field.
 */

#[binwrite]
#[bw(big)]
#[binread]
struct DataComponent {
    #[bw(try_calc(u32::try_from(value.len())))]
    value_len: u32,
    #[br(count = value_len)]
    value: Vec<u8>,
}

#[binwrite]
#[bw(big)]
#[binread]
struct PrincipalV4 {
    name_type: u32,
    #[bw(try_calc(u32::try_from(components.len())))]
    components_count: u32,
    realm: DataComponent,
    #[br(count = components_count)]
    components: Vec<DataComponent>,
}

#[binwrite]
#[bw(big)]
#[binread]
enum Principal {
    V4(PrincipalV4),
}

#[binwrite]
#[bw(big)]
#[binread]
struct KeyBlockV4 {
    enc_type: u16,
    data: DataComponent,
}

#[binwrite]
#[bw(big)]
#[binread]
enum KeyBlock {
    V4(KeyBlockV4),
}

#[binwrite]
#[bw(big)]
#[binread]
struct Address {
    addr_type: u16,
    data: DataComponent,
}

#[binwrite]
#[bw(big)]
#[binread]
struct Addresses {
    #[bw(try_calc(u32::try_from(addresses.len())))]
    count: u32,
    #[br(count = count)]
    addresses: Vec<Address>,
}

#[binwrite]
#[bw(big)]
#[binread]
struct AuthDataComponent {
    ad_type: u16,
    data: DataComponent,
}

#[binwrite]
#[bw(big)]
#[binread]
struct AuthData {
    #[bw(try_calc(u32::try_from(auth_data.len())))]
    count: u32,
    #[br(count = count)]
    auth_data: Vec<AuthDataComponent>,
}

#[binwrite]
#[bw(big)]
#[binread]
enum Credential {
    V4(CredentialV4),
}

#[binwrite]
#[bw(big)]
#[binread]
struct CredentialV4 {
    client: PrincipalV4,
    server: PrincipalV4,
    keyblock: KeyBlock,
    authtime: u32,
    starttime: u32,
    endtime: u32,
    renew_till: u32,
    is_skey: u8,
    ticket_flags: u32,
    addresses: Addresses,
    authdata: AuthData,
    ticket: DataComponent,
    second_ticket: DataComponent,
}

impl CredentialV4 {
    pub fn new(
        client: &Name,
        ticket: &EncTicket,
        enc_part: &KdcReplyPart,
    ) -> Result<Self, KrbError> {
        let cred: Self = CredentialV4 {
            client: client.try_into()?,
            server: (&enc_part.server).try_into()?,
            keyblock: KeyBlock::V4((&enc_part.key).try_into()?),
            authtime: enc_part
                .auth_time
                .duration_since(SystemTime::UNIX_EPOCH)
                .map_err(|_| KrbError::InsufficientData)?
                .as_secs() as u32,
            starttime: if let Some(start_time) = enc_part.start_time {
                start_time
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .map_err(|_| KrbError::InsufficientData)?
                    .as_secs() as u32
            } else {
                0u32
            },
            endtime: enc_part
                .end_time
                .duration_since(SystemTime::UNIX_EPOCH)
                .map_err(|_| KrbError::InsufficientData)?
                .as_secs() as u32,
            renew_till: if let Some(till) = enc_part.renew_until {
                till.duration_since(SystemTime::UNIX_EPOCH)
                    .map_err(|_| KrbError::InsufficientData)?
                    .as_secs() as u32
            } else {
                0u32
            },
            is_skey: 0u8,
            ticket_flags: enc_part.flags.bits().reverse_bits(),
            addresses: Addresses { addresses: vec![] },
            authdata: AuthData { auth_data: vec![] },
            ticket: DataComponent {
                value: match &ticket.enc_part {
                    EncryptedData::Aes256CtsHmacSha196 { kvno, data } => {
                        let t = Asn1Ticket {
                            tkt_vno: 5,
                            realm: (&enc_part.server).try_into()?,
                            sname: (&enc_part.server).try_into()?,
                            enc_part: Asn1EncryptedData {
                                etype: Asn1EncryptionType::AES256_CTS_HMAC_SHA1_96 as i32,
                                kvno: *kvno,
                                cipher: OctetString::new(data.clone())
                                    .map_err(|_| KrbError::DerEncodeOctetString)?,
                            },
                        };
                        let tt = Asn1TaggedTicket::new(t);
                        tt.to_der().map_err(|e| {
                            println!("{e:#?}");
                            KrbError::DerEncodeEncTicketPart
                        })?
                    }
                    EncryptedData::Opaque { etype, kvno, data } => {
                        let t = Asn1Ticket {
                            tkt_vno: 5,
                            realm: (&enc_part.server).try_into()?,
                            sname: (&enc_part.server).try_into()?,
                            enc_part: Asn1EncryptedData {
                                etype: *etype,
                                kvno: *kvno,
                                cipher: OctetString::new(data.clone())
                                    .map_err(|_| KrbError::DerEncodeOctetString)?,
                            },
                        };
                        let tt = Asn1TaggedTicket::new(t);
                        tt.to_der().map_err(|e| {
                            error!(?e, "DerEncodeEncTicketPart");
                            KrbError::DerEncodeEncTicketPart
                        })?
                    }
                },
            },
            second_ticket: DataComponent { value: vec![] },
        };
        Ok(cred)
    }
}

impl TryFrom<&Name> for PrincipalV4 {
    type Error = KrbError;

    fn try_from(name: &Name) -> Result<Self, Self::Error> {
        match name {
            Name::Principal { name, realm } => {
                let p: PrincipalV4 = PrincipalV4 {
                    name_type: PrincipalNameType::NtPrincipal as u32,
                    realm: DataComponent {
                        value: realm.as_bytes().into(),
                    },
                    components: vec![DataComponent {
                        value: name.as_bytes().into(),
                    }],
                };
                Ok(p)
            }
            Name::SrvInst {
                service,
                instance,
                realm,
            } => {
                let mut components: Vec<DataComponent> = vec![];
                components.push(DataComponent {
                    value: service.as_bytes().into(),
                });
                let iv: Vec<DataComponent> = instance
                    .iter()
                    .map(|x| DataComponent {
                        value: x.as_bytes().into(),
                    })
                    .collect();
                components.extend(iv);

                let p: PrincipalV4 = PrincipalV4 {
                    name_type: PrincipalNameType::NtSrvInst as u32,
                    realm: DataComponent {
                        value: realm.as_bytes().into(),
                    },
                    components,
                };
                Ok(p)
            }
            _ => Err(KrbError::PrincipalNameInvalidType),
        }
    }
}

impl TryInto<Name> for PrincipalV4 {
    type Error = KrbError;

    fn try_into(self) -> Result<Name, Self::Error> {
        let name_type: i32 = self.name_type as i32;
        let name_type: PrincipalNameType = name_type.try_into().map_err(|err| {
            error!(?err, ?name_type, "invalid principal name type");
            KrbError::PrincipalNameInvalidType
        })?;

        match name_type {
            PrincipalNameType::NtPrincipal => {
                let n: Name = Name::Principal {
                    name: self
                        .components
                        .iter()
                        .map(|x| String::from_utf8_lossy(x.value.as_slice()).to_string())
                        .collect::<Vec<String>>()
                        .join(""),
                    realm: String::from_utf8_lossy(self.realm.value.as_slice()).to_string(),
                };
                Ok(n)
            }
            PrincipalNameType::NtSrvInst => {
                let n: Name = Name::SrvInst {
                    service: self
                        .components
                        .first()
                        .ok_or(KrbError::NameNotPrincipal)
                        .map(|x| String::from_utf8_lossy(x.value.as_slice()).to_string())?,
                    instance: self
                        .components
                        .get(1..)
                        .ok_or(KrbError::NameNotPrincipal)?
                        .iter()
                        .map(|x| String::from_utf8_lossy(x.value.as_slice()).to_string())
                        .collect::<Vec<String>>(),
                    realm: String::from_utf8_lossy(self.realm.value.as_slice()).to_string(),
                };
                Ok(n)
            }
            _ => Err(KrbError::PrincipalNameInvalidType),
        }
    }
}

impl TryFrom<&SessionKey> for KeyBlockV4 {
    type Error = KrbError;

    fn try_from(value: &SessionKey) -> Result<Self, Self::Error> {
        match value {
            SessionKey::Aes256CtsHmacSha196 { k } => Ok(KeyBlockV4 {
                enc_type: 0x12,
                data: DataComponent { value: k.to_vec() },
            }),
        }
    }
}

fn parse_ccache_name(ccache: Option<&str>) -> String {
    let uid = get_current_uid().to_string();

    match ccache {
        Some(c) => c.to_string(),
        None => match env::var("KRB5CCNAME") {
            Ok(val) => val,
            _ => "FILE:/tmp/krb5cc_%{uid}".to_string(),
        },
    }
    .replace("%{uid}", uid.as_str())
}

pub trait CredentialCache {
    fn init(&mut self, name: &Name, clock_skew: Option<Duration>) -> Result<(), KrbError>;
    fn destroy(&mut self) -> Result<(), KrbError>;
    fn store(&mut self, credentials: &KerberosCredentials) -> Result<(), KrbError>;
}

pub fn resolve(ccache_name: Option<&str>) -> Result<Box<dyn CredentialCache>, KrbError> {
    let ccache_name = parse_ccache_name(ccache_name);
    trace!(?ccache_name, "Resolving credential cache");

    if ccache_name.starts_with("FILE:") {
        return cc_file::resolve(ccache_name.as_str());
    }

    if ccache_name.starts_with("DIR:") {
        return cc_dir::resolve(ccache_name.as_str());
    }

    #[cfg(feature = "keyring")]
    if ccache_name.starts_with("KEYRING:") {
        return cc_keyring::resolve(ccache_name.as_str());
    }

    debug!(?ccache_name, "Unsupported credential cache type");
    Err(KrbError::UnsupportedCredentialCacheType)
}

#[cfg(test)]
mod tests {
    use tracing::warn;

    use super::*;
    use std::process::Command;
    #[cfg(feature = "keyring")]
    use std::process::Stdio;

    #[tokio::test]
    async fn test_ccache_file_store() -> Result<(), KrbError> {
        let _ = tracing_subscriber::fmt::try_init();
        if std::env::var("CI").is_ok() {
            // Skip this test in CI, as it requires a KDC running on localhost
            warn!("Skipping test_ccache_file_store in CI");
            return Ok(());
        }

        let creds = crate::proto::get_tgt("testuser", "EXAMPLE.COM", "password").await?;

        let path = "/tmp/krb5cc_krime";
        let ccache_name = format!("FILE:{path}");
        let mut ccache = super::resolve(Some(ccache_name.as_str()))?;
        ccache.init(&creds.name, None)?;
        ccache.store(&creds)?;
        assert!(std::fs::exists(path).expect("Unable to check if file exists"));

        // TODO load and compare

        // Test MIT can parse the created ccache
        let output = Command::new("klist")
            .arg("-c")
            .arg(ccache_name.as_str())
            .output()
            .expect("Unable to execute command klist");
        assert!(output.status.success());

        let output = String::from_utf8_lossy(output.stdout.as_slice()).to_string();
        assert!(output.contains("testuser@EXAMPLE.COM"));

        ccache.destroy()?;
        assert!(!std::fs::exists(path).expect("Unable to check if file exists"));

        Ok(())
    }

    #[tokio::test]
    #[cfg(feature = "keyring")]
    async fn test_ccache_keyring_store() -> Result<(), KrbError> {
        if std::env::var("CI").is_ok() {
            // Skip this test in CI, as it requires a KDC running on localhost
            warn!("Skipping get_tgt in CI");
            return Ok(());
        }

        let ccache_name = "KEYRING:session:abc";
        let ccname = Some(ccache_name);

        let mut ccache = super::resolve(ccname)?;
        let creds = crate::proto::get_tgt("testuser", "EXAMPLE.COM", "password").await?;
        ccache.init(&creds.name, None)?;
        ccache.store(&creds)?;

        let mut ccache = super::resolve(ccname)?;
        let creds = crate::proto::get_tgt("testuser2", "EXAMPLE.COM", "password").await?;
        ccache.init(&creds.name, None)?;
        ccache.store(&creds)?;

        let output = Command::new("klist")
            .stderr(Stdio::null())
            .arg("-c")
            .arg(ccache_name)
            .arg("-A")
            .output()
            .expect("Unable to execute command klist");
        assert!(output.status.success());

        let output = String::from_utf8_lossy(output.stdout.as_slice()).to_string();
        assert!(output.contains("testuser@EXAMPLE.COM"));
        assert!(output.contains("testuser2@EXAMPLE.COM"));

        Ok(())
    }
}