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
// Copyright 2016 Jonathan Anderson <jonathan.anderson@mun.ca>
//
// This software was developed by BAE Systems, the University of Cambridge
// Computer Laboratory, and Memorial University under DARPA/AFRL contract
// FA8650-15-C-7558 ("CADETS"), as part of the DARPA Transparent Computing
// (TC) research program.
//
// Licensed under the Apache License, Version 2.0,
// <LICENSE-APACHE or http://apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. This file may not be copied, modified, or distributed
// except according to those terms.

use byteorder::{ByteOrder,NativeEndian};
use std::fmt;
use ::{Error,RecordType,Result};


#[derive(Clone,Debug)]
pub enum Record {
    /// At least one record was dropped.
    Drop,

    /// KTR_SYSCALL - system call record
    SystemCall {
        /// syscall number
        number: u16,

        /// user arguments
        args: Vec<u64>,
    },

    /// KTR_SYSRET - return from system call record
    SystemCallReturn {
        code: u16,
        eosys: u16,
        error: u32,
        retval: u64,
    },

    /// KTR_NAMEI - namei record
    Namei(String),

    /// KTR_GENIO - trace generic process I/O
    GenericIO {
        fd: i32,
        rw: IODir,
        data: Vec<u8>,
    },

    /// KTR_PSIG - trace processed signal
    Signal {
        signo: i32,
        handler: *const SignalHandler,
        code: i32,
        mask: Vec<u32>,
    },

    /// KTR_CSW - trace context switches
    ContextSwitch {
        out: bool,
        user: bool,
        message: String,
    },

    /// KTR_USER - data coming from userland
    UserData(Vec<u8>),

    /// KTR_STRUCT - misc. structs
    Struct {
        name: String,
        content: Vec<u8>,
    },

    /// KTR_SYSCTL - name of a sysctl MIB
    Sysctl(String),

    /// KTR_PROCCTOR - trace process creation (multiple ABI support)
    ProcessCreation { flags: u32 },

    /// KTR_PROCDTOR - trace process destruction (multiple ABI support)
    ProcessDestruction,

    /// KTR_CAPFAIL - trace capability check failure
    CapabilityFailure {
        fail_type: CapabilityFailureType,
        rights_needed: CapabilityRights,
        rights_held: CapabilityRights,
    },

    /// KTR_FAULT - page fault record
    PageFault {
        virtual_address: u64,
        fault_type: u32,
    },

    /// KTR_FAULTEND - end of page fault record
    PageFaultEnd {
        result: u32,
    },
}

/// Ways that capability-aware operations can fail
#[derive(Clone,Debug)]
pub enum CapabilityFailureType {
    /// insufficient capabilities in cap_check()
    NotCapable,

    /// attempt to increase capabilities
    Increase,

    /// disallowed system call
    Syscall,

    /// disallowed VFS lookup
    Lookup,
}

impl CapabilityFailureType {
    fn from(value: u32) -> Result<CapabilityFailureType> {
        match value {
            0 => Ok(CapabilityFailureType::NotCapable),
            1 => Ok(CapabilityFailureType::NotCapable),
            2 => Ok(CapabilityFailureType::NotCapable),
            3 => Ok(CapabilityFailureType::NotCapable),
            x => Err(Error::bad_value(
                    "ktr_cap_fail_type (integer 0-3)", x.to_string()))
        }
    }
}

/// Rights that are (or can be) associated with a capability
#[derive(Clone,Debug)]
pub struct CapabilityRights;

/// Directions that I/O can take place in
#[derive(Clone,Debug)]
pub enum IODir {
    Read,
    Write,
}

/// Opaque representation of a C signal handler
pub enum SignalHandler {}

