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;
 
   47 import org.w3c.dom.Document;
 
   48 import org.w3c.dom.Element;
 
   49 import org.w3c.dom.NodeList;
 
   51 class InterestingItemsFilesSetSettings 
implements Serializable {
 
   53     private static final long serialVersionUID = 1L;
 
   56     private static final String FILE_SETS_ROOT_TAG = 
"INTERESTING_FILE_SETS"; 
 
   57     private static final String DESC_ATTR = 
"description"; 
 
   58     private static final String IGNORE_KNOWN_FILES_ATTR = 
"ignoreKnown"; 
 
   59     private static final String PATH_REGEX_ATTR = 
"pathRegex"; 
 
   60     private static final String TYPE_FILTER_VALUE_ALL = 
"all";
 
   61     private static final String TYPE_FILTER_VALUE_FILES_AND_DIRS = 
"files_and_dirs"; 
 
   62     private static final String IGNORE_UNALLOCATED_SPACE = 
"ingoreUnallocated"; 
 
   63     private static final String PATH_FILTER_ATTR = 
"pathFilter"; 
 
   64     private static final String TYPE_FILTER_VALUE_DIRS = 
"dir"; 
 
   65     private static final String REGEX_ATTR = 
"regex"; 
 
   66     private static final List<String> illegalFileNameChars = FilesSetsManager.getIllegalFileNameChars();
 
   67     private static final String FILE_SET_TAG = 
"INTERESTING_FILE_SET"; 
 
   68     private static final String NAME_RULE_TAG = 
"NAME"; 
 
   69     private static final String NAME_ATTR = 
"name"; 
 
   70     private static final String MIME_ATTR = 
"mimeType";
 
   71     private static final String FS_COMPARATOR_ATTR = 
"comparatorSymbol";
 
   72     private static final String FS_SIZE_ATTR = 
"sizeValue";
 
   73     private static final String FS_UNITS_ATTR = 
"sizeUnits";
 
   74     private static final String TYPE_FILTER_VALUE_FILES = 
"file"; 
 
   75     private static final String XML_ENCODING = 
"UTF-8"; 
 
   76     private static final Logger logger = Logger.getLogger(InterestingItemsFilesSetSettings.class.getName());
 
   77     private static final String TYPE_FILTER_ATTR = 
"typeFilter"; 
 
   78     private static final String EXTENSION_RULE_TAG = 
"EXTENSION"; 
 
   80     private Map<String, FilesSet> filesSets;
 
   82     InterestingItemsFilesSetSettings(Map<String, FilesSet> filesSets) {
 
   83         this.filesSets = filesSets;
 
   89     Map<String, FilesSet> getFilesSets() {
 
  100     private static String readRuleName(Element elem) {
 
  102         String ruleName = elem.getAttribute(NAME_ATTR);
 
  114     private static Map<String, FilesSet> readSerializedDefinitions(String serialFileName) 
throws FilesSetsManager.FilesSetsManagerException {
 
  115         Path filePath = Paths.get(PlatformUtil.getUserConfigDirectory(), serialFileName);
 
  116         File fileSetFile = filePath.toFile();
 
  117         String filePathStr = filePath.toString();
 
  118         if (fileSetFile.exists()) {
 
  120                 try (
final NbObjectInputStream in = 
new NbObjectInputStream(
new FileInputStream(filePathStr))) {
 
  121                     InterestingItemsFilesSetSettings filesSetsSettings = (InterestingItemsFilesSetSettings) in.readObject();
 
  122                     return filesSetsSettings.getFilesSets();
 
  124             } 
catch (IOException | ClassNotFoundException ex) {
 
  125                 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Failed to read settings from %s", filePathStr), ex);
 
  128             return new HashMap<>();
 
  143     private static ParentPathCondition readPathCondition(Element ruleElement) 
throws FilesSetsManager.FilesSetsManagerException {
 
  146         ParentPathCondition pathCondition = null;
 
  147         if (!ruleElement.getAttribute(PATH_FILTER_ATTR).isEmpty() || !ruleElement.getAttribute(PATH_REGEX_ATTR).isEmpty()) {
 
  148             String path = ruleElement.getAttribute(PATH_FILTER_ATTR);
 
  149             String pathRegex = ruleElement.getAttribute(PATH_REGEX_ATTR);
 
  150             if (!pathRegex.isEmpty() && path.isEmpty()) {
 
  152                     Pattern pattern = Pattern.compile(pathRegex);
 
  153                     pathCondition = 
new ParentPathCondition(pattern);
 
  154                 } 
catch (PatternSyntaxException ex) {
 
  155                     logger.log(Level.SEVERE, 
"Error compiling " + PATH_REGEX_ATTR + 
" regex, ignoring malformed path condition definition", ex); 
 
  156                     throw new FilesSetsManager.FilesSetsManagerException(String.format(
"error compiling %s regex", PATH_REGEX_ATTR), ex);
 
  158             } 
else if (!path.isEmpty() && pathRegex.isEmpty()) {
 
  159                 pathCondition = 
new ParentPathCondition(path);
 
  161             if (pathCondition == null) {
 
  163                 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Error creating path condition for rule %s", readRuleName(ruleElement)));
 
  166         return pathCondition;
 
  176     private static Pattern compileRegex(String regex) {
 
  178             return Pattern.compile(regex);
 
  179         } 
catch (PatternSyntaxException ex) {
 
  180             logger.log(Level.SEVERE, 
"Error compiling rule regex: " + ex.getMessage(), ex); 
 
  196     private static FilesSet.Rule readRule(Element elem) 
throws FilesSetsManager.FilesSetsManagerException {
 
  197         String ruleName = readRuleName(elem);
 
  198         FileNameCondition nameCondition = readNameCondition(elem);
 
  199         MetaTypeCondition metaCondition = readMetaTypeCondition(elem);
 
  200         ParentPathCondition pathCondition = readPathCondition(elem);
 
  201         MimeTypeCondition mimeCondition = readMimeCondition(elem);
 
  202         FileSizeCondition sizeCondition = readSizeCondition(elem);
 
  204         if (metaCondition == null || (nameCondition == null && pathCondition == null && mimeCondition == null && sizeCondition == null)) {
 
  205             logger.log(Level.WARNING, 
"Error Reading Rule, " + ruleName + 
" was either missing a meta condition or contained only a meta condition. No rule was imported."); 
 
  206             throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Invalid Rule in FilesSet xml, missing necessary conditions for %s", ruleName));
 
  208         return new FilesSet.Rule(ruleName, nameCondition, metaCondition, pathCondition, mimeCondition, sizeCondition);
 
  222     private static FileNameCondition readNameCondition(Element elem) 
throws FilesSetsManager.FilesSetsManagerException {
 
  223         FileNameCondition nameCondition = null;
 
  224         String content = elem.getTextContent();
 
  225         String regex = elem.getAttribute(REGEX_ATTR);
 
  226         if (content != null && !content.isEmpty()) {  
 
  227             if ((!regex.isEmpty() && regex.equalsIgnoreCase(
"true")) || content.contains(
"*")) { 
 
  228                 Pattern pattern = compileRegex(content);
 
  229                 if (pattern != null) {
 
  230                     if (elem.getTagName().equals(NAME_RULE_TAG)) {
 
  231                         nameCondition = 
new FilesSet.Rule.FullNameCondition(pattern);
 
  232                     } 
else if (elem.getTagName().equals(EXTENSION_RULE_TAG)) {
 
  233                         nameCondition = 
new FilesSet.Rule.ExtensionCondition(pattern);
 
  235                         throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Name condition has invalid tag name of %s for rule %s", elem.getTagName(), readRuleName(elem)));
 
  238                     logger.log(Level.SEVERE, 
"Error compiling " + elem.getTagName() + 
" regex, ignoring malformed '{0}' rule definition", readRuleName(elem)); 
 
  239                     throw new FilesSetsManager.FilesSetsManagerException(String.format(
"error compiling %s regex in rule %s", REGEX_ATTR, readRuleName(elem)));
 
  242                 for (String illegalChar : illegalFileNameChars) {
 
  243                     if (content.contains(illegalChar)) {
 
  244                         logger.log(Level.SEVERE, elem.getTagName() + 
" content has illegal chars, ignoring malformed '{0}' rule definition", 
new Object[]{elem.getTagName(), readRuleName(elem)}); 
 
  245                         throw new FilesSetsManager.FilesSetsManagerException(String.format(
"File name has illegal character of %s in rule %s", illegalChar, readRuleName(elem)));
 
  248                 if (elem.getTagName().equals(NAME_RULE_TAG)) {
 
  249                     nameCondition = 
new FilesSet.Rule.FullNameCondition(content);
 
  250                 } 
else if (elem.getTagName().equals(EXTENSION_RULE_TAG)) {
 
  251                     nameCondition = 
new FilesSet.Rule.ExtensionCondition(content);
 
  255         return nameCondition;
 
  266     private static MimeTypeCondition readMimeCondition(Element elem) {
 
  267         MimeTypeCondition mimeCondition = null;
 
  268         if (!elem.getAttribute(MIME_ATTR).isEmpty()) {
 
  269             mimeCondition = 
new MimeTypeCondition(elem.getAttribute(MIME_ATTR));
 
  274         return mimeCondition;
 
  288     private static FileSizeCondition readSizeCondition(Element elem) 
throws FilesSetsManager.FilesSetsManagerException {
 
  289         FileSizeCondition sizeCondition = null;
 
  290         if (!elem.getAttribute(FS_COMPARATOR_ATTR).isEmpty() && !elem.getAttribute(FS_SIZE_ATTR).isEmpty() && !elem.getAttribute(FS_UNITS_ATTR).isEmpty()) {
 
  292                 FileSizeCondition.COMPARATOR comparator = FileSizeCondition.COMPARATOR.fromSymbol(elem.getAttribute(FS_COMPARATOR_ATTR));
 
  293                 FileSizeCondition.SIZE_UNIT sizeUnit = FileSizeCondition.SIZE_UNIT.fromName(elem.getAttribute(FS_UNITS_ATTR));
 
  294                 int size = Integer.parseInt(elem.getAttribute(FS_SIZE_ATTR));
 
  295                 sizeCondition = 
new FileSizeCondition(comparator, sizeUnit, size);
 
  296             } 
catch (NumberFormatException nfEx) {
 
  297                 logger.log(Level.SEVERE, 
"Value in file size attribute was not an integer, unable to create FileSizeCondition for rule: " + readRuleName(elem), nfEx);
 
  298                 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Non integer size in FilesSet XML for rule %s", readRuleName(elem)), nfEx);
 
  299             } 
catch (IllegalArgumentException iaEx) {
 
  300                 logger.log(Level.SEVERE, 
"Invalid Comparator symbol or Size Unit set in FilesSet xml, unable to create FileSizeCondition for rule: " + readRuleName(elem), iaEx);
 
  301                 throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Invalid Comparator or Size unit in FilesSet XML for rule %s", readRuleName(elem)), iaEx);
 
  304         else if (!elem.getAttribute(FS_COMPARATOR_ATTR).isEmpty() || !elem.getAttribute(FS_SIZE_ATTR).isEmpty() || !elem.getAttribute(FS_UNITS_ATTR).isEmpty()) {
 
  305             logger.log(Level.SEVERE, 
"Invalid Comparator symbol or Size Unit set in FilesSet xml, unable to create FileSizeCondition for rule: " + readRuleName(elem));
 
  306             throw new FilesSetsManager.FilesSetsManagerException(String.format(
"XML malformed missing at least one fileSize attribute for rule %s", readRuleName(elem)));
 
  308         return sizeCondition;
 
  321     private static void readFilesSet(Element setElem, Map<String, FilesSet> filesSets, String filePath) 
throws FilesSetsManager.FilesSetsManagerException {
 
  323         String setName = setElem.getAttribute(NAME_ATTR);
 
  324         if (setName.isEmpty()) {
 
  325             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}); 
 
  328         if (filesSets.containsKey(setName)) {
 
  329             logger.log(Level.SEVERE, 
"Found duplicate definition of set named {0} in FilesSet definition file at {1}, discarding duplicate set", 
new Object[]{setName, filePath}); 
 
  333         String description = setElem.getAttribute(DESC_ATTR);
 
  336         String ignoreKnown = setElem.getAttribute(IGNORE_KNOWN_FILES_ATTR);
 
  337         boolean ignoreKnownFiles = 
false;
 
  338         if (!ignoreKnown.isEmpty()) {
 
  339             ignoreKnownFiles = Boolean.parseBoolean(ignoreKnown);
 
  343         String ignoreUnallocated = setElem.getAttribute(IGNORE_UNALLOCATED_SPACE);
 
  344         boolean ignoreUnallocatedSpace = 
false;
 
  345         if (!ignoreUnallocated.isEmpty()) {
 
  346             ignoreUnallocatedSpace = Boolean.parseBoolean(ignoreUnallocated);
 
  349         Map<String, FilesSet.Rule> rules = 
new HashMap<>();
 
  350         NodeList allRuleElems = setElem.getChildNodes();
 
  351         for (
int j = 0; j < allRuleElems.getLength(); ++j) {
 
  352             if (allRuleElems.item(j) instanceof Element) {  
 
  353                 Element elem = (Element) allRuleElems.item(j);
 
  354                 FilesSet.Rule rule = readRule(elem);
 
  356                     if (!rules.containsKey(rule.getUuid())) {
 
  357                         rules.put(rule.getUuid(), rule);
 
  359                         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}); 
 
  363                     logger.log(Level.SEVERE, 
"Found malformed rule for set named {0} in FilesSet definition file at {1}, discarding malformed set", 
new Object[]{setName, filePath}); 
 
  371         FilesSet set = 
new FilesSet(setName, description, ignoreKnownFiles, ignoreUnallocatedSpace, rules);
 
  372         filesSets.put(set.getName(), set);
 
  390     static Map<String, FilesSet> readDefinitionsFile(String fileName, String legacyFileName) 
throws FilesSetsManager.FilesSetsManagerException {
 
  391         Map<String, FilesSet> filesSets = readSerializedDefinitions(fileName);
 
  392         if (!filesSets.isEmpty()) {
 
  396         if (!legacyFileName.isEmpty()) {
 
  397             return readDefinitionsXML(Paths.get(PlatformUtil.getUserConfigDirectory(), legacyFileName).toFile());
 
  415     static Map<String, FilesSet> readDefinitionsXML(File xmlFile) 
throws FilesSetsManager.FilesSetsManagerException {
 
  416         Map<String, FilesSet> filesSets = 
new HashMap<>();
 
  417         if (!xmlFile.exists()) {
 
  421         if (!xmlFile.canRead()) {
 
  422             logger.log(Level.SEVERE, 
"FilesSet definition file at {0} exists, but cannot be read", xmlFile.getPath()); 
 
  426         Document doc = XMLUtil.loadDoc(InterestingItemsFilesSetSettings.class, xmlFile.getPath());
 
  428             logger.log(Level.SEVERE, 
"FilesSet definition file at {0}", xmlFile.getPath()); 
 
  432         Element root = doc.getDocumentElement();
 
  434             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()}); 
 
  438         NodeList setElems = root.getElementsByTagName(FILE_SET_TAG);
 
  439         for (
int i = 0; i < setElems.getLength(); ++i) {
 
  440             readFilesSet((Element) setElems.item(i), filesSets, xmlFile.getPath());
 
  455     static boolean writeDefinitionsFile(String fileName, Map<String, FilesSet> interestingFilesSets) 
throws FilesSetsManager.FilesSetsManagerException {
 
  456         try (
final NbObjectOutputStream out = 
new NbObjectOutputStream(
new FileOutputStream(Paths.get(PlatformUtil.getUserConfigDirectory(), fileName).toString()))) {
 
  457             out.writeObject(
new InterestingItemsFilesSetSettings(interestingFilesSets));
 
  458         } 
catch (IOException ex) {
 
  459             throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Failed to write settings to %s", fileName), ex);
 
  473     static boolean exportXmlDefinitionsFile(File xmlFile, List<FilesSet> interestingFilesSets) {
 
  474         DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
 
  477             DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
 
  478             Document doc = docBuilder.newDocument();
 
  479             Element rootElement = doc.createElement(FILE_SETS_ROOT_TAG);
 
  480             doc.appendChild(rootElement);
 
  482             for (FilesSet set : interestingFilesSets) {
 
  484                 Element setElement = doc.createElement(FILE_SET_TAG);
 
  485                 setElement.setAttribute(NAME_ATTR, set.getName());
 
  486                 setElement.setAttribute(DESC_ATTR, set.getDescription());
 
  487                 setElement.setAttribute(IGNORE_KNOWN_FILES_ATTR, Boolean.toString(set.ignoresKnownFiles()));
 
  490                 for (FilesSet.Rule rule : set.getRules().values()) {
 
  495                     FileNameCondition nameCondition = rule.getFileNameCondition();
 
  500                     if (nameCondition instanceof FilesSet.Rule.FullNameCondition) {
 
  501                         ruleElement = doc.createElement(NAME_RULE_TAG);
 
  503                         ruleElement = doc.createElement(EXTENSION_RULE_TAG);
 
  506                     ruleElement.setAttribute(NAME_ATTR, rule.getName());
 
  507                     if (nameCondition != null) {
 
  509                         ruleElement.setAttribute(REGEX_ATTR, Boolean.toString(nameCondition.isRegex()));
 
  511                         ruleElement.setTextContent(nameCondition.getTextToMatch());
 
  514                     MetaTypeCondition typeCondition = rule.getMetaTypeCondition();
 
  515                     switch (typeCondition.getMetaType()) {
 
  517                             ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_FILES);
 
  520                             ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_DIRS);
 
  523                             ruleElement.setAttribute(TYPE_FILTER_ATTR, TYPE_FILTER_VALUE_ALL);
 
  527                     ParentPathCondition pathCondition = rule.getPathCondition();
 
  528                     if (pathCondition != null) {
 
  529                         if (pathCondition.isRegex()) {
 
  530                             ruleElement.setAttribute(PATH_REGEX_ATTR, pathCondition.getTextToMatch());
 
  532                             ruleElement.setAttribute(PATH_FILTER_ATTR, pathCondition.getTextToMatch());
 
  536                     MimeTypeCondition mimeCondition = rule.getMimeTypeCondition();
 
  537                     if (mimeCondition != null) {
 
  538                         ruleElement.setAttribute(MIME_ATTR, mimeCondition.getMimeType());
 
  541                     FileSizeCondition sizeCondition = rule.getFileSizeCondition();
 
  542                     if (sizeCondition != null) {
 
  543                         ruleElement.setAttribute(FS_COMPARATOR_ATTR, sizeCondition.getComparator().getSymbol());
 
  544                         ruleElement.setAttribute(FS_SIZE_ATTR, Integer.toString(sizeCondition.getSizeValue()));
 
  545                         ruleElement.setAttribute(FS_UNITS_ATTR, sizeCondition.getUnit().getName());
 
  547                     setElement.appendChild(ruleElement);
 
  549                 rootElement.appendChild(setElement);
 
  553             return XMLUtil.saveDoc(InterestingItemsFilesSetSettings.class, xmlFile.getPath(), XML_ENCODING, doc);
 
  554         } 
catch (ParserConfigurationException ex) {
 
  555             logger.log(Level.SEVERE, 
"Error writing interesting files definition file to " + xmlFile.getPath(), ex); 
 
  571     private static MetaTypeCondition readMetaTypeCondition(Element ruleElement) 
throws FilesSetsManager.FilesSetsManagerException {
 
  572         MetaTypeCondition metaCondition = null;
 
  575         if (!ruleElement.getAttribute(TYPE_FILTER_ATTR).isEmpty()) {
 
  576             String conditionAttribute = ruleElement.getAttribute(TYPE_FILTER_ATTR);
 
  577             if (!conditionAttribute.isEmpty()) {
 
  578                 switch (conditionAttribute) {
 
  579                     case TYPE_FILTER_VALUE_FILES:
 
  580                         metaCondition = 
new MetaTypeCondition(MetaTypeCondition.Type.FILES);
 
  582                     case TYPE_FILTER_VALUE_DIRS:
 
  583                         metaCondition = 
new MetaTypeCondition(MetaTypeCondition.Type.DIRECTORIES);
 
  585                     case TYPE_FILTER_VALUE_ALL:
 
  586                     case TYPE_FILTER_VALUE_FILES_AND_DIRS:  
 
  587                         metaCondition = 
new MetaTypeCondition(MetaTypeCondition.Type.ALL);
 
  590                         logger.log(Level.SEVERE, 
"Found {0} " + TYPE_FILTER_ATTR + 
" attribute with unrecognized value ''{0}'', ignoring malformed rule definition", conditionAttribute); 
 
  592                         throw new FilesSetsManager.FilesSetsManagerException(String.format(
"Malformed XML for Metatype condition, %s, in rule %s", conditionAttribute, readRuleName(ruleElement)));
 
  596         if (metaCondition == null) {
 
  599             metaCondition = 
new MetaTypeCondition(MetaTypeCondition.Type.FILES);
 
  601         return metaCondition;