labeled 0.1.0

Dynamic information-flow-control labels
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
//! Buckle is a hierarchical version of DCLabels
//!
//! Similar to DCLabels, Buckle labels are composed of a secrecy and integrity
//! components which are conjunctions of disjunctions of principals. However,
//! unlike DCLabels, Buckle principals are not strings, but rather ordered
//! lists, where prefixes imply longer lists.

use core::fmt::Display;

#[cfg(test)]
use alloc::boxed::Box;
use alloc::vec::Vec;
#[cfg(test)]
use quickcheck::Arbitrary;
use serde::{Deserialize, Serialize};

use super::{HasPrivilege, Label};

pub mod clause;
pub mod component;

pub use clause::*;
pub use component::*;

pub type Principal = alloc::string::String;

#[derive(PartialEq, Eq, Clone, PartialOrd, Ord, Debug, Serialize, Deserialize)]
pub struct Buckle {
    pub secrecy: Component,
    pub integrity: Component,
}

impl Display for Buckle {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{},{}", self.secrecy, self.integrity)
    }
}

impl Buckle {
    /// Parses a string into a DCLabel.
    ///
    /// The string separates secrecy and integrity with a comma, clauses
    /// separated with a '&' and principle vectors with a '|', and delegated
    /// principles with '/'. The backslash character ('\') allows escaping these
    /// special characters (including itself).
    pub fn parse(input: &str) -> Result<Buckle, nom::Err<nom::error::Error<&str>>> {
        Self::parser(input).map(|r| r.1)
    }

    pub fn parser(input: &str) -> nom::IResult<&str, Buckle> {
        use alloc::collections::BTreeSet;
        use nom::{
            bytes::complete::{escaped_transform, tag},
            character::complete::{none_of, one_of},
            multi::separated_list1,
            sequence::tuple,
            Parser,
        };

        fn component(input: &str) -> nom::IResult<&str, Component> {
            tag("T")
                .map(|_| Component::dc_true())
                .or(tag("F").map(|_| Component::dc_false()))
                .or(nom::combinator::map(
                    separated_list1(
                        tag("&"),
                        separated_list1(
                            tag("|"),
                            separated_list1(
                                tag("/"),
                                escaped_transform(none_of(r#",|&/\"#), '\\', one_of(r#",|&/\"#)),
                            ),
                        ),
                    ),
                    |mut c| {
                        Component::DCFormula(
                            c.iter_mut()
                                .map(|c| c.drain(..).collect::<BTreeSet<Vec<Principal>>>().into())
                                .collect::<BTreeSet<Clause>>(),
                        )
                    },
                ))
                .parse(input)
        }

        let (input, (secrecy, _, integrity)) =
            tuple((component, tag(","), component)).parse(input)?;

        Ok((input, Buckle::new(secrecy, integrity)))
    }
}

#[cfg(test)]
impl Arbitrary for Buckle {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        Buckle {
            secrecy: Component::arbitrary(g),
            integrity: Component::arbitrary(g),
        }
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.secrecy.clone(), self.integrity.clone())
                .shrink()
                .map(|(secrecy, integrity)| Buckle { secrecy, integrity }),
        )
    }
}

impl Buckle {
    pub fn new<S: Into<Component>, I: Into<Component>>(secrecy: S, integrity: I) -> Buckle {
        let mut secrecy = secrecy.into();
        let mut integrity = integrity.into();
        secrecy.reduce();
        integrity.reduce();
        Buckle { secrecy, integrity }
    }

    pub fn public() -> Buckle {
        Self::new(Component::dc_true(), Component::dc_true())
    }

    pub fn top() -> Buckle {
        Self::new(Component::dc_false(), Component::dc_true())
    }

    pub fn bottom() -> Buckle {
        Self::new(Component::dc_true(), Component::dc_false())
    }

    pub fn reduce(&mut self) {
        self.secrecy.reduce();
        self.integrity.reduce();
    }

    pub fn endorse(mut self, privilege: &Component) -> Buckle {
        self.integrity = privilege.clone() & self.integrity;
        self
    }
}

