Sleuth Kit Java Bindings (JNI)  4.10.2
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>()
86  .build();
87 
88  // all known artifact type ids (used for determining if an artifact is standard or custom event)
89  private static final Set<Integer> ARTIFACT_TYPE_IDS = Stream.of(BlackboardArtifact.ARTIFACT_TYPE.values())
90  .map(artType -> artType.getTypeID())
91  .collect(Collectors.toSet());
92 
93  private final SleuthkitCase caseDB;
94 
99  private static final Long MAX_TIMESTAMP_TO_ADD = Instant.now().getEpochSecond() + 394200000;
100 
104  private final Map<Long, TimelineEventType> eventTypeIDMap = new HashMap<>();
105 
116  this.caseDB = caseDB;
117 
118  List<TimelineEventType> fullList = new ArrayList<>();
119  fullList.addAll(ROOT_CATEGORY_AND_FILESYSTEM_TYPES);
120  fullList.addAll(PREDEFINED_EVENT_TYPES);
121 
123  try (final CaseDbConnection con = caseDB.getConnection();
124  final PreparedStatement pStatement = con.prepareStatement(
125  insertOrIgnore(" INTO tsk_event_types(event_type_id, display_name, super_type_id) VALUES (?, ?, ?)"),
126  Statement.NO_GENERATED_KEYS)) {
127  for (TimelineEventType type : fullList) {
128  pStatement.setLong(1, type.getTypeID());
129  pStatement.setString(2, escapeSingleQuotes(type.getDisplayName()));
130  if (type != type.getParent()) {
131  pStatement.setLong(3, type.getParent().getTypeID());
132  } else {
133  pStatement.setNull(3, java.sql.Types.INTEGER);
134  }
135 
136  con.executeUpdate(pStatement);
137  eventTypeIDMap.put(type.getTypeID(), type);
138  }
139  } catch (SQLException ex) {
140  throw new TskCoreException("Failed to initialize timeline event types", ex); // NON-NLS
141  } finally {
143  }
144  }
145 
157  public Interval getSpanningInterval(Collection<Long> eventIDs) throws TskCoreException {
158  if (eventIDs.isEmpty()) {
159  return null;
160  }
161  final String query = "SELECT Min(time) as minTime, Max(time) as maxTime FROM tsk_events WHERE event_id IN (" + buildCSVString(eventIDs) + ")"; //NON-NLS
163  try (CaseDbConnection con = caseDB.getConnection();
164  Statement stmt = con.createStatement();
165  ResultSet results = stmt.executeQuery(query);) {
166  if (results.next()) {
167  return new Interval(results.getLong("minTime") * 1000, (results.getLong("maxTime") + 1) * 1000, DateTimeZone.UTC); // NON-NLS
168  }
169  } catch (SQLException ex) {
170  throw new TskCoreException("Error executing get spanning interval query: " + query, ex); // NON-NLS
171  } finally {
173  }
174  return null;
175  }
176 
189  public Interval getSpanningInterval(Interval timeRange, TimelineFilter.RootFilter filter, DateTimeZone timeZone) throws TskCoreException {
190  long start = timeRange.getStartMillis() / 1000;
191  long end = timeRange.getEndMillis() / 1000;
192  String sqlWhere = getSQLWhere(filter);
193  String augmentedEventsTablesSQL = getAugmentedEventsTablesSQL(filter);
194  String queryString = " SELECT (SELECT Max(time) FROM " + augmentedEventsTablesSQL
195  + " WHERE time <=" + start + " AND " + sqlWhere + ") AS start,"
196  + " (SELECT Min(time) FROM " + augmentedEventsTablesSQL
197  + " WHERE time >= " + end + " AND " + sqlWhere + ") AS end";//NON-NLS
199  try (CaseDbConnection con = caseDB.getConnection();
200  Statement stmt = con.createStatement(); //can't use prepared statement because of complex where clause
201  ResultSet results = stmt.executeQuery(queryString);) {
202 
203  if (results.next()) {
204  long start2 = results.getLong("start"); // NON-NLS
205  long end2 = results.getLong("end"); // NON-NLS
206 
207  if (end2 == 0) {
208  end2 = getMaxEventTime();
209  }
210  return new Interval(start2 * 1000, (end2 + 1) * 1000, timeZone);
211  }
212  } catch (SQLException ex) {
213  throw new TskCoreException("Failed to get MIN time.", ex); // NON-NLS
214  } finally {
216  }
217  return null;
218  }
219 
229  public TimelineEvent getEventById(long eventID) throws TskCoreException {
230  String sql = "SELECT * FROM " + getAugmentedEventsTablesSQL(false) + " WHERE event_id = " + eventID;
232  try (CaseDbConnection con = caseDB.getConnection();
233  Statement stmt = con.createStatement();) {
234  try (ResultSet results = stmt.executeQuery(sql);) {
235  if (results.next()) {
236  int typeID = results.getInt("event_type_id");
237  TimelineEventType type = getEventType(typeID).orElseThrow(() -> newEventTypeMappingException(typeID)); //NON-NLS
238  return new TimelineEvent(eventID,
239  results.getLong("data_source_obj_id"),
240  results.getLong("content_obj_id"),
241  results.getLong("artifact_id"),
242  results.getLong("time"),
243  type, results.getString("full_description"),
244  results.getString("med_description"),
245  results.getString("short_description"),
246  intToBoolean(results.getInt("hash_hit")),
247  intToBoolean(results.getInt("tagged")));
248  }
249  }
250  } catch (SQLException sqlEx) {
251  throw new TskCoreException("Error while executing query " + sql, sqlEx); // NON-NLS
252  } finally {
254  }
255  return null;
256  }
257 
269  public List<Long> getEventIDs(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
270  Long startTime = timeRange.getStartMillis() / 1000;
271  Long endTime = timeRange.getEndMillis() / 1000;
272 
273  if (Objects.equals(startTime, endTime)) {
274  endTime++; //make sure end is at least 1 millisecond after start
275  }
276 
277  ArrayList<Long> resultIDs = new ArrayList<>();
278 
279  String query = "SELECT tsk_events.event_id AS event_id FROM " + getAugmentedEventsTablesSQL(filter)
280  + " WHERE time >= " + startTime + " AND time <" + endTime + " AND " + getSQLWhere(filter) + " ORDER BY time ASC"; // NON-NLS
282  try (CaseDbConnection con = caseDB.getConnection();
283  Statement stmt = con.createStatement();
284  ResultSet results = stmt.executeQuery(query);) {
285  while (results.next()) {
286  resultIDs.add(results.getLong("event_id")); //NON-NLS
287  }
288 
289  } catch (SQLException sqlEx) {
290  throw new TskCoreException("Error while executing query " + query, sqlEx); // NON-NLS
291  } finally {
293  }
294 
295  return resultIDs;
296  }
297 
306  public Long getMaxEventTime() throws TskCoreException {
308  try (CaseDbConnection con = caseDB.getConnection();
309  Statement stms = con.createStatement();
310  ResultSet results = stms.executeQuery(STATEMENTS.GET_MAX_TIME.getSQL());) {
311  if (results.next()) {
312  return results.getLong("max"); // NON-NLS
313  }
314  } catch (SQLException ex) {
315  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
316  } finally {
318  }
319  return -1l;
320  }
321 
330  public Long getMinEventTime() throws TskCoreException {
332  try (CaseDbConnection con = caseDB.getConnection();
333  Statement stms = con.createStatement();
334  ResultSet results = stms.executeQuery(STATEMENTS.GET_MIN_TIME.getSQL());) {
335  if (results.next()) {
336  return results.getLong("min"); // NON-NLS
337  }
338  } catch (SQLException ex) {
339  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
340  } finally {
342  }
343  return -1l;
344  }
345 
354  public Optional<TimelineEventType> getEventType(long eventTypeID) {
355  return Optional.ofNullable(eventTypeIDMap.get(eventTypeID));
356  }
357 
363  public ImmutableList<TimelineEventType> getEventTypes() {
364  return ImmutableList.copyOf(eventTypeIDMap.values());
365  }
366 
367  private String insertOrIgnore(String query) {
368  switch (caseDB.getDatabaseType()) {
369  case POSTGRESQL:
370  return " INSERT " + query + " ON CONFLICT DO NOTHING "; //NON-NLS
371  case SQLITE:
372  return " INSERT OR IGNORE " + query; //NON-NLS
373  default:
374  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());
375  }
376  }
377 
381  private enum STATEMENTS {
382 
383  GET_MAX_TIME("SELECT Max(time) AS max FROM tsk_events"), // NON-NLS
384  GET_MIN_TIME("SELECT Min(time) AS min FROM tsk_events"); // NON-NLS
385 
386  private final String sql;
387 
388  private STATEMENTS(String sql) {
389  this.sql = sql;
390  }
391 
392  String getSQL() {
393  return sql;
394  }
395  }
396 
407  public List<Long> getEventIDsForArtifact(BlackboardArtifact artifact) throws TskCoreException {
408  ArrayList<Long> eventIDs = new ArrayList<>();
409 
410  String query
411  = "SELECT event_id FROM tsk_events "
412  + " LEFT JOIN tsk_event_descriptions on ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id ) "
413  + " WHERE artifact_id = " + artifact.getArtifactID();
415  try (CaseDbConnection con = caseDB.getConnection();
416  Statement stmt = con.createStatement();
417  ResultSet results = stmt.executeQuery(query);) {
418  while (results.next()) {
419  eventIDs.add(results.getLong("event_id"));//NON-NLS
420  }
421  } catch (SQLException ex) {
422  throw new TskCoreException("Error executing getEventIDsForArtifact query.", ex); // NON-NLS
423  } finally {
425  }
426  return eventIDs;
427  }
428 
442  public Set<Long> getEventIDsForContent(Content content, boolean includeDerivedArtifacts) throws TskCoreException {
444  try (CaseDbConnection conn = caseDB.getConnection()) {
445  return getEventAndDescriptionIDs(conn, content.getId(), includeDerivedArtifacts).keySet();
446  } finally {
448  }
449  }
450 
469  private Long addEventDescription(long dataSourceObjId, long fileObjId, Long artifactID,
470  String fullDescription, String medDescription, String shortDescription,
471  boolean hasHashHits, boolean tagged, CaseDbConnection connection) throws TskCoreException, DuplicateException {
472  String tableValuesClause
473  = "tsk_event_descriptions ( "
474  + "data_source_obj_id, content_obj_id, artifact_id, "
475  + " full_description, med_description, short_description, "
476  + " hash_hit, tagged "
477  + " ) VALUES "
478  + "(?, ?, ?, ?, ?, ?, ?, ?)";
479 
480  String insertDescriptionSql = getSqlIgnoreConflict(tableValuesClause);
481 
483  try {
484  PreparedStatement insertDescriptionStmt = connection.getPreparedStatement(insertDescriptionSql, PreparedStatement.RETURN_GENERATED_KEYS);
485  insertDescriptionStmt.clearParameters();
486  insertDescriptionStmt.setLong(1, dataSourceObjId);
487  insertDescriptionStmt.setLong(2, fileObjId);
488 
489  if (artifactID == null) {
490  insertDescriptionStmt.setNull(3, Types.INTEGER);
491  } else {
492  insertDescriptionStmt.setLong(3, artifactID);
493  }
494 
495  insertDescriptionStmt.setString(4, fullDescription);
496  insertDescriptionStmt.setString(5, medDescription);
497  insertDescriptionStmt.setString(6, shortDescription);
498  insertDescriptionStmt.setInt(7, booleanToInt(hasHashHits));
499  insertDescriptionStmt.setInt(8, booleanToInt(tagged));
500  int row = insertDescriptionStmt.executeUpdate();
501  // if no inserted rows, there is a conflict due to a duplicate event
502  // description. If that happens, return null as no id was inserted.
503  if (row < 1) {
504  return null;
505  }
506 
507  try (ResultSet generatedKeys = insertDescriptionStmt.getGeneratedKeys()) {
508  if (generatedKeys.next()) {
509  return generatedKeys.getLong(1);
510  } else {
511  return null;
512  }
513  }
514  } catch (SQLException ex) {
515  throw new TskCoreException("Failed to insert event description.", ex); // NON-NLS
516  } finally {
518  }
519  }
520 
534  private Long getEventDescription(long dataSourceObjId, long fileObjId, Long artifactID,
535  String fullDescription, CaseDbConnection connection) throws TskCoreException {
536 
537  String query = "SELECT event_description_id FROM tsk_event_descriptions "
538  + "WHERE data_source_obj_id = " + dataSourceObjId
539  + " AND content_obj_id = " + fileObjId
540  + " AND artifact_id " + (artifactID != null ? " = " + artifactID : "IS null")
541  + " AND full_description " + (fullDescription != null ? "= '"
542  + SleuthkitCase.escapeSingleQuotes(fullDescription) + "'" : "IS null");
543 
545  try (ResultSet resultSet = connection.createStatement().executeQuery(query)) {
546 
547  if (resultSet.next()) {
548  long id = resultSet.getLong(1);
549  return id;
550  }
551  } catch (SQLException ex) {
552  throw new TskCoreException(String.format("Failed to get description, dataSource=%d, fileObjId=%d, artifactId=%d", dataSourceObjId, fileObjId, artifactID), ex);
553  } finally {
555  }
556 
557  return null;
558  }
559 
560  Collection<TimelineEvent> addEventsForNewFile(AbstractFile file, CaseDbConnection connection) throws TskCoreException {
561  Set<TimelineEvent> events = addEventsForNewFileQuiet(file, connection);
562  events.stream()
563  .map(TimelineEventAddedEvent::new)
564  .forEach(caseDB::fireTSKEvent);
565 
566  return events;
567  }
568 
583  Set<TimelineEvent> addEventsForNewFileQuiet(AbstractFile file, CaseDbConnection connection) throws TskCoreException {
584  //gather time stamps into map
585  Map<TimelineEventType, Long> timeMap = ImmutableMap.of(TimelineEventType.FILE_CREATED, file.getCrtime(),
586  TimelineEventType.FILE_ACCESSED, file.getAtime(),
587  TimelineEventType.FILE_CHANGED, file.getCtime(),
588  TimelineEventType.FILE_MODIFIED, file.getMtime());
589 
590  /*
591  * If there are no legitimate ( greater than zero ) time stamps skip the
592  * rest of the event generation.
593  */
594  if (Collections.max(timeMap.values()) <= 0) {
595  return Collections.emptySet();
596  }
597 
598  String description = file.getParentPath() + file.getName();
599  long fileObjId = file.getId();
600  Set<TimelineEvent> events = new HashSet<>();
602  try {
603  Long descriptionID = addEventDescription(file.getDataSourceObjectId(), fileObjId, null,
604  description, null, null, false, false, connection);
605 
606  if(descriptionID == null) {
607  descriptionID = getEventDescription(file.getDataSourceObjectId(), fileObjId, null, description, connection);
608  }
609  if(descriptionID != null) {
610  for (Map.Entry<TimelineEventType, Long> timeEntry : timeMap.entrySet()) {
611  Long time = timeEntry.getValue();
612  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
613  TimelineEventType type = timeEntry.getKey();
614  long eventID = addEventWithExistingDescription(time, type, descriptionID, connection);
615 
616  /*
617  * Last two flags indicating hasTags and hasHashHits are
618  * both set to false with the assumption that this is not
619  * possible for a new file. See JIRA-5407
620  */
621  events.add(new TimelineEvent(eventID, descriptionID, fileObjId, null, time, type,
622  description, null, null, false, false));
623  } else {
624  if (time >= MAX_TIMESTAMP_TO_ADD) {
625  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()));
626  }
627  }
628  }
629  } else {
630  throw new TskCoreException(String.format("Failed to get event description for file id = %d", fileObjId));
631  }
632  } catch (DuplicateException dupEx) {
633  logger.log(Level.SEVERE, "Attempt to make file event duplicate.", dupEx);
634  } finally {
636  }
637 
638  return events;
639  }
640 
654  Set<TimelineEvent> addArtifactEvents(BlackboardArtifact artifact) throws TskCoreException {
655  Set<TimelineEvent> newEvents = new HashSet<>();
656 
657  /*
658  * If the artifact is a TSK_TL_EVENT, use the TSK_TL_EVENT_TYPE
659  * attribute to determine its event type, but give it a generic
660  * description.
661  */
662  if (artifact.getArtifactTypeID() == TSK_TL_EVENT.getTypeID()) {
663  TimelineEventType eventType;//the type of the event to add.
664  BlackboardAttribute attribute = artifact.getAttribute(new BlackboardAttribute.Type(TSK_TL_EVENT_TYPE));
665  if (attribute == null) {
666  eventType = TimelineEventType.OTHER;
667  } else {
668  long eventTypeID = attribute.getValueLong();
669  eventType = eventTypeIDMap.getOrDefault(eventTypeID, TimelineEventType.OTHER);
670  }
671 
672  try {
673  // @@@ This casting is risky if we change class hierarchy, but was expedient. Should move parsing to another class
674  addArtifactEvent(((TimelineEventArtifactTypeImpl) TimelineEventType.OTHER).makeEventDescription(artifact), eventType, artifact)
675  .ifPresent(newEvents::add);
676  } catch (DuplicateException ex) {
677  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make a timeline event artifact duplicate"), ex);
678  }
679  } else {
680  /*
681  * If there are any event types configured to make descriptions
682  * automatically, use those.
683  */
684  Set<TimelineEventArtifactTypeImpl> eventTypesForArtifact = eventTypeIDMap.values().stream()
685  .filter(TimelineEventArtifactTypeImpl.class::isInstance)
686  .map(TimelineEventArtifactTypeImpl.class::cast)
687  .filter(eventType -> eventType.getArtifactTypeID() == artifact.getArtifactTypeID())
688  .collect(Collectors.toSet());
689 
690  boolean duplicateExists = false;
691  for (TimelineEventArtifactTypeImpl eventType : eventTypesForArtifact) {
692  try {
693  addArtifactEvent(eventType.makeEventDescription(artifact), eventType, artifact)
694  .ifPresent(newEvents::add);
695  } catch (DuplicateException ex) {
696  duplicateExists = true;
697  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make artifact event duplicate"), ex);
698  }
699  }
700 
701  // if no other timeline events were created directly, then create new 'other' ones.
702  if (!duplicateExists && newEvents.isEmpty()) {
703  try {
704  addOtherEventDesc(artifact).ifPresent(newEvents::add);
705  } catch (DuplicateException ex) {
706  logger.log(Level.SEVERE, getDuplicateExceptionMessage(artifact, "Attempt to make 'other' artifact event duplicate"), ex);
707  }
708  }
709  }
710  newEvents.stream()
711  .map(TimelineEventAddedEvent::new)
712  .forEach(caseDB::fireTSKEvent);
713  return newEvents;
714  }
715 
728  private String getDuplicateExceptionMessage(BlackboardArtifact artifact, String error) {
729  String artifactIDStr = null;
730  String sourceStr = null;
731 
732  if (artifact != null) {
733  artifactIDStr = Long.toString(artifact.getId());
734 
735  try {
736  sourceStr = artifact.getAttributes().stream()
737  .filter(attr -> attr != null && attr.getSources() != null && !attr.getSources().isEmpty())
738  .map(attr -> String.join(",", attr.getSources()))
739  .findFirst()
740  .orElse(null);
741  } catch (TskCoreException ex) {
742  logger.log(Level.WARNING, String.format("Could not fetch artifacts for artifact id: %d.", artifact.getId()), ex);
743  }
744  }
745 
746  artifactIDStr = (artifactIDStr == null) ? "<null>" : artifactIDStr;
747  sourceStr = (sourceStr == null) ? "<null>" : sourceStr;
748 
749  return String.format("%s (artifactID=%s, Source=%s).", error, artifactIDStr, sourceStr);
750  }
751 
763  private Optional<TimelineEvent> addOtherEventDesc(BlackboardArtifact artifact) throws TskCoreException, DuplicateException {
764  if (artifact == null) {
765  return Optional.empty();
766  }
767 
768  Long timeVal = artifact.getAttributes().stream()
769  .filter((attr) -> attr.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME)
770  .map(attr -> attr.getValueLong())
771  .findFirst()
772  .orElse(null);
773 
774  if (timeVal == null) {
775  return Optional.empty();
776  }
777 
778  String description = String.format("%s: %d", artifact.getDisplayName(), artifact.getId());
779 
780  TimelineEventDescriptionWithTime evtWDesc = new TimelineEventDescriptionWithTime(timeVal, description, description, description);
781 
782  TimelineEventType evtType = (ARTIFACT_TYPE_IDS.contains(artifact.getArtifactTypeID()))
783  ? TimelineEventType.OTHER
784  : TimelineEventType.USER_CREATED;
785 
786  return addArtifactEvent(evtWDesc, evtType, artifact);
787  }
788 
802  private Optional<TimelineEvent> addArtifactEvent(TimelineEventDescriptionWithTime eventPayload,
803  TimelineEventType eventType, BlackboardArtifact artifact) throws TskCoreException, DuplicateException {
804 
805  if (eventPayload == null) {
806  return Optional.empty();
807  }
808  long time = eventPayload.getTime();
809  // 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
810  if (time <= 0 || time >= MAX_TIMESTAMP_TO_ADD) {
811  if (time >= MAX_TIMESTAMP_TO_ADD) {
812  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()));
813  }
814  return Optional.empty();
815  }
816  String fullDescription = eventPayload.getDescription(TimelineLevelOfDetail.HIGH);
817  String medDescription = eventPayload.getDescription(TimelineLevelOfDetail.MEDIUM);
818  String shortDescription = eventPayload.getDescription(TimelineLevelOfDetail.LOW);
819  long artifactID = artifact.getArtifactID();
820  long fileObjId = artifact.getObjectID();
821  Long dataSourceObjectID = artifact.getDataSourceObjectID();
822 
823  if(dataSourceObjectID == null) {
824  logger.log(Level.SEVERE, String.format("Failed to create timeline event for artifact (%d), artifact data source was null"), artifact.getId());
825  return Optional.empty();
826  }
827 
828  AbstractFile file = caseDB.getAbstractFileById(fileObjId);
829  boolean hasHashHits = false;
830  // file will be null if source was data source or some non-file
831  if (file != null) {
832  hasHashHits = isNotEmpty(file.getHashSetNames());
833  }
834  boolean tagged = isNotEmpty(caseDB.getBlackboardArtifactTagsByArtifact(artifact));
835 
836  TimelineEvent event;
838  try (CaseDbConnection connection = caseDB.getConnection();) {
839 
840  Long descriptionID = addEventDescription(dataSourceObjectID, fileObjId, artifactID,
841  fullDescription, medDescription, shortDescription,
842  hasHashHits, tagged, connection);
843 
844  if(descriptionID == null) {
845  descriptionID = getEventDescription(dataSourceObjectID, fileObjId, artifactID,
846  fullDescription, connection);
847  }
848 
849  if(descriptionID != null) {
850  long eventID = addEventWithExistingDescription(time, eventType, descriptionID, connection);
851 
852  event = new TimelineEvent(eventID, dataSourceObjectID, fileObjId, artifactID,
853  time, eventType, fullDescription, medDescription, shortDescription,
854  hasHashHits, tagged);
855  } else {
856  throw new TskCoreException(String.format("Failed to get event description for file id = %d, artifactId %d", fileObjId, artifactID));
857  }
858 
859  } finally {
861  }
862  return Optional.of(event);
863  }
864 
865  private long addEventWithExistingDescription(Long time, TimelineEventType type, long descriptionID, CaseDbConnection connection) throws TskCoreException, DuplicateException {
866  String tableValuesClause
867  = "tsk_events ( event_type_id, event_description_id , time) VALUES (?, ?, ?)";
868 
869  String insertEventSql = getSqlIgnoreConflict(tableValuesClause);
870 
872  try {
873  PreparedStatement insertRowStmt = connection.getPreparedStatement(insertEventSql, Statement.RETURN_GENERATED_KEYS);
874  insertRowStmt.clearParameters();
875  insertRowStmt.setLong(1, type.getTypeID());
876  insertRowStmt.setLong(2, descriptionID);
877  insertRowStmt.setLong(3, time);
878  int row = insertRowStmt.executeUpdate();
879  // if no inserted rows, return null.
880  if (row < 1) {
881  throw new DuplicateException(String.format("An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
882  time == null ? "<null>" : Long.toString(time),
883  type == null ? "<null>" : type.toString(),
884  descriptionID));
885  }
886 
887  try (ResultSet generatedKeys = insertRowStmt.getGeneratedKeys();) {
888  if (generatedKeys.next()) {
889  return generatedKeys.getLong(1);
890  } else {
891  throw new DuplicateException(String.format("An event already exists in the event table for this item [time: %s, type: %s, description: %d].",
892  time == null ? "<null>" : Long.toString(time),
893  type == null ? "<null>" : type.toString(),
894  descriptionID));
895  }
896  }
897  } catch (SQLException ex) {
898  throw new TskCoreException("Failed to insert event for existing description.", ex); // NON-NLS
899  } finally {
901  }
902  }
903 
904  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, boolean includeArtifacts) throws TskCoreException {
905  return getEventAndDescriptionIDsHelper(conn, contentObjID, (includeArtifacts ? "" : " AND artifact_id IS NULL"));
906  }
907 
908  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, Long artifactID) throws TskCoreException {
909  return getEventAndDescriptionIDsHelper(conn, contentObjID, " AND artifact_id = " + artifactID);
910  }
911 
912  private Map<Long, Long> getEventAndDescriptionIDsHelper(CaseDbConnection con, long fileObjID, String artifactClause) throws TskCoreException {
913  //map from event_id to the event_description_id for that event.
914  Map<Long, Long> eventIDToDescriptionIDs = new HashMap<>();
915  String sql = "SELECT event_id, tsk_events.event_description_id"
916  + " FROM tsk_events "
917  + " LEFT JOIN tsk_event_descriptions ON ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id )"
918  + " WHERE content_obj_id = " + fileObjID
919  + artifactClause;
920  try (Statement selectStmt = con.createStatement(); ResultSet executeQuery = selectStmt.executeQuery(sql);) {
921  while (executeQuery.next()) {
922  eventIDToDescriptionIDs.put(executeQuery.getLong("event_id"), executeQuery.getLong("event_description_id")); //NON-NLS
923  }
924  } catch (SQLException ex) {
925  throw new TskCoreException("Error getting event description ids for object id = " + fileObjID, ex);
926  }
927  return eventIDToDescriptionIDs;
928  }
929 
946  @Beta
947  public Set<Long> updateEventsForContentTagAdded(Content content) throws TskCoreException {
949  try (CaseDbConnection conn = caseDB.getConnection()) {
950  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
951  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
952  return eventIDs.keySet();
953  } finally {
955  }
956  }
957 
975  @Beta
976  public Set<Long> updateEventsForContentTagDeleted(Content content) throws TskCoreException {
978  try (CaseDbConnection conn = caseDB.getConnection()) {
979  if (caseDB.getContentTagsByContent(content).isEmpty()) {
980  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
981  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
982  return eventIDs.keySet();
983  } else {
984  return Collections.emptySet();
985  }
986  } finally {
988  }
989  }
990 
1002  public Set<Long> updateEventsForArtifactTagAdded(BlackboardArtifact artifact) throws TskCoreException {
1004  try (CaseDbConnection conn = caseDB.getConnection()) {
1005  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1006  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
1007  return eventIDs.keySet();
1008  } finally {
1010  }
1011  }
1012 
1025  public Set<Long> updateEventsForArtifactTagDeleted(BlackboardArtifact artifact) throws TskCoreException {
1027  try (CaseDbConnection conn = caseDB.getConnection()) {
1028  if (caseDB.getBlackboardArtifactTagsByArtifact(artifact).isEmpty()) {
1029  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
1030  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
1031  return eventIDs.keySet();
1032  } else {
1033  return Collections.emptySet();
1034  }
1035  } finally {
1037  }
1038  }
1039 
1040  private void updateEventSourceTaggedFlag(CaseDbConnection conn, Collection<Long> eventDescriptionIDs, int flagValue) throws TskCoreException {
1041  if (eventDescriptionIDs.isEmpty()) {
1042  return;
1043  }
1044 
1045  String sql = "UPDATE tsk_event_descriptions SET tagged = " + flagValue + " WHERE event_description_id IN (" + buildCSVString(eventDescriptionIDs) + ")"; //NON-NLS
1046  try (Statement updateStatement = conn.createStatement()) {
1047  updateStatement.executeUpdate(sql);
1048  } catch (SQLException ex) {
1049  throw new TskCoreException("Error marking content events tagged: " + sql, ex);//NON-NLS
1050  }
1051  }
1052 
1067  public Set<Long> updateEventsForHashSetHit(Content content) throws TskCoreException {
1069  try (CaseDbConnection con = caseDB.getConnection(); Statement updateStatement = con.createStatement();) {
1070  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(con, content.getId(), true);
1071  if (!eventIDs.isEmpty()) {
1072  String sql = "UPDATE tsk_event_descriptions SET hash_hit = 1" + " WHERE event_description_id IN (" + buildCSVString(eventIDs.values()) + ")"; //NON-NLS
1073  try {
1074  updateStatement.executeUpdate(sql); //NON-NLS
1075  return eventIDs.keySet();
1076  } catch (SQLException ex) {
1077  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
1078  }
1079  } else {
1080  return eventIDs.keySet();
1081  }
1082  } catch (SQLException ex) {
1083  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
1084  } finally {
1086  }
1087  }
1088 
1089  void rollBackTransaction(SleuthkitCase.CaseDbTransaction trans) throws TskCoreException {
1090  trans.rollback();
1091  }
1092 
1112  public Map<TimelineEventType, Long> countEventsByType(Long startTime, Long endTime, TimelineFilter.RootFilter filter, TimelineEventType.HierarchyLevel typeHierachyLevel) throws TskCoreException {
1113  long adjustedEndTime = Objects.equals(startTime, endTime) ? endTime + 1 : endTime;
1114  //do we want the base or subtype column of the databse
1115  String typeColumn = typeColumnHelper(TimelineEventType.HierarchyLevel.EVENT.equals(typeHierachyLevel));
1116 
1117  String queryString = "SELECT count(DISTINCT tsk_events.event_id) AS count, " + typeColumn//NON-NLS
1118  + " FROM " + getAugmentedEventsTablesSQL(filter)//NON-NLS
1119  + " WHERE time >= " + startTime + " AND time < " + adjustedEndTime + " AND " + getSQLWhere(filter) // NON-NLS
1120  + " GROUP BY " + typeColumn; // NON-NLS
1121 
1123  try (CaseDbConnection con = caseDB.getConnection();
1124  Statement stmt = con.createStatement();
1125  ResultSet results = stmt.executeQuery(queryString);) {
1126  Map<TimelineEventType, Long> typeMap = new HashMap<>();
1127  while (results.next()) {
1128  int eventTypeID = results.getInt(typeColumn);
1129  TimelineEventType eventType = getEventType(eventTypeID)
1130  .orElseThrow(() -> newEventTypeMappingException(eventTypeID));//NON-NLS
1131 
1132  typeMap.put(eventType, results.getLong("count")); // NON-NLS
1133  }
1134  return typeMap;
1135  } catch (SQLException ex) {
1136  throw new TskCoreException("Error getting count of events from db: " + queryString, ex); // NON-NLS
1137  } finally {
1139  }
1140  }
1141 
1142  private static TskCoreException newEventTypeMappingException(int eventTypeID) {
1143  return new TskCoreException("Error mapping event type id " + eventTypeID + " to EventType.");//NON-NLS
1144  }
1145 
1159  static private String getAugmentedEventsTablesSQL(TimelineFilter.RootFilter filter) {
1160  TimelineFilter.FileTypesFilter fileTypesFitler = filter.getFileTypesFilter();
1161  boolean needsMimeTypes = fileTypesFitler != null && fileTypesFitler.hasSubFilters();
1162 
1163  return getAugmentedEventsTablesSQL(needsMimeTypes);
1164  }
1165 
1180  static private String getAugmentedEventsTablesSQL(boolean needMimeTypes) {
1181  /*
1182  * Regarding the timeline event tables schema, note that several columns
1183  * in the tsk_event_descriptions table seem, at first glance, to be
1184  * attributes of events rather than their descriptions and would appear
1185  * to belong in tsk_events table instead. The rationale for putting the
1186  * data source object ID, content object ID, artifact ID and the flags
1187  * indicating whether or not the event source has a hash set hit or is
1188  * tagged were motivated by the fact that these attributes are identical
1189  * for each event in a set of file system file MAC time events. The
1190  * decision was made to avoid duplication and save space by placing this
1191  * data in the tsk_event-descriptions table.
1192  */
1193  return "( SELECT event_id, time, tsk_event_descriptions.data_source_obj_id, content_obj_id, artifact_id, "
1194  + " full_description, med_description, short_description, tsk_events.event_type_id, super_type_id,"
1195  + " hash_hit, tagged "
1196  + (needMimeTypes ? ", mime_type" : "")
1197  + " FROM tsk_events "
1198  + " JOIN tsk_event_descriptions ON ( tsk_event_descriptions.event_description_id = tsk_events.event_description_id)"
1199  + " JOIN tsk_event_types ON (tsk_events.event_type_id = tsk_event_types.event_type_id ) "
1200  + (needMimeTypes ? " LEFT OUTER JOIN tsk_files "
1201  + " ON (tsk_event_descriptions.content_obj_id = tsk_files.obj_id)"
1202  : "")
1203  + ") AS tsk_events";
1204  }
1205 
1213  private static int booleanToInt(boolean value) {
1214  return value ? 1 : 0;
1215  }
1216 
1217  private static boolean intToBoolean(int value) {
1218  return value != 0;
1219  }
1220 
1233  public List<TimelineEvent> getEvents(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
1234  List<TimelineEvent> events = new ArrayList<>();
1235 
1236  Long startTime = timeRange.getStartMillis() / 1000;
1237  Long endTime = timeRange.getEndMillis() / 1000;
1238 
1239  if (Objects.equals(startTime, endTime)) {
1240  endTime++; //make sure end is at least 1 millisecond after start
1241  }
1242 
1243  if (filter == null) {
1244  return events;
1245  }
1246 
1247  if (endTime < startTime) {
1248  return events;
1249  }
1250 
1251  //build dynamic parts of query
1252  String querySql = "SELECT time, content_obj_id, data_source_obj_id, artifact_id, " // NON-NLS
1253  + " event_id, " //NON-NLS
1254  + " hash_hit, " //NON-NLS
1255  + " tagged, " //NON-NLS
1256  + " event_type_id, super_type_id, "
1257  + " full_description, med_description, short_description " // NON-NLS
1258  + " FROM " + getAugmentedEventsTablesSQL(filter) // NON-NLS
1259  + " WHERE time >= " + startTime + " AND time < " + endTime + " AND " + getSQLWhere(filter) // NON-NLS
1260  + " ORDER BY time"; // NON-NLS
1261 
1263  try (CaseDbConnection con = caseDB.getConnection();
1264  Statement stmt = con.createStatement();
1265  ResultSet resultSet = stmt.executeQuery(querySql);) {
1266 
1267  while (resultSet.next()) {
1268  int eventTypeID = resultSet.getInt("event_type_id");
1269  TimelineEventType eventType = getEventType(eventTypeID).orElseThrow(()
1270  -> new TskCoreException("Error mapping event type id " + eventTypeID + "to EventType."));//NON-NLS
1271 
1272  TimelineEvent event = new TimelineEvent(
1273  resultSet.getLong("event_id"), // NON-NLS
1274  resultSet.getLong("data_source_obj_id"), // NON-NLS
1275  resultSet.getLong("content_obj_id"), // NON-NLS
1276  resultSet.getLong("artifact_id"), // NON-NLS
1277  resultSet.getLong("time"), // NON-NLS
1278  eventType,
1279  resultSet.getString("full_description"), // NON-NLS
1280  resultSet.getString("med_description"), // NON-NLS
1281  resultSet.getString("short_description"), // NON-NLS
1282  resultSet.getInt("hash_hit") != 0, //NON-NLS
1283  resultSet.getInt("tagged") != 0);
1284 
1285  events.add(event);
1286  }
1287 
1288  } catch (SQLException ex) {
1289  throw new TskCoreException("Error getting events from db: " + querySql, ex); // NON-NLS
1290  } finally {
1292  }
1293 
1294  return events;
1295  }
1296 
1304  private static String typeColumnHelper(final boolean useSubTypes) {
1305  return useSubTypes ? "event_type_id" : "super_type_id"; //NON-NLS
1306  }
1307 
1316  String getSQLWhere(TimelineFilter.RootFilter filter) {
1317 
1318  String result;
1319  if (filter == null) {
1320  return getTrueLiteral();
1321  } else {
1322  result = filter.getSQLWhere(this);
1323  }
1324 
1325  return result;
1326  }
1327 
1339  private String getSqlIgnoreConflict(String insertTableValues) throws TskCoreException {
1340  switch (caseDB.getDatabaseType()) {
1341  case POSTGRESQL:
1342  return "INSERT INTO " + insertTableValues + " ON CONFLICT DO NOTHING";
1343  case SQLITE:
1344  return "INSERT OR IGNORE INTO " + insertTableValues;
1345  default:
1346  throw new TskCoreException("Unknown DB Type: " + caseDB.getDatabaseType().name());
1347  }
1348  }
1349 
1350  private String getTrueLiteral() {
1351  switch (caseDB.getDatabaseType()) {
1352  case POSTGRESQL:
1353  return "TRUE";//NON-NLS
1354  case SQLITE:
1355  return "1";//NON-NLS
1356  default:
1357  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());//NON-NLS
1358 
1359  }
1360  }
1361 
1366  final static public class TimelineEventAddedEvent {
1367 
1368  private final TimelineEvent addedEvent;
1369 
1371  return addedEvent;
1372  }
1373 
1375  this.addedEvent = event;
1376  }
1377  }
1378 
1382  private static class DuplicateException extends Exception {
1383 
1384  private static final long serialVersionUID = 1L;
1385 
1391  DuplicateException(String message) {
1392  super(message);
1393  }
1394  }
1395 }
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.