sdjournal 0.1.22

Pure Rust systemd journal reader and query engine
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
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
use super::fsprg::{FsprgParams, FsprgState};
use super::key::VerificationKey;
use super::{HmacSha256, TAG_LENGTH, VERIFY_READ_CHUNK_SIZE};
use crate::error::{LimitKind, Result, SdJournalError};
use crate::file::JournalFile;
use crate::format::{
    HEADER_SIZE_MIN, OBJECT_DATA, OBJECT_DATA_HASH_TABLE, OBJECT_ENTRY, OBJECT_ENTRY_ARRAY,
    OBJECT_FIELD, OBJECT_FIELD_HASH_TABLE, OBJECT_TAG, ObjectHeader,
};
use crate::util::{checked_add_u64, read_u64_le};
use hmac::{KeyInit as _, Mac as _};

pub(crate) fn verify_file_seal(
    file: &JournalFile,
    params: &FsprgParams,
    key: &VerificationKey,
) -> Result<()> {
    let header = file.header();
    if !header.is_sealed() {
        return Ok(());
    }

    let header_size = header.header_size;
    let tail_object_offset = header.tail_object_offset;
    let used_size = file.used_size();

    if header_size < HEADER_SIZE_MIN || header_size > used_size || !header_size.is_multiple_of(8) {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(88),
            reason: format!("invalid header_size: {header_size}"),
        });
    }

    if tail_object_offset == 0 {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(136),
            reason: "sealed journal contains no objects".to_string(),
        });
    }
    if tail_object_offset < header_size || tail_object_offset >= used_size {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(136),
            reason: format!(
                "invalid tail_object_offset: {tail_object_offset} (header_size={header_size}, used_size={used_size})"
            ),
        });
    }

    let mut fsprg = FsprgState::new(params);
    let mut n_tags: u64 = 0;
    let mut last_epoch: u64 = 0;
    let mut last_tag_end: u64 = 0;
    let mut last_tag_realtime: Option<u64> = None;
    let mut min_entry_realtime: Option<u64> = None;
    let mut max_entry_realtime: Option<u64> = None;

    let mut p = header_size;
    let mut found_tail = false;
    while p <= tail_object_offset {
        let oh = read_object_header(file, p)?;

        if oh.object_type == OBJECT_ENTRY {
            if n_tags == 0 {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: "sealed journal has ENTRY before first TAG".to_string(),
                });
            }

            let realtime = read_entry_realtime(file, p, &oh)?;
            if last_tag_realtime.is_some_and(|start| realtime < start) {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: format!(
                        "ENTRY realtime is older than the preceding TAG window ({realtime} < {})",
                        last_tag_realtime.unwrap_or_default()
                    ),
                });
            }
            min_entry_realtime =
                Some(min_entry_realtime.map_or(realtime, |current| current.min(realtime)));
            max_entry_realtime =
                Some(max_entry_realtime.map_or(realtime, |current| current.max(realtime)));
        }

        if oh.object_type == OBJECT_TAG {
            let tag = read_tag_object(file, p, &oh)?;

            let expected_seqnum = n_tags
                .checked_add(1)
                .ok_or_else(|| SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: "TAG sequence number overflow".to_string(),
                })?;
            if tag.seqnum != expected_seqnum {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: format!(
                        "tag sequence number out of sync ({} != {})",
                        tag.seqnum, expected_seqnum
                    ),
                });
            }

            if header.is_sealed_continuous() {
                let next_epoch = last_epoch.checked_add(1);
                if !(n_tags == 0
                    || (n_tags == 1 && tag.epoch == last_epoch)
                    || next_epoch == Some(tag.epoch))
                {
                    return Err(SdJournalError::Corrupt {
                        path: Some(file.path().to_path_buf()),
                        offset: Some(p),
                        reason: format!(
                            "epoch sequence not continuous ({} vs {})",
                            tag.epoch, last_epoch
                        ),
                    });
                }
            } else if tag.epoch < last_epoch {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: format!(
                        "epoch sequence out of sync ({} < {})",
                        tag.epoch, last_epoch
                    ),
                });
            }

            let (tag_realtime, tag_realtime_end) = tag_realtime_window(file, key, p, tag.epoch)?;
            if let Some(max_realtime) = max_entry_realtime
                && max_realtime >= tag_realtime_end
            {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: format!(
                        "ENTRY realtime is too late for TAG epoch {} ({max_realtime} >= {tag_realtime_end})",
                        tag.epoch
                    ),
                });
            }
            if let Some(min_realtime) = min_entry_realtime
                && min_realtime < tag_realtime
            {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: format!(
                        "ENTRY realtime is too early for TAG epoch {} ({min_realtime} < {tag_realtime})",
                        tag.epoch
                    ),
                });
            }

            fsprg.seek(tag.epoch)?;
            let hmac_key = fsprg.get_key(TAG_LENGTH, 0);
            let mut mac =
                HmacSha256::new_from_slice(&hmac_key).map_err(|_| SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: "failed to initialize HMAC".to_string(),
                })?;

            if last_tag_end == 0 {
                hmac_put_header(file, &mut mac)?;
            }

            let mut q = if last_tag_end == 0 {
                header_size
            } else {
                last_tag_end
            };
            while q <= p {
                let qh = read_object_header(file, q)?;
                hmac_put_object(file, &mut mac, q, &qh)?;
                let adv = align64(qh.size)?;
                q = checked_add_u64(q, adv, "verify-seal next object")?;
            }

            let digest = mac.finalize().into_bytes();
            if digest.as_slice() != tag.tag.as_slice() {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(p),
                    reason: "tag failed verification".to_string(),
                });
            }

            last_tag_end = checked_add_u64(p, align64(oh.size)?, "verify-seal tag end")?;
            last_tag_realtime = Some(tag_realtime);
            min_entry_realtime = None;
            max_entry_realtime = None;
            last_epoch = tag.epoch;
            n_tags = expected_seqnum;
        }

        if p == tail_object_offset {
            found_tail = true;
            break;
        }
        p = checked_add_u64(p, align64(oh.size)?, "verify-seal advance")?;
    }

    if !found_tail {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(tail_object_offset),
            reason: "tail_object_offset does not point to an object boundary".to_string(),
        });
    }

    if n_tags == 0 {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(136),
            reason: "sealed journal contains no TAG objects".to_string(),
        });
    }

    Ok(())
}