impl Label for Buckle {
    fn lub(self, rhs: Self) -> Self {
        let mut res = Buckle {
            secrecy: self.secrecy & rhs.secrecy,
            integrity: self.integrity | rhs.integrity,
        };
        res.reduce();
        res
    }

    fn glb(self, rhs: Self) -> Self {
        let mut res = Buckle {
            secrecy: self.secrecy | rhs.secrecy,
            integrity: self.integrity & rhs.integrity,
        };
        res.reduce();
        res
    }

    fn can_flow_to(&self, rhs: &Self) -> bool {
        rhs.secrecy.implies(&self.secrecy) && self.integrity.implies(&rhs.integrity)
    }
}

impl HasPrivilege for Buckle {
    type Privilege = Component;

    fn downgrade(mut self, privilege: &Component) -> Buckle {
        self.secrecy = match (self.secrecy, privilege) {
            //not real (DCTrue, _) => DCTrue, // can't go lower than true
            (_, Component::DCFalse) => Component::dc_true(), // false can downgrade _anything_ to true
            (Component::DCFalse, _) => Component::dc_false(), // only false can downgrade false
            (Component::DCFormula(mut sec), Component::DCFormula(p)) => {
                sec.retain(|c| !p.iter().any(|pclause| pclause.implies(c)));
                Component::DCFormula(sec)
            }
        };
        self.integrity = privilege.clone() & self.integrity;
        self
    }

    fn downgrade_to(self, target: Self, privilege: &Self::Privilege) -> Self {
        if self.can_flow_to_with_privilege(&target, privilege) {
            return target;
        } else {
            return self;
        }
    }

