Autopsy  4.7.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
TermsComponentQuery.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2011-2018 Basis Technology Corp.
5  * Contact: carrier <at> sleuthkit <dot> org
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19 package org.sleuthkit.autopsy.keywordsearch;
20 
21 import com.google.common.base.CharMatcher;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.logging.Level;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.solr.client.solrj.SolrQuery;
34 import org.apache.solr.client.solrj.response.TermsResponse.Term;
35 import org.openide.util.Exceptions;
41 import org.sleuthkit.datamodel.AbstractFile;
42 import org.sleuthkit.datamodel.Account;
43 import org.sleuthkit.datamodel.AccountFileInstance;
44 import org.sleuthkit.datamodel.BlackboardArtifact;
45 import org.sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
46 import org.sleuthkit.datamodel.BlackboardAttribute;
47 import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
48 import org.sleuthkit.datamodel.Content;
49 import org.sleuthkit.datamodel.TskCoreException;
50 import org.sleuthkit.datamodel.TskData;
51 
58 final class TermsComponentQuery implements KeywordSearchQuery {
59 
60  private static final Logger LOGGER = Logger.getLogger(TermsComponentQuery.class.getName());
61  private static final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
62  private static final String SEARCH_HANDLER = "/terms"; //NON-NLS
63  private static final String SEARCH_FIELD = Server.Schema.TEXT.toString();
64  private static final int TERMS_SEARCH_TIMEOUT = 90 * 1000; // Milliseconds
65  private static final String CASE_INSENSITIVE = "case_insensitive"; //NON-NLS
66  private static final boolean DEBUG_FLAG = Version.Type.DEVELOPMENT.equals(Version.getBuildType());
67  private static final int MAX_TERMS_QUERY_RESULTS = 20000;
68 
69  private final KeywordList keywordList;
70  private final Keyword originalKeyword;
71  private final List<KeywordQueryFilter> filters = new ArrayList<>(); // THIS APPEARS TO BE UNUSED
72 
73  private String searchTerm;
74  private boolean searchTermIsEscaped;
75 
76  /*
77  * The following fields are part of the initial implementation of credit
78  * card account search and should be factored into another class when time
79  * permits.
80  */
86  static final Pattern CREDIT_CARD_NUM_PATTERN
87  = Pattern.compile("(?<ccn>[2-6]([ -]?[0-9]){11,18})");
88  static final Pattern CREDIT_CARD_TRACK1_PATTERN = Pattern.compile(
89  /*
90  * Track 1 is alphanumeric.
91  *
92  * This regex matches 12-19 digit ccns embeded in a track 1 formated
93  * string. This regex matches (and extracts groups) even if the
94  * entire track is not present as long as the part that is conforms
95  * to the track format.
96  */
97  "(?:" //begin nested optinal group //NON-NLS
98  + "%?" //optional start sentinal: % //NON-NLS
99  + "B)?" //format code //NON-NLS
100  + "(?<accountNumber>[2-6]([ -]?[0-9]){11,18})" //12-19 digits, with possible single spaces or dashes in between. first digit is 2,3,4,5, or 6 //NON-NLS
101  + "\\^" //separator //NON-NLS
102  + "(?<name>[^^]{2,26})" //2-26 charachter name, not containing ^ //NON-NLS
103  + "(?:\\^" //separator //NON-NLS
104  + "(?:(?:\\^|(?<expiration>\\d{4}))" //separator or 4 digit expiration YYMM //NON-NLS
105  + "(?:(?:\\^|(?<serviceCode>\\d{3}))"//separator or 3 digit service code //NON-NLS
106  + "(?:(?<discretionary>[^?]*)" // discretionary data not containing separator //NON-NLS
107  + "(?:\\?" // end sentinal: ? //NON-NLS
108  + "(?<LRC>.)" //longitudinal redundancy check //NON-NLS
109  + "?)?)?)?)?)?");//close nested optional groups //NON-NLS
110  static final Pattern CREDIT_CARD_TRACK2_PATTERN = Pattern.compile(
111  /*
112  * Track 2 is numeric plus six punctuation symbolls :;<=>?
113  *
114  * This regex matches 12-19 digit ccns embeded in a track 2 formated
115  * string. This regex matches (and extracts groups) even if the
116  * entire track is not present as long as the part that is conforms
117  * to the track format.
118  *
119  */
120  "[:;<=>?]?" //(optional)start sentinel //NON-NLS
121  + "(?<accountNumber>[2-6]([ -]?[0-9]){11,18})" //12-19 digits, with possible single spaces or dashes in between. first digit is 2,3,4,5, or 6 //NON-NLS
122  + "(?:[:;<=>?]" //separator //NON-NLS
123  + "(?:(?<expiration>\\d{4})" //4 digit expiration date YYMM //NON-NLS
124  + "(?:(?<serviceCode>\\d{3})" //3 digit service code //NON-NLS
125  + "(?:(?<discretionary>[^:;<=>?]*)" //discretionary data, not containing punctuation marks //NON-NLS
126  + "(?:[:;<=>?]" //end sentinel //NON-NLS
127  + "(?<LRC>.)" //longitudinal redundancy check //NON-NLS
128  + "?)?)?)?)?)?"); //close nested optional groups //NON-NLS
129  static final BlackboardAttribute.Type KEYWORD_SEARCH_DOCUMENT_ID = new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_DOCUMENT_ID);
130 
143  // TODO: Why is both the list and the keyword added to the state of this
144  // object?
145  // TODO: Why is the search term not escaped and given substring wildcards,
146  // if needed, here in the constructor?
147  TermsComponentQuery(KeywordList keywordList, Keyword keyword) {
148  this.keywordList = keywordList;
149  this.originalKeyword = keyword;
150  this.searchTerm = keyword.getSearchTerm();
151  }
152 
159  @Override
160  public KeywordList getKeywordList() {
161  return keywordList;
162  }
163 
170  @Override
171  public String getQueryString() {
172  return originalKeyword.getSearchTerm();
173  }
174 
182  @Override
183  public boolean isLiteral() {
184  return false;
185  }
186 
191  @Override
192  public void setSubstringQuery() {
193  searchTerm = ".*" + searchTerm + ".*";
194  }
195 
199  @Override
200  public void escape() {
201  searchTerm = Pattern.quote(originalKeyword.getSearchTerm());
202  searchTermIsEscaped = true;
203  }
204 
210  @Override
211  public boolean isEscaped() {
212  return searchTermIsEscaped;
213  }
214 
221  @Override
222  public String getEscapedQueryString() {
223  return this.searchTerm;
224  }
225 
231  @Override
232  public boolean validate() {
233  if (searchTerm.isEmpty()) {
234  return false;
235  }
236  try {
237  Pattern.compile(searchTerm);
238  return true;
239  } catch (IllegalArgumentException ex) {
240  return false;
241  }
242  }
243 
250  @Override
251  public void setField(String field) {
252  }
253 
259  // TODO: Document this better.
260  @Override
261  public void addFilter(KeywordQueryFilter filter) {
262  this.filters.add(filter);
263  }
264 
275  @Override
276  public QueryResults performQuery() throws KeywordSearchModuleException, NoOpenCoreException {
277  /*
278  * Do a query using the Solr terms component to find any terms in the
279  * index that match the regex.
280  */
281  final SolrQuery termsQuery = new SolrQuery();
282  termsQuery.setRequestHandler(SEARCH_HANDLER);
283  termsQuery.setTerms(true);
284  termsQuery.setTermsRegexFlag(CASE_INSENSITIVE);
285  termsQuery.setTermsRegex(searchTerm);
286  termsQuery.addTermsField(SEARCH_FIELD);
287  termsQuery.setTimeAllowed(TERMS_SEARCH_TIMEOUT);
288  termsQuery.setShowDebugInfo(DEBUG_FLAG);
289  termsQuery.setTermsLimit(MAX_TERMS_QUERY_RESULTS);
290  List<Term> terms = KeywordSearch.getServer().queryTerms(termsQuery).getTerms(SEARCH_FIELD);
291  /*
292  * Do a term query for each term that matched the regex.
293  */
294  QueryResults results = new QueryResults(this);
295  for (Term term : terms) {
296  /*
297  * If searching for credit card account numbers, do a Luhn check on
298  * the term and discard it if it does not pass.
299  */
300  if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
301  Matcher matcher = CREDIT_CARD_NUM_PATTERN.matcher(term.getTerm());
302  if (false == matcher.find()
303  || false == CreditCardValidator.isValidCCN(matcher.group("ccn"))) {
304  continue;
305  }
306  }
307 
308  /*
309  * Do an ordinary query with the escaped term and convert the query
310  * results into a single list of keyword hits without duplicates.
311  *
312  * Note that the filters field appears to be unused. There is an old
313  * comment here, what does it mean? "Note: we can't set filter query
314  * on terms query but setting filter query on fileResults query will
315  * yield the same result." The filter is NOT being added to the term
316  * query.
317  */
318  String escapedTerm = KeywordSearchUtil.escapeLuceneQuery(term.getTerm());
319  LuceneQuery termQuery = new LuceneQuery(keywordList, new Keyword(escapedTerm, true, true));
320  filters.forEach(termQuery::addFilter); // This appears to be unused
321  QueryResults termQueryResult = termQuery.performQuery();
322  Set<KeywordHit> termHits = new HashSet<>();
323  for (Keyword word : termQueryResult.getKeywords()) {
324  termHits.addAll(termQueryResult.getResults(word));
325  }
326  results.addResult(new Keyword(term.getTerm(), false, true, originalKeyword.getListName(), originalKeyword.getOriginalTerm()), new ArrayList<>(termHits));
327  }
328  return results;
329  }
330 
347  @Override
348  public BlackboardArtifact postKeywordHitToBlackboard(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
349 
350  /*
351  * CCN hits are handled specially
352  */
353  if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
354  createCCNAccount(content, hit, snippet, listName);
355  return null;
356  }
357 
358  /*
359  * Create a "plain vanilla" keyword hit artifact with keyword and regex
360  * attributes,
361  */
362  BlackboardArtifact newArtifact;
363  Collection<BlackboardAttribute> attributes = new ArrayList<>();
364 
365  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, foundKeyword.getSearchTerm()));
366  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP, MODULE_NAME, originalKeyword.getSearchTerm()));
367 
368  try {
369  newArtifact = content.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
370 
371  } catch (TskCoreException ex) {
372  LOGGER.log(Level.SEVERE, "Error adding artifact for keyword hit to blackboard", ex); //NON-NLS
373  return null;
374  }
375 
376  if (StringUtils.isNotBlank(listName)) {
377  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
378  }
379  if (snippet != null) {
380  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
381  }
382 
383  hit.getArtifactID().ifPresent(
384  artifactID -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
385  );
386 
387  // TermsComponentQuery is now being used exclusively for substring searches.
388  attributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.SUBSTRING.ordinal()));
389 
390  try {
391  newArtifact.addAttributes(attributes);
392  return newArtifact;
393  } catch (TskCoreException e) {
394  LOGGER.log(Level.SEVERE, "Error adding bb attributes for terms search artifact", e); //NON-NLS
395  return null;
396  }
397  }
398 
399  private void createCCNAccount(Content content, KeywordHit hit, String snippet, String listName) {
400 
401  if (originalKeyword.getArtifactAttributeType() != ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
402  LOGGER.log(Level.SEVERE, "Keyword hit is not a credit card number"); //NON-NLS
403  return;
404  }
405 
406  /*
407  * Create a credit card account with attributes parsed from from the
408  * snippet for the hit and looked up based on the parsed bank
409  * identifcation number.
410  */
411  Collection<BlackboardAttribute> attributes = new ArrayList<>();
412 
413  Map<BlackboardAttribute.Type, BlackboardAttribute> parsedTrackAttributeMap = new HashMap<>();
414  Matcher matcher = CREDIT_CARD_TRACK1_PATTERN.matcher(hit.getSnippet());
415  if (matcher.find()) {
416  parseTrack1Data(parsedTrackAttributeMap, matcher);
417  }
418  matcher = CREDIT_CARD_TRACK2_PATTERN.matcher(hit.getSnippet());
419  if (matcher.find()) {
420  parseTrack2Data(parsedTrackAttributeMap, matcher);
421  }
422  final BlackboardAttribute ccnAttribute = parsedTrackAttributeMap.get(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_CARD_NUMBER));
423  if (ccnAttribute == null || StringUtils.isBlank(ccnAttribute.getValueString())) {
424  if (hit.isArtifactHit()) {
425  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for artifact keyword hit: term = %s, snippet = '%s', artifact id = %d", searchTerm, hit.getSnippet(), hit.getArtifactID().get())); //NON-NLS
426  } else {
427  long contentId = 0;
428  try {
429  contentId = hit.getContentID();
430  } catch (TskCoreException ex) {
431  LOGGER.log(Level.SEVERE, String.format("Failed to content id from keyword hit: term = %s, snippet = '%s'", searchTerm, hit.getSnippet()), ex); //NON-NLS
432  }
433  if (contentId > 0) {
434  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for content keyword hit: term = %s, snippet = '%s', object id = %d", searchTerm, hit.getSnippet(), contentId)); //NON-NLS
435  } else {
436  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for content keyword hit: term = %s, snippet = '%s'", searchTerm, hit.getSnippet())); //NON-NLS
437  }
438  }
439  return;
440  }
441  attributes.addAll(parsedTrackAttributeMap.values());
442 
443  /*
444  * Look up the bank name, scheme, etc. attributes for the bank
445  * indentification number (BIN).
446  */
447  final int bin = Integer.parseInt(ccnAttribute.getValueString().substring(0, 8));
448  CreditCards.BankIdentificationNumber binInfo = CreditCards.getBINInfo(bin);
449  if (binInfo != null) {
450  binInfo.getScheme().ifPresent(scheme
451  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_SCHEME, MODULE_NAME, scheme)));
452  binInfo.getCardType().ifPresent(cardType
453  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_TYPE, MODULE_NAME, cardType)));
454  binInfo.getBrand().ifPresent(brand
455  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BRAND_NAME, MODULE_NAME, brand)));
456  binInfo.getBankName().ifPresent(bankName
457  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BANK_NAME, MODULE_NAME, bankName)));
458  binInfo.getBankPhoneNumber().ifPresent(phoneNumber
459  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER, MODULE_NAME, phoneNumber)));
460  binInfo.getBankURL().ifPresent(url
461  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL, MODULE_NAME, url)));
462  binInfo.getCountry().ifPresent(country
463  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COUNTRY, MODULE_NAME, country)));
464  binInfo.getBankCity().ifPresent(city
465  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CITY, MODULE_NAME, city)));
466  }
467 
468  /*
469  * If the hit is from unused or unallocated space, record the Solr
470  * document id to support showing just the chunk that contained the hit.
471  */
472  if (content instanceof AbstractFile) {
473  AbstractFile file = (AbstractFile) content;
474  if (file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS
475  || file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) {
476  attributes.add(new BlackboardAttribute(KEYWORD_SEARCH_DOCUMENT_ID, MODULE_NAME, hit.getSolrDocumentId()));
477  }
478  }
479 
480  if (StringUtils.isNotBlank(listName)) {
481  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
482  }
483  if (snippet != null) {
484  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
485  }
486 
487  hit.getArtifactID().ifPresent(
488  artifactID -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
489  );
490 
491  // TermsComponentQuery is now being used exclusively for substring searches.
492  attributes.add(new BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.SUBSTRING.ordinal()));
493 
494  /*
495  * Create an account.
496  */
497  try {
498  AccountFileInstance ccAccountInstance = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.CREDIT_CARD, ccnAttribute.getValueString(), MODULE_NAME, content);
499  ccAccountInstance.addAttributes(attributes);
500  } catch (TskCoreException | NoCurrentCaseException ex) {
501  LOGGER.log(Level.SEVERE, "Error creating CCN account instance", ex); //NON-NLS
502  }
503 
504  }
505 
514  static private void parseTrack2Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributesMap, Matcher matcher) {
515  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_NUMBER, "accountNumber", matcher);
516  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_EXPIRATION, "expiration", matcher);
517  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_SERVICE_CODE, "serviceCode", matcher);
518  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_DISCRETIONARY, "discretionary", matcher);
519  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_LRC, "LRC", matcher);
520  }
521 
531  static private void parseTrack1Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, Matcher matcher) {
532  parseTrack2Data(attributeMap, matcher);
533  addAttributeIfNotAlreadyCaptured(attributeMap, ATTRIBUTE_TYPE.TSK_NAME_PERSON, "name", matcher);
534  }
535 
547  static private void addAttributeIfNotAlreadyCaptured(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, ATTRIBUTE_TYPE attrType, String groupName, Matcher matcher) {
548  BlackboardAttribute.Type type = new BlackboardAttribute.Type(attrType);
549  attributeMap.computeIfAbsent(type, (BlackboardAttribute.Type t) -> {
550  String value = matcher.group(groupName);
551  if (attrType.equals(ATTRIBUTE_TYPE.TSK_CARD_NUMBER)) {
552  value = CharMatcher.anyOf(" -").removeFrom(value);
553  }
554  if (StringUtils.isNotBlank(value)) {
555  return new BlackboardAttribute(attrType, MODULE_NAME, value);
556  }
557  return null;
558  });
559  }
560 
561 }

Copyright © 2012-2016 Basis Technology. Generated on: Mon Jun 18 2018
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.