Autopsy  4.19.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
OtherOccurrences.java
Go to the documentation of this file.
1 /*
2  * Central Repository
3  *
4  * Copyright 2021 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.centralrepository.application;
20 
21 import java.io.BufferedWriter;
22 import java.io.File;
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.text.DateFormat;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34 import java.util.Optional;
35 import java.util.logging.Level;
36 import org.apache.commons.lang3.StringUtils;
37 import org.joda.time.DateTimeZone;
38 import org.joda.time.LocalDateTime;
39 import org.openide.nodes.Node;
40 import org.openide.util.NbBundle;
51 import org.sleuthkit.datamodel.AbstractFile;
52 import org.sleuthkit.datamodel.BlackboardArtifact;
53 import org.sleuthkit.datamodel.BlackboardArtifactTag;
54 import org.sleuthkit.datamodel.Content;
55 import org.sleuthkit.datamodel.ContentTag;
56 import org.sleuthkit.datamodel.DataSource;
57 import org.sleuthkit.datamodel.OsAccount;
58 import org.sleuthkit.datamodel.OsAccountInstance;
59 import org.sleuthkit.datamodel.SleuthkitCase;
60 import org.sleuthkit.datamodel.TskCoreException;
61 import org.sleuthkit.datamodel.TskData;
62 
67 public final class OtherOccurrences {
68 
69  private static final Logger logger = Logger.getLogger(OtherOccurrences.class.getName());
70 
71  private static final String UUID_PLACEHOLDER_STRING = "NoCorrelationAttributeInstance";
72 
73  private OtherOccurrences() {
74  }
75 
84  public static Collection<CorrelationAttributeInstance> getCorrelationAttributeFromOsAccount(Node node, OsAccount osAccount) {
85  Collection<CorrelationAttributeInstance> ret = new ArrayList<>();
86  Optional<String> osAccountAddr = osAccount.getAddr();
87 
88  if (osAccountAddr.isPresent()) {
89  try {
90  for (OsAccountInstance instance : osAccount.getOsAccountInstances()) {
91  DataSource osAccountDataSource = instance.getDataSource();
92  try {
94  CorrelationAttributeInstance correlationAttributeInstance = new CorrelationAttributeInstance(
96  osAccountAddr.get(),
97  correlationCase,
98  CorrelationDataSource.fromTSKDataSource(correlationCase, instance.getDataSource()),
99  "",
100  "",
101  TskData.FileKnown.KNOWN,
102  osAccount.getId());
103 
104  ret.add(correlationAttributeInstance);
105  } catch (CentralRepoException ex) {
106  logger.log(Level.SEVERE, String.format("Cannot get central repository for OsAccount: %s.", osAccountAddr.get()), ex); //NON-NLS
107  } catch (NoCurrentCaseException ex) {
108  logger.log(Level.WARNING, String.format("Exception while getting open case looking up osAccount %s.", osAccountAddr.get()), ex); //NON-NLS
110  logger.log(Level.SEVERE, String.format("Exception with Correlation Attribute Normalization for osAccount %s.", osAccountAddr.get()), ex); //NON-NLS
111  }
112  }
113  } catch (TskCoreException ex) {
114  logger.log(Level.INFO, String.format("Unable to check create CorrelationAttribtueInstance for osAccount %s.", osAccountAddr.get()), ex);
115  }
116  }
117 
118  return ret;
119  }
120 
130  public static Collection<CorrelationAttributeInstance> getCorrelationAttributesFromNode(Node node, AbstractFile file) {
131  Collection<CorrelationAttributeInstance> ret = new ArrayList<>();
132 
133  // correlate on blackboard artifact attributes if they exist and supported
134  BlackboardArtifact bbArtifact = getBlackboardArtifactFromNode(node);
135  if (bbArtifact != null && CentralRepository.isEnabled()) {
137  }
138 
139  // we can correlate based on the MD5 if it is enabled
140  if (file != null && CentralRepository.isEnabled() && file.getSize() > 0) {
141  try {
142 
144  String md5 = file.getMd5Hash();
145  if (md5 != null && !md5.isEmpty() && null != artifactTypes && !artifactTypes.isEmpty()) {
146  for (CorrelationAttributeInstance.Type aType : artifactTypes) {
147  if (aType.getId() == CorrelationAttributeInstance.FILES_TYPE_ID) {
149  try {
150  ret.add(new CorrelationAttributeInstance(
151  aType,
152  md5,
153  corCase,
154  CorrelationDataSource.fromTSKDataSource(corCase, file.getDataSource()),
155  file.getParentPath() + file.getName(),
156  "",
157  file.getKnown(),
158  file.getId()));
160  logger.log(Level.INFO, String.format("Unable to check create CorrelationAttribtueInstance for value %s and type %s.", md5, aType.toString()), ex);
161  }
162  break;
163  }
164  }
165  }
166  } catch (CentralRepoException | TskCoreException ex) {
167  logger.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
168  }
169  // If EamDb not enabled, get the Files default correlation type to allow Other Occurances to be enabled.
170  } else if (file != null && file.getSize() > 0) {
171  String md5 = file.getMd5Hash();
172  if (md5 != null && !md5.isEmpty()) {
173  try {
174  final CorrelationAttributeInstance.Type fileAttributeType
176  .stream()
177  .filter(attrType -> attrType.getId() == CorrelationAttributeInstance.FILES_TYPE_ID)
178  .findAny()
179  .get();
180  //The Central Repository is not enabled
181  ret.add(new CorrelationAttributeInstance(fileAttributeType, md5, null, null, "", "", TskData.FileKnown.UNKNOWN, file.getId()));
182  } catch (CentralRepoException ex) {
183  logger.log(Level.SEVERE, "Error connecting to DB", ex); // NON-NLS
185  logger.log(Level.INFO, String.format("Unable to create CorrelationAttributeInstance for value %s", md5), ex); // NON-NLS
186  }
187  }
188  }
189  return ret;
190  }
191 
199  public static BlackboardArtifact getBlackboardArtifactFromNode(Node node) {
200  BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
201  BlackboardArtifact nodeBbArtifact = node.getLookup().lookup(BlackboardArtifact.class);
202 
203  if (nodeBbArtifactTag != null) {
204  return nodeBbArtifactTag.getArtifact();
205  } else if (nodeBbArtifact != null) {
206  return nodeBbArtifact;
207  }
208 
209  return null;
210 
211  }
212 
220  public static AbstractFile getAbstractFileFromNode(Node node) {
221  BlackboardArtifactTag nodeBbArtifactTag = node.getLookup().lookup(BlackboardArtifactTag.class);
222  ContentTag nodeContentTag = node.getLookup().lookup(ContentTag.class);
223  AbstractFile nodeAbstractFile = node.getLookup().lookup(AbstractFile.class);
224 
225  if (nodeBbArtifactTag != null) {
226  Content content = nodeBbArtifactTag.getContent();
227  if (content instanceof AbstractFile) {
228  return (AbstractFile) content;
229  }
230  } else if (nodeContentTag != null) {
231  Content content = nodeContentTag.getContent();
232  if (content instanceof AbstractFile) {
233  return (AbstractFile) content;
234  }
235  } else if (nodeAbstractFile != null) {
236  return nodeAbstractFile;
237  }
238 
239  return null;
240  }
241 
255  public static Map<UniquePathKey, NodeData> getCorrelatedInstances(AbstractFile file, String deviceId, String dataSourceName, CorrelationAttributeInstance corAttr) {
256  // @@@ Check exception
257  try {
258  final Case openCase = Case.getCurrentCaseThrows();
259  String caseUUID = openCase.getName();
260  HashMap<UniquePathKey, NodeData> nodeDataMap = new HashMap<>();
261 
263  List<CorrelationAttributeInstance> instances = CentralRepository.getInstance().getArtifactInstancesByTypeValue(corAttr.getCorrelationType(), corAttr.getCorrelationValue());
264 
265  for (CorrelationAttributeInstance artifactInstance : instances) {
266 
267  // Only add the attribute if it isn't the object the user selected.
268  // We consider it to be a different object if at least one of the following is true:
269  // - the case UUID is different
270  // - the data source name is different
271  // - the data source device ID is different
272  // - the file path is different
273  if (artifactInstance.getCorrelationCase().getCaseUUID().equals(caseUUID)
274  && (!StringUtils.isBlank(dataSourceName) && artifactInstance.getCorrelationDataSource().getName().equals(dataSourceName))
275  && (!StringUtils.isBlank(deviceId) && artifactInstance.getCorrelationDataSource().getDeviceID().equals(deviceId))
276  && (file != null && artifactInstance.getFilePath().equalsIgnoreCase(file.getParentPath() + file.getName()))) {
277  continue;
278  }
279  NodeData newNode = new NodeData(artifactInstance, corAttr.getCorrelationType(), corAttr.getCorrelationValue());
280  UniquePathKey uniquePathKey = new UniquePathKey(newNode);
281  nodeDataMap.put(uniquePathKey, newNode);
282  }
283  }
284  if (file != null && corAttr.getCorrelationType().getDisplayName().equals("Files")) {
285  List<AbstractFile> caseDbFiles = getCaseDbMatches(corAttr, openCase, file);
286 
287  for (AbstractFile caseDbFile : caseDbFiles) {
288  addOrUpdateNodeData(openCase, nodeDataMap, caseDbFile);
289  }
290  }
291  return nodeDataMap;
292  } catch (CentralRepoException ex) {
293  logger.log(Level.SEVERE, "Error getting artifact instances from database.", ex); // NON-NLS
295  logger.log(Level.INFO, "Error getting artifact instances from database.", ex); // NON-NLS
296  } catch (NoCurrentCaseException ex) {
297  logger.log(Level.SEVERE, "Exception while getting open case.", ex); // NON-NLS
298  } catch (TskCoreException ex) {
299  // do nothing.
300  // @@@ Review this behavior
301  logger.log(Level.SEVERE, "Exception while querying open case.", ex); // NON-NLS
302  }
303 
304  return new HashMap<>(
305  0);
306  }
307 
322  public static List<AbstractFile> getCaseDbMatches(CorrelationAttributeInstance corAttr, Case openCase, AbstractFile file) throws NoCurrentCaseException, TskCoreException, CentralRepoException {
323  List<AbstractFile> caseDbArtifactInstances = new ArrayList<>();
324  if (file != null) {
325  String md5 = corAttr.getCorrelationValue();
326  SleuthkitCase tsk = openCase.getSleuthkitCase();
327  List<AbstractFile> matches = tsk.findAllFilesWhere(String.format("md5 = '%s'", new Object[]{md5}));
328 
329  for (AbstractFile fileMatch : matches) {
330  if (file.equals(fileMatch)) {
331  continue; // If this is the file the user clicked on
332  }
333  caseDbArtifactInstances.add(fileMatch);
334  }
335  }
336  return caseDbArtifactInstances;
337 
338  }
339 
350  public static void addOrUpdateNodeData(final Case autopsyCase, Map<UniquePathKey, NodeData> nodeDataMap, AbstractFile newFile) throws TskCoreException, CentralRepoException {
351 
352  NodeData newNode = new NodeData(newFile, autopsyCase);
353 
354  // If the caseDB object has a notable tag associated with it, update
355  // the known status to BAD
356  if (newNode.getKnown() != TskData.FileKnown.BAD) {
357  List<ContentTag> fileMatchTags = autopsyCase.getServices().getTagsManager().getContentTagsByContent(newFile);
358  for (ContentTag tag : fileMatchTags) {
359  TskData.FileKnown tagKnownStatus = tag.getName().getKnownStatus();
360  if (tagKnownStatus.equals(TskData.FileKnown.BAD)) {
361  newNode.updateKnown(TskData.FileKnown.BAD);
362  break;
363  }
364  }
365  }
366 
367  // Make a key to see if the file is already in the map
368  UniquePathKey uniquePathKey = new UniquePathKey(newNode);
369 
370  // If this node is already in the list, the only thing we need to do is
371  // update the known status to BAD if the caseDB version had known status BAD.
372  // Otherwise this is a new node so add the new node to the map.
373  if (nodeDataMap.containsKey(uniquePathKey)) {
374  if (newNode.getKnown() == TskData.FileKnown.BAD) {
375  NodeData prevInstance = nodeDataMap.get(uniquePathKey);
376  prevInstance.updateKnown(newNode.getKnown());
377  }
378  } else {
379  nodeDataMap.put(uniquePathKey, newNode);
380  }
381  }
382 
387  public static String makeDataSourceString(String caseUUID, String deviceId, String dataSourceName) {
388  return caseUUID + deviceId + dataSourceName;
389  }
390 
395  public static String getEarliestCaseDate() throws CentralRepoException {
396  String dateStringDisplay = "";
397 
399  LocalDateTime earliestDate = LocalDateTime.now(DateTimeZone.UTC);
400  DateFormat datetimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US);
402  List<CorrelationCase> cases = dbManager.getCases();
403  for (CorrelationCase aCase : cases) {
404  LocalDateTime caseDate;
405  try {
406  caseDate = LocalDateTime.fromDateFields(datetimeFormat.parse(aCase.getCreationDate()));
407 
408  if (caseDate.isBefore(earliestDate)) {
409  earliestDate = caseDate;
410  dateStringDisplay = aCase.getCreationDate();
411  }
412  } catch (ParseException ex) {
413  throw new CentralRepoException("Failed to format case creation date " + aCase.getCreationDate(), ex);
414  }
415  }
416  }
417 
418  return dateStringDisplay;
419  }
420 
421  @NbBundle.Messages({
422  "OtherOccurrences.csvHeader.case=Case",
423  "OtherOccurrences.csvHeader.device=Device",
424  "OtherOccurrences.csvHeader.dataSource=Data Source",
425  "OtherOccurrences.csvHeader.attribute=Matched Attribute",
426  "OtherOccurrences.csvHeader.value=Attribute Value",
427  "OtherOccurrences.csvHeader.known=Known",
428  "OtherOccurrences.csvHeader.path=Path",
429  "OtherOccurrences.csvHeader.comment=Comment"
430  })
431 
444  public static void writeOtherOccurrencesToFileAsCSV(File destFile, AbstractFile abstractFile, Collection<CorrelationAttributeInstance> correlationAttList, String dataSourceName, String deviceId) throws IOException {
445  try (BufferedWriter writer = Files.newBufferedWriter(destFile.toPath())) {
446  //write headers
447  StringBuilder headers = new StringBuilder("\"");
448  headers.append(Bundle.OtherOccurrences_csvHeader_case())
449  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_dataSource())
450  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_attribute())
451  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_value())
452  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_known())
453  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_path())
454  .append(NodeData.getCsvItemSeparator()).append(Bundle.OtherOccurrences_csvHeader_comment())
455  .append('"').append(System.getProperty("line.separator"));
456  writer.write(headers.toString());
457  //write content
458  for (CorrelationAttributeInstance corAttr : correlationAttList) {
459  Map<UniquePathKey, NodeData> correlatedNodeDataMap = new HashMap<>(0);
460  // get correlation and reference set instances from DB
461  correlatedNodeDataMap.putAll(getCorrelatedInstances(abstractFile, deviceId, dataSourceName, corAttr));
462  for (NodeData nodeData : correlatedNodeDataMap.values()) {
463  writer.write(nodeData.toCsvString());
464  }
465  }
466  }
467  }
468 
475  public static String getPlaceholderUUID() {
477  }
478 }
static void writeOtherOccurrencesToFileAsCSV(File destFile, AbstractFile abstractFile, Collection< CorrelationAttributeInstance > correlationAttList, String dataSourceName, String deviceId)
static Map< UniquePathKey, NodeData > getCorrelatedInstances(AbstractFile file, String deviceId, String dataSourceName, CorrelationAttributeInstance corAttr)
List< CorrelationAttributeInstance > getArtifactInstancesByTypeValue(CorrelationAttributeInstance.Type aType, String value)
static CorrelationDataSource fromTSKDataSource(CorrelationCase correlationCase, Content dataSource)
static Collection< CorrelationAttributeInstance > getCorrelationAttributeFromOsAccount(Node node, OsAccount osAccount)
List< CorrelationAttributeInstance.Type > getDefinedCorrelationTypes()
static List< CorrelationAttributeInstance > makeCorrAttrsForCorrelation(BlackboardArtifact artifact)
static Collection< CorrelationAttributeInstance > getCorrelationAttributesFromNode(Node node, AbstractFile file)
static List< AbstractFile > getCaseDbMatches(CorrelationAttributeInstance corAttr, Case openCase, AbstractFile file)
synchronized static Logger getLogger(String name)
Definition: Logger.java:124
static void addOrUpdateNodeData(final Case autopsyCase, Map< UniquePathKey, NodeData > nodeDataMap, AbstractFile newFile)
CorrelationAttributeInstance.Type getCorrelationTypeById(int typeId)
static String makeDataSourceString(String caseUUID, String deviceId, String dataSourceName)

Copyright © 2012-2021 Basis Technology. Generated on: Fri Aug 6 2021
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.