    fn can_flow_to_with_privilege(&self, rhs: &Self, privilege: &Component) -> bool {
        (rhs.secrecy.clone() & privilege.clone()).implies(&self.secrecy)
            && (self.integrity.clone() & privilege.clone()).implies(&rhs.integrity)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_can_flow_to_with_privilege() {
        let privilege = &Component::formula([["go_grader"]]);
        // declassification
        assert_eq!(
            true,
            Buckle::new([["go_grader"]], [["go_grader"]])
                .can_flow_to_with_privilege(&Buckle::new(true, [["go_grader"]]), privilege)
        );

        assert_eq!(
            true,
            Buckle::new([["go_grader"], ["bob"]], [["go_grader"]])
                .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        assert_eq!(
            true,
            Buckle::new([vec!["go_grader", "staff"], vec!["bob"]], [["go_grader"]])
                .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        assert_eq!(
            true,
            Buckle::new([vec!["go_grader", "staff"], vec!["bob"]], [["go_grader"]])
                .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        assert_eq!(
            true,
            Buckle::new(
                [
                    vec!["go_grader", "staff"],
                    vec!["go_grader", "alice"],
                    vec!["bob"]
                ],
                [["go_grader"]]
            )
            .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        assert_eq!(
            true,
            Buckle::new(
                [
                    vec!["go_grader", "staff"],
                    vec!["go_grader", "alice"],
                    vec!["bob"]
                ],
                [["go_grader"]]
            )
            .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        // banned declassification
        assert_eq!(
            false,
            Buckle::new([["go_grader"], ["staff"], ["bob"]], [["go_grader"]])
                .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );

        // endorse
        assert_eq!(
            true,
            Buckle::new([["bob"]], true)
                .can_flow_to_with_privilege(&Buckle::new([["bob"]], [["go_grader"]]), privilege)
        );
    }

    #[test]
    fn test_downgrade() {

        let privilege = &Component::formula([Clause::new(["princeton.edu", "aalevy"])]);
        assert_eq!(
            Buckle::new(true, privilege.clone()),
            Buckle::new(Component::formula([Clause::new(["princeton.edu", "aalevy"])]), true).downgrade(privilege)
        );
        // True can't downgrade anything
        assert_eq!(
            Buckle::new(true, true),
            Buckle::new(true, true).downgrade(&true.into())
        );
        assert_eq!(
            Buckle::new(false, true),
            Buckle::new(false, true).downgrade(&true.into())
        );
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new(true, false).downgrade(&true.into())
        );
        assert_eq!(
            Buckle::new([["amit"]], false),
            Buckle::new([["amit"]], false).downgrade(&true.into())
        );
        assert_eq!(
            Buckle::new(false, [["amit"]]),
            Buckle::new(false, [["amit"]]).downgrade(&true.into())
        );

        // False downgrades everything
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new(true, true).downgrade(&false.into())
        );
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new(false, true).downgrade(&false.into())
        );
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new(true, false).downgrade(&false.into())
        );
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new([["amit"]], false).downgrade(&false.into())
        );
        assert_eq!(
            Buckle::new(true, false),
            Buckle::new(false, [["amit"]]).downgrade(&false.into())
        );
    }

    #[test]
    fn test_extreme_can_flow_to() {
        assert_eq!(true, Buckle::bottom().can_flow_to(&Buckle::top()));
        assert_eq!(true, Buckle::bottom().can_flow_to(&Buckle::public()));
        assert_eq!(true, Buckle::public().can_flow_to(&Buckle::top()));

        assert_eq!(false, Buckle::top().can_flow_to(&Buckle::bottom()));
        assert_eq!(false, Buckle::top().can_flow_to(&Buckle::public()));
        assert_eq!(false, Buckle::public().can_flow_to(&Buckle::bottom()));
    }

    #[test]
    fn test_basic_can_flow_to_integrity() {
        assert_eq!(
            true,
            Buckle::new(true, [["Amit"]]).can_flow_to(&Buckle::public())
        );

        assert_eq!(
            true,
            Buckle::new(true, [["Amit", "Yue"]]).can_flow_to(&Buckle::public())
        );

        assert_eq!(
            true,
            Buckle::new(true, [["Amit"], ["Yue"]]).can_flow_to(&Buckle::new(true, [["Amit"]]))
        );

        assert_eq!(
            true,
            Buckle::new(true, [["Amit"], ["Yue"]])
                .can_flow_to(&Buckle::new(true, [["Amit", "Yue"]]))
        );

        assert_eq!(
            false,
            Buckle::new(true, [["Amit", "Yue"]])
                .can_flow_to(&Buckle::new(true, [["Amit"], ["Yue"]]))
        );
    }

    #[test]
    fn test_basic_can_flow_to_secrecy() {
        assert_eq!(
            false,
            Buckle::new([["Amit"]], true).can_flow_to(&Buckle::public())
        );

        assert_eq!(
            false,
            Buckle::new([["Amit", "Yue"]], true).can_flow_to(&Buckle::public())
        );

        assert_eq!(
            false,
            Buckle::new([["Amit"], ["Yue"]], true).can_flow_to(&Buckle::new([["Amit"]], true))
        );

        assert_eq!(
            false,
            Buckle::new([["Amit"], ["Yue"]], true).can_flow_to(&Buckle::new([["Amit"]], true))
        );

        assert_eq!(
            false,
            Buckle::new([["Amit"], ["Yue"]], true)
                .can_flow_to(&Buckle::new([["Amit", "Yue"]], true))
        );

        assert_eq!(
            true,
            Buckle::new([["Amit", "Yue"]], true)
                .can_flow_to(&Buckle::new([["Amit"], ["Yue"]], true))
        );
    }

    #[test]
    fn test_lub() {
        assert_eq!(Buckle::top(), Buckle::public().lub(Buckle::top()));
        assert_eq!(Buckle::top(), Buckle::top().lub(Buckle::public()));
        assert_eq!(Buckle::top(), Buckle::bottom().lub(Buckle::top()));
        assert_eq!(Buckle::public(), Buckle::bottom().lub(Buckle::public()));

        assert_eq!(
            Buckle::new([["Amit"], ["Yue"]], true),
            Buckle::new([["Amit"]], true).lub(Buckle::new([["Yue"]], true))
        );

        assert_eq!(
            Buckle::new(true, [["Amit", "Yue"]]),
            Buckle::new(true, [["Amit"]]).lub(Buckle::new(true, [["Yue"]]))
        );
    }

    #[test]
    fn test_glb() {
        assert_eq!(Buckle::public(), Buckle::public().glb(Buckle::top()));
        assert_eq!(Buckle::public(), Buckle::top().glb(Buckle::public()));
        assert_eq!(Buckle::bottom(), Buckle::bottom().glb(Buckle::top()));
        assert_eq!(Buckle::bottom(), Buckle::bottom().glb(Buckle::public()));

        assert_eq!(
            Buckle::new([["Amit", "Yue"]], true),
            Buckle::new([["Amit"]], true).glb(Buckle::new([["Yue"]], true))
        );

        assert_eq!(
            Buckle::new(true, [["Amit"], ["Yue"]]),
            Buckle::new(true, [["Amit"]]).glb(Buckle::new(true, [["Yue"]]))
        );
    }

    #[test]
    fn test_parse() {
        assert_eq!(Buckle::parse("T,T"), Ok(Buckle::public()));
        assert_eq!(Buckle::parse("T,F"), Ok(Buckle::bottom()));
        assert_eq!(Buckle::parse("F,T"), Ok(Buckle::top()));
        assert_eq!(
            Buckle::parse("Amit,Yue"),
            Ok(Buckle::new([["Amit"]], [["Yue"]]))
        );
        assert_eq!(
            Buckle::parse("Amit|Yue,Yue"),
            Ok(Buckle::new([["Amit", "Yue"]], [["Yue"]]))
        );
        assert_eq!(
            Buckle::parse("Amit&Yue,Yue"),
            Ok(Buckle::new([["Amit"], ["Yue"]], [["Yue"]]))
        );
        assert_eq!(
            Buckle::parse("Amit&Yue|Natalie|Gongqi&Deian,Yue"),
            Ok(Buckle::new(
                [
                    Clause::from(["Amit"]),
                    Clause::from(["Yue", "Natalie", "Gongqi"]),
                    Clause::from(["Deian"])
                ],
                [["Yue"]]
            ))
        );
        assert_eq!(
            Buckle::parse(r#"Am\&it&Yue,Y\|ue"#),
            Ok(Buckle::new([["Am&it"], ["Yue"]], [["Y|ue"]]))
        );

        assert_eq!(
            Buckle::parse("Amit/test,Amit"),
            Ok(Buckle::new(
                Component::from([Clause::new_from_vec(vec![vec!["Amit", "test"]])]),
                [["Amit"]]
            ))
        );

        assert_eq!(
            Buckle::parse("princeton.edu/test,Amit"),
            Ok(Buckle::new(
                Component::from([Clause::new_from_vec(vec![vec!["princeton.edu", "test"]])]),
                [["Amit"]]
            ))
        )
    }

    quickcheck! {
        fn everything_can_flow_to_top(lbl: Buckle) -> bool {
            let top = Buckle::top();
            lbl.can_flow_to(&top)
        }

        fn bottom_can_flow_to_everything(lbl: Buckle) -> bool {
            let bottom = Buckle::bottom();
            bottom.can_flow_to(&lbl)
        }

        fn both_can_flow_to_lub(lbl1: Buckle, lbl2: Buckle) -> bool {
            let result = lbl1.clone().lub(lbl2.clone());
            lbl1.can_flow_to(&result) && lbl2.can_flow_to(&result)
        }

        fn glb_can_flow_to_both(lbl1: Buckle, lbl2: Buckle) -> bool {
            let result = lbl1.clone().glb(lbl2.clone());
            result.can_flow_to(&lbl1) && result.can_flow_to(&lbl2)
        }

        fn endorse_equiv_downgrade_to(lbl: Buckle, privilege: Component) -> bool {
            let target = Buckle { secrecy: lbl.secrecy.clone(), integrity: lbl.integrity.clone() & privilege.clone() };
            lbl.clone().downgrade_to(target, &privilege) == lbl.endorse(&privilege)
        }
    }
}