Autopsy  4.8.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.BlackboardArtifact.ARTIFACT_TYPE;
52 import org.sleuthkit.datamodel.BlackboardAttribute;
53 import org.sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
54 import org.sleuthkit.datamodel.Content;
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 
359  offset = hitMatcher.end();
360  final ATTRIBUTE_TYPE artifactAttributeType = originalKeyword.getArtifactAttributeType();
361 
362  // We attempt to reduce false positives for phone numbers and IP address hits
363  // by querying Solr for hits delimited by a set of known boundary characters.
364  // See KeywordSearchList.PHONE_NUMBER_REGEX for an example.
365  // Because of this the hits may contain an extra character at the beginning or end that
366  // needs to be chopped off, unless the user has supplied their own wildcard suffix
367  // as part of the regex.
368  if (!queryStringContainsWildcardSuffix
369  && (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER
370  || artifactAttributeType == ATTRIBUTE_TYPE.TSK_IP_ADDRESS)) {
371  if (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER) {
372  // For phone numbers replace all non numeric characters (except "(") at the start of the hit.
373  hit = hit.replaceAll("^[^0-9\\(]", "");
374  } else {
375  // Replace all non numeric characters at the start of the hit.
376  hit = hit.replaceAll("^[^0-9]", "");
377  }
378  // Replace all non numeric at the end of the hit.
379  hit = hit.replaceAll("[^0-9]$", "");
380  }
381 
390  if (originalKeyword.searchTermIsLiteral()) {
391  hit = hit.replaceAll("^" + KeywordSearchList.BOUNDARY_CHARACTERS + "*", "");
392  hit = hit.replaceAll(KeywordSearchList.BOUNDARY_CHARACTERS + "*$", "");
393 
402  if (hit.length() > 255) {
403  break;
404  }
405  }
406 
415  hit = hit.intern();
416 
417  // We will only create one KeywordHit instance per document for
418  // a given hit.
419  if (keywordsFoundInThisDocument.containsKey(hit)) {
420  continue;
421  }
422  keywordsFoundInThisDocument.put(hit, hit);
423 
424  if (artifactAttributeType == null) {
425  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
426  } else {
427  switch (artifactAttributeType) {
428  case TSK_EMAIL:
429  /*
430  * Reduce false positives by eliminating email
431  * address hits that are either too short or are
432  * not for valid top level domains.
433  */
434  if (hit.length() >= MIN_EMAIL_ADDR_LENGTH
435  && DomainValidator.getInstance(true).isValidTld(hit.substring(hit.lastIndexOf('.')))) {
436  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
437  }
438 
439  break;
440  case TSK_CARD_NUMBER:
441  /*
442  * If searching for credit card account numbers,
443  * do extra validation on the term and discard
444  * it if it does not pass.
445  */
446  Matcher ccnMatcher = CREDIT_CARD_NUM_PATTERN.matcher(hit);
447 
448  for (int rLength = hit.length(); rLength >= 12; rLength--) {
449  ccnMatcher.region(0, rLength);
450  if (ccnMatcher.find()) {
451  final String group = ccnMatcher.group("ccn");
452  if (CreditCardValidator.isValidCCN(group)) {
453  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
454  }
455  }
456  }
457 
458  break;
459  default:
460  hits.add(new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
461  break;
462  }
463  }
464  }
465  }
466  } catch (Throwable error) {
467  /*
468  * NOTE: Matcher.find() is known to throw StackOverflowError in rare
469  * cases (see JIRA-2700). StackOverflowError is an error, not an
470  * exception, and therefore needs to be caught as a Throwable. When
471  * this occurs we should re-throw the error as TskCoreException so
472  * that it is logged by the calling method and move on to the next
473  * Solr document.
474  */
475  throw new TskCoreException("Failed to create keyword hits for Solr document id " + docId + " due to " + error.getMessage());
476  }
477  return hits;
478  }
479 
493  private String makeSnippet(String content, Matcher hitMatcher, String hit) {
494  // Get the snippet from the document.
495  int maxIndex = content.length() - 1;
496  final int end = hitMatcher.end();
497  final int start = hitMatcher.start();
498 
499  return content.substring(Integer.max(0, start - 20), Integer.max(0, start))
500  + SNIPPET_DELIMITER + hit + SNIPPET_DELIMITER
501  + content.substring(Integer.min(maxIndex, end), Integer.min(maxIndex, end + 20));
502  }
503 
504  @Override
505  public void addFilter(KeywordQueryFilter filter) {
506  this.filters.add(filter);
507  }
508 
509  @Override
510  public void setField(String field) {
511  this.field = field;
512  }
513 
514  @Override
515  public void setSubstringQuery() {
516  }
517 
518  @Override
519  synchronized public void escape() {
520  if (isEscaped() == false) {
521  escapedQuery = KeywordSearchUtil.escapeLuceneQuery(keywordString);
522  escaped = true;
523  }
524  }
525 
526  @Override
527  synchronized public boolean isEscaped() {
528  return escaped;
529  }
530 
531  @Override
532  public boolean isLiteral() {
533  return false;
534  }
535 
536  @Override
537  public String getQueryString() {
538  return originalKeyword.getSearchTerm();
539  }
540 
541  @Override
542  synchronized public String getEscapedQueryString() {
543  if (false == isEscaped()) {
544  escape();
545  }
546  return escapedQuery;
547  }
548 
565  @Override
566  public BlackboardArtifact postKeywordHitToBlackboard(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
567  final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
568 
569  if (content == null) {
570  LOGGER.log(Level.WARNING, "Error adding artifact for keyword hit to blackboard"); //NON-NLS
571  return null;
572  }
573 
574  /*
575  * Credit Card number hits are handled differently
576  */
577  if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
578  createCCNAccount(content, foundKeyword, hit, snippet, listName);
579  return null;
580  }
581 
582  /*
583  * Create a "plain vanilla" keyword hit artifact with keyword and regex
584  * attributes
585  */
586  BlackboardArtifact newArtifact;
587  Collection<BlackboardAttribute> attributes = new ArrayList<>();
588 
589  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, foundKeyword.getSearchTerm()));
590  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP, MODULE_NAME, getQueryString()));
591 
592  try {
593  newArtifact = content.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
594  } catch (TskCoreException ex) {
595  LOGGER.log(Level.SEVERE, "Error adding artifact for keyword hit to blackboard", ex); //NON-NLS
596  return null;
597  }
598 
599  if (StringUtils.isNotBlank(listName)) {
600  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
601  }
602  if (snippet != null) {
603  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
604  }
605 
606  hit.getArtifactID().ifPresent(artifactID
607  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
608  );
609 
610  if (originalKeyword.searchTermIsLiteral()) {
611  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.SUBSTRING.ordinal()));
612  } else {
613  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
614  }
615 
616  try {
617  newArtifact.addAttributes(attributes);
618  return newArtifact;
619  } catch (TskCoreException e) {
620  LOGGER.log(Level.SEVERE, "Error adding bb attributes for terms search artifact", e); //NON-NLS
621  return null;
622  }
623  }
624 
625  private void createCCNAccount(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
626 
627  final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
628 
629  if (originalKeyword.getArtifactAttributeType() != ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
630  LOGGER.log(Level.SEVERE, "Keyword hit is not a credit card number"); //NON-NLS
631  return;
632  }
633  /*
634  * Create a credit card account with attributes parsed from the snippet
635  * for the hit and looked up based on the parsed bank identifcation
636  * number.
637  */
638  Collection<BlackboardAttribute> attributes = new ArrayList<>();
639 
640  Map<BlackboardAttribute.Type, BlackboardAttribute> parsedTrackAttributeMap = new HashMap<>();
641  Matcher matcher = CREDIT_CARD_TRACK1_PATTERN.matcher(hit.getSnippet());
642  if (matcher.find()) {
643  parseTrack1Data(parsedTrackAttributeMap, matcher);
644  }
645  matcher = CREDIT_CARD_TRACK2_PATTERN.matcher(hit.getSnippet());
646  if (matcher.find()) {
647  parseTrack2Data(parsedTrackAttributeMap, matcher);
648  }
649  final BlackboardAttribute ccnAttribute = parsedTrackAttributeMap.get(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_CARD_NUMBER));
650  if (ccnAttribute == null || StringUtils.isBlank(ccnAttribute.getValueString())) {
651 
652  if (hit.isArtifactHit()) {
653  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
654  } else {
655  try {
656  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
657  } catch (TskCoreException ex) {
658  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
659  LOGGER.log(Level.SEVERE, "There was a error getting contentID for keyword hit.", ex); //NON-NLS
660  }
661  }
662  return;
663  }
664  attributes.addAll(parsedTrackAttributeMap.values());
665 
666  /*
667  * Look up the bank name, scheme, etc. attributes for the bank
668  * indentification number (BIN).
669  */
670  final int bin = Integer.parseInt(ccnAttribute.getValueString().substring(0, 8));
671  CreditCards.BankIdentificationNumber binInfo = CreditCards.getBINInfo(bin);
672  if (binInfo != null) {
673  binInfo.getScheme().ifPresent(scheme
674  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_SCHEME, MODULE_NAME, scheme)));
675  binInfo.getCardType().ifPresent(cardType
676  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_TYPE, MODULE_NAME, cardType)));
677  binInfo.getBrand().ifPresent(brand
678  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BRAND_NAME, MODULE_NAME, brand)));
679  binInfo.getBankName().ifPresent(bankName
680  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BANK_NAME, MODULE_NAME, bankName)));
681  binInfo.getBankPhoneNumber().ifPresent(phoneNumber
682  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER, MODULE_NAME, phoneNumber)));
683  binInfo.getBankURL().ifPresent(url
684  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL, MODULE_NAME, url)));
685  binInfo.getCountry().ifPresent(country
686  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COUNTRY, MODULE_NAME, country)));
687  binInfo.getBankCity().ifPresent(city
688  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CITY, MODULE_NAME, city)));
689  }
690 
691  /*
692  * If the hit is from unused or unallocated space, record the Solr
693  * document id to support showing just the chunk that contained the hit.
694  */
695  if (content instanceof AbstractFile) {
696  AbstractFile file = (AbstractFile) content;
697  if (file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS
698  || file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) {
699  attributes.add(new BlackboardAttribute(KEYWORD_SEARCH_DOCUMENT_ID, MODULE_NAME, hit.getSolrDocumentId()));
700  }
701  }
702 
703  if (StringUtils.isNotBlank(listName)) {
704  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
705  }
706  if (snippet != null) {
707  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
708  }
709 
710  hit.getArtifactID().ifPresent(artifactID
711  -> attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
712  );
713 
714  attributes.add(new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
715 
716  /*
717  * Create an account instance.
718  */
719  try {
720  AccountFileInstance ccAccountInstance = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.CREDIT_CARD, ccnAttribute.getValueString(), MODULE_NAME, content);
721 
722  ccAccountInstance.addAttributes(attributes);
723 
724  } catch (TskCoreException | NoCurrentCaseException ex) {
725  LOGGER.log(Level.SEVERE, "Error creating CCN account instance", ex); //NON-NLS
726 
727  }
728 
729  }
730 
739  static private void parseTrack2Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributesMap, Matcher matcher) {
740  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_NUMBER, "accountNumber", matcher);
741  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_EXPIRATION, "expiration", matcher);
742  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_SERVICE_CODE, "serviceCode", matcher);
743  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_DISCRETIONARY, "discretionary", matcher);
744  addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_LRC, "LRC", matcher);
745  }
746 
756  static private void parseTrack1Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, Matcher matcher) {
757  parseTrack2Data(attributeMap, matcher);
758  addAttributeIfNotAlreadyCaptured(attributeMap, ATTRIBUTE_TYPE.TSK_NAME_PERSON, "name", matcher);
759  }
760 
773  static private void addAttributeIfNotAlreadyCaptured(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, ATTRIBUTE_TYPE attrType, String groupName, Matcher matcher) {
774  BlackboardAttribute.Type type = new BlackboardAttribute.Type(attrType);
775 
776  if (!attributeMap.containsKey(type)) {
777  String value = matcher.group(groupName);
778  if (attrType.equals(ATTRIBUTE_TYPE.TSK_CARD_NUMBER)) {
779  attributeMap.put(new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD),
780  new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, value));
781  value = CharMatcher.anyOf(" -").removeFrom(value);
782  }
783 
784  if (StringUtils.isNotBlank(value)) {
785  attributeMap.put(type, new BlackboardAttribute(attrType, MODULE_NAME, value));
786  }
787  }
788  }
789 }

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