19 package org.sleuthkit.autopsy.keywordsearch;
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;
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;
51 import org.
sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
53 import org.
sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
72 final class RegexQuery
implements KeywordSearchQuery {
74 public static final Logger LOGGER = Logger.getLogger(RegexQuery.class.getName());
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"};
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));
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(
117 +
"(?<accountNumber>[2-6]([ -]?[0-9]){11,18})"
119 +
"(?<name>[^^]{2,26})"
121 +
"(?:(?:\\^|(?<expiration>\\d{4}))"
122 +
"(?:(?:\\^|(?<serviceCode>\\d{3}))"
123 +
"(?:(?<discretionary>[^?]*)"
127 static final Pattern CREDIT_CARD_TRACK2_PATTERN = Pattern.compile(
138 +
"(?<accountNumber>[2-6]([ -]?[0-9]){11,18})"
140 +
"(?:(?<expiration>\\d{4})"
141 +
"(?:(?<serviceCode>\\d{3})"
142 +
"(?:(?<discretionary>[^:;<=>?]*)"
146 static final BlackboardAttribute.Type KEYWORD_SEARCH_DOCUMENT_ID =
new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_DOCUMENT_ID);
148 private final List<KeywordQueryFilter> filters =
new ArrayList<>();
149 private final KeywordList keywordList;
150 private final Keyword originalKeyword;
151 private final String keywordString;
152 private final boolean queryStringContainsWildcardPrefix;
153 private final boolean queryStringContainsWildcardSuffix;
155 private boolean escaped;
156 private String escapedQuery;
157 private String field = Server.Schema.CONTENT_STR.toString();
165 RegexQuery(KeywordList keywordList, Keyword keyword) {
166 this.keywordList = keywordList;
167 this.originalKeyword = keyword;
168 this.keywordString = keyword.getSearchTerm();
170 this.queryStringContainsWildcardPrefix = this.keywordString.startsWith(
".*");
171 this.queryStringContainsWildcardSuffix = this.keywordString.endsWith(
".*");
175 public KeywordList getKeywordList() {
180 public boolean validate() {
181 if (keywordString.isEmpty()) {
186 Pattern.compile(keywordString, Pattern.UNICODE_CHARACTER_CLASS);
192 for (CharSequence c : UNSUPPORTED_CHARS) {
193 if (keywordString.contains(c)) {
198 }
catch (IllegalArgumentException ex) {
204 public QueryResults performQuery() throws NoOpenCoreException {
206 final Server solrServer = KeywordSearch.getServer();
207 SolrQuery solrQuery =
new SolrQuery();
226 boolean skipWildcardPrefix = queryStringContainsWildcardPrefix || getQueryString().startsWith(
"^");
227 boolean skipWildcardSuffix = queryStringContainsWildcardSuffix
228 || (getQueryString().endsWith(
"$") && (!getQueryString().endsWith(
"\\$")));
244 String queryString = (originalKeyword.searchTermIsLiteral() ? getEscapedQueryString() : getQueryString());
245 double indexSchemaVersion = NumberUtils.toDouble(solrServer.getIndexInfo().getSchemaVersion());
246 if (indexSchemaVersion >= 2.1) {
247 queryString = queryString.toLowerCase();
250 solrQuery.setQuery((field == null ? Server.Schema.CONTENT_STR.toString() : field) +
":/"
251 + (skipWildcardPrefix ?
"" :
".*")
255 + (skipWildcardSuffix ?
"" :
".*") +
"/");
258 solrQuery.setFields(Server.Schema.CONTENT_STR.toString(), Server.Schema.ID.toString(), Server.Schema.CHUNK_SIZE.toString());
261 .map(KeywordQueryFilter::toString)
262 .forEach(solrQuery::addFilterQuery);
264 solrQuery.setRows(MAX_RESULTS_PER_CURSOR_MARK);
266 solrQuery.setSort(SortClause.asc(Server.Schema.ID.toString()));
268 String cursorMark = CursorMarkParams.CURSOR_MARK_START;
269 SolrDocumentList resultList;
270 boolean allResultsProcessed =
false;
271 QueryResults results =
new QueryResults(
this);
273 while (!allResultsProcessed) {
275 solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
276 QueryResponse response = solrServer.query(solrQuery, SolrRequest.METHOD.POST);
277 resultList = response.getResults();
279 for (SolrDocument resultDoc : resultList) {
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);
289 hitsForKeyword.add(hit);
291 }
catch (TskCoreException ex) {
292 LOGGER.log(Level.SEVERE,
"Error creating keyword hits", ex);
296 String nextCursorMark = response.getNextCursorMark();
297 if (cursorMark.equals(nextCursorMark)) {
298 allResultsProcessed =
true;
300 cursorMark = nextCursorMark;
301 }
catch (KeywordSearchModuleException ex) {
302 LOGGER.log(Level.SEVERE,
"Error executing Regex Solr Query: " + keywordString, ex);
303 MessageNotifyUtil.Notify.error(NbBundle.getMessage(Server.class,
"Server.query.exception.msg", keywordString), ex.getCause().getMessage());
310 private List<KeywordHit> createKeywordHits(SolrDocument solrDoc)
throws TskCoreException {
312 final HashMap<String, String> keywordsFoundInThisDocument =
new HashMap<>();
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());
318 final Collection<Object> content_str = solrDoc.getFieldValues(Server.Schema.CONTENT_STR.toString());
320 String searchPattern;
321 if (originalKeyword.searchTermIsLiteral()) {
335 searchPattern =
"[\\w[\\.']]*" + Pattern.quote(keywordString.toLowerCase()) +
"[\\w[\\.']]*";
337 searchPattern = keywordString;
340 final Pattern pattern = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE);
343 for (Object content_obj : content_str) {
344 String content = (String) content_obj;
345 Matcher hitMatcher = pattern.matcher(content);
348 while (hitMatcher.find(offset)) {
353 if (chunkSize != null && hitMatcher.start() >= chunkSize) {
357 String hit = hitMatcher.group();
359 offset = hitMatcher.end();
360 final ATTRIBUTE_TYPE artifactAttributeType = originalKeyword.getArtifactAttributeType();
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) {
373 hit = hit.replaceAll(
"^[^0-9\\(]",
"");
376 hit = hit.replaceAll(
"^[^0-9]",
"");
379 hit = hit.replaceAll(
"[^0-9]$",
"");
390 if (originalKeyword.searchTermIsLiteral()) {
391 hit = hit.replaceAll(
"^" + KeywordSearchList.BOUNDARY_CHARACTERS +
"*",
"");
392 hit = hit.replaceAll(KeywordSearchList.BOUNDARY_CHARACTERS +
"*$",
"");
402 if (hit.length() > 255) {
419 if (keywordsFoundInThisDocument.containsKey(hit)) {
422 keywordsFoundInThisDocument.put(hit, hit);
424 if (artifactAttributeType == null) {
425 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
427 switch (artifactAttributeType) {
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));
440 case TSK_CARD_NUMBER:
446 Matcher ccnMatcher = CREDIT_CARD_NUM_PATTERN.matcher(hit);
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));
460 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
466 }
catch (Throwable error) {
475 throw new TskCoreException(
"Failed to create keyword hits for Solr document id " + docId +
" due to " + error.getMessage());
493 private String makeSnippet(String content, Matcher hitMatcher, String hit) {
495 int maxIndex = content.length() - 1;
496 final int end = hitMatcher.end();
497 final int start = hitMatcher.start();
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));
505 public void addFilter(KeywordQueryFilter filter) {
506 this.filters.add(filter);
510 public void setField(String field) {
515 public void setSubstringQuery() {
519 synchronized public void escape() {
520 if (isEscaped() ==
false) {
521 escapedQuery = KeywordSearchUtil.escapeLuceneQuery(keywordString);
527 synchronized public boolean isEscaped() {
532 public boolean isLiteral() {
537 public String getQueryString() {
538 return originalKeyword.getSearchTerm();
542 synchronized public String getEscapedQueryString() {
543 if (
false == isEscaped()) {
566 public BlackboardArtifact postKeywordHitToBlackboard(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
567 final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
569 if (content == null) {
570 LOGGER.log(Level.WARNING,
"Error adding artifact for keyword hit to blackboard");
577 if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
578 createCCNAccount(content, foundKeyword, hit, snippet, listName);
586 BlackboardArtifact newArtifact;
587 Collection<BlackboardAttribute> attributes =
new ArrayList<>();
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()));
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);
599 if (StringUtils.isNotBlank(listName)) {
600 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
602 if (snippet != null) {
603 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
606 hit.getArtifactID().ifPresent(artifactID
607 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
610 if (originalKeyword.searchTermIsLiteral()) {
611 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.SUBSTRING.ordinal()));
613 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
617 newArtifact.addAttributes(attributes);
619 }
catch (TskCoreException e) {
620 LOGGER.log(Level.SEVERE,
"Error adding bb attributes for terms search artifact", e);
625 private void createCCNAccount(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
627 final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
629 if (originalKeyword.getArtifactAttributeType() != ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
630 LOGGER.log(Level.SEVERE,
"Keyword hit is not a credit card number");
638 Collection<BlackboardAttribute> attributes =
new ArrayList<>();
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);
645 matcher = CREDIT_CARD_TRACK2_PATTERN.matcher(hit.getSnippet());
646 if (matcher.find()) {
647 parseTrack2Data(parsedTrackAttributeMap, matcher);
649 final BlackboardAttribute ccnAttribute = parsedTrackAttributeMap.get(
new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_CARD_NUMBER));
650 if (ccnAttribute == null || StringUtils.isBlank(ccnAttribute.getValueString())) {
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()));
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()));
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()));
659 LOGGER.log(Level.SEVERE,
"There was a error getting contentID for keyword hit.", ex);
664 attributes.addAll(parsedTrackAttributeMap.values());
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)));
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()));
703 if (StringUtils.isNotBlank(listName)) {
704 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
706 if (snippet != null) {
707 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
710 hit.getArtifactID().ifPresent(artifactID
711 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
714 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
720 AccountFileInstance ccAccountInstance = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.CREDIT_CARD, ccnAttribute.getValueString(), MODULE_NAME, content);
722 ccAccountInstance.addAttributes(attributes);
724 }
catch (TskCoreException | NoCurrentCaseException ex) {
725 LOGGER.log(Level.SEVERE,
"Error creating CCN account instance", ex);
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);
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);
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);
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);
784 if (StringUtils.isNotBlank(value)) {
785 attributeMap.put(type,
new BlackboardAttribute(attrType, MODULE_NAME, value));