-
Notifications
You must be signed in to change notification settings - Fork 19
/
RuleService.java
336 lines (272 loc) · 10.2 KB
/
RuleService.java
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
/*
* Copyright (c) 2016-2019, Fraunhofer AISEC. All rights reserved.
*
*
* $$\ $$\ $$\ $$\
* $$ | $$ |\__| $$ |
* $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\
* $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\
* $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__|
* $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ |
* \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ |
* \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
*
* This file is part of Clouditor Community Edition.
*
* Clouditor Community Edition is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Clouditor Community Edition is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* long with Clouditor Community Edition. If not, see <https://www.gnu.org/licenses/>
*/
package io.clouditor.assurance;
import static io.clouditor.assurance.RuleService.RuleVisitor.renderText;
import io.clouditor.assurance.ccl.CCLDeserializer;
import io.clouditor.discovery.AssetService;
import io.clouditor.discovery.DiscoveryResult;
import io.clouditor.events.DiscoveryResultSubscriber;
import io.clouditor.util.FileSystemManager;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.BulletList;
import org.commonmark.node.FencedCodeBlock;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.commonmark.renderer.text.TextContentRenderer;
import org.jvnet.hk2.annotations.Service;
/** The {@link RuleService} keeps a map of all rules and their associated asset type. */
@Service
public class RuleService extends DiscoveryResultSubscriber {
@Inject private AssetService assetService;
@Inject private CertificationService certificationService;
private Map<String, Set<Rule>> rules = new HashMap<>();
private RuleService() {
LOGGER.info("Initializing {}...", this.getClass().getSimpleName());
}
public void load(Path path) {
try {
if (Files.isDirectory(path)) {
LOGGER.info("Looping through path {}...", path);
try (var stream = Files.list(path)) {
for (var p : stream.collect(Collectors.toList())) {
if (Files.isDirectory(path) || p.endsWith(".md")) {
this.load(p);
}
}
}
} else {
var rule = loadRule(path);
if (rule.getAssetType() != null) {
// make sure, the set exists
this.rules.putIfAbsent(rule.getAssetType(), new HashSet<>());
// getScanners the set to update it
var set = this.rules.get(rule.getAssetType());
set.add(rule);
LOGGER.info("Added rule {} for asset type {}", path.getFileName(), rule.getAssetType());
}
}
} catch (IOException ex) {
LOGGER.error("Could not load file or path {}: {}", path, ex.getMessage());
}
}
public RuleEvaluation getStatus(Rule rule) {
var status = new RuleEvaluation(rule);
var assets = this.assetService.getAssetsWithType(rule.getAssetType());
for (var asset : assets) {
var o =
asset.getEvaluationResults().stream()
.filter(result -> Objects.equals(result.getRule().getId(), rule.getId()))
.findAny();
if (o.isPresent() && o.get().isOk()) {
status.addCompliant(asset);
} else {
status.addNonCompliant(asset);
}
}
return status;
}
public Rule getWithId(String id) {
return rules.entrySet().stream()
.flatMap(e -> e.getValue().stream().filter(rule -> Objects.equals(rule.getId(), id)))
.findFirst()
.orElse(null);
}
public static class ControlsVisitor extends AbstractVisitor {
private Rule rule;
ControlsVisitor(Rule rule) {
this.rule = rule;
}
@Override
public void visit(BulletList bulletList) {
var node = bulletList.getFirstChild();
this.rule.getControls().add(renderText(node.getFirstChild()));
while (node.getNext() != null) {
node = node.getNext();
this.rule.getControls().add(renderText(node.getFirstChild()));
}
}
}
public static class RuleVisitor extends AbstractVisitor {
private Rule rule;
RuleVisitor(Rule rule) {
this.rule = rule;
}
@Override
public void visit(Heading heading) {
var title = renderText(heading).trim();
switch (heading.getLevel()) {
case 1:
// update the name
this.rule.setName(title);
// update the description
var next = heading.getNext();
// if the next one is a Heading, then we have no description
if (!(next instanceof Heading)) {
this.rule.setDescription(renderHTML(next));
}
// additionally, visit all children of the heading to parse code blocks
this.visitChildren(heading);
break;
case 2:
if (title.equals("Controls")) {
var node = heading.getNext();
node.accept(new ControlsVisitor(this.rule));
}
break;
default:
super.visit(heading);
}
}
@Override
public void visit(FencedCodeBlock fencedCodeBlock) {
if (fencedCodeBlock.getInfo().equals("ccl")) {
var code = fencedCodeBlock.getLiteral();
// parse CCL
// for now, one line is one condition, later me might have more complex statements
var lines = code.split("\\n");
for (var line : lines) {
// TODO: this should actually be handled by the grammar
if (!line.startsWith("#")) {
var condition = new CCLDeserializer().parse(line);
this.rule.addCondition(condition);
}
}
} else {
super.visit(fencedCodeBlock);
}
}
private static String renderHTML(Node node) {
var renderer = HtmlRenderer.builder().build();
return renderer.render(node);
}
static String renderText(Node node) {
var renderer = TextContentRenderer.builder().build();
return renderer.render(node);
}
}
/**
* Loads a rule from a Markdown-style document specified by the path.
*
* @param path The path to the Markdown file
* @return a parsed {@link Rule}
* @throws IOException if a parsing error occurred
*/
public Rule loadRule(Path path) throws IOException {
var rule = new Rule();
LOGGER.info("Trying to load rule from {}...", path.getFileName());
var parser = Parser.builder().build();
var doc = parser.parseReader(new InputStreamReader(Files.newInputStream(path)));
doc.accept(new RuleVisitor(rule));
rule.setId(
path.getParent().getParent().getFileName()
+ "-"
+ path.getParent().getFileName()
+ "-"
+ path.getFileName().toString().split("\\.")[0]);
rule.setActive(true);
return rule;
}
public Set<Rule> get(String assetType) {
return this.rules.getOrDefault(assetType, Collections.emptySet()).stream()
.filter(Rule::isActive)
.collect(Collectors.toSet());
}
@Override
public void handle(DiscoveryResult result) {
LOGGER.info("Handling scan result from {}", result.getTimestamp());
for (var asset : result.getDiscoveredAssets().values()) {
// find rules for the asset
var assetType = asset.getType();
var rulesForAsset = this.get(assetType);
// update it regardless of rules, so even an asset with an empty rule set gets recognized
// TODO: pub/sub?
assetService.update(asset);
LOGGER.debug("Evaluating {} rules for asset {}", rulesForAsset.size(), asset.getId());
// evaluate all rules
rulesForAsset.forEach(
rule -> {
EvaluationResult eval;
if (!rule.evaluateApplicability(asset)) {
// simply add an empty EvaluationResult
eval = new EvaluationResult(rule, asset.getProperties());
} else {
eval = rule.evaluate(asset);
}
// TODO: can we really update the asset?
asset.addEvaluationResult(eval);
if (!eval.isOk()) {
LOGGER.info(
"The following rule failed for asset {} with {} failed conditions: {}",
asset.getId(),
eval.getFailedConditions().size(),
rule.getName());
}
// update asset
assetService.update(asset);
});
}
// now all assets should be evaluated, now we can update the certification
// TODO: would be nice to only update relevant controls
this.certificationService.updateCertification();
}
public Map<String, Set<Rule>> getRules() {
return this.rules;
}
public List<Rule> getRulesForControl(String controlId) {
return this.rules.values().stream()
.flatMap(Collection::stream)
.filter(rule -> rule.getControls() != null && rule.getControls().contains(controlId))
.collect(Collectors.toList());
}
public void loadAll() {
try {
load(FileSystemManager.getInstance().getPathForResource("rules/aws"));
load(FileSystemManager.getInstance().getPathForResource("rules/azure"));
} catch (IOException e) {
LOGGER.error("Could not load rules", e);
}
LOGGER.info("Loaded {} rules", this.rules.size());
}
}