Autopsy  4.12.0
Graphical digital forensics platform for The Sleuth Kit and other tools.
VcardParser.java
Go to the documentation of this file.
1 /*
2  * Autopsy Forensic Browser
3  *
4  * Copyright 2019 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.thunderbirdparser;
20 
21 import ezvcard.Ezvcard;
22 import ezvcard.VCard;
23 import ezvcard.parameter.EmailType;
24 import ezvcard.parameter.TelephoneType;
25 import ezvcard.property.Email;
26 import ezvcard.property.Organization;
27 import ezvcard.property.Photo;
28 import ezvcard.property.Telephone;
29 import ezvcard.property.Url;
30 import java.io.File;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.nio.file.Paths;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.logging.Level;
41 import org.apache.commons.lang3.StringUtils;
42 import org.openide.util.NbBundle;
51 import static org.sleuthkit.autopsy.thunderbirdparser.ThunderbirdMboxFileIngestModule.getRelModuleOutputPath;
52 import org.sleuthkit.datamodel.AbstractFile;
53 import org.sleuthkit.datamodel.Account;
54 import org.sleuthkit.datamodel.AccountFileInstance;
55 import org.sleuthkit.datamodel.Blackboard;
56 import org.sleuthkit.datamodel.BlackboardArtifact;
57 import org.sleuthkit.datamodel.BlackboardAttribute;
58 import org.sleuthkit.datamodel.Content;
59 import org.sleuthkit.datamodel.DataSource;
60 import org.sleuthkit.datamodel.ReadContentInputStream;
61 import org.sleuthkit.datamodel.Relationship;
62 import org.sleuthkit.datamodel.SleuthkitCase;
63 import org.sleuthkit.datamodel.TskCoreException;
64 import org.sleuthkit.datamodel.TskData;
65 import org.sleuthkit.datamodel.TskDataException;
66 import org.sleuthkit.datamodel.TskException;
67 
72 final class VcardParser {
73  private static final String VCARD_HEADER = "BEGIN:VCARD";
74  private static final long MIN_FILE_SIZE = 22;
75 
76  private static final String PHOTO_TYPE_BMP = "bmp";
77  private static final String PHOTO_TYPE_GIF = "gif";
78  private static final String PHOTO_TYPE_JPEG = "jpeg";
79  private static final String PHOTO_TYPE_PNG = "png";
80  private static final Map<String, String> photoTypeExtensions;
81  static {
82  photoTypeExtensions = new HashMap<>();
83  photoTypeExtensions.put(PHOTO_TYPE_BMP, ".bmp");
84  photoTypeExtensions.put(PHOTO_TYPE_GIF, ".gif");
85  photoTypeExtensions.put(PHOTO_TYPE_JPEG, ".jpg");
86  photoTypeExtensions.put(PHOTO_TYPE_PNG, ".png");
87  }
88 
89  private static final Logger logger = Logger.getLogger(VcardParser.class.getName());
90 
91  private final IngestServices services = IngestServices.getInstance();
92  private final FileManager fileManager;
93  private final IngestJobContext context;
94  private final Blackboard blackboard;
95  private final Case currentCase;
96  private final SleuthkitCase tskCase;
97 
101  VcardParser(Case currentCase, IngestJobContext context) {
102  this.context = context;
103  this.currentCase = currentCase;
104  tskCase = currentCase.getSleuthkitCase();
105  blackboard = tskCase.getBlackboard();
106  fileManager = currentCase.getServices().getFileManager();
107  }
108 
116  static boolean isVcardFile(Content content) {
117  try {
118  if (content.getSize() > MIN_FILE_SIZE) {
119  byte[] buffer = new byte[VCARD_HEADER.length()];
120  int byteRead = content.read(buffer, 0, VCARD_HEADER.length());
121  if (byteRead > 0) {
122  String header = new String(buffer);
123  return header.equalsIgnoreCase(VCARD_HEADER);
124  }
125  }
126  } catch (TskException ex) {
127  logger.log(Level.WARNING, String.format("Exception while detecting if the file '%s' (id=%d) is a vCard file.",
128  content.getName(), content.getId())); //NON-NLS
129  }
130 
131  return false;
132  }
133 
145  void parse(AbstractFile abstractFile) throws IOException, NoCurrentCaseException {
146  for (VCard vcard: Ezvcard.parse(new ReadContentInputStream(abstractFile)).all()) {
147  addContactArtifact(vcard, abstractFile);
148  }
149  }
150 
151 
152 
163  @NbBundle.Messages({"VcardParser.addContactArtifact.indexError=Failed to index the contact artifact for keyword search."})
164  private BlackboardArtifact addContactArtifact(VCard vcard, AbstractFile abstractFile) throws NoCurrentCaseException {
165  List<BlackboardAttribute> attributes = new ArrayList<>();
166  List<AccountFileInstance> accountInstances = new ArrayList<>();
167 
168  String name = "";
169  if (vcard.getFormattedName() != null) {
170  name = vcard.getFormattedName().getValue();
171  } else {
172  if (vcard.getStructuredName() != null) {
173  // Attempt to put the name together if there was no formatted version
174  for (String prefix:vcard.getStructuredName().getPrefixes()) {
175  name += prefix + " ";
176  }
177  if (vcard.getStructuredName().getGiven() != null) {
178  name += vcard.getStructuredName().getGiven() + " ";
179  }
180  if (vcard.getStructuredName().getFamily() != null) {
181  name += vcard.getStructuredName().getFamily() + " ";
182  }
183  for (String suffix:vcard.getStructuredName().getSuffixes()) {
184  name += suffix + " ";
185  }
186  if (! vcard.getStructuredName().getAdditionalNames().isEmpty()) {
187  name += "(";
188  for (String addName:vcard.getStructuredName().getAdditionalNames()) {
189  name += addName + " ";
190  }
191  name += ")";
192  }
193  }
194  }
195  ThunderbirdMboxFileIngestModule.addArtifactAttribute(name, BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME, attributes);
196 
197  for (Telephone telephone : vcard.getTelephoneNumbers()) {
198  addPhoneAttributes(telephone, abstractFile, attributes);
199  addPhoneAccountInstances(telephone, abstractFile, accountInstances);
200  }
201 
202  for (Email email : vcard.getEmails()) {
203  addEmailAttributes(email, abstractFile, attributes);
204  addEmailAccountInstances(email, abstractFile, accountInstances);
205  }
206 
207  for (Url url : vcard.getUrls()) {
208  ThunderbirdMboxFileIngestModule.addArtifactAttribute(url.getValue(), BlackboardAttribute.ATTRIBUTE_TYPE.TSK_URL, attributes);
209  }
210 
211  for (Organization organization : vcard.getOrganizations()) {
212  List<String> values = organization.getValues();
213  if (values.isEmpty() == false) {
214  ThunderbirdMboxFileIngestModule.addArtifactAttribute(values.get(0), BlackboardAttribute.ATTRIBUTE_TYPE.TSK_ORGANIZATION, attributes);
215  }
216  }
217 
218  AccountFileInstance deviceAccountInstance = addDeviceAccountInstance(abstractFile);
219 
220  BlackboardArtifact artifact = null;
221  org.sleuthkit.datamodel.Blackboard tskBlackboard = tskCase.getBlackboard();
222  try {
223  // Create artifact if it doesn't already exist.
224  if (!tskBlackboard.artifactExists(abstractFile, BlackboardArtifact.ARTIFACT_TYPE.TSK_CONTACT, attributes)) {
225  artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_CONTACT);
226  artifact.addAttributes(attributes);
227  List<BlackboardArtifact> blackboardArtifacts = new ArrayList<>();
228  blackboardArtifacts.add(artifact);
229 
230  extractPhotos(vcard, abstractFile, artifact);
231 
232  // Add account relationships.
233  if (deviceAccountInstance != null) {
234  try {
235  currentCase.getSleuthkitCase().getCommunicationsManager().addRelationships(
236  deviceAccountInstance, accountInstances, artifact, Relationship.Type.CONTACT, abstractFile.getCrtime());
237  } catch (TskDataException ex) {
238  logger.log(Level.SEVERE, String.format("Failed to create phone and e-mail account relationships (fileName='%s'; fileId=%d; accountId=%d).",
239  abstractFile.getName(), abstractFile.getId(), deviceAccountInstance.getAccount().getAccountID()), ex); //NON-NLS
240  }
241  }
242 
243  // Index the artifact for keyword search.
244  try {
245  blackboard.postArtifact(artifact, EmailParserModuleFactory.getModuleName());
246  } catch (Blackboard.BlackboardException ex) {
247  logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex); //NON-NLS
248  MessageNotifyUtil.Notify.error(Bundle.VcardParser_addContactArtifact_indexError(), artifact.getDisplayName());
249  }
250  }
251  } catch (TskCoreException ex) {
252  logger.log(Level.SEVERE, String.format("Failed to create contact artifact for vCard file '%s' (id=%d).",
253  abstractFile.getName(), abstractFile.getId()), ex); //NON-NLS
254  }
255 
256  return artifact;
257  }
258 
267  private void extractPhotos(VCard vcard, AbstractFile abstractFile, BlackboardArtifact artifact) throws NoCurrentCaseException {
268  String parentFileName = getUniqueName(abstractFile);
269  // Skip files that already have been extracted.
270  try {
271  String outputPath = getOutputFolderPath(parentFileName);
272  if (new File(outputPath).exists()) {
273  List<Photo> vcardPhotos = vcard.getPhotos();
274  List<AbstractFile> derivedFilesCreated = new ArrayList<>();
275  for (int i=0; i < vcardPhotos.size(); i++) {
276  Photo photo = vcardPhotos.get(i);
277 
278  if (photo.getUrl() != null) {
279  // Skip this photo since its data is not embedded.
280  continue;
281  }
282 
283  String type = photo.getType();
284  if (type == null) {
285  // Skip this photo since no type is defined.
286  continue;
287  }
288 
289  // Get the file extension for the subtype.
290  type = type.toLowerCase();
291  if (type.startsWith("image/")) {
292  type = type.substring(6);
293  }
294  String extension = photoTypeExtensions.get(type);
295 
296  // Read the photo data and create a derived file from it.
297  byte[] data = photo.getData();
298  String extractedFileName = String.format("photo_%d%s", i, extension == null ? "" : extension);
299  String extractedFilePath = Paths.get(outputPath, extractedFileName).toString();
300  try {
301  writeExtractedImage(extractedFilePath, data);
302  derivedFilesCreated.add(fileManager.addDerivedFile(extractedFileName, getFileRelativePath(parentFileName, extractedFileName), data.length,
303  abstractFile.getCtime(), abstractFile.getCrtime(), abstractFile.getAtime(), abstractFile.getAtime(),
304  true, artifact, null, EmailParserModuleFactory.getModuleName(), EmailParserModuleFactory.getModuleVersion(), "", TskData.EncodingType.NONE));
305  } catch (IOException | TskCoreException ex) {
306  logger.log(Level.WARNING, String.format("Could not write image to '%s' (id=%d).", extractedFilePath, abstractFile.getId()), ex); //NON-NLS
307  }
308  }
309  if (!derivedFilesCreated.isEmpty()) {
310  services.fireModuleContentEvent(new ModuleContentEvent(abstractFile));
311  context.addFilesToJob(derivedFilesCreated);
312  }
313  }
314  else {
315  logger.log(Level.INFO, String.format("Skipping photo extraction for file '%s' (id=%d), because it has already been processed.",
316  abstractFile.getName(), abstractFile.getId())); //NON-NLS
317  }
318  } catch (SecurityException ex) {
319  logger.log(Level.WARNING, String.format("Could not create extraction folder for '%s' (id=%d).", parentFileName, abstractFile.getId()));
320  }
321  }
322 
330  private void writeExtractedImage(String outputPath, byte[] data) throws IOException {
331  File outputFile = new File(outputPath);
332  FileOutputStream outputStream = new FileOutputStream(outputFile);
333  outputStream.write(data);
334  }
335 
344  private String getUniqueName(AbstractFile file) {
345  return file.getName() + "_" + file.getId();
346  }
347 
357  private String getFileRelativePath(String parentFileName, String fileName) throws NoCurrentCaseException {
358  // Used explicit FWD slashes to maintain DB consistency across operating systems.
359  return Paths.get(getRelModuleOutputPath(), parentFileName, fileName).toString();
360  }
361 
372  private String getOutputFolderPath(String parentFileName) throws NoCurrentCaseException {
373  String outputFolderPath = ThunderbirdMboxFileIngestModule.getModuleOutputPath() + File.separator + parentFileName;
374  File outputFilePath = new File(outputFolderPath);
375  if (!outputFilePath.exists()) {
376  outputFilePath.mkdirs();
377  }
378  return outputFolderPath;
379  }
380 
389  private void addPhoneAttributes(Telephone telephone, AbstractFile abstractFile, Collection<BlackboardAttribute> attributes) {
390  String telephoneText = telephone.getText();
391  if (telephoneText == null || telephoneText.isEmpty()) {
392  return;
393  }
394 
395  // Add phone number to collection for later creation of TSK_CONTACT.
396  List<TelephoneType> telephoneTypes = telephone.getTypes();
397  if (telephoneTypes.isEmpty()) {
398  ThunderbirdMboxFileIngestModule.addArtifactAttribute(telephone.getText(), BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PHONE_NUMBER, attributes);
399  } else {
400  for (TelephoneType type : telephoneTypes) {
401  /*
402  * Unfortunately, if the types are lower-case, they don't
403  * get separated correctly into individual TelephoneTypes by
404  * ez-vcard. Therefore, we must read them manually
405  * ourselves.
406  */
407  List<String> splitTelephoneTypes = Arrays.asList(
408  type.getValue().toUpperCase().replaceAll("\\s+","").split(","));
409 
410  for (String splitType : splitTelephoneTypes) {
411  String attributeTypeName = "TSK_PHONE_NUMBER_" + splitType;
412  try {
413  BlackboardAttribute.Type attributeType = tskCase.getAttributeType(attributeTypeName);
414  if (attributeType == null) {
415  // Add this attribute type to the case database.
416  attributeType = tskCase.addArtifactAttributeType(attributeTypeName,
417  BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.STRING,
418  String.format("Phone (%s)", StringUtils.capitalize(splitType.toLowerCase())));
419  }
420  ThunderbirdMboxFileIngestModule.addArtifactAttribute(telephone.getText(), attributeType, attributes);
421  } catch (TskCoreException ex) {
422  logger.log(Level.SEVERE, String.format("Unable to retrieve attribute type '%s' for file '%s' (id=%d).", attributeTypeName, abstractFile.getName(), abstractFile.getId()), ex);
423  } catch (TskDataException ex) {
424  logger.log(Level.SEVERE, String.format("Unable to add custom attribute type '%s' for file '%s' (id=%d).", attributeTypeName, abstractFile.getName(), abstractFile.getId()), ex);
425  }
426  }
427  }
428  }
429  }
430 
439  private void addEmailAttributes(Email email, AbstractFile abstractFile, Collection<BlackboardAttribute> attributes) {
440  String emailValue = email.getValue();
441  if (emailValue == null || emailValue.isEmpty()) {
442  return;
443  }
444 
445  // Add phone number to collection for later creation of TSK_CONTACT.
446  List<EmailType> emailTypes = email.getTypes();
447  if (emailTypes.isEmpty()) {
448  ThunderbirdMboxFileIngestModule.addArtifactAttribute(email.getValue(), BlackboardAttribute.ATTRIBUTE_TYPE.TSK_EMAIL, attributes);
449  } else {
450  for (EmailType type : emailTypes) {
451  /*
452  * Unfortunately, if the types are lower-case, they don't
453  * get separated correctly into individual EmailTypes by
454  * ez-vcard. Therefore, we must read them manually
455  * ourselves.
456  */
457  List<String> splitEmailTypes = Arrays.asList(
458  type.getValue().toUpperCase().replaceAll("\\s+","").split(","));
459 
460  for (String splitType : splitEmailTypes) {
461  String attributeTypeName = "TSK_EMAIL_" + splitType;
462  try {
463  BlackboardAttribute.Type attributeType = tskCase.getAttributeType(attributeTypeName);
464  if (attributeType == null) {
465  // Add this attribute type to the case database.
466  attributeType = tskCase.addArtifactAttributeType(attributeTypeName,
467  BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.STRING,
468  String.format("Email (%s)", StringUtils.capitalize(splitType.toLowerCase())));
469  }
470  ThunderbirdMboxFileIngestModule.addArtifactAttribute(email.getValue(), attributeType, attributes);
471  } catch (TskCoreException ex) {
472  logger.log(Level.SEVERE, String.format("Unable to retrieve attribute type '%s' for file '%s' (id=%d).", attributeTypeName, abstractFile.getName(), abstractFile.getId()), ex);
473  } catch (TskDataException ex) {
474  logger.log(Level.SEVERE, String.format("Unable to add custom attribute type '%s' for file '%s' (id=%d).", attributeTypeName, abstractFile.getName(), abstractFile.getId()), ex);
475  }
476  }
477  }
478  }
479  }
480 
490  private void addPhoneAccountInstances(Telephone telephone, AbstractFile abstractFile, Collection<AccountFileInstance> accountInstances) {
491  String telephoneText = telephone.getText();
492  if (telephoneText == null || telephoneText.isEmpty()) {
493  return;
494  }
495 
496  // Add phone number as a TSK_ACCOUNT.
497  try {
498  AccountFileInstance phoneAccountInstance = tskCase.getCommunicationsManager().createAccountFileInstance(Account.Type.PHONE,
499  telephoneText, EmailParserModuleFactory.getModuleName(), abstractFile);
500  accountInstances.add(phoneAccountInstance);
501  }
502  catch(TskCoreException ex) {
503  logger.log(Level.WARNING, String.format(
504  "Failed to create account for phone number '%s' (content='%s'; id=%d).",
505  telephoneText, abstractFile.getName(), abstractFile.getId()), ex); //NON-NLS
506  }
507  }
508 
518  private void addEmailAccountInstances(Email email, AbstractFile abstractFile, Collection<AccountFileInstance> accountInstances) {
519  String emailValue = email.getValue();
520  if (emailValue == null || emailValue.isEmpty()) {
521  return;
522  }
523 
524  // Add e-mail as a TSK_ACCOUNT.
525  try {
526  AccountFileInstance emailAccountInstance = tskCase.getCommunicationsManager().createAccountFileInstance(Account.Type.EMAIL,
527  emailValue, EmailParserModuleFactory.getModuleName(), abstractFile);
528  accountInstances.add(emailAccountInstance);
529  }
530  catch(TskCoreException ex) {
531  logger.log(Level.WARNING, String.format(
532  "Failed to create account for e-mail address '%s' (content='%s'; id=%d).",
533  emailValue, abstractFile.getName(), abstractFile.getId()), ex); //NON-NLS
534  }
535  }
536 
544  private AccountFileInstance addDeviceAccountInstance(AbstractFile abstractFile) {
545  // Add 'DEVICE' TSK_ACCOUNT.
546  AccountFileInstance deviceAccountInstance = null;
547  String deviceId = null;
548  try {
549  long dataSourceObjId = abstractFile.getDataSourceObjectId();
550  DataSource dataSource = tskCase.getDataSource(dataSourceObjId);
551  deviceId = dataSource.getDeviceId();
552  deviceAccountInstance = tskCase.getCommunicationsManager().createAccountFileInstance(Account.Type.DEVICE,
553  deviceId, EmailParserModuleFactory.getModuleName(), abstractFile);
554  }
555  catch (TskCoreException ex) {
556  logger.log(Level.WARNING, String.format(
557  "Failed to create device account for '%s' (content='%s'; id=%d).",
558  deviceId, abstractFile.getName(), abstractFile.getId()), ex); //NON-NLS
559  }
560  catch (TskDataException ex) {
561  logger.log(Level.WARNING, String.format(
562  "Failed to get the data source from the case database (id=%d).",
563  abstractFile.getId()), ex); //NON-NLS
564  }
565 
566  return deviceAccountInstance;
567  }
568 }

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