impl Record {
    pub fn parse<E>(data: &[u8], t: &RecordType) -> Result<Record>
        where E : ByteOrder
    {
        match t {
            &RecordType::SystemCall => {
                if data.len() < 4 {
                    return Err(Error::bad_value(
                            "2*u16", format!["{} B: {:?}", data.len(), data]));
                }

                let code = E::read_u16(&data[0..2]);
                let num_args = E::read_u16(&data[2..4]);

                // There is padding before the arguments begin
                let arg_data = &data[8..];

                if arg_data.len() != 8 * num_args as usize {
                    return Err(Error::bad_value(
                            format!["{} 8B arguments", num_args],
                            format!["{} B: {:?}", arg_data.len(), &arg_data]));
                }

                // TODO: find a more idiomatic way of doing this, probably
                //       with some sort of iterator adapter
                let mut args = Vec::new();
                for i in 0..num_args {
                    let start = 8 * i as usize;
                    args.push(E::read_u64(&arg_data[start..start+8]));
                }

                Ok(Record::SystemCall {
                    number: code,
                    args: args,
                })
            },

            &RecordType::SystemCallReturn => {
                if data.len() != 16 {
                    return Err(Error::bad_value(
                            "16 B", format!["{} B: {:?}", data.len(), data]));
                }

                Ok(Record::SystemCallReturn {
                    code: E::read_u16(&data[0..2]),
                    eosys: E::read_u16(&data[2..4]),
                    error: E::read_u32(&data[4..8]),
                    retval: E::read_u64(&data[8..16]),
                })
            },

            &RecordType::Namei => {
                String::from_utf8(data.to_vec())
                       .map(Record::Namei)
                       .map_err(Error::UTF8)
            },

            &RecordType::GenericIO => {
                if data.len() < 8 {
                    return Err(Error::bad_value(
                            "2*int", format!["{} B: {:?}", data.len(), data]));
                }

                Ok(Record::GenericIO{
                    fd: E::read_i32(&data[0..4]),
                    rw: match E::read_u32(&data[4..8]) {
                        0 => IODir::Read,
                        1 => IODir::Write,
                        x => return Err(Error::bad_value("uio_rw",
                                                         format!["{}", x]))
                    },
                    data: data[8..].to_vec(),
                })
            },

            &RecordType::Signal => {
                if data.len() < 20 {
                    return Err(Error::bad_value(
                        "2*int + sig_t + sigset_t + padding",
                        format!["{} B: {:?}", data.len(), data]
                    ));
                }

                Ok(Record::Signal {
                    signo: E::read_i32(&data[0..4]),
                    handler: E::read_u64(&data[8..16]) as *const SignalHandler,
                    code: E::read_i32(&data[16..20]),
                    mask: data[20..].chunks(4)
                                    .map(|chunk| E::read_u32(chunk))
                                    .collect::<Vec<_>>(),
                })
            },

            &RecordType::ContextSwitch => {
                Ok(Record::ContextSwitch {
                    out: (E::read_u32(&data[0..4]) != 0),
                    user: (E::read_u32(&data[4..8]) != 0),
                    message: try! {
                        String::from_utf8(data[8..].to_vec())
                               .map_err(Error::UTF8)
                    },
                })
            },

            &RecordType::UserData => {
                Ok(Record::UserData(data.to_vec()))
            },

            &RecordType::Struct => {
                let nul = try! {
                    data.iter()
                        .position(|x| *x == 0)
                        .ok_or(Error::msg("no NULL byte in struct name"))
                };

                Ok(Record::Struct {
                    name: try! {
                        String::from_utf8(data[..nul].to_vec())
                               .map_err(Error::UTF8)
                    },
                    content: data[nul..].to_vec(),
                })
            },

            &RecordType::Sysctl => {
                if data.len() == 0 {
                    return Err(Error::bad_value("sysctl MIB", "empty string"));
                }

                String::from_utf8(data.to_vec())
                       .map(Record::Sysctl)
                       .map_err(Error::UTF8)
            },

            &RecordType::ProcessCreation => {
                if data.len() != 4 {
                    Err(Error::bad_value(
                            "u32", format!["{} B: {:?}", data.len(), data]))
                } else {
                    Ok(Record::ProcessCreation {
                        flags: NativeEndian::read_u32(data)
                    })
                }
            },

            &RecordType::ProcessDestruction => {
                if data.len() != 0 {
                    return Err(Error::bad_value(
                        "no data for process destruction",
                        format!["{:?}", data]
                    ));
                }

                Ok(Record::ProcessDestruction)
            },

            &RecordType::CapabilityFailure => {
                if data.len() < 20 {
                    return Err(Error::bad_value(
                        "enum ktr_cap_fail_type + two cap_rights_t",
                        format!["{} B: {:?}", data.len(), data]
                    ));
                }

                let fail_type = try! {
                    CapabilityFailureType::from(E::read_u32(&data[0..4]))
                };

                // TODO: actually parse struct cap_rights:
                /*
                let cap_rights_size = (data.len() - 4) / 2;
                let cap_rights_version = cap_rights_size / 8 - 2;
                */

                Ok(Record::CapabilityFailure {
                    fail_type: fail_type,
                    rights_needed: CapabilityRights,
                    rights_held: CapabilityRights,
                })
            },

            &RecordType::PageFault => {
                if data.len() < 12 {
                    return Err(Error::bad_value(
                        "vm_offset_t + int",
                        format!["{} B: {:?}", data.len(), data]
                    ));
                }

                Ok(Record::PageFault {
                    virtual_address: E::read_u64(&data[0..8]),
                    fault_type: E::read_u32(&data[8..12]),
                })
            },

            &RecordType::PageFaultEnd => {
                if data.len() != 4 {
                    return Err(Error::bad_value("int",
                        format!["{} B: {:?}", data.len(), data]
                    ));
                }

                Ok(Record::PageFaultEnd {
                    result: E::read_u32(data),
                })
            },
        }
    }
}

