Sleuth Kit Java Bindings (JNI)  4.11.0
Java bindings for using The Sleuth Kit
TimelineManager.java
Go to the documentation of this file.
1 /*
2  * Sleuth Kit Data Model
3  *
4  * Copyright 2018-2020 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.datamodel;
20 
21 import com.google.common.annotations.Beta;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import java.sql.PreparedStatement;
25 import java.sql.ResultSet;
26 import java.sql.SQLException;
27 import java.sql.Statement;
28 import java.sql.Types;
29 import java.time.Instant;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.Objects;
38 import java.util.Optional;
39 import java.util.Set;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import java.util.stream.Collectors;
43 import java.util.stream.Stream;
44 import org.joda.time.DateTimeZone;
45 import org.joda.time.Interval;
48 import static org.sleuthkit.datamodel.CollectionUtils.isNotEmpty;
51 import static org.sleuthkit.datamodel.StringUtils.buildCSVString;
52 
56 public final class TimelineManager {
57 
58  private static final Logger logger = Logger.getLogger(TimelineManager.class.getName());
59 
63  private static final ImmutableList<TimelineEventType> ROOT_CATEGORY_AND_FILESYSTEM_TYPES
64  = ImmutableList.of(
73 
80  private static final ImmutableList<TimelineEventType> PREDEFINED_EVENT_TYPES
81  = new ImmutableList.Builder<TimelineEventType>()
84  .build();
85 
86  // all known artifact type ids (used for determining if an artifact is standard or custom event)
87  private static final Set<Integer> ARTIFACT_TYPE_IDS = Stream.of(BlackboardArtifact.ARTIFACT_TYPE.values())
88  .map(artType -> artType.getTypeID())
89  .collect(Collectors.toSet());
90 
91  private final SleuthkitCase caseDB;
92 
97  private static final Long MAX_TIMESTAMP_TO_ADD = Instant.now().getEpochSecond() + 394200000;
98 
102  private final Map<Long, TimelineEventType> eventTypeIDMap = new HashMap<>();
103 
114  this.caseDB = caseDB;
115 
116  List<TimelineEventType> fullList = new ArrayList<>();
117  fullList.addAll(ROOT_CATEGORY_AND_FILESYSTEM_TYPES);
118  fullList.addAll(PREDEFINED_EVENT_TYPES);
119 
121  try (final CaseDbConnection con = caseDB.getConnection();
122  final PreparedStatement pStatement = con.prepareStatement(
123  insertOrIgnore(" INTO tsk_event_types(event_type_id, display_name, super_type_id) VALUES (?, ?, ?)"),
124  Statement.NO_GENERATED_KEYS)) {
125  for (TimelineEventType type : fullList) {
126  pStatement.setLong(1, type.getTypeID());
127  pStatement.setString(2, escapeSingleQuotes(type.getDisplayName()));
128  if (type != type.getParent()) {
129  pStatement.setLong(3, type.getParent().getTypeID());
130  } else {
131  pStatement.setNull(3, java.sql.Types.INTEGER);
132  }
133 
134  con.executeUpdate(pStatement);
135  eventTypeIDMap.put(type.getTypeID(), type);
136  }
137  } catch (SQLException ex) {
138  throw new TskCoreException("Failed to initialize timeline event types", ex); // NON-NLS
139  } finally {
141  }
142  }
143 
155  public Interval getSpanningInterval(Collection<Long> eventIDs) throws TskCoreException {
156  if (eventIDs.isEmpty()) {
157  return null;
158  }
159  final String query = "SELECT Min(time) as minTime, Max(time) as maxTime FROM tsk_events WHERE event_id IN (" + buildCSVString(eventIDs) + ")"; //NON-NLS
161  try (CaseDbConnection con = caseDB.getConnection();
162  Statement stmt = con.createStatement();
163  ResultSet results = stmt.executeQuery(query);) {
164  if (results.next()) {
165  return new Interval(results.getLong("minTime") * 1000, (results.getLong("maxTime") + 1) * 1000, DateTimeZone.UTC); // NON-NLS
166  }
167  } catch (SQLException ex) {
168  throw new TskCoreException("Error executing get spanning interval query: " + query, ex); // NON-NLS
169  } finally {
171  }
172  return null;
173  }
174 
187  public Interval getSpanningInterval(Interval timeRange, TimelineFilter.RootFilter filter, DateTimeZone timeZone) throws TskCoreException {
188  long start = timeRange.getStartMillis() / 1000;
189  long end = timeRange.getEndMillis() / 1000;
190  String sqlWhere = getSQLWhere(filter);
191  String augmentedEventsTablesSQL = getAugmentedEventsTablesSQL(filter);
192  String queryString = " SELECT (SELECT Max(time) FROM " + augmentedEventsTablesSQL
193  + " WHERE time <=" + start + " AND " + sqlWhere + ") AS start,"
194  + " (SELECT Min(time) FROM " + augmentedEventsTablesSQL
195  + " WHERE time >= " + end + " AND " + sqlWhere + ") AS end";//NON-NLS
197  try (CaseDbConnection con = caseDB.getConnection();
198  Statement stmt = con.createStatement(); //can't use prepared statement because of complex where clause
199  ResultSet results = stmt.executeQuery(queryString);) {
200 
201  if (results.next()) {
202  long start2 = results.getLong("start"); // NON-NLS
203  long end2 = results.getLong("end"); // NON-NLS
204 
205  if (end2 == 0) {
206  end2 = getMaxEventTime();
207  }
208  return new Interval(start2 * 1000, (end2 + 1) * 1000, timeZone);
209  }
210  } catch (SQLException ex) {
211  throw new TskCoreException("Failed to get MIN time.", ex); // NON-NLS
212  } finally {
214  }
215  return null;
216  }
217 
227  public TimelineEvent getEventById(long eventID) throws TskCoreException {
228  String sql = "SELECT * FROM " + getAugmentedEventsTablesSQL(false) + " WHERE event_id = " + eventID;
230  try (CaseDbConnection con = caseDB.getConnection();
231  Statement stmt = con.createStatement();) {
232  try (ResultSet results = stmt.executeQuery(sql);) {
233  if (results.next()) {
234  int typeID = results.getInt("event_type_id");
235  TimelineEventType type = getEventType(typeID).orElseThrow(() -> newEventTypeMappingException(typeID)); //NON-NLS
236  return new TimelineEvent(eventID,
237  results.getLong("data_source_obj_id"),
238  results.getLong("content_obj_id"),
239  results.getLong("artifact_id"),
240  results.getLong("time"),
241  type, results.getString("full_description"),
242  results.getString("med_description"),
243  results.getString("short_description"),
244  intToBoolean(results.getInt("hash_hit")),
245  intToBoolean(results.getInt("tagged")));
246  }
247  }
248  } catch (SQLException sqlEx) {
249  throw new TskCoreException("Error while executing query " + sql, sqlEx); // NON-NLS
250  } finally {
252  }
253  return null;
254  }
255 
267  public List<Long> getEventIDs(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
268  Long startTime = timeRange.getStartMillis() / 1000;
269  Long endTime = timeRange.getEndMillis() / 1000;
270 
271  if (Objects.equals(startTime, endTime)) {
272  endTime++; //make sure end is at least 1 millisecond after start
273  }
274 
275  ArrayList<Long> resultIDs = new ArrayList<>();
276 
277  String query = "SELECT tsk_events.event_id AS event_id FROM " + getAugmentedEventsTablesSQL(filter)
278  + " WHERE time >= " + startTime + " AND time <" + endTime + " AND " + getSQLWhere(filter) + " ORDER BY time ASC"; // NON-NLS
280  try (CaseDbConnection con = caseDB.getConnection();
281  Statement stmt = con.createStatement();
282  ResultSet results = stmt.executeQuery(query);) {
283  while (results.next()) {
284  resultIDs.add(results.getLong("event_id")); //NON-NLS
285  }
286 
287  } catch (SQLException sqlEx) {
288  throw new TskCoreException("Error while executing query " + query, sqlEx); // NON-NLS
289  } finally {
291  }
292 
293  return resultIDs;
294  }
295 
304  public Long getMaxEventTime() throws TskCoreException {
306  try (CaseDbConnection con = caseDB.getConnection();
307  Statement stms = con.createStatement();
308  ResultSet results = stms.executeQuery(STATEMENTS.GET_MAX_TIME.getSQL());) {
309  if (results.next()) {
310  return results.getLong("max"); // NON-NLS
311  }
312  } catch (SQLException ex) {
313  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
314  } finally {
316  }
317  return -1l;
318  }
319 
328  public Long getMinEventTime() throws TskCoreException {
330  try (CaseDbConnection con = caseDB.getConnection();
331  Statement stms = con.createStatement();
332  ResultSet results = stms.executeQuery(STATEMENTS.GET_MIN_TIME.getSQL());) {
333  if (results.next()) {
334  return results.getLong("min"); // NON-NLS
335  }
336  } catch (SQLException ex) {
337  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
338  } finally {
340  }
341  return -1l;
342  }
343 
352  public Optional<TimelineEventType> getEventType(long eventTypeID) {
353  // The parent EventType with ID 22 has been deprecated. This ID had two
354  // children which have be reassigned to MISC_TYPES.
355  if(eventTypeID == TimelineEventType.DEPRECATED_OTHER_EVENT_ID) {
356  return Optional.of(TimelineEventType.MISC_TYPES);
357  }
358 
359  return Optional.ofNullable(eventTypeIDMap.get(eventTypeID));
360  }
361 
367  public ImmutableList<TimelineEventType> getEventTypes() {
368  return ImmutableList.copyOf(eventTypeIDMap.values());
369  }
370 
371  private String insertOrIgnore(String query) {
372  switch (caseDB.getDatabaseType()) {
373  case POSTGRESQL:
374  return " INSERT " + query + " ON CONFLICT DO NOTHING "; //NON-NLS
375  case SQLITE:
376  return " INSERT OR IGNORE " + query; //NON-NLS
377  default:
378  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());
379  }
380  }
381 
385  private enum STATEMENTS {
386 
387  GET_MAX_TIME("SELECT Max(time) AS max FROM tsk_events"), // NON-NLS
388  GET_MIN_TIME("SELECT Min(time) AS min FROM tsk_events"); // NON-NLS
389 
390  private final String sql;
391 
392  private STATEMENTS(String sql) {
393  this.sql = sql;
394  }
395 
396  String getSQL() {
397  return sql;
398  }
399  }
400 
411  public List<Long> getEventIDsForArtifact(BlackboardArtifact artifact) throws TskCoreException {
412  ArrayList<Long> eventIDs = new ArrayList<>();
413 
414  String query
415  = "SELECT event_id FROM tsk_events "
416  + " LEFT JOIN tsk_event_descriptions on ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id ) "
417  + " WHERE artifact_id = " + artifact.getArtifactID();
419  try (CaseDbConnection con = caseDB.getConnection();
420  Statement stmt = con.createStatement();
421  ResultSet results = stmt.executeQuery(query);) {
422  while (results.next()) {
423  eventIDs.add(results.getLong("event_id"));//NON-NLS
424  }
425  } catch (SQLException ex) {
426  throw new TskCoreException("Error executing getEventIDsForArtifact query.", ex); // NON-NLS
427  } finally {
429  }
430  return eventIDs;
431  }
432 
446  public Set<Long> getEventIDsForContent(Content content, boolean includeDerivedArtifacts) throws TskCoreException {
448  try (CaseDbConnection conn = caseDB.getConnection()) {
449  return getEventAndDescriptionIDs(conn, content.getId(), includeDerivedArtifacts).keySet();
450  } finally {
452  }
453  }
454 
473  private Long addEventDescription(long dataSourceObjId, long fileObjId, Long artifactID,
474  String fullDescription, String medDescription, String shortDescription,
475  boolean hasHashHits, boolean tagged, CaseDbConnection connection) throws TskCoreException, DuplicateException {
476  String tableValuesClause
477  = "tsk_event_descriptions ( "
478  + "data_source_obj_id, content_obj_id, artifact_id, "
479  + " full_description, med_description, short_description, "
480  + " hash_hit, tagged "
481  + " ) VALUES "
482  + "(?, ?, ?, ?, ?, ?, ?, ?)";
483 
484  String insertDescriptionSql = getSqlIgnoreConflict(tableValuesClause);
485 
487  try {
488  PreparedStatement insertDescriptionStmt = connection.getPreparedStatement(insertDescriptionSql, PreparedStatement.RETURN_GENERATED_KEYS);
489  insertDescriptionStmt.clearParameters();
490  insertDescriptionStmt.setLong(1, dataSourceObjId);
491  insertDescriptionStmt.setLong(2, fileObjId);
492 
493  if (artifactID == null) {
494  insertDescriptionStmt.setNull(3, Types.INTEGER);
495  } else {
496  insertDescriptionStmt.setLong(3, artifactID);
497  }
498 
499  insertDescriptionStmt.setString(4, fullDescription);
500  insertDescriptionStmt.setString(5, medDescription);
501  insertDescriptionStmt.setString(6, shortDescription);
502  insertDescriptionStmt.setInt(7, booleanToInt(hasHashHits));
503  insertDescriptionStmt.setInt(8, booleanToInt(tagged));
504  int row = insertDescriptionStmt.executeUpdate();
505  // if no inserted rows, there is a conflict due to a duplicate event
506  // description. If that happens, return null as no id was inserted.
507  if (row < 1) {
508  return null;
509  }
510 
511  try (ResultSet generatedKeys = insertDescriptionStmt.getGeneratedKeys()) {
512  if (generatedKeys.next()) {
513  return generatedKeys.getLong(1);
514  } else {
515  return null;
516  }
517  }
518  } catch (SQLException ex) {
519  throw new TskCoreException("Failed to insert event description.", ex); // NON-NLS
520  } finally {
522  }
523  }
524 
538  private Long getEventDescription(long dataSourceObjId, long fileObjId, Long artifactID,
539  String fullDescription, CaseDbConnection connection) throws TskCoreException {
540 
541  String query = "SELECT event_description_id FROM tsk_event_descriptions "
542  + "WHERE data_source_obj_id = " + dataSourceObjId
543  + " AND content_obj_id = " + fileObjId
544  + " AND artifact_id " + (artifactID != null ? " = " + artifactID : "IS null")
545  + " AND full_description " + (fullDescription != null ? "= '"
546  + SleuthkitCase.escapeSingleQuotes(fullDescription) + "'" : "IS null");
547 
549  try (ResultSet resultSet = connection.createStatement().executeQuery(query)) {
550 
551  if (resultSet.next()) {
552  long id = resultSet.getLong(1);
553  return id;
554  }
555  } catch (SQLException ex) {
556  throw new TskCoreException(String.format("Failed to get description, dataSource=%d, fileObjId=%d, artifactId=%d", dataSourceObjId, fileObjId, artifactID), ex);
557  } finally {
559  }
560 
561  return null;
562  }
563 
564  Collection<TimelineEvent> addEventsForNewFile(AbstractFile file, CaseDbConnection connection) throws TskCoreException {
565  Set<TimelineEvent> events = addEventsForNewFileQuiet(file, connection);
566  events.stream()
567  .map(TimelineEventAddedEvent::new)
568  .forEach(caseDB::fireTSKEvent);
569 
570  return events;
571  }
572 
587  Set<TimelineEvent> addEventsForNewFileQuiet(AbstractFile file, CaseDbConnection connection) throws TskCoreException {
588  //gather time stamps into map
589  Map<TimelineEventType, Long> timeMap = ImmutableMap.of(TimelineEventType.FILE_CREATED, file.getCrtime(),
590  TimelineEventType.FILE_ACCESSED, file.getAtime(),
591  TimelineEventType.FILE_CHANGED, file.getCtime(),
592  TimelineEventType.FILE_MODIFIED, file.getMtime());
593 
594  /*
595  * If there are no legitimate ( greater than zero ) time stamps skip the
596  * rest of the event generation.
597  */
598  if (Collections.max(timeMap.values()) <= 0) {
599  return Collections.emptySet();
600  }
601 
602  String description = file.getParentPath() + file.getName();
603  long fileObjId = file.getId();
604  Set<TimelineEvent> events = new HashSet<>();
606  try {
607  Long descriptionID = addEventDescription(file.getDataSourceObjectId(), fileObjId, null,
608  description, null, null, false, false, connection);
609 
610  if(descriptionID == null) {
611  descriptionID = getEventDescription(file.getDataSourceObjectId(), fileObjId, null, description, connection);
612  }
613  if(descriptionID != null) {
614  for (Map.Entry<TimelineEventType, Long> timeEntry : timeMap.entrySet()) {
615  Long time = timeEntry.getValue();
616  if (time > 0 && time < MAX_TIMESTAMP_TO_ADD) {// if the time is legitimate ( greater than zero and less then 12 years from current date) insert it
617  TimelineEventType type = timeEntry.getKey();
618  long eventID = addEventWithExistingDescription(time, type, descriptionID, connection);
619 
620  /*
621  * Last two flags indicating hasTags and hasHashHits are
622  * both set to false with the assumption that this is not
623  * possible for a new file. See JIRA-5407
624  */
625  events.add(new TimelineEvent(eventID, descriptionID, fileObjId, null, time, type,
626  description, null, null, false, false));
627  } else {
628  if (time >= MAX_TIMESTAMP_TO_ADD) {
629  logger.log(Level.WARNING, String.format("Date/Time discarded from Timeline for %s for file %s with Id %d", timeEntry.getKey().getDisplayName(), file.getParentPath() + file.getName(), file.getId()));
630  }
631  }
632  }
633  } else {
634  throw new TskCoreException(String.format("Failed to get event description for file id = %d", fileObjId));
635  }
636  } catch (DuplicateException dupEx) {
637  logger.log(Level.SEVERE, "Attempt to make file event duplicate.", dupEx);
638  } finally {
640  }
641 
642  return events;
643  }
644 
658  Set<TimelineEvent> addArtifactEvents(BlackboardArtifact artifact) throws TskCoreException {
659  Set<TimelineEvent> newEvents = new HashSet<>();
660 
661  /*
662  * If the artifact is a TSK_TL_EVENT, use the TSK_TL_EVENT_TYPE
663  * attribute to determine its event type, but give it a generic
664  * description.
665  */
666  if (artifact.getArtifactTypeID() == TSK_TL_EVENT.getTypeID()) {
667  TimelineEventType eventType;//the type of the event to add.
668  BlackboardAttribute attribute = artifact.getAttribute(new BlackboardAttribute.Type(TSK_TL_EVENT_TYPE));
669  if (attribute == null) {
670  eventType = TimelineEventType.STANDARD_ARTIFACT_CATCH_ALL;
671  } else {
672  long eventTypeID = attribute.getValueLong();
673  eventType = eventTypeIDMap.getOrDefault(eventTypeID, TimelineEventType.STANDARD_ARTIFACT_CATCH_ALL);
674  }
675 
676  try {
677  // @@@ This casting is risky if we change class hierarchy, but was expedient. Should move parsing to another class
678  addArtifactEvent(((TimelineEventArtifactTypeImpl) TimelineEventType.STANDARD_ARTIFACT_CATCH_ALL).makeEventDescription(artifact), eventType, artifact)
679  .ifPresent(newEvents::add);
680  } catch (DuplicateException ex) {
681  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make a timeline event artifact duplicate"), ex);
682  }
683  } else {
684  /*
685  * If there are any event types configured to make descriptions
686  * automatically, use those.
687  */
688  Set<TimelineEventArtifactTypeImpl> eventTypesForArtifact = eventTypeIDMap.values().stream()
689  .filter(TimelineEventArtifactTypeImpl.class::isInstance)
690  .map(TimelineEventArtifactTypeImpl.class::cast)
691  .filter(eventType -> eventType.getArtifactTypeID() == artifact.getArtifactTypeID())
692  .collect(Collectors.toSet());
693 
694  boolean duplicateExists = false;
695  for (TimelineEventArtifactTypeImpl eventType : eventTypesForArtifact) {
696  try {
697  addArtifactEvent(eventType.makeEventDescription(artifact), eventType, artifact)
698  .ifPresent(newEvents::add);
699  } catch (DuplicateException ex) {
700  duplicateExists = true;
701  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make artifact event duplicate"), ex);
702  }
703  }
704 
705  // if no other timeline events were created directly, then create new 'other' ones.
706  if (!duplicateExists && newEvents.isEmpty()) {
707  try {
708  addOtherEventDesc(artifact).ifPresent(newEvents::add);
709  } catch (DuplicateException ex) {
710  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make 'other' artifact event duplicate"), ex);
711  }
712  }
713  }
714  newEvents.stream()
715  .map(TimelineEventAddedEvent::new)
716  .forEach(caseDB::fireTSKEvent);
717  return newEvents;
718  }
719 
732  private String getDuplicateExceptionMessage(BlackboardArtifact artifact, String error) {
733  String artifactIDStr = null;
734  String sourceStr = null;
735 
736  if (artifact != null) {
737  artifactIDStr = Long.toString(artifact.getId());
738 
739  try {
740  sourceStr = artifact.getAttributes().stream()
741  .filter(attr -> attr != null && attr.getSources() != null && !attr.getSources().isEmpty())
742  .map(attr -> String.join(",", attr.getSources()))
743  .findFirst()
744  .orElse(null);
745  } catch (TskCoreException ex) {
746  logger.log(Level.WARNING, String.format("Could not fetch artifacts for artifact id: %d.", artifact.getId()), ex);
747  }
748  }
749 
750  artifactIDStr = (artifactIDStr == null) ? "<null>" : artifactIDStr;
751  sourceStr = (sourceStr == null) ? "<null>" : sourceStr;
752 
753  return String.format("%s (artifactID=%s, Source=%s).", error, artifactIDStr, sourceStr);
754  }
755 
767  private Optional<TimelineEvent> addOtherEventDesc(BlackboardArtifact artifact) throws TskCoreException, DuplicateException {
768  if (artifact == null) {
769  return Optional.empty();
770  }
771 
772  Long timeVal = artifact.getAttributes().stream()
773  .filter((attr) -> attr.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME)
774  .map(attr -> attr.getValueLong())
775  .findFirst()
776  .orElse(null);
777 
778  if (timeVal == null) {
779  return Optional.empty();
780  }
781 
782  String description = String.format("%s: %d", artifact.getDisplayName(), artifact.getId());
783 
784  TimelineEventDescriptionWithTime evtWDesc = new TimelineEventDescriptionWithTime(timeVal, description, description, description);
785 
786  TimelineEventType evtType = (ARTIFACT_TYPE_IDS.contains(artifact.getArtifactTypeID()))
787  ? TimelineEventType.STANDARD_ARTIFACT_CATCH_ALL
788  : TimelineEventType.CUSTOM_ARTIFACT_CATCH_ALL;
789 
790  return addArtifactEvent(evtWDesc, evtType, artifact);
791  }
792 
806  private Optional<TimelineEvent> addArtifactEvent(TimelineEventDescriptionWithTime eventPayload,
807  TimelineEventType eventType, BlackboardArtifact artifact) throws TskCoreException, DuplicateException {
808 
809  if (eventPayload == null) {
810  return Optional.empty();
811  }
812  long time = eventPayload.getTime();
813  // if the time is legitimate ( greater than or equal to zero or less than or equal to 12 years from present time) insert it into the db
814  if (time <= 0 || time >= MAX_TIMESTAMP_TO_ADD) {
815  if (time >= MAX_TIMESTAMP_TO_ADD) {
816  logger.log(Level.WARNING, String.format("Date/Time discarded from Timeline for %s for artifact %s with id %d", artifact.getDisplayName(), eventPayload.getDescription(TimelineLevelOfDetail.HIGH), artifact.getId()));
817  }
818  return Optional.empty();
819  }
820  String fullDescription = eventPayload.getDescription(TimelineLevelOfDetail.HIGH);
821  String medDescription = eventPayload.getDescription(TimelineLevelOfDetail.MEDIUM);
822  String shortDescription = eventPayload.getDescription(TimelineLevelOfDetail.LOW);
823  long artifactID = artifact.getArtifactID();
824  long fileObjId = artifact.getObjectID();
825  Long dataSourceObjectID = artifact.getDataSourceObjectID();
826 
827  if(dataSourceObjectID == null) {
828  logger.log(Level.SEVERE, String.format("Failed to create timeline event for artifact (%d), artifact data source was null"), artifact.getId());
829  return Optional.empty();
830  }
831 
832  AbstractFile file = caseDB.getAbstractFileById(fileObjId);
833  boolean hasHashHits = false;
834  // file will be null if source was data source or some non-file
835  if (file != null) {
836  hasHashHits = isNotEmpty(file.getHashSetNames());
837  }
838  boolean tagged = isNotEmpty(caseDB.getBlackboardArtifactTagsByArtifact(artifact));
839 
840  TimelineEvent event;
842  try (CaseDbConnection connection = caseDB.getConnection();) {
843 
844  Long descriptionID = addEventDescription(dataSourceObjectID, fileObjId, artifactID,
845  fullDescription, medDescription, shortDescription,
846  hasHashHits, tagged, connection);
847 
848  if(descriptionID == null) {
849  descriptionID = getEventDescription(dataSourceObjectID, fileObjId, artifactID,
850  fullDescription, connection);
851  }
852 
853  if(descriptionID != null) {
854  long eventID = addEventWithExistingDescription(time, eventType, descriptionID, connection);
855 
856  event = new TimelineEvent(eventID, dataSourceObjectID, fileObjId, artifactID,
857  time, eventType, fullDescription, medDescription, shortDescription,
858  hasHashHits, tagged);
859  } else {
860  throw new TskCoreException(String.format("Failed to get event description for file id = %d, artifactId %d", fileObjId, artifactID));
861  }
862 
863  } finally {
865  }
866  return Optional.of(event);
867  }
868 
869  private long addEventWithExistingDescription(Long time, TimelineEventType type, long descriptionID, CaseDbConnection connection) throws TskCoreException, DuplicateException {
870  String tableValuesClause
871  = "tsk_events ( event_type_id, event_description_id , time) VALUES (?, ?, ?)";
872 
873  String insertEventSql = getSqlIgnoreConflict(tableValuesClause);
874 
876  try {
877  PreparedStatement insertRowStmt = connection.getPreparedStatement(insertEventSql, Statement.RETURN_GENERATED_KEYS);
878  insertRowStmt.clearParameters();
879  insertRowStmt.setLong(1, type.getTypeID());
880  insertRowStmt.setLong(2, descriptionID);
881  insertRowStmt.setLong(3, time);
882  int row = insertRowStmt.executeUpdate();
883  // if no inserted rows, return null.
884  if (row < 1) {
885  throw new DuplicateException(String.format("An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
886  time == null ? "<null>" : Long.toString(time),
887  type == null ? "<null>" : type.toString(),
888  descriptionID));
889  }
890 
891  try (ResultSet generatedKeys = insertRowStmt.getGeneratedKeys();) {
892  if (generatedKeys.next()) {
893  return generatedKeys.getLong(1);
894  } else {
895  throw new DuplicateException(String.format("An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
896  time == null ? "<null>" : Long.toString(time),
897  type == null ? "<null>" : type.toString(),
898  descriptionID));
899  }
900  }
901  } catch (SQLException ex) {
902  throw new TskCoreException("Failed to insert event for existing description.", ex); // NON-NLS
903  } finally {
905  }
906  }
907 
908  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, boolean includeArtifacts) throws TskCoreException {
909  return getEventAndDescriptionIDsHelper(conn, contentObjID, (includeArtifacts ? "" : " AND artifact_id IS NULL"));
910  }
911 
912  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, Long artifactID) throws TskCoreException {
913  return getEventAndDescriptionIDsHelper(conn, contentObjID, " AND artifact_id = " + artifactID);
914  }
915 
916  private Map<Long, Long> getEventAndDescriptionIDsHelper(CaseDbConnection con, long fileObjID, String artifactClause) throws TskCoreException {
917  //map from event_id to the event_description_id for that event.
918  Map<Long, Long> eventIDToDescriptionIDs = new HashMap<>();
919  String sql = "SELECT event_id, tsk_events.event_description_id"
920  + " FROM tsk_events "
921  + " LEFT JOIN tsk_event_descriptions ON ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id )"
922  + " WHERE content_obj_id = " + fileObjID
923  + artifactClause;
924  try (Statement selectStmt = con.createStatement(); ResultSet executeQuery = selectStmt.executeQuery(sql);) {
925  while (executeQuery.next()) {
926  eventIDToDescriptionIDs.put(executeQuery.getLong("event_id"), executeQuery.getLong("event_description_id")); //NON-NLS
927  }
928  } catch (SQLException ex) {
929  throw new TskCoreException("Error getting event description ids for object id = " + fileObjID, ex);
930  }
931  return eventIDToDescriptionIDs;
932  }
933 
950  @Beta
951  public Set<Long> updateEventsForContentTagAdded(Content content) throws TskCoreException {
953  try (CaseDbConnection conn = caseDB.getConnection()) {
954  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
955  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
956  return eventIDs.keySet();
957  } finally {
959  }
960  }
961 
979  @Beta
980  public Set<Long> updateEventsForContentTagDeleted(Content content) throws TskCoreException {
982  try (CaseDbConnection conn = caseDB.getConnection()) {
983  if (caseDB.getContentTagsByContent(content).isEmpty()) {
984  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
985  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
986  return eventIDs.keySet();
987  } else {
988  return Collections.emptySet();
989  }
990  } finally {
992  }
993  }
994 
1006  public Set<Long> updateEventsForArtifactTagAdded(BlackboardArtifact artifact) throws TskCoreException {
1008  try (CaseDbConnection conn = caseDB.getConnection()) {
1009  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1010  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
1011  return eventIDs.keySet();
1012  } finally {
1014  }
1015  }
1016 
1029  public Set<Long> updateEventsForArtifactTagDeleted(BlackboardArtifact artifact) throws TskCoreException {
1031  try (CaseDbConnection conn = caseDB.getConnection()) {
1032  if (caseDB.getBlackboardArtifactTagsByArtifact(artifact).isEmpty()) {
1033  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1034  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
1035  return eventIDs.keySet();
1036  } else {
1037  return Collections.emptySet();
1038  }
1039  } finally {
1041  }
1042  }
1043 
1044  private void updateEventSourceTaggedFlag(CaseDbConnection conn, Collection<Long> eventDescriptionIDs, int flagValue) throws TskCoreException {
1045  if (eventDescriptionIDs.isEmpty()) {
1046  return;
1047  }
1048 
1049  String sql = "UPDATE tsk_event_descriptions SET tagged = " + flagValue + " WHERE event_description_id IN (" + buildCSVString(eventDescriptionIDs) + ")"; //NON-NLS
1050  try (Statement updateStatement = conn.createStatement()) {
1051  updateStatement.executeUpdate(sql);
1052  } catch (SQLException ex) {
1053  throw new TskCoreException("Error marking content events tagged: " + sql, ex);//NON-NLS
1054  }
1055  }
1056 
1071  public Set<Long> updateEventsForHashSetHit(Content content) throws TskCoreException {
1073  try (CaseDbConnection con = caseDB.getConnection(); Statement updateStatement = con.createStatement();) {
1074  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(con, content.getId(), true);
1075  if (!eventIDs.isEmpty()) {
1076  String sql = "UPDATE tsk_event_descriptions SET hash_hit = 1" + " WHERE event_description_id IN (" + buildCSVString(eventIDs.values()) + ")"; //NON-NLS
1077  try {
1078  updateStatement.executeUpdate(sql); //NON-NLS
1079  return eventIDs.keySet();
1080  } catch (SQLException ex) {
1081  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
1082  }
1083  } else {
1084  return eventIDs.keySet();
1085  }
1086  } catch (SQLException ex) {
1087  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
1088  } finally {
1090  }
1091  }
1092 
1093  void rollBackTransaction(SleuthkitCase.CaseDbTransaction trans) throws TskCoreException {
1094  trans.rollback();
1095  }
1096 
1116  public Map<TimelineEventType, Long> countEventsByType(Long startTime, Long endTime, TimelineFilter.RootFilter filter, TimelineEventType.HierarchyLevel typeHierachyLevel) throws TskCoreException {
1117  long adjustedEndTime = Objects.equals(startTime, endTime) ? endTime + 1 : endTime;
1118  //do we want the base or subtype column of the databse
1119  String typeColumn = typeColumnHelper(TimelineEventType.HierarchyLevel.EVENT.equals(typeHierachyLevel));
1120 
1121  String queryString = "SELECT count(DISTINCT tsk_events.event_id) AS count, " + typeColumn//NON-NLS
1122  + " FROM " + getAugmentedEventsTablesSQL(filter)//NON-NLS
1123  + " WHERE time >= " + startTime + " AND time < " + adjustedEndTime + " AND " + getSQLWhere(filter) // NON-NLS
1124  + " GROUP BY " + typeColumn; // NON-NLS
1125 
1127  try (CaseDbConnection con = caseDB.getConnection();
1128  Statement stmt = con.createStatement();
1129  ResultSet results = stmt.executeQuery(queryString);) {
1130  Map<TimelineEventType, Long> typeMap = new HashMap<>();
1131  while (results.next()) {
1132  int eventTypeID = results.getInt(typeColumn);
1133  TimelineEventType eventType = getEventType(eventTypeID)
1134  .orElseThrow(() -> newEventTypeMappingException(eventTypeID));//NON-NLS
1135 
1136  typeMap.put(eventType, results.getLong("count")); // NON-NLS
1137  }
1138  return typeMap;
1139  } catch (SQLException ex) {
1140  throw new TskCoreException("Error getting count of events from db: " + queryString, ex); // NON-NLS
1141  } finally {
1143  }
1144  }
1145 
1146  private static TskCoreException newEventTypeMappingException(int eventTypeID) {
1147  return new TskCoreException("Error mapping event type id " + eventTypeID + " to EventType.");//NON-NLS
1148  }
1149 
1163  static private String getAugmentedEventsTablesSQL(TimelineFilter.RootFilter filter) {
1164  TimelineFilter.FileTypesFilter fileTypesFitler = filter.getFileTypesFilter();
1165  boolean needsMimeTypes = fileTypesFitler != null && fileTypesFitler.hasSubFilters();
1166 
1167  return getAugmentedEventsTablesSQL(needsMimeTypes);
1168  }
1169 
1184  static private String getAugmentedEventsTablesSQL(boolean needMimeTypes) {
1185  /*
1186  * Regarding the timeline event tables schema, note that several columns
1187  * in the tsk_event_descriptions table seem, at first glance, to be
1188  * attributes of events rather than their descriptions and would appear
1189  * to belong in tsk_events table instead. The rationale for putting the
1190  * data source object ID, content object ID, artifact ID and the flags
1191  * indicating whether or not the event source has a hash set hit or is
1192  * tagged were motivated by the fact that these attributes are identical
1193  * for each event in a set of file system file MAC time events. The
1194  * decision was made to avoid duplication and save space by placing this
1195  * data in the tsk_event-descriptions table.
1196  */
1197  return "( SELECT event_id, time, tsk_event_descriptions.data_source_obj_id, content_obj_id, artifact_id, "
1198  + " full_description, med_description, short_description, tsk_events.event_type_id, super_type_id,"
1199  + " hash_hit, tagged "
1200  + (needMimeTypes ? ", mime_type" : "")
1201  + " FROM tsk_events "
1202  + " JOIN tsk_event_descriptions ON ( tsk_event_descriptions.event_description_id = tsk_events.event_description_id)"
1203  + " JOIN tsk_event_types ON (tsk_events.event_type_id = tsk_event_types.event_type_id ) "
1204  + (needMimeTypes ? " LEFT OUTER JOIN tsk_files "
1205  + " ON (tsk_event_descriptions.content_obj_id = tsk_files.obj_id)"
1206  : "")
1207  + ") AS tsk_events";
1208  }
1209 
1217  private static int booleanToInt(boolean value) {
1218  return value ? 1 : 0;
1219  }
1220 
1221  private static boolean intToBoolean(int value) {
1222  return value != 0;
1223  }
1224 
1237  public List<TimelineEvent> getEvents(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
1238  List<TimelineEvent> events = new ArrayList<>();
1239 
1240  Long startTime = timeRange.getStartMillis() / 1000;
1241  Long endTime = timeRange.getEndMillis() / 1000;
1242 
1243  if (Objects.equals(startTime, endTime)) {
1244  endTime++; //make sure end is at least 1 millisecond after start
1245  }
1246 
1247  if (filter == null) {
1248  return events;
1249  }
1250 
1251  if (endTime < startTime) {
1252  return events;
1253  }
1254 
1255  //build dynamic parts of query
1256  String querySql = "SELECT time, content_obj_id, data_source_obj_id, artifact_id, " // NON-NLS
1257  + " event_id, " //NON-NLS
1258  + " hash_hit, " //NON-NLS
1259  + " tagged, " //NON-NLS
1260  + " event_type_id, super_type_id, "
1261  + " full_description, med_description, short_description " // NON-NLS
1262  + " FROM " + getAugmentedEventsTablesSQL(filter) // NON-NLS
1263  + " WHERE time >= " + startTime + " AND time < " + endTime + " AND " + getSQLWhere(filter) // NON-NLS
1264  + " ORDER BY time"; // NON-NLS
1265 
1267  try (CaseDbConnection con = caseDB.getConnection();
1268  Statement stmt = con.createStatement();
1269  ResultSet resultSet = stmt.executeQuery(querySql);) {
1270 
1271  while (resultSet.next()) {
1272  int eventTypeID = resultSet.getInt("event_type_id");
1273  TimelineEventType eventType = getEventType(eventTypeID).orElseThrow(()
1274  -> new TskCoreException("Error mapping event type id " + eventTypeID + "to EventType."));//NON-NLS
1275 
1276  TimelineEvent event = new TimelineEvent(
1277  resultSet.getLong("event_id"), // NON-NLS
1278  resultSet.getLong("data_source_obj_id"), // NON-NLS
1279  resultSet.getLong("content_obj_id"), // NON-NLS
1280  resultSet.getLong("artifact_id"), // NON-NLS
1281  resultSet.getLong("time"), // NON-NLS
1282  eventType,
1283  resultSet.getString("full_description"), // NON-NLS
1284  resultSet.getString("med_description"), // NON-NLS
1285  resultSet.getString("short_description"), // NON-NLS
1286  resultSet.getInt("hash_hit") != 0, //NON-NLS
1287  resultSet.getInt("tagged") != 0);
1288 
1289  events.add(event);
1290  }
1291 
1292  } catch (SQLException ex) {
1293  throw new TskCoreException("Error getting events from db: " + querySql, ex); // NON-NLS
1294  } finally {
1296  }
1297 
1298  return events;
1299  }
1300 
1308  private static String typeColumnHelper(final boolean useSubTypes) {
1309  return useSubTypes ? "event_type_id" : "super_type_id"; //NON-NLS
1310  }
1311 
1320  String getSQLWhere(TimelineFilter.RootFilter filter) {
1321 
1322  String result;
1323  if (filter == null) {
1324  return getTrueLiteral();
1325  } else {
1326  result = filter.getSQLWhere(this);
1327  }
1328 
1329  return result;
1330  }
1331 
1343  private String getSqlIgnoreConflict(String insertTableValues) throws TskCoreException {
1344  switch (caseDB.getDatabaseType()) {
1345  case POSTGRESQL:
1346  return "INSERT INTO " + insertTableValues + " ON CONFLICT DO NOTHING";
1347  case SQLITE:
1348  return "INSERT OR IGNORE INTO " + insertTableValues;
1349  default:
1350  throw new TskCoreException("Unknown DB Type: " + caseDB.getDatabaseType().name());
1351  }
1352  }
1353 
1354  private String getTrueLiteral() {
1355  switch (caseDB.getDatabaseType()) {
1356  case POSTGRESQL:
1357  return "TRUE";//NON-NLS
1358  case SQLITE:
1359  return "1";//NON-NLS
1360  default:
1361  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());//NON-NLS
1362 
1363  }
1364  }
1365 
1370  final static public class TimelineEventAddedEvent {
1371 
1372  private final TimelineEvent addedEvent;
1373 
1375  return addedEvent;
1376  }
1377 
1379  this.addedEvent = event;
1380  }
1381  }
1382 
1386  private static class DuplicateException extends Exception {
1387 
1388  private static final long serialVersionUID = 1L;
1389 
1395  DuplicateException(String message) {
1396  super(message);
1397  }
1398  }
1399 }
List< Long > getEventIDs(Interval timeRange, TimelineFilter.RootFilter filter)
TimelineEvent getEventById(long eventID)
ImmutableList< TimelineEventType > getEventTypes()
Interval getSpanningInterval(Interval timeRange, TimelineFilter.RootFilter filter, DateTimeZone timeZone)
Set< Long > getEventIDsForContent(Content content, boolean includeDerivedArtifacts)
Interval getSpanningInterval(Collection< Long > eventIDs)
Set< Long > updateEventsForContentTagAdded(Content content)
List< BlackboardArtifactTag > getBlackboardArtifactTagsByArtifact(BlackboardArtifact artifact)
SortedSet<?extends TimelineEventType > getChildren()
Set< Long > updateEventsForContentTagDeleted(Content content)
Set< Long > updateEventsForHashSetHit(Content content)
static String escapeSingleQuotes(String text)
Set< Long > updateEventsForArtifactTagDeleted(BlackboardArtifact artifact)
Map< TimelineEventType, Long > countEventsByType(Long startTime, Long endTime, TimelineFilter.RootFilter filter, TimelineEventType.HierarchyLevel typeHierachyLevel)
List< Long > getEventIDsForArtifact(BlackboardArtifact artifact)
List< TimelineEvent > getEvents(Interval timeRange, TimelineFilter.RootFilter filter)
List< ContentTag > getContentTagsByContent(Content content)
Optional< TimelineEventType > getEventType(long eventTypeID)
Set< Long > updateEventsForArtifactTagAdded(BlackboardArtifact artifact)

Copyright © 2011-2021 Brian Carrier. (carrier -at- sleuthkit -dot- org)
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.