Autopsy  4.18.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
RegexQuery.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.List;
26 import java.util.Map;
27 import java.util.logging.Level;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import org.apache.commons.lang3.StringUtils;
31 import org.apache.commons.lang3.math.NumberUtils;
32 import org.apache.commons.validator.routines.DomainValidator;
33 import org.apache.solr.client.solrj.SolrQuery;
34 import org.apache.solr.client.solrj.SolrQuery.SortClause;
35 import org.apache.solr.client.solrj.SolrRequest;
36 import org.apache.solr.client.solrj.response.QueryResponse;
37 import org.apache.solr.common.SolrDocument;
38 import org.apache.solr.common.SolrDocumentList;
39 import org.apache.solr.common.params.CursorMarkParams;
40 import org.openide.util.NbBundle;
46 import static org.sleuthkit.autopsy.keywordsearch.KeywordSearchSettings.MODULE_NAME;
47 import org.sleuthkit.datamodel.AbstractFile;
48 import org.sleuthkit.datamodel.Account;
49 import org.sleuthkit.datamodel.AccountFileInstance;
50 import org.sleuthkit.datamodel.BlackboardArtifact;
51 import org.sleuthkit.datamodel.BlackboardAttribute;
52 import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
53 import org.sleuthkit.datamodel.Content;
54 import org.sleuthkit.datamodel.Score;
55 import org.sleuthkit.datamodel.TskCoreException;
56 import org.sleuthkit.datamodel.TskData;
57 
72 final class RegexQuery implements KeywordSearchQuery {
73 
74  public static final Logger LOGGER = Logger.getLogger(RegexQuery.class.getName());
75 
86  private static final CharSequence[] UNSUPPORTED_CHARS = {"\\d", "\\D", "\\w", "\\W", "\\s", "\\S", "\\n",
87  "\\t", "\\r", "\\f", "\\a", "\\e", "\\v", "\\V", "\\h", "\\H", "\\p"}; //NON-NLS
88 
89  private static final int MAX_RESULTS_PER_CURSOR_MARK = 512;
90  private static final int MIN_EMAIL_ADDR_LENGTH = 8;
91  private static final String SNIPPET_DELIMITER = String.valueOf(Character.toChars(171));
92 
93  /*
94  * The following fields are part of the initial implementation of credit
95  * card account search and should be factored into another class when time
96  * permits.
97  */
103  static final Pattern CREDIT_CARD_NUM_PATTERN
104  = Pattern.compile("(?<ccn>[2-6]([ -]?[0-9]){11,18})");
105  static final Pattern CREDIT_CARD_TRACK1_PATTERN = Pattern.compile(
106  /*
107  * Track 1 is alphanumeric.
108  *
109  * This regex matches 12-19 digit ccns embeded in a track 1 formated
110  * string. This regex matches (and extracts groups) even if the
111  * entire track is not present as long as the part that is conforms
112  * to the track format.
113  */
114  "(?:" //begin nested optinal group //NON-NLS
115  + "%?" //optional start sentinal: % //NON-NLS
116  + "B)?" //format code //NON-NLS
117  + "(?<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
118  + "\\^" //separator //NON-NLS
119  + "(?<name>[^^]{2,26})" //2-26 charachter name, not containing ^ //NON-NLS
120  + "(?:\\^" //separator //NON-NLS
121  + "(?:(?:\\^|(?<expiration>\\d{4}))" //separator or 4 digit expiration YYMM //NON-NLS
122  + "(?:(?:\\^|(?<serviceCode>\\d{3}))"//separator or 3 digit service code //NON-NLS
123  + "(?:(?<discretionary>[^?]*)" // discretionary data not containing separator //NON-NLS
124  + "(?:\\?" // end sentinal: ? //NON-NLS
125  + "(?<LRC>.)" //longitudinal redundancy check //NON-NLS
126  + "?)?)?)?)?)?");//close nested optional groups //NON-NLS
127  static final Pattern CREDIT_CARD_TRACK2_PATTERN = Pattern.compile(
128  /*
129  * Track 2 is numeric plus six punctuation symbolls :;<=>?
130  *
131  * This regex matches 12-19 digit ccns embeded in a track 2 formated
132  * string. This regex matches (and extracts groups) even if the
133  * entire track is not present as long as the part that is conforms
134  * to the track format.
135  *
136  */
137  "[:;<=>?]?" //(optional)start sentinel //NON-NLS
138  + "(?<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
139  + "(?:[:;<=>?]" //separator //NON-NLS
140  + "(?:(?<expiration>\\d{4})" //4 digit expiration date YYMM //NON-NLS
141  + "(?:(?<serviceCode>\\d{3})" //3 digit service code //NON-NLS
142  + "(?:(?<discretionary>[^:;<=>?]*)" //discretionary data, not containing punctuation marks //NON-NLS
143  + "(?:[:;<=>?]" //end sentinel //NON-NLS
144  + "(?<LRC>.)" //longitudinal redundancy check //NON-NLS
145  + "?)?)?)?)?)?"); //close nested optional groups //NON-NLS
146  static final BlackboardAttribute.Type KEYWORD_SEARCH_DOCUMENT_ID = new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_DOCUMENT_ID);
147 
148  private final List<KeywordQueryFilter> filters = new ArrayList<>();
149  private final KeywordList keywordList;
150  private final Keyword originalKeyword; // The regular expression originalKeyword used to perform the search.
151  private final String keywordString;
152  private final boolean queryStringContainsWildcardPrefix;
153  private final boolean queryStringContainsWildcardSuffix;
154 
155  private boolean escaped;
156  private String escapedQuery;
157  private String field = Server.Schema.CONTENT_STR.toString();
158 
165  RegexQuery(KeywordList keywordList, Keyword keyword) {
166  this.keywordList = keywordList;
167  this.originalKeyword = keyword;
168  this.keywordString = keyword.getSearchTerm();
169 
170  this.queryStringContainsWildcardPrefix = this.keywordString.startsWith(".*");
171  this.queryStringContainsWildcardSuffix = this.keywordString.endsWith(".*");
172  }
173 
174  @Override
175  public KeywordList getKeywordList() {
176  return keywordList;
177  }
178 
179  @Override
180  public boolean validate() {
181  if (keywordString.isEmpty()) {
182  return false;
183  }
184  try {
185  // First we perform regular Java regex validation to catch errors.
186  Pattern.compile(keywordString, Pattern.UNICODE_CHARACTER_CLASS);
187 
188  // Then we check for the set of Java predefined and POSIX character
189  // classes. While they are valid Lucene regex characters, they will
190  // behave differently than users may expect. E.g. the regex \d\d\d
191  // will not find 3 digits but will instead find a sequence of 3 'd's.
192  for (CharSequence c : UNSUPPORTED_CHARS) {
193  if (keywordString.contains(c)) {
194  return false;
195  }
196  }
197  return true;
198  } catch (IllegalArgumentException ex) {
199  return false;
200  }
201  }
202 
203  @Override
204  public QueryResults performQuery() throws NoOpenCoreException {
205 
206  final Server solrServer = KeywordSearch.getServer();
207  SolrQuery solrQuery = new SolrQuery();
208 
209  /*
210  * The provided regular expression may include wildcards at the
211  * beginning and/or end. These wildcards are used to indicate that the
212  * user wants to find hits for the regex that are embedded within other
213  * characters. For example, if we are given .*127.0.0.1.* as a regular
214  * expression, this will produce hits for: (a) " 127.0.0.1 " as a
215  * standalone token (surrounded by whitespace). (b) "abc127.0.0.1def"
216  * where the IP address is surrounded by other characters.
217  *
218  * If we are given this type of regex, we do not need to add our own
219  * wildcards to anchor the query. Otherwise, we need to add wildcard
220  * anchors because Lucene string regex searches default to using ^ and $
221  * to match the entire string.
222  */
223  // We construct the query by surrounding it with slashes (to indicate it is
224  // a regular expression search) and .* as anchors (if the query doesn't
225  // already have them). We do not add .* if there is a boundary character.
226  boolean skipWildcardPrefix = queryStringContainsWildcardPrefix || getQueryString().startsWith("^");
227  boolean skipWildcardSuffix = queryStringContainsWildcardSuffix
228  || (getQueryString().endsWith("$") && (!getQueryString().endsWith("\\$")));
229 
244  String queryString = (originalKeyword.searchTermIsLiteral() ? getEscapedQueryString() : getQueryString());
245  double indexSchemaVersion = NumberUtils.toDouble(solrServer.getIndexInfo().getSchemaVersion());
246  if (indexSchemaVersion >= 2.1) {
247  queryString = queryString.toLowerCase();
248  }
249 
250  solrQuery.setQuery((field == null ? Server.Schema.CONTENT_STR.toString() : field) + ":/"
251  + (skipWildcardPrefix ? "" : ".*")
252  // if the query is for a substring (i.e. literal search term) we want
253  // to escape characters such as ()[]-.
254  + queryString
255  + (skipWildcardSuffix ? "" : ".*") + "/");
256 
257  // Set the fields we want to have returned by the query.
258  solrQuery.setFields(Server.Schema.CONTENT_STR.toString(), Server.Schema.ID.toString(), Server.Schema.CHUNK_SIZE.toString());
259 
260  filters.stream()
261  .map(KeywordQueryFilter::toString)
262  .forEach(solrQuery::addFilterQuery);
263 
264  solrQuery.setRows(MAX_RESULTS_PER_CURSOR_MARK);
265  // Setting the sort order is necessary for cursor based paging to work.
266  solrQuery.setSort(SortClause.asc(Server.Schema.ID.toString()));
267 
268  String cursorMark = CursorMarkParams.CURSOR_MARK_START;
269  SolrDocumentList resultList;
270  boolean allResultsProcessed = false;
271  QueryResults results = new QueryResults(this);
272 
273  while (!allResultsProcessed) {
274  try {
275  solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
276  QueryResponse response = solrServer.query(solrQuery, SolrRequest.METHOD.POST);
277  resultList = response.getResults();
278 
279  for (SolrDocument resultDoc : resultList) {
280  try {
281  List<KeywordHit> keywordHits = createKeywordHits(resultDoc);
282  for (KeywordHit hit : keywordHits) {
283  Keyword keywordInstance = new Keyword(hit.getHit(), true, true, originalKeyword.getListName(), originalKeyword.getOriginalTerm());
284  List<KeywordHit> hitsForKeyword = results.getResults(keywordInstance);
285  if (hitsForKeyword == null) {
286  hitsForKeyword = new ArrayList<>();
287  results.addResult(keywordInstance, hitsForKeyword);
288  }
289  hitsForKeyword.add(hit);
290  }
291  } catch (TskCoreException ex) {
292  LOGGER.log(Level.SEVERE, "Error creating keyword hits", ex); //NON-NLS
293  }
294  }
295 
296  String nextCursorMark = response.getNextCursorMark();
297  if (cursorMark.equals(nextCursorMark)) {
298  allResultsProcessed = true;
299  }
300  cursorMark = nextCursorMark;
301  } catch (KeywordSearchModuleException ex) {
302  LOGGER.log(Level.SEVERE, "Error executing Regex Solr Query: " + keywordString, ex); //NON-NLS
303  MessageNotifyUtil.Notify.error(NbBundle.getMessage(Server.class, "Server.query.exception.msg", keywordString), ex.getCause().getMessage());
304  }
305  }
306 
307  return results;
308  }
309 
310  private List<KeywordHit> createKeywordHits(SolrDocument solrDoc) throws TskCoreException {
311 
312  final HashMap<String, String> keywordsFoundInThisDocument = new HashMap<>();
313 
314  List<KeywordHit> hits = new ArrayList<>();
315  final String docId = solrDoc.getFieldValue(Server.Schema.ID.toString()).toString();
316  final Integer chunkSize = (Integer) solrDoc.getFieldValue(Server.Schema.CHUNK_SIZE.toString());
317 
318  final Collection<Object> content_str = solrDoc.getFieldValues(Server.Schema.CONTENT_STR.toString());
319 
320  String searchPattern;
321  if (originalKeyword.searchTermIsLiteral()) {
335  searchPattern = "[\\w[\\.']]*" + Pattern.quote(keywordString.toLowerCase()) + "[\\w[\\.']]*";
336  } else {
337  searchPattern = keywordString;
338  }
339 
340  final Pattern pattern = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE);
341 
342  try {
343  for (Object content_obj : content_str) {
344  String content = (String) content_obj;
345  Matcher hitMatcher = pattern.matcher(content);
346  int offset = 0;
347 
348  while (hitMatcher.find(offset)) {
349 
350  // If the location of the hit is beyond this chunk (i.e. it
351  // exists in the overlap region), we skip the hit. It will
352  // show up again as a hit in the chunk following this one.
353  if (chunkSize != null && hitMatcher.start() >= chunkSize) {
354  break;
355  }
356 
357  String hit = hitMatcher.group();
358 
362  if ("".equals(hit)) {
363  break;
364  }
365 
366  offset = hitMatcher.end();
367  final ATTRIBUTE_TYPE artifactAttributeType = originalKeyword.getArtifactAttributeType();
368 
369  // We attempt to reduce false positives for phone numbers and IP address hits
370  // by querying Solr for hits delimited by a set of known boundary characters.
371  // See KeywordSearchList.PHONE_NUMBER_REGEX for an example.
372  // Because of this the hits may contain an extra character at the beginning or end that
373  // needs to be chopped off, unless the user has supplied their own wildcard suffix
374  // as part of the regex.
375  if (!queryStringContainsWildcardSuffix
376  && (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER
377  || artifactAttributeType == ATTRIBUTE_TYPE.TSK_IP_ADDRESS)) {
378  if (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER) {
379  // For phone numbers replace all non numeric characters (except "(") at the start of the hit.
380  hit = hit.replaceAll("^[^0-9\\(]", "");
381  } else {
382  // Replace all non numeric characters at the start of the hit.
383  hit = hit.replaceAll("^[^0-9]", "");
384  }
385  // Replace all non numeric at the end of the hit.
386  hit = hit.replaceAll("[^0-9]$", "");
387  }
388 
397  if (originalKeyword.searchTermIsLiteral()) {
398  hit = hit.replaceAll("^" + KeywordSearchList.BOUNDARY_CHARACTERS + "*", "");
399  hit = hit.replaceAll(KeywordSearchList.BOUNDARY_CHARACTERS + "*$", "");
400 
409  if (hit.length() > 255) {
410  break;
411  }
412  }
413 
422  hit = hit.intern();
423 
424  // We will only create one KeywordHit instance per document for
425  // a given hit.
426  if (keywordsFoundInThisDocument.containsKey(hit)) {
427  continue;
428  }
429  keywordsFoundInThisDocument.put(hit, hit);
430 
431  if (artifactAttributeType == null) {
432  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
433  } else {
434  switch (artifactAttributeType) {
435  case TSK_EMAIL:
436  /*
437  * Reduce false positives by eliminating email
438  * address hits that are either too short or are
439  * not for valid top level domains.
440  */
441  if (hit.length() >= MIN_EMAIL_ADDR_LENGTH
442  && DomainValidator.getInstance(true).isValidTld(hit.substring(hit.lastIndexOf('.')))) {
443  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
444  }
445 
446  break;
447  case TSK_CARD_NUMBER:
448  /*
449  * If searching for credit card account numbers,
450  * do extra validation on the term and discard
451  * it if it does not pass.
452  */
453  Matcher ccnMatcher = CREDIT_CARD_NUM_PATTERN.matcher(hit);
454 
455  for (int rLength = hit.length(); rLength >= 12; rLength--) {
456  ccnMatcher.region(0, rLength);
457  if (ccnMatcher.find()) {
458  final String group = ccnMatcher.group("ccn");
459  if (CreditCardValidator.isValidCCN(group)) {
460  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
461  }
462  }
463  }
464 
465  break;
466  default:
467  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
468  break;
469  }
470  }
471  }
472  }
473  } catch (Throwable error) {
474  /*
475  * NOTE: Matcher.find() is known to throw StackOverflowError in rare
476  * cases (see JIRA-2700). StackOverflowError is an error, not an
477  * exception, and therefore needs to be caught as a Throwable. When
478  * this occurs we should re-throw the error as TskCoreException so
479  * that it is logged by the calling method and move on to the next
480  * Solr document.
481  */
482  throw new TskCoreException("Failed to create keyword hits for Solr document id " + docId + " due to " + error.getMessage());
483  }
484  return hits;
485  }
486 
500  private String makeSnippet(String content, Matcher hitMatcher, String hit) {
501  // Get the snippet from the document.
502  int maxIndex = content.length() - 1;
503  final int end = hitMatcher.end();
504  final int start = hitMatcher.start();
505 
506  return content.substring(Integer.max(0, start - 20), Integer.max(0, start))
507  + SNIPPET_DELIMITER + hit + SNIPPET_DELIMITER
508  + content.substring(Integer.min(maxIndex, end), Integer.min(maxIndex, end + 20));
509  }
510 
511  @Override
512  public void addFilter(KeywordQueryFilter filter) {
513  this.filters.add(filter);
514  }
515 
516  @Override
517  public void setField(String field) {
518  this.field = field;
519  }
520 
521  @Override
522  public void setSubstringQuery() {
523  }
524 
525  @Override
526  synchronized public void escape() {
527  if (isEscaped() == false) {
528  escapedQuery = KeywordSearchUtil.escapeLuceneQuery(keywordString);
529  escaped = true;
530  }
531  }
532 
533  @Override
534  synchronized public boolean isEscaped() {
535  return escaped;
536  }
537 
538  @Override
539  public boolean isLiteral() {
540  return false;
541  }
542 
543  @Override
544  public String getQueryString() {
545  return originalKeyword.getSearchTerm();
546  }
547 
548  @Override
549  synchronized public String getEscapedQueryString() {
550  if (false == isEscaped()) {
551  escape();
552  }
553  return escapedQuery;
554  }
555 
572  @Override
573  public BlackboardArtifact createKeywordHitArtifact(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
574  final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
575 
576  if (content == null) {
577  LOGGER.log(Level.WARNING, "Error adding artifact for keyword hit to blackboard"); //NON-NLS
578  return null;
579  }
580 
581  /*
582  * Credit Card number hits are handled differently
583  */
584  if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
585  createCCNAccount(content, foundKeyword, hit, snippet, listName);
586  return null;
587  }
588 
589  /*
590  * Create a "plain vanilla" keyword hit artifact with keyword and regex
591  * attributes
592  */
593  Collection<BlackboardAttribute> attributes = new ArrayList<>();
594 
595  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, foundKeyword.getSearchTerm()));
596  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP, MODULE_NAME, getQueryString()));
597 
598  if (StringUtils.isNotBlank(listName)) {
599  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
600  }
601  if (snippet != null) {
602  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
603  }
604 
605  hit.getArtifactID().ifPresent(artifactID
606  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
607  );
608 
609  if (originalKeyword.searchTermIsLiteral()) {
610  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.SUBSTRING.ordinal()));
611  } else {
612  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
613  }
614 
615  try {
616  return content.newAnalysisResult(
617  BlackboardArtifact.Type.TSK_KEYWORD_HIT, Score.SCORE_LIKELY_NOTABLE,
618  null, listName, null, attributes)
619  .getAnalysisResult();
620  } catch (TskCoreException e) {
621  LOGGER.log(Level.SEVERE, "Error adding bb attributes for terms search artifact", e); //NON-NLS
622  return null;
623  }
624  }
625 
626  private void createCCNAccount(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
627 
628  final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
629 
630  if (originalKeyword.getArtifactAttributeType() != ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
631  LOGGER.log(Level.SEVERE, "Keyword hit is not a credit card number"); //NON-NLS
632  return;
633  }
634  /*
635  * Create a credit card account with attributes parsed from the snippet
636  * for the hit and looked up based on the parsed bank identifcation
637  * number.
638  */
639  Collection<BlackboardAttribute> attributes = new ArrayList<>();
640 
641  Map<BlackboardAttribute.Type, BlackboardAttribute> parsedTrackAttributeMap = new HashMap<>();
642  Matcher matcher = CREDIT_CARD_TRACK1_PATTERN.matcher(hit.getSnippet());
643  if (matcher.find()) {
644  parseTrack1Data(parsedTrackAttributeMap, matcher);
645  }
646  matcher = CREDIT_CARD_TRACK2_PATTERN.matcher(hit.getSnippet());
647  if (matcher.find()) {
648  parseTrack2Data(parsedTrackAttributeMap, matcher);
649  }
650  final BlackboardAttribute ccnAttribute = parsedTrackAttributeMap.get(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_CARD_NUMBER));
651  if (ccnAttribute == null || StringUtils.isBlank(ccnAttribute.getValueString())) {
652 
653  if (hit.isArtifactHit()) {
654  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for artifact keyword hit: term = %s, snippet = '%s', artifact id = %d", foundKeyword.getSearchTerm(), hit.getSnippet(), hit.getArtifactID().get())); //NON-NLS
655  } else {
656  try {
657  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for content keyword hit: term = %s, snippet = '%s', object id = %d", foundKeyword.getSearchTerm(), hit.getSnippet(), hit.getContentID())); //NON-NLS
658  } catch (TskCoreException ex) {
659  LOGGER.log(Level.SEVERE, String.format("Failed to parse credit card account number for content keyword hit: term = %s, snippet = '%s' ", foundKeyword.getSearchTerm(), hit.getSnippet())); //NON-NLS
660  LOGGER.log(Level.SEVERE, "There was a error getting contentID for keyword hit.", ex); //NON-NLS
661  }
662  }
663  return;
664  }
665  attributes.addAll(parsedTrackAttributeMap.values());
666 
667  /*
668  * Look up the bank name, scheme, etc. attributes for the bank
669  * indentification number (BIN).
670  */
671  final int bin = Integer.parseInt(ccnAttribute.getValueString().substring(0, 8));
672  CreditCards.BankIdentificationNumber binInfo = CreditCards.getBINInfo(bin);
673  if (binInfo != null) {
674  binInfo.getScheme().ifPresent(scheme
675  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_SCHEME, MODULE_NAME, scheme)));
676  binInfo.getCardType().ifPresent(cardType
677  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_TYPE, MODULE_NAME, cardType)));
678  binInfo.getBrand().ifPresent(brand
679  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BRAND_NAME, MODULE_NAME, brand)));
680  binInfo.getBankName().ifPresent(bankName
681  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BANK_NAME, MODULE_NAME, bankName)));
682  binInfo.getBankPhoneNumber().ifPresent(phoneNumber
683  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER, MODULE_NAME, phoneNumber)));
684  binInfo.getBankURL().ifPresent(url
685  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL, MODULE_NAME, url)));
686  binInfo.getCountry().ifPresent(country
687  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COUNTRY, MODULE_NAME, country)));
688  binInfo.getBankCity().ifPresent(city
689  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CITY, MODULE_NAME, city)));
690  }
691 
692  /*
693  * If the hit is from unused or unallocated space, record the Solr
694  * document id to support showing just the chunk that contained the hit.
695  */
696  if (content instanceof AbstractFile) {
697  AbstractFile file = (AbstractFile) content;
698  if (file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS
699  || file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) {
700  attributes.add(new BlackboardAttribute(KEYWORD_SEARCH_DOCUMENT_ID, MODULE_NAME, hit.getSolrDocumentId()));
701  }
702  }
703 
704  if (StringUtils.isNotBlank(listName)) {
705  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
706  }
707  if (snippet != null) {
708  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
709  }
710 
711  hit.getArtifactID().ifPresent(artifactID
712  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
713  );
714 
715  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
716 
717  /*
718  * Create an account instance.
719  */
720  try {
721  AccountFileInstance ccAccountInstance = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.CREDIT_CARD, ccnAttribute.getValueString(), MODULE_NAME, content);
722 
723  ccAccountInstance.addAttributes(attributes);
724 
725  } catch (TskCoreException | NoCurrentCaseException ex) {
726  LOGGER.log(Level.SEVERE, "Error creating CCN account instance", ex); //NON-NLS
727 
728  }
729 
730  }
731 
740  static private void parseTrack2Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributesMap, Matcher matcher) {
741  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_NUMBER, "accountNumber", matcher);
742  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_EXPIRATION, "expiration", matcher);
743  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_SERVICE_CODE, "serviceCode", matcher);
744  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_DISCRETIONARY, "discretionary", matcher);
745  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_LRC, "LRC", matcher);
746  }
747 
757  static private void parseTrack1Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, Matcher matcher) {
758  parseTrack2Data(attributeMap, matcher);
759  addAttributeIfNotAlreadyCaptured(attributeMap, ATTRIBUTE_TYPE.TSK_NAME_PERSON, "name", matcher);
760  }
761 
774  static private void addAttributeIfNotAlreadyCaptured(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, ATTRIBUTE_TYPE attrType, String groupName, Matcher matcher) {
775  BlackboardAttribute.Type type = new BlackboardAttribute.Type(attrType);
776 
777  if (!attributeMap.containsKey(type)) {
778  String value = matcher.group(groupName);
779  if (attrType.equals(ATTRIBUTE_TYPE.TSK_CARD_NUMBER)) {
780  attributeMap.put(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD),
781  new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, value));
782  value = CharMatcher.anyOf(" -").removeFrom(value);
783  }
784 
785  if (StringUtils.isNotBlank(value)) {
786  attributeMap.put(type, new BlackboardAttribute(attrType, MODULE_NAME, value));
787  }
788  }
789  }
790 }

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