-
Notifications
You must be signed in to change notification settings - Fork 447
Expand file tree
/
Copy pathUfedXmlReader.java
More file actions
1612 lines (1383 loc) · 72.7 KB
/
UfedXmlReader.java
File metadata and controls
1612 lines (1383 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package iped.engine.datasource;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tika.metadata.Message;
import org.apache.tika.metadata.Property;
import org.apache.tika.mime.MediaType;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import iped.data.ICaseData;
import iped.data.IItem;
import iped.datasource.IDataSource;
import iped.engine.config.ConfigurationManager;
import iped.engine.config.ParsingTaskConfig;
import iped.engine.core.Manager;
import iped.engine.data.CaseData;
import iped.engine.data.DataSource;
import iped.engine.data.Item;
import iped.engine.datasource.ufed.UfedModelHandler;
import iped.engine.datasource.ufed.UfedModelHandler.UfedModelListener;
import iped.engine.io.MetadataInputStreamFactory;
import iped.engine.io.UFDRInputStreamFactory;
import iped.engine.io.UFEDXMLWrapper;
import iped.engine.localization.Messages;
import iped.engine.task.ExportFileTask;
import iped.engine.task.die.DIETask;
import iped.engine.util.Util;
import iped.parsers.telegram.TelegramParser;
import iped.parsers.ufed.UfedChatParser;
import iped.parsers.ufed.model.BaseModel;
import iped.parsers.ufed.model.Chat;
import iped.parsers.util.MetadataUtil;
import iped.parsers.util.PhoneParsingConfig;
import iped.parsers.whatsapp.WhatsAppParser;
import iped.properties.ExtraProperties;
import iped.properties.MediaTypes;
import iped.utils.FileInputStreamFactory;
import iped.utils.IOUtil;
import iped.utils.LocalizedFormat;
import iped.utils.SimpleHTMLEncoder;
public class UfedXmlReader extends DataSourceReader {
private static Logger LOGGER = LogManager.getLogger(UfedXmlReader.class);
private final Level CONSOLE = Level.getLevel("MSG"); //$NON-NLS-1$
private static final String[] HEADER_STRINGS = { "project id", "extractionType", "sourceExtractions" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
private static final byte[] UFDR_PROTECTION_NO_PASSWORD_REPORT_XML_INITIAL_BYTES = new byte[] { 0x2D, 0x06, 0x52, 0x6D };
private static final int UFDR_REPORT_XML_INITIAL_BYTES_TO_READ = 1024;
private static final String UFDR_EXTENSION = "ufdr";
private static final String XML_REPORT_EXTENSION = "xml";
private static final String AVATAR_PATH_META = ExtraProperties.UFED_META_PREFIX + "contactphoto_extracted_path"; //$NON-NLS-1$
private static final String ATTACH_PATH_META = ExtraProperties.UFED_META_PREFIX + "attachment_extracted_path"; //$NON-NLS-1$
private static final String MEDIA_CLASSES_PROPERTY = ExtraProperties.UFED_META_PREFIX + "mediaClasses"; //$NON-NLS-1$
private static final String MEDIA_CLASSES_SCORE_PREFIX = ExtraProperties.UFED_META_PREFIX + "mediaClassScore:"; //$NON-NLS-1$
private static final float MEDIA_CLASSES_THRESHOLD = 50.0f;
private static final double MISSING_FRAME_SCORE = 49.99f;
public static final String UFED_ID = ExtraProperties.UFED_META_PREFIX + "id"; //$NON-NLS-1$
public static final String UFED_MIME_PREFIX = MediaTypes.UFED_MIME_PREFIX;
public static final String UFED_EMAIL_MIME = MediaTypes.UFED_EMAIL_MIME.toString();
public static final String UFED_CONTACTPHOTO_MIME = UFED_MIME_PREFIX + "contactphoto";
public static final String UFED_NATIVE_SCENE_CLASSIFICATION = ExtraProperties.UFED_META_PREFIX + "Native Scene Classification";
public static final String MSISDN_PROP = "MSISDN";
private static final String EMPTY_EXTRACTION_STR = "-";
private static final String FILE_ID_ATTR = ExtraProperties.UFED_META_PREFIX + "file_id"; //$NON-NLS-1$
private static final String LOCAL_PATH_META = ExtraProperties.UFED_META_PREFIX + "local_path"; //$NON-NLS-1$
public static final String META_PHONE_OWNER = ExtraProperties.UFED_META_PREFIX + "phoneOwner";
public static final String META_FROM_OWNER = ExtraProperties.UFED_META_PREFIX + "fromOwner";
public static final String CHILD_MSG_IDS = ExtraProperties.UFED_META_PREFIX + "msgChildIds";
public static final String ATTACHED_MEDIA_MSG = "ATTACHED_MEDIA: ";
private Set<String> supportedApps = new HashSet<String>(Arrays.asList(WhatsAppParser.WHATSAPP,
TelegramParser.TELEGRAM, WhatsAppParser.WHATSAPP + " Business", WhatsAppParser.WHATSAPP + " (Dual App)"));
private static HashMap<File, UFDRInputStreamFactory> uisfMap = new HashMap<>();
File root, rootFolder, ufdrFile;
UFDRInputStreamFactory uisf;
FileInputStreamFactory fisf, previewFisf;
IItem rootItem;
IItem decodedFolder;
HashMap<String, IItem> pathToParent = new HashMap<>();
boolean ignoreSupportedChats = false;
HashMap<String, String> ufdrPathToUfedId = new HashMap<>();
HashMap<String, String> ufedFileIdToLocalPath = new HashMap<>(); // used to replace non-existent attachment extracted path by local path
private final List<String[]> deviceInfoData = new ArrayList<String[]>();
private HashSet<String> addedTrackIds = new HashSet<>();
HashMap<String, String> md5ToLocalPath = new HashMap<>();
public UfedXmlReader(ICaseData caseData, File output, boolean listOnly) {
super(caseData, output, listOnly);
}
@Override
public boolean isSupported(File datasource) {
if (FilenameUtils.isExtension(datasource.getName(), UFDR_EXTENSION)) {
return true;
}
// supports any folder with valid XML report inside
InputStream xmlReport = lookUpXmlReportInputStream(datasource);
IOUtil.closeQuietly(xmlReport);
return xmlReport != null;
}
private InputStream getXmlInputStream(File file) {
if (FilenameUtils.isExtension(file.getName(), XML_REPORT_EXTENSION)) {
try (InputStream fis = new FileInputStream(file)) {
byte[] initialBytes = fis.readNBytes(UFDR_REPORT_XML_INITIAL_BYTES_TO_READ);
if (!containsHeaderStrings(initialBytes)) {
return null;
}
return new FileInputStream(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else if (FilenameUtils.isExtension(file.getName(), UFDR_EXTENSION)) {
try {
ufdrFile = file;
String xml = "report.xml";
if (!getUISF().entryExists(xml)) {
xml = "Report.xml";
if (!getUISF().entryExists(xml)) {
return null;
}
}
return getUISF().getSeekableInputStream(xml);
} catch (Exception e) {
throw new RuntimeException("Invalid UFDR file " + file.getAbsolutePath(), e);
}
}
return null;
}
private boolean isReportXmlProtected(byte[] initialBytes) {
int len = UFDR_PROTECTION_NO_PASSWORD_REPORT_XML_INITIAL_BYTES.length;
return Arrays.equals(initialBytes, 0, len, UFDR_PROTECTION_NO_PASSWORD_REPORT_XML_INITIAL_BYTES, 0, len);
}
private boolean containsHeaderStrings(byte[] initialBytes) {
String header = new String(initialBytes, StandardCharsets.UTF_8);
for (String str : HEADER_STRINGS)
if (header.contains(str))
return true;
return false;
}
private boolean entryExists(String entryPath) {
if (ufdrFile != null) {
return getUISF().entryExists(entryPath);
} else {
return Files.exists(root.toPath().resolve(entryPath));
}
}
private UFDRInputStreamFactory getUISF() {
if (uisf == null) {
synchronized (uisfMap) {
uisf = uisfMap.get(ufdrFile);
if (uisf == null) {
uisf = new UFDRInputStreamFactory(ufdrFile.toPath());
uisfMap.put(ufdrFile, uisf);
}
}
}
return uisf;
}
private FileInputStreamFactory getFISF() {
if (fisf == null) {
synchronized (root) {
if (fisf == null) {
rootFolder = root.isDirectory() ? root : root.getParentFile();
fisf = new FileInputStreamFactory(rootFolder.toPath());
}
}
}
return fisf;
}
private InputStream lookUpXmlReportInputStream(File root) {
if (root.isFile())
return getXmlInputStream(root);
for (File file : FileUtils.listFiles(root, new String[]{XML_REPORT_EXTENSION}, false)) {
InputStream is = getXmlInputStream(file);
if (is != null)
return is;
}
return null;
}
@Override
public void read(File root) throws Exception {
read(root, null);
}
@Override
public void read(File root, Item parent) throws Exception {
this.root = root;
addRootItem(parent);
addVirtualDecodedFolder();
InputStream xmlStream = null;
try {
xmlStream = lookUpXmlReportInputStream(root);
validateXmlStream(xmlStream);
configureParsers();
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new XMLContentHandler(xmlReader));
xmlReader.setErrorHandler(new XMLErrorHandler());
xmlReader.parse(new InputSource(new UFEDXMLWrapper(xmlStream)));
} finally {
IOUtil.closeQuietly(xmlStream);
}
}
private void validateXmlStream(InputStream xmlStream) throws IOException {
if (xmlStream == null) {
if (root.isFile()) {
throw new RuntimeException("Invalid UFDR file: XML report not found. File: " + root.getAbsolutePath());
} else {
throw new RuntimeException("Invalid UFDR folder: No XML report has been found. Folder: " + root.getAbsolutePath());
}
}
if (root.isFile()) {
xmlStream.mark(0);
byte[] initialBytes = xmlStream.readNBytes(UFDR_REPORT_XML_INITIAL_BYTES_TO_READ);
if (isReportXmlProtected(initialBytes)) {
throw new RuntimeException(
"Unsupported UFDR file: protection is enabled. Generate the UFDR file again with protection disabled. File: "
+ root.getAbsolutePath());
}
if (!containsHeaderStrings(initialBytes)) {
throw new RuntimeException("Invalid UFDR file: XML report is not valid. "
+ "Protection may be enabled. Generate the UFDR file again with protection disabled. File: " + root.getAbsolutePath());
}
xmlStream.reset();
}
}
private void configureParsers() {
configureParsers(false);
}
private void configureParsers(boolean isIOS) {
ParsingTaskConfig parsingConfig = ConfigurationManager.get().findObject(ParsingTaskConfig.class);
PhoneParsingConfig.setUfdrReaderName(UfedXmlReader.class.getSimpleName());
try {
supportedApps = new HashSet<String>(Arrays.asList(parsingConfig.getInternalParsersList().split("\\s*,\\s*")));
} catch (Exception e) {
LOGGER.warn("Failed to parse {} parameter from {}. Using default internal value: {}", ParsingTaskConfig.SOURCES_WITH_PARSERS, ParsingTaskConfig.CONF_FILE, supportedApps.toString());
}
if (!TelegramParser.isEnabledForUfdr()) {
supportedApps.remove(TelegramParser.TELEGRAM);
}
if (parsingConfig.getPhoneParsersToUse().equalsIgnoreCase("internal")) { //$NON-NLS-1$
UfedChatParser.setSupportedTypes(Collections.singleton(UfedChatParser.UFED_CHAT_MIME));
ignoreSupportedChats = true;
} else if (parsingConfig.getPhoneParsersToUse().equalsIgnoreCase("external")) { //$NON-NLS-1$
PhoneParsingConfig.enableExternalPhoneParsersOnly();
}
}
private void addRootItem(IItem parent) throws InterruptedException {
if (listOnly)
return;
String evidenceName = getEvidenceName(root);
IDataSource evidenceSource = new DataSource(root);
evidenceSource.setName(evidenceName);
rootItem = new Item();
rootItem.setDataSource(evidenceSource);
rootItem.setIdInDataSource("");
rootItem.setHasChildren(true);
if (FilenameUtils.isExtension(root.getName(), UFDR_EXTENSION)) {
rootItem.setLength(root.length());
rootItem.setSumVolume(false);
}
// rootItem.setLength(0L);
rootItem.setHash(""); //$NON-NLS-1$
if (parent != null) {
rootItem.setName(root.getName());
rootItem.setParent(parent);
rootItem.setPath(parent.getPath() + "/" + root.getName());
} else {
rootItem.setPath(evidenceName);
rootItem.setRoot(true);
rootItem.setName(evidenceName);
}
rootItem.setExtraAttribute(ExtraProperties.DATASOURCE_READER, this.getClass().getSimpleName());
pathToParent.put(rootItem.getPath(), rootItem);
caseData.incDiscoveredEvidences(1);
Manager.getInstance().addItemToQueue(rootItem);
}
private void addVirtualDecodedFolder() throws InterruptedException {
if (listOnly)
return;
decodedFolder = new Item();
decodedFolder.setName("_DecodedData"); //$NON-NLS-1$
decodedFolder.setParent(rootItem);
decodedFolder.setIdInDataSource("");
decodedFolder.setPath(rootItem.getPath() + "/" + decodedFolder.getName()); //$NON-NLS-1$
decodedFolder.setIsDir(true);
decodedFolder.setHasChildren(true);
decodedFolder.setHash(""); //$NON-NLS-1$
decodedFolder.setExtraAttribute(ExtraProperties.DATASOURCE_READER, UfedXmlReader.class.getSimpleName());
pathToParent.put(decodedFolder.getPath(), decodedFolder);
caseData.incDiscoveredEvidences(1);
Manager.getInstance().addItemToQueue(decodedFolder);
}
private class XMLErrorHandler implements ErrorHandler {
@Override
public void warning(SAXParseException exception) throws SAXException {
}
@Override
public void error(SAXParseException exception) throws SAXException {
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
exception.printStackTrace();
}
}
private class XMLContentHandler implements ContentHandler, UfedModelListener {
private static final String LAST_USE_PREFIX = "last known use:";
private final StringBuilder chars = new StringBuilder();
HashMap<String, String> extractionInfoMap = new HashMap<String, String>();
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); //$NON-NLS-1$
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); //$NON-NLS-1$
DateFormat df3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); //$NON-NLS-1$
DateFormat df4 = new SimpleDateFormat("dd-MMM-yy hh:mm:ss XXX"); //$NON-NLS-1$
DateFormat df5 = new SimpleDateFormat("dd-MMM-yy hh:mm:ss XXX"); //$NON-NLS-1$
DateFormat df6 = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss XXX"); //$NON-NLS-1$
DateFormat[] dfs = { df1, df2, df3, df4, df5, df6 };
DateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
private final DecimalFormat currencyFormat = LocalizedFormat.getDecimalInstance("#,##0.00");
Stack<XmlNode> nodeSeq = new Stack<>();
Stack<Item> itemSeq = new Stack<>();
HashSet<String> elements = new HashSet<>();
HashSet<String> ownerParties = new HashSet<>();
List<String> msisdns = new ArrayList<>();
TreeMap<Date, String> lastUseToMsisdn = new TreeMap<>();
TreeMap<Date, String> iphoneSimSwitch = new TreeMap<>();
private XMLReader xmlReader;
private class XmlNode {
String element;
HashMap<String, String> atts = new HashMap<>();
private XmlNode(String element, Attributes atts) {
this.element = element;
for (int i = 0; i < atts.getLength(); i++) {
this.atts.put(atts.getQName(i), atts.getValue(i));
}
}
}
HashSet<String> ignoreAttrs = new HashSet<>(Arrays.asList("type", //$NON-NLS-1$
"path", //$NON-NLS-1$
"size", //$NON-NLS-1$
"deleted", //$NON-NLS-1$
"deleted_state" //$NON-NLS-1$
));
HashSet<String> ignoreNameAttrs = new HashSet<>(Arrays.asList("Tags", //$NON-NLS-1$
"CreationTime", //$NON-NLS-1$
"ModifyTime", //$NON-NLS-1$
"AccessTime", //$NON-NLS-1$
"CoreFileSystemFileSystemNodeCreationTime", //$NON-NLS-1$
"CoreFileSystemFileSystemNodeModifyTime", //$NON-NLS-1$
"CoreFileSystemFileSystemNodeLastAccessTime", //$NON-NLS-1$
"UserMapping",
"source"
));
HashSet<String> mergeInParentNode = new HashSet<>(Arrays.asList("Party", //$NON-NLS-1$
"PhoneNumber", //$NON-NLS-1$
"EmailAddress", //$NON-NLS-1$
"Coordinate", //$NON-NLS-1$
"Organization", //$NON-NLS-1$
"UserID", //$NON-NLS-1$
"ContactPhoto", //$NON-NLS-1$
"ForwardedMessageData", //$NON-NLS-1$
"ReplyMessageData", //$NON-NLS-1$
"StreetAddress", //$NON-NLS-1$
"ContactEntry", //$NON-NLS-1$
"KeyValueModel", //$NON-NLS-1$
"MessageLabel", //$NON-NLS-1$
"ProfilePicture", //$NON-NLS-1$
"WebAddress", //$NON-NLS-1$
"Reaction", //$NON-NLS-1$
"Price",
"QuotedMessageData"
));
public XMLContentHandler(XMLReader xmlReader) {
this.xmlReader = xmlReader;
}
@Override
public void setDocumentLocator(Locator locator) {
// TODO Auto-generated method stub
}
@Override
public void startDocument() throws SAXException {
// TODO remover timezone da exibição? obter da linha de comando?
for (DateFormat df : dfs) {
df.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
}
out.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$
}
private Date parseDate(String value) throws ParseException {
for (DateFormat df : dfs) {
try {
return df.parse(value);
} catch (ParseException e) {
// ignore
}
}
throw new ParseException("No dateformat configured for value " + value, 0);
}
@Override
public void endDocument() throws SAXException {
/*
* for(String s : elements) System.out.println("element: " + s); for(String s :
* types) System.out.println("type: " + s);
*/
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
// TODO Auto-generated method stub
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
// TODO Auto-generated method stub
}
private IItem getParent(String path) throws SAXException {
int idx = path.lastIndexOf('/');
if (idx < 1)
return rootItem;
String parentPath = path.substring(0, idx);
IItem parent = pathToParent.get(parentPath);
if (parent != null)
return parent;
parent = new Item();
parent.setName(parentPath.substring(parentPath.lastIndexOf('/') + 1));
parent.setPath(parentPath);
parent.setHasChildren(true);
parent.setIsDir(true);
// parent.setLength(0L);
parent.setHash(""); //$NON-NLS-1$
parent.setIdInDataSource("");
parent.setParent(getParent(parentPath));
parent.setExtraAttribute(ExtraProperties.DATASOURCE_READER, UfedXmlReader.class.getSimpleName());
pathToParent.put(parentPath, parent);
try {
caseData.incDiscoveredEvidences(1);
Manager.getInstance().addItemToQueue(parent);
} catch (InterruptedException e) {
throw new SAXException(e);
}
return parent;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
chars.setLength(0);
// if started <modelType type="Chat">, <modelType type="InstantMessage"> and so on...
// then delegates the parsing to UfedModelHandler
if (qName.equals("modelType") && StringUtils.equalsAny(atts.getValue("type"),
"Chat", "InstantMessage", "Contact", "UserAccount", "Email")) {
xmlReader.setContentHandler(UfedModelHandler.create(xmlReader, this, this, listOnly));
return;
}
XmlNode node = new XmlNode(qName, atts);
nodeSeq.push(node);
if (!listOnly)
elements.add(qName);
if (qName.equals("extractionInfo")) { //$NON-NLS-1$
String id = atts.getValue("id"); //$NON-NLS-1$
String name = atts.getValue("name"); //$NON-NLS-1$
extractionInfoMap.put(id, name);
} else if (qName.equals("file")) { //$NON-NLS-1$
String len = atts.getValue("size"); //$NON-NLS-1$
Long size = null;
if (len != null)
size = Long.valueOf(len.trim());
if (listOnly) {
caseData.incDiscoveredEvidences(1);
caseData.incDiscoveredVolume(size);
return;
}
Item item = new Item();
item.setExtraAttribute(ExtraProperties.DATASOURCE_READER, UfedXmlReader.class.getSimpleName());
item.setLength(size);
String fs = "/" + atts.getValue("fs"); //$NON-NLS-1$ //$NON-NLS-2$
String path = rootItem.getName() + fs + atts.getValue("path"); //$NON-NLS-1$
item.setPath(path);
String name = path.substring(path.lastIndexOf('/') + 1);
// Check if the name is not too long (see issue #2107)
updateName(item, name);
item.setParent(getParent(path));
boolean deleted = "deleted".equalsIgnoreCase(atts.getValue("deleted")); //$NON-NLS-1$ //$NON-NLS-2$
item.setDeleted(deleted);
fillCommonMeta(item, atts);
itemSeq.push(item);
} else if (qName.equals("model")) { //$NON-NLS-1$
XmlNode prevNode = nodeSeq.get(nodeSeq.size() - 2);
if (prevNode.element.equals("modelType")) { //$NON-NLS-1$
if (listOnly) {
caseData.incDiscoveredEvidences(1);
return;
}
Item item = createModelItem(atts);
itemSeq.push(item);
} else if (prevNode.element.equals("modelField") || prevNode.element.equals("multiModelField")) { //$NON-NLS-1$ //$NON-NLS-2$
String type = atts.getValue("type"); //$NON-NLS-1$
if (listOnly) {
if (!mergeInParentNode.contains(type))
caseData.incDiscoveredEvidences(1);
return;
}
Item item = new Item();
item.setExtraAttribute(ExtraProperties.DATASOURCE_READER, UfedXmlReader.class.getSimpleName());
IItem parent = itemSeq.get(itemSeq.size() - 1);
String name = type + "_" + atts.getValue("id"); //$NON-NLS-1$ //$NON-NLS-2$
String prevNameAtt = prevNode.atts.get("name"); //$NON-NLS-1$
if ("Location".equals(type) && ("FromPoint".equals(prevNameAtt) || "ToPoint".equals(prevNameAtt))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
name = prevNameAtt + "_" + name; //$NON-NLS-1$
item.setName(name);
item.setPath(parent.getPath() + "/" + name); //$NON-NLS-1$
item.setMediaType(MediaType.application(UFED_MIME_PREFIX + type));
item.setInputStreamFactory(new MetadataInputStreamFactory(item.getMetadata()));
item.setHash(""); //$NON-NLS-1$
Util.calctrackIDAndUpdateID((CaseData) caseData, parent);
item.setParent(parent);
if (!mergeInParentNode.contains(type))
parent.setHasChildren(true);
boolean deleted = "deleted".equalsIgnoreCase(atts.getValue("deleted_state")); //$NON-NLS-1$ //$NON-NLS-2$
item.setDeleted(deleted);
fillCommonMeta(item, atts);
itemSeq.push(item);
}
}
}
private Item createModelItem(Attributes atts) throws SAXException {
Item item = new Item();
item.setExtraAttribute(ExtraProperties.DATASOURCE_READER, UfedXmlReader.class.getSimpleName());
String type = atts.getValue("type");
String name = type + "_" + atts.getValue("id");
item.setName(name);
String path = decodedFolder.getPath() + "/" + type + "/" + name;
item.setPath(path);
item.setParent(getParent(path));
item.setMediaType(MediaType.application(UFED_MIME_PREFIX + type));
if (caseData.containsReport()) {
// export metadata as content only if generating blind report
item.setInputStreamFactory(new MetadataInputStreamFactory(item.getMetadata()));
}
item.setHash("");
boolean deleted = "deleted".equalsIgnoreCase(atts.getValue("deleted_state"));
item.setDeleted(deleted);
fillCommonMeta(item, atts);
return item;
}
private void fillCommonMeta(IItem item, Attributes atts) {
if ("StreetAddress".equals(atts.getValue("type"))) //$NON-NLS-1$ //$NON-NLS-2$
return;
String extractionName = extractionInfoMap.get(atts.getValue("extractionId")); //$NON-NLS-1$
item.getMetadata().add(ExtraProperties.UFED_META_PREFIX + "extractionName", extractionName); //$NON-NLS-1$
for (int i = 0; i < atts.getLength(); i++) {
String attName = atts.getQName(i);
if (!ignoreAttrs.contains(attName)) {
String value = atts.getValue(i);
if ("name".equals(attName)) {
attName = StringUtils.capitalize(attName);
}
item.getMetadata().add(ExtraProperties.UFED_META_PREFIX + attName, value);
}
}
if (item.getMetadata().get(UFED_ID) != null) {
item.setIdInDataSource(item.getMetadata().get(UFED_ID));
} else {
// item.setIdInDataSource("");
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
XmlNode currentNode = nodeSeq.pop();
for (XmlNode node : nodeSeq) {
if (node.element.equals("entityBookmarks")) { //$NON-NLS-1$
// currently there is no support for bookmarks
return;
}
}
if (listOnly)
return;
String nameAttr = currentNode.atts.get("name"); //$NON-NLS-1$
Item item = null;
if (!itemSeq.empty())
item = itemSeq.peek();
XmlNode parentNode = null;
if (!nodeSeq.empty())
parentNode = nodeSeq.peek();
String metadataSection = parentNode != null ? parentNode.atts.get("section") : null;
if ("Extraction Data".equals(metadataSection) || "Device Info".equals(metadataSection)) {
String val = chars.toString().toLowerCase();
if (val.contains("apple") || val.contains("iphone")) {
configureParsers(true);
}
}
if (("MSISDN".equals(nameAttr) || "LastUsedMSISDN".equals(nameAttr)) && parentNode != null
&& "Device Info".equals(parentNode.atts.get("section"))) {
String msisdn = chars.toString().trim();
if (!msisdn.isEmpty()) {
if ("LastUsedMSISDN".equals(nameAttr))
msisdns.add(0, msisdn);
else
msisdns.add(msisdn);
caseData.putCaseObject(MSISDN_PROP + rootItem.getDataSource().getUUID(), msisdns);
for (String attrVal : currentNode.atts.values()) {
if (attrVal.toLowerCase().startsWith(LAST_USE_PREFIX)) {
attrVal = attrVal.substring(LAST_USE_PREFIX.length()).trim();
try {
Date date = parseDate(attrVal);
this.lastUseToMsisdn.put(date, msisdn);
} catch (ParseException e) {
e.printStackTrace();
}
break;
}
}
}
} else if (qName.equals("item")) { //$NON-NLS-1$
if ("Tags".equals(nameAttr) && "Configuration".equals(chars.toString())) { //$NON-NLS-1$ //$NON-NLS-2$
item.setCategory(chars.toString());
} else if ("Local Path".equals(nameAttr)) { //$NON-NLS-1$
String normalizedPath = normalizePaths(chars.toString());
setContent(item, normalizedPath);
// Add "Local Path" to item metadata
item.getMetadata().add(LOCAL_PATH_META, normalizedPath);
// Add key to map item id to "Local Path"
ufedFileIdToLocalPath.put(item.getMetadata().get(UFED_ID), normalizedPath);
if (item.getPath().endsWith("wireless/Library/Databases/CellularUsage.db")) {
parseIphoneSimSwitch(item);
}
} else if (!ignoreNameAttrs.contains(nameAttr) && !nameAttr.toLowerCase().startsWith("exif")) //$NON-NLS-1$
if (item != null && !chars.toString().trim().isEmpty())
item.getMetadata().add(ExtraProperties.UFED_META_PREFIX + nameAttr, chars.toString().trim());
} else if (qName.equals("timestamp")) { //$NON-NLS-1$
try {
String value = chars.toString().trim();
if (!value.isEmpty()) {
if (nameAttr.equals("CreationTime")) //$NON-NLS-1$
item.setCreationDate(parseDate(value));
else if (nameAttr.equals("ModifyTime")) //$NON-NLS-1$
item.setModificationDate(parseDate(value));
else if (nameAttr.equals("AccessTime")) //$NON-NLS-1$
item.setAccessDate(parseDate(value));
else
item.getMetadata().add(ExtraProperties.UFED_META_PREFIX + nameAttr, value);
}
} catch (ParseException e) {
throw new SAXException(e);
}
} else if (qName.equals("value")) { //$NON-NLS-1$
if (parentNode.element.equals("field") || parentNode.element.equals("multiField")) { //$NON-NLS-1$ //$NON-NLS-2$
String parentNameAttr = parentNode.atts.get("name"); //$NON-NLS-1$
if (!ignoreNameAttrs.contains(parentNameAttr)) {
String meta = ExtraProperties.UFED_META_PREFIX + parentNameAttr;
String type = currentNode.atts.get("type"); //$NON-NLS-1$
String value = chars.toString().trim();
if (type.equals("TimeStamp") && !value.isEmpty()) //$NON-NLS-1$
try {
item.getMetadata().add(meta, out.format(parseDate(value)));
} catch (ParseException e) {
throw new SAXException(e);
}
else if (item != null && !value.isEmpty()) {
if ("Base64String".equalsIgnoreCase(currentNode.atts.get("format"))) {
String decoded = new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
boolean isString = true;
for (char c : decoded.toCharArray()) {
if (!(Character.isLetter(c) || c == 0x0A || c == 0x0D || c == 0x09 || c == 0x0B
|| (c >= 0x20 && c <= 0x7E) || (c >= 0xA0 && c <= 0xFF))) {
isString = false;
}
}
if (isString) {
value = decoded;
} else {
item.getMetadata().add(meta + ":format", "base64");
}
}
item.getMetadata().add(meta, value);
}
}
}
} else if (qName.equals("targetid") && parentNode.element.equals("jumptargets")) { //$NON-NLS-1$ //$NON-NLS-2$
item.getMetadata().add(ExtraProperties.UFED_JUMP_TARGETS, chars.toString().trim());
} else if (qName.equals("ownerid") && parentNode.element.equals("sourcemodels")) {
item.getMetadata().add(ExtraProperties.UFED_SOURCE_MODELS, chars.toString().trim());
} else if (qName.equals("taggedFiles")) { //$NON-NLS-1$
md5ToLocalPath.clear();
} else if (qName.equals("file")) { //$NON-NLS-1$
itemSeq.pop();
// See https://github.com/sepinf-inc/IPED/issues/2299
String md5 = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "MD5");
String localPath = item.getMetadata().get(LOCAL_PATH_META);
if (StringUtils.isNotBlank(md5) && md5.length() == 32) {
if (item.getInputStreamFactory() != null && !md5ToLocalPath.containsKey(md5) && StringUtils.isNotBlank(localPath)) {
md5ToLocalPath.put(md5, localPath);
} else if (item.getInputStreamFactory() == null && md5ToLocalPath.containsKey(md5)) {
String seenPath = md5ToLocalPath.get(md5);
setContent(item, seenPath);
}
}
// See https://github.com/sepinf-inc/IPED/issues/1685
boolean merged = false;
if (!itemSeq.isEmpty()) {
IItem parentItem = itemSeq.peek();
if (parentItem.getMediaType() != null && UFED_CONTACTPHOTO_MIME.equals(parentItem.getMediaType().getSubtype())) {
String[] split = item.getIdInDataSource().split(UFDRInputStreamFactory.UFDR_PATH_PREFIX);
String exportPath = split[split.length - 1];
parentItem.getMetadata().set(AVATAR_PATH_META, exportPath);
caseData.incDiscoveredEvidences(-1);
merged = true;
}
}
String sceneClassifications = item.getMetadata().get(UFED_NATIVE_SCENE_CLASSIFICATION);
if (sceneClassifications != null) {
item.getMetadata().remove(UFED_NATIVE_SCENE_CLASSIFICATION);
for (String sceneClass : sceneClassifications.split(",")) {
sceneClass = MetadataUtil.normalizeTerm(sceneClass);
if (!sceneClass.isEmpty()) {
item.getMetadata().add(UFED_NATIVE_SCENE_CLASSIFICATION, sceneClass);
}
}
}
if (!merged) {
setMediaResult(item);
String trackId = Util.getTrackID(item);
if (!addedTrackIds.add(trackId)) {
LOGGER.log(CONSOLE, "Unexpected UFDR report.xml structure, item with duplicated track id {}: {}.\nPlease report this to project"
+ " developers sending the UFDR report.xml to add proper support for the new structure.", trackId, item.getPath());
}
try {
Manager.getInstance().addItemToQueue(item);
} catch (Exception e) {
throw new SAXException(e);
}
}
} else if (qName.equals("model") && ( //$NON-NLS-1$
parentNode.element.equals("modelType") || //$NON-NLS-1$
parentNode.element.equals("modelField") || //$NON-NLS-1$
parentNode.element.equals("multiModelField"))) { //$NON-NLS-1$
itemSeq.pop();
String type = currentNode.atts.get("type"); //$NON-NLS-1$
if ("Attachment".equals(type)) { //$NON-NLS-1$
handleAttachment(item);
}
if ("Call".equals(type) || "SMS".equals(type) //$NON-NLS-4$
|| "MMS".equals(type)) { //$NON-NLS-1$
String date = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "TimeStamp"); //$NON-NLS-1$
item.getMetadata().remove(ExtraProperties.UFED_META_PREFIX + "TimeStamp"); //$NON-NLS-1$
item.getMetadata().set(ExtraProperties.COMMUNICATION_DATE, date);
String subject = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Subject"); //$NON-NLS-1$
item.getMetadata().remove(ExtraProperties.UFED_META_PREFIX + "Subject"); //$NON-NLS-1$
item.getMetadata().set(ExtraProperties.MESSAGE_SUBJECT, subject);
String body = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Body"); //$NON-NLS-1$
item.getMetadata().remove(ExtraProperties.UFED_META_PREFIX + "Body"); //$NON-NLS-1$
if (body == null) {
body = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Snippet"); //$NON-NLS-1$
item.getMetadata().remove(ExtraProperties.UFED_META_PREFIX + "Snippet"); //$NON-NLS-1$
}
item.getMetadata().set(ExtraProperties.MESSAGE_BODY, body);
}
if (mergeInParentNode.contains(type) && !itemSeq.empty()) {
IItem parentItem = itemSeq.peek();
if ("Party".equals(type)) { //$NON-NLS-1$
String role = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Role"); //$NON-NLS-1$
String parentNameAttr = parentNode.atts.get("name"); //$NON-NLS-1$
if (role == null || role.equals("General")) //$NON-NLS-1$
role = parentNameAttr;
if (role.equals("To") && (parentNameAttr.equals("Bcc") || parentNameAttr.equals("Cc"))) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
role = parentNameAttr;
if (role.equals("Parties")) //$NON-NLS-1$
role = "Participants"; //$NON-NLS-1$
String identifier = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Identifier"); //$NON-NLS-1$
String name = item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "Name"); //$NON-NLS-1$
String value = name == null || name.equals(identifier) ? identifier
: identifier == null ? name : name + "(" + identifier + ")"; //$NON-NLS-1$ //$NON-NLS-2$
if (value != null) {
if ("From".equalsIgnoreCase(role)) //$NON-NLS-1$
parentItem.getMetadata().add(ExtraProperties.COMMUNICATION_FROM, value);
else if ("To".equalsIgnoreCase(role)) //$NON-NLS-1$
parentItem.getMetadata().add(ExtraProperties.COMMUNICATION_TO, value);
else if ("Cc".equalsIgnoreCase(role)) //$NON-NLS-1$
parentItem.getMetadata().add(Message.MESSAGE_CC, value);
else if ("Bcc".equalsIgnoreCase(role)) //$NON-NLS-1$
parentItem.getMetadata().add(Message.MESSAGE_BCC, value);
else
parentItem.getMetadata().add(ExtraProperties.UFED_META_PREFIX + role, value);
}
boolean isOwner = Boolean
.valueOf(item.getMetadata().get(ExtraProperties.UFED_META_PREFIX + "IsPhoneOwner")); //$NON-NLS-1$
if (value != null && isOwner) { // $NON-NLS-1$
ownerParties.add(value);
if (parentItem.getMediaType().toString().contains("chat"))
parentItem.getMetadata().add(META_PHONE_OWNER, value);
}
if (isOwner && "From".equals(role)) //$NON-NLS-1$
parentItem.getMetadata().add(META_FROM_OWNER, Boolean.TRUE.toString());