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.validator.routines.DomainValidator;
32 import org.apache.solr.client.solrj.SolrQuery;
33 import org.apache.solr.client.solrj.SolrQuery.SortClause;
34 import org.apache.solr.client.solrj.SolrRequest;
35 import org.apache.solr.client.solrj.response.QueryResponse;
36 import org.apache.solr.common.SolrDocument;
37 import org.apache.solr.common.SolrDocumentList;
38 import org.apache.solr.common.params.CursorMarkParams;
39 import org.openide.util.Exceptions;
40 import org.openide.util.NbBundle;
54 import org.
sleuthkit.datamodel.BlackboardArtifact.ARTIFACT_TYPE;
56 import org.
sleuthkit.datamodel.BlackboardAttribute.ATTRIBUTE_TYPE;
75 final class RegexQuery
implements KeywordSearchQuery {
77 public static final Logger LOGGER = Logger.getLogger(RegexQuery.class.getName());
89 private static final CharSequence[] UNSUPPORTED_CHARS = {
"\\d",
"\\D",
"\\w",
"\\W",
"\\s",
"\\S",
"\\n",
90 "\\t",
"\\r",
"\\f",
"\\a",
"\\e",
"\\v",
"\\V",
"\\h",
"\\H",
"\\p"};
92 private static final int MAX_RESULTS_PER_CURSOR_MARK = 512;
93 private static final int MIN_EMAIL_ADDR_LENGTH = 8;
94 private static final String SNIPPET_DELIMITER = String.valueOf(Character.toChars(171));
96 private final List<KeywordQueryFilter> filters =
new ArrayList<>();
97 private final KeywordList keywordList;
98 private final Keyword originalKeyword;
99 private final String keywordString;
100 private final boolean queryStringContainsWildcardPrefix;
101 private final boolean queryStringContainsWildcardSuffix;
103 private boolean escaped;
104 private String escapedQuery;
105 private String field = Server.Schema.CONTENT_STR.toString();
113 RegexQuery(KeywordList keywordList, Keyword keyword) {
114 this.keywordList = keywordList;
115 this.originalKeyword = keyword;
116 this.keywordString = keyword.getSearchTerm();
118 this.queryStringContainsWildcardPrefix = this.keywordString.startsWith(
".*");
119 this.queryStringContainsWildcardSuffix = this.keywordString.endsWith(
".*");
123 public KeywordList getKeywordList() {
128 public boolean validate() {
129 if (keywordString.isEmpty()) {
134 Pattern.compile(keywordString, Pattern.UNICODE_CHARACTER_CLASS);
140 for (CharSequence c : UNSUPPORTED_CHARS) {
141 if (keywordString.contains(c)) {
146 }
catch (IllegalArgumentException ex) {
152 public QueryResults performQuery() throws NoOpenCoreException {
154 final Server solrServer = KeywordSearch.getServer();
155 SolrQuery solrQuery =
new SolrQuery();
174 boolean skipWildcardPrefix = queryStringContainsWildcardPrefix || getQueryString().startsWith(
"^");
175 boolean skipWildcardSuffix = queryStringContainsWildcardSuffix ||
176 (getQueryString().endsWith(
"$") && ( ! getQueryString().endsWith(
"\\$")));
177 solrQuery.setQuery((field == null ? Server.Schema.CONTENT_STR.toString() : field) +
":/"
178 + (skipWildcardPrefix ?
"" :
".*") + getQueryString()
179 + (skipWildcardSuffix ?
"" :
".*") +
"/");
182 solrQuery.setFields(Server.Schema.CONTENT_STR.toString(), Server.Schema.ID.toString(), Server.Schema.CHUNK_SIZE.toString());
185 .map(KeywordQueryFilter::toString)
186 .forEach(solrQuery::addFilterQuery);
188 solrQuery.setRows(MAX_RESULTS_PER_CURSOR_MARK);
190 solrQuery.setSort(SortClause.asc(Server.Schema.ID.toString()));
192 String cursorMark = CursorMarkParams.CURSOR_MARK_START;
193 SolrDocumentList resultList;
194 boolean allResultsProcessed =
false;
195 QueryResults results =
new QueryResults(
this);
197 while (!allResultsProcessed) {
199 solrQuery.set(CursorMarkParams.CURSOR_MARK_PARAM, cursorMark);
200 QueryResponse response = solrServer.query(solrQuery, SolrRequest.METHOD.POST);
201 resultList = response.getResults();
203 for (SolrDocument resultDoc : resultList) {
205 List<KeywordHit> keywordHits = createKeywordHits(resultDoc);
206 for (KeywordHit hit : keywordHits) {
207 Keyword keywordInstance =
new Keyword(hit.getHit(),
true,
true, originalKeyword.getListName(), originalKeyword.getOriginalTerm());
208 List<KeywordHit> hitsForKeyword = results.getResults(keywordInstance);
209 if (hitsForKeyword == null) {
210 hitsForKeyword =
new ArrayList<>();
211 results.addResult(keywordInstance, hitsForKeyword);
213 hitsForKeyword.add(hit);
215 }
catch (TskCoreException ex) {
216 LOGGER.log(Level.SEVERE,
"Error creating keyword hits", ex);
220 String nextCursorMark = response.getNextCursorMark();
221 if (cursorMark.equals(nextCursorMark)) {
222 allResultsProcessed =
true;
224 cursorMark = nextCursorMark;
225 }
catch (KeywordSearchModuleException ex) {
226 LOGGER.log(Level.SEVERE,
"Error executing Regex Solr Query: " + keywordString, ex);
227 MessageNotifyUtil.Notify.error(NbBundle.getMessage(Server.class,
"Server.query.exception.msg", keywordString), ex.getCause().getMessage());
234 private List<KeywordHit> createKeywordHits(SolrDocument solrDoc)
throws TskCoreException {
236 final HashMap<String, String> keywordsFoundInThisDocument =
new HashMap<>();
238 List<KeywordHit> hits =
new ArrayList<>();
239 final String docId = solrDoc.getFieldValue(Server.Schema.ID.toString()).toString();
240 final Integer chunkSize = (Integer) solrDoc.getFieldValue(Server.Schema.CHUNK_SIZE.toString());
242 final Collection<Object> content_str = solrDoc.getFieldValues(Server.Schema.CONTENT_STR.toString());
244 final Pattern pattern = Pattern.compile(keywordString);
246 for (Object content_obj : content_str) {
247 String content = (String) content_obj;
248 Matcher hitMatcher = pattern.matcher(content);
251 while (hitMatcher.find(offset)) {
256 if (chunkSize != null && hitMatcher.start() >= chunkSize) {
260 String hit = hitMatcher.group();
262 offset = hitMatcher.end();
263 final ATTRIBUTE_TYPE artifactAttributeType = originalKeyword.getArtifactAttributeType();
271 if (!queryStringContainsWildcardSuffix
272 && (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER
273 || artifactAttributeType == ATTRIBUTE_TYPE.TSK_IP_ADDRESS)) {
274 if (artifactAttributeType == ATTRIBUTE_TYPE.TSK_PHONE_NUMBER) {
276 hit = hit.replaceAll(
"^[^0-9\\(]",
"");
279 hit = hit.replaceAll(
"^[^0-9]",
"");
282 hit = hit.replaceAll(
"[^0-9]$",
"");
297 if (keywordsFoundInThisDocument.containsKey(hit)) {
300 keywordsFoundInThisDocument.put(hit, hit);
302 if (artifactAttributeType == null) {
303 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
305 switch (artifactAttributeType) {
312 if (hit.length() >= MIN_EMAIL_ADDR_LENGTH
313 && DomainValidator.getInstance(
true).isValidTld(hit.substring(hit.lastIndexOf(
'.')))) {
314 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
318 case TSK_CARD_NUMBER:
324 Matcher ccnMatcher = CREDIT_CARD_NUM_PATTERN.matcher(hit);
326 for (
int rLength = hit.length(); rLength >= 12; rLength--) {
327 ccnMatcher.region(0, rLength);
328 if (ccnMatcher.find()) {
329 final String group = ccnMatcher.group(
"ccn");
330 if (CreditCardValidator.isValidCCN(group)) {
331 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
338 hits.add(
new KeywordHit(docId, makeSnippet(content, hitMatcher, hit), hit));
345 }
catch (Throwable error) {
354 throw new TskCoreException(
"Failed to create keyword hits for Solr document id " + docId +
" due to " + error.getMessage());
372 private String makeSnippet(String content, Matcher hitMatcher, String hit) {
374 int maxIndex = content.length() - 1;
375 final int end = hitMatcher.end();
376 final int start = hitMatcher.start();
378 return content.substring(Integer.max(0, start - 20), Integer.max(0, start))
379 + SNIPPET_DELIMITER + hit + SNIPPET_DELIMITER
380 + content.substring(Integer.min(maxIndex, end), Integer.min(maxIndex, end + 20));
384 public void addFilter(KeywordQueryFilter filter) {
385 this.filters.add(filter);
389 public void setField(String field) {
394 public void setSubstringQuery() {
398 synchronized public void escape() {
399 if (isEscaped() ==
false) {
400 escapedQuery = KeywordSearchUtil.escapeLuceneQuery(keywordString);
406 synchronized public boolean isEscaped() {
411 public boolean isLiteral() {
416 public String getQueryString() {
417 return originalKeyword.getSearchTerm();
421 synchronized public String getEscapedQueryString() {
422 if (
false == isEscaped()) {
445 public BlackboardArtifact postKeywordHitToBlackboard(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
446 final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
448 if (content == null) {
449 LOGGER.log(Level.WARNING,
"Error adding artifact for keyword hit to blackboard");
456 if (originalKeyword.getArtifactAttributeType() == ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
457 createCCNAccount(content, foundKeyword, hit, snippet, listName);
465 BlackboardArtifact newArtifact;
466 Collection<BlackboardAttribute> attributes =
new ArrayList<>();
468 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, foundKeyword.getSearchTerm()));
469 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_REGEXP, MODULE_NAME, getQueryString()));
472 newArtifact = content.newArtifact(ARTIFACT_TYPE.TSK_KEYWORD_HIT);
473 }
catch (TskCoreException ex) {
474 LOGGER.log(Level.SEVERE,
"Error adding artifact for keyword hit to blackboard", ex);
478 if (StringUtils.isNotBlank(listName)) {
479 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
481 if (snippet != null) {
482 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
485 hit.getArtifactID().ifPresent(artifactID
486 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
489 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
492 newArtifact.addAttributes(attributes);
494 }
catch (TskCoreException e) {
495 LOGGER.log(Level.SEVERE,
"Error adding bb attributes for terms search artifact", e);
500 private void createCCNAccount(Content content, Keyword foundKeyword, KeywordHit hit, String snippet, String listName) {
502 final String MODULE_NAME = KeywordSearchModuleFactory.getModuleName();
504 if (originalKeyword.getArtifactAttributeType() != ATTRIBUTE_TYPE.TSK_CARD_NUMBER) {
505 LOGGER.log(Level.SEVERE,
"Keyword hit is not a credit card number");
513 Collection<BlackboardAttribute> attributes =
new ArrayList<>();
515 Map<BlackboardAttribute.Type, BlackboardAttribute> parsedTrackAttributeMap =
new HashMap<>();
516 Matcher matcher = TermsComponentQuery.CREDIT_CARD_TRACK1_PATTERN.matcher(hit.getSnippet());
517 if (matcher.find()) {
518 parseTrack1Data(parsedTrackAttributeMap, matcher);
520 matcher = CREDIT_CARD_TRACK2_PATTERN.matcher(hit.getSnippet());
521 if (matcher.find()) {
522 parseTrack2Data(parsedTrackAttributeMap, matcher);
524 final BlackboardAttribute ccnAttribute = parsedTrackAttributeMap.get(
new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_CARD_NUMBER));
525 if (ccnAttribute == null || StringUtils.isBlank(ccnAttribute.getValueString())) {
527 if (hit.isArtifactHit()) {
528 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()));
531 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()));
532 }
catch (TskCoreException ex) {
533 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()));
534 LOGGER.log(Level.SEVERE,
"There was a error getting contentID for keyword hit.", ex);
539 attributes.addAll(parsedTrackAttributeMap.values());
545 final int bin = Integer.parseInt(ccnAttribute.getValueString().substring(0, 8));
546 CreditCards.BankIdentificationNumber binInfo = CreditCards.getBINInfo(bin);
547 if (binInfo != null) {
548 binInfo.getScheme().ifPresent(scheme
549 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_SCHEME, MODULE_NAME, scheme)));
550 binInfo.getCardType().ifPresent(cardType
551 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CARD_TYPE, MODULE_NAME, cardType)));
552 binInfo.getBrand().ifPresent(brand
553 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BRAND_NAME, MODULE_NAME, brand)));
554 binInfo.getBankName().ifPresent(bankName
555 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_BANK_NAME, MODULE_NAME, bankName)));
556 binInfo.getBankPhoneNumber().ifPresent(phoneNumber
557 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_PHONE_NUMBER, MODULE_NAME, phoneNumber)));
558 binInfo.getBankURL().ifPresent(url
559 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_URL, MODULE_NAME, url)));
560 binInfo.getCountry().ifPresent(country
561 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_COUNTRY, MODULE_NAME, country)));
562 binInfo.getBankCity().ifPresent(city
563 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_CITY, MODULE_NAME, city)));
571 if (content instanceof AbstractFile) {
572 AbstractFile file = (AbstractFile) content;
573 if (file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNUSED_BLOCKS
574 || file.getType() == TskData.TSK_DB_FILES_TYPE_ENUM.UNALLOC_BLOCKS) {
575 attributes.add(
new BlackboardAttribute(KEYWORD_SEARCH_DOCUMENT_ID, MODULE_NAME, hit.getSolrDocumentId()));
579 if (StringUtils.isNotBlank(listName)) {
580 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_SET_NAME, MODULE_NAME, listName));
582 if (snippet != null) {
583 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_PREVIEW, MODULE_NAME, snippet));
586 hit.getArtifactID().ifPresent(artifactID
587 -> attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT, MODULE_NAME, artifactID))
590 attributes.add(
new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE, MODULE_NAME, KeywordSearch.QueryType.REGEX.ordinal()));
597 AccountFileInstance ccAccountInstance = Case.getOpenCase().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.CREDIT_CARD, ccnAttribute.getValueString() , MODULE_NAME, content);
599 ccAccountInstance.addAttributes(attributes);
601 }
catch (TskCoreException | NoCurrentCaseException ex) {
602 LOGGER.log(Level.SEVERE,
"Error creating CCN account instance", ex);
615 static private void parseTrack2Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributesMap, Matcher matcher) {
616 addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_NUMBER,
"accountNumber", matcher);
617 addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_EXPIRATION,
"expiration", matcher);
618 addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_SERVICE_CODE,
"serviceCode", matcher);
619 addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_DISCRETIONARY,
"discretionary", matcher);
620 addAttributeIfNotAlreadyCaptured(attributesMap, ATTRIBUTE_TYPE.TSK_CARD_LRC,
"LRC", matcher);
632 static private void parseTrack1Data(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, Matcher matcher) {
633 parseTrack2Data(attributeMap, matcher);
634 addAttributeIfNotAlreadyCaptured(attributeMap, ATTRIBUTE_TYPE.TSK_NAME_PERSON,
"name", matcher);
649 static private void addAttributeIfNotAlreadyCaptured(Map<BlackboardAttribute.Type, BlackboardAttribute> attributeMap, ATTRIBUTE_TYPE attrType, String groupName, Matcher matcher) {
650 BlackboardAttribute.Type type =
new BlackboardAttribute.Type(attrType);
652 if( ! attributeMap.containsKey(type)) {
653 String value = matcher.group(groupName);
654 if (attrType.equals(ATTRIBUTE_TYPE.TSK_CARD_NUMBER)) {
655 attributeMap.put(
new BlackboardAttribute.Type(ATTRIBUTE_TYPE.TSK_KEYWORD),
656 new BlackboardAttribute(ATTRIBUTE_TYPE.TSK_KEYWORD, MODULE_NAME, value));
657 value = CharMatcher.anyOf(
" -").removeFrom(value);
660 if (StringUtils.isNotBlank(value)) {
661 attributeMap.put(type,
new BlackboardAttribute(attrType, MODULE_NAME, value));