forked from google/timesketch
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsketch.py
More file actions
2130 lines (1741 loc) · 73.8 KB
/
sketch.py
File metadata and controls
2130 lines (1741 loc) · 73.8 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
# Copyright 2019 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Timesketch API client library."""
from __future__ import unicode_literals
import copy
import json
import logging
import os
import pandas
from . import aggregation, analyzer, definitions, error, graph
from . import index as api_index
from . import resource
from . import scenario as scenario_lib
from . import search, searchtemplate, story, timeline
logger = logging.getLogger("timesketch_api.sketch")
class Sketch(resource.BaseResource):
"""Timesketch sketch object.
A sketch in Timesketch is a collection of one or more timelines. It has
access control and its own namespace for things like labels and comments.
Attributes:
id: The ID of the sketch.
api: An instance of TimesketchApi object.
"""
# Add in necessary fields in data ingested via a different mechanism.
_NECESSARY_DATA_FIELDS = frozenset(["timestamp_desc", "datetime"])
def __init__(self, sketch_id, api, sketch_name=None):
"""Initializes the Sketch object.
Args:
sketch_id: Primary key ID of the sketch.
api: An instance of TimesketchApi object.
sketch_name: Name of the sketch (optional).
"""
self.id = sketch_id
self.api = api
self._archived = None
self._sketch_name = sketch_name
super().__init__(api=api, resource_uri=f"sketches/{self.id}/")
@property
def acl(self):
"""Property that returns back a ACL dict."""
data = self.lazyload_data(refresh_cache=True)
objects = data.get("objects")
if not objects:
return {}
data_object = objects[0]
permission_string = data_object.get("all_permissions")
if not permission_string:
return {}
return json.loads(permission_string)
@property
def attributes(self):
"""Property that returns the sketch attributes."""
data = self.lazyload_data(refresh_cache=True)
meta = data.get("meta", {})
return meta.get("attributes", {})
@property
def attributes_table(self):
"""DEPRECATED: Property that returns the sketch attributes
as a data frame.
Given the fluid setup of attributes, this is not a good way to
represent the data. Use the attributes property instead."""
data = self.lazyload_data(refresh_cache=True)
meta = data.get("meta", {})
attributes = meta.get("attributes", [])
data_frame = pandas.DataFrame(attributes)
data_frame.columns = ["attribute", "values", "ontology"]
return data_frame
@property
def description(self):
"""Property that returns sketch description.
Returns:
Sketch description as string.
"""
sketch = self.lazyload_data()
return sketch["objects"][0]["description"]
@description.setter
def description(self, description_value):
"""Change the sketch description to a new value."""
if not isinstance(description_value, str):
logger.error("Unable to change the name to a non string value")
return
resource_url = "{0:s}/sketches/{1:d}/".format(self.api.api_root, self.id)
data = {
"description": description_value,
}
response = self.api.session.post(resource_url, json=data)
_ = error.check_return_status(response, logger)
# Force the new description to be re-loaded.
_ = self.lazyload_data(refresh_cache=True)
@property
def labels(self):
"""Property that returns the sketch labels."""
data = self.lazyload_data(refresh_cache=True)
objects = data.get("objects", [])
if not objects:
return []
sketch_data = objects[0]
label_string = sketch_data.get("label_string", "")
if label_string:
return json.loads(label_string)
return []
@property
def last_activity(self):
"""Property that returns the last activity.
Returns:
Sketch last activity as a string.
"""
data = self.lazyload_data(refresh_cache=True)
meta = data.get("meta", {})
return meta.get("last_activity", "")
@property
def my_acl(self):
"""Property that returns back the ACL for the current user."""
data = self.lazyload_data(refresh_cache=True)
objects = data.get("objects")
if not objects:
return []
data_object = objects[0]
permission_string = data_object.get("my_permissions")
if not permission_string:
return []
return json.loads(permission_string)
@property
def name(self):
"""Property that returns sketch name.
Returns:
Sketch name as string.
"""
if not self._sketch_name:
sketch = self.lazyload_data()
self._sketch_name = sketch["objects"][0]["name"]
return self._sketch_name
@name.setter
def name(self, name_value):
"""Change the name of the sketch to a new value."""
if not isinstance(name_value, str):
logger.error("Unable to change the name to a non string value")
return
resource_url = "{0:s}/sketches/{1:d}/".format(self.api.api_root, self.id)
data = {
"name": name_value,
}
response = self.api.session.post(resource_url, json=data)
_ = error.check_return_status(response, logger)
# Force the new name to be re-loaded.
self._sketch_name = ""
_ = self.lazyload_data(refresh_cache=True)
@property
def status(self):
"""Property that returns sketch status.
Returns:
Sketch status as string.
"""
data = self.lazyload_data(refresh_cache=True)
objects = data.get("objects")
if not objects:
return "Unknown"
if not isinstance(objects, (list, tuple)):
return "Unknown"
first_object = objects[0]
status_list = first_object.get("status")
if not status_list:
return "Unknown"
if len(status_list) < 1:
return "Unknown"
return status_list[0].get("status", "Unknown")
def add_attribute_list(self, name, values, ontology="text"):
"""Adds or modifies attributes to the sketch.
Args:
name (str): The name of the attribute.
values (list): A list of values (in their correct type according
to the ontology).
ontology (str): The ontology (matches with
/data/ontology.yaml), which defines how the attribute
is interpreted.
Raises:
ValueError: If any of the parameters are of the wrong type.
Returns:
A dict with the results from the operation.
"""
if not isinstance(name, str):
raise ValueError("Name needs to be a string.")
if not isinstance(ontology, str):
raise ValueError("Ontology needs to be a string.")
resource_url = "{0:s}/sketches/{1:d}/attribute/".format(
self.api.api_root, self.id
)
data = {
"name": name,
"values": values,
"ontology": ontology,
}
response = self.api.session.post(resource_url, json=data)
status = error.check_return_status(response, logger)
if not status:
logger.error("Unable to add the attribute to the sketch.")
return error.get_response_json(response, logger)
def add_attribute(self, name, value, ontology="text"):
"""Adds or modifies an attribute to the sketch.
Args:
name (str): The name of the attribute.
value (str): Value of the attribute, stored as a string.
ontology (str): The ontology (matches with
/data/ontology.yaml), which defines
how the attribute is interpreted.
Raises:
ValueError: If any of the parameters are of the wrong type.
Returns:
A dict with the results from the operation.
"""
if not isinstance(name, str):
raise ValueError("Name needs to be a string.")
return self.add_attribute_list(name=name, values=[value], ontology=ontology)
def add_sketch_label(self, label):
"""Add a label to the sketch.
Args:
label (str): A string with the label to add to the sketch.
Returns:
bool: A boolean to indicate whether the label was successfully
added to the sketch.
"""
if label in self.labels:
logger.error("Label [{0:s}] already applied to sketch.".format(label))
return False
resource_url = "{0:s}/sketches/{1:d}/".format(self.api.api_root, self.id)
data = {
"labels": [label],
"label_action": "add",
}
response = self.api.session.post(resource_url, json=data)
status = error.check_return_status(response, logger)
if not status:
logger.error("Unable to add the label [{0:s}] to the sketch.".format(label))
return status
def remove_attribute(self, name, ontology):
"""Remove an attribute from the sketch.
Args:
name (str): The name of the attribute.
ontology (str): The ontology (matches with
/data/ontology.yaml), which defines how the attribute
is interpreted.
Raises:
ValueError: If any of the parameters are of the wrong type.
Returns:
Boolean value whether the attribute was successfully
removed or not.
"""
if not isinstance(name, str):
raise ValueError("Name needs to be a string.")
resource_url = "{0:s}/sketches/{1:d}/attribute/".format(
self.api.api_root, self.id
)
data = {
"name": name,
"ontology": ontology,
}
response = self.api.session.delete(resource_url, json=data)
status = error.check_return_status(response, logger)
if not status:
logger.error("Unable to remove the attribute from the sketch.")
return status
def remove_sketch_label(self, label):
"""Remove a label from the sketch.
Args:
label (str): A string with the label to remove from the sketch.
Returns:
bool: A boolean to indicate whether the label was successfully
removed from the sketch.
"""
if label not in self.labels:
logger.error(
"Unable to remove label [{0:s}], not a label "
"attached to this sketch.".format(label)
)
return False
resource_url = "{0:s}/sketches/{1:d}/".format(self.api.api_root, self.id)
data = {
"labels": [label],
"label_action": "remove",
}
response = self.api.session.post(resource_url, json=data)
status = error.check_return_status(response, logger)
if not status:
logger.error("Unable to remove the label from the sketch.")
return status
def create_view(self, name, query_string="", query_dsl="", query_filter=None):
"""Create a view object.
Args:
name (str): the name of the view.
query_string (str): OpenSearch query string. This is optional
yet either a query string or a query DSL is required.
query_dsl (str): OpenSearch query DSL as JSON string. This is
optional yet either a query string or a query DSL is required.
query_filter (dict): Filter for the query as a dict.
Raises:
ValueError: if neither query_string nor query_dsl is provided or
if query_filter is not a dict.
RuntimeError: if a view wasn't created for some reason.
Returns:
A search.Search object that has been saved to the database.
"""
if not (query_string or query_dsl):
raise ValueError("You need to supply a query string or a dsl")
if self.is_archived():
raise RuntimeError("Unable create a view on an archived sketch.")
search_obj = search.Search(sketch=self)
search_obj.from_manual(
query_string=query_string,
query_dsl=query_dsl,
query_filter=query_filter,
)
search_obj.name = name
search_obj.save()
return search_obj
def create_story(self, title):
"""Create a story object.
Args:
title: the title of the story.
Raises:
RuntimeError: if a story wasn't created for some reason.
Returns:
A story object (instance of Story) for the newly
created story.
"""
if self.is_archived():
raise RuntimeError("Unable to create a story in an archived sketch.")
resource_url = "{0:s}/sketches/{1:d}/stories/".format(
self.api.api_root, self.id
)
data = {"title": title, "content": ""}
response = self.api.session.post(resource_url, json=data)
status = error.check_return_status(response, logger)
if not status:
error.error_message(
response, "Unable to create a story", error=RuntimeError
)
response_json = error.get_response_json(response, logger)
story_dict = response_json.get("objects", [{}])[0]
return story.Story(story_id=story_dict.get("id", 0), sketch=self, api=self.api)
def delete(self):
"""Deletes the sketch."""
if self.is_archived():
raise RuntimeError(
"Unable to delete an archived sketch, first unarchive then delete."
)
resource_url = "{0:s}/sketches/{1:d}/".format(self.api.api_root, self.id)
response = self.api.session.delete(resource_url)
return error.check_return_status(response, logger)
def add_to_acl(
self,
user_list=None,
group_list=None,
make_public=False,
permissions=None,
):
"""Add users or groups to the sketch ACL.
Args:
user_list: optional list of users to add to the ACL
of the sketch. Each user is a string.
group_list: optional list of groups to add to the ACL
of the sketch. Each user is a string.
make_public: Optional boolean indicating the sketch should be
marked as public.
permissions: optional list of permissions (read, write, delete).
If not the default set of permissions are applied (read, write)
Returns:
A boolean indicating whether the ACL change was successful.
"""
if not user_list and not group_list and not make_public:
return False
resource_url = "{0:s}/sketches/{1:d}/collaborators/".format(
self.api.api_root, self.id
)
data = {}
if group_list:
group_list_corrected = [str(x).strip() for x in group_list]
data["groups"] = group_list_corrected
if user_list:
user_list_corrected = [str(x).strip() for x in user_list]
data["users"] = user_list_corrected
if make_public:
data["public"] = "true"
if permissions:
allowed_permissions = set(["read", "write", "delete"])
use_permissions = list(allowed_permissions.intersection(set(permissions)))
if set(use_permissions) != set(permissions):
logger.warning(
"Some permissions are invalid: {0:s}".format(
", ".join(
list(set(permissions).difference(set(use_permissions)))
)
)
)
if not use_permissions:
logger.error("No permissions left to add.")
return False
data["permissions"] = json.dumps(use_permissions)
if not data:
return True
response = self.api.session.post(resource_url, json=data)
# Refresh the sketch data to reflect ACL changes.
_ = self.lazyload_data(refresh_cache=True)
return error.check_return_status(response, logger)
def list_aggregation_groups(self):
"""List all saved aggregation groups for this sketch.
Returns:
List of aggregation groups (instances of AggregationGroup objects)
"""
if self.is_archived():
raise RuntimeError(
"Unable to list aggregation groups on an archived sketch."
)
groups = []
data = self.api.fetch_resource_data(f"sketches/{self.id}/aggregation/group/")
for group_dict in data.get("objects", []):
if not group_dict.get("id"):
continue
group = aggregation.AggregationGroup(sketch=self)
group.from_saved(group_dict.get("id"))
groups.append(group)
return groups
def list_aggregations(self, include_labels=None, exclude_labels=None):
"""List all saved aggregations for this sketch.
Args:
include_labels (list): list of strings with labels. If defined
then only return aggregations that have the label in the list.
exclude_labels (list): list of strings with labels. If defined
then only return aggregations that don't have a label in the
list. include_labels will be processed first in case both are
defined.
Returns:
List of aggregations (instances of Aggregation objects)
"""
if self.is_archived():
raise RuntimeError("Unable to list aggregations on an archived sketch.")
aggregations = []
data = self.api.fetch_resource_data(f"sketches/{self.id}/aggregation/")
objects = data.get("objects")
if not objects:
return aggregations
if not isinstance(objects, (list, tuple)):
return aggregations
object_list = objects[0]
if not isinstance(object_list, (list, tuple)):
return aggregations
for aggregation_dict in object_list:
agg_id = aggregation_dict.get("id")
group_id = aggregation_dict.get("aggregationgroup_id")
if group_id:
continue
label_string = aggregation_dict.get("label_string", "")
if label_string:
labels = json.loads(label_string)
else:
labels = []
if include_labels:
if not any(x in include_labels for x in labels):
continue
if exclude_labels:
if any(x in exclude_labels for x in labels):
continue
aggregation_obj = aggregation.Aggregation(sketch=self)
aggregation_obj.from_saved(aggregation_id=agg_id)
aggregations.append(aggregation_obj)
return aggregations
def list_graphs(self):
"""Returns a list of stored graphs."""
if self.is_archived():
raise RuntimeError("Unable to list graphs on an archived sketch.")
resource_uri = f"{self.api.api_root}/sketches/{self.id}/graphs/"
response = self.api.session.get(resource_uri)
response_json = error.get_response_json(response, logger)
objects = response_json.get("objects")
if not objects:
logger.warning("No graphs discovered.")
return []
return_list = []
graph_list = objects[0]
for graph_dict in graph_list:
graph_obj = graph.Graph(sketch=self)
graph_obj.from_saved(graph_dict.get("id"))
return_list.append(graph_obj)
return return_list
def get_analyzer_status(self, as_sessions=False):
"""Returns a list of started analyzers and their status.
Args:
as_sessions (bool): optional, if set to True then a list of
AnalyzerResult objects will be returned. Defaults to
returning a list of dicts.
Returns:
If "as_sessions" is set then a list of AnalyzerResult gets
returned, otherwise a list of dict objects that contains
status information of each analyzer run. The dict contains
information about what timeline it ran against, the
results and current status of the analyzer run.
"""
if self.is_archived():
raise RuntimeError("Unable to list analyzer status on an archived sketch.")
stats_list = []
sessions = []
for timeline_obj in self.list_timelines():
resource_uri = ("{0:s}/sketches/{1:d}/timelines/{2:d}/analysis").format(
self.api.api_root, self.id, timeline_obj.id
)
response = self.api.session.get(resource_uri)
response_json = error.get_response_json(response, logger)
objects = response_json.get("objects")
if not objects:
continue
for result in objects[0]:
session_id = result.get("analysissession_id")
if as_sessions and session_id:
sessions.append(
analyzer.AnalyzerResult(
timeline_id=timeline_obj.id,
session_id=session_id,
sketch_id=self.id,
api=self.api,
)
)
status = result.get("status", [])
if len(status) == 1:
result["status"] = status[0].get("status", "N/A")
stats_list.append(result)
if as_sessions:
return sessions
return stats_list
def get_aggregation(self, aggregation_id):
"""Return a stored aggregation.
Args:
aggregation_id: id of the stored aggregation.
Returns:
An aggregation object, if stored (instance of Aggregation),
otherwise None object.
"""
if self.is_archived():
raise RuntimeError("Unable to get aggregations on an archived sketch.")
for aggregation_obj in self.list_aggregations():
if aggregation_obj.id == aggregation_id:
return aggregation_obj
return None
def get_aggregation_group(self, group_id):
"""Return a stored aggregation group.
Args:
group_id: id of the stored aggregation group.
Returns:
An aggregation group object (instance of AggregationGroup)
if stored, otherwise None object.
"""
if self.is_archived():
raise RuntimeError(
"Unable to get aggregation groups on an archived sketch."
)
for group_obj in self.list_aggregation_groups():
if group_obj.id == group_id:
return group_obj
return None
def get_story(self, story_id=None, story_title=None):
"""Returns a story object that is stored in the sketch.
Args:
story_id: an integer indicating the ID of the story to
be fetched. Defaults to None.
story_title: a string with the title of the story. Optional
and defaults to None.
Returns:
A story object (instance of Story) if one is found. Returns
a None if neither story_id or story_title is defined or if
the view does not exist. If a story title is defined and
not a story id, the first story that is found with the same
title will be returned.
"""
if self.is_archived():
raise RuntimeError("Unable to get stories on an archived sketch.")
if story_id is None and story_title is None:
return None
for story_obj in self.list_stories():
if story_id and story_id == story_obj.id:
return story_obj
if story_title and story_title.lower() == story_obj.title.lower():
return story_obj
return None
def get_view(self, view_id=None, view_name=None):
"""Returns a saved search object that is stored in the sketch.
Args:
view_id: an integer indicating the ID of the saved search to
be fetched. Defaults to None.
view_name: a string with the name of the saved search. Optional
and defaults to None.
Returns:
A search object (instance of search.Search) if one is found.
Returns a None if neither view_id or view_name is defined or if
the search does not exist.
"""
return self.get_saved_search(search_id=view_id, search_name=view_name)
def get_saved_search(self, search_id=None, search_name=None):
"""Returns a saved search object that is stored in the sketch.
Args:
view_id: an integer indicating the ID of the view to
be fetched. Defaults to None.
view_name: a string with the name of the view. Optional
and defaults to None.
Returns:
A search object (instance of search.Search) if one is found.
Returns a None if neither search_id or search_name is defined or if
the search does not exist.
"""
if self.is_archived():
raise RuntimeError("Unable to get saved searches on an archived sketch.")
if search_id is None and search_name is None:
return None
for search_obj in self.list_saved_searches():
if search_id and search_id == search_obj.id:
return search_obj
if search_name and search_name.lower() == search_obj.name.lower():
return search_obj
return None
def get_timeline(self, timeline_id=None, timeline_name=None):
"""Returns a timeline object that is stored in the sketch.
Args:
timeline_id: an integer indicating the ID of the timeline to
be fetched. Defaults to None.
timeline_name: a string with the name of the timeline. Optional
and defaults to None.
Returns:
A timeline object (instance of Timeline) if one is found. Returns
a None if neither timeline_id or timeline_name is defined or if
the timeline does not exist.
"""
if self.is_archived():
raise RuntimeError("Unable to get timelines on an archived sketch.")
if timeline_id is None and timeline_name is None:
return None
for timeline_ in self.list_timelines():
if timeline_id and timeline_id == timeline_.id:
return timeline_
if timeline_name:
if timeline_name.lower() == timeline_.name.lower():
return timeline_
return None
def get_intelligence_attribute(self):
"""Returns a timeline object that is stored in the sketch.
Returns:
A list of dicts with indicators stored in the intelligence
attribute of the sketch.
"""
if self.is_archived():
raise RuntimeError("Unable to get attributes on an archived sketch.")
intel_attribute = (
self.attributes.get("intelligence", {}).get("value", {}).get("data", {})
)
return intel_attribute
def list_stories(self):
"""Get a list of all stories that are attached to the sketch.
Returns:
List of stories (instances of Story objects)
"""
if self.is_archived():
raise RuntimeError("Unable to list stories on an archived sketch.")
story_list = []
resource_url = "{0:s}/sketches/{1:d}/stories/".format(
self.api.api_root, self.id
)
response = self.api.session.get(resource_url)
response_json = error.get_response_json(response, logger)
story_objects = response_json.get("objects")
if not story_objects:
return story_list
if not len(story_objects) == 1:
return story_list
stories = story_objects[0]
for story_dict in stories:
story_list.append(
story.Story(
story_id=story_dict.get("id", -1),
sketch=self,
api=self.api,
)
)
return story_list
def list_views(self):
"""List all saved views for this sketch.
Returns:
List of search object (instance of search.Search).
"""
return self.list_saved_searches()
def list_saved_searches(self):
"""List all saved searches for this sketch.
Returns:
List of search object (instance of search.Search).
"""
if self.is_archived():
raise RuntimeError("Unable to list saved searches on an archived sketch.")
data = self.lazyload_data()
searches = []
meta = data.get("meta", {})
for saved_search in meta.get("views", []):
search_obj = search.Search(sketch=self)
try:
search_obj.from_saved(saved_search.get("id"))
searches.append(search_obj)
except ValueError:
logger.error(
"Unable to load a saved search with ID: {0:d}".format(
saved_search.get("id", 0)
),
exc_info=True,
)
return searches
def list_search_templates(self):
"""Get a list of all search templates that are available.
Returns:
List of searchtemplate.SearchTemplate object instances.
"""
response = self.api.fetch_resource_data("searchtemplates/")
objects = response.get("objects", [])
if not objects:
return []
template_dicts = objects[0]
template_list = []
for template_dict in template_dicts:
template_obj = searchtemplate.SearchTemplate(api=self.api)
template_obj.from_saved(template_dict.get("id"), sketch_id=self.id)
template_list.append(template_obj)
return template_list
def list_timelines(self):
"""List all timelines for this sketch.
Returns:
List of timelines (instances of Timeline objects)
"""
if self.is_archived():
raise RuntimeError("Unable to list timelines on an archived sketch.")
timelines = []
data = self.lazyload_data()
objects = data.get("objects")
if not objects:
return timelines
for timeline_dict in objects[0].get("timelines", []):
timeline_obj = timeline.Timeline(
timeline_id=timeline_dict["id"],
sketch_id=self.id,
api=self.api,
name=timeline_dict["name"],
searchindex=timeline_dict["searchindex"]["index_name"],
)
timelines.append(timeline_obj)
return timelines
def upload(self, timeline_name, file_path, es_index=None):
"""Deprecated function to upload data, does nothing.
Args:
timeline_name: Name of the resulting timeline.
file_path: Path to the file to be uploaded.
es_index: Index name for the ES database
Raises:
RuntimeError: If this function is used, since it has been
deprecated in favor of the importer client.
"""
message = (
"This function has been deprecated, use the CLI tool: "
"timesketch_importer: https://github.com/google/timesketch/blob/"
"master/docs/UploadData.md#using-the-importer-clie-tool or the "
"importer library: https://github.com/google/timesketch/blob/"
"master/docs/UploadDataViaAPI.md"
)
logger.error(message)
raise RuntimeError(message)
def add_timeline(self, searchindex):
"""Deprecated function to add timeline to sketch.
Args:
searchindex: SearchIndex object instance.
Raises:
RuntimeError: If this function is called.
"""
message = (
"This function has been deprecated, since adding already existing "
"indices to a sketch is no longer supported."
)
logger.error(message)
raise RuntimeError(message)
def explore(
self,
query_string=None,
query_dsl=None,
query_filter=None,
view=None,
return_fields=None,
max_entries=None,
file_name="",
as_dict=False,
as_object=False,
):
"""Explore the sketch.
Args:
query_string (str): OpenSearch query string.
query_dsl (str): OpenSearch query DSL as JSON string.
query_filter (dict): Filter for the query as a dict.
view: View object instance (optional).
return_fields (str): A comma separated string with a list of fields
that should be included in the response. Optional and defaults
to None.
max_entries (int): Optional integer denoting a best effort to limit
the output size to the number of events. Events are read in,