cfn-guard-preview 0.7.0

A preview for CloudFormation Guard (cfn-guard)
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::{HashMap, HashSet};
use std::env;

use log::{self, debug, error, trace};
use regex::{Captures, Regex};
use serde_json::Value;

use crate::guard_types::enums::{CompoundType, LineType, OpCode, RValueType, RuleType};
use crate::guard_types::structs::{CompoundRule, ConditionalRule, ParsedRuleSet, Rule};
use crate::util;
use lazy_static::lazy_static;

// This sets it up so the regexen only get compiled once
// See: https://docs.rs/regex/1.3.9/regex/#example-avoid-compiling-the-same-regex-in-a-loop
lazy_static! {
    static ref ASSIGN_REG: Regex = Regex::new(r"let (?P<var_name>\w+) +(?P<operator>\S+) +(?P<var_value>.+)").unwrap();
    static ref RULE_REG: Regex = Regex::new(r"^(?P<resource_type>\S+) +(?P<resource_property>[\w\.\|\*]+) +(?P<operator>==|!=|<|>|<=|>=|IN|NOT_IN) +(?P<rule_value>[^\n\r]+)").unwrap();
    static ref COMMENT_REG: Regex = Regex::new(r#"^#(?P<comment>.*)"#).unwrap();
    static ref WILDCARD_OR_RULE_REG: Regex = Regex::new(r"(\S+) (\S*\*\S*) (==|IN) (.+)").unwrap();
    static ref RULE_WITH_OPTIONAL_MESSAGE_REG: Regex = Regex::new(
        r"^(?P<resource_type>\S+) +(?P<resource_property>[\w\.\*]+) +(?P<operator>==|!=|<|>|<=|>=|IN|NOT_IN) +(?P<rule_value>[^\n\r]+) +<{2} *(?P<custom_msg>.*)").unwrap();
    static ref WHITE_SPACE_REG: Regex = Regex::new(r"^\s+$").unwrap();
    static ref CONDITIONAL_RULE_REG: Regex = Regex::new(r"(?P<resource_type>\S+) +(when|WHEN) +(?P<condition>.+) +(check|CHECK) +(?P<consequent>.*)").unwrap();
}

pub(crate) fn parse_rules(
    rules_file_contents: &str,
    cfn_resources: &HashMap<String, Value>,
) -> Result<ParsedRuleSet, String> {
    debug!("Entered parse_rules");
    trace!(
        "Parse rules entered with rules_file_contents: {:#?}",
        &rules_file_contents
    );
    trace!(
        "Parse rules entered with cfn_resources: {:#?}",
        &cfn_resources
    );

    let mut rule_set: Vec<RuleType> = vec![];
    let mut variables = HashMap::new();

    let lines = rules_file_contents.lines();
    trace!(
        "Rules file lines: {:#?}",
        lines.clone().into_iter().collect::<Vec<&str>>()
    );

    for l in lines {
        debug!("Parsing '{}'", &l);
        let trimmed_line = l.trim();
        if trimmed_line.is_empty() {
            continue;
        };
        let line_type = match find_line_type(trimmed_line) {
            Ok(lt) => lt,
            Err(e) => return Err(e),
        };
        debug!("line_type is {:#?}", line_type);
        match line_type {
            LineType::Assignment => {
                let caps = match process_assignment(trimmed_line) {
                    Ok(a) => a,
                    Err(e) => return Err(e),
                };
                trace!("Parsed assignment's captures are: {:#?}", &caps);
                if caps["operator"] != *"=" {
                    let msg_string = format!(
                        "Bad Assignment Operator: [{}] in '{}'",
                        &caps["operator"], trimmed_line
                    );
                    error!("{}", &msg_string);
                    return Err(msg_string);
                }
                let var_name = caps["var_name"].to_string();
                let var_value = caps["var_value"].to_string();
                trace!(
                    "Inserting key: [{}], value: [{}] into variables",
                    var_name,
                    var_value
                );
                variables.insert(var_name, var_value);
            }
            LineType::Comment => (),
            LineType::Rule => match parse_rule_line(trimmed_line, &cfn_resources) {
                Ok(prl) => {
                    debug!("Parsed rule is: {:#?}", &prl);
                    rule_set.push(prl)
                }
                Err(e) => return Err(e),
            },
            LineType::Conditional => match parse_rule_line(trimmed_line, &cfn_resources) {
                Ok(c) => {
                    debug!("Parsed conditional is {:#?}", &c);
                    rule_set.push(c);
                }
                Err(e) => return Err(e),
            },
            LineType::WhiteSpace => {
                debug!("Line is white space");
                continue;
            }
        }
    }
    for (key, value) in env::vars() {
        let key_name = format!("ENV_{}", key);
        variables.insert(key_name, value);
    }
    let filtered_env_vars = util::filter_for_env_vars(&variables);
    debug!("Variables dictionary is {:?}", &filtered_env_vars);
    debug!("Rule Set is {:#?}", &rule_set);
    Ok(ParsedRuleSet {
        variables,
        rule_set,
    })
}

fn parse_rule_line(l: &str, cfn_resources: &HashMap<String, Value>) -> Result<RuleType, String> {
    match is_or_rule(l) {
        true => {
            debug!("Line is an |OR| rule");
            match process_or_rule(l, &cfn_resources) {
                Ok(r) => Ok(r),
                Err(e) => Err(e),
            }
        }
        false => {
            debug!("Line is an 'AND' rule");
            match process_and_rule(l, &cfn_resources) {
                Ok(r) => Ok(r),
                Err(e) => return Err(e),
            }
        }
    }
}

fn process_conditional(
    line: &str,
    cfn_resources: &HashMap<String, Value>,
) -> Result<ConditionalRule, String> {
    let caps = CONDITIONAL_RULE_REG.captures(line).unwrap();
    trace!("ConditionalRule regex captures are {:#?}", &caps);

    if RULE_REG.is_match(&caps["condition"])
        || RULE_WITH_OPTIONAL_MESSAGE_REG.is_match(&caps["condition"])
    {
        return Err(format!(
            "Invalid condition: '{}' in '{}'",
            &caps["condition"], line
        ));
    }
    let conjd_caps_conditional = format!("{} {}", &caps["resource_type"], &caps["condition"]);
    trace!("conjd_caps_conditional is {:#?}", conjd_caps_conditional);
    match parse_rule_line(&conjd_caps_conditional, cfn_resources) {
        Ok(cond) => {
            let condition = match cond {
                RuleType::CompoundRule(s) => s,
                _ => return Err(format!("Bad destructure of conditional rule: {}", line)),
            };
            if RULE_REG.is_match(&caps["consequent"])
                || RULE_WITH_OPTIONAL_MESSAGE_REG.is_match(&caps["consequent"])
            {
                return Err(format!(
                    "Invalid consequent: '{}' in '{}'. Consequents cannot contain resource types.",
                    &caps["consequent"], line
                ));
            }
            let conjd_caps_consequent =
                format!("{} {}", &caps["resource_type"], &caps["consequent"]);
            trace!("conjd_caps_consequent is {:#?}", conjd_caps_consequent);
            match parse_rule_line(&conjd_caps_consequent, cfn_resources) {
                Ok(cons) => {
                    let consequent = match cons {
                        RuleType::CompoundRule(s) => s,
                        _ => return Err(format!("Bad destructure of conditional rule: {}", line)),
                    };
                    Ok(ConditionalRule {
                        condition,
                        consequent,
                    })
                }
                Err(e) => Err(e),
            }
        }
        Err(e) => Err(e),
    }
}

fn find_line_type(line: &str) -> Result<LineType, String> {
    if COMMENT_REG.is_match(line) {
        return Ok(LineType::Comment);
    };
    if ASSIGN_REG.is_match(line) {
        return Ok(LineType::Assignment);
    };
    if CONDITIONAL_RULE_REG.is_match(line) {
        return Ok(LineType::Conditional);
    };
    if RULE_REG.is_match(line) {
        return Ok(LineType::Rule);
    };
    if WHITE_SPACE_REG.is_match(line) {
        return Ok(LineType::WhiteSpace);
    }
    let msg_string = format!("BAD RULE: {:?}", line);
    error!("{}", &msg_string);
    Err(msg_string)
}

fn process_assignment(line: &str) -> Result<Captures, String> {
    match ASSIGN_REG.captures(line) {
        Some(c) => Ok(c),
        None => Err(format!("Invalid assignment statement: '{}", line)),
    }
}

fn is_or_rule(line: &str) -> bool {
    line.contains("|OR|") || WILDCARD_OR_RULE_REG.is_match(line)
}

fn process_or_rule(line: &str, cfn_resources: &HashMap<String, Value>) -> Result<RuleType, String> {
    trace!("Entered process_or_rule");
    let branches = line.split("|OR|");
    // debug!("Rule branches are: {:#?}", &branches);
    let mut rules: Vec<RuleType> = vec![];
    for b in branches {
        debug!("Rule |OR| branch is '{}'", b);
        match destructure_rule(b.trim(), cfn_resources) {
            Ok(r) => rules.append(&mut r.clone()),
            Err(e) => return Err(e),
        }
    }
    Ok(RuleType::CompoundRule(CompoundRule {
        compound_type: CompoundType::OR,
        raw_rule: line.to_string(),
        rule_list: rules,
    }))
}

fn process_and_rule(
    line: &str,
    cfn_resources: &HashMap<String, Value>,
) -> Result<RuleType, String> {
    trace!("Entered process_and_rule");
    let branches = line.split("|AND|");
    let mut rules: Vec<RuleType> = vec![];
    for b in branches {
        debug!("AND rule branch is: {:#?}", &b);
        match destructure_rule(b.trim(), cfn_resources) {
            Ok(r) => rules.append(&mut r.clone()),
            Err(e) => return Err(e),
        }
    }
    Ok(RuleType::CompoundRule(CompoundRule {
        compound_type: CompoundType::AND,
        raw_rule: line.to_string(),
        rule_list: rules,
    }))
}

fn destructure_rule(
    rule_text: &str,
    cfn_resources: &HashMap<String, Value>,
) -> Result<Vec<RuleType>, String> {
    trace!("Entered destructure_rule");
    let mut rules_hash: HashSet<RuleType> = HashSet::new();
    if CONDITIONAL_RULE_REG.is_match(rule_text) {
        match process_conditional(rule_text, cfn_resources) {
            Ok(r) => {
                rules_hash.insert(RuleType::ConditionalRule(r));
            }
            Err(e) => return Err(e),
        }
    } else {
        let caps = match RULE_WITH_OPTIONAL_MESSAGE_REG.captures(rule_text) {
            Some(c) => c,
            None => match RULE_REG.captures(rule_text) {
                Some(c) => c,
                None => {
                    return Err(format!("Invalid rule: {}", rule_text));
                }
            },
        };

        trace!("Parsed rule's captures are: {:#?}", &caps);
        let mut props: Vec<String> = vec![];
        if caps["resource_property"].contains('*') {
            for (_name, value) in cfn_resources {
                if caps["resource_type"] == value["Type"] {
                    let target_field: Vec<&str> = caps["resource_property"].split('.').collect();
                    let (property_root, address) = match target_field.first() {
                        Some(x) => {
                            if *x == "" {
                                // If the first address segment is a '.'
                                (value, target_field) // Return the root of the Value for lookup
                            } else {
                                // Otherwise, treat it as a normal property lookup
                                (&value["Properties"], target_field)
                            }
                        }
                        None => {
                            let msg_string =
                                format!("Invalid property address: {:#?}", target_field);
                            error!("{}", msg_string);
                            return Err(msg_string);
                        }
                    };
                    if let Some(p) = util::expand_wildcard_props(
                        property_root,
                        address.join("."),
                        String::from(""),
                    ) {
                        props.append(&mut p.clone());
                        trace!("Expanded props are {:#?}", &props);
                    }
                }
            }
        } else {
            props.push(caps["resource_property"].to_string());
        };

        for p in props {
            let rule = Rule {
                resource_type: caps["resource_type"].to_string(),
                field: p.to_string(),
                operation: {
                    match &caps["operator"] {
                        "==" => OpCode::Require,
                        "!=" => OpCode::RequireNot,
                        "<" => OpCode::LessThan,
                        ">" => OpCode::GreaterThan,
                        "<=" => OpCode::LessThanOrEqualTo,
                        ">=" => OpCode::GreaterThanOrEqualTo,
                        "IN" => OpCode::In,
                        "NOT_IN" => OpCode::NotIn,
                        _ => {
                            let msg_string = format!(
                                "Bad Rule Operator: [{}] in '{}'",
                                &caps["operator"], rule_text
                            );
                            error!("{}", &msg_string);
                            return Err(msg_string);
                        }
                    }
                },
                rule_vtype: {
                    let rv = caps["rule_value"].chars().next().unwrap();
                    match rv {
                        '[' => match &caps["operator"] {
                            "==" | "!=" | "<=" | ">=" | "<" | ">" => RValueType::Value,
                            "IN" | "NOT_IN" => RValueType::List,
                            _ => {
                                let msg_string = format!(
                                    "Bad Rule Operator: [{}] in '{}'",
                                    &caps["operator"], rule_text
                                );
                                error!("{}", &msg_string);
                                return Err(msg_string);
                            }
                        },
                        '/' => RValueType::Regex,
                        '%' => RValueType::Variable,
                        _ => RValueType::Value,
                    }
                },
                value: {
                    let rv = caps["rule_value"].chars().next().unwrap();
                    match rv {
                        '/' => caps["rule_value"].trim_matches('/').to_string(),
                        _ => caps["rule_value"].to_string().trim().to_string(),
                    }
                },
                custom_msg: match caps.name("custom_msg") {
                    Some(s) => Some(s.as_str().to_string()),
                    None => None,
                },
            };
            rules_hash.insert(RuleType::SimpleRule(rule));
        }
    }

    let rules = rules_hash.into_iter().collect::<Vec<RuleType>>();
    trace!("Destructured rules are: {:#?}", &rules);
    Ok(rules)
}

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

    #[test]
    fn test_find_line_type() {
        let comment = find_line_type("# This is a comment");
        let assignment = find_line_type("let x = assignment");
        let rule = find_line_type("AWS::EC2::Volume Encryption == true");
        let white_space = find_line_type("         ");
        assert_eq!(comment, Ok(crate::enums::LineType::Comment));
        assert_eq!(assignment, Ok(crate::enums::LineType::Assignment));
        assert_eq!(rule, Ok(crate::enums::LineType::Rule));
        assert_eq!(white_space, Ok(crate::enums::LineType::WhiteSpace))
    }

    #[test]
    fn test_parse_variable() {
        let assignment = "let var = [128]";
        let cfn_resources: HashMap<String, Value> = HashMap::new();
        let mut var_map: HashMap<String, String> = HashMap::new();
        var_map.insert("var".to_string(), "[128]".to_string());

        let parsed_rules = parse_rules(assignment, &cfn_resources).unwrap();
        assert!(parsed_rules.variables["var"] == "[128]");
    }
}