Sleuth Kit Java Bindings (JNI)  4.8.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.time.Instant;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Objects;
37 import static java.util.Objects.isNull;
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 org.joda.time.DateTimeZone;
44 import org.joda.time.Interval;
47 import static org.sleuthkit.datamodel.CollectionUtils.isNotEmpty;
50 import static org.sleuthkit.datamodel.StringUtils.buildCSVString;
51 
55 public final class TimelineManager {
56 
57  private static final Logger logger = Logger.getLogger(TimelineManager.class.getName());
58 
62  private static final ImmutableList<TimelineEventType> ROOT_CATEGORY_AND_FILESYSTEM_TYPES
63  = ImmutableList.of(
72 
79  private static final ImmutableList<TimelineEventType> PREDEFINED_EVENT_TYPES
80  = new ImmutableList.Builder<TimelineEventType>()
85  .build();
86 
87  private final SleuthkitCase caseDB;
88 
92  private static final Long MAX_TIMESTAMP_TO_ADD = Instant.now().getEpochSecond() + 394200000;
93 
97  private final Map<Long, TimelineEventType> eventTypeIDMap = new HashMap<>();
98 
109  this.caseDB = caseDB;
110 
111  //initialize root and base event types, these are added to the DB in c++ land
112  ROOT_CATEGORY_AND_FILESYSTEM_TYPES.forEach(eventType -> eventTypeIDMap.put(eventType.getTypeID(), eventType));
113 
114  //initialize the other event types that aren't added in c++
116  try (final CaseDbConnection con = caseDB.getConnection();
117  final Statement statement = con.createStatement()) {
118  for (TimelineEventType type : PREDEFINED_EVENT_TYPES) {
119  con.executeUpdate(statement,
120  insertOrIgnore(" INTO tsk_event_types(event_type_id, display_name, super_type_id) "
121  + "VALUES( " + type.getTypeID() + ", '"
122  + escapeSingleQuotes(type.getDisplayName()) + "',"
123  + type.getParent().getTypeID()
124  + ")")); //NON-NLS
125  eventTypeIDMap.put(type.getTypeID(), type);
126  }
127  } catch (SQLException ex) {
128  throw new TskCoreException("Failed to initialize timeline event types", ex); // NON-NLS
129  } finally {
131  }
132  }
133 
145  public Interval getSpanningInterval(Collection<Long> eventIDs) throws TskCoreException {
146  if (eventIDs.isEmpty()) {
147  return null;
148  }
149  final String query = "SELECT Min(time) as minTime, Max(time) as maxTime FROM tsk_events WHERE event_id IN (" + buildCSVString(eventIDs) + ")"; //NON-NLS
151  try (CaseDbConnection con = caseDB.getConnection();
152  Statement stmt = con.createStatement();
153  ResultSet results = stmt.executeQuery(query);) {
154  if (results.next()) {
155  return new Interval(results.getLong("minTime") * 1000, (results.getLong("maxTime") + 1) * 1000, DateTimeZone.UTC); // NON-NLS
156  }
157  } catch (SQLException ex) {
158  throw new TskCoreException("Error executing get spanning interval query: " + query, ex); // NON-NLS
159  } finally {
161  }
162  return null;
163  }
164 
177  public Interval getSpanningInterval(Interval timeRange, TimelineFilter.RootFilter filter, DateTimeZone timeZone) throws TskCoreException {
178  long start = timeRange.getStartMillis() / 1000;
179  long end = timeRange.getEndMillis() / 1000;
180  String sqlWhere = getSQLWhere(filter);
181  String augmentedEventsTablesSQL = getAugmentedEventsTablesSQL(filter);
182  String queryString = " SELECT (SELECT Max(time) FROM " + augmentedEventsTablesSQL
183  + " WHERE time <=" + start + " AND " + sqlWhere + ") AS start,"
184  + " (SELECT Min(time) FROM " + augmentedEventsTablesSQL
185  + " WHERE time >= " + end + " AND " + sqlWhere + ") AS end";//NON-NLS
187  try (CaseDbConnection con = caseDB.getConnection();
188  Statement stmt = con.createStatement(); //can't use prepared statement because of complex where clause
189  ResultSet results = stmt.executeQuery(queryString);) {
190 
191  if (results.next()) {
192  long start2 = results.getLong("start"); // NON-NLS
193  long end2 = results.getLong("end"); // NON-NLS
194 
195  if (end2 == 0) {
196  end2 = getMaxEventTime();
197  }
198  return new Interval(start2 * 1000, (end2 + 1) * 1000, timeZone);
199  }
200  } catch (SQLException ex) {
201  throw new TskCoreException("Failed to get MIN time.", ex); // NON-NLS
202  } finally {
204  }
205  return null;
206  }
207 
217  public TimelineEvent getEventById(long eventID) throws TskCoreException {
218  String sql = "SELECT * FROM " + getAugmentedEventsTablesSQL(false) + " WHERE event_id = " + eventID;
220  try (CaseDbConnection con = caseDB.getConnection();
221  Statement stmt = con.createStatement();) {
222  try (ResultSet results = stmt.executeQuery(sql);) {
223  if (results.next()) {
224  int typeID = results.getInt("event_type_id");
225  TimelineEventType type = getEventType(typeID).orElseThrow(() -> newEventTypeMappingException(typeID)); //NON-NLS
226  return new TimelineEvent(eventID,
227  results.getLong("data_source_obj_id"),
228  results.getLong("content_obj_id"),
229  results.getLong("artifact_id"),
230  results.getLong("time"),
231  type, results.getString("full_description"),
232  results.getString("med_description"),
233  results.getString("short_description"),
234  intToBoolean(results.getInt("hash_hit")),
235  intToBoolean(results.getInt("tagged")));
236  }
237  }
238  } catch (SQLException sqlEx) {
239  throw new TskCoreException("Error while executing query " + sql, sqlEx); // NON-NLS
240  } finally {
242  }
243  return null;
244  }
245 
257  public List<Long> getEventIDs(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
258  Long startTime = timeRange.getStartMillis() / 1000;
259  Long endTime = timeRange.getEndMillis() / 1000;
260 
261  if (Objects.equals(startTime, endTime)) {
262  endTime++; //make sure end is at least 1 millisecond after start
263  }
264 
265  ArrayList<Long> resultIDs = new ArrayList<>();
266 
267  String query = "SELECT tsk_events.event_id AS event_id FROM " + getAugmentedEventsTablesSQL(filter)
268  + " WHERE time >= " + startTime + " AND time <" + endTime + " AND " + getSQLWhere(filter) + " ORDER BY time ASC"; // NON-NLS
270  try (CaseDbConnection con = caseDB.getConnection();
271  Statement stmt = con.createStatement();
272  ResultSet results = stmt.executeQuery(query);) {
273  while (results.next()) {
274  resultIDs.add(results.getLong("event_id")); //NON-NLS
275  }
276 
277  } catch (SQLException sqlEx) {
278  throw new TskCoreException("Error while executing query " + query, sqlEx); // NON-NLS
279  } finally {
281  }
282 
283  return resultIDs;
284  }
285 
294  public Long getMaxEventTime() throws TskCoreException {
296  try (CaseDbConnection con = caseDB.getConnection();
297  Statement stms = con.createStatement();
298  ResultSet results = stms.executeQuery(STATEMENTS.GET_MAX_TIME.getSQL());) {
299  if (results.next()) {
300  return results.getLong("max"); // NON-NLS
301  }
302  } catch (SQLException ex) {
303  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
304  } finally {
306  }
307  return -1l;
308  }
309 
318  public Long getMinEventTime() throws TskCoreException {
320  try (CaseDbConnection con = caseDB.getConnection();
321  Statement stms = con.createStatement();
322  ResultSet results = stms.executeQuery(STATEMENTS.GET_MIN_TIME.getSQL());) {
323  if (results.next()) {
324  return results.getLong("min"); // NON-NLS
325  }
326  } catch (SQLException ex) {
327  throw new TskCoreException("Error while executing query " + STATEMENTS.GET_MAX_TIME.getSQL(), ex); // NON-NLS
328  } finally {
330  }
331  return -1l;
332  }
333 
342  public Optional<TimelineEventType> getEventType(long eventTypeID) {
343  return Optional.ofNullable(eventTypeIDMap.get(eventTypeID));
344  }
345 
351  public ImmutableList<TimelineEventType> getEventTypes() {
352  return ImmutableList.copyOf(eventTypeIDMap.values());
353  }
354 
355  private String insertOrIgnore(String query) {
356  switch (caseDB.getDatabaseType()) {
357  case POSTGRESQL:
358  return " INSERT " + query + " ON CONFLICT DO NOTHING "; //NON-NLS
359  case SQLITE:
360  return " INSERT OR IGNORE " + query; //NON-NLS
361  default:
362  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());
363  }
364  }
365 
369  private enum STATEMENTS {
370 
371  GET_MAX_TIME("SELECT Max(time) AS max FROM tsk_events"), // NON-NLS
372  GET_MIN_TIME("SELECT Min(time) AS min FROM tsk_events"); // NON-NLS
373 
374  private final String sql;
375 
376  private STATEMENTS(String sql) {
377  this.sql = sql;
378  }
379 
380  String getSQL() {
381  return sql;
382  }
383  }
384 
395  public List<Long> getEventIDsForArtifact(BlackboardArtifact artifact) throws TskCoreException {
396  ArrayList<Long> eventIDs = new ArrayList<>();
397 
398  String query
399  = "SELECT event_id FROM tsk_events "
400  + " LEFT JOIN tsk_event_descriptions on ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id ) "
401  + " WHERE artifact_id = " + artifact.getArtifactID();
403  try (CaseDbConnection con = caseDB.getConnection();
404  Statement stmt = con.createStatement();
405  ResultSet results = stmt.executeQuery(query);) {
406  while (results.next()) {
407  eventIDs.add(results.getLong("event_id"));//NON-NLS
408  }
409  } catch (SQLException ex) {
410  throw new TskCoreException("Error executing getEventIDsForArtifact query.", ex); // NON-NLS
411  } finally {
413  }
414  return eventIDs;
415  }
416 
430  public Set<Long> getEventIDsForContent(Content content, boolean includeDerivedArtifacts) throws TskCoreException {
432  try (CaseDbConnection conn = caseDB.getConnection()) {
433  return getEventAndDescriptionIDs(conn, content.getId(), includeDerivedArtifacts).keySet();
434  } finally {
436  }
437  }
438 
456  private long addEventDescription(long dataSourceObjId, long fileObjId, Long artifactID,
457  String fullDescription, String medDescription, String shortDescription,
458  boolean hasHashHits, boolean tagged, CaseDbConnection connection) throws TskCoreException {
459  String insertDescriptionSql
460  = "INSERT INTO tsk_event_descriptions ( "
461  + "data_source_obj_id, content_obj_id, artifact_id, "
462  + " full_description, med_description, short_description, "
463  + " hash_hit, tagged "
464  + " ) VALUES ("
465  + dataSourceObjId + ","
466  + fileObjId + ","
467  + Objects.toString(artifactID, "NULL") + ","
468  + quotePreservingNull(fullDescription) + ","
469  + quotePreservingNull(medDescription) + ","
470  + quotePreservingNull(shortDescription) + ", "
471  + booleanToInt(hasHashHits) + ","
472  + booleanToInt(tagged)
473  + " )";
474 
476  try (Statement insertDescriptionStmt = connection.createStatement()) {
477  connection.executeUpdate(insertDescriptionStmt, insertDescriptionSql, PreparedStatement.RETURN_GENERATED_KEYS);
478  try (ResultSet generatedKeys = insertDescriptionStmt.getGeneratedKeys()) {
479  generatedKeys.next();
480  return generatedKeys.getLong(1);
481  }
482  } catch (SQLException ex) {
483  throw new TskCoreException("Failed to insert event description.", ex); // NON-NLS
484  } finally {
486  }
487  }
488 
489  Collection<TimelineEvent> addEventsForNewFile(AbstractFile file, CaseDbConnection connection) throws TskCoreException {
490  //gather time stamps into map
491  Map<TimelineEventType, Long> timeMap = ImmutableMap.of(TimelineEventType.FILE_CREATED, file.getCrtime(),
492  TimelineEventType.FILE_ACCESSED, file.getAtime(),
493  TimelineEventType.FILE_CHANGED, file.getCtime(),
494  TimelineEventType.FILE_MODIFIED, file.getMtime());
495 
496  /*
497  * If there are no legitimate ( greater than zero ) time stamps skip the
498  * rest of the event generation.
499  */
500  if (Collections.max(timeMap.values()) <= 0) {
501  return Collections.emptySet();
502  }
503 
504  String description = file.getParentPath() + file.getName();
505  long fileObjId = file.getId();
506  Set<TimelineEvent> events = new HashSet<>();
508  try {
509  long descriptionID = addEventDescription(file.getDataSourceObjectId(), fileObjId, null,
510  description, null, null, false, false, connection);
511 
512  for (Map.Entry<TimelineEventType, Long> timeEntry : timeMap.entrySet()) {
513  Long time = timeEntry.getValue();
514  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
515  TimelineEventType type = timeEntry.getKey();
516  long eventID = addEventWithExistingDescription(time, type, descriptionID, connection);
517 
518  /*
519  * Last two flags indicating hasTags and hasHashHits are
520  * both set to false with the assumption that this is not
521  * possible for a new file. See JIRA-5407
522  */
523  events.add(new TimelineEvent(eventID, descriptionID, fileObjId, null, time, type,
524  description, null, null, false, false));
525  } else {
526  if (time >= MAX_TIMESTAMP_TO_ADD) {
527  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()));
528  }
529  }
530  }
531 
532  } finally {
534  }
535  events.stream()
536  .map(TimelineEventAddedEvent::new)
537  .forEach(caseDB::fireTSKEvent);
538 
539  return events;
540  }
541 
555  Set<TimelineEvent> addArtifactEvents(BlackboardArtifact artifact) throws TskCoreException {
556  Set<TimelineEvent> newEvents = new HashSet<>();
557 
558  /*
559  * If the artifact is a TSK_TL_EVENT, use the TSK_TL_EVENT_TYPE
560  * attribute to determine its event type, but give it a generic
561  * description.
562  */
563  if (artifact.getArtifactTypeID() == TSK_TL_EVENT.getTypeID()) {
564  TimelineEventType eventType;//the type of the event to add.
565  BlackboardAttribute attribute = artifact.getAttribute(new BlackboardAttribute.Type(TSK_TL_EVENT_TYPE));
566  if (attribute == null) {
567  eventType = TimelineEventType.OTHER;
568  } else {
569  long eventTypeID = attribute.getValueLong();
570  eventType = eventTypeIDMap.getOrDefault(eventTypeID, TimelineEventType.OTHER);
571  }
572 
573  // @@@ This casting is risky if we change class hierarchy, but was expedient. Should move parsing to another class
574  addArtifactEvent(((TimelineEventArtifactTypeImpl) TimelineEventType.OTHER)::makeEventDescription, eventType, artifact)
575  .ifPresent(newEvents::add);
576  } else {
577  /*
578  * If there are any event types configured to make descriptions
579  * automatically, use those.
580  */
581  Set<TimelineEventArtifactTypeImpl> eventTypesForArtifact = eventTypeIDMap.values().stream()
582  .filter(TimelineEventArtifactTypeImpl.class::isInstance)
583  .map(TimelineEventArtifactTypeImpl.class::cast)
584  .filter(eventType -> eventType.getArtifactTypeID() == artifact.getArtifactTypeID())
585  .collect(Collectors.toSet());
586 
587  for (TimelineEventArtifactTypeImpl eventType : eventTypesForArtifact) {
588  addArtifactEvent(eventType::makeEventDescription, eventType, artifact)
589  .ifPresent(newEvents::add);
590  }
591  }
592  newEvents.stream()
593  .map(TimelineEventAddedEvent::new)
594  .forEach(caseDB::fireTSKEvent);
595  return newEvents;
596  }
597 
615  private Optional<TimelineEvent> addArtifactEvent(TSKCoreCheckedFunction<BlackboardArtifact, TimelineEventDescriptionWithTime> payloadExtractor,
616  TimelineEventType eventType, BlackboardArtifact artifact) throws TskCoreException {
617  TimelineEventDescriptionWithTime eventPayload = payloadExtractor.apply(artifact);
618  if (eventPayload == null) {
619  return Optional.empty();
620  }
621  long time = eventPayload.getTime();
622  // 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
623  if (time <= 0 || time >= MAX_TIMESTAMP_TO_ADD) {
624  if (time >= MAX_TIMESTAMP_TO_ADD) {
625  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()));
626  }
627  return Optional.empty();
628  }
629  String fullDescription = eventPayload.getDescription(TimelineLevelOfDetail.HIGH);
630  String medDescription = eventPayload.getDescription(TimelineLevelOfDetail.MEDIUM);
631  String shortDescription = eventPayload.getDescription(TimelineLevelOfDetail.LOW);
632  long artifactID = artifact.getArtifactID();
633  long fileObjId = artifact.getObjectID();
634  long dataSourceObjectID = artifact.getDataSourceObjectID();
635 
636  AbstractFile file = caseDB.getAbstractFileById(fileObjId);
637  boolean hasHashHits = false;
638  // file will be null if source was data source or some non-file
639  if (file != null) {
640  hasHashHits = isNotEmpty(file.getHashSetNames());
641  }
642  boolean tagged = isNotEmpty(caseDB.getBlackboardArtifactTagsByArtifact(artifact));
643 
644  TimelineEvent event;
646  try (CaseDbConnection connection = caseDB.getConnection();) {
647 
648  long descriptionID = addEventDescription(dataSourceObjectID, fileObjId, artifactID,
649  fullDescription, medDescription, shortDescription,
650  hasHashHits, tagged, connection);
651 
652  long eventID = addEventWithExistingDescription(time, eventType, descriptionID, connection);
653 
654  event = new TimelineEvent(eventID, dataSourceObjectID, fileObjId, artifactID,
655  time, eventType, fullDescription, medDescription, shortDescription,
656  hasHashHits, tagged);
657 
658  } finally {
660  }
661  return Optional.of(event);
662  }
663 
664  private long addEventWithExistingDescription(Long time, TimelineEventType type, long descriptionID, CaseDbConnection connection) throws TskCoreException {
665  String insertEventSql
666  = "INSERT INTO tsk_events ( event_type_id, event_description_id , time) "
667  + " VALUES (" + type.getTypeID() + ", " + descriptionID + ", " + time + ")";
668 
670  try (Statement insertRowStmt = connection.createStatement();) {
671  connection.executeUpdate(insertRowStmt, insertEventSql, PreparedStatement.RETURN_GENERATED_KEYS);
672 
673  try (ResultSet generatedKeys = insertRowStmt.getGeneratedKeys();) {
674  generatedKeys.next();
675  return generatedKeys.getLong(1);
676  }
677  } catch (SQLException ex) {
678  throw new TskCoreException("Failed to insert event for existing description.", ex); // NON-NLS
679  } finally {
681  }
682  }
683 
684  static private String quotePreservingNull(String value) {
685  return isNull(value) ? " NULL " : "'" + escapeSingleQuotes(value) + "'";//NON-NLS
686  }
687 
688  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, boolean includeArtifacts) throws TskCoreException {
689  return getEventAndDescriptionIDsHelper(conn, contentObjID, (includeArtifacts ? "" : " AND artifact_id IS NULL"));
690  }
691 
692  private Map<Long, Long> getEventAndDescriptionIDs(CaseDbConnection conn, long contentObjID, Long artifactID) throws TskCoreException {
693  return getEventAndDescriptionIDsHelper(conn, contentObjID, " AND artifact_id = " + artifactID);
694  }
695 
696  private Map<Long, Long> getEventAndDescriptionIDsHelper(CaseDbConnection con, long fileObjID, String artifactClause) throws TskCoreException {
697  //map from event_id to the event_description_id for that event.
698  Map<Long, Long> eventIDToDescriptionIDs = new HashMap<>();
699  String sql = "SELECT event_id, tsk_events.event_description_id"
700  + " FROM tsk_events "
701  + " LEFT JOIN tsk_event_descriptions ON ( tsk_events.event_description_id = tsk_event_descriptions.event_description_id )"
702  + " WHERE content_obj_id = " + fileObjID
703  + artifactClause;
704  try (Statement selectStmt = con.createStatement(); ResultSet executeQuery = selectStmt.executeQuery(sql);) {
705  while (executeQuery.next()) {
706  eventIDToDescriptionIDs.put(executeQuery.getLong("event_id"), executeQuery.getLong("event_description_id")); //NON-NLS
707  }
708  } catch (SQLException ex) {
709  throw new TskCoreException("Error getting event description ids for object id = " + fileObjID, ex);
710  }
711  return eventIDToDescriptionIDs;
712  }
713 
730  @Beta
731  public Set<Long> updateEventsForContentTagAdded(Content content) throws TskCoreException {
733  try (CaseDbConnection conn = caseDB.getConnection()) {
734  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
735  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
736  return eventIDs.keySet();
737  } finally {
739  }
740  }
741 
759  @Beta
760  public Set<Long> updateEventsForContentTagDeleted(Content content) throws TskCoreException {
762  try (CaseDbConnection conn = caseDB.getConnection()) {
763  if (caseDB.getContentTagsByContent(content).isEmpty()) {
764  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, content.getId(), false);
765  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
766  return eventIDs.keySet();
767  } else {
768  return Collections.emptySet();
769  }
770  } finally {
772  }
773  }
774 
788  try (CaseDbConnection conn = caseDB.getConnection()) {
789  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
790  updateEventSourceTaggedFlag(conn, eventIDs.values(), 1);
791  return eventIDs.keySet();
792  } finally {
794  }
795  }
796 
811  try (CaseDbConnection conn = caseDB.getConnection()) {
812  if (caseDB.getBlackboardArtifactTagsByArtifact(artifact).isEmpty()) {
813  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(conn, artifact.getObjectID(), artifact.getArtifactID());
814  updateEventSourceTaggedFlag(conn, eventIDs.values(), 0);
815  return eventIDs.keySet();
816  } else {
817  return Collections.emptySet();
818  }
819  } finally {
821  }
822  }
823 
824  private void updateEventSourceTaggedFlag(CaseDbConnection conn, Collection<Long> eventDescriptionIDs, int flagValue) throws TskCoreException {
825  if (eventDescriptionIDs.isEmpty()) {
826  return;
827  }
828 
829  String sql = "UPDATE tsk_event_descriptions SET tagged = " + flagValue + " WHERE event_description_id IN (" + buildCSVString(eventDescriptionIDs) + ")"; //NON-NLS
830  try (Statement updateStatement = conn.createStatement()) {
831  updateStatement.executeUpdate(sql);
832  } catch (SQLException ex) {
833  throw new TskCoreException("Error marking content events tagged: " + sql, ex);//NON-NLS
834  }
835  }
836 
851  public Set<Long> updateEventsForHashSetHit(Content content) throws TskCoreException {
853  try (CaseDbConnection con = caseDB.getConnection(); Statement updateStatement = con.createStatement();) {
854  Map<Long, Long> eventIDs = getEventAndDescriptionIDs(con, content.getId(), true);
855  if (! eventIDs.isEmpty()) {
856  String sql = "UPDATE tsk_event_descriptions SET hash_hit = 1" + " WHERE event_description_id IN (" + buildCSVString(eventIDs.values()) + ")"; //NON-NLS
857  try {
858  updateStatement.executeUpdate(sql); //NON-NLS
859  return eventIDs.keySet();
860  } catch (SQLException ex) {
861  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
862  }
863  } else {
864  return eventIDs.keySet();
865  }
866  } catch (SQLException ex) {
867  throw new TskCoreException("Error setting hash_hit of events.", ex);//NON-NLS
868  } finally {
870  }
871  }
872 
873  void rollBackTransaction(SleuthkitCase.CaseDbTransaction trans) throws TskCoreException {
874  trans.rollback();
875  }
876 
896  public Map<TimelineEventType, Long> countEventsByType(Long startTime, Long endTime, TimelineFilter.RootFilter filter, TimelineEventType.HierarchyLevel typeHierachyLevel) throws TskCoreException {
897  long adjustedEndTime = Objects.equals(startTime, endTime) ? endTime + 1 : endTime;
898  //do we want the base or subtype column of the databse
899  String typeColumn = typeColumnHelper(TimelineEventType.HierarchyLevel.EVENT.equals(typeHierachyLevel));
900 
901  String queryString = "SELECT count(DISTINCT tsk_events.event_id) AS count, " + typeColumn//NON-NLS
902  + " FROM " + getAugmentedEventsTablesSQL(filter)//NON-NLS
903  + " WHERE time >= " + startTime + " AND time < " + adjustedEndTime + " AND " + getSQLWhere(filter) // NON-NLS
904  + " GROUP BY " + typeColumn; // NON-NLS
905 
907  try (CaseDbConnection con = caseDB.getConnection();
908  Statement stmt = con.createStatement();
909  ResultSet results = stmt.executeQuery(queryString);) {
910  Map<TimelineEventType, Long> typeMap = new HashMap<>();
911  while (results.next()) {
912  int eventTypeID = results.getInt(typeColumn);
913  TimelineEventType eventType = getEventType(eventTypeID)
914  .orElseThrow(() -> newEventTypeMappingException(eventTypeID));//NON-NLS
915 
916  typeMap.put(eventType, results.getLong("count")); // NON-NLS
917  }
918  return typeMap;
919  } catch (SQLException ex) {
920  throw new TskCoreException("Error getting count of events from db: " + queryString, ex); // NON-NLS
921  } finally {
923  }
924  }
925 
926  private static TskCoreException newEventTypeMappingException(int eventTypeID) {
927  return new TskCoreException("Error mapping event type id " + eventTypeID + " to EventType.");//NON-NLS
928  }
929 
943  static private String getAugmentedEventsTablesSQL(TimelineFilter.RootFilter filter) {
944  TimelineFilter.FileTypesFilter fileTypesFitler = filter.getFileTypesFilter();
945  boolean needsMimeTypes = fileTypesFitler != null && fileTypesFitler.hasSubFilters();
946 
947  return getAugmentedEventsTablesSQL(needsMimeTypes);
948  }
949 
964  static private String getAugmentedEventsTablesSQL(boolean needMimeTypes) {
965  /*
966  * Regarding the timeline event tables schema, note that several columns
967  * in the tsk_event_descriptions table seem, at first glance, to be
968  * attributes of events rather than their descriptions and would appear
969  * to belong in tsk_events table instead. The rationale for putting the
970  * data source object ID, content object ID, artifact ID and the flags
971  * indicating whether or not the event source has a hash set hit or is
972  * tagged were motivated by the fact that these attributes are identical
973  * for each event in a set of file system file MAC time events. The
974  * decision was made to avoid duplication and save space by placing this
975  * data in the tsk_event-descriptions table.
976  */
977  return "( SELECT event_id, time, tsk_event_descriptions.data_source_obj_id, content_obj_id, artifact_id, "
978  + " full_description, med_description, short_description, tsk_events.event_type_id, super_type_id,"
979  + " hash_hit, tagged "
980  + (needMimeTypes ? ", mime_type" : "")
981  + " FROM tsk_events "
982  + " JOIN tsk_event_descriptions ON ( tsk_event_descriptions.event_description_id = tsk_events.event_description_id)"
983  + " JOIN tsk_event_types ON (tsk_events.event_type_id = tsk_event_types.event_type_id ) "
984  + (needMimeTypes ? " LEFT OUTER JOIN tsk_files "
985  + " ON (tsk_event_descriptions.content_obj_id = tsk_files.obj_id)"
986  : "")
987  + ") AS tsk_events";
988  }
989 
997  private static int booleanToInt(boolean value) {
998  return value ? 1 : 0;
999  }
1000 
1001  private static boolean intToBoolean(int value) {
1002  return value != 0;
1003  }
1004 
1017  public List<TimelineEvent> getEvents(Interval timeRange, TimelineFilter.RootFilter filter) throws TskCoreException {
1018  List<TimelineEvent> events = new ArrayList<>();
1019 
1020  Long startTime = timeRange.getStartMillis() / 1000;
1021  Long endTime = timeRange.getEndMillis() / 1000;
1022 
1023  if (Objects.equals(startTime, endTime)) {
1024  endTime++; //make sure end is at least 1 millisecond after start
1025  }
1026 
1027  if (filter == null) {
1028  return events;
1029  }
1030 
1031  if (endTime < startTime) {
1032  return events;
1033  }
1034 
1035  //build dynamic parts of query
1036  String querySql = "SELECT time, content_obj_id, data_source_obj_id, artifact_id, " // NON-NLS
1037  + " event_id, " //NON-NLS
1038  + " hash_hit, " //NON-NLS
1039  + " tagged, " //NON-NLS
1040  + " event_type_id, super_type_id, "
1041  + " full_description, med_description, short_description " // NON-NLS
1042  + " FROM " + getAugmentedEventsTablesSQL(filter) // NON-NLS
1043  + " WHERE time >= " + startTime + " AND time < " + endTime + " AND " + getSQLWhere(filter) // NON-NLS
1044  + " ORDER BY time"; // NON-NLS
1045 
1047  try (CaseDbConnection con = caseDB.getConnection();
1048  Statement stmt = con.createStatement();
1049  ResultSet resultSet = stmt.executeQuery(querySql);) {
1050 
1051  while (resultSet.next()) {
1052  int eventTypeID = resultSet.getInt("event_type_id");
1053  TimelineEventType eventType = getEventType(eventTypeID).orElseThrow(()
1054  -> new TskCoreException("Error mapping event type id " + eventTypeID + "to EventType."));//NON-NLS
1055 
1056  TimelineEvent event = new TimelineEvent(
1057  resultSet.getLong("event_id"), // NON-NLS
1058  resultSet.getLong("data_source_obj_id"), // NON-NLS
1059  resultSet.getLong("content_obj_id"), // NON-NLS
1060  resultSet.getLong("artifact_id"), // NON-NLS
1061  resultSet.getLong("time"), // NON-NLS
1062  eventType,
1063  resultSet.getString("full_description"), // NON-NLS
1064  resultSet.getString("med_description"), // NON-NLS
1065  resultSet.getString("short_description"), // NON-NLS
1066  resultSet.getInt("hash_hit") != 0, //NON-NLS
1067  resultSet.getInt("tagged") != 0);
1068 
1069  events.add(event);
1070  }
1071 
1072  } catch (SQLException ex) {
1073  throw new TskCoreException("Error getting events from db: " + querySql, ex); // NON-NLS
1074  } finally {
1076  }
1077 
1078  return events;
1079  }
1080 
1088  private static String typeColumnHelper(final boolean useSubTypes) {
1089  return useSubTypes ? "event_type_id" : "super_type_id"; //NON-NLS
1090  }
1091 
1100  String getSQLWhere(TimelineFilter.RootFilter filter) {
1101 
1102  String result;
1103  if (filter == null) {
1104  return getTrueLiteral();
1105  } else {
1106  result = filter.getSQLWhere(this);
1107  }
1108 
1109  return result;
1110  }
1111 
1112  private String getTrueLiteral() {
1113  switch (caseDB.getDatabaseType()) {
1114  case POSTGRESQL:
1115  return "TRUE";//NON-NLS
1116  case SQLITE:
1117  return "1";//NON-NLS
1118  default:
1119  throw new UnsupportedOperationException("Unsupported DB type: " + caseDB.getDatabaseType().name());//NON-NLS
1120 
1121  }
1122  }
1123 
1128  final static public class TimelineEventAddedEvent {
1129 
1130  private final TimelineEvent addedEvent;
1131 
1133  return addedEvent;
1134  }
1135 
1137  this.addedEvent = event;
1138  }
1139  }
1140 
1148  @FunctionalInterface
1149  private interface TSKCoreCheckedFunction<I, O> {
1150 
1151  O apply(I input) throws TskCoreException;
1152  }
1153 }
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-2020 Brian Carrier. (carrier -at- sleuthkit -dot- org)
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.