impl fmt::Display for Record {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Record::Drop => {
                write![f, "<record(s) dropped>"]
            },

            &Record::SystemCall{number, ref args} => {
                write![f, "CALL  {}({})",
                    number,
                    args.iter()
                        .map(|x| format!["0x{:x}", x])
                        .collect::<Vec<_>>()
                        .join(", ")
                ]
            },

            &Record::SystemCallReturn{code, retval, ..} => {
                write![f, "RET   {} {}", code, retval]
            },

            &Record::Namei(ref name) => {
                write![f, "NAMI  \"{}\"", name]
            },

            &Record::GenericIO{ref fd, ref rw, ref data} => {
                write![f, "GENIO {} {:?}: {}B: {:?} [...]",
                    fd, rw, data.len(),
                    data[..8].iter()
                              .map(|x| format!["{:02x}", x])
                              .collect::<Vec<_>>()
                              .join(" ")
                ]
            },

            &Record::Signal{signo, handler, code, ..} => {
                write![f, "{} caught handler=0x{:x} mask=?? code={}",
                    signo, handler as u64, code]
            },

            &Record::ContextSwitch{out, user, ref message} => {
                write![f, "CSW   {} {} \"{}\"",
                    if out { "stop" } else { "resume" },
                    if user { "user" } else { "kernel" },
                    message
                ]
            },

            &Record::UserData(ref data) => {
                write![f, "UTRACE {:?}", data]
            },

            &Record::Struct{ref name, ..} => {
                write![f, "STRU  struct {} {{ ... }}", name]
            },

            &Record::Sysctl(ref name) => {
                write![f, "SCTL  \"{}\"", name]
            },

            &Record::ProcessCreation{ref flags} => {
                write![f, "PROCC 0x{:x}", flags]
            },

            &Record::ProcessDestruction => {
                write![f, "PDEST"]
            },

            &Record::CapabilityFailure{ref fail_type, ..} => {
                // TODO: describe rights held and needed
                write![f, "CAPF  {:?}", fail_type]
            },

            &Record::PageFault{virtual_address, fault_type} => {
                write![f, "PFLT  0x{:x} {}", virtual_address, fault_type]
            },

            &Record::PageFaultEnd{result} => {
                write![f, "PRET  {}", result]
            },
        }
    }
}