fn read_object_header(file: &JournalFile, offset: u64) -> Result<ObjectHeader> {
    file.validate_object_offset(offset)?;
    if !offset.is_multiple_of(8) {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(offset),
            reason: format!("object offset is not 8-byte aligned: {offset}"),
        });
    }

    let buf = file.read_bytes(offset, 16)?;
    let oh = ObjectHeader::parse(buf.as_slice(), file.path(), offset)?;

    if oh.size < 16 {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(offset),
            reason: format!("object size too small: {}", oh.size),
        });
    }
    if oh.size > file.config().max_object_size_bytes {
        return Err(SdJournalError::LimitExceeded {
            kind: LimitKind::ObjectSizeBytes,
            limit: file.config().max_object_size_bytes,
        });
    }
    let raw_end = checked_add_u64(offset, oh.size, "verify-seal object end")?;
    let padded_end = checked_add_u64(offset, align64(oh.size)?, "verify-seal padded object end")?;
    if raw_end > file.used_size() || padded_end > file.used_size() {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(offset),
            reason: format!(
                "object extends beyond used journal data (raw_end={raw_end}, padded_end={padded_end}, used_size={})",
                file.used_size()
            ),
        });
    }

    Ok(oh)
}

fn read_entry_realtime(file: &JournalFile, offset: u64, oh: &ObjectHeader) -> Result<u64> {
    const ENTRY_HEADER_SIZE: u64 = 64;
    if oh.size < ENTRY_HEADER_SIZE {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(offset),
            reason: format!("ENTRY object too small: {}", oh.size),
        });
    }

    let buf = file.read_bytes(offset, usize::try_from(ENTRY_HEADER_SIZE).unwrap_or(64))?;
    read_u64_le(buf.as_slice(), 24).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(offset.saturating_add(24)),
        reason: "ENTRY realtime truncated".to_string(),
    })
}

fn tag_realtime_window(
    file: &JournalFile,
    key: &VerificationKey,
    tag_offset: u64,
    epoch: u64,
) -> Result<(u64, u64)> {
    let epoch_offset =
        epoch
            .checked_mul(key.interval_usec())
            .ok_or_else(|| SdJournalError::Corrupt {
                path: Some(file.path().to_path_buf()),
                offset: Some(tag_offset),
                reason: format!("TAG epoch {epoch} overflows the verification-key time range"),
            })?;
    let start =
        key.start_usec()
            .checked_add(epoch_offset)
            .ok_or_else(|| SdJournalError::Corrupt {
                path: Some(file.path().to_path_buf()),
                offset: Some(tag_offset),
                reason: format!("TAG epoch {epoch} overflows the verification-key start time"),
            })?;
    let end = start
        .checked_add(key.interval_usec())
        .ok_or_else(|| SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(tag_offset),
            reason: format!("TAG epoch {epoch} overflows the verification-key end time"),
        })?;
    Ok((start, end))
}

fn hmac_put_header(file: &JournalFile, mac: &mut HmacSha256) -> Result<()> {
    let header_bytes = file.read_bytes(0, 136)?;
    let b = header_bytes.as_slice();

    mac.update(b.get(0..16).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(0),
        reason: "header too short for sealing verification".to_string(),
    })?);
    mac.update(b.get(24..56).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(24),
        reason: "header too short for sealing verification".to_string(),
    })?);
    mac.update(b.get(72..96).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(72),
        reason: "header too short for sealing verification".to_string(),
    })?);
    mac.update(b.get(104..136).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(104),
        reason: "header too short for sealing verification".to_string(),
    })?);

    Ok(())
}

fn hmac_put_object(
    file: &JournalFile,
    mac: &mut HmacSha256,
    offset: u64,
    oh: &ObjectHeader,
) -> Result<()> {
    hmac_update_range(file, mac, offset, 16)?;

    match oh.object_type {
        OBJECT_DATA => {
            hmac_update_range(file, mac, checked_add_u64(offset, 16, "data.hash")?, 8)?;

            let payload_offset = if file.header().is_compact() {
                72u64
            } else {
                64u64
            };
            if oh.size < payload_offset {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(offset),
                    reason: format!("DATA object too small: {}", oh.size),
                });
            }

            let payload_len = oh.size - payload_offset;
            hmac_update_range(
                file,
                mac,
                checked_add_u64(offset, payload_offset, "data.payload")?,
                payload_len,
            )?;
        }
        OBJECT_FIELD => {
            const PAYLOAD_OFFSET: u64 = 40;
            hmac_update_range(file, mac, checked_add_u64(offset, 16, "field.hash")?, 8)?;
            if oh.size < PAYLOAD_OFFSET {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(offset),
                    reason: format!("FIELD object too small: {}", oh.size),
                });
            }
            hmac_update_range(
                file,
                mac,
                checked_add_u64(offset, PAYLOAD_OFFSET, "field.payload")?,
                oh.size - PAYLOAD_OFFSET,
            )?;
        }
        OBJECT_ENTRY => {
            let payload_len = oh
                .size
                .checked_sub(16)
                .ok_or_else(|| SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(offset),
                    reason: "ENTRY object too small".to_string(),
                })?;
            hmac_update_range(
                file,
                mac,
                checked_add_u64(offset, 16, "entry.payload")?,
                payload_len,
            )?;
        }
        OBJECT_DATA_HASH_TABLE | OBJECT_FIELD_HASH_TABLE | OBJECT_ENTRY_ARRAY => {}
        OBJECT_TAG => {
            if oh.size != 64 {
                return Err(SdJournalError::Corrupt {
                    path: Some(file.path().to_path_buf()),
                    offset: Some(offset),
                    reason: format!("TAG object has invalid size: {}", oh.size),
                });
            }
            hmac_update_range(file, mac, checked_add_u64(offset, 16, "tag.seqnum")?, 16)?;
        }
        other => {
            return Err(SdJournalError::Unsupported {
                reason: format!("unsupported object type in sealing verification: {other}"),
            });
        }
    }

    Ok(())
}

fn hmac_update_range(
    file: &JournalFile,
    mac: &mut HmacSha256,
    offset: u64,
    len: u64,
) -> Result<()> {
    let mut off = offset;
    let mut remaining = len;
    while remaining > 0 {
        let take_u64 = std::cmp::min(remaining, VERIFY_READ_CHUNK_SIZE as u64);
        let take = usize::try_from(take_u64).unwrap_or(VERIFY_READ_CHUNK_SIZE);
        let buf = file.read_bytes(off, take)?;
        mac.update(buf.as_slice());
        off = checked_add_u64(off, take_u64, "verify-seal range")?;
        remaining -= take_u64;
    }
    Ok(())
}

#[derive(Debug)]
struct TagObject {
    seqnum: u64,
    epoch: u64,
    tag: [u8; TAG_LENGTH],
}

fn read_tag_object(file: &JournalFile, offset: u64, oh: &ObjectHeader) -> Result<TagObject> {
    if oh.size != 64 {
        return Err(SdJournalError::Corrupt {
            path: Some(file.path().to_path_buf()),
            offset: Some(offset),
            reason: format!("TAG object has invalid size: {}", oh.size),
        });
    }

    let buf = file.read_bytes(offset, 64)?;
    let b = buf.as_slice();
    let seqnum = read_u64_le(b, 16).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(offset + 16),
        reason: "TAG.seqnum truncated".to_string(),
    })?;
    let epoch = read_u64_le(b, 24).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(offset + 24),
        reason: "TAG.epoch truncated".to_string(),
    })?;
    let tag_bytes = b.get(32..64).ok_or_else(|| SdJournalError::Corrupt {
        path: Some(file.path().to_path_buf()),
        offset: Some(offset + 32),
        reason: "TAG.tag truncated".to_string(),
    })?;
    let mut tag = [0u8; TAG_LENGTH];
    tag.copy_from_slice(tag_bytes);

    Ok(TagObject { seqnum, epoch, tag })
}

fn align64(size: u64) -> Result<u64> {
    let added = checked_add_u64(size, 7, "align64")?;
    Ok(added & !7u64)
}

#[cfg(test)]
mod tests {
    use super::{read_object_header, tag_realtime_window};
    use crate::config::JournalConfig;
    use crate::file::JournalFile;
    use crate::format::{HEADER_SIGNATURE, HEADER_SIZE_MIN, OBJECT_FIELD, STATE_ARCHIVED};
    use crate::seal::parse_verification_key;
    use std::fs;

    fn journal_with_unaligned_field() -> (tempfile::TempDir, JournalFile) {
        const HEADER_SIZE: usize = HEADER_SIZE_MIN as usize;
        const FIELD_SIZE: usize = 41;
        const USED_SIZE: usize = 256;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("unaligned-field.journal");
        let mut bytes = vec![0u8; USED_SIZE];
        bytes[..8].copy_from_slice(HEADER_SIGNATURE);
        bytes[16] = STATE_ARCHIVED;
        bytes[88..96].copy_from_slice(&(HEADER_SIZE as u64).to_le_bytes());
        bytes[96..104].copy_from_slice(&((USED_SIZE - HEADER_SIZE) as u64).to_le_bytes());
        bytes[136..144].copy_from_slice(&(HEADER_SIZE as u64).to_le_bytes());
        bytes[HEADER_SIZE] = OBJECT_FIELD;
        bytes[HEADER_SIZE + 8..HEADER_SIZE + 16]
            .copy_from_slice(&(FIELD_SIZE as u64).to_le_bytes());
        fs::write(&path, bytes).unwrap();

        let config = JournalConfig::default();
        #[cfg(feature = "mmap")]
        let config = {
            let mut config = config;
            config.mmap_policy = crate::config::MmapPolicy::Never;
            config
        };
        let file = JournalFile::open(path, &config).unwrap();
        (dir, file)
    }

    #[test]
    fn object_header_accepts_unaligned_raw_size_with_aligned_padding() {
        let (_dir, file) = journal_with_unaligned_field();
        let header = read_object_header(&file, HEADER_SIZE_MIN).unwrap();
        assert_eq!(header.size, 41);
    }

    #[test]
    fn tag_realtime_window_uses_key_start_interval_and_epoch() {
        let (_dir, file) = journal_with_unaligned_field();
        let key = parse_verification_key("01-23-45-67-89-ab-cd-ef-01-23-45-67/1-10").unwrap();

        assert_eq!(
            tag_realtime_window(&file, &key, HEADER_SIZE_MIN, 2).unwrap(),
            (48, 64)
        );
        assert!(tag_realtime_window(&file, &key, HEADER_SIZE_MIN, u64::MAX).is_err());
    }
}