19 package org.sleuthkit.autopsy.modules.interestingitems;
22 import java.io.FileInputStream;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.Serializable;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.logging.Level;
32 import java.util.regex.Pattern;
33 import java.util.regex.PatternSyntaxException;
34 import javax.xml.parsers.DocumentBuilder;
35 import javax.xml.parsers.DocumentBuilderFactory;
36 import javax.xml.parsers.ParserConfigurationException;
37 import org.openide.util.io.NbObjectInputStream;
38 import org.openide.util.io.NbObjectOutputStream;
48 import org.w3c.dom.Document;
49 import org.w3c.dom.Element;
50 import org.w3c.dom.NodeList;
52 class InterestingItemsFilesSetSettings
implements Serializable {
54 private static final long serialVersionUID = 1L;
57 private static final String FILE_SETS_ROOT_TAG =
"INTERESTING_FILE_SETS";
58 private static final String DESC_ATTR =
"description";
59 private static final String IGNORE_KNOWN_FILES_ATTR =
"ignoreKnown";
60 private static final String PATH_REGEX_ATTR =
"pathRegex";
61 private static final String TYPE_FILTER_VALUE_ALL =
"all";
62 private static final String TYPE_FILTER_VALUE_FILES_AND_DIRS =
"files_and_dirs";
63 private static final String IGNORE_UNALLOCATED_SPACE =
"ingoreUnallocated";
64 private static final String PATH_FILTER_ATTR =
"pathFilter";
65 private static final String TYPE_FILTER_VALUE_DIRS =
"dir";
66 private static final String REGEX_ATTR =
"regex";
67 private static final List<String> illegalFileNameChars = FilesSetsManager.getIllegalFileNameChars();
68 private static final String FILE_SET_TAG =
"INTERESTING_FILE_SET";
69 private static final String NAME_RULE_TAG =
"NAME";
70 private static final String NAME_ATTR =
"name";
71 private static final String DAYS_INCLUDED_ATTR =
"daysIncluded";
72 private static final String MIME_ATTR =
"mimeType";
73 private static final String FS_COMPARATOR_ATTR =
"comparatorSymbol";
74 private static final String FS_SIZE_ATTR =
"sizeValue";
75 private static final String FS_UNITS_ATTR =
"sizeUnits";
76 private static final String TYPE_FILTER_VALUE_FILES =
"file";
77 private static final String XML_ENCODING =
"UTF-8";
78 private static final Logger logger = Logger.getLogger(InterestingItemsFilesSetSettings.class.getName());
79 private static final String TYPE_FILTER_ATTR =
"typeFilter";
80 private static final String EXTENSION_RULE_TAG =
"EXTENSION";
82 private Map<String, FilesSet> filesSets;
84 InterestingItemsFilesSetSettings(Map<String, FilesSet> filesSets) {
85 this.filesSets = filesSets;
91 Map<String, FilesSet> getFilesSets() {
102 private static String readRuleName(Element elem) {
104 String ruleName = elem.getAttribute(NAME_ATTR);
116 private static Map<String, FilesSet> readSerializedDefinitions(String serialFileName)
throws FilesSetsManager.FilesSetsManagerException {
117 Path filePath = Paths.get(PlatformUtil.getUserConfigDirectory(), serialFileName);
118 File fileSetFile = filePath.toFile();
119 String filePathStr = filePath.toString();
120 if (fileSetFile.exists()) {
122 try (
final NbObjectInputStream in =
new NbObjectInputStream(
new FileInputStream(filePathStr))) {
123 InterestingItemsFilesSetSettings filesSetsSettings = (InterestingItemsFilesSetSettings) in.readObject();
124 return filesSetsSettings.getFilesSets();
126 }
catch (IOException | ClassNotFoundException ex) {
127 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Failed to read settings from %s", filePathStr), ex);
130 return new HashMap<>();
145 private static ParentPathCondition readPathCondition(Element ruleElement)
throws FilesSetsManager.FilesSetsManagerException {
148 ParentPathCondition pathCondition = null;
149 if (!ruleElement.getAttribute(PATH_FILTER_ATTR).isEmpty() || !ruleElement.getAttribute(PATH_REGEX_ATTR).isEmpty()) {
150 String path = ruleElement.getAttribute(PATH_FILTER_ATTR);
151 String pathRegex = ruleElement.getAttribute(PATH_REGEX_ATTR);
152 if (!pathRegex.isEmpty() && path.isEmpty()) {
154 Pattern pattern = Pattern.compile(pathRegex);
155 pathCondition =
new ParentPathCondition(pattern);
156 }
catch (PatternSyntaxException ex) {
157 logger.log(Level.SEVERE,
"Error compiling " + PATH_REGEX_ATTR +
" regex, ignoring malformed path condition definition", ex);
158 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"error compiling %s regex", PATH_REGEX_ATTR), ex);
160 }
else if (!path.isEmpty() && pathRegex.isEmpty()) {
161 pathCondition =
new ParentPathCondition(path);
163 if (pathCondition == null) {
165 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Error creating path condition for rule %s", readRuleName(ruleElement)));
168 return pathCondition;
182 private static DateCondition readDateCondition(Element ruleElement)
throws FilesSetsManager.FilesSetsManagerException {
185 DateCondition dateCondition = null;
186 if (!ruleElement.getAttribute(DAYS_INCLUDED_ATTR).isEmpty()) {
187 String daysIncluded = ruleElement.getAttribute(DAYS_INCLUDED_ATTR);
188 if (!daysIncluded.isEmpty()) {
190 dateCondition =
new DateCondition(Integer.parseInt(daysIncluded));
191 }
catch (NumberFormatException ex) {
192 logger.log(Level.SEVERE,
"Error creating condition for " + daysIncluded +
", ignoring malformed date condition definition", ex);
193 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"error compiling %s regex", DAYS_INCLUDED_ATTR), ex);
197 return dateCondition;
207 private static Pattern compileRegex(String regex) {
209 return Pattern.compile(regex);
210 }
catch (PatternSyntaxException ex) {
211 logger.log(Level.SEVERE,
"Error compiling rule regex: " + ex.getMessage(), ex);
228 private static FilesSet.Rule readRule(Element elem)
throws FilesSetsManager.FilesSetsManagerException {
229 String ruleName = readRuleName(elem);
230 FileNameCondition nameCondition = readNameCondition(elem);
231 MetaTypeCondition metaCondition = readMetaTypeCondition(elem);
232 ParentPathCondition pathCondition = readPathCondition(elem);
233 MimeTypeCondition mimeCondition = readMimeCondition(elem);
234 FileSizeCondition sizeCondition = readSizeCondition(elem);
235 DateCondition dateCondition = readDateCondition(elem);
236 if (metaCondition == null || (nameCondition == null && pathCondition == null && mimeCondition == null && sizeCondition == null && dateCondition == null)) {
237 logger.log(Level.WARNING,
"Error Reading Rule, " + ruleName +
" was either missing a meta condition or contained only a meta condition. No rule was imported.");
238 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Invalid Rule in FilesSet xml, missing necessary conditions for %s", ruleName));
240 return new FilesSet.Rule(ruleName, nameCondition, metaCondition, pathCondition, mimeCondition, sizeCondition, dateCondition);
254 private static FileNameCondition readNameCondition(Element elem)
throws FilesSetsManager.FilesSetsManagerException {
255 FileNameCondition nameCondition = null;
256 String content = elem.getTextContent();
257 String regex = elem.getAttribute(REGEX_ATTR);
258 if (content != null && !content.isEmpty()) {
259 if ((!regex.isEmpty() && regex.equalsIgnoreCase(
"true")) || content.contains(
"*")) {
260 Pattern pattern = compileRegex(content);
261 if (pattern != null) {
262 if (elem.getTagName().equals(NAME_RULE_TAG)) {
263 nameCondition =
new FilesSet.Rule.FullNameCondition(pattern);
264 }
else if (elem.getTagName().equals(EXTENSION_RULE_TAG)) {
265 nameCondition =
new FilesSet.Rule.ExtensionCondition(pattern);
267 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Name condition has invalid tag name of %s for rule %s", elem.getTagName(), readRuleName(elem)));
270 logger.log(Level.SEVERE,
"Error compiling " + elem.getTagName() +
" regex, ignoring malformed '{0}' rule definition", readRuleName(elem));
271 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"error compiling %s regex in rule %s", REGEX_ATTR, readRuleName(elem)));
274 for (String illegalChar : illegalFileNameChars) {
275 if (content.contains(illegalChar)) {
276 logger.log(Level.SEVERE, elem.getTagName() +
" content has illegal chars, ignoring malformed '{0}' rule definition",
new Object[]{elem.getTagName(), readRuleName(elem)});
277 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"File name has illegal character of %s in rule %s", illegalChar, readRuleName(elem)));
280 if (elem.getTagName().equals(NAME_RULE_TAG)) {
281 nameCondition =
new FilesSet.Rule.FullNameCondition(content);
282 }
else if (elem.getTagName().equals(EXTENSION_RULE_TAG)) {
283 nameCondition =
new FilesSet.Rule.ExtensionCondition(content);
287 return nameCondition;
298 private static MimeTypeCondition readMimeCondition(Element elem) {
299 MimeTypeCondition mimeCondition = null;
300 if (!elem.getAttribute(MIME_ATTR).isEmpty()) {
301 mimeCondition =
new MimeTypeCondition(elem.getAttribute(MIME_ATTR));
306 return mimeCondition;
320 private static FileSizeCondition readSizeCondition(Element elem)
throws FilesSetsManager.FilesSetsManagerException {
321 FileSizeCondition sizeCondition = null;
322 if (!elem.getAttribute(FS_COMPARATOR_ATTR).isEmpty() && !elem.getAttribute(FS_SIZE_ATTR).isEmpty() && !elem.getAttribute(FS_UNITS_ATTR).isEmpty()) {
324 FileSizeCondition.COMPARATOR comparator = FileSizeCondition.COMPARATOR.fromSymbol(elem.getAttribute(FS_COMPARATOR_ATTR));
325 FileSizeCondition.SIZE_UNIT sizeUnit = FileSizeCondition.SIZE_UNIT.fromName(elem.getAttribute(FS_UNITS_ATTR));
326 int size = Integer.parseInt(elem.getAttribute(FS_SIZE_ATTR));
327 sizeCondition =
new FileSizeCondition(comparator, sizeUnit, size);
328 }
catch (NumberFormatException nfEx) {
329 logger.log(Level.SEVERE,
"Value in file size attribute was not an integer, unable to create FileSizeCondition for rule: " + readRuleName(elem), nfEx);
330 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Non integer size in FilesSet XML for rule %s", readRuleName(elem)), nfEx);
331 }
catch (IllegalArgumentException iaEx) {
332 logger.log(Level.SEVERE,
"Invalid Comparator symbol or Size Unit set in FilesSet xml, unable to create FileSizeCondition for rule: " + readRuleName(elem), iaEx);
333 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Invalid Comparator or Size unit in FilesSet XML for rule %s", readRuleName(elem)), iaEx);
336 else if (!elem.getAttribute(FS_COMPARATOR_ATTR).isEmpty() || !elem.getAttribute(FS_SIZE_ATTR).isEmpty() || !elem.getAttribute(FS_UNITS_ATTR).isEmpty()) {
337 logger.log(Level.SEVERE,
"Invalid Comparator symbol or Size Unit set in FilesSet xml, unable to create FileSizeCondition for rule: " + readRuleName(elem));
338 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"XML malformed missing at least one fileSize attribute for rule %s", readRuleName(elem)));
340 return sizeCondition;
353 private static void readFilesSet(Element setElem, Map<String, FilesSet> filesSets, String filePath)
throws FilesSetsManager.FilesSetsManagerException {
355 String setName = setElem.getAttribute(NAME_ATTR);
356 if (setName.isEmpty()) {
357 logger.log(Level.SEVERE,
"Found {0} element without required {1} attribute, ignoring malformed file set definition in FilesSet definition file at {2}",
new Object[]{FILE_SET_TAG, NAME_ATTR, filePath});
360 if (filesSets.containsKey(setName)) {
361 logger.log(Level.SEVERE,
"Found duplicate definition of set named {0} in FilesSet definition file at {1}, discarding duplicate set",
new Object[]{setName, filePath});
365 String description = setElem.getAttribute(DESC_ATTR);
368 String ignoreKnown = setElem.getAttribute(IGNORE_KNOWN_FILES_ATTR);
369 boolean ignoreKnownFiles =
false;
370 if (!ignoreKnown.isEmpty()) {
371 ignoreKnownFiles = Boolean.parseBoolean(ignoreKnown);
375 String ignoreUnallocated = setElem.getAttribute(IGNORE_UNALLOCATED_SPACE);
376 boolean ignoreUnallocatedSpace =
false;
377 if (!ignoreUnallocated.isEmpty()) {
378 ignoreUnallocatedSpace = Boolean.parseBoolean(ignoreUnallocated);
381 Map<String, FilesSet.Rule> rules =
new HashMap<>();
382 NodeList allRuleElems = setElem.getChildNodes();
383 for (
int j = 0; j < allRuleElems.getLength(); ++j) {
384 if (allRuleElems.item(j) instanceof Element) {
385 Element elem = (Element) allRuleElems.item(j);
386 FilesSet.Rule rule = readRule(elem);
388 if (!rules.containsKey(rule.getUuid())) {
389 rules.put(rule.getUuid(), rule);
391 logger.log(Level.SEVERE,
"Found duplicate rule {0} for set named {1} in FilesSet definition file at {2}, discarding malformed set",
new Object[]{rule.getUuid(), setName, filePath});
395 logger.log(Level.SEVERE,
"Found malformed rule for set named {0} in FilesSet definition file at {1}, discarding malformed set",
new Object[]{setName, filePath});
403 FilesSet set =
new FilesSet(setName, description, ignoreKnownFiles, ignoreUnallocatedSpace, rules);
404 filesSets.put(set.getName(), set);
422 static Map<String, FilesSet> readDefinitionsFile(String fileName, String legacyFileName)
throws FilesSetsManager.FilesSetsManagerException {
423 Map<String, FilesSet> filesSets = readSerializedDefinitions(fileName);
424 if (!filesSets.isEmpty()) {
428 if (!legacyFileName.isEmpty()) {
429 return readDefinitionsXML(Paths.get(PlatformUtil.getUserConfigDirectory(), legacyFileName).toFile());
447 static Map<String, FilesSet> readDefinitionsXML(File xmlFile)
throws FilesSetsManager.FilesSetsManagerException {
448 Map<String, FilesSet> filesSets =
new HashMap<>();
449 if (!xmlFile.exists()) {
453 if (!xmlFile.canRead()) {
454 logger.log(Level.SEVERE,
"FilesSet definition file at {0} exists, but cannot be read", xmlFile.getPath());
458 Document doc = XMLUtil.loadDoc(InterestingItemsFilesSetSettings.class, xmlFile.getPath());
460 logger.log(Level.SEVERE,
"FilesSet definition file at {0}", xmlFile.getPath());
464 Element root = doc.getDocumentElement();
466 logger.log(Level.SEVERE,
"Failed to get root {0} element tag of FilesSet definition file at {1}",
new Object[]{FILE_SETS_ROOT_TAG, xmlFile.getPath()});
470 NodeList setElems = root.getElementsByTagName(FILE_SET_TAG);
471 for (
int i = 0; i < setElems.getLength(); ++i) {
472 readFilesSet((Element) setElems.item(i), filesSets, xmlFile.getPath());
487 static boolean writeDefinitionsFile(String fileName, Map<String, FilesSet> interestingFilesSets)
throws FilesSetsManager.FilesSetsManagerException {
488 try (
final NbObjectOutputStream out =
new NbObjectOutputStream(
new FileOutputStream(Paths.get(PlatformUtil.getUserConfigDirectory(), fileName).toString()))) {
489 out.writeObject(
new InterestingItemsFilesSetSettings(interestingFilesSets));
490 }
catch (IOException ex) {
491 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Failed to write settings to %s", fileName), ex);
505 static boolean exportXmlDefinitionsFile(File xmlFile, List<FilesSet> interestingFilesSets) {
506 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
509 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
510 Document doc = docBuilder.newDocument();
511 Element rootElement = doc.createElement(FILE_SETS_ROOT_TAG);
512 doc.appendChild(rootElement);
514 for (FilesSet set : interestingFilesSets) {
516 Element setElement = doc.createElement(FILE_SET_TAG);
517 setElement.setAttribute(NAME_ATTR, set.getName());
518 setElement.setAttribute(DESC_ATTR, set.getDescription());
519 setElement.setAttribute(IGNORE_KNOWN_FILES_ATTR, Boolean.toString(set.ignoresKnownFiles()));
522 for (FilesSet.Rule rule : set.getRules().values()) {
527 FileNameCondition nameCondition = rule.getFileNameCondition();
532 if (nameCondition instanceof FilesSet.Rule.FullNameCondition) {
533 ruleElement = doc.createElement(NAME_RULE_TAG);
535 ruleElement = doc.createElement(EXTENSION_RULE_TAG);
538 ruleElement.setAttribute(NAME_ATTR, rule.getName());
539 if (nameCondition != null) {
541 ruleElement.setAttribute(REGEX_ATTR, Boolean.toString(nameCondition.isRegex()));
543 ruleElement.setTextContent(nameCondition.getTextToMatch());
546 MetaTypeCondition typeCondition = rule.getMetaTypeCondition();
547 switch (typeCondition.getMetaType()) {
549 ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_FILES);
552 ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_DIRS);
555 ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_ALL);
559 ParentPathCondition pathCondition = rule.getPathCondition();
560 if (pathCondition != null) {
561 if (pathCondition.isRegex()) {
562 ruleElement.setAttribute(PATH_REGEX_ATTR, pathCondition.getTextToMatch());
564 ruleElement.setAttribute(PATH_FILTER_ATTR, pathCondition.getTextToMatch());
568 MimeTypeCondition mimeCondition = rule.getMimeTypeCondition();
569 if (mimeCondition != null) {
570 ruleElement.setAttribute(MIME_ATTR, mimeCondition.getMimeType());
573 FileSizeCondition sizeCondition = rule.getFileSizeCondition();
574 if (sizeCondition != null) {
575 ruleElement.setAttribute(FS_COMPARATOR_ATTR, sizeCondition.getComparator().getSymbol());
576 ruleElement.setAttribute(FS_SIZE_ATTR, Integer.toString(sizeCondition.getSizeValue()));
577 ruleElement.setAttribute(FS_UNITS_ATTR, sizeCondition.getUnit().getName());
581 DateCondition dateCondition = rule.getDateCondition();
582 if (dateCondition != null) {
583 ruleElement.setAttribute(DAYS_INCLUDED_ATTR, Integer.toString(dateCondition.getDaysIncluded()));
586 setElement.appendChild(ruleElement);
588 rootElement.appendChild(setElement);
592 return XMLUtil.saveDoc(InterestingItemsFilesSetSettings.class, xmlFile.getPath(), XML_ENCODING, doc);
593 }
catch (ParserConfigurationException ex) {
594 logger.log(Level.SEVERE,
"Error writing interesting files definition file to " + xmlFile.getPath(), ex);
610 private static MetaTypeCondition readMetaTypeCondition(Element ruleElement)
throws FilesSetsManager.FilesSetsManagerException {
611 MetaTypeCondition metaCondition = null;
614 if (!ruleElement.getAttribute(TYPE_FILTER_ATTR).isEmpty()) {
615 String conditionAttribute = ruleElement.getAttribute(TYPE_FILTER_ATTR);
616 if (!conditionAttribute.isEmpty()) {
617 switch (conditionAttribute) {
618 case TYPE_FILTER_VALUE_FILES:
619 metaCondition =
new MetaTypeCondition(MetaTypeCondition.Type.FILES);
621 case TYPE_FILTER_VALUE_DIRS:
622 metaCondition =
new MetaTypeCondition(MetaTypeCondition.Type.DIRECTORIES);
624 case TYPE_FILTER_VALUE_ALL:
625 case TYPE_FILTER_VALUE_FILES_AND_DIRS:
626 metaCondition =
new MetaTypeCondition(MetaTypeCondition.Type.ALL);
629 logger.log(Level.SEVERE,
"Found {0} " + TYPE_FILTER_ATTR +
" attribute with unrecognized value ''{0}'', ignoring malformed rule definition", conditionAttribute);
631 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Malformed XML for Metatype condition, %s, in rule %s", conditionAttribute, readRuleName(ruleElement)));
635 if (metaCondition == null) {
638 metaCondition =
new MetaTypeCondition(MetaTypeCondition.Type.FILES);
640 return metaCondition;