author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
263,133
10.02.2020 12:45:06
0
874192f0446048ac1c876ce812b49894495efff6
Initial changes to importer and upload API.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "\"\"\"Timesketch data importer.\"\"\"\nfrom __future__ import unicode_literals\n+import io\nimport json\nimport math\nimport logging\n@@ -38,6 +39,10 @@ class ImportStreamer(object):\n# the streamer.\nENTRY_THRESHOLD = 100000\n+ # Number of bytes in a binary file before automatically\n+ # chunking it up into smaller pieces.\n+ SIZE_THRESHOLD = 10485760\n+\ndef __init__(self, entry_threshold=None):\n\"\"\"Initialize the upload streamer.\"\"\"\nself._count = 0\n@@ -140,6 +145,49 @@ class ImportStreamer(object):\nself._timeline_id = response_dict.get('objects', [{}])[0].get('id')\nself._last_response = response_dict\n+ def _upload_binary_file(self, file_path):\n+ \"\"\"Upload binary data to Timesketch, potentially chunking it up.\n+\n+ Args:\n+ file_path: a full path to the file that is about to be uploaded.\n+ \"\"\"\n+ resource_url = '{0:s}/upload/'.format(self._sketch.api.api_root)\n+ file_size = os.path.getsize(file_path)\n+ data = {\n+ 'name': timeline_name,\n+ 'sketch_id': self.id,\n+ 'total_file_size': file_size,\n+ }\n+ if file_size >= self.SIZE_THRESHOLD:\n+ file_dict = {\n+ 'file': open(file_path, 'rb')}\n+ response = self._sketch.api.session.post(\n+ resource_url, files=file_dict, data=data)\n+ else:\n+ chunks = int(math.ceil(float(file_size) / self._threshold))\n+ data['chunk_total_chunks'] = chunks\n+ for index in range(0, chunks):\n+ data['chunk_index'] = index\n+ start = self.SIZE_THRESHOLD * index\n+ data['chunk_byte_offset'] = start\n+ fh = open(file_path, 'rb')\n+ fh.seek(start)\n+ data = fh.read(self.SIZE_TRESHOLD)\n+ file_stream = io.BytesIO(data)\n+ file_dict = {'file': file_stream}\n+ response = self._sketch.api.session.post(\n+ resource_url, files=file_dict, data=data)\n+\n+ response_dict = response.json()\n+ timeline_dict = response_dict['objects'][0]\n+ timeline_obj = timeline.Timeline(\n+ timeline_id=timeline_dict['id'],\n+ sketch_id=self.id,\n+ api=self.api,\n+ name=timeline_dict['name'],\n+ searchindex=timeline_dict['searchindex']['index_name'])\n+ return timeline_obj\n+\ndef add_data_frame(self, data_frame, part_of_iter=False):\n\"\"\"Add a data frame into the buffer.\n@@ -284,7 +332,7 @@ class ImportStreamer(object):\nfilepath, delimiter=delimiter, chunksize=self._threshold):\nself.add_data_frame(chunk_frame, part_of_iter=True)\nelif file_ending == 'plaso':\n- self._sketch.upload(self._timeline_name, filepath)\n+ self._upload_binary_file(filepath)\nelif file_ending == 'jsonl':\ndata_frame = None\nwith open(filepath, 'r') as fh:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1550,8 +1550,74 @@ class UploadFileResource(ResourceMixin, Resource):\nindex_name = codecs.decode(index_name, 'utf-8')\nfile_path = os.path.join(upload_folder, filename)\n+\n+ chunk_index = form.chunk_index.data or None\n+ chunk_byte_offset = form.chunk_byte_offset or None\n+ chunk_total_chunks = form.chunk_total_chunks or None\n+ file_size = form.total_file_size or None\n+ enable_stream = form.enable_stream.data\n+\n+ if chunk_index is None:\nfile_storage.save(file_path)\n+ return self._complete_upload(\n+ file_path,\n+ file_extension,\n+ timeline_name,\n+ index_name,\n+ sketch,\n+ sketch_id,\n+ current_user,\n+ enable_stream)\n+\n+ try:\n+ with open(file_path, 'ab') as fh:\n+ fh.seek(chunk_byte_offset)\n+ fh.write(file_storage.read())\n+ except OSError as e:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to write data with error: {0!s}.'.format(e))\n+\n+ if (chunk_index + 1) != chunk_total_chunks:\n+ schema = {\n+ 'meta': {\n+ 'file_upload': True,\n+ 'upload_complete': False,\n+ 'total_chunks': chunk_total_chunks,\n+ 'chunk_index': chunk_index,\n+ 'file_size': file_size},\n+ 'objects': []}\n+ response = jsonify(schema)\n+ response.status_code = HTTP_STATUS_CODE_CREATED\n+ return response\n+ if os.path.getsize(file_path) != file_size:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to save file correctly, inconsistent file size '\n+ '({0:d} but should have been {1:d})'.format(\n+ os.path.getsize(file_path), file_size))\n+\n+ meta = {\n+ 'file_upload': True,\n+ 'upload_complete': True,\n+ 'file_size': file_size,\n+ 'total_chunks': chunk_total_chunks,\n+ }\n+\n+ return self._complete_upload(\n+ file_path=file_path,\n+ file_extension=file_extension,\n+ timeline_name=timeline_name,\n+ index_name=index_name,\n+ sketch=sketch,\n+ sketch_id=sketch_id,\n+ current_user=current_user,\n+ enable_stream=enable_stream,\n+ meta=meta)\n+\n+ def _complete_upload(\n+ file_path, file_extension, timeline_name, index_name, sketch, sketch_id, current_user, enable_stream, meta=None):\n# Check if search index already exists.\nsearchindex = SearchIndex.query.filter_by(\nname=timeline_name,\n@@ -1590,7 +1656,6 @@ class UploadFileResource(ResourceMixin, Resource):\ndb_session.add(timeline)\ndb_session.commit()\n- enable_stream = form.enable_stream.data\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks\n@@ -1603,10 +1668,10 @@ class UploadFileResource(ResourceMixin, Resource):\n# pylint: disable=no-else-return\nif timeline:\nreturn self.to_json(\n- timeline, status_code=HTTP_STATUS_CODE_CREATED)\n+ timeline, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\nreturn self.to_json(\n- searchindex, status_code=HTTP_STATUS_CODE_CREATED)\n+ searchindex, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\nclass TaskResource(ResourceMixin, Resource):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -251,6 +251,12 @@ class UploadFileForm(BaseForm):\nindex_name = StringField('Index Name', validators=[Optional()])\nenable_stream = BooleanField(\n'Enable stream', false_values={False, 'false', ''}, default=False)\n+ chunk_index = IntegerField('Chunk Index', validators=[Optional()])\n+ chunk_byte_offset = IntegerField(\n+ 'Chunk Byte Offset', validators=[Optional()])\n+ chunk_total_chunks = IntegerField(\n+ 'Total Chunk Count', validators=[Optional()])\n+ total_file_size = IntegerField('Total File size', validators=[Optional()])\nclass StoryForm(BaseForm):\n" } ]
Python
Apache License 2.0
google/timesketch
Initial changes to importer and upload API.
263,133
10.02.2020 15:47:45
0
a9b52c814d5b9b1f17b04d4701cfb266d30d53fe
Further fixes and cleanups.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -41,7 +41,7 @@ class ImportStreamer(object):\n# Number of bytes in a binary file before automatically\n# chunking it up into smaller pieces.\n- SIZE_THRESHOLD = 10485760\n+ FILE_SIZE_THRESHOLD = 104857600 # 100 Mb.\ndef __init__(self, entry_threshold=None):\n\"\"\"Initialize the upload streamer.\"\"\"\n@@ -153,40 +153,58 @@ class ImportStreamer(object):\n\"\"\"\nresource_url = '{0:s}/upload/'.format(self._sketch.api.api_root)\nfile_size = os.path.getsize(file_path)\n+\n+ if self._timeline_name:\n+ timeline_name = self._timeline_name\n+ else:\n+ file_name = os.basename(file_path)\n+ file_name_no_ext, _, _ = file_name.rpartition('.')\n+ timeline_name = file_name_no_ext\n+\ndata = {\n'name': timeline_name,\n- 'sketch_id': self.id,\n+ 'sketch_id': self._sketch.id,\n'total_file_size': file_size,\n}\n- if file_size >= self.SIZE_THRESHOLD:\n+ if file_size <= self.FILE_SIZE_THRESHOLD:\nfile_dict = {\n'file': open(file_path, 'rb')}\nresponse = self._sketch.api.session.post(\nresource_url, files=file_dict, data=data)\nelse:\n- chunks = int(math.ceil(float(file_size) / self._threshold))\n+ chunks = int(math.ceil(float(file_size) / self.FILE_SIZE_THRESHOLD))\ndata['chunk_total_chunks'] = chunks\nfor index in range(0, chunks):\ndata['chunk_index'] = index\n- start = self.SIZE_THRESHOLD * index\n+ start = self.FILE_SIZE_THRESHOLD * index\ndata['chunk_byte_offset'] = start\nfh = open(file_path, 'rb')\nfh.seek(start)\n- data = fh.read(self.SIZE_TRESHOLD)\n- file_stream = io.BytesIO(data)\n+ binary_data = fh.read(self.FILE_SIZE_THRESHOLD)\n+ file_stream = io.BytesIO(binary_data)\n+ file_stream.name = file_path\nfile_dict = {'file': file_stream}\nresponse = self._sketch.api.session.post(\nresource_url, files=file_dict, data=data)\n+ if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ # TODO (kiddi): Re-do this chunk.\n+ raise RuntimeError(\n+ 'Error uploading data chunk: {0:d}/{1:d}. Status code: '\n+ '{2:d} - {3:s} {4:s}'.format(\n+ index, chunks, response.status_code,\n+ response.reason, response.text))\n+\n+ if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error uploading data: [{0:d}] {1:s} {2:s}, file: {3:s}, '\n+ 'index {4:s}'.format(\n+ response.status_code, response.reason, response.text,\n+ file_path, self._index))\n+\nresponse_dict = response.json()\n- timeline_dict = response_dict['objects'][0]\n- timeline_obj = timeline.Timeline(\n- timeline_id=timeline_dict['id'],\n- sketch_id=self.id,\n- api=self.api,\n- name=timeline_dict['name'],\n- searchindex=timeline_dict['searchindex']['index_name'])\n- return timeline_obj\n+ self._last_response = response_dict\n+ self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\ndef add_data_frame(self, data_frame, part_of_iter=False):\n\"\"\"Add a data frame into the buffer.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1551,24 +1551,27 @@ class UploadFileResource(ResourceMixin, Resource):\nfile_path = os.path.join(upload_folder, filename)\n- chunk_index = form.chunk_index.data or None\n- chunk_byte_offset = form.chunk_byte_offset or None\n- chunk_total_chunks = form.chunk_total_chunks or None\n- file_size = form.total_file_size or None\n+ chunk_index = form.chunk_index.data\n+ chunk_byte_offset = form.chunk_byte_offset.data\n+ chunk_total_chunks = form.chunk_total_chunks.data\n+ file_size = form.total_file_size.data or None\nenable_stream = form.enable_stream.data\n- if chunk_index is None:\n+ if chunk_total_chunks is None:\nfile_storage.save(file_path)\nreturn self._complete_upload(\n- file_path,\n- file_extension,\n- timeline_name,\n- index_name,\n- sketch,\n- sketch_id,\n- current_user,\n- enable_stream)\n+ file_path=file_path,\n+ file_extension=file_extension,\n+ timeline_name=timeline_name,\n+ index_name=index_name,\n+ sketch=sketch,\n+ sketch_id=sketch_id,\n+ enable_stream=enable_stream)\n+ # For file chunks we need the correct filepath, otherwise each chunk\n+ # will get their own UUID as a filename.\n+ file_path = os.path.join(\n+ upload_folder, os.path.basename(file_storage.filename))\ntry:\nwith open(file_path, 'ab') as fh:\nfh.seek(chunk_byte_offset)\n@@ -1612,12 +1615,31 @@ class UploadFileResource(ResourceMixin, Resource):\nindex_name=index_name,\nsketch=sketch,\nsketch_id=sketch_id,\n- current_user=current_user,\nenable_stream=enable_stream,\nmeta=meta)\ndef _complete_upload(\n- file_path, file_extension, timeline_name, index_name, sketch, sketch_id, current_user, enable_stream, meta=None):\n+ self, file_path, file_extension, timeline_name, index_name, sketch,\n+ sketch_id, enable_stream, meta=None):\n+ \"\"\"Creates a full pipeline for an uploaded file and returns the results.\n+\n+ Args:\n+ file_path: full path to the file that was uploaded.\n+ file_extension: the extension of the uploaded file.\n+ timeline_name: name the timeline will be stored under in the\n+ datastore.\n+ index_name: the index name for the file.\n+ sketch: a Sketch model object.\n+ sketch_id: integer with the sketch ID.\n+ enable_stream: boolean indicating whether this is file is part of a\n+ stream or not.\n+ meta: optional dict with additional meta fields that will be\n+ included in the return.\n+\n+ Returns:\n+ A timeline if created otherwise a search index in JSON (instance\n+ of flask.wrappers.Response)\n+ \"\"\"\n# Check if search index already exists.\nsearchindex = SearchIndex.query.filter_by(\nname=timeline_name,\n@@ -1658,6 +1680,7 @@ class UploadFileResource(ResourceMixin, Resource):\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\n+ # pylint: disable=import-outside-toplevel\nfrom timesketch.lib import tasks\npipeline = tasks.build_index_pipeline(\nfile_path, timeline_name, index_name, file_extension, sketch_id,\n@@ -1679,6 +1702,7 @@ class TaskResource(ResourceMixin, Resource):\ndef __init__(self):\nsuper(TaskResource, self).__init__()\n+ # pylint: disable=import-outside-toplevel\nfrom timesketch import create_celery_app\nself.celery = create_celery_app()\n@@ -2069,6 +2093,7 @@ class AnalyzerRunResource(ResourceMixin, Resource):\n'Kwargs needs to be a dictionary of parameters.')\n# Import here to avoid circular imports.\n+ # pylint: disable=import-outside-toplevel\nfrom timesketch.lib import tasks\ntry:\nanalyzer_group, session_id = tasks.build_sketch_analysis_pipeline(\n@@ -2153,6 +2178,7 @@ class TimelineListResource(ResourceMixin, Resource):\n# Run sketch analyzers when timeline is added. Import here to avoid\n# circular imports.\nif current_app.config.get('AUTO_SKETCH_ANALYZERS'):\n+ # pylint: disable=import-outside-toplevel\nfrom timesketch.lib import tasks\nsketch_analyzer_group, _ = tasks.build_sketch_analysis_pipeline(\nsketch_id, searchindex_id, current_user.id)\n" } ]
Python
Apache License 2.0
google/timesketch
Further fixes and cleanups.
263,133
11.02.2020 08:46:07
0
fa9c9855fee282f087bca478051b929b0ffaae74
Adding the ability to specify index on plaso files.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -145,11 +145,12 @@ class ImportStreamer(object):\nself._timeline_id = response_dict.get('objects', [{}])[0].get('id')\nself._last_response = response_dict\n- def _upload_binary_file(self, file_path):\n+ def _upload_binary_file(self, file_path, index=None):\n\"\"\"Upload binary data to Timesketch, potentially chunking it up.\nArgs:\nfile_path: a full path to the file that is about to be uploaded.\n+ index: optional string to specify the ES index to store the file in.\n\"\"\"\nresource_url = '{0:s}/upload/'.format(self._sketch.api.api_root)\nfile_size = os.path.getsize(file_path)\n@@ -165,6 +166,7 @@ class ImportStreamer(object):\n'name': timeline_name,\n'sketch_id': self._sketch.id,\n'total_file_size': file_size,\n+ 'index_name': self._index,\n}\nif file_size <= self.FILE_SIZE_THRESHOLD:\nfile_dict = {\n@@ -350,7 +352,7 @@ class ImportStreamer(object):\nfilepath, delimiter=delimiter, chunksize=self._threshold):\nself.add_data_frame(chunk_frame, part_of_iter=True)\nelif file_ending == 'plaso':\n- self._upload_binary_file(filepath)\n+ self._upload_binary_file(filepath, index=self._index)\nelif file_ending == 'jsonl':\ndata_frame = None\nwith open(filepath, 'r') as fh:\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to specify index on plaso files.
263,133
11.02.2020 09:07:14
0
3836e96349da6cb82e16549214990761351dd37d
Fixing index settings.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -145,12 +145,11 @@ class ImportStreamer(object):\nself._timeline_id = response_dict.get('objects', [{}])[0].get('id')\nself._last_response = response_dict\n- def _upload_binary_file(self, file_path, index=None):\n+ def _upload_binary_file(self, file_path):\n\"\"\"Upload binary data to Timesketch, potentially chunking it up.\nArgs:\nfile_path: a full path to the file that is about to be uploaded.\n- index: optional string to specify the ES index to store the file in.\n\"\"\"\nresource_url = '{0:s}/upload/'.format(self._sketch.api.api_root)\nfile_size = os.path.getsize(file_path)\n@@ -352,7 +351,7 @@ class ImportStreamer(object):\nfilepath, delimiter=delimiter, chunksize=self._threshold):\nself.add_data_frame(chunk_frame, part_of_iter=True)\nelif file_ending == 'plaso':\n- self._upload_binary_file(filepath, index=self._index)\n+ self._upload_binary_file(filepath)\nelif file_ending == 'jsonl':\ndata_frame = None\nwith open(filepath, 'r') as fh:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1570,8 +1570,7 @@ class UploadFileResource(ResourceMixin, Resource):\n# For file chunks we need the correct filepath, otherwise each chunk\n# will get their own UUID as a filename.\n- file_path = os.path.join(\n- upload_folder, os.path.basename(file_storage.filename))\n+ file_path = os.path.join(upload_folder, index_name)\ntry:\nwith open(file_path, 'ab') as fh:\nfh.seek(chunk_byte_offset)\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing index settings.
263,133
11.02.2020 10:52:55
0
10b3b46a7735e2b2b24e79e050a10cf9e951821b
Making minor changes to the documentation.
[ { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "@@ -171,12 +171,37 @@ Let's look at an example:\n```\n-## CSV or JSONL file.\n+## A file, CSV, PLASO or JSONL.\n+\n+Files can also be added using the importer. That is files that are\n+supported by Timesketch. These would be CSV, JSONL (JSON lines) and\n+a plaso file.\n+\n+The function `add_file` in the importer is used to add a file.\n+\n+Here is an example of how the importer can be used:\n```\n-#TODO: Add an example here.\n+from timesketch_api_client import importer\n+from timesketch_api_client import client\n+\n+...\n+\n+with importer.ImportStreamer() as streamer:\n+ streamer.set_sketch(my_sketch)\n+ streamer.set_timeline_name('my_file_with_a_timeline')\n+ streamer.set_timestamp_description('some_description')\n+\n+ streamer.add_file('/path_to_file/mydump.plaso')\n```\n+If the file that is being imported is either a CSV or a JSONL file the importer\n+will split the file up if it is large and send it in pieces. Each piece of the\n+file will be indexed as soon as it is uploaded to the backend.\n+\n+In the case of a plaso file, it will also be split up into smaller chunks and\n+uploaded. However indexing does not start until all pieces have been transferred\n+and the final plaso storage file reassambled.\n## Excel Sheet\n" } ]
Python
Apache License 2.0
google/timesketch
Making minor changes to the documentation.
263,178
12.02.2020 12:43:00
-3,600
bec86711ae8eb9c23d0f9801de7da7791bd62a96
Changes to use pybuild debhelper
[ { "change_type": "MODIFY", "old_path": "config/dpkg/changelog", "new_path": "config/dpkg/changelog", "diff": "-timesketch (20190609-1) unstable; urgency=low\n+timesketch (20200131-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Sun, 09 Jun 2019 10:46:39 +0200\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Wed, 12 Feb 2020 07:08:38 +0100\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -2,9 +2,8 @@ Source: timesketch\nSection: python\nPriority: extra\nMaintainer: Timesketch development team <timesketch-dev@googlegroups.com>\n-Build-Depends: debhelper (>= 9), dh-python, dh-systemd (>= 1.5), python-all (>= 2.7~), python-setuptools, python-pip, python3-all (>= 3.4~), python3-setuptools, python3-pip\n-Standards-Version: 3.9.5\n-X-Python-Version: >= 2.7\n+Build-Depends: debhelper (>= 9), dh-python, dh-systemd (>= 1.5), python3-all (>= 3.4~), python3-setuptools, python3-pip\n+Standards-Version: 4.1.4\nX-Python3-Version: >= 3.4\nHomepage: http://timesketch.org\n@@ -17,15 +16,6 @@ Description: Data files for Timesketch\norganize timelines and analyze them all at the same time. Add meaning\nto your raw data with rich annotations, comments, tags and stars.\n-Package: python-timesketch\n-Architecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python-alembic (>= 0.9.5), python-altair (>= 2.4.1), python-amqp (>= 2.2.1), python-aniso8601 (>= 1.2.1), python-asn1crypto (>= 0.24.0), python-attr (>= 19.1.0), python-bcrypt (>= 3.1.3), python-billiard (>= 3.5.0.3), python-blinker (>= 1.4), python-bs4 (>= 4.6.3), python-celery (>= 4.1.0), python-certifi (>= 2017.7.27.1), python-cffi (>= 1.10.0), python-chardet (>= 3.0.4), python-click (>= 6.7), python-configparser (>= 3.5.0), python-cryptography (>= 2.4.1), python-datasketch (>= 1.2.5), python-dateutil (>= 2.6.1), python-editor (>= 1.0.3), python-elasticsearch (>= 6.0), python-entrypoints (>= 0.2.3), python-enum34 (>= 1.1.6), python-flask (>= 1.0.2), python-flask-bcrypt (>= 0.7.1), python-flask-login (>= 0.4.0), python-flask-migrate (>= 2.1.1), python-flask-restful (>= 0.3.6), python-flask-script (>= 2.0.5), python-flask-sqlalchemy (>= 2.2), python-flaskext.wtf (>= 0.14.2), python-gunicorn (>= 19.7.1), python-idna (>= 2.6), python-ipaddress (>= 1.0.22), python-itsdangerous (>= 0.24), python-jinja2 (>= 2.10), python-jsonschema (>= 2.6.0), python-jwt (>= 1.6.4), python-kombu (>= 4.1.0), python-mako (>= 1.0.7), python-markupsafe (>= 1.0), python-neo4jrestclient (>= 2.1.1), python-numpy (>= 1.13.3), python-pandas (>= 0.22.0), python-parameterized (>= 0.6.1), python-pycparser (>= 2.18), python-pyrsistent (>= 0.14.11), python-redis (>= 2.10.6), python-requests (>= 2.20.1), python-six (>= 1.10.0), python-sqlalchemy (>= 1.1.13), python-toolz (>= 0.8.2), python-typing (>= 3.6.2), python-tz, python-urllib3 (>= 1.24.1), python-vine (>= 1.1.4), python-werkzeug (>= 0.14.1), python-wtforms (>= 2.1), python-yaml (>= 3.10), ${python:Depends}, ${misc:Depends}\n-Description: Python 2 module of Timesketch\n- Timesketch is a web based tool for collaborative forensic\n- timeline analysis. Using sketches you and your collaborators can easily\n- organize timelines and analyze them all at the same time. Add meaning\n- to your raw data with rich annotations, comments, tags and stars.\n-\nPackage: python3-timesketch\nArchitecture: all\nDepends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-ipaddress (>= 1.0.22), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\n" }, { "change_type": "DELETE", "old_path": "config/dpkg/python-timesketch.install", "new_path": null, "diff": "-usr/lib/python2*/dist-packages/timesketch/*.py\n-usr/lib/python2*/dist-packages/timesketch/*/*.py\n-usr/lib/python2*/dist-packages/timesketch/*/*/*.py\n-usr/lib/python2*/dist-packages/timesketch/frontend/dist/*\n-usr/lib/python2*/dist-packages/timesketch/frontend/dist/*/*\n-usr/lib/python2*/dist-packages/timesketch/static/*/*\n-usr/lib/python2*/dist-packages/timesketch/static/*/*/*\n-usr/lib/python2*/dist-packages/timesketch/templates/*\n-usr/lib/python2*/dist-packages/timesketch/templates/*/*\n-usr/lib/python2*/dist-packages/timesketch*.egg-info/*\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/rules", "new_path": "config/dpkg/rules", "diff": "#!/usr/bin/make -f\n%:\n- dh $@ --buildsystem=python_distutils --with=python2,python3,systemd\n+ dh $@ --buildsystem=pybuild --with=python3,systemd\n-.PHONY: override_dh_auto_clean\n-override_dh_auto_clean:\n- dh_auto_clean\n- rm -rf build timesketch.egg-info/SOURCES.txt timesketch.egg-info/PKG-INFO\n-\n-.PHONY: override_dh_auto_build\n-override_dh_auto_build:\n- dh_auto_build\n- set -ex; for python in $(shell py3versions -r); do \\\n- $$python setup.py build; \\\n- done;\n-\n-.PHONY: override_dh_auto_install\n-override_dh_auto_install:\n- dh_auto_install --destdir $(CURDIR)\n- set -ex; for python in $(shell py3versions -r); do \\\n- $$python setup.py install --root=$(CURDIR) --install-layout=deb; \\\n- done;\n+.PHONY: override_dh_auto_test\n+override_dh_auto_test:\n.PHONY: override_dh_installinit\noverride_dh_installinit:\n" } ]
Python
Apache License 2.0
google/timesketch
Changes to use pybuild debhelper (#1101)
263,178
12.02.2020 12:52:04
-3,600
2cc9d0baba3d4ef89e6b2449c228c4308901b110
Changed setup.py to support bdist
[ { "change_type": "MODIFY", "old_path": "config/travis/runtests.sh", "new_path": "config/travis/runtests.sh", "diff": "@@ -24,4 +24,7 @@ elif test ${MODE} = \"pypi\"; then\nelif test \"${TRAVIS_OS_NAME}\" = \"linux\"; then\npython3 ./run_tests.py\n+ python3 ./setup.py bdist\n+\n+ python3 ./setup.py sdist\nfi\n" }, { "change_type": "MODIFY", "old_path": "setup.py", "new_path": "setup.py", "diff": "sudo python setup.py install\n\"\"\"\n+from __future__ import print_function\nfrom __future__ import unicode_literals\nimport glob\nimport os\n+import sys\nfrom setuptools import find_packages\nfrom setuptools import setup\n@@ -33,6 +35,13 @@ except ImportError: # for pip <= 9.0.3\nfrom pip.download import PipSession\nfrom pip.req import parse_requirements\n+version_tuple = (sys.version_info[0], sys.version_info[1])\n+if version_tuple < (3, 5):\n+ print((\n+ 'Unsupported Python version: {0:s}, version 3.5 or higher '\n+ 'required.').format(sys.version))\n+ sys.exit(1)\n+\ntimesketch_version = '20200131'\n@@ -59,7 +68,9 @@ setup(\n],\ndata_files=[\n('share/timesketch', glob.glob(\n- os.path.join('data', '*'), recursive=True)),\n+ os.path.join('data', '*.*'))),\n+ ('share/timesketch/linux', glob.glob(\n+ os.path.join('data', 'linux', '*.*'))),\n('share/doc/timesketch', [\n'AUTHORS', 'LICENSE', 'README.md']),\n],\n" } ]
Python
Apache License 2.0
google/timesketch
Changed setup.py to support bdist (#1103) Co-authored-by: Johan Berggren <jberggren@gmail.com>
263,133
13.02.2020 09:14:59
0
ad4ce3859b3441700b4809598080fe8e44b7c044
Adding a new frontend to the importer, to assist with file uploads.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "\"\"\"This is the setup file for the project.\"\"\"\nfrom __future__ import unicode_literals\n+import os\n+import glob\n+\nfrom setuptools import find_packages\nfrom setuptools import setup\n@@ -36,6 +39,7 @@ setup(\npackages=find_packages(),\ninclude_package_data=True,\nzip_safe=False,\n+ scripts=glob.glob(os.path.join('tools', '[a-z]*.py')),\ninstall_requires=frozenset([\n'pandas',\n'requests',\n@@ -43,5 +47,6 @@ setup(\n'xlrd',\n'google-auth',\n'google_auth_oauthlib',\n+ 'pyyaml',\n'beautifulsoup4']),\n)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -240,6 +240,10 @@ class TimesketchApi(object):\n\"\"\"\nif auth_mode == 'oauth':\nreturn self._create_oauth_session(client_id, client_secret)\n+ elif auth_mode == 'oauth_local':\n+ return self._create_oauth_session(\n+ client_id=client_id, client_secret=client_secret,\n+ run_server=False, skip_open=True)\nsession = requests.Session()\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/tools/timesketch_importer.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"A simple frontend to the Timesketch data importer.\n+\n+This tool is limited to upload files to Timesketch, which is only\n+part of the capabilities of the importer API.\n+\"\"\"\n+from __future__ import unicode_literals\n+\n+import argparse\n+import getpass\n+import json\n+import logging\n+import os\n+import sys\n+\n+from typing import Dict\n+\n+import yaml\n+\n+from timesketch_api_client import client\n+from timesketch_api_client import importer\n+from timesketch_api_client import sketch\n+\n+\n+def get_client(\n+ host: str, username: str, password: str='', client_id: str='',\n+ client_secret: str='', run_local: bool=False) -> client.TimesketchApi:\n+ \"\"\"Returns a Timesketch API client.\n+\n+ Args:\n+ host (str): the Timesketch host.\n+ username (str): the username to authenticate with.\n+ password (str): optional used if OAUTH is not the authentication\n+ mechanism.\n+ client_id (str): if OAUTH is used then a client ID needs to be set.\n+ client_secret (str): if OAUTH is used then a client secret needs to be\n+ set.\n+ run_local (bool): if OAUTH is used to authenticate and set to True\n+ then the authentication URL is printed on screen\n+ instead of starting a web server, this suits well\n+ if the connection is over a SSH connection for\n+ instance.\n+\n+ Returns:\n+ A Timesketch API client object or none if unable to authenticate.\n+ \"\"\"\n+ if run_local and client_secret:\n+ auth_mode = 'oauth_local'\n+ elif client_secret:\n+ auth_mode = 'oauth'\n+ elif password:\n+ auth_mode = 'timesketch'\n+ else:\n+ logging.error(\n+ 'Neither password nor client secret provided, unable '\n+ 'to authenticate')\n+ return\n+\n+ if not host.startswith('http'):\n+ host = 'https://{0:s}'.format(host)\n+\n+ api_client = client.TimesketchApi(\n+ host_uri=host, username=username, password=password,\n+ client_id=client_id, client_secret=client_secret, auth_mode=auth_mode)\n+\n+ return api_client\n+\n+\n+def upload_file(\n+ sketch: sketch.Sketch, config:Dict[str, any], file_path:str) -> str:\n+ \"\"\"Uploads a file to Timesketch.\n+\n+ Args:\n+ sketch (sketch.Sketch): a sketch object to point to the sketch the data\n+ will be imported to.\n+ config (dict): dict with settings for the importer.\n+ file_path (str): the path to the file to upload.\n+\n+ Returns:\n+ A string with results (whether successful or not).\n+ \"\"\"\n+ if not sketch or not hasattr(sketch, 'id'):\n+ return 'Sketch needs to be set'\n+\n+ with importer.ImportStreamer() as streamer:\n+ streamer.set_sketch(sketch)\n+\n+ format_string = config.get('message_format_string')\n+ if format_string:\n+ streamer.set_message_format_string(format_string)\n+ timeline_name = config.get('timeline_name')\n+ if timeline_name:\n+ streamer.set_timeline_name(timeline_name)\n+ index_name = config.get('index_name')\n+ if index_name:\n+ streamer.set_index_name(index_name)\n+ time_desc = config.get('timestamp_description')\n+ if time_desc:\n+ streamer.set_timestamp_description(time_desc)\n+\n+ streamer.add_file(file_path)\n+\n+ return 'File got successfully uploaded to sketch: {0:d}'.format(sketch.id)\n+\n+\n+if __name__ == '__main__':\n+ argument_parser = argparse.ArgumentParser(\n+ description='A tool to upload data to Timesketch, using the API.')\n+\n+ auth_group = argument_parser.add_argument_group('Authentication Arguments')\n+ auth_group.add_argument(\n+ '-u', '--user', '--username', action='store', dest='username',\n+ type=str, help='The username of the Timesketch user.')\n+ auth_group.add_argument(\n+ '-p', '--password', '--pwd', action='store', type=str, dest='password',\n+ help=(\n+ 'If authenticated with password, provide the password on the CLI. '\n+ 'If neither password is provided nor a password prompt an OAUTH '\n+ 'connection is assumed.'))\n+ auth_group.add_argument(\n+ '--pwd-prompt', '--pwd_prompt', action='store_true', default=False,\n+ dest='pwd_prompt', help='Prompt for password.')\n+ auth_group.add_argument(\n+ '--client-secret', '--client_secret', action='store', type=str,\n+ default='', dest='client_secret', help='OAUTH client secret.')\n+ auth_group.add_argument(\n+ '--client-id', '--client_id', action='store', type=str, default='',\n+ dest='client_id', help='OAUTH client ID.')\n+ auth_group.add_argument(\n+ '--run_local', '--run-local', action='store_true', dest='run_local',\n+ help=(\n+ 'If OAUTH is used to authenticate and the connection is over '\n+ 'SSH then it is recommended to set this option. When set an '\n+ 'authentication URL is prompted on the screen, requiring a '\n+ 'copy/paste into a browser to complete the OAUTH dance.'))\n+\n+ config_group = argument_parser.add_argument_group(\n+ 'Configuration Arguments')\n+ config_group.add_argument(\n+ '--config-file', '--config_file', action='store', type=str,\n+ default='', metavar='FILEPATH', dest='config_file', help=(\n+ 'Path to a YAML config file that can be used to store '\n+ 'all parameters to this tool (except this path)'))\n+ config_group.add_argument(\n+ '--host', '--hostname', '--host-uri', '--host_uri', dest='host',\n+ type=str, default='', action='store',\n+ help='The URI to the Timesketch instance')\n+ config_group.add_argument(\n+ '--format_string', '--format-string', type=str, action='store',\n+ dest='format_string', default='', help=(\n+ 'Formatting string for the message field. If there is no message '\n+ 'field in the input data a message string can be composed using '\n+ 'a format string.'))\n+ config_group.add_argument(\n+ '--timeline_name', '--timeline-name', action='store', type=str,\n+ dest='timeline_name', default='', help=(\n+ 'String that will be used as the timeline name.'))\n+ config_group.add_argument(\n+ '--index-name', '--index_name', action='store', type=str, default='',\n+ dest='index_name', help=(\n+ 'If the data should be imported into a specific timeline the '\n+ 'index name needs to be provided, otherwise a new index will '\n+ 'be generated.'))\n+ config_group.add_argument(\n+ '--timestamp_description', '--timestamp-description', '--time-desc',\n+ '--time_desc', action='store', type=str, default='', dest='time_desc',\n+ help='Value for the timestamp_description field.')\n+ config_group.add_argument(\n+ '--sketch_id', '--sketch-id', type=int, default=0, dest='sketch_id',\n+ action='store', help=(\n+ 'The sketch ID to store the timeline in, if no sketch ID is '\n+ 'provided a new sketch will be created.'))\n+\n+ argument_parser.add_argument(\n+ 'path', action='store', type=str, help=(\n+ 'Path to the file that is to be imported.'))\n+\n+ options = argument_parser.parse_args()\n+ config_options = {}\n+\n+ if options.config_file:\n+ if not os.path.isfile(options.config_file):\n+ logging.error('Config file does not exist ({0:s})'.format(\n+ options.config_file))\n+ sys.exit(1)\n+ with open(options.config_file, 'r') as fh:\n+ config_options = yaml.safe_load(fh)\n+\n+ if not os.path.isfile(options.path):\n+ logging.error('Path {0:s} is not valid, unable to continue.')\n+ sys.exit(1)\n+\n+ host = options.host or config_options.get('host', '')\n+ if not host:\n+ logging.error('Hostname for Timesketch server must be set.')\n+ sys.exit(1)\n+\n+ password = options.password or config_options.get('password', '')\n+ pwd_prompt = options.pwd_prompt or config_options.get(\n+ 'pwd_prompt', False)\n+ if not password and pwd_prompt:\n+ password = getpass.getpass('Type in the password: ')\n+\n+ client_id = options.client_id or config_options.get('client_id', '')\n+ client_secret = options.client_secret or config_options.get(\n+ 'client_secret', '')\n+ username = options.username or config_options.get('username', '')\n+ run_local = options.run_local or config_options.get('run_local', False)\n+\n+ ts_client = get_client(\n+ host=host, username=username, password=password, client_id=client_id,\n+ client_secret=client_secret, run_local=run_local)\n+\n+ if not ts_client:\n+ logging.error('Unable to create a Timesketch API client, exiting.')\n+ sys.exit(1)\n+\n+ sketch_id = options.sketch_id or config_options.get('sketch_id', 0)\n+ if sketch_id:\n+ sketch = ts_client.get_sketch(sketch_id)\n+ else:\n+ sketch = ts_client.create_sketch('New Sketch From Importer CLI')\n+\n+ if not sketch:\n+ logging.error('Unable to get sketch ID: {0:d}'.format(sketch_id))\n+ sys.exit(1)\n+\n+ config = {\n+ 'message_format_string': options.format_string or config_options.get(\n+ 'format_string', ''),\n+ 'timeline_name': options.timeline_name or config_options.get(\n+ 'timeline_name', ''),\n+ 'index_name': options.index_name or config_options.get(\n+ 'index_name', ''),\n+ 'timestamp_description': options.time_desc or config_options.get(\n+ 'timestamp_description', ''),\n+ }\n+\n+ result = upload_file(sketch=sketch, config=config, file_path=options.path)\n+ print(result)\n+\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a new frontend to the importer, to assist with file uploads.
263,133
13.02.2020 09:23:10
0
efe04ae9b4fdf97e5622f0d7026a29291c2a7349
Adding a documentation skeleton
[ { "change_type": "ADD", "old_path": null, "new_path": "docs/UploadData.md", "diff": "+# Upload Data to Timesketch\n+\n+There are several different ways to upload data to Timesketch. This document\n+attempts to explore them all.\n+\n+These are the different ways to upload data:\n+\n+1. Directly using the REST API.\n+2. Using the API client, or the importer library.\n+3. Using the web UI.\n+4. Using the importer CLI tool.\n+5. SCP or transferring a file to an upload folder on the Timesketch server.\n+\n+Let's explore each of these ways a bit further.\n+\n+## Using the REST API.\n+\n+```\n+TODO: add documentation\n+```\n+\n+## Using the API client.\n+\n+The API client defines an importer library that is used to help with\n+file or data uploads. This is documented further\n+[here](/docs/UploadDataViaAPI.md)\n+\n+## Using the Web UI.\n+\n+```\n+TODO: add documentation\n+```\n+## Using the importer CLI tool..\n+\n+```\n+TODO: add documentation\n+```\n+\n+## SCP/File Transfer to an Upload Folder\n+\n+```\n+TODO: add documentation\n+```\n+\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a documentation skeleton
263,133
13.02.2020 09:46:54
0
7c55365cf371670726f74f0c12f9041b3ad7bd5c
Updating the documentation.
[ { "change_type": "MODIFY", "old_path": "api_client/python/tools/timesketch_importer.py", "new_path": "api_client/python/tools/timesketch_importer.py", "diff": "@@ -237,11 +237,13 @@ if __name__ == '__main__':\nlogging.error('Unable to get sketch ID: {0:d}'.format(sketch_id))\nsys.exit(1)\n+ timeline_name = options.timeline_name or config_options.get(\n+ 'timeline_name', 'unnamed_timeline_imported_from_importer')\n+\nconfig = {\n'message_format_string': options.format_string or config_options.get(\n'format_string', ''),\n- 'timeline_name': options.timeline_name or config_options.get(\n- 'timeline_name', ''),\n+ 'timeline_name': timeline_name,\n'index_name': options.index_name or config_options.get(\n'index_name', ''),\n'timestamp_description': options.time_desc or config_options.get(\n" }, { "change_type": "MODIFY", "old_path": "docs/UploadData.md", "new_path": "docs/UploadData.md", "diff": "@@ -13,12 +13,6 @@ These are the different ways to upload data:\nLet's explore each of these ways a bit further.\n-## Using the REST API.\n-\n-```\n-TODO: add documentation\n-```\n-\n## Using the API client.\nThe API client defines an importer library that is used to help with\n@@ -30,15 +24,70 @@ file or data uploads. This is documented further\n```\nTODO: add documentation\n```\n-## Using the importer CLI tool..\n+## Using the importer CLI Tool.\n+\n+If the data that is to be imported is a single file then the importer tool\n+can be used. It utilizes the API client and the importer library to upload\n+the file. This is a simple wrapper around that library. The tool comes with\n+the installation of the timesketch API client.\n+\n+There are two methods to use the tool:\n+\n+1. Define all parameters on the command line.\n+2. Define all configuration in a YAML config file and only provide a path\n+to the tool (and the config file).\n+\n+The easiest way to discover the parameters and how to run the tool is to run:\n```\n-TODO: add documentation\n+$ timesketch_importer.py -h\n+```\n+\n+The minimum set of parameters to the run tool are:\n+\n+```\n+$ timesketch_importer.py --pwd-prompt -u <USERNAME> --host https://mytimesketch.com path_to_my_file.csv\n```\n+However if the authentication mechanism is OAUTH then `client_id` and\n+`client_secret` need to be set.\n+\n+Other parameters suggested to be set are `sketch_id` (if it isn't provided a\n+new sketch will be created) and `timeline_name` (otherwise a default name\n+will be chosen).\n+\n+In order to reduce the amount of parameters to pass to the tool a YAML\n+configuration file can be used. The format of it is simple:\n+\n+```\n+config_option: value\n+...\n+```\n+\n+The configuration options that can be defined in the YAML file are:\n+\n+| Option | Type | Notes |\n+| ------ | ---- | ----- |\n+| username | string | The username to use to authenticate against the Timesketch server |\n+| password | string | If password is used, it can be provided here (not recommended) |\n+| pwd_prompt | boolean | If set to True then the tool will prompt the user for a password, only used if password is used to authenticate |\n+| client_secret | string | If OAUTH is used for authentication then a client secret needs to be defined. |\n+| client_id | string | If OAUTH is used for authentication a client ID needs to be defined. |\n+| run_local | boolean | If set to True and OAUTH is used for authentication then an authentication URL is prompted on the screen that the user needs to follow in order to complete the OAUTH dance, this is particularly useful if the tool is run through a remote session, like SSH. |\n+| host | string | URI that points to the Timesketch instance. |\n+| format_string | string | Formatting string for the message field if it is not defined in the input data. |\n+| timeline_name | string | Name that will be used for the timeline as it gets imported into Timesketch. |\n+| index_name | string | If the data should be imported into a specific timeline the index needs to be defined, otherwise a new index will be generated. |\n+\n+\n## SCP/File Transfer to an Upload Folder\n```\nTODO: add documentation\n```\n+## Using the REST API.\n+\n+```\n+TODO: add documentation\n+```\n" } ]
Python
Apache License 2.0
google/timesketch
Updating the documentation.
263,133
13.02.2020 14:46:50
0
cbc1433d3459b807fee5ceac78ca18dc5cf88a09
Splitting JSONL files into chunks.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -288,13 +288,21 @@ class ImportStreamer(object):\nelif file_ending == 'jsonl':\ndata_frame = None\nwith open(filepath, 'r') as fh:\n- lines = [json.loads(x) for x in fh]\n+ line_number = 0\n+ lines = []\n+ for line in fh:\n+ line_number += 1\n+ lines.append(json.loads(line.strip()))\n+ if line_number < self._threshold:\n+ continue\n+\ndata_frame = pandas.DataFrame(lines)\n- if data_frame is None:\n- raise TypeError('Unable to parse the JSON file.')\n- if data_frame.empty:\n- raise TypeError('Is the JSON file empty?')\n+ lines = []\n+ line_number = 0\n+ if not data_frame.empty:\n+ self.add_data_frame(data_frame, part_of_iter=True)\n+ data_frame = pandas.DataFrame(lines)\nself.add_data_frame(data_frame)\nelse:\nraise TypeError(\n" } ]
Python
Apache License 2.0
google/timesketch
Splitting JSONL files into chunks.
263,133
13.02.2020 15:50:15
0
af8281226e8fcfbf81fbb05026c0dbe111debea6
Changing the way the json lines was handled, simplifying.'
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -286,24 +286,12 @@ class ImportStreamer(object):\nelif file_ending == 'plaso':\nself._sketch.upload(self._timeline_name, filepath, self._index)\nelif file_ending == 'jsonl':\n- data_frame = None\nwith open(filepath, 'r') as fh:\n- line_number = 0\n- lines = []\nfor line in fh:\n- line_number += 1\n- lines.append(json.loads(line.strip()))\n- if line_number < self._threshold:\n- continue\n-\n- data_frame = pandas.DataFrame(lines)\n- lines = []\n- line_number = 0\n- if not data_frame.empty:\n- self.add_data_frame(data_frame, part_of_iter=True)\n-\n- data_frame = pandas.DataFrame(lines)\n- self.add_data_frame(data_frame)\n+ try:\n+ self.add_json(line.strip())\n+ except TypeError as e:\n+ logging.error('Unable to decode line: {0!s}'.format(e))\nelse:\nraise TypeError(\n'File needs to have a file extension of: .csv, .jsonl or '\n" } ]
Python
Apache License 2.0
google/timesketch
Changing the way the json lines was handled, simplifying.'
263,133
13.02.2020 16:52:28
0
7d1e0825e87bb5934f0e75769873714c9086abde
minor adjustments to documentation
[ { "change_type": "MODIFY", "old_path": "docs/UploadData.md", "new_path": "docs/UploadData.md", "diff": "@@ -79,6 +79,21 @@ The configuration options that can be defined in the YAML file are:\n| timeline_name | string | Name that will be used for the timeline as it gets imported into Timesketch. |\n| index_name | string | If the data should be imported into a specific timeline the index needs to be defined, otherwise a new index will be generated. |\n+An example config file would be:\n+```\n+$ cat importer.config\n+username: dev\n+pwd_prompt: True\n+host: https://myinstance.goodcorp.com\n+```\n+\n+And then run the tool:\n+\n+```\n+$ timesketch_importer.py --config_file importer.config --timeline_name super_secret_timeline cases/secret_log.jsonl\n+```\n+\n+For larger files the importer will split them up into pieces before uploading.\n## SCP/File Transfer to an Upload Folder\n" } ]
Python
Apache License 2.0
google/timesketch
minor adjustments to documentation
263,178
15.02.2020 14:07:30
-3,600
58b881714c6b5a08281239e256124408ed7a3ee2
Updated l2tdevtools configuration and dpkg files
[ { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -4,7 +4,7 @@ Priority: extra\nMaintainer: Timesketch development team <timesketch-dev@googlegroups.com>\nBuild-Depends: debhelper (>= 9), dh-python, dh-systemd (>= 1.5), python3-all (>= 3.4~), python3-setuptools, python3-pip\nStandards-Version: 4.1.4\n-X-Python3-Version: >= 3.4\n+X-Python3-Version: >= 3.5\nHomepage: http://timesketch.org\nPackage: timesketch-data\n@@ -18,7 +18,7 @@ Description: Data files for Timesketch\nPackage: python3-timesketch\nArchitecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-ipaddress (>= 1.0.22), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\nDescription: Python 3 module of Timesketch\nTimesketch is a web based tool for collaborative forensic\ntimeline analysis. Using sketches you and your collaborators can easily\n" }, { "change_type": "MODIFY", "old_path": "dependencies.ini", "new_path": "dependencies.ini", "diff": "[alembic]\n-dpkg_name: python-alembic\n+dpkg_name: python3-alembic\nminimum_version: 0.9.5\n-rpm_name: python2-alembic\n+rpm_name: python3-alembic\n[altair]\n-dpkg_name: python-altair\n+dpkg_name: python3-altair\nminimum_version: 2.4.1\n-rpm_name: python2-altair\n+rpm_name: python3-altair\n[amqp]\n-dpkg_name: python-amqp\n+dpkg_name: python3-amqp\nminimum_version: 2.2.1\n-rpm_name: python2-amqp\n+rpm_name: python3-amqp\n[aniso8601]\n-dpkg_name: python-aniso8601\n+dpkg_name: python3-aniso8601\nminimum_version: 1.2.1\n-rpm_name: python2-aniso8601\n+rpm_name: python3-aniso8601\n[asn1crypto]\n-dpkg_name: python-asn1crypto\n+dpkg_name: python3-asn1crypto\nminimum_version: 0.24.0\n-rpm_name: python2-asn1crypto\n+rpm_name: python3-asn1crypto\n[attrs]\n-dpkg_name: python-attr\n+dpkg_name: python3-attr\nminimum_version: 19.1.0\n-rpm_name: python2-attrs\n+rpm_name: python3-attrs\n[bcrypt]\n-dpkg_name: python-bcrypt\n+dpkg_name: python3-bcrypt\nminimum_version: 3.1.3\n-rpm_name: python2-bcrypt\n+rpm_name: python3-bcrypt\n[billiard]\n-dpkg_name: python-billiard\n+dpkg_name: python3-billiard\nminimum_version: 3.5.0.3\n-rpm_name: python2-billiard\n+rpm_name: python3-billiard\n[blinker]\n-dpkg_name: python-blinker\n+dpkg_name: python3-blinker\nminimum_version: 1.4\n-rpm_name: python2-blinker\n+rpm_name: python3-blinker\n[bs4]\n-dpkg_name: python-bs4\n+dpkg_name: python3-bs4\nminimum_version: 4.6.3\npypi_name: beautifulsoup4\n-rpm_name: python2-beautifulsoup4\n+rpm_name: python3-beautifulsoup4\nversion_property: __version__\n[celery]\n-dpkg_name: python-celery\n+dpkg_name: python3-celery\nminimum_version: 4.1.0\n-rpm_name: python2-celery\n+rpm_name: python3-celery\n[certifi]\n-dpkg_name: python-certifi\n+dpkg_name: python3-certifi\nminimum_version: 2017.7.27.1\n-rpm_name: python2-certifi\n+rpm_name: python3-certifi\n[cffi]\n-dpkg_name: python-cffi\n+dpkg_name: python3-cffi\nminimum_version: 1.10.0\n-rpm_name: python2-cffi\n+rpm_name: python3-cffi\n[chardet]\n-dpkg_name: python-chardet\n+dpkg_name: python3-chardet\nminimum_version: 3.0.4\n-rpm_name: python2-chardet\n+rpm_name: python3-chardet\n[Click]\n-dpkg_name: python-click\n+dpkg_name: python3-click\nminimum_version: 6.7\n-rpm_name: python2-click\n-\n-[configparser]\n-dpkg_name: python-configparser\n-minimum_version: 3.5.0\n-python2_only: true\n-rpm_name: python2-configparser\n+rpm_name: python3-click\n[cryptography]\n-dpkg_name: python-cryptography\n+dpkg_name: python3-cryptography\nminimum_version: 2.4.1\n-rpm_name: python2-cryptography\n+rpm_name: python3-cryptography\n[datasketch]\n-dpkg_name: python-datasketch\n+dpkg_name: python3-datasketch\nminimum_version: 1.2.5\n-rpm_name: python2-datasketch\n+rpm_name: python3-datasketch\n[dateutil]\n-dpkg_name: python-dateutil\n+dpkg_name: python3-dateutil\nminimum_version: 2.6.1\n-pypi_name: python-dateutil\n-rpm_name: python2-dateutil\n+pypi_name: python3-dateutil\n+rpm_name: python3-dateutil\nversion_property: __version__\n[elasticsearch]\n-dpkg_name: python-elasticsearch\n+dpkg_name: python3-elasticsearch\nis_optional: true\nl2tbinaries_name: elasticsearch-py\nminimum_version: 6.0\npypi_name: elasticsearch\n-rpm_name: python-elasticsearch\n+rpm_name: python3-elasticsearch\nversion_property: __versionstr__\n-[enum34]\n-dpkg_name: python-enum34\n-minimum_version: 1.1.6\n-python2_only: true\n-rpm_name: python2-enum34\n-\n[entrypoints]\n-dpkg_name: python-entrypoints\n+dpkg_name: python3-entrypoints\nminimum_version: 0.2.3\n-rpm_name: python2-entrypoints\n+rpm_name: python3-entrypoints\n[Flask]\n-dpkg_name: python-flask\n+dpkg_name: python3-flask\nminimum_version: 1.0.2\n-rpm_name: python2-flask\n+rpm_name: python3-flask\n[Flask-Bcrypt]\n-dpkg_name: python-flask-bcrypt\n+dpkg_name: python3-flask-bcrypt\nminimum_version: 0.7.1\n-rpm_name: python2-flask-bcrypt\n+rpm_name: python3-flask-bcrypt\n[Flask-Login]\n-dpkg_name: python-flask-login\n+dpkg_name: python3-flask-login\nminimum_version: 0.4.0\n-rpm_name: python2-flask-login\n+rpm_name: python3-flask-login\n[Flask-Migrate]\n-dpkg_name: python-flask-migrate\n+dpkg_name: python3-flask-migrate\nminimum_version: 2.1.1\n-rpm_name: python2-flask-migrate\n+rpm_name: python3-flask-migrate\n[Flask-RESTful]\n-dpkg_name: python-flask-restful\n+dpkg_name: python3-flask-restful\nminimum_version: 0.3.6\n-rpm_name: python2-flask-restful\n+rpm_name: python3-flask-restful\n[Flask-Script]\n-dpkg_name: python-flask-script\n+dpkg_name: python3-flask-script\nminimum_version: 2.0.5\n-rpm_name: python2-flask-script\n+rpm_name: python3-flask-script\n[Flask-SQLAlchemy]\n-dpkg_name: python-flask-sqlalchemy\n+dpkg_name: python3-flask-sqlalchemy\nminimum_version: 2.2\n-rpm_name: python2-flask-sqlalchemy\n+rpm_name: python3-flask-sqlalchemy\n[Flask-WTF]\n-dpkg_name: python-flaskext.wtf\n+dpkg_name: python3-flaskext.wtf\nminimum_version: 0.14.2\n-rpm_name: python2-flask-wtf\n+rpm_name: python3-flask-wtf\n+\n+[google-auth]\n+dpkg_name: python3-google-auth\n+minimum_version: 1.6.3\n+rpm_name:\n+\n+[google-auth-oauthlib]\n+dpkg_name: python3-google-auth-oauthlib\n+minimum_version: 0.4.1\n+rpm_name:\n[gunicorn]\n-dpkg_name: python-gunicorn\n+dpkg_name: python3-gunicorn\nminimum_version: 19.7.1\n-rpm_name: python2-gunicorn\n+rpm_name: python3-gunicorn\n[idna]\n-dpkg_name: python-idna\n+dpkg_name: python3-idna\nminimum_version: 2.6\n-rpm_name: python2-idna\n-\n-[ipaddress]\n-dpkg_name: python-ipaddress\n-minimum_version: 1.0.22\n-rpm_name: python2-ipaddress\n+rpm_name: python3-idna\n[itsdangerous]\n-dpkg_name: python-itsdangerous\n+dpkg_name: python3-itsdangerous\nminimum_version: 0.24\n-rpm_name: python2-itsdangerous\n+rpm_name: python3-itsdangerous\n[Jinja2]\n-dpkg_name: python-jinja2\n+dpkg_name: python3-jinja2\nminimum_version: 2.10\n-rpm_name: python2-jinja2\n+rpm_name: python3-jinja2\n[jsonschema]\n-dpkg_name: python-jsonschema\n+dpkg_name: python3-jsonschema\nminimum_version: 2.6.0\n-rpm_name: python2-jsonschema\n+rpm_name: python3-jsonschema\n[kombu]\n-dpkg_name: python-kombu\n+dpkg_name: python3-kombu\nminimum_version: 4.1.0\nrpm_name:\n[Mako]\n-dpkg_name: python-mako\n+dpkg_name: python3-mako\nminimum_version: 1.0.7\nrpm_name:\n[MarkupSafe]\n-dpkg_name: python-markupsafe\n+dpkg_name: python3-markupsafe\nminimum_version: 1.0\n-rpm_name: python2-markupsafe\n+rpm_name: python3-markupsafe\n[neo4jrestclient]\n-dpkg_name: python-neo4jrestclient\n+dpkg_name: python3-neo4jrestclient\nminimum_version: 2.1.1\n-rpm_name: python2-neo4jrestclient\n+rpm_name: python3-neo4jrestclient\n[numpy]\n-dpkg_name: python-numpy\n+dpkg_name: python3-numpy\nminimum_version: 1.13.3\n-rpm_name: python2-numpy\n+rpm_name: python3-numpy\n+\n+[oauthlib]\n+dpkg_name: python3-oauthlib\n+minimum_version: 3.1.0\n+rpm_name:\n[pandas]\n-dpkg_name: python-pandas\n+dpkg_name: python3-pandas\nminimum_version: 0.22.0\n-rpm_name: python2-pandas\n+rpm_name: python3-pandas\n[parameterized]\n-dpkg_name: python-parameterized\n+dpkg_name: python3-parameterized\nminimum_version: 0.6.1\n-rpm_name: python2-parameterized\n+rpm_name: python3-parameterized\n[pycparser]\n-dpkg_name: python-pycparser\n+dpkg_name: python3-pycparser\nminimum_version: 2.18\n-rpm_name: python2-pycparser\n+rpm_name: python3-pycparser\n[PyJWT]\n-dpkg_name: python-jwt\n+dpkg_name: python3-jwt\nminimum_version: 1.6.4\n-rpm_name: python2-jwt\n+rpm_name: python3-jwt\n[pyrsistent]\n-dpkg_name: python-pyrsistent\n+dpkg_name: python3-pyrsistent\nminimum_version: 0.14.11\n-rpm_name: python2-pyrsistent\n+rpm_name: python3-pyrsistent\n[python-editor]\n-dpkg_name: python-editor\n+dpkg_name: python3-editor\nminimum_version: 1.0.3\n-rpm_name: python2-editor\n+rpm_name: python3-editor\n[pytz]\n-dpkg_name: python-tz\n-rpm_name: python2-pytz\n+dpkg_name: python3-tz\n+rpm_name: python3-pytz\nversion_property: __version__\n[redis]\n-dpkg_name: python-redis\n+dpkg_name: python3-redis\nminimum_version: 2.10.6\n-rpm_name: python2-redis\n+rpm_name: python3-redis\n[requests]\n-dpkg_name: python-requests\n+dpkg_name: python3-requests\nminimum_version: 2.20.1\n-rpm_name: python2-requests\n+rpm_name: python3-requests\n+\n+[requests-oauthlib]\n+dpkg_name: python3-requests-oauthlib\n+minimum_version: 1.3.0\n+rpm_name:\n+\n+[sigmatools]\n+dpkg_name: python3-sigmatools\n+minimum_version: 0.15.0\n+rpm_name:\n[six]\n-dpkg_name: python-six\n+dpkg_name: python3-six\nminimum_version: 1.10.0\n-rpm_name: python2-six\n+rpm_name: python3-six\n[SQLAlchemy]\n-dpkg_name: python-sqlalchemy\n+dpkg_name: python3-sqlalchemy\nminimum_version: 1.1.13\n-rpm_name: python2-sqlalchemy\n+rpm_name: python3-sqlalchemy\n[toolz]\n-dpkg_name: python-toolz\n+dpkg_name: python3-toolz\nminimum_version: 0.8.2\n-rpm_name: python2-toolz\n-\n-[typing]\n-dpkg_name: python-typing\n-minimum_version: 3.6.2\n-python2_only: true\n-rpm_name: python2-typing\n+rpm_name: python3-toolz\n[urllib3]\n-dpkg_name: python-urllib3\n+dpkg_name: python3-urllib3\nminimum_version: 1.24.1\n-rpm_name: python2-urllib3\n+rpm_name: python3-urllib3\n[vine]\n-dpkg_name: python-vine\n+dpkg_name: python3-vine\nminimum_version: 1.1.4\n-rpm_name: python2-vine\n+rpm_name: python3-vine\n[werkzeug]\n-dpkg_name: python-werkzeug\n+dpkg_name: python3-werkzeug\nminimum_version: 0.14.1\n-rpm_name: python2-werkzeug\n+rpm_name: python3-werkzeug\n[WTForms]\n-dpkg_name: python-wtforms\n+dpkg_name: python3-wtforms\nminimum_version: 2.1\n-rpm_name: python2-wtforms\n+rpm_name: python3-wtforms\n+\n+[xlrd]\n+dpkg_name: python3-xlrd\n+minimum_version: 1.2.0\n+rpm_name:\n[yaml]\n-dpkg_name: python-yaml\n+dpkg_name: python3-yaml\nl2tbinaries_name: PyYAML\nminimum_version: 3.10\npypi_name: PyYAML\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch.ini", "diff": "+[project]\n+name: timesketch\n+name_description: Timesketch\n+maintainer: Timesketch development team <timesketch-dev@googlegroups.com>\n+homepage_url: http://timesketch.org\n+description_short: Collaborative digital forensic timeline analysis\n+description_long: Timesketch is a web based tool for collaborative forensic\n+ timeline analysis. Using sketches you and your collaborators can easily\n+ organize timelines and analyze them all at the same time. Add meaning\n+ to your raw data with rich annotations, comments, tags and stars.\n" } ]
Python
Apache License 2.0
google/timesketch
Updated l2tdevtools configuration and dpkg files (#1104)
263,133
16.02.2020 22:25:43
-3,600
b3b23b9db04bc015cc5c4af87c335d4fe24e43ff
Adding support for uploading events in API
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -113,33 +113,30 @@ class ImportStreamer(object):\nself._count = 0\nself._data_lines = []\n- def _upload_data(self, file_name, end_stream):\n+ def _upload_data_frame(self, data_frame, end_stream):\n\"\"\"Upload data to Timesketch.\nArgs:\n- file_name: a full path to the file that is about to be uploaded.\n+ data_frame: a pandas DataFrame with the content to upload.\nend_stream: boolean indicating whether this is the last chunk of\nthe stream.\n\"\"\"\n- files = {\n- 'file': open(file_name, 'rb')\n- }\ndata = {\n'name': self._timeline_name,\n'sketch_id': self._sketch.id,\n'enable_stream': not end_stream,\n'index_name': self._index,\n+ 'events': data_frame.to_json(orient='records', lines=True)\n}\n- response = self._sketch.api.session.post(\n- self._resource_url, files=files, data=data)\n-\n+ response = self._sketch.api.session.post(self._resource_url, data=data)\n+ # TODO: Add in the ability to re-upload failed file.\nif response.status_code not in definitions.HTTP_STATUS_CODE_20X:\nraise RuntimeError(\n- 'Error uploading data: [{0:d}] {1:s} {2:s}, file: {3:s}, '\n- 'index {4:s}'.format(\n+ 'Error uploading data: [{0:d}] {1:s} {2:s}, '\n+ 'index {3:s}'.format(\nresponse.status_code, response.reason, response.text,\n- file_name, self._index))\n+ self._index))\nresponse_dict = response.json()\nself._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n@@ -151,7 +148,6 @@ class ImportStreamer(object):\nArgs:\nfile_path: a full path to the file that is about to be uploaded.\n\"\"\"\n- resource_url = '{0:s}/upload/'.format(self._sketch.api.api_root)\nfile_size = os.path.getsize(file_path)\nif self._timeline_name:\n@@ -171,7 +167,7 @@ class ImportStreamer(object):\nfile_dict = {\n'file': open(file_path, 'rb')}\nresponse = self._sketch.api.session.post(\n- resource_url, files=file_dict, data=data)\n+ self._resource_url, files=file_dict, data=data)\nelse:\nchunks = int(math.ceil(float(file_size) / self.FILE_SIZE_THRESHOLD))\ndata['chunk_total_chunks'] = chunks\n@@ -186,7 +182,7 @@ class ImportStreamer(object):\nfile_stream.name = file_path\nfile_dict = {'file': file_stream}\nresponse = self._sketch.api.session.post(\n- resource_url, files=file_dict, data=data)\n+ self._resource_url, files=file_dict, data=data)\nif response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n# TODO (kiddi): Re-do this chunk.\n@@ -246,10 +242,8 @@ class ImportStreamer(object):\n'Need a field called timestamp_desc in the data frame.')\nif size <= self._threshold:\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\nend_stream = not part_of_iter\n- self._upload_data(csv_file.name, end_stream=end_stream)\n+ self._upload_data_frame(data_frame_use, end_stream=end_stream)\nreturn\nchunks = int(math.ceil(float(size) / self._threshold))\n@@ -257,12 +251,8 @@ class ImportStreamer(object):\nchunk_start = index * self._threshold\ndata_chunk = data_frame_use[\nchunk_start:chunk_start + self._threshold]\n-\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_chunk.to_csv(csv_file.name, index=False, encoding='utf-8')\n-\nend_stream = bool(index == chunks - 1)\n- self._upload_data(csv_file.name, end_stream=end_stream)\n+ self._upload_data_frame(data_chunk, end_stream=end_stream)\ndef add_dict(self, entry):\n\"\"\"Add an entry into the buffer.\n@@ -440,11 +430,7 @@ class ImportStreamer(object):\ndata_frame = pandas.DataFrame(self._data_lines)\ndata_frame_use = self._fix_data_frame(data_frame)\n-\n- csv_file = tempfile.NamedTemporaryFile(suffix='.csv')\n- data_frame_use.to_csv(csv_file.name, index=False, encoding='utf-8')\n-\n- self._upload_data(csv_file.name, end_stream=end_stream)\n+ self._upload_data_frame(data_frame_use, end_stream=end_stream)\n@property\ndef response(self):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -34,6 +34,7 @@ import codecs\nimport datetime\nimport json\nimport hashlib\n+import io\nimport os\nimport time\nimport uuid\n@@ -78,7 +79,6 @@ from timesketch.lib.forms import NameDescriptionForm\nfrom timesketch.lib.forms import EventAnnotationForm\nfrom timesketch.lib.forms import EventCreateForm\nfrom timesketch.lib.forms import ExploreForm\n-from timesketch.lib.forms import UploadFileForm\nfrom timesketch.lib.forms import StoryForm\nfrom timesketch.lib.forms import GraphExploreForm\nfrom timesketch.lib.forms import SearchIndexForm\n@@ -1509,35 +1509,127 @@ class EventAnnotationResource(ResourceMixin, Resource):\nclass UploadFileResource(ResourceMixin, Resource):\n\"\"\"Resource that processes uploaded files.\"\"\"\n- @login_required\n- def post(self):\n- \"\"\"Handles POST request to the resource.\n+ def _upload_and_index(\n+ self, file_extension, timeline_name, index_name, sketch, sketch_id,\n+ enable_stream, file_path='', events='', meta=None):\n+ \"\"\"Creates a full pipeline for an uploaded file and returns the results.\n+\n+ Args:\n+ file_extension: the extension of the uploaded file.\n+ timeline_name: name the timeline will be stored under in the\n+ datastore.\n+ index_name: the Elastic index name for the timeline.\n+ sketch: Instance of timesketch.models.sketch.Sketch\n+ sketch_id: integer with the sketch ID.\n+ enable_stream: boolean indicating whether this is file is part of a\n+ stream or not.\n+ file_path: the path to the file to be uploaded (optional).\n+ events: a string with events to upload (optional).\n+ meta: optional dict with additional meta fields that will be\n+ included in the return.\nReturns:\n- A view in JSON (instance of flask.wrappers.Response)\n+ A timeline if created otherwise a search index in JSON (instance\n+ of flask.wrappers.Response)\n\"\"\"\n- upload_enabled = current_app.config['UPLOAD_ENABLED']\n- if not upload_enabled:\n- abort(HTTP_STATUS_CODE_BAD_REQUEST, 'Upload not enabled')\n+ # Check if search index already exists.\n+ searchindex = SearchIndex.query.filter_by(\n+ name=timeline_name,\n+ description=timeline_name,\n+ user=current_user,\n+ index_name=index_name).first()\n- upload_folder = current_app.config['UPLOAD_FOLDER']\n+ timeline = None\n- form = UploadFileForm()\n- if not form.validate_on_submit():\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST,\n- 'Upload validation failed: {0:s}'.format(\n- form.errors['file'][0]))\n+ if searchindex:\n+ searchindex.set_status('processing')\n+ else:\n+ # Create the search index in the Timesketch database\n+ searchindex = SearchIndex.get_or_create(\n+ name=timeline_name,\n+ description=timeline_name,\n+ user=current_user,\n+ index_name=index_name)\n+ searchindex.grant_permission(permission='read', user=current_user)\n+ searchindex.grant_permission(permission='write', user=current_user)\n+ searchindex.grant_permission(\n+ permission='delete', user=current_user)\n+ searchindex.set_status('processing')\n+ db_session.add(searchindex)\n+ db_session.commit()\n+\n+ if sketch and sketch.has_permission(current_user, 'write'):\n+ timeline = Timeline(\n+ name=searchindex.name,\n+ description=searchindex.description,\n+ sketch=sketch,\n+ user=current_user,\n+ searchindex=searchindex)\n+ timeline.set_status('processing')\n+ sketch.timelines.append(timeline)\n+ db_session.add(timeline)\n+ db_session.commit()\n+\n+ # Start Celery pipeline for indexing and analysis.\n+ # Import here to avoid circular imports.\n+ # pylint: disable=import-outside-toplevel\n+ from timesketch.lib import tasks\n+ pipeline = tasks.build_index_pipeline(\n+ file_path=file_path, events=events, timeline_name=timeline_name,\n+ index_name=index_name, file_extension=file_extension,\n+ sketch_id=sketch_id, only_index=enable_stream)\n+ pipeline.apply_async()\n+\n+ # Return Timeline if it was created.\n+ # pylint: disable=no-else-return\n+ if timeline:\n+ return self.to_json(\n+ timeline, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n+\n+ return self.to_json(\n+ searchindex, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n- sketch_id = form.sketch_id.data or None\n- file_storage = form.file.data\n+ def _upload_events(self, events, form, sketch, index_name):\n+ \"\"\"Upload a file like object.\n+\n+ Args:\n+ events: string with all the events.\n+ form: a dict with the configuration for the upload.\n+ sketch: Instance of timesketch.models.sketch.Sketch\n+ index_name: the Elastic index name for the timeline.\n+\n+ Returns:\n+ A timeline if created otherwise a search index in JSON (instance\n+ of flask.wrappers.Response)\n+ \"\"\"\n+ timeline_name = form.get('name', 'unknown_events')\n+ file_extension = 'jsonl'\n+\n+ return self._upload_and_index(\n+ events=events,\n+ file_extension=file_extension,\n+ timeline_name=timeline_name,\n+ index_name=index_name,\n+ sketch=sketch,\n+ sketch_id=sketch.id,\n+ enable_stream=form.get('enable_stream', False))\n+\n+ def _upload_file(self, file_storage, form, sketch, index_name):\n+ \"\"\"Upload a file.\n+\n+ Args:\n+ file_storage: a FileStorage object.\n+ form: a dict with the configuration for the upload.\n+ sketch: Instance of timesketch.models.sketch.Sketch\n+ index_name: the Elastic index name for the timeline.\n+\n+ Returns:\n+ A timeline if created otherwise a search index in JSON (instance\n+ of flask.wrappers.Response)\n+ \"\"\"\n_filename, _extension = os.path.splitext(file_storage.filename)\nfile_extension = _extension.lstrip('.')\n- timeline_name = form.name.data or _filename.rstrip('.')\n-\n- sketch = None\n- if sketch_id:\n- sketch = Sketch.query.get_with_acl(sketch_id)\n+ timeline_name = form.get('name', _filename.rstrip('.'))\n# We do not need a human readable filename or\n# datastore index name, so we use UUIDs here.\n@@ -1545,27 +1637,23 @@ class UploadFileResource(ResourceMixin, Resource):\nif not isinstance(filename, six.text_type):\nfilename = codecs.decode(filename, 'utf-8')\n- index_name = form.index_name.data or uuid.uuid4().hex\n- if not isinstance(index_name, six.text_type):\n- index_name = codecs.decode(index_name, 'utf-8')\n-\n+ upload_folder = current_app.config['UPLOAD_FOLDER']\nfile_path = os.path.join(upload_folder, filename)\n- chunk_index = form.chunk_index.data\n- chunk_byte_offset = form.chunk_byte_offset.data\n- chunk_total_chunks = form.chunk_total_chunks.data\n- file_size = form.total_file_size.data or None\n- enable_stream = form.enable_stream.data\n+ chunk_index = form.get('chunk_index')\n+ chunk_byte_offset = form.get('chunk_byte_offset')\n+ chunk_total_chunks = form.get('chunk_total_chunks')\n+ file_size = form.get('total_file_size')\n+ enable_stream = form.get('enable_stream', False)\nif chunk_total_chunks is None:\n- file_storage.save(file_path)\n- return self._complete_upload(\n+ return self._upload_and_index(\nfile_path=file_path,\nfile_extension=file_extension,\ntimeline_name=timeline_name,\nindex_name=index_name,\nsketch=sketch,\n- sketch_id=sketch_id,\n+ sketch_id=sketch.id,\nenable_stream=enable_stream)\n# For file chunks we need the correct filepath, otherwise each chunk\n@@ -1607,93 +1695,54 @@ class UploadFileResource(ResourceMixin, Resource):\n'total_chunks': chunk_total_chunks,\n}\n- return self._complete_upload(\n+ return self._upload_and_index(\nfile_path=file_path,\nfile_extension=file_extension,\ntimeline_name=timeline_name,\nindex_name=index_name,\nsketch=sketch,\n- sketch_id=sketch_id,\n+ sketch_id=sketch.id,\nenable_stream=enable_stream,\nmeta=meta)\n- def _complete_upload(\n- self, file_path, file_extension, timeline_name, index_name, sketch,\n- sketch_id, enable_stream, meta=None):\n- \"\"\"Creates a full pipeline for an uploaded file and returns the results.\n-\n- Args:\n- file_path: full path to the file that was uploaded.\n- file_extension: the extension of the uploaded file.\n- timeline_name: name the timeline will be stored under in the\n- datastore.\n- index_name: the index name for the file.\n- sketch: a Sketch model object.\n- sketch_id: integer with the sketch ID.\n- enable_stream: boolean indicating whether this is file is part of a\n- stream or not.\n- meta: optional dict with additional meta fields that will be\n- included in the return.\n+ @login_required\n+ def post(self):\n+ \"\"\"Handles POST request to the resource.\nReturns:\n- A timeline if created otherwise a search index in JSON (instance\n- of flask.wrappers.Response)\n+ A view in JSON (instance of flask.wrappers.Response)\n\"\"\"\n- # Check if search index already exists.\n- searchindex = SearchIndex.query.filter_by(\n- name=timeline_name,\n- description=timeline_name,\n- user=current_user,\n- index_name=index_name).first()\n+ upload_enabled = current_app.config['UPLOAD_ENABLED']\n+ if not upload_enabled:\n+ abort(HTTP_STATUS_CODE_BAD_REQUEST, 'Upload not enabled')\n- timeline = None\n+ form = request.data\n+ if not form:\n+ form = request.form\n- if searchindex:\n- searchindex.set_status('processing')\n- else:\n- # Create the search index in the Timesketch database\n- searchindex = SearchIndex.get_or_create(\n- name=timeline_name,\n- description=timeline_name,\n- user=current_user,\n- index_name=index_name)\n- searchindex.grant_permission(permission='read', user=current_user)\n- searchindex.grant_permission(permission='write', user=current_user)\n- searchindex.grant_permission(\n- permission='delete', user=current_user)\n- searchindex.set_status('processing')\n- db_session.add(searchindex)\n- db_session.commit()\n+ sketch_id = form.get('sketch_id', None)\n+ if not isinstance(sketch_id, int):\n+ sketch_id = int(sketch_id)\n- if sketch and sketch.has_permission(current_user, 'write'):\n- timeline = Timeline(\n- name=searchindex.name,\n- description=searchindex.description,\n- sketch=sketch,\n- user=current_user,\n- searchindex=searchindex)\n- timeline.set_status('processing')\n- sketch.timelines.append(timeline)\n- db_session.add(timeline)\n- db_session.commit()\n+ sketch = None\n+ if sketch_id:\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n- # Start Celery pipeline for indexing and analysis.\n- # Import here to avoid circular imports.\n- # pylint: disable=import-outside-toplevel\n- from timesketch.lib import tasks\n- pipeline = tasks.build_index_pipeline(\n- file_path, timeline_name, index_name, file_extension, sketch_id,\n- only_index=enable_stream)\n- pipeline.apply_async()\n+ index_name = form.get('index_name', uuid.uuid4().hex)\n+ if not isinstance(index_name, six.text_type):\n+ index_name = codecs.decode(index_name, 'utf-8')\n- # Return Timeline if it was created.\n- # pylint: disable=no-else-return\n- if timeline:\n- return self.to_json(\n- timeline, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n+ file_storage = request.files.get('file')\n- return self.to_json(\n- searchindex, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n+ if file_storage:\n+ return self._upload_file(file_storage, form)\n+\n+ events = form.get('events', [])\n+ if not events:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to upload data, no file uploaded nor any events.')\n+ return self._upload_events(events, form, sketch, index_name)\nclass TaskResource(ResourceMixin, Resource):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/errors.py", "new_path": "timesketch/lib/errors.py", "diff": "@@ -18,7 +18,11 @@ from __future__ import unicode_literals\nfrom flask import jsonify\n-class ApiHTTPError(Exception):\n+class Error(Exception):\n+ \"\"\"Base error class.\"\"\"\n+\n+\n+class ApiHTTPError(Error):\n\"\"\"Error class for API HTTP errors.\"\"\"\ndef __init__(self, message, status_code):\n@@ -28,7 +32,7 @@ class ApiHTTPError(Exception):\nmessage: Description of the error.\nstatus_code: HTTP status code.\n\"\"\"\n- Exception.__init__(self)\n+ super(ApiHTTPError, self).__init__()\nself.message = message\nself.status_code = status_code\n@@ -44,3 +48,7 @@ class ApiHTTPError(Exception):\n})\nresponse.status_code = self.status_code\nreturn response\n+\n+\n+class DataIngestionError(Error):\n+ \"\"\"Raised when unable to ingest data.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/forms.py", "new_path": "timesketch/lib/forms.py", "diff": "@@ -237,28 +237,6 @@ class EventAnnotationForm(BaseForm):\nevents = StringField('Events', validators=[DataRequired()])\n-class UploadFileForm(BaseForm):\n- \"\"\"Form to handle file uploads.\"\"\"\n- file = FileField(\n- 'file',\n- validators=[\n- FileRequired(),\n- FileAllowed(['plaso', 'csv', 'jsonl'],\n- 'Allowed file extensions: .plaso, .csv, or .jsonl')\n- ])\n- name = StringField('Timeline name', validators=[Optional()])\n- sketch_id = IntegerField('Sketch ID', validators=[Optional()])\n- index_name = StringField('Index Name', validators=[Optional()])\n- enable_stream = BooleanField(\n- 'Enable stream', false_values={False, 'false', ''}, default=False)\n- chunk_index = IntegerField('Chunk Index', validators=[Optional()])\n- chunk_byte_offset = IntegerField(\n- 'Chunk Byte Offset', validators=[Optional()])\n- chunk_total_chunks = IntegerField(\n- 'Total Chunk Count', validators=[Optional()])\n- total_file_size = IntegerField('Total File size', validators=[Optional()])\n-\n-\nclass StoryForm(BaseForm):\n\"\"\"Form to handle stories.\"\"\"\ntitle = StringField('Title', validators=[])\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -19,6 +19,7 @@ import logging\nimport subprocess\nimport traceback\n+import io\nimport json\nimport six\n@@ -28,6 +29,7 @@ from flask import current_app\nfrom sqlalchemy import create_engine\nfrom timesketch import create_celery_app\n+from timesketch.lib import errors\nfrom timesketch.lib.analyzers import manager\nfrom timesketch.lib.datastores.elastic import ElasticsearchDataStore\nfrom timesketch.lib.utils import read_and_validate_csv\n@@ -104,7 +106,7 @@ def _get_index_task_class(file_extension):\n\"\"\"\nif file_extension == 'plaso':\nindex_class = run_plaso\n- elif file_extension in ['csv', 'jsonl']:\n+ elif file_extension in ['csv', 'jsonl', 'string']:\nindex_class = run_csv_jsonl\nelse:\nraise KeyError('No task that supports {0:s}'.format(file_extension))\n@@ -131,12 +133,16 @@ def _get_index_analyzers():\nreturn chain(tasks)\n-def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\n- sketch_id=None, only_index=False):\n+def build_index_pipeline(\n+ file_path='', events='', timeline_name='', index_name='',\n+ file_extension='', sketch_id=None, only_index=False):\n\"\"\"Build a pipeline for index and analysis.\nArgs:\n- file_path: Path to the file to index.\n+ file_path: The full path to a file to upload, either a file_path or\n+ or events need to be defined.\n+ events: String with the event data, either file_path or events\n+ needs to be defined.\ntimeline_name: Name of the timeline to create.\nindex_name: Name of the index to index to.\nfile_extension: The file extension of the file.\n@@ -150,13 +156,16 @@ def build_index_pipeline(file_path, timeline_name, index_name, file_extension,\nCelery chain with indexing task (or single indexing task) and analyzer\ntask group.\n\"\"\"\n+ if not (file_path or events):\n+ raise RuntimeError(\n+ 'Unable to upload data, missing either a file or events.')\nindex_task_class = _get_index_task_class(file_extension)\nindex_analyzer_chain = _get_index_analyzers()\nsketch_analyzer_chain = None\nsearchindex = SearchIndex.query.filter_by(index_name=index_name).first()\nindex_task = index_task_class.s(\n- file_path, timeline_name, index_name, file_extension)\n+ file_path, events, timeline_name, index_name, file_extension)\nif only_index:\nreturn index_task\n@@ -395,11 +404,12 @@ def run_sketch_analyzer(index_name, sketch_id, analysis_id, analyzer_name,\n@celery.task(track_started=True, base=SqlAlchemyTask)\n-def run_plaso(source_file_path, timeline_name, index_name, source_type):\n+def run_plaso(file_path, events, timeline_name, index_name, source_type):\n\"\"\"Create a Celery task for processing Plaso storage file.\nArgs:\n- source_file_path: Path to plaso storage file.\n+ file_path: Path to the plaso file on disk.\n+ events: String with event data, invalid for plaso files.\ntimeline_name: Name of the Timesketch timeline.\nindex_name: Name of the datastore index.\nsource_type: Type of file, csv or jsonl.\n@@ -407,6 +417,8 @@ def run_plaso(source_file_path, timeline_name, index_name, source_type):\nReturns:\nName (str) of the index.\n\"\"\"\n+ if events:\n+ raise RuntimeError('Plaso uploads needs a file, not events.')\n# Log information to Celery\nmessage = 'Index timeline [{0:s}] to index [{1:s}] (source: {2:s})'\nlogging.info(message.format(timeline_name, index_name, source_type))\n@@ -417,7 +429,7 @@ def run_plaso(source_file_path, timeline_name, index_name, source_type):\npsort_path = 'psort.py'\ncmd = [\n- psort_path, '-o', 'timesketch', source_file_path, '--name',\n+ psort_path, '-o', 'timesketch', file_path, '--name',\ntimeline_name, '--status_view', 'none', '--index', index_name\n]\n@@ -440,11 +452,12 @@ def run_plaso(source_file_path, timeline_name, index_name, source_type):\n@celery.task(track_started=True, base=SqlAlchemyTask)\n-def run_csv_jsonl(source_file_path, timeline_name, index_name, source_type):\n+def run_csv_jsonl(file_path, events, timeline_name, index_name, source_type):\n\"\"\"Create a Celery task for processing a CSV or JSONL file.\nArgs:\n- source_file_path: Path to CSV or JSONL file.\n+ file_path: Path to the JSON or CSV file.\n+ events: A string with the events.\ntimeline_name: Name of the Timesketch timeline.\nindex_name: Name of the datastore index.\nsource_type: Type of file, csv or jsonl.\n@@ -455,7 +468,7 @@ def run_csv_jsonl(source_file_path, timeline_name, index_name, source_type):\nevent_type = 'generic_event' # Document type for Elasticsearch\nvalidators = {\n'csv': read_and_validate_csv,\n- 'jsonl': read_and_validate_jsonl\n+ 'jsonl': read_and_validate_jsonl,\n}\nread_and_validate = validators.get(source_type)\n@@ -468,15 +481,23 @@ def run_csv_jsonl(source_file_path, timeline_name, index_name, source_type):\nhost=current_app.config['ELASTIC_HOST'],\nport=current_app.config['ELASTIC_PORT'])\n+ if events:\n+ file_handle = io.StringIO(events)\n+ else:\n+ file_handle = open(file_path, 'r', encoding='utf-8')\n# Reason for the broad exception catch is that we want to capture\n# all possible errors and exit the task.\ntry:\nes.create_index(index_name=index_name, doc_type=event_type)\n- for event in read_and_validate(source_file_path):\n+ for event in read_and_validate(file_handle):\nes.import_event(index_name, event_type, event)\n# Import the remaining events\nes.flush_queued_events()\n+ except errors.DataIngestionError as e:\n+ _set_timeline_status(index_name, status='fail', error_msg=str(e))\n+ raise\n+\nexcept (RuntimeError, ImportError, NameError, UnboundLocalError) as e:\n_set_timeline_status(index_name, status='fail', error_msg=str(e))\nraise\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/utils.py", "new_path": "timesketch/lib/utils.py", "diff": "@@ -20,6 +20,7 @@ import csv\nimport datetime\nimport email\nimport json\n+import logging\nimport random\nimport smtplib\nimport sys\n@@ -30,6 +31,8 @@ import six\nfrom dateutil import parser\nfrom flask import current_app\n+from timesketch.lib import errors\n+\n# Set CSV field size limit to systems max value.\ncsv.field_size_limit(sys.maxsize)\n@@ -49,13 +52,16 @@ def random_color():\nreturn '{0:02X}{1:02X}{2:02X}'.format(rgb[0], rgb[1], rgb[2])\n-\n-def read_and_validate_csv(path, delimiter=','):\n+def read_and_validate_csv(file_handle, delimiter=','):\n\"\"\"Generator for reading a CSV file.\nArgs:\n- path: Path to the CSV file\n+ file_handle: a file-like object containing the CSV content.\ndelimiter: character used as a field separator, default: ','\n+\n+ Raises:\n+ RuntimeError: when there are missing fields.\n+ DataIngestionError: when there are issues with the data ingestion.\n\"\"\"\n# Columns that must be present in the CSV file.\nmandatory_fields = ['message', 'datetime', 'timestamp_desc']\n@@ -67,12 +73,8 @@ def read_and_validate_csv(path, delimiter=','):\n# Due to issues with python2.\nif six.PY2:\ndelimiter = str(delimiter)\n- open_function = open(path, 'r')\n- else:\n- open_function = open(path, mode='r', encoding='utf-8')\n- with open_function as fh:\n- reader = csv.DictReader(fh, delimiter=delimiter)\n+ reader = csv.DictReader(file_handle, delimiter=delimiter)\ncsv_header = reader.fieldnames\nmissing_fields = []\n# Validate the CSV header\n@@ -83,6 +85,7 @@ def read_and_validate_csv(path, delimiter=','):\nraise RuntimeError(\n'Missing fields in CSV header: {0:s}'.format(\n','.join(missing_fields)))\n+ try:\nfor row in reader:\ntry:\n# normalize datetime to ISO 8601 format if it's not the case.\n@@ -97,24 +100,24 @@ def read_and_validate_csv(path, delimiter=','):\ncontinue\nyield row\n+ except csv.Error as e:\n+ error_string = 'Unable to read file, with error: {0!s}'.format(e)\n+ logging.error(error_string)\n+ raise errors.DataIngestionError(error_string)\n-def read_and_validate_redline(path):\n+def read_and_validate_redline(file_handle):\n\"\"\"Generator for reading a Redline CSV file.\nArgs:\n- path: Path to the file\n+ file_handle: a file-like object containing the CSV content.\n\"\"\"\n# Columns that must be present in the CSV file\n-\n- # check if it is the right redline format\nmandatory_fields = ['Alert', 'Tag', 'Timestamp', 'Field', 'Summary']\n- with open(path, 'rb') as fh:\n- csv.register_dialect('myDialect',\n- delimiter=',',\n- quoting=csv.QUOTE_ALL,\n+ csv.register_dialect(\n+ 'myDialect', delimiter=',', quoting=csv.QUOTE_ALL,\nskipinitialspace=True)\n- reader = csv.DictReader(fh, delimiter=',', dialect='myDialect')\n+ reader = csv.DictReader(file_handle, delimiter=',', dialect='myDialect')\ncsv_header = reader.fieldnames\nmissing_fields = []\n@@ -126,7 +129,6 @@ def read_and_validate_redline(path):\nraise RuntimeError(\n'Missing fields in CSV header: {0:s}'.format(missing_fields))\nfor row in reader:\n-\ndt = parser.parse(row['Timestamp'])\ntimestamp = int(time.mktime(dt.timetuple())) * 1000\ndt_iso_format = dt.isoformat()\n@@ -148,17 +150,23 @@ def read_and_validate_redline(path):\nyield row_to_yield\n-def read_and_validate_jsonl(path):\n+def read_and_validate_jsonl(file_handle):\n\"\"\"Generator for reading a JSONL (json lines) file.\nArgs:\n- path: Path to the JSONL file\n+ file_handle: a file-like object containing the CSV content.\n+\n+ Raises:\n+ RuntimeError: if there are missing fields.\n+ DataIngestionError: If the ingestion fails.\n+\n+ Yields:\n+ A dict that's ready to add to the datastore.\n\"\"\"\n# Fields that must be present in each entry of the JSONL file.\nmandatory_fields = ['message', 'datetime', 'timestamp_desc']\n- with open(path, 'rb') as fh:\nlineno = 0\n- for line in fh:\n+ for line in file_handle:\nlineno += 1\ntry:\nlinedict = json.loads(line)\n@@ -170,21 +178,17 @@ def read_and_validate_jsonl(path):\nif 'timestamp' not in ld_keys and 'datetime' in ld_keys:\nlinedict['timestamp'] = parser.parse(linedict['datetime'])\n- missing_fields = []\n- for field in mandatory_fields:\n- if field not in linedict.keys():\n- missing_fields.append(field)\n+ missing_fields = [x for x in mandatory_fields if x not in linedict]\nif missing_fields:\nraise RuntimeError(\n- u\"Missing field(s) at line {0:n}: {1:s}\"\n- .format(lineno, missing_fields))\n+ 'Missing field(s) at line {0:n}: {1:s}'.format(\n+ lineno, ','.join(missing_fields)))\nyield linedict\nexcept ValueError as e:\n- raise RuntimeError(\n- u\"Error parsing JSON at line {0:n}: {1:s}\"\n- .format(lineno, e))\n+ raise errors.DataIngestionError(\n+ 'Error parsing JSON at line {0:n}: {1:s}'.format(lineno, e))\ndef get_validated_indices(indices, sketch_indices):\n" } ]
Python
Apache License 2.0
google/timesketch
Adding support for uploading events in API
263,133
16.02.2020 22:47:07
-3,600
892260e8fda47d5918995c70e9a7f9dddb357ff9
Fixing issues with int casting strings from requests.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1640,9 +1640,17 @@ class UploadFileResource(ResourceMixin, Resource):\nfile_path = os.path.join(upload_folder, filename)\nchunk_index = form.get('chunk_index')\n+ if isinstance(chunk_index, six.string_types):\n+ chunk_index = int(chunk_index)\nchunk_byte_offset = form.get('chunk_byte_offset')\n+ if isinstance(chunk_byte_offset, six.string_types):\n+ chunk_byte_offset = int(chunk_byte_offset)\nchunk_total_chunks = form.get('chunk_total_chunks')\n+ if isinstance(chunk_total_chunks, six.string_types):\n+ chunk_total_chunks = int(chunk_total_chunks)\nfile_size = form.get('total_file_size')\n+ if isinstance(file_size, six.string_types):\n+ file_size = int(file_size)\nenable_stream = form.get('enable_stream', False)\nif chunk_total_chunks is None:\n@@ -1736,7 +1744,7 @@ class UploadFileResource(ResourceMixin, Resource):\nif file_storage:\nreturn self._upload_file(file_storage, form, sketch, index_name)\n- events = form.get('events', [])\n+ events = form.get('events')\nif not events:\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing issues with int casting strings from requests.
263,133
16.02.2020 22:58:43
-3,600
013d4c12dcd481ebbadf1e8ea7e538df94f0bf24
Incrementing version of timesketch api client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20191220',\n+ version='20200216',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Incrementing version of timesketch api client.
263,133
16.02.2020 23:16:33
-3,600
0ef2f4abcb3753c7f5226215cb00e4e7d721b867
Minor changes to tasks and upgrading tsctl as well.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -106,7 +106,7 @@ def _get_index_task_class(file_extension):\n\"\"\"\nif file_extension == 'plaso':\nindex_class = run_plaso\n- elif file_extension in ['csv', 'jsonl', 'string']:\n+ elif file_extension in ['csv', 'jsonl']:\nindex_class = run_csv_jsonl\nelse:\nraise KeyError('No task that supports {0:s}'.format(file_extension))\n@@ -465,6 +465,12 @@ def run_csv_jsonl(file_path, events, timeline_name, index_name, source_type):\nReturns:\nName (str) of the index.\n\"\"\"\n+ if events:\n+ file_handle = io.StringIO(events)\n+ source_type = 'jsonl'\n+ else:\n+ file_handle = open(file_path, 'r', encoding='utf-8')\n+\nevent_type = 'generic_event' # Document type for Elasticsearch\nvalidators = {\n'csv': read_and_validate_csv,\n@@ -481,10 +487,6 @@ def run_csv_jsonl(file_path, events, timeline_name, index_name, source_type):\nhost=current_app.config['ELASTIC_HOST'],\nport=current_app.config['ELASTIC_PORT'])\n- if events:\n- file_handle = io.StringIO(events)\n- else:\n- file_handle = open(file_path, 'r', encoding='utf-8')\n# Reason for the broad exception catch is that we want to capture\n# all possible errors and exit the task.\ntry:\n" }, { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -446,7 +446,9 @@ class ImportTimeline(Command):\n# Import here to avoid circular imports.\nfrom timesketch.lib import tasks # pylint: disable=import-outside-toplevel\npipeline = tasks.build_index_pipeline(\n- file_path, timeline_name, index_name, extension, sketch.id)\n+ file_path=file_path, events='', timeline_name=timeline_name,\n+ index_name=index_name, file_extension=extension,\n+ sketch_id=sketch.id)\npipeline.apply_async(task_id=index_name)\nprint('Imported {0:s} to sketch: {1:d} ({2:s})'.format(\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to tasks and upgrading tsctl as well.
263,133
17.02.2020 09:53:15
18,000
65d81c69ef3feb111628f4ac96c8d953f1feb5c3
Storing the content of a file storage.
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1654,6 +1654,7 @@ class UploadFileResource(ResourceMixin, Resource):\nenable_stream = form.get('enable_stream', False)\nif chunk_total_chunks is None:\n+ file_storage.save(file_path)\nreturn self._upload_and_index(\nfile_path=file_path,\nfile_extension=file_extension,\n" } ]
Python
Apache License 2.0
google/timesketch
Storing the content of a file storage.
263,133
18.02.2020 22:12:10
18,000
e88b2122d3e240e84875b341e02e62b901e97a3c
Changing data frame to json functions.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "@@ -126,12 +126,13 @@ class ImportStreamer(object):\nend_stream: boolean indicating whether this is the last chunk of\nthe stream.\n\"\"\"\n+ events = [x.dropna().to_dict() for _, x in data_frame.iterrows()]\ndata = {\n'name': self._timeline_name,\n'sketch_id': self._sketch.id,\n'enable_stream': not end_stream,\n'index_name': self._index,\n- 'events': data_frame.to_json(orient='records', lines=True)\n+ 'events': json.dumps(events),\n}\nresponse = self._sketch.api.session.post(self._resource_url, data=data)\n" } ]
Python
Apache License 2.0
google/timesketch
Changing data frame to json functions.
263,133
19.02.2020 21:52:15
18,000
372abb8d627f82b939309654d66628b857fa979f
Changing how JSON and dicts are uploaded.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "api_client/python/timesketch_api_client/importer.py", "diff": "\"\"\"Timesketch data importer.\"\"\"\nfrom __future__ import unicode_literals\n+import datetime\nimport io\nimport codecs\nimport json\n@@ -21,8 +22,11 @@ import math\nimport logging\nimport os\nimport uuid\n+import time\n+import six\nimport pandas\n+import dateutil.parser\nfrom . import timeline\nfrom . import definitions\n@@ -59,10 +63,55 @@ class ImportStreamer(object):\nself._timeline_name = None\nself._timestamp_desc = None\n+ self._chunk = 1\n+\nself._text_encoding = self.DEFAULT_TEXT_ENCODING\nself._threshold_entry = self.DEFAULT_ENTRY_THRESHOLD\nself._threshold_filesize = self.DEFAULT_FILESIZE_THRESHOLD\n+ def _fix_dict(self, my_dict):\n+ \"\"\"Adjusts a dict with so that it can be uploaded to Timesketch.\n+\n+ Args:\n+ my_dict: a dictionary that may be missing few fields needed\n+ for Timesketch.\n+ \"\"\"\n+ if 'message' not in my_dict and self._format_string:\n+ my_dict['message'] = self._format_string.format(**my_dict)\n+\n+ _ = my_dict.setdefault('timestamp_desc', self._timestamp_desc)\n+\n+ if 'datetime' not in my_dict:\n+ for key in my_dict:\n+ key_string = key.lower()\n+ if 'time' not in key_string:\n+ continue\n+\n+ if key_string == 'timestamp_desc':\n+ continue\n+\n+ value = my_dict[key]\n+ if isinstance(value, six.string_types):\n+ try:\n+ date = dateutil.parser.parse(my_dict[key])\n+ my_dict['datetime'] = date.isoformat()\n+ break\n+ except ValueError:\n+ continue\n+ else:\n+ try:\n+ date = datetime.datetime.utcfromtimestamp(value / 1e6)\n+ my_dict['datetime'] = date.isoformat()\n+ break\n+ except ValueError:\n+ continue\n+\n+ # We don't want to include any columns that start with an underscore.\n+ underscore_columns = [x for x in my_dict if x.startswith('_')]\n+ if underscore_columns:\n+ for column in underscore_columns:\n+ del my_dict[column]\n+\ndef _fix_data_frame(self, data_frame):\n\"\"\"Returns a data frame with added columns for Timesketch upload.\n@@ -118,6 +167,45 @@ class ImportStreamer(object):\nself._count = 0\nself._data_lines = []\n+ def _upload_data_buffer(self, end_stream):\n+ \"\"\"Upload data to Timesketch.\n+\n+ Args:\n+ end_stream: boolean indicating whether this is the last chunk of\n+ the stream.\n+ \"\"\"\n+ if not self._data_lines:\n+ return\n+\n+ start_time = time.time()\n+ data = {\n+ 'name': self._timeline_name,\n+ 'sketch_id': self._sketch.id,\n+ 'enable_stream': not end_stream,\n+ 'index_name': self._index,\n+ 'events': '\\n'.join([json.dumps(x) for x in self._data_lines]),\n+ }\n+ logging.debug(\n+ 'Data buffer ready for upload, took {0:.2f} seconds to '\n+ 'prepare.'.format(time.time() - start_time))\n+\n+ response = self._sketch.api.session.post(self._resource_url, data=data)\n+ # TODO: Add in the ability to re-upload failed file.\n+ if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ raise RuntimeError(\n+ 'Error uploading data: [{0:d}] {1:s} {2:s}, '\n+ 'index {3:s}'.format(\n+ response.status_code, response.reason, response.text,\n+ self._index))\n+\n+ logging.debug(\n+ 'Data buffer nr. {0:d} uploaded, total time: {1:.2f}s'.format(\n+ self._chunk, time.time() - start_time))\n+ self._chunk += 1\n+ response_dict = response.json()\n+ self._timeline_id = response_dict.get('objects', [{}])[0].get('id')\n+ self._last_response = response_dict\n+\ndef _upload_data_frame(self, data_frame, end_stream):\n\"\"\"Upload data to Timesketch.\n@@ -126,16 +214,16 @@ class ImportStreamer(object):\nend_stream: boolean indicating whether this is the last chunk of\nthe stream.\n\"\"\"\n- events = [x.dropna().to_dict() for _, x in data_frame.iterrows()]\ndata = {\n'name': self._timeline_name,\n'sketch_id': self._sketch.id,\n'enable_stream': not end_stream,\n'index_name': self._index,\n- 'events': json.dumps(events),\n+ 'events': data_frame.to_json(orient='records', lines=True),\n}\nresponse = self._sketch.api.session.post(self._resource_url, data=data)\n+ self._chunk += 1\n# TODO: Add in the ability to re-upload failed file.\nif response.status_code not in definitions.HTTP_STATUS_CODE_20X:\nraise RuntimeError(\n@@ -278,6 +366,7 @@ class ImportStreamer(object):\nself.flush(end_stream=False)\nself._reset()\n+ self._fix_dict(entry)\nself._data_lines.append(entry)\nself._count += 1\n@@ -356,16 +445,16 @@ class ImportStreamer(object):\nelif file_ending == 'jsonl':\n# TODO (kiddi): Replace JSONL handling as a followup to prevent\n# merge issues with other PRs.\n- data_frame = None\n- with open(filepath, 'r') as fh:\n- lines = [json.loads(x) for x in fh]\n- data_frame = pandas.DataFrame(lines)\n- if data_frame is None:\n- raise TypeError('Unable to parse the JSON file.')\n- if data_frame.empty:\n- raise TypeError('Is the JSON file empty?')\n-\n- self.add_data_frame(data_frame)\n+ with codecs.open(\n+ filepath, 'r', encoding=self._text_encoding,\n+ errors='replace') as fh:\n+ for line in fh:\n+ try:\n+ self.add_json(line.strip())\n+ except TypeError as e:\n+ logging.error(\n+ 'Unable to decode line: {0!s} - {1:s}'.format(\n+ e, line))\nelse:\nraise TypeError(\n'File needs to have a file extension of: .csv, .jsonl or '\n@@ -440,10 +529,7 @@ class ImportStreamer(object):\nreturn\nself._ready()\n-\n- data_frame = pandas.DataFrame(self._data_lines)\n- data_frame_use = self._fix_data_frame(data_frame)\n- self._upload_data_frame(data_frame_use, end_stream=end_stream)\n+ self._upload_data_buffer(end_stream=end_stream)\n@property\ndef response(self):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -508,9 +508,9 @@ def run_csv_jsonl(file_path, events, timeline_name, index_name, source_type):\nexcept Exception as e: # pylint: disable=broad-except\n# Mark the searchindex and timelines as failed and exit the task\n- error_msg = traceback.format_exc(e)\n+ error_msg = traceback.format_exc()\n_set_timeline_status(index_name, status='fail', error_msg=error_msg)\n- logging.error(error_msg)\n+ logging.error('Error: {0!s}\\n{1:s}'.format(e, error_msg))\nreturn None\n# Set status to ready when done\n" } ]
Python
Apache License 2.0
google/timesketch
Changing how JSON and dicts are uploaded.
263,111
21.02.2020 05:00:18
0
a7b1b61c9f6e2fcde43e81189b71750cc76d0522
The initial version of the Timesketch Analyzer that identifies Windows artefacts of application crashes and also checks if the crash reporting has been explicitly disabled.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/__init__.py", "new_path": "timesketch/lib/analyzers/__init__.py", "diff": "@@ -18,6 +18,7 @@ from timesketch.lib.analyzers import account_finder\nfrom timesketch.lib.analyzers import browser_search\nfrom timesketch.lib.analyzers import browser_timeframe\nfrom timesketch.lib.analyzers import chain\n+from timesketch.lib.analyzers import crash\nfrom timesketch.lib.analyzers import domain\nfrom timesketch.lib.analyzers import expert_sessionizers\nfrom timesketch.lib.analyzers import feature_extraction\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/crash.py", "diff": "+\"\"\"Sketch analyzer plugin for crashes.\"\"\"\n+from __future__ import unicode_literals\n+\n+import re\n+\n+from timesketch.lib import emojis\n+from timesketch.lib.analyzers import interface\n+from timesketch.lib.analyzers import manager\n+\n+\n+class CrashesSketchPlugin(interface.BaseSketchAnalyzer):\n+ \"\"\"Sketch analyzer for Windows Application Crashes.\"\"\"\n+\n+ NAME = 'crashes'\n+\n+ DEPENDENCIES = frozenset()\n+\n+ def __init__(self, index_name, sketch_id):\n+ \"\"\"Initialize The Sketch Analyzer.\n+\n+ Args:\n+ index_name: Elasticsearch index name\n+ sketch_id: Sketch ID\n+ \"\"\"\n+ self.index_name = index_name\n+ super(CrashesSketchPlugin, self).__init__(index_name, sketch_id)\n+\n+ def run(self):\n+ \"\"\"Entry point for the analyzer.\n+\n+ Returns:\n+ String with summary of the analyzer result\n+ \"\"\"\n+ query_elements = {\n+ 'Event - App Error' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Application Error\"',\n+ 'event_identifier:\"1000\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - WER' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Windows Error Reporting\"',\n+ 'event_identifier:\"1001\"',\n+ 'event_level:\"4\"', # Level: Info\n+ ),\n+ 'Event - BSOD' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Microsoft-Windows-WER-SystemErrorReporting\"',\n+ 'event_identifier:\"1001\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - App Hang' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Application Error\"',\n+ 'event_identifier:\"1002\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - EMET Warning' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"EMET\"',\n+ 'event_identifier:\"1\"',\n+ 'event_level:\"3\"', # Level: Warning\n+ ),\n+ 'Event - EMET Error' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"EMET\"',\n+ 'event_identifier:\"1\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - .NET App Crash' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\".NET Runtime\"',\n+ 'event_identifier:\"1026\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'File - WER Report' : (\n+ 'data_type:\"fs:stat\"',\n+ 'filename:\"/Microsoft/Windows/WER/\"',\n+ 'filename:/((Non)?Critical|AppCrash)_.*/',\n+ 'file_entry_type:(\"directory\" or \"2\")',\n+ ),\n+ 'Registry - Crash Reporting' : (\n+ 'data_type:\"windows:registry:key_value\"',\n+ r'key_path:r\"\\\\Control\\\\CrashControl\"',\n+ 'values:(\"LogEvent: REG_DWORD_LE 0\" OR \"SendAlert: REG_DWORD_LE 0\" OR \"CrashDumpEnabled: REG_DWORD_LE 0\")',\n+ ),\n+ 'Registry - Error Reporting' : (\n+ 'data_type:\"windows:registry:key_value\"',\n+ r'key_path:\"\\\\Software\\\\Microsoft\\\\PCHealth\\\\ErrorReporting\"',\n+ 'values:(\"DoReport: REG_DWORD_LE 0\" OR \"ShowUI: REG_DWORD_LE 0\")',\n+ ),\n+ }\n+\n+ # Creator of nested Elastic Search queries.\n+ def formulate_query(elements):\n+ conditions = []\n+ for e in elements.values():\n+ conditions += ['({0})'.format(' AND '.join(e))]\n+ return ' OR '.join(conditions)\n+\n+ # Re-usable filename matching function.\n+ def extract_filename(text, regex):\n+ if '.exe' in text.lower():\n+ match = regex.search(message)\n+ if match:\n+ # The regex can match on full file paths and filenames,\n+ # so only return the filename.\n+ return min([m for m in match.groups() if m])\n+ return None\n+\n+ # For adding information to identified entries.\n+ def mark_as_crash(event, filename):\n+ event.add_star()\n+ event.add_attributes({'crash_app': filename})\n+ event.add_label('crash')\n+\n+ query = formulate_query(query_elements)\n+\n+ return_fields = ['data_type', 'message', 'filename']\n+\n+ # Generator of events based on your query.\n+ events = self.event_stream(\n+ query_string=query, return_fields=return_fields)\n+\n+ # Get the executable filenames.\n+ # Examples:\n+ # \"[...]\\WER\\ReportQueue\\AppCrash_notepad.exe_8d163e29d3960561ca2e9723640cd8fff5c2ad5_cab_0a5810ac\"\n+ # \"[...]/WER/ReportQueue/NonCritical_x64_d473a376adfb18a7b165c5e3c26de43cd8bccb_cab_07fd2620\"\n+ # \"Strings: ['iexplore.exe', '8.0.7601.17514' [...]\"\n+ re_filename = re.compile(r'(?:\\\\|\\/)(?:AppCrash|Critical|NonCritical)_(.+?\\.exe)_[a-f0-9]{16,}|\\'([^\\']+\\.exe)\\'', re.I)\n+\n+ # Container for filenames of crashed applications.\n+ filenames = dict()\n+\n+ for event in events:\n+\n+ data_type = event.source.get('data_type')\n+\n+ # Search event log entries for filenames of crashed applications.\n+ if data_type == 'windows:evtx:record':\n+ message = event.source.get('message')\n+\n+ fn = extract_filename(message, re_filename)\n+ if not fn:\n+ continue\n+ filenames[fn] = ''\n+ mark_as_crash(event, fn)\n+\n+ # Search file system entries for filenames of crashed applications.\n+ elif data_type == 'fs:stat':\n+ filename = event.source.get('filename')\n+\n+ fn = extract_filename(filename, re_filename)\n+ if not fn:\n+ continue\n+ filenames[fn] = ''\n+ mark_as_crash(event, fn)\n+\n+ # Check if the crash reporting has been disabled in the registry.\n+ elif data_type == 'windows:registry:key_value':\n+ event.add_star()\n+ event.add_comment('WARNING: The crash reporting was disabled. '\n+ 'It could be indicative of attacker activity. '\n+ 'For details refer to page 16 from '\n+ 'https://assets.documentcloud.org/documents/3461560/Google-Aquarium-Clean.pdf.')\n+\n+ # Commit the event to the datastore.\n+ event.commit()\n+\n+ # Create a saved view with our query.\n+ if filenames:\n+ self.sketch.add_view('Crash activity', 'app_crashes', query_string=query)\n+\n+ return 'Crash analyzer completed, {0:d} crashed application{1:s} identified: {2:s}'.format(\n+ len(filenames), 's' if len(filenames) > 1 else '', ', '.join(filenames.keys()))\n+\n+manager.AnalysisManager.register_analyzer(CrashesSketchPlugin)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/crash_test.py", "diff": "+\"\"\"Tests for CrashPlugin.\"\"\"\n+from __future__ import unicode_literals\n+\n+import mock\n+\n+from timesketch.lib.analyzers import crash\n+from timesketch.lib.testlib import BaseTest\n+from timesketch.lib.testlib import MockDataStore\n+\n+\n+class TestCrashPlugin(BaseTest):\n+ \"\"\"Tests the functionality of the analyzer.\"\"\"\n+\n+ def __init__(self, *args, **kwargs):\n+ super(TestCrashPlugin, self).__init__(*args, **kwargs)\n+\n+ # Mock the Elasticsearch datastore.\n+ @mock.patch(\n+ u'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore)\n+ def test_analyzer(self):\n+ \"\"\"Test analyzer.\"\"\"\n+ # TODO: Write actual tests here.\n+ self.assertEqual(True, False)\n" } ]
Python
Apache License 2.0
google/timesketch
The initial version of the Timesketch Analyzer that identifies Windows artefacts of application crashes and also checks if the crash reporting has been explicitly disabled.
263,111
28.02.2020 04:32:10
0
8541d1d3b1d74f8b481bc6b0552789d40f1df251
Addressed comments from the pull request and added unit tests.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/__init__.py", "new_path": "timesketch/lib/analyzers/__init__.py", "diff": "@@ -18,7 +18,6 @@ from timesketch.lib.analyzers import account_finder\nfrom timesketch.lib.analyzers import browser_search\nfrom timesketch.lib.analyzers import browser_timeframe\nfrom timesketch.lib.analyzers import chain\n-from timesketch.lib.analyzers import crash\nfrom timesketch.lib.analyzers import domain\nfrom timesketch.lib.analyzers import expert_sessionizers\nfrom timesketch.lib.analyzers import feature_extraction\n@@ -31,3 +30,4 @@ from timesketch.lib.analyzers import ssh_sessionizer\nfrom timesketch.lib.analyzers import gcp_servicekey\nfrom timesketch.lib.analyzers import ntfs_timestomp\nfrom timesketch.lib.analyzers import yetiindicators\n+from timesketch.lib.analyzers import win_crash\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/win_crash.py", "diff": "+\"\"\"Sketch analyzer plugin for Windows crash artefacts.\"\"\"\n+from __future__ import unicode_literals\n+\n+import re\n+\n+from timesketch.lib.analyzers import interface\n+from timesketch.lib.analyzers import manager\n+\n+class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\n+ \"\"\"Sketch analyzer for Windows application crashes.\"\"\"\n+\n+ NAME = 'win_crash'\n+\n+ DEPENDENCIES = frozenset()\n+\n+ FILENAME_REGEX = re.compile(\n+ r'(?:\\\\|\\/)(?:AppCrash|Critical|NonCritical)_(.+?\\.exe)_[a-f0-9]{16,}'\n+ r'|\\'([^\\']+\\.exe)\\'', re.IGNORECASE)\n+\n+ QUERY_ELEMENTS = {\n+ 'Event - App Error' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Application Error\"',\n+ 'event_identifier:\"1000\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - WER' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Windows Error Reporting\"',\n+ 'event_identifier:\"1001\"',\n+ 'event_level:\"4\"', # Level: Info\n+ ),\n+ 'Event - BSOD' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Microsoft-Windows-WER-SystemErrorReporting\"',\n+ 'event_identifier:\"1001\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - App Hang' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"Application Error\"',\n+ 'event_identifier:\"1002\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - EMET Warning' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"EMET\"',\n+ 'event_identifier:\"1\"',\n+ 'event_level:\"3\"', # Level: Warning\n+ ),\n+ 'Event - EMET Error' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\"EMET\"',\n+ 'event_identifier:\"1\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'Event - .NET App Crash' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'source_name:\".NET Runtime\"',\n+ 'event_identifier:\"1026\"',\n+ 'event_level:\"2\"', # Level: Error\n+ ),\n+ 'File - WER Report' : (\n+ 'data_type:\"fs:stat\"',\n+ 'filename:\"/Microsoft/Windows/WER/\"',\n+ 'filename:/((Non)?Critical|AppCrash)_.*/',\n+ 'file_entry_type:(\"directory\" or \"2\")',\n+ ),\n+ 'Registry - Crash Reporting' : (\n+ 'data_type:\"windows:registry:key_value\"',\n+ r'key_path:\"\\\\Control\\\\CrashControl\"',\n+ 'values:(\"LogEvent: REG_DWORD_LE 0\"' + \\\n+ ' OR \"SendAlert: REG_DWORD_LE 0\"' + \\\n+ ' OR \"CrashDumpEnabled: REG_DWORD_LE 0\")',\n+ ),\n+ 'Registry - Error Reporting' : (\n+ 'data_type:\"windows:registry:key_value\"',\n+ r'key_path:\"\\\\Software\\\\Microsoft\\\\PCHealth\\\\ErrorReporting\"',\n+ 'values:(\"DoReport: REG_DWORD_LE 0\" OR \"ShowUI: REG_DWORD_LE 0\")',\n+ ),\n+ }\n+\n+ def __init__(self, index_name, sketch_id):\n+ \"\"\"Initialize The Sketch Analyzer.\n+\n+ Args:\n+ index_name: Elasticsearch index name\n+ sketch_id: Sketch ID\n+ \"\"\"\n+ self.index_name = index_name\n+ super(WinCrashSketchPlugin, self).__init__(index_name, sketch_id)\n+\n+ def formulate_query(self, elements):\n+ \"\"\"Generates the Elasticsearch query.\n+\n+ Args:\n+ elements: Dictionary with a list of conditions\n+\n+ Returns:\n+ The Elasticsearch query\n+ \"\"\"\n+ conditions = list()\n+ for e in elements.values():\n+ conditions += ['({0})'.format(' AND '.join(e))]\n+ return ' OR '.join(conditions)\n+\n+ def extract_filename(self, text):\n+ \"\"\"Finds filenames of crashed applications using a regular expression.\n+\n+ Args:\n+ text: String that might contain the filename\n+\n+ Returns:\n+ The string with filename if found\n+ \"\"\"\n+ if '.exe' in str(text or '').lower():\n+ match = self.FILENAME_REGEX.search(text)\n+ if match:\n+ # The regex can match on full file paths and filenames,\n+ # so only return the filename.\n+ return min([m for m in match.groups() if m])\n+ return None\n+\n+ def mark_as_crash(self, event, filename):\n+ \"\"\"Mark entries with crash artefacts.\n+\n+ Args:\n+ event: Elasticsearch event\n+ filename: Application that crashed\n+ \"\"\"\n+ if filename:\n+ event.add_attributes({'crash_app': filename})\n+ event.add_tags(['win_crash'])\n+\n+ def run(self):\n+ \"\"\"Entry point for the analyzer.\n+\n+ Returns:\n+ String with summary of the analyzer result\n+ \"\"\"\n+ query = self.formulate_query(self.QUERY_ELEMENTS)\n+\n+ return_fields = ['data_type', 'message', 'filename']\n+\n+ # Generator of events based on your query.\n+ events = self.event_stream(\n+ query_string=query, return_fields=return_fields)\n+\n+ # Container for filenames of crashed applications.\n+ filenames = list()\n+\n+ for event in events:\n+ data_type = event.source.get('data_type')\n+ event_text = None\n+\n+ # Search event log entries for filenames of crashed applications.\n+ if data_type == 'windows:evtx:record':\n+ event_text = event.source.get('message')\n+\n+ # Search file system entries for filenames of crashed applications.\n+ elif data_type == 'fs:stat':\n+ event_text = event.source.get('filename')\n+\n+ # Tag entries that show the crash reporting has been disabled.\n+ elif data_type == 'windows:registry:key_value':\n+ event.add_comment(\n+ 'WARNING: The crash reporting was disabled. '\n+ 'It could be indicative of attacker activity. '\n+ 'For details refer to page 16 from '\n+ 'https://assets.documentcloud.org/documents/3461560/'\n+ 'Google-Aquarium-Clean.pdf.')\n+ event.commit()\n+\n+ # If found the filename, tag the entry as crash-related\n+ filename = self.extract_filename(event_text)\n+ if filename:\n+ self.mark_as_crash(event, filename)\n+ filenames.append(filename)\n+ event.commit()\n+\n+ # Dedup the filenames of crashed apps\n+ filenames = set(filenames)\n+\n+ # Create a saved view with our query.\n+ if filenames:\n+ self.sketch.add_view(\n+ 'Windows Crash activity', 'win_crash', query_string=query)\n+\n+ return 'Windows Crash analyzer completed, ' + \\\n+ '{0:d} crashed application{1:s} identified: {2:s}'.format(\n+ len(filenames),\n+ 's' if len(filenames) > 1 else '',\n+ ', '.join(filenames))\n+\n+manager.AnalysisManager.register_analyzer(WinCrashSketchPlugin)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/analyzers/win_crash_test.py", "diff": "+\"\"\"Tests for WinCrashPlugin.\"\"\"\n+from __future__ import unicode_literals\n+\n+import mock, unittest\n+\n+from timesketch.lib.analyzers import win_crash\n+from timesketch.lib.testlib import BaseTest\n+from timesketch.lib.testlib import MockDataStore\n+from timesketch.models.user import User\n+from timesketch.models.sketch import Sketch\n+\n+class TestWinCrashPlugin(BaseTest):\n+ \"\"\"Tests the functionality of the analyzer.\"\"\"\n+\n+ @mock.patch(\n+ 'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore)\n+ def setUp(self):\n+ super().setUp()\n+ self.analyzer = win_crash.WinCrashSketchPlugin('test_index', 1)\n+\n+ def test_formulate_query(self):\n+ \"\"\"Test generator of Elasticsearch queries\"\"\"\n+ template = {\n+ 'Event - App Error' : (\n+ 'data_type:\"windows:evtx:record\"',\n+ 'event_level:\"2\"',\n+ ),\n+ 'File - WER Report' : (\n+ 'data_type:\"fs:stat\"',\n+ 'filename:\"/Microsoft/Windows/WER/\"',\n+ ),\n+ 'Registry - Crash Reporting' : (\n+ 'data_type:\"windows:registry:key_value\"',\n+ r'key_path:\"\\\\Control\\\\CrashControl\"',\n+ ),\n+ }\n+ expected_query = (\n+ '(data_type:\"windows:evtx:record\" AND event_level:\"2\")'\n+ ' OR (data_type:\"fs:stat\" AND filename:\"/Microsoft/Windows/WER/\")'\n+ ' OR (data_type:\"windows:registry:key_value\" AND '\n+ 'key_path:\"\\\\\\\\Control\\\\\\\\CrashControl\")'\n+ )\n+\n+ self.assertEqual(\n+ self.analyzer.formulate_query(template),\n+ expected_query)\n+\n+ def test_extract_filename(self):\n+ \"\"\"Test generator of filename extraction regex\"\"\"\n+ string_list = (\n+ '\\\\WER\\\\ReportQueue\\\\AppCrash_notepad.exe_8d163e29d3960561ca2e972'\n+ '3640cd8fff5c2ad5_cab_0a5810ac\\\\Report.wer',\n+ '/WER/ReportQueue/NonCritical_notepad.exe_d473a376adfb18a7b165c5e'\n+ '3c26de43cd8bccb_cab_07fd2620',\n+ '/WER/ReportQueue/NonCritical_x64_d473a376adfb18a7b165c5e3c26de43'\n+ 'cd8bccb_cab_07fd2620',\n+ 'Strings: [\\'iexplore.exe\\', \\'8.0.7601.17514\\'')\n+ expected_list = (\n+ 'notepad.exe',\n+ 'notepad.exe',\n+ None,\n+ 'iexplore.exe')\n+\n+ for i, s in enumerate(string_list):\n+ self.assertEqual(\n+ self.analyzer.extract_filename(s),\n+ expected_list[i])\n+\n+if __name__ == '__main__':\n+ unittest.main()\n\\ No newline at end of file\n" } ]
Python
Apache License 2.0
google/timesketch
Addressed comments from the pull request and added unit tests.
263,111
28.02.2020 04:39:54
0
2edbebe93420e90b4f71a674c33d73fe314a70e5
Removed the old files (renamed crash.py to win_crash.py).
[ { "change_type": "DELETE", "old_path": "timesketch/lib/analyzers/crash.py", "new_path": null, "diff": "-\"\"\"Sketch analyzer plugin for crashes.\"\"\"\n-from __future__ import unicode_literals\n-\n-import re\n-\n-from timesketch.lib import emojis\n-from timesketch.lib.analyzers import interface\n-from timesketch.lib.analyzers import manager\n-\n-\n-class CrashesSketchPlugin(interface.BaseSketchAnalyzer):\n- \"\"\"Sketch analyzer for Windows Application Crashes.\"\"\"\n-\n- NAME = 'crashes'\n-\n- DEPENDENCIES = frozenset()\n-\n- def __init__(self, index_name, sketch_id):\n- \"\"\"Initialize The Sketch Analyzer.\n-\n- Args:\n- index_name: Elasticsearch index name\n- sketch_id: Sketch ID\n- \"\"\"\n- self.index_name = index_name\n- super(CrashesSketchPlugin, self).__init__(index_name, sketch_id)\n-\n- def run(self):\n- \"\"\"Entry point for the analyzer.\n-\n- Returns:\n- String with summary of the analyzer result\n- \"\"\"\n- query_elements = {\n- 'Event - App Error' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"Application Error\"',\n- 'event_identifier:\"1000\"',\n- 'event_level:\"2\"', # Level: Error\n- ),\n- 'Event - WER' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"Windows Error Reporting\"',\n- 'event_identifier:\"1001\"',\n- 'event_level:\"4\"', # Level: Info\n- ),\n- 'Event - BSOD' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"Microsoft-Windows-WER-SystemErrorReporting\"',\n- 'event_identifier:\"1001\"',\n- 'event_level:\"2\"', # Level: Error\n- ),\n- 'Event - App Hang' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"Application Error\"',\n- 'event_identifier:\"1002\"',\n- 'event_level:\"2\"', # Level: Error\n- ),\n- 'Event - EMET Warning' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"EMET\"',\n- 'event_identifier:\"1\"',\n- 'event_level:\"3\"', # Level: Warning\n- ),\n- 'Event - EMET Error' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\"EMET\"',\n- 'event_identifier:\"1\"',\n- 'event_level:\"2\"', # Level: Error\n- ),\n- 'Event - .NET App Crash' : (\n- 'data_type:\"windows:evtx:record\"',\n- 'source_name:\".NET Runtime\"',\n- 'event_identifier:\"1026\"',\n- 'event_level:\"2\"', # Level: Error\n- ),\n- 'File - WER Report' : (\n- 'data_type:\"fs:stat\"',\n- 'filename:\"/Microsoft/Windows/WER/\"',\n- 'filename:/((Non)?Critical|AppCrash)_.*/',\n- 'file_entry_type:(\"directory\" or \"2\")',\n- ),\n- 'Registry - Crash Reporting' : (\n- 'data_type:\"windows:registry:key_value\"',\n- r'key_path:r\"\\\\Control\\\\CrashControl\"',\n- 'values:(\"LogEvent: REG_DWORD_LE 0\" OR \"SendAlert: REG_DWORD_LE 0\" OR \"CrashDumpEnabled: REG_DWORD_LE 0\")',\n- ),\n- 'Registry - Error Reporting' : (\n- 'data_type:\"windows:registry:key_value\"',\n- r'key_path:\"\\\\Software\\\\Microsoft\\\\PCHealth\\\\ErrorReporting\"',\n- 'values:(\"DoReport: REG_DWORD_LE 0\" OR \"ShowUI: REG_DWORD_LE 0\")',\n- ),\n- }\n-\n- # Creator of nested Elastic Search queries.\n- def formulate_query(elements):\n- conditions = []\n- for e in elements.values():\n- conditions += ['({0})'.format(' AND '.join(e))]\n- return ' OR '.join(conditions)\n-\n- # Re-usable filename matching function.\n- def extract_filename(text, regex):\n- if '.exe' in text.lower():\n- match = regex.search(message)\n- if match:\n- # The regex can match on full file paths and filenames,\n- # so only return the filename.\n- return min([m for m in match.groups() if m])\n- return None\n-\n- # For adding information to identified entries.\n- def mark_as_crash(event, filename):\n- event.add_star()\n- event.add_attributes({'crash_app': filename})\n- event.add_label('crash')\n-\n- query = formulate_query(query_elements)\n-\n- return_fields = ['data_type', 'message', 'filename']\n-\n- # Generator of events based on your query.\n- events = self.event_stream(\n- query_string=query, return_fields=return_fields)\n-\n- # Get the executable filenames.\n- # Examples:\n- # \"[...]\\WER\\ReportQueue\\AppCrash_notepad.exe_8d163e29d3960561ca2e9723640cd8fff5c2ad5_cab_0a5810ac\"\n- # \"[...]/WER/ReportQueue/NonCritical_x64_d473a376adfb18a7b165c5e3c26de43cd8bccb_cab_07fd2620\"\n- # \"Strings: ['iexplore.exe', '8.0.7601.17514' [...]\"\n- re_filename = re.compile(r'(?:\\\\|\\/)(?:AppCrash|Critical|NonCritical)_(.+?\\.exe)_[a-f0-9]{16,}|\\'([^\\']+\\.exe)\\'', re.I)\n-\n- # Container for filenames of crashed applications.\n- filenames = dict()\n-\n- for event in events:\n-\n- data_type = event.source.get('data_type')\n-\n- # Search event log entries for filenames of crashed applications.\n- if data_type == 'windows:evtx:record':\n- message = event.source.get('message')\n-\n- fn = extract_filename(message, re_filename)\n- if not fn:\n- continue\n- filenames[fn] = ''\n- mark_as_crash(event, fn)\n-\n- # Search file system entries for filenames of crashed applications.\n- elif data_type == 'fs:stat':\n- filename = event.source.get('filename')\n-\n- fn = extract_filename(filename, re_filename)\n- if not fn:\n- continue\n- filenames[fn] = ''\n- mark_as_crash(event, fn)\n-\n- # Check if the crash reporting has been disabled in the registry.\n- elif data_type == 'windows:registry:key_value':\n- event.add_star()\n- event.add_comment('WARNING: The crash reporting was disabled. '\n- 'It could be indicative of attacker activity. '\n- 'For details refer to page 16 from '\n- 'https://assets.documentcloud.org/documents/3461560/Google-Aquarium-Clean.pdf.')\n-\n- # Commit the event to the datastore.\n- event.commit()\n-\n- # Create a saved view with our query.\n- if filenames:\n- self.sketch.add_view('Crash activity', 'app_crashes', query_string=query)\n-\n- return 'Crash analyzer completed, {0:d} crashed application{1:s} identified: {2:s}'.format(\n- len(filenames), 's' if len(filenames) > 1 else '', ', '.join(filenames.keys()))\n-\n-manager.AnalysisManager.register_analyzer(CrashesSketchPlugin)\n" }, { "change_type": "DELETE", "old_path": "timesketch/lib/analyzers/crash_test.py", "new_path": null, "diff": "-\"\"\"Tests for CrashPlugin.\"\"\"\n-from __future__ import unicode_literals\n-\n-import mock\n-\n-from timesketch.lib.analyzers import crash\n-from timesketch.lib.testlib import BaseTest\n-from timesketch.lib.testlib import MockDataStore\n-\n-\n-class TestCrashPlugin(BaseTest):\n- \"\"\"Tests the functionality of the analyzer.\"\"\"\n-\n- def __init__(self, *args, **kwargs):\n- super(TestCrashPlugin, self).__init__(*args, **kwargs)\n-\n- # Mock the Elasticsearch datastore.\n- @mock.patch(\n- u'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n- MockDataStore)\n- def test_analyzer(self):\n- \"\"\"Test analyzer.\"\"\"\n- # TODO: Write actual tests here.\n- self.assertEqual(True, False)\n" } ]
Python
Apache License 2.0
google/timesketch
Removed the old files (renamed crash.py to win_crash.py).
263,092
03.03.2020 23:45:30
-3,600
afcf492168e5795c79e64751a172c796cfff0104
Fix start of Elasticsearch Run Elasticsearch as a single node. Documented at .
[ { "change_type": "MODIFY", "old_path": "docker/docker-compose.yml", "new_path": "docker/docker-compose.yml", "diff": "@@ -29,6 +29,7 @@ services:\nenvironment:\n- TAKE_FILE_OWNERSHIP=1\n+ - discovery.type=single-node\n# uncomment the following lines to control JVM memory utilization\n# in smaller deployments with minimal resources\n# - ES_JAVA_OPTS= -Xms1g -Xmx1g # 1G min/1G max\n" } ]
Python
Apache License 2.0
google/timesketch
Fix start of Elasticsearch (#1118) Run Elasticsearch as a single node. Documented at https://hub.docker.com/_/elasticsearch .
263,133
06.03.2020 09:36:26
0
46050ed4619b65e88da15064361a2a3ebcb038db
Changing how 'fields' gets handled in explore API.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -305,7 +305,7 @@ class Sketch(resource.BaseResource):\nArgs:\nquery_string: Elasticsearch query string.\nquery_dsl: Elasticsearch query DSL as JSON string.\n- query_filter: Filter for the query as JSON string.\n+ query_filter: Filter for the query as a dict.\nview: View object instance (optional).\nreturn_fields: List of fields that should be included in the\nresponse. Optional and defaults to None.\n@@ -322,8 +322,13 @@ class Sketch(resource.BaseResource):\nRaises:\nValueError: if unable to query for the results.\n+ RuntimeError: if the query is missing needed values.\n\"\"\"\n- default_filter = {\n+ if not (query_string or query_filter or query_dsl or view):\n+ raise RuntimeError('You need to supply a query or view')\n+\n+ if not query_filter:\n+ query_filter = {\n'time_start': None,\n'time_end': None,\n'size': self.DEFAULT_SIZE_LIMIT,\n@@ -332,27 +337,22 @@ class Sketch(resource.BaseResource):\n'order': 'asc'\n}\n- if as_pandas:\n- default_filter['size'] = 10000\n- default_filter['terminate_after'] = 10000\n-\n- if not (query_string or query_filter or query_dsl or view):\n- raise RuntimeError('You need to supply a query or view')\n-\n- if not query_filter:\n- query_filter = default_filter\n+ if not isinstance(query_filter, dict):\n+ raise ValueError(\n+ 'Unable to query with a query filter that isn\\'t a dict.')\nif view:\nif view.query_string:\nquery_string = view.query_string\nquery_filter = json.loads(view.query_filter)\n- query_filter['size'] = self.DEFAULT_SIZE_LIMIT\n- query_filter['terminate_after'] = self.DEFAULT_SIZE_LIMIT\n-\nif view.query_dsl:\nquery_dsl = json.loads(view.query_dsl)\n+ if as_pandas:\n+ query_filter.setdefault('size', self.DEFAULT_SIZE_LIMIT)\n+ query_filter.setdefault('terminate_after', self.DEFAULT_SIZE_LIMIT)\n+\nresource_url = '{0:s}/sketches/{1:d}/explore/'.format(\nself.api.api_root, self.id)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -781,7 +781,7 @@ class ExploreResource(ResourceMixin, Resource):\nenable_scroll = form.enable_scroll.data\nscroll_id = form.scroll_id.data\n- query_filter = request.json.get('filter', [])\n+ query_filter = request.json.get('filter', {})\nreturn_field_string = form.fields.data\nif return_field_string:\n" } ]
Python
Apache License 2.0
google/timesketch
Changing how 'fields' gets handled in explore API.
263,133
06.03.2020 14:25:35
0
9792182a3a009ac3ff71cbf7868bee396f12496e
Adding logging to sketch explore.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "from __future__ import unicode_literals\nimport json\n+import logging\nimport pandas\n@@ -25,6 +26,11 @@ from . import resource\nfrom . import timeline\nfrom . import view as view_lib\n+\n+logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))\n+logger = logging.getLogger('sketch_api')\n+\n+\nclass Sketch(resource.BaseResource):\n\"\"\"Timesketch sketch object.\n@@ -394,6 +400,12 @@ class Sketch(resource.BaseResource):\nadded_time = more_meta.get('es_time', 0)\nresponse_json['meta']['es_time'] += added_time\n+ total_elastic_count = response_json.get('es_total_count', 0)\n+ if total_elastic_count != total_count:\n+ logger.info('{0:>30s}: {1:d}\\n{2:>30s}: {3:d}'.format(\n+ 'Total results from search', total_elastic_count,\n+ 'Total results returned', total_count))\n+\nif as_pandas:\nreturn self._build_pandas_dataframe(response_json, return_fields)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding logging to sketch explore.
263,133
06.03.2020 14:35:20
0
432cfcc8332d8f52cbab66db3a8a4612d4757ae2
Fixing the sketch logging.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200305',\n+ version='20200306',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "\"\"\"Timesketch API client library.\"\"\"\nfrom __future__ import unicode_literals\n+import os\nimport json\nimport logging\n@@ -400,11 +401,12 @@ class Sketch(resource.BaseResource):\nadded_time = more_meta.get('es_time', 0)\nresponse_json['meta']['es_time'] += added_time\n- total_elastic_count = response_json.get('es_total_count', 0)\n+ total_elastic_count = response_json.get(\n+ 'meta', {}).get('es_total_count', 0)\nif total_elastic_count != total_count:\n- logger.info('{0:>30s}: {1:d}\\n{2:>30s}: {3:d}'.format(\n- 'Total results from search', total_elastic_count,\n- 'Total results returned', total_count))\n+ logger.info(\n+ '{0:d} results were returned, but {1:d} records matched the '\n+ 'search query'.format(total_count, total_elastic_count))\nif as_pandas:\nreturn self._build_pandas_dataframe(response_json, return_fields)\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing the sketch logging.
263,111
10.03.2020 14:54:28
-39,600
20c93190ecb76fc4460d21f4be41cde984057e48
Addressed comments from the Pull Request
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/win_crash.py", "new_path": "timesketch/lib/analyzers/win_crash.py", "diff": "@@ -100,8 +100,8 @@ class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\nThe Elasticsearch query\n\"\"\"\nconditions = list()\n- for e in elements.values():\n- conditions += ['({0})'.format(' AND '.join(e))]\n+ for element_list in elements.values():\n+ conditions += ['({0})'.format(' AND '.join(element_list))]\nreturn ' OR '.join(conditions)\ndef extract_filename(self, text):\n@@ -119,7 +119,7 @@ class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\n# The regex can match on full file paths and filenames,\n# so only return the filename.\nreturn min([m for m in match.groups() if m])\n- return None\n+ return ''\ndef mark_as_crash(self, event, filename):\n\"\"\"Mark entries with crash artefacts.\n@@ -147,22 +147,14 @@ class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\nquery_string=query, return_fields=return_fields)\n# Container for filenames of crashed applications.\n- filenames = list()\n+ filenames = set()\nfor event in events:\ndata_type = event.source.get('data_type')\nevent_text = None\n- # Search event log entries for filenames of crashed applications.\n- if data_type == 'windows:evtx:record':\n- event_text = event.source.get('message')\n-\n- # Search file system entries for filenames of crashed applications.\n- elif data_type == 'fs:stat':\n- event_text = event.source.get('filename')\n-\n# Tag entries that show the crash reporting has been disabled.\n- elif data_type == 'windows:registry:key_value':\n+ if data_type == 'windows:registry:key_value':\nevent.add_comment(\n'WARNING: The crash reporting was disabled. '\n'It could be indicative of attacker activity. '\n@@ -170,21 +162,28 @@ class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\n'https://assets.documentcloud.org/documents/3461560/'\n'Google-Aquarium-Clean.pdf.')\nevent.commit()\n+ continue\n+\n+ # Search event log entries for filenames of crashed applications.\n+ if data_type == 'windows:evtx:record':\n+ event_text = event.source.get('message')\n+\n+ # Search file system entries for filenames of crashed applications.\n+ elif data_type == 'fs:stat':\n+ event_text = event.source.get('filename')\n# If found the filename, tag the entry as crash-related\nfilename = self.extract_filename(event_text)\nif filename:\nself.mark_as_crash(event, filename)\n- filenames.append(filename)\n+ filenames.add(filename)\nevent.commit()\n- # Dedup the filenames of crashed apps\n- filenames = set(filenames)\n-\n# Create a saved view with our query.\nif filenames:\nself.sketch.add_view(\n- 'Windows Crash activity', 'win_crash', query_string=query)\n+ 'Windows Crash activity', 'win_crash',\n+ query_string='tag:\"win_crash\"')\nreturn 'Windows Crash analyzer completed, ' + \\\n'{0:d} crashed application{1:s} identified: {2:s}'.format(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/win_crash_test.py", "new_path": "timesketch/lib/analyzers/win_crash_test.py", "diff": "@@ -58,7 +58,7 @@ class TestWinCrashPlugin(BaseTest):\nexpected_list = (\n'notepad.exe',\n'notepad.exe',\n- None,\n+ '',\n'iexplore.exe')\nfor i, s in enumerate(string_list):\n" } ]
Python
Apache License 2.0
google/timesketch
Addressed comments from the Pull Request
263,134
10.03.2020 11:02:01
-3,600
bf05853a9d250e742de68a510e6ae8b85adc84e0
replaces PASSWORD with PASSWORD_FILE (fixes
[ { "change_type": "MODIFY", "old_path": "docker/docker-entrypoint.sh", "new_path": "docker/docker-entrypoint.sh", "diff": "@@ -10,8 +10,12 @@ if [ \"$1\" = 'timesketch' ]; then\nfi\n# Set up the Postgres connection\n+ if [ $POSTGRES_PASSWORD ]; then echo \"POSTGRES_PASSWORD usage is discouraged. Use Docker Secrets instead and set POSTGRES_PASSWORD_FILE to /run/secrets/secret-name\"; fi\n+ if [ $POSTGRES_PASSWORD_FILE ]; then POSTGRES_PASSWORD=$(cat $POSTGRES_PASSWORD_FILE); fi\n+\nif [ $POSTGRES_USER ] && [ $POSTGRES_PASSWORD ] && [ $POSTGRES_ADDRESS ] && [ $POSTGRES_PORT ]; then\nsed -i 's#postgresql://<USERNAME>:<PASSWORD>@localhost#postgresql://'$POSTGRES_USER':'$POSTGRES_PASSWORD'@'$POSTGRES_ADDRESS':'$POSTGRES_PORT'#' /etc/timesketch/timesketch.conf\n+ unset POSTGRES_PASSWORD\nelse\n# Log an error since we need the above-listed environment variables\necho \"Please pass values for the POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_ADDRESS, and POSTGRES_PORT environment variables\"\n@@ -42,6 +46,8 @@ if [ \"$1\" = 'timesketch' ]; then\nTIMESKETCH_USER=\"admin\"\necho \"TIMESKETCH_USER set to default: ${TIMESKETCH_USER}\";\nfi\n+ if [ $TIMESKETCH_PASSWORD ]; then echo \"TIMESKETCH_PASSWORD usage is discouraged. Use Docker Secrets instead and set TIMESKETCH_PASSWORD_FILE to /run/secrets/secret-name\"; fi\n+ if [ $TIMESKETCH_PASSWORD_FILE ]; then TIMESKETCH_PASSWORD=$(cat $TIMESKETCH_PASSWORD_FILE); fi\nif [ -z ${TIMESKETCH_PASSWORD:+x} ]; then\nTIMESKETCH_PASSWORD=\"$(openssl rand -base64 32)\"\necho \"TIMESKETCH_PASSWORD set randomly to: ${TIMESKETCH_PASSWORD}\";\n@@ -50,6 +56,7 @@ if [ \"$1\" = 'timesketch' ]; then\n# Sleep to allow the other processes to start\nsleep 5\ntsctl add_user --username \"$TIMESKETCH_USER\" --password \"$TIMESKETCH_PASSWORD\"\n+ unset TIMESKETCH_PASSWORD\n# Run the Timesketch server (without SSL)\ncd /tmp\n" } ]
Python
Apache License 2.0
google/timesketch
replaces PASSWORD with PASSWORD_FILE (fixes #1126) (#1127)
263,133
10.03.2020 13:52:24
0
6fbde74e9795dadeef8d5b0e3f8e99c48fa92b7a
Adding a check for indexing.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/tasks.py", "new_path": "timesketch/lib/tasks.py", "diff": "@@ -22,6 +22,7 @@ import traceback\nimport codecs\nimport io\nimport json\n+import time\nimport six\nfrom celery import chain\n@@ -242,13 +243,32 @@ def build_sketch_analysis_pipeline(sketch_id, searchindex_id, user_id,\nsketch = Sketch.query.get(sketch_id)\nanalysis_session = AnalysisSession(user, sketch)\n+ searchindex = SearchIndex.query.get(searchindex_id)\n+ counter = 0\n+ while True:\n+ status = searchindex.get_status()\n+ if status == 'READY':\n+ break\n+\n+ if status == 'FAIL':\n+ logging.error(\n+ 'Unable to run analyzer on a failed index ({0:s})'.format(\n+ searchindex_id))\n+ return None, None\n+\n+ time.sleep(10)\n+ counter += 1\n+ if counter >= 360:\n+ logging.error(\n+ 'Indexing has taken too long time, aborting run of analyzer')\n+ return None, None\n+\nanalyzers = manager.AnalysisManager.get_analyzers(analyzer_names)\nfor analyzer_name, analyzer_cls in analyzers:\nif not analyzer_cls.IS_SKETCH_ANALYZER:\ncontinue\nkwargs = analyzer_kwargs.get(analyzer_name, {})\n- searchindex = SearchIndex.query.get(searchindex_id)\ntimeline = Timeline.query.filter_by(\nsketch=sketch, searchindex=searchindex).first()\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a check for indexing.
263,133
11.03.2020 13:50:45
0
e18ac02adb2763d37d21d8d1d599d9f7d9063c8c
Bumping API client version
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200311',\n+ version='20200312',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Bumping API client version
263,133
11.03.2020 16:08:39
0
22a5da1695c5454ef373b0d7e73d3a70ac2fa932
Adding the ability to delete stories, and work with stories in the API
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "from __future__ import unicode_literals\nimport os\n+import json\n+import logging\nimport uuid\n# pylint: disable=wrong-import-order\n@@ -35,6 +37,9 @@ from . import index\nfrom . import sketch\n+logger = logging.getLogger('client_api')\n+\n+\nclass TimesketchApi(object):\n\"\"\"Timesketch API object\n@@ -270,10 +275,16 @@ class TimesketchApi(object):\nReturns:\nDictionary with the response data.\n\"\"\"\n- # TODO: Catch HTTP errors and add descriptive message string.\nresource_url = '{0:s}/{1:s}'.format(self.api_root, resource_uri)\nresponse = self.session.get(resource_url)\n+ try:\nreturn response.json()\n+ except json.JSONDecodeError as e:\n+ logger.error(\n+ 'Error fetching resources: [{0:d}] {1!s} {2!s}, error: '\n+ '{3!s}'.format(\n+ response.status_code, response.reason, response.text, e))\n+ return {}\ndef create_sketch(self, name, description=None):\n\"\"\"Create a new sketch.\n@@ -362,7 +373,7 @@ class TimesketchApi(object):\nreturn pandas.DataFrame(lines)\ndef list_sketches(self):\n- \"\"\"Get list of all open sketches that the user has access to.\n+ \"\"\"Get a list of all open sketches that the user has access to.\nReturns:\nList of Sketch objects instances.\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -24,6 +24,7 @@ from . import aggregation\nfrom . import definitions\nfrom . import error\nfrom . import resource\n+from . import story\nfrom . import timeline\nfrom . import view as view_lib\n@@ -143,6 +144,31 @@ class Sketch(resource.BaseResource):\nreturn data_frame\n+ def create_story(self, title):\n+ \"\"\"Create a story object.\n+\n+ Args:\n+ title: the title of the story.\n+\n+ Returns:\n+ A story object (instance of Story) for the newly\n+ created story.\n+ \"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/stories/'.format(\n+ self.api.api_root, self.id)\n+ data = {\n+ 'title': title,\n+ 'content': ''\n+ }\n+\n+ response = self.api.session.post(resource_url, json=data)\n+ response_json = response.json()\n+ story_dict = response_json.get('objects', [{}])[0]\n+ return story.Story(\n+ story_id=story_dict.get('id', -1),\n+ sketch_id=self.id,\n+ api=self.api)\n+\ndef list_aggregations(self):\n\"\"\"List all saved aggregations for this sketch.\n@@ -209,6 +235,25 @@ class Sketch(resource.BaseResource):\nreturn view\nreturn None\n+ def list_stories(self):\n+ \"\"\"Get a list of all stories that are attached to the sketch.\n+\n+ Returns:\n+ List of stories (instances of Story objects)\n+ \"\"\"\n+ story_list = []\n+ resource_url = '{0:s}/sketches/{1:d}/stories/'.format(\n+ self.api.api_root, self.id)\n+ response = self.api.session.get(resource_url)\n+ response_json = response.json()\n+ stories = response_json.get('objects', [[]])[0]\n+ for story_dict in stories:\n+ story_list.append(story.Story(\n+ story_id=story_dict.get('id', -1),\n+ sketch_id=self.id,\n+ api=self.api))\n+ return story_list\n+\ndef list_views(self):\n\"\"\"List all saved views for this sketch.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1882,7 +1882,7 @@ class StoryListResource(ResourceMixin, Resource):\ntitle = form.title.data\nsketch = Sketch.query.get_with_acl(sketch_id)\nstory = Story(\n- title=title, content='', sketch=sketch, user=current_user)\n+ title=title, content='[]', sketch=sketch, user=current_user)\ndb_session.add(story)\ndb_session.commit()\nreturn self.to_json(story, status_code=HTTP_STATUS_CODE_CREATED)\n@@ -1932,25 +1932,68 @@ class StoryResource(ResourceMixin, Resource):\nReturns:\nA view in JSON (instance of flask.wrappers.Response)\n\"\"\"\n- form = StoryForm.build(request)\n- if not form.validate_on_submit():\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate form data.')\nsketch = Sketch.query.get_with_acl(sketch_id)\nstory = Story.query.get(story_id)\n+ if not story:\n+ msg = 'No Story found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\n+ if not sketch:\n+ msg = 'No sketch found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\nif story.sketch_id != sketch.id:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\n'Sketch ID ({0:d}) does not match with the ID in '\n'the story ({1:d})'.format(sketch.id, story.sketch_id))\n- story.title = form.title.data\n- story.content = form.content.data\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ story.title = form.get('title', '')\n+ story.content = form.get('content', '[]')\ndb_session.add(story)\ndb_session.commit()\nreturn self.to_json(story, status_code=HTTP_STATUS_CODE_CREATED)\n+ @login_required\n+ def delete(self, sketch_id, story_id):\n+ \"\"\"Handles DELETE request to the resource.\n+\n+ Args:\n+ sketch_id: Integer primary key for a sketch database model\n+ story_id: Integer primary key for a story database model\n+ \"\"\"\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ story = Story.query.get(story_id)\n+\n+ if not story:\n+ msg = 'No Story found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\n+ if not sketch:\n+ msg = 'No sketch found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\n+ # Check that this timeline belongs to the sketch\n+ if story.sketch_id != sketch.id:\n+ msg = (\n+ 'The sketch ID ({0:d}) does not match with the story'\n+ 'sketch ID ({1:d})'.format(sketch.id, story.sketch_id))\n+ abort(HTTP_STATUS_CODE_FORBIDDEN, msg)\n+\n+ if not sketch.has_permission(user=current_user, permission='write'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'The user does not have write permission on the sketch.')\n+\n+ sketch.stories.remove(story)\n+ db_session.commit()\n+ return HTTP_STATUS_CODE_OK\n+\nclass QueryResource(ResourceMixin, Resource):\n\"\"\"Resource to get a query.\"\"\"\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to delete stories, and work with stories in the API
263,133
11.03.2020 16:09:34
0
6fac9c8e152420f810b730ddf47410672013d3fe
adding the story file
[ { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch API client library.\"\"\"\n+from __future__ import unicode_literals\n+\n+import json\n+\n+from . import definitions\n+from . import resource\n+\n+\n+class Story(resource.BaseResource):\n+ \"\"\"Story object.\n+\n+ Attributes:\n+ id: Primary key of the story.\n+ \"\"\"\n+\n+ def __init__(self, story_id, sketch_id, api):\n+ \"\"\"Initializes the Story object.\n+\n+ Args:\n+ story_id: The primary key ID of the story.\n+ sketch_id: ID of a sketch.\n+ api: Instance of a TimesketchApi object.\n+ \"\"\"\n+ self.id = story_id\n+ self._title = ''\n+ self._content = ''\n+\n+ resource_uri = 'sketches/{0:d}/stories/{1:d}/'.format(\n+ sketch_id, self.id)\n+ super(Story, self).__init__(api, resource_uri)\n+\n+ @property\n+ def title(self):\n+ \"\"\"Property that returns story title.\n+\n+ Returns:\n+ Story name as a string.\n+ \"\"\"\n+ if not self._title:\n+ story = self.lazyload_data()\n+ objects = story.get('objects')\n+ if objects:\n+ self._title = objects[0].get('title', 'No Title')\n+ return self._title\n+\n+ @property\n+ def content(self):\n+ \"\"\"Property that returns the content of a story.\n+\n+ Returns:\n+ Story content as a list of blocks.\n+ \"\"\"\n+ if not self._content:\n+ story = self.lazyload_data()\n+ objects = story.get('objects')\n+ if objects:\n+ self._content = objects[0].get('content', [])\n+ return self._content\n+\n+ def _add_block(self, block):\n+ \"\"\"Adds a block to the story's content.\"\"\"\n+ self.refresh()\n+ content = self.content\n+ if content:\n+ content_list = json.loads(content)\n+ else:\n+ content_list = []\n+\n+ content_list.append(block)\n+ self._content = json.dumps(content_list)\n+\n+ data = {\n+ 'title': self.title,\n+ 'content': self._content,\n+ }\n+ response = self.api.session.post(\n+ '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri),\n+ json=data)\n+\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\n+ def _create_new_block(self):\n+ \"\"\"Returns a new block dict.\"\"\"\n+ return {\n+ 'componentName': '',\n+ 'componentProps': {},\n+ 'content': '',\n+ 'edit': False,\n+ 'showPanel': False,\n+ 'isActive': False\n+ }\n+\n+ def add_text(self, text):\n+ \"\"\"Adds a text block to the story.\n+\n+ Args:\n+ text: the string to add to the story.\n+\n+ Returns:\n+ Boolean that indicates whether block was successfully added.\n+ \"\"\"\n+ text_block = self._create_new_block()\n+ text_block['content'] = text\n+\n+ return self._add_block(text_block)\n+\n+ def add_view(self, view):\n+ \"\"\"Add a view to the story.\n+\n+ Args:\n+ view: a view object (instance of view.View)\n+\n+ Returns:\n+ Boolean that indicates whether block was successfully added.\n+\n+ Raises:\n+ TypeError: if the view object is not of the correct type.\n+ \"\"\"\n+ if not hasattr(view, 'id'):\n+ raise TypeError('View object is not correctly formed.')\n+\n+ if not hasattr(view, 'name'):\n+ raise TypeError('View object is not correctly formed.')\n+\n+ view_block = self._create_new_block()\n+ view_block['componentName'] = 'TsViewEventList'\n+ view_block['componentProps']['view'] = {\n+ 'id': view.id, 'name': view.name}\n+\n+ return self._add_block(view_block)\n+\n+ def delete(self):\n+ \"\"\"Delete the story from the sketch.\n+\n+ Returns:\n+ Boolean that indicates whether the deletion was successful.\n+ \"\"\"\n+ response = self.api.session.delete(\n+ '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri))\n+\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\n+ def refresh(self):\n+ \"\"\"Refresh story content.\"\"\"\n+ self._title = ''\n+ self._content = ''\n+ _ = self.lazyload_data(refresh_cache=True)\n" } ]
Python
Apache License 2.0
google/timesketch
adding the story file
263,133
12.03.2020 10:11:41
0
f4c57455094e4ad52c69a0b9d0c040f489014a9e
Adding tests and rewriting how the story API client works.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -166,7 +166,7 @@ class Sketch(resource.BaseResource):\nstory_dict = response_json.get('objects', [{}])[0]\nreturn story.Story(\nstory_id=story_dict.get('id', -1),\n- sketch_id=self.id,\n+ sketch=self,\napi=self.api)\ndef list_aggregations(self):\n@@ -250,7 +250,7 @@ class Sketch(resource.BaseResource):\nfor story_dict in stories:\nstory_list.append(story.Story(\nstory_id=story_dict.get('id', -1),\n- sketch_id=self.id,\n+ sketch=self,\napi=self.api))\nreturn story_list\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -18,6 +18,189 @@ import json\nfrom . import definitions\nfrom . import resource\n+from . import view\n+\n+\n+class BaseBlock(object):\n+ \"\"\"Base block object.\"\"\"\n+\n+ # A string representation of the type of block.\n+ TYPE = ''\n+\n+ def __init__(self, story, index):\n+ \"\"\"Initialize the base block.\"\"\"\n+ self.index = index\n+ self._story = story\n+\n+ self._data = None\n+\n+ @property\n+ def data(self):\n+ \"\"\"Returns the building block.\"\"\"\n+ return self.to_dict()\n+\n+ @data.setter\n+ def data(self, data):\n+ \"\"\"Feeds data to the block.\"\"\"\n+ self._data = data\n+\n+ @property\n+ def json(self):\n+ \"\"\"Returns the building block.\"\"\"\n+ return self.to_dict()\n+\n+ def _get_base(self):\n+ \"\"\"Returns a base building block.\"\"\"\n+ return {\n+ 'componentName': '',\n+ 'componentProps': {},\n+ 'content': '',\n+ 'edit': False,\n+ 'showPanel': False,\n+ 'isActive': False\n+ }\n+\n+ def delete(self):\n+ \"\"\"Remove block from index.\"\"\"\n+ self._story.remove_block(self.index)\n+\n+ def feed(self, data):\n+ \"\"\"Feed data into the block.\"\"\"\n+ self._data = data\n+\n+ def from_dict(self, data_dict):\n+ \"\"\"Feed a block from a block dict.\"\"\"\n+ raise NotImplementedError\n+\n+ def move_down(self):\n+ \"\"\"Moves a block down one location in the index.\"\"\"\n+ self._story.move_to(self, self.index+1)\n+\n+ def move_up(self):\n+ \"\"\"Moves a block up one location in the index.\"\"\"\n+ self._story.move_to(self, self.index-1)\n+\n+ def to_dict(self):\n+ \"\"\"Returns a dict with the block data.\n+\n+ Raises:\n+ ValueError: if the block has not been fed with data.\n+ TypeError: if the data that was fed is of the wrong type.\n+\n+ Returns:\n+ A dict with the block data.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+ def reset(self):\n+ \"\"\"Resets the data in the block.\"\"\"\n+ self._data = None\n+\n+\n+class ViewBlock(BaseBlock):\n+ \"\"\"Block object for views.\"\"\"\n+\n+ TYPE = 'view'\n+\n+ def __init__(self, story, index):\n+ super(ViewBlock, self).__init__(story, index)\n+ self._view_id = 0\n+ self._view_name = ''\n+\n+ @property\n+ def view(self):\n+ \"\"\"Returns the view.\"\"\"\n+ return self._data\n+\n+ @property\n+ def view_id(self):\n+ \"\"\"Returns the view ID.\"\"\"\n+ if self._data and hasattr(self._data, 'id'):\n+ return self._data.id\n+ return self._view_id\n+\n+ @property\n+ def view_name(self):\n+ \"\"\"Returns the view name.\"\"\"\n+ if self._data and hasattr(self._data, 'name'):\n+ return self._data.name\n+ return self._view_name\n+\n+ def from_dict(self, data_dict):\n+ \"\"\"Feed a block from a block dict.\"\"\"\n+ props = data_dict.get('componentProps', {})\n+ view_dict = props.get('view')\n+ if not view_dict:\n+ raise TypeError('View not defined')\n+\n+ self._view_id = view_dict.get('id', 0)\n+ self._view_name = view_dict.get('name', '')\n+\n+ def to_dict(self):\n+ \"\"\"Returns a dict with the block data.\n+\n+ Raises:\n+ ValueError: if the block has not been fed with data.\n+ TypeError: if the data that was fed is of the wrong type.\n+\n+ Returns:\n+ A dict with the block data.\n+ \"\"\"\n+ if not self._data:\n+ raise ValueError('No data has been fed to the block.')\n+\n+ view_obj = self._data\n+ if not hasattr(view_obj, 'id'):\n+ raise TypeError('View object is not correctly formed.')\n+\n+ if not hasattr(view_obj, 'name'):\n+ raise TypeError('View object is not correctly formed.')\n+\n+ view_block = self._get_base()\n+ view_block['componentName'] = 'TsViewEventList'\n+ view_block['componentProps']['view'] = {\n+ 'id': view_obj.id, 'name': view_obj.name}\n+\n+ return view_block\n+\n+\n+class TextBlock(BaseBlock):\n+ \"\"\"Block object for text.\"\"\"\n+\n+ TYPE = 'text'\n+\n+ @property\n+ def text(self):\n+ \"\"\"Returns the text.\"\"\"\n+ if not self._data:\n+ return ''\n+ return self._data\n+\n+ def from_dict(self, data_dict):\n+ \"\"\"Feed a block from a block dict.\"\"\"\n+ text = data_dict.get('content', '')\n+ self.feed(text)\n+\n+ def to_dict(self):\n+ \"\"\"Returns a dict with the block data.\n+\n+ Raises:\n+ ValueError: if the block has not been fed with data.\n+ TypeError: if the data that was fed is of the wrong type.\n+\n+ Returns:\n+ A dict with the block data.\n+ \"\"\"\n+ if not self._data:\n+ raise ValueError('No data has been fed to the block.')\n+\n+ if not isinstance(self._data, str):\n+ raise TypeError('Data to a text block needs to be a string.')\n+\n+ text_block = self._get_base()\n+ text_block['content'] = self._data\n+\n+ return text_block\nclass Story(resource.BaseResource):\n@@ -27,22 +210,49 @@ class Story(resource.BaseResource):\nid: Primary key of the story.\n\"\"\"\n- def __init__(self, story_id, sketch_id, api):\n+ def __init__(self, story_id, sketch, api):\n\"\"\"Initializes the Story object.\nArgs:\nstory_id: The primary key ID of the story.\n- sketch_id: ID of a sketch.\n+ sketch: The sketch object (instance of Sketch).\napi: Instance of a TimesketchApi object.\n\"\"\"\nself.id = story_id\n+ self._api = api\nself._title = ''\n- self._content = ''\n+ self._blocks = []\n+ self._sketch = sketch\nresource_uri = 'sketches/{0:d}/stories/{1:d}/'.format(\n- sketch_id, self.id)\n+ sketch.id, self.id)\nsuper(Story, self).__init__(api, resource_uri)\n+ @property\n+ def blocks(self):\n+ \"\"\"Returns all the blocks of the story.\"\"\"\n+ if not self._blocks:\n+ story_data = self.lazyload_data()\n+ objects = story_data.get('objects')\n+ content = ''\n+ if objects:\n+ content = objects[0].get('content', [])\n+ index = 0\n+ for content_block in json.loads(content):\n+ if content_block.get('content'):\n+ block = TextBlock(self, index)\n+ block.from_dict(content_block)\n+ else:\n+ block = ViewBlock(self, index)\n+ block.from_dict(content_block)\n+ view_obj = view.View(\n+ block.view_id, block.view_name, self._sketch.id,\n+ self._api)\n+ block.feed(view_obj)\n+ self._blocks.append(block)\n+ index += 1\n+ return self._blocks\n+\n@property\ndef title(self):\n\"\"\"Property that returns story title.\n@@ -64,28 +274,32 @@ class Story(resource.BaseResource):\nReturns:\nStory content as a list of blocks.\n\"\"\"\n- if not self._content:\n- story = self.lazyload_data()\n- objects = story.get('objects')\n- if objects:\n- self._content = objects[0].get('content', [])\n- return self._content\n+ content_list = [x.to_dict() for x in self.blocks]\n+ return json.dumps(content_list)\n+\n+ @property\n+ def size(self):\n+ \"\"\"Retiurns the number of blocks stored in the story.\"\"\"\n+ return len(self._blocks)\n- def _add_block(self, block):\n+ def __len__(self):\n+ \"\"\"Returns the number of blocks stored in the story.\"\"\"\n+ return len(self._blocks)\n+\n+ def _add_block(self, block, index):\n\"\"\"Adds a block to the story's content.\"\"\"\n+ self._blocks.insert(index, block)\n+ self._commit()\nself.refresh()\n- content = self.content\n- if content:\n- content_list = json.loads(content)\n- else:\n- content_list = []\n- content_list.append(block)\n- self._content = json.dumps(content_list)\n+ def _commit(self):\n+ \"\"\"Commit the story to the server.\"\"\"\n+ content_list = [x.to_dict() for x in self._blocks]\n+ content = json.dumps(content_list)\ndata = {\n'title': self.title,\n- 'content': self._content,\n+ 'content': content,\n}\nresponse = self.api.session.post(\n'{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri),\n@@ -93,36 +307,33 @@ class Story(resource.BaseResource):\nreturn response.status_code in definitions.HTTP_STATUS_CODE_20X\n- def _create_new_block(self):\n- \"\"\"Returns a new block dict.\"\"\"\n- return {\n- 'componentName': '',\n- 'componentProps': {},\n- 'content': '',\n- 'edit': False,\n- 'showPanel': False,\n- 'isActive': False\n- }\n-\n- def add_text(self, text):\n+ def add_text(self, text, index=-1):\n\"\"\"Adds a text block to the story.\nArgs:\ntext: the string to add to the story.\n+ index: an integer, if supplied determines where the new\n+ block will be added. If not supplied it will be\n+ appended at the end.\nReturns:\nBoolean that indicates whether block was successfully added.\n\"\"\"\n- text_block = self._create_new_block()\n- text_block['content'] = text\n+ if index == -1:\n+ index = len(self._blocks)\n+ text_block = TextBlock(self, index)\n+ text_block.feed(text)\n- return self._add_block(text_block)\n+ return self._add_block(text_block, index)\n- def add_view(self, view):\n+ def add_view(self, view_obj, index=-1):\n\"\"\"Add a view to the story.\nArgs:\n- view: a view object (instance of view.View)\n+ view_obj: a view object (instance of view.View)\n+ index: an integer, if supplied determines where the new\n+ block will be added. If not supplied it will be\n+ appended at the end.\nReturns:\nBoolean that indicates whether block was successfully added.\n@@ -130,18 +341,19 @@ class Story(resource.BaseResource):\nRaises:\nTypeError: if the view object is not of the correct type.\n\"\"\"\n- if not hasattr(view, 'id'):\n+ if not hasattr(view_obj, 'id'):\nraise TypeError('View object is not correctly formed.')\n- if not hasattr(view, 'name'):\n+ if not hasattr(view_obj, 'name'):\nraise TypeError('View object is not correctly formed.')\n- view_block = self._create_new_block()\n- view_block['componentName'] = 'TsViewEventList'\n- view_block['componentProps']['view'] = {\n- 'id': view.id, 'name': view.name}\n+ if index == -1:\n+ index = len(self._blocks)\n+\n+ view_block = ViewBlock(self, index)\n+ view_block.feed(view_obj)\n- return self._add_block(view_block)\n+ return self._add_block(view_block, index)\ndef delete(self):\n\"\"\"Delete the story from the sketch.\n@@ -154,8 +366,39 @@ class Story(resource.BaseResource):\nreturn response.status_code in definitions.HTTP_STATUS_CODE_20X\n+ def move_to(self, block, new_index):\n+ \"\"\"Moves a block from one index to another.\"\"\"\n+ if new_index < 0:\n+ return\n+ old_index = block.index\n+ old_block = self._blocks.pop(old_index)\n+ if old_block.data != block.data:\n+ raise ValueError('Block is not correctly set.')\n+ self._blocks.insert(new_index, block)\n+ self._commit()\n+\n+ def remove_block(self, index):\n+ \"\"\"Removes a block from the story.\"\"\"\n+ _ = self._blocks.pop(index)\n+ self._commit()\n+ self.refresh()\n+\ndef refresh(self):\n\"\"\"Refresh story content.\"\"\"\nself._title = ''\n- self._content = ''\n+ self._blocks = []\n_ = self.lazyload_data(refresh_cache=True)\n+ _ = self.blocks\n+\n+ def to_string(self):\n+ \"\"\"Returns a string with the content of all the story.\"\"\"\n+ self.refresh()\n+ string_list = []\n+ for block in self.blocks:\n+ if block.TYPE == 'text':\n+ string_list.append(block.text)\n+ elif block.TYPE == 'view':\n+ data_frame = self._sketch.explore(\n+ view=block.view, as_pandas=True)\n+ string_list.append(data_frame.to_string(index=False))\n+ return '\\n'.join(string_list)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/story_test.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Tests for the Timesketch API client\"\"\"\n+from __future__ import unicode_literals\n+\n+import unittest\n+import mock\n+\n+from . import client\n+from . import test_lib\n+from . import story as story_lib\n+\n+\n+class StoryTest(unittest.TestCase):\n+ \"\"\"Test Story object.\"\"\"\n+\n+ @mock.patch('requests.Session', test_lib.mock_session)\n+ def setUp(self):\n+ \"\"\"Setup test case.\"\"\"\n+ self.api_client = client.TimesketchApi(\n+ 'http://127.0.0.1', 'test', 'test')\n+ self.sketch = self.api_client.get_sketch(1)\n+\n+ def test_story(self):\n+ \"\"\"Test story object.\"\"\"\n+ story = self.sketch.list_stories()[0]\n+ self.assertIsInstance(story, story_lib.Story)\n+ self.assertEqual(story.id, 1)\n+ self.assertEqual(story.title, 'my first test story')\n+ self.assertEqual(len(story), 2)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding tests and rewriting how the story API client works.
263,133
12.03.2020 12:52:00
0
66336dacc9938d1f9e22c36b5e66b5d8d0365a0d
Fixing running tests to include API client tests, fixing tests.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/importer_test.py", "new_path": "api_client/python/timesketch_api_client/importer_test.py", "diff": "@@ -35,20 +35,23 @@ class MockSketch(object):\nclass MockStreamer(importer.ImportStreamer):\n\"\"\"Mock the import streamer.\"\"\"\n- def __init__(self, entry_threshold=None):\n- super(MockStreamer, self).__init__(entry_threshold)\n- self.files = []\n+ def __init__(self):\n+ super(MockStreamer, self).__init__()\nself.lines = []\n- self.columns = []\n- def _upload_data(self, file_name, end_stream):\n- self.files.append(file_name)\n- with open(file_name, 'r') as fh:\n- first_line = next(fh)\n- self.columns = [x.strip() for x in first_line.split(',')]\n- for line in fh:\n- line = line.strip()\n- self.lines.append(line)\n+ @property\n+ def columns(self):\n+ columns = set()\n+ for line in self.lines:\n+ columns.update(line.keys())\n+ return list(columns)\n+\n+ def _upload_data_buffer(self, end_stream):\n+ self.lines.extend(self._data_lines)\n+\n+ def _upload_data_frame(self, data_frame, end_stream):\n+ self.lines.extend(\n+ json.loads(data_frame.to_json(orient='records')))\ndef close(self):\npass\n@@ -110,7 +113,6 @@ class TimesketchImporterTest(unittest.TestCase):\ndef test_adding_data_frames(self):\n\"\"\"Test adding a data frame to the importer.\"\"\"\n-\nwith MockStreamer() as streamer:\nstreamer.set_sketch(MockSketch())\nstreamer.set_timestamp_description('Log Entries')\n@@ -120,25 +122,24 @@ class TimesketchImporterTest(unittest.TestCase):\nstreamer.add_data_frame(self.frame)\nself._run_all_tests(streamer.columns, streamer.lines)\n- self.assertEqual(len(streamer.files), 1)\n+ self.assertEqual(len(streamer.lines), 5)\n# Test by splitting up the dataset into chunks.\nlines = None\n- files = None\ncolumns = None\n- with MockStreamer(2) as streamer:\n+ with MockStreamer() as streamer:\nstreamer.set_sketch(MockSketch())\nstreamer.set_timestamp_description('Log Entries')\nstreamer.set_timeline_name('Test Entries')\n+ streamer.set_entry_threshold(2)\nstreamer.set_message_format_string(\n'{stuff:s} -> {correct!s} [{random_number:d}]')\nstreamer.add_data_frame(self.frame)\nlines = streamer.lines\n- files = streamer.files\ncolumns = streamer.columns\nself._run_all_tests(columns, lines)\n- self.assertEqual(len(files), 3)\n+ self.assertEqual(len(lines), 5)\ndef test_adding_dict(self):\n\"\"\"Test adding a dict to the importer.\"\"\"\n@@ -183,12 +184,7 @@ class TimesketchImporterTest(unittest.TestCase):\nself.assertSetEqual(column_set, correct_set)\n- message_index = columns.index('message')\n- messages = []\n- for line in lines:\n- message = line.split(',')[message_index]\n- messages.append(message)\n-\n+ messages = [x.get('message', 'N/A') for x in lines]\nmessage_correct = set([\n'fra sjalfstaedi til sjalfstaedis -> True [52]',\n'from bar to foobar -> False [13245]',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -261,8 +261,8 @@ class Story(resource.BaseResource):\nStory name as a string.\n\"\"\"\nif not self._title:\n- story = self.lazyload_data()\n- objects = story.get('objects')\n+ story_data = self.lazyload_data()\n+ objects = story_data.get('objects')\nif objects:\nself._title = objects[0].get('title', 'No Title')\nreturn self._title\n@@ -284,6 +284,7 @@ class Story(resource.BaseResource):\ndef __len__(self):\n\"\"\"Returns the number of blocks stored in the story.\"\"\"\n+ _ = self.blocks\nreturn len(self._blocks)\ndef _add_block(self, block, index):\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story_test.py", "new_path": "api_client/python/timesketch_api_client/story_test.py", "diff": "@@ -37,5 +37,23 @@ class StoryTest(unittest.TestCase):\nstory = self.sketch.list_stories()[0]\nself.assertIsInstance(story, story_lib.Story)\nself.assertEqual(story.id, 1)\n- self.assertEqual(story.title, 'my first test story')\n- self.assertEqual(len(story), 2)\n+ self.assertEqual(story.title, 'My First Story')\n+ self.assertEqual(len(story), 3)\n+ blocks = list(story.blocks)\n+ text_count = 0\n+ view_count = 0\n+ for block in blocks:\n+ if block.TYPE == 'text':\n+ text_count += 1\n+ elif block.TYPE == 'view':\n+ view_count += 1\n+\n+ self.assertEqual(text_count, 2)\n+ self.assertEqual(view_count, 1)\n+\n+ self.assertEqual(blocks[0].text, '# My Heading\\nWith Some Text.')\n+\n+ blocks[0].move_down()\n+ blocks = list(story.blocks)\n+ self.assertEqual(len(blocks), 3)\n+ self.assertEqual(blocks[1].text, '# My Heading\\nWith Some Text.')\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/test_lib.py", "new_path": "api_client/python/timesketch_api_client/test_lib.py", "diff": "\"\"\"Tests for the Timesketch API client\"\"\"\nfrom __future__ import unicode_literals\n+import json\n+\ndef mock_session():\n\"\"\"Mock HTTP requests session.\"\"\"\n@@ -124,6 +126,49 @@ def mock_response(*args, **kwargs):\n'objects': []\n}\n+ story_list_data = {\n+ 'meta': {'es_time': 23},\n+ 'objects': [[{'id': 1}]]\n+ }\n+\n+ story_data = {\n+ 'meta': {\n+ 'es_time': 1,\n+ },\n+ 'objects': [{\n+ 'title': 'My First Story',\n+ 'content': json.dumps([\n+ {\n+ 'componentName': '',\n+ 'componentProps': {},\n+ 'content': '# My Heading\\nWith Some Text.',\n+ 'edit': False,\n+ 'showPanel': False,\n+ 'isActive': False\n+ },\n+ {\n+ 'componentName': 'TsViewEventList',\n+ 'componentProps': {\n+ 'view': {\n+ 'id': 1,\n+ 'name': 'Smoking Gun'}},\n+ 'content': '',\n+ 'edit': False,\n+ 'showPanel': False,\n+ 'isActive': False\n+ },\n+ {\n+ 'componentName': '',\n+ 'componentProps': {},\n+ 'content': '... and that was the true crime.',\n+ 'edit': False,\n+ 'showPanel': False,\n+ 'isActive': False\n+ }\n+ ])\n+ }]\n+ }\n+\n# Register API endpoints to the correct mock response data.\nurl_router = {\n'http://127.0.0.1':\n@@ -136,8 +181,13 @@ def mock_response(*args, **kwargs):\nMockResponse(json_data=timeline_data),\n'http://127.0.0.1/api/v1/sketches/1/explore/':\nMockResponse(json_data=timeline_data),\n+ 'http://127.0.0.1/api/v1/sketches/1/stories/':\n+ MockResponse(json_data=story_list_data),\n+ 'http://127.0.0.1/api/v1/sketches/1/stories/1/':\n+ MockResponse(json_data=story_data),\n}\nif kwargs.get('empty', False):\nreturn MockResponse(text_data=empty_data)\n+\nreturn url_router.get(args[0], MockResponse(None, 404))\n" }, { "change_type": "MODIFY", "old_path": "run_tests.py", "new_path": "run_tests.py", "diff": "@@ -13,11 +13,12 @@ def run_python_tests(coverage=False):\nsubprocess.check_call(\n'nosetests --with-coverage'\n+ ' --cover-package=timesketch_api_client,timesketch'\n- + ' api_client/python/timesketch_api_client/ timesketch/',\n+ + ' api_client/python/ timesketch/',\nshell=True,\n)\nelse:\n- subprocess.check_call(['nosetests'])\n+ subprocess.check_call(\n+ ['nosetests', '-x', 'timesketch/', 'api_client/python/'])\nfinally:\nsubprocess.check_call(['rm', '-f', '.coverage'])\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing running tests to include API client tests, fixing tests.
263,133
12.03.2020 13:07:14
0
9b060ea56c995de24ae3647934603e1d94c20c83
Adding a get_story function
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -211,14 +211,38 @@ class Sketch(resource.BaseResource):\nreturn aggregation_obj\nreturn None\n+ def get_story(self, story_id=None, story_title=None):\n+ \"\"\"Returns a story object that is stored in the sketch.\n+\n+ Args:\n+ story_id: an integer indicating the ID of the story to\n+ be fetched. Defaults to None.\n+ story_title: a string with the title of the story. Optional\n+ and defaults to None.\n+\n+ Returns:\n+ A story object (instance of Story) if one is found. Returns\n+ a None if neiter story_id or story_title is defined or if\n+ the view does not exist.\n+ \"\"\"\n+ if story_id is None and story_title is None:\n+ return None\n+\n+ for story in self.list_stories():\n+ if story_id and story_id == story.id:\n+ return story\n+ if story_title and story_title.lower() == story.title.lower():\n+ return story\n+ return None\n+\ndef get_view(self, view_id=None, view_name=None):\n\"\"\"Returns a view object that is stored in the sketch.\nArgs:\n- view_name: a string with the name of the view. Optional\n- and defaults to None.\nview_id: an integer indicating the ID of the view to\nbe fetched. Defaults to None.\n+ view_name: a string with the name of the view. Optional\n+ and defaults to None.\nReturns:\nA view object (instance of View) if one is found. Returns\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a get_story function
263,133
12.03.2020 13:11:54
0
7b8d2121e76be1f03ae392c5418344cdae3ae2e8
Updating index in blocks
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -74,11 +74,15 @@ class BaseBlock(object):\ndef move_down(self):\n\"\"\"Moves a block down one location in the index.\"\"\"\n- self._story.move_to(self, self.index+1)\n+ new_index = self.index + 1\n+ self._story.move_to(self, new_index)\n+ self.index = new_index\ndef move_up(self):\n\"\"\"Moves a block up one location in the index.\"\"\"\n- self._story.move_to(self, self.index-1)\n+ new_index = self.index - 1\n+ self._story.move_to(self, new_index)\n+ self.index = new_index\ndef to_dict(self):\n\"\"\"Returns a dict with the block data.\n" } ]
Python
Apache License 2.0
google/timesketch
Updating index in blocks
263,133
12.03.2020 13:27:26
0
aa02c99d7f70316c6aee6c735473ccae0be4a12d
Adding the ability to update text/views ni blocks
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -43,6 +43,7 @@ class BaseBlock(object):\ndef data(self, data):\n\"\"\"Feeds data to the block.\"\"\"\nself._data = data\n+ self._story.commit()\n@property\ndef json(self):\n@@ -116,6 +117,11 @@ class ViewBlock(BaseBlock):\n\"\"\"Returns the view.\"\"\"\nreturn self._data\n+ @view.setter\n+ def view(self, new_view):\n+ \"\"\"Sets a new view to the block.\"\"\"\n+ self.data = new_view\n+\n@property\ndef view_id(self):\n\"\"\"Returns the view ID.\"\"\"\n@@ -180,6 +186,11 @@ class TextBlock(BaseBlock):\nreturn ''\nreturn self._data\n+ @text.setter\n+ def text(self, new_text):\n+ \"\"\"Sets a new text to the block.\"\"\"\n+ self.data = new_text\n+\ndef from_dict(self, data_dict):\n\"\"\"Feed a block from a block dict.\"\"\"\ntext = data_dict.get('content', '')\n@@ -294,23 +305,8 @@ class Story(resource.BaseResource):\ndef _add_block(self, block, index):\n\"\"\"Adds a block to the story's content.\"\"\"\nself._blocks.insert(index, block)\n- self._commit()\n- self.refresh()\n-\n- def _commit(self):\n- \"\"\"Commit the story to the server.\"\"\"\n- content_list = [x.to_dict() for x in self._blocks]\n- content = json.dumps(content_list)\n-\n- data = {\n- 'title': self.title,\n- 'content': content,\n- }\n- response = self.api.session.post(\n- '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri),\n- json=data)\n-\n- return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+ self.commit()\n+ self.reset()\ndef add_text(self, text, index=-1):\n\"\"\"Adds a text block to the story.\n@@ -360,6 +356,21 @@ class Story(resource.BaseResource):\nreturn self._add_block(view_block, index)\n+ def commit(self):\n+ \"\"\"Commit the story to the server.\"\"\"\n+ content_list = [x.to_dict() for x in self._blocks]\n+ content = json.dumps(content_list)\n+\n+ data = {\n+ 'title': self.title,\n+ 'content': content,\n+ }\n+ response = self.api.session.post(\n+ '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri),\n+ json=data)\n+\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\ndef delete(self):\n\"\"\"Delete the story from the sketch.\n@@ -380,15 +391,15 @@ class Story(resource.BaseResource):\nif old_block.data != block.data:\nraise ValueError('Block is not correctly set.')\nself._blocks.insert(new_index, block)\n- self._commit()\n+ self.commit()\ndef remove_block(self, index):\n\"\"\"Removes a block from the story.\"\"\"\n_ = self._blocks.pop(index)\n- self._commit()\n- self.refresh()\n+ self.commit()\n+ self.reset()\n- def refresh(self):\n+ def reset(self):\n\"\"\"Refresh story content.\"\"\"\nself._title = ''\nself._blocks = []\n@@ -397,7 +408,7 @@ class Story(resource.BaseResource):\ndef to_string(self):\n\"\"\"Returns a string with the content of all the story.\"\"\"\n- self.refresh()\n+ self.reset()\nstring_list = []\nfor block in self.blocks:\nif block.TYPE == 'text':\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to update text/views ni blocks
263,133
12.03.2020 13:52:30
0
46a0fadb78fa7ca78cb8140608c526a01e8229f6
adding a line space adding a line space, should be double
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/win_crash.py", "new_path": "timesketch/lib/analyzers/win_crash.py", "diff": "@@ -6,6 +6,7 @@ import re\nfrom timesketch.lib.analyzers import interface\nfrom timesketch.lib.analyzers import manager\n+\nclass WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\n\"\"\"Sketch analyzer for Windows application crashes.\"\"\"\n@@ -191,4 +192,5 @@ class WinCrashSketchPlugin(interface.BaseSketchAnalyzer):\n's' if len(filenames) > 1 else '',\n', '.join(filenames))\n+\nmanager.AnalysisManager.register_analyzer(WinCrashSketchPlugin)\n" } ]
Python
Apache License 2.0
google/timesketch
adding a line space adding a line space, should be double
263,133
12.03.2020 16:12:45
0
bf604f41fb67ca6389d414dbb2749ae5ac1cefc4
Adding aggregation objects into stories
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/aggregation.py", "new_path": "api_client/python/timesketch_api_client/aggregation.py", "diff": "@@ -35,8 +35,7 @@ class Aggregation(resource.BaseResource):\nview: a view ID if the aggregation is tied to a specific view.\n\"\"\"\n- def __init__(\n- self, sketch, api):\n+ def __init__(self, sketch, api):\nself._sketch = sketch\nself._aggregator_data = {}\nself._parameters = {}\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -16,6 +16,9 @@ from __future__ import unicode_literals\nimport json\n+import pandas as pd\n+\n+from . import aggregation\nfrom . import definitions\nfrom . import resource\nfrom . import view\n@@ -218,6 +221,108 @@ class TextBlock(BaseBlock):\nreturn text_block\n+class AggregationBlock(BaseBlock):\n+ \"\"\"Block object for aggregation.\"\"\"\n+\n+ TYPE = 'aggregation'\n+\n+ def __init__(self, story, index):\n+ super(AggregationBlock, self).__init__(story, index)\n+ self._agg_id = 0\n+ self._agg_name = ''\n+ self._agg_type = ''\n+\n+ @property\n+ def aggregation(self):\n+ \"\"\"Returns the aggregation object.\"\"\"\n+ if self._data:\n+ return self._data\n+\n+ @aggregation.setter\n+ def aggregation(self, agg_obj):\n+ \"\"\"Set the aggregation object.\"\"\"\n+ self._data = agg_obj\n+\n+ @property\n+ def agg_name(self):\n+ \"\"\"Returns the aggregation name.\"\"\"\n+ return self._agg_name\n+\n+ @property\n+ def agg_id(self):\n+ \"\"\"Returns the aggregation ID.\"\"\"\n+ return self._agg_id\n+\n+ @property\n+ def agg_type(self):\n+ \"\"\"Returns the aggregation type.\"\"\"\n+ return self._agg_type\n+\n+ @agg_type.setter\n+ def agg_type(self, new_type):\n+ \"\"\"Sets the aggregation type.\"\"\"\n+ self._agg_type = new_type\n+\n+ @property\n+ def table(self):\n+ \"\"\"Returns a table view, as a pandas DataFrame.\"\"\"\n+ if not self._data:\n+ return pd.DataFrame()\n+ return self._data.table\n+\n+ @property\n+ def chart(self):\n+ \"\"\"Returns a chart back from the aggregation.\"\"\"\n+ if not self._data:\n+ return None\n+ return self._data.chart\n+\n+ def from_dict(self, data_dict):\n+ \"\"\"Feed a block from a block dict.\"\"\"\n+ component = data_dict.get('componentName', 'N/A')\n+ if component != 'TsAggregationEventList':\n+ raise TypeError('Not an aggregation block.')\n+\n+ props = data_dict.get('componentProps', {})\n+ agg_dict = props.get('aggregation')\n+ if not agg_dict:\n+ raise TypeError('View not defined')\n+\n+ self._agg_id = agg_dict.get('id', 0)\n+ self._agg_name = agg_dict.get('name', '')\n+ self._agg_type = agg_dict.get('type', 'chart')\n+\n+ def to_dict(self):\n+ \"\"\"Returns a dict with the block data.\n+\n+ Raises:\n+ ValueError: if the block has not been fed with data.\n+ TypeError: if the data that was fed is of the wrong type.\n+\n+ Returns:\n+ A dict with the block data.\n+ \"\"\"\n+ if not self._data:\n+ raise ValueError('No data has been fed to the block.')\n+\n+ aggregation_obj = self._data\n+ if not hasattr(aggregation_obj, 'id'):\n+ raise TypeError('Aggregation object is not correctly formed.')\n+\n+ if not hasattr(aggregation_obj, 'name'):\n+ raise TypeError('Aggregation object is not correctly formed.')\n+\n+ aggregation_block = self._get_base()\n+ aggregation_block['componentName'] = 'TsAggregationEventList'\n+ aggregation_block['componentProps']['aggregation'] = {\n+ 'id': aggregation_obj.id,\n+ 'name': aggregation_obj.name,\n+ 'type': self._agg_type,\n+ }\n+\n+ return aggregation_block\n+\n+\nclass Story(resource.BaseResource):\n\"\"\"Story object.\n@@ -254,18 +359,23 @@ class Story(resource.BaseResource):\ncontent = objects[0].get('content', [])\nindex = 0\nfor content_block in json.loads(content):\n+ name = content_block.get('componentName', '')\nif content_block.get('content'):\nblock = TextBlock(self, index)\nblock.from_dict(content_block)\n- else:\n+ elif name == 'TsViewEventList':\nblock = ViewBlock(self, index)\nblock.from_dict(content_block)\nview_obj = view.View(\nblock.view_id, block.view_name, self._sketch.id,\nself._api)\nblock.feed(view_obj)\n- self._blocks.append(block)\n- index += 1\n+ elif name == 'TsAggregationEventList':\n+ block = AggregationBlock(self, index)\n+ block.from_dict(content_block)\n+ agg_obj = aggregation.Aggregation(self._sketch, self._api)\n+ agg_obj.from_store(block.agg_id)\n+ block.feed(agg_obj)\nreturn self._blocks\n@property\n@@ -417,4 +527,8 @@ class Story(resource.BaseResource):\ndata_frame = self._sketch.explore(\nview=block.view, as_pandas=True)\nstring_list.append(data_frame.to_string(index=False))\n+ elif block.TYPE == 'aggregation':\n+ data_frame = self.get_aggregation(block.agg_id)\n+ # TODO: Support charts.\n+ string_list.append(data_frame.to_string(index=False))\nreturn '\\n\\n'.join(string_list)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding aggregation objects into stories
263,133
12.03.2020 17:19:40
0
d5fe56bf0aa1f64eb0cf0a06b8e4cc9cc23c274d
Adding aggregation support.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -376,6 +376,7 @@ class Story(resource.BaseResource):\nagg_obj = aggregation.Aggregation(self._sketch, self._api)\nagg_obj.from_store(block.agg_id)\nblock.feed(agg_obj)\n+ self._blocks.append(block)\nreturn self._blocks\n@property\n@@ -418,6 +419,35 @@ class Story(resource.BaseResource):\nself.commit()\nself.reset()\n+ def add_aggregation(self, agg_obj, index=-1):\n+ \"\"\"Adds an aggregation object to the story.\n+\n+ Args:\n+ agg_obj: an aggregation object (instance of aggregation.Aggregation).\n+ index: an integer, if supplied determines where the new\n+ block will be added. If not supplied it will be\n+ appended at the end.\n+\n+ Returns:\n+ Boolean that indicates whether block was successfully added.\n+\n+ Raises:\n+ TypeError: if the view object is not of the correct type.\n+ \"\"\"\n+ if not hasattr(agg_obj, 'id'):\n+ raise TypeError('Aggregation object is not correctly formed.')\n+\n+ if not hasattr(agg_obj, 'name'):\n+ raise TypeError('Aggregation object is not correctly formed.')\n+\n+ if index == -1:\n+ index = len(self._blocks)\n+\n+ agg_block = AggregationBlock(self, index)\n+ agg_block.feed(agg_obj)\n+\n+ return self._add_block(agg_block, index)\n+\ndef add_text(self, text, index=-1):\n\"\"\"Adds a text block to the story.\n@@ -528,7 +558,8 @@ class Story(resource.BaseResource):\nview=block.view, as_pandas=True)\nstring_list.append(data_frame.to_string(index=False))\nelif block.TYPE == 'aggregation':\n- data_frame = self.get_aggregation(block.agg_id)\n+ agg_obj = self._sketch.get_aggregation(block.agg_id)\n# TODO: Support charts.\n+ data_frame = agg_obj.table\nstring_list.append(data_frame.to_string(index=False))\nreturn '\\n\\n'.join(string_list)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1905,6 +1905,14 @@ class StoryResource(ResourceMixin, Resource):\nsketch = Sketch.query.get_with_acl(sketch_id)\nstory = Story.query.get(story_id)\n+ if not story:\n+ msg = 'No Story found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\n+ if not sketch:\n+ msg = 'No sketch found with this ID.'\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, msg)\n+\n# Check that this story belongs to the sketch\nif story.sketch_id != sketch.id:\nabort(\n" } ]
Python
Apache License 2.0
google/timesketch
Adding aggregation support.
263,133
13.03.2020 07:47:14
0
80017183c23d67ff8de7f143cf34db0688096c89
Adding the ability for analyzers to add aggregation into stories.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -434,6 +434,22 @@ class Story(object):\nblock['content'] = text\nself._commit(block)\n+ def add_aggregation(self, aggregation, agg_type):\n+ \"\"\"Add a saved aggregation to the Story.\n+\n+ Args:\n+ aggregation (Aggregation): Saved aggregation to add to the story.\n+ agg_type (str): string indicating the type of aggregation, can be:\n+ \"table\" or the name of the chart to be used, eg \"barcharct\",\n+ \"hbarchart\".\n+ \"\"\"\n+ block = self._create_new_block()\n+ block['componentName'] = 'TsAggregationEventList'\n+ block['componentProps']['aggregation'] = {\n+ 'id': aggregation.id, 'name': aggregation.name,\n+ 'type': agg_type}\n+ self._commit(block)\n+\ndef add_view(self, view):\n\"\"\"Add a saved view to the Story.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability for analyzers to add aggregation into stories.
263,133
13.03.2020 07:57:41
0
36fd840ad0ed8717fddbed99313692fe70b7a280
Adding option to define aggregation type in api
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -424,11 +424,14 @@ class Story(resource.BaseResource):\nself.commit()\nself.reset()\n- def add_aggregation(self, agg_obj, index=-1):\n+ def add_aggregation(self, agg_obj, agg_type='table', index=-1):\n\"\"\"Adds an aggregation object to the story.\nArgs:\nagg_obj: an aggregation object (instance of aggregation.Aggregation)\n+ agg_type (str): string indicating the type of aggregation, can be:\n+ \"table\" or the name of the chart to be used, eg \"barcharct\",\n+ \"hbarchart\". Defaults to \"table\".\nindex: an integer, if supplied determines where the new\nblock will be added. If not supplied it will be\nappended at the end.\n@@ -450,6 +453,7 @@ class Story(resource.BaseResource):\nagg_block = AggregationBlock(self, index)\nagg_block.feed(agg_obj)\n+ agg_block.agg_type = agg_type\nreturn self._add_block(agg_block, index)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding option to define aggregation type in api
263,133
13.03.2020 09:22:53
0
a6614bb7e09b6b07a0e02fc2c641f43d0ffd6d64
Adding new parts to the fake analyzer interface.
[ { "change_type": "MODIFY", "old_path": "test_tools/timesketch/lib/analyzers/interface.py", "new_path": "test_tools/timesketch/lib/analyzers/interface.py", "diff": "@@ -31,6 +31,7 @@ EVENT_CHANGE = collections.namedtuple('event_change', 'type, source, what')\nSKETCH_CHANGE = collections.namedtuple('sketch_change', 'type, source, what')\nVIEW_OBJECT = collections.namedtuple('view', 'id, name')\n+AGG_OBJECT = collections.namedtuple('aggregation', 'id', 'name')\nclass AnalyzerContext(object):\n@@ -107,6 +108,27 @@ class AnalyzerContext(object):\nif event.event_id not in self.event_cache:\nself.event_cache[event.event_id] = event\n+ def add_story(self, title):\n+ \"\"\"Add a story to the Sketch.\n+\n+ Args:\n+ title: The name of the view.\n+\n+ Raises:\n+ ValueError: If both query_string an query_dsl are missing.\n+\n+ Returns:\n+ An instance of a Story object.\n+ \"\"\"\n+ params = {\n+ 'title': title,\n+ }\n+ change = SKETCH_CHANGE('ADD', 'story', params)\n+ self.updates.append(change)\n+\n+ story = Story(self, title=title)\n+ return story\n+\ndef add_query(\nself, query_string=None, query_dsl=None, indices=None, fields=None):\n\"\"\"Add a query string or DSL to the context.\n@@ -629,3 +651,56 @@ class BaseSketchAnalyzer(BaseIndexAnalyzer):\ndef run(self):\n\"\"\"Entry point for the analyzer.\"\"\"\nraise NotImplementedError\n+\n+\n+class Story(object):\n+ \"\"\"Mocked story object.\"\"\"\n+\n+ def __init__(self, analyzer, title):\n+ \"\"\"Initialize the story.\"\"\"\n+ self.id = 1\n+ self.title = title\n+ self._analyzer = analyzer\n+\n+ def add_aggregation(self, aggregation, agg_type):\n+ \"\"\"Add a saved aggregation to the Story.\n+\n+ Args:\n+ aggregation (Aggregation): Saved aggregation to add to the story.\n+ agg_type (str): string indicating the type of aggregation, can be:\n+ \"table\" or the name of the chart to be used, eg \"barcharct\",\n+ \"hbarchart\".\n+ \"\"\"\n+ params = {\n+ 'agg_id': aggregation.id,\n+ 'agg_name': aggregation.name,\n+ 'agg_type': agg_type,\n+ }\n+ change = SKETCH_CHANGE('STORY_ADD', 'aggregation', params)\n+ self._analyzer.updates.append(change)\n+\n+ def add_text(self, text):\n+ \"\"\"Add a text block to the Story.\n+\n+ Args:\n+ text (str): text (markdown is supported) to add to the story.\n+ \"\"\"\n+ params = {\n+ 'text': text,\n+ }\n+ change = SKETCH_CHANGE('STORY_ADD', 'text', params)\n+ self._analyzer.updates.append(change)\n+\n+ def add_view(self, view):\n+ \"\"\"Add a saved view to the story.\n+\n+ Args:\n+ view (View): Saved view to add to the story.\n+ \"\"\"\n+ params = {\n+ 'view_id': view.id,\n+ 'view_name': view.name\n+ }\n+ change = SKETCH_CHANGE('STORY_ADD', 'view', params)\n+ self._analyzer.updates.append(change)\n+\n" } ]
Python
Apache License 2.0
google/timesketch
Adding new parts to the fake analyzer interface.
263,133
13.03.2020 09:38:39
0
4d9a9fd6f906a93c9f9420650873a1de84cba25a
Fixing the fake analyzer.
[ { "change_type": "MODIFY", "old_path": "test_tools/timesketch/lib/analyzers/interface.py", "new_path": "test_tools/timesketch/lib/analyzers/interface.py", "diff": "@@ -31,7 +31,7 @@ EVENT_CHANGE = collections.namedtuple('event_change', 'type, source, what')\nSKETCH_CHANGE = collections.namedtuple('sketch_change', 'type, source, what')\nVIEW_OBJECT = collections.namedtuple('view', 'id, name')\n-AGG_OBJECT = collections.namedtuple('aggregation', 'id', 'name')\n+AGG_OBJECT = collections.namedtuple('aggregation', 'id, name')\nclass AnalyzerContext(object):\n@@ -108,27 +108,6 @@ class AnalyzerContext(object):\nif event.event_id not in self.event_cache:\nself.event_cache[event.event_id] = event\n- def add_story(self, title):\n- \"\"\"Add a story to the Sketch.\n-\n- Args:\n- title: The name of the view.\n-\n- Raises:\n- ValueError: If both query_string an query_dsl are missing.\n-\n- Returns:\n- An instance of a Story object.\n- \"\"\"\n- params = {\n- 'title': title,\n- }\n- change = SKETCH_CHANGE('ADD', 'story', params)\n- self.updates.append(change)\n-\n- story = Story(self, title=title)\n- return story\n-\ndef add_query(\nself, query_string=None, query_dsl=None, indices=None, fields=None):\n\"\"\"Add a query string or DSL to the context.\n@@ -395,6 +374,9 @@ class Sketch(object):\nchange = SKETCH_CHANGE('ADD', 'aggregation', params)\nself.updates.append(change)\n+ agg_obj = AGG_OBJECT(1, name)\n+ return agg_obj\n+\ndef add_view(self, view_name, analyzer_name, query_string=None,\nquery_dsl=None, query_filter=None):\n\"\"\"Add saved view to the Sketch.\n@@ -430,6 +412,27 @@ class Sketch(object):\nview = VIEW_OBJECT(1, name)\nreturn view\n+ def add_story(self, title):\n+ \"\"\"Add a story to the Sketch.\n+\n+ Args:\n+ title: The name of the view.\n+\n+ Raises:\n+ ValueError: If both query_string an query_dsl are missing.\n+\n+ Returns:\n+ An instance of a Story object.\n+ \"\"\"\n+ params = {\n+ 'title': title,\n+ }\n+ change = SKETCH_CHANGE('ADD', 'story', params)\n+ self.updates.append(change)\n+\n+ story = Story(self, title=title)\n+ return story\n+\ndef get_all_indices(self):\n\"\"\"List all indices in the Sketch.\nReturns:\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing the fake analyzer.
263,133
17.03.2020 09:11:02
0
63b15879118ce77383fb4829baa2679ff5dfc618
Adding the ability to add users or groups to the sketch ACL.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200312',\n+ version='20200317',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -169,6 +169,40 @@ class Sketch(resource.BaseResource):\nsketch=self,\napi=self.api)\n+ def add_to_acl(self, user_list=None, group_list=None):\n+ \"\"\"Add users or groups to the sketch ACL.\n+\n+ Args:\n+ user_list: optional list of users to add to the ACL\n+ of the sketch. Each user is a string.\n+ group_list: optional list of groups to add to the ACL\n+ of the sketch. Each user is a string.\n+\n+ Returns:\n+ A boolean indicating whether the ACL change was successful.\n+ \"\"\"\n+ if not user_list and not group_list:\n+ return True\n+\n+ resource_url = '{0:s}/sketches/{1:d}/collaborator/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {}\n+ if group_list:\n+ group_list_corrected = [str(x).strip() for x in group_list]\n+ data['groups'] = group_list_corrected\n+\n+ if user_list:\n+ user_list_corrected = [str(x).strip() for x in user_list]\n+ data['users'] = user_list_corrected\n+\n+ if not data:\n+ return True\n+\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\ndef list_aggregations(self):\n\"\"\"List all saved aggregations for this sketch.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to add users or groups to the sketch ACL.
263,133
17.03.2020 09:15:38
0
d326a77505cfe76dfb03f2ef0708ff0b0ab97304
Adding the ability to remove ACLs from sketch.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -169,7 +169,7 @@ class Sketch(resource.BaseResource):\nsketch=self,\napi=self.api)\n- def add_to_acl(self, user_list=None, group_list=None):\n+ def add_to_acl(self, user_list=None, group_list=None, make_public=False):\n\"\"\"Add users or groups to the sketch ACL.\nArgs:\n@@ -177,6 +177,8 @@ class Sketch(resource.BaseResource):\nof the sketch. Each user is a string.\ngroup_list: optional list of groups to add to the ACL\nof the sketch. Each user is a string.\n+ make_public: Optional boolean indicating the sketch should be\n+ marked as public.\nReturns:\nA boolean indicating whether the ACL change was successful.\n@@ -196,6 +198,9 @@ class Sketch(resource.BaseResource):\nuser_list_corrected = [str(x).strip() for x in user_list]\ndata['users'] = user_list_corrected\n+ if make_public:\n+ data['public'] = 'true'\n+\nif not data:\nreturn True\n@@ -605,6 +610,45 @@ class Sketch(resource.BaseResource):\nreturn '[{0:d}] {1:s} {2:s}'.format(\nresponse.status_code, response.reason, response.text)\n+ def remove_acl(self, user_list=None, group_list=None, remove_public=False):\n+ \"\"\"Remove users or groups to the sketch ACL.\n+\n+ Args:\n+ user_list: optional list of users to remove from the ACL\n+ of the sketch. Each user is a string.\n+ group_list: optional list of groups to remove from the ACL\n+ of the sketch. Each user is a string.\n+ remove_public: Optional boolean indicating the sketch should be\n+ no longer marked as public.\n+\n+ Returns:\n+ A boolean indicating whether the ACL change was successful.\n+ \"\"\"\n+ if not user_list and not group_list:\n+ return True\n+\n+ resource_url = '{0:s}/sketches/{1:d}/collaborator/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {}\n+ if group_list:\n+ group_list_corrected = [str(x).strip() for x in group_list]\n+ data['remove_groups'] = group_list_corrected\n+\n+ if user_list:\n+ user_list_corrected = [str(x).strip() for x in user_list]\n+ data['remove_users'] = user_list_corrected\n+\n+ if remove_public:\n+ data['public'] = 'false'\n+\n+ if not data:\n+ return True\n+\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ return response.status_code in definitions.HTTP_STATUS_CODE_20X\n+\ndef aggregate(self, aggregate_dsl):\n\"\"\"Run an aggregation request on the sketch.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to remove ACLs from sketch.
263,133
19.03.2020 08:18:50
0
eef14312466df9359af3aaa6553471ba9bbe1fd1
Adding the ability to export stories.
[ { "change_type": "MODIFY", "old_path": "requirements.txt", "new_path": "requirements.txt", "diff": "@@ -30,3 +30,4 @@ SQLAlchemy==1.3.12\nWerkzeug==0.16.0\nWTForms==2.2.1\nxlrd==1.2.0\n+tabulate=0.8.6\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -82,6 +82,8 @@ from timesketch.lib.forms import StoryForm\nfrom timesketch.lib.forms import GraphExploreForm\nfrom timesketch.lib.forms import SearchIndexForm\nfrom timesketch.lib.forms import TimelineForm\n+from timesketch.lib.stories import api_fetcher as story_api_fetcher\n+from timesketch.lib.stories import manager as story_export_manager\nfrom timesketch.lib.utils import get_validated_indices\nfrom timesketch.lib.experimental.utils import GRAPH_VIEWS\nfrom timesketch.lib.experimental.utils import get_graph_views\n@@ -1891,6 +1893,21 @@ class StoryListResource(ResourceMixin, Resource):\nclass StoryResource(ResourceMixin, Resource):\n\"\"\"Resource to get a story.\"\"\"\n+ def _export_story(self, story, sketch_id, export_format='markdown'):\n+ \"\"\"Returns a story in a format as requested in export_format.\"\"\"\n+ exporter_class = story_export_manager.StoryExportManager.get_exporter(\n+ export_format)\n+ if not exporter_class:\n+ return b''\n+\n+ with exporter_class() as exporter:\n+ data_fetcher = story_api_fetcher.ApiDataFetcher()\n+ exporter.set_data_fetcher(data_fetcher)\n+ exporter.set_sketch_id(sketch_id)\n+\n+ exporter.from_string(story.content)\n+ return exporter.export_story()\n+\n@login_required\ndef get(self, sketch_id, story_id):\n\"\"\"Handles GET request to the resource.\n@@ -1961,6 +1978,11 @@ class StoryResource(ResourceMixin, Resource):\nif not form:\nform = request.data\n+ if form and form.get('export_format'):\n+ export_format = form.get('export_format')\n+ return self._export_story(\n+ story=story, sketch_id=sketch_id, export_format=export_format)\n+\nstory.title = form.get('title', '')\nstory.content = form.get('content', '[]')\ndb_session.add(story)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/__init__.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Story exporter modules.\"\"\"\n+\n+# Register all analyzers here by importing them.\n+from timesketch.lib.stories import markdown\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/api_fetcher.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This file contains the interface for a story exporter.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+from flask import current_app\n+import pandas as pd\n+\n+from timesketch.lib.stories import interface\n+\n+from timesketch.lib.aggregators import manager as aggregator_manager\n+from timesketch.lib.datastores.elastic import ElasticsearchDataStore\n+from timesketch.models.sketch import Aggregation\n+from timesketch.models.sketch import View\n+\n+\n+class ApiDataFetcher(interface.DataFetcher):\n+ \"\"\"Data Fetcher for an API story exporter.\"\"\"\n+\n+ def __init__(self):\n+ \"\"\"Initialize the data fetcher.\"\"\"\n+ super(ApiDataFetcher, self).__init__()\n+ self._datastore = ElasticsearchDataStore(\n+ host=current_app.config['ELASTIC_HOST'],\n+ port=current_app.config['ELASTIC_PORT'])\n+\n+ def get_aggregation(self, agg_dict):\n+ \"\"\"Returns a data frame from an aggregation dict.\n+\n+ Args:\n+ agg_dict (dict): a dictionary containing information\n+ about the stored aggregation.\n+\n+ Returns:\n+ A pandas DataFrame with the results from a saved aggregation.\n+ \"\"\"\n+ aggregation_id = agg_dict.get('id')\n+ if not aggregation_id:\n+ return pd.DataFrame()\n+\n+ aggregation = Aggregation.query.get(aggregation_id)\n+ if not aggregation:\n+ return pd.DataFrame()\n+\n+ # Run the aggregator...\n+ try:\n+ agg_class = aggregator_manager.AggregatorManager.get_aggregator(\n+ aggregation.name)\n+ except KeyError:\n+ return pd.DataFrame()\n+\n+ if not agg_class:\n+ return pd.DataFrame()\n+ aggregator = agg_class(sketch_id=self._sketch_id)\n+ result_obj = aggregator.run(aggregation.parameters)\n+ # TODO: Support charts.\n+ return result_obj.to_pandas()\n+\n+ def get_view(self, view_dict):\n+ \"\"\"Returns a data frame from a view dict.\n+\n+ Args:\n+ view_dict (dict): a dictionary containing information\n+ about the stored view.\n+\n+ Returns:\n+ A pandas DataFrame with the results from a view aggregation.\n+ \"\"\"\n+ view_id = view_dict.get('id')\n+ if not view_id:\n+ return pd.DataFrame()\n+\n+ view = View.query.get(view_id)\n+ if not view:\n+ return pd.DataFrame()\n+\n+ if not view.query_string and not view.query_dsl:\n+ return pd.DataFrame()\n+\n+ query_filter = view.query_filter\n+ if not query_filter:\n+ query_filter = {'indices': '_all', 'size': 100}\n+\n+ results = self._datastore.search_stream(\n+ sketch_id=self._sketch_id,\n+ query_string=view.query_string,\n+ query_filter=query_filter,\n+ query_dsl=view.query_dsl,\n+ indices='_all',\n+ )\n+ result_list = [x.get('_source') for x in results]\n+ return pd.DataFrame(result_list)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/interface.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This file contains the interface for a story exporter.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+import json\n+\n+\n+class StoryExporter(object):\n+ \"\"\"Interface for a story exporter.\"\"\"\n+\n+ # String representing the output format of the story.\n+ EXPORT_FORMAT = ''\n+\n+ def __init__(self):\n+ \"\"\"Initialize the exporter.\"\"\"\n+ self._data_lines = []\n+ self._sketch_id = 0\n+ self._data_fetcher = None\n+\n+ @property\n+ def data(self):\n+ \"\"\"Returns the data.\"\"\"\n+ return self.export_story()\n+\n+ def export_story(self):\n+ \"\"\"Export the story in the format.\"\"\"\n+ raise NotImplementedError\n+\n+ def from_string(self, json_string):\n+ \"\"\"Feed the exporter with a JSON string.\"\"\"\n+ blocks = json.loads(json_string)\n+ if not isinstance(blocks, (list, tuple)):\n+ return\n+\n+ for block in blocks:\n+ self.from_dict(block)\n+\n+ def from_dict(self, block):\n+ \"\"\"Feed the exporter with a single block dict.\"\"\"\n+ component = block.get('componentName', 'N/A')\n+ properties = block.get('componentProps', {})\n+\n+ if not self._data_fetcher:\n+ return\n+\n+ if not component:\n+ self._data_lines.append(block.get('content', ''))\n+ elif component == 'TsViewEventList':\n+ self._data_lines.append(\n+ self._data_fetcher.get_view(properties.get('view')))\n+ elif component == 'TsAggregationEventList':\n+ self._data_lines.append(\n+ self._data_fetcher.get_aggregation(\n+ properties.get('aggregation')))\n+\n+ def reset(self):\n+ \"\"\"Reset the story.\"\"\"\n+ self._data_lines = []\n+\n+ def set_data_fetcher(self, data_fetcher):\n+ \"\"\"Set the data fetcher.\n+\n+ Args:\n+ data_fetcher (DataFetcher): set the data fetcher.\n+ \"\"\"\n+ self._data_fetcher = data_fetcher\n+\n+ def set_sketch_id(self, sketch_id):\n+ \"\"\"Set the sketch id.\"\"\"\n+ self._sketch_id = sketch_id\n+\n+ def __enter__(self):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self.reset()\n+ return self\n+\n+ # pylint: disable=unused-argument\n+ def __exit__(self, exception_type, exception_value, traceback):\n+ \"\"\"Make it possible to use \"with\" statement.\"\"\"\n+ self.reset()\n+\n+\n+class DataFetcher(object):\n+ \"\"\"A data fetcher interface.\"\"\"\n+\n+ def get_aggregation(self, agg_dict):\n+ \"\"\"Returns a data frame from an aggregation dict.\n+\n+ Args:\n+ agg_dict (dict): a dictionary containing information\n+ about the stored aggregation.\n+\n+ Returns:\n+ A pandas DataFrame with the results from a saved aggregation.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+ def get_view(self, view_dict):\n+ \"\"\"Returns a data frame from a view dict.\n+\n+ Args:\n+ view_dict (dict): a dictionary containing information\n+ about the stored view.\n+\n+ Returns:\n+ A pandas DataFrame with the results from a view aggregation.\n+ \"\"\"\n+ raise NotImplementedError\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/manager.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This file contains a class for managing story exporters.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+\n+class StoryExportManager(object):\n+ \"\"\"The story export manager.\"\"\"\n+\n+ _class_registry = {}\n+\n+ @classmethod\n+ def clear_registration(cls):\n+ \"\"\"Clears all analyzer registration.\"\"\"\n+ cls._class_registry = {}\n+\n+ @classmethod\n+ def get_exporters(cls, exporter_types=None):\n+ \"\"\"Retrieves the registered story exporters.\n+\n+ Args:\n+ exporter_types (list): List of exporter types.\n+\n+ Yields:\n+ tuple: containing:\n+ str: the uniquely identifying name of the story exporter.\n+ type: the exporter class.\n+ \"\"\"\n+ for exporter_type, exporter_class in cls._class_registry.items():\n+ if exporter_types and exporter_type not in exporter_types:\n+ continue\n+ yield exporter_type, exporter_class\n+\n+ @classmethod\n+ def get_exporter(cls, exporter_type):\n+ \"\"\"Retrieves a class object of a specific exporter.\n+\n+ Args:\n+ exporter_type (str): name of the exporter to retrieve.\n+\n+ Returns:\n+ StoryExporter class object.\n+ \"\"\"\n+ return cls._class_registry.get(exporter_type.lower())\n+\n+ @classmethod\n+ def register_exporter(cls, exporter_class):\n+ \"\"\"Registers an exporter class.\n+\n+ The exporter classes are identified by their lower export format.\n+\n+ Args:\n+ exporter_class (type): the exporter class to register.\n+\n+ Raises:\n+ KeyError: if class is already set for the corresponding name.\n+ \"\"\"\n+ exporter_type = exporter_class.EXPORT_FORMAT.lower()\n+ if exporter_type in cls._class_registry:\n+ raise KeyError('Class already set for name: {0:s}.'.format(\n+ exporter_class.EXPORT_FORMAT))\n+\n+ cls._class_registry[exporter_type] = exporter_class\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/manager_test.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Tests for story export manager.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+from timesketch.lib.testlib import BaseTest\n+from timesketch.lib.stories import manager\n+\n+\n+class MockStoryExporter(object):\n+ \"\"\"Mock story exporter class,\"\"\"\n+ EXPORT_FORMAT = 'MockFormat'\n+\n+\n+class MockStoryExporter2(object):\n+ \"\"\"Mock story exporter class,\"\"\"\n+ EXPORT_FORMAT = 'MockFormat2'\n+\n+\n+class MockStoryExporter3(object):\n+ \"\"\"Mock story exporter class,\"\"\"\n+ EXPORT_FORMAT = 'MockFormat3'\n+\n+\n+class TestStoryExportManager(BaseTest):\n+ \"\"\"Tests for the functionality of the manager module.\"\"\"\n+\n+ def setUp(self):\n+ \"\"\"Set up the tests.\"\"\"\n+ super(TestStoryExportManager, self).setUp()\n+ manager.StoryExportManager.clear_registration()\n+ manager.StoryExportManager.register_exporter(MockStoryExporter)\n+\n+ def test_get_exporters(self):\n+ \"\"\"Test to get exporter class objects.\"\"\"\n+ exporters = manager.StoryExportManager.get_exporters()\n+ exporter_list = list(exporters)\n+ self.assertIsInstance(exporter_list, list)\n+ exporter_dict = {}\n+ for name, exporter_class in exporter_list:\n+ exporter_dict[name] = exporter_class\n+ self.assertIn('mockformat', exporter_dict)\n+ exporter_class = exporter_dict.get('mockformat')\n+ self.assertEqual(exporter_class, MockStoryExporter)\n+\n+ manager.StoryExportMannager.clear_registration()\n+ exporters = manager.StoryExportManager.get_exporters()\n+ exporter_list = list(exporters)\n+ self.assertEqual(exporter_list, [])\n+\n+ manager.StoryExportManager.register_analyzer(MockStoryExporter)\n+ manager.StoryExportManager.register_analyzer(MockStoryExporter2)\n+ manager.StoryExportManager.register_analyzer(MockStoryExporter3)\n+\n+ manager.StoryExportMannager.clear_registration()\n+ exporters = manager.StoryExportManager.get_exporters()\n+ self.assertEqual(len(exporter_list), 3)\n+ self.assertIn('mockformat', exporter_list)\n+\n+ def test_get_exporter(self):\n+ \"\"\"Test to get exporter class from registry.\"\"\"\n+ exporter_class = manager.StoryExportManager.get_exporter('mockformat')\n+ self.assertEqual(exporter_class, MockStoryExporter)\n+\n+ def test_register_analyzer(self):\n+ \"\"\"Test so we raise KeyError when exporter is already registered.\"\"\"\n+ self.assertRaises(\n+ KeyError, manager.StoryExportManager.register_exporter,\n+ MockStoryExporter)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/stories/markdown.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This file contains a markdown story exporter.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+import tabulate\n+\n+from timesketch.lib.stories import interface\n+from timesketch.lib.stories import manager\n+\n+\n+class MarkdownStoryExporter(interface.StoryExporter):\n+ \"\"\"Markdown story exporter.\"\"\"\n+\n+ # String representing the output format of the story.\n+ EXPORT_FORMAT = 'markdown'\n+\n+ def export_story(self):\n+ \"\"\"Export the story as a markdown.\"\"\"\n+ return_strings = []\n+ for line in self._data_lines:\n+ if isinstance(line, str):\n+ return_strings.append(line)\n+ continue\n+\n+ return_strings.append(\n+ tabulate.tabulate(line, tablefmt='pipe', headers='keys'))\n+\n+ return '\\n\\n'.join(return_strings)\n+\n+\n+manager.StoryExportManager.register_exporter(MarkdownStoryExporter)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to export stories.
263,133
19.03.2020 08:44:06
0
7b8d6bffe0f7d7b9c2f44bdb731e5f8f55351b19
Adding markdown support in API client and fixing export
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200317',\n+ version='20200319',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "from __future__ import unicode_literals\nimport json\n+import logging\nimport pandas as pd\n@@ -24,6 +25,9 @@ from . import resource\nfrom . import view\n+logger = logging.getLogger('story_api')\n+\n+\nclass BaseBlock(object):\n\"\"\"Base block object.\"\"\"\n@@ -514,8 +518,8 @@ class Story(resource.BaseResource):\n'title': self.title,\n'content': content,\n}\n- response = self.api.session.post(\n- '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri),\n+ response = self._api.session.post(\n+ '{0:s}/{1:s}'.format(self._api.api_root, self.resource_uri),\njson=data)\nreturn response.status_code in definitions.HTTP_STATUS_CODE_20X\n@@ -526,8 +530,8 @@ class Story(resource.BaseResource):\nReturns:\nBoolean that indicates whether the deletion was successful.\n\"\"\"\n- response = self.api.session.delete(\n- '{0:s}/{1:s}'.format(self.api.api_root, self.resource_uri))\n+ response = self._api.session.delete(\n+ '{0:s}/{1:s}'.format(self._api.api_root, self.resource_uri))\nreturn response.status_code in definitions.HTTP_STATUS_CODE_20X\n@@ -555,6 +559,24 @@ class Story(resource.BaseResource):\n_ = self.lazyload_data(refresh_cache=True)\n_ = self.blocks\n+ def to_markdown(self):\n+ \"\"\"Return a markdown formatted string with the content of the story.\"\"\"\n+ resource_url = '{0:s}/sketches/{1:d}/stories/{2:d}/'.format(\n+ self._api.api_root, self._sketch.id, self.id)\n+\n+ data = {\n+ 'export_format': 'markdown'\n+ }\n+ response = self._api.session.post(resource_url, json=data)\n+\n+ if response.status_code in definitions.HTTP_STATUS_CODE_20X:\n+ return response.text\n+\n+ logger.error(\n+ 'Error exporting story: [{0:d}] {1!s} {2!s}'.format(\n+ response.status_code, response.reason, response.text))\n+ return ''\n+\ndef to_string(self):\n\"\"\"Returns a string with the content of all the story.\"\"\"\nself.reset()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1902,9 +1902,9 @@ class StoryResource(ResourceMixin, Resource):\nwith exporter_class() as exporter:\ndata_fetcher = story_api_fetcher.ApiDataFetcher()\n- exporter.set_data_fetcher(data_fetcher)\n- exporter.set_sketch_id(sketch_id)\n+ data_fetcher.set_sketch_id(sketch_id)\n+ exporter.set_data_fetcher(data_fetcher)\nexporter.from_string(story.content)\nreturn exporter.export_story()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/api_fetcher.py", "new_path": "timesketch/lib/stories/api_fetcher.py", "diff": "from __future__ import unicode_literals\n+import json\n+\nfrom flask import current_app\nimport pandas as pd\n@@ -23,6 +25,7 @@ from timesketch.lib.stories import interface\nfrom timesketch.lib.aggregators import manager as aggregator_manager\nfrom timesketch.lib.datastores.elastic import ElasticsearchDataStore\nfrom timesketch.models.sketch import Aggregation\n+from timesketch.models.sketch import Sketch\nfrom timesketch.models.sketch import View\n@@ -90,15 +93,28 @@ class ApiDataFetcher(interface.DataFetcher):\nreturn pd.DataFrame()\nquery_filter = view.query_filter\n- if not query_filter:\n+ if query_filter and isinstance(query_filter, str):\n+ query_filter = json.loads(query_filter)\n+ elif not query_filter:\nquery_filter = {'indices': '_all', 'size': 100}\n+ if view.query_dsl:\n+ query_dsl = json.loads(view.query_dsl)\n+ else:\n+ query_dsl = None\n+\n+ sketch = Sketch.query.get_with_acl(self._sketch_id)\n+ sketch_indices = [\n+ t.searchindex.index_name\n+ for t in sketch.active_timelines\n+ ]\n+\nresults = self._datastore.search_stream(\nsketch_id=self._sketch_id,\nquery_string=view.query_string,\nquery_filter=query_filter,\n- query_dsl=view.query_dsl,\n- indices='_all',\n+ query_dsl=query_dsl,\n+ indices=sketch_indices,\n)\nresult_list = [x.get('_source') for x in results]\nreturn pd.DataFrame(result_list)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/interface.py", "new_path": "timesketch/lib/stories/interface.py", "diff": "@@ -27,7 +27,6 @@ class StoryExporter(object):\ndef __init__(self):\n\"\"\"Initialize the exporter.\"\"\"\nself._data_lines = []\n- self._sketch_id = 0\nself._data_fetcher = None\n@property\n@@ -78,10 +77,6 @@ class StoryExporter(object):\n\"\"\"\nself._data_fetcher = data_fetcher\n- def set_sketch_id(self, sketch_id):\n- \"\"\"Set the sketch id.\"\"\"\n- self._sketch_id = sketch_id\n-\ndef __enter__(self):\n\"\"\"Make it possible to use \"with\" statement.\"\"\"\nself.reset()\n@@ -96,6 +91,10 @@ class StoryExporter(object):\nclass DataFetcher(object):\n\"\"\"A data fetcher interface.\"\"\"\n+ def __init__(self):\n+ \"\"\"Initialize the data fetcher.\"\"\"\n+ self._sketch_id = 0\n+\ndef get_aggregation(self, agg_dict):\n\"\"\"Returns a data frame from an aggregation dict.\n@@ -119,3 +118,7 @@ class DataFetcher(object):\nA pandas DataFrame with the results from a view aggregation.\n\"\"\"\nraise NotImplementedError\n+\n+ def set_sketch_id(self, sketch_id):\n+ \"\"\"Set the sketch id.\"\"\"\n+ self._sketch_id = sketch_id\n" } ]
Python
Apache License 2.0
google/timesketch
Adding markdown support in API client and fixing export
263,133
19.03.2020 09:12:33
0
99ab88cd10c0bcfa7696317b573fede292533ecc
Fixing manager test.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/manager_test.py", "new_path": "timesketch/lib/stories/manager_test.py", "diff": "@@ -55,17 +55,18 @@ class TestStoryExportManager(BaseTest):\nexporter_class = exporter_dict.get('mockformat')\nself.assertEqual(exporter_class, MockStoryExporter)\n- manager.StoryExportMannager.clear_registration()\n+ manager.StoryExportManager.clear_registration()\nexporters = manager.StoryExportManager.get_exporters()\n- exporter_list = list(exporters)\n+ exporter_list = [x for x, _ in exporters]\nself.assertEqual(exporter_list, [])\n- manager.StoryExportManager.register_analyzer(MockStoryExporter)\n- manager.StoryExportManager.register_analyzer(MockStoryExporter2)\n- manager.StoryExportManager.register_analyzer(MockStoryExporter3)\n+ manager.StoryExportManager.clear_registration()\n+ manager.StoryExportManager.register_exporter(MockStoryExporter)\n+ manager.StoryExportManager.register_exporter(MockStoryExporter2)\n+ manager.StoryExportManager.register_exporter(MockStoryExporter3)\n- manager.StoryExportMannager.clear_registration()\nexporters = manager.StoryExportManager.get_exporters()\n+ exporter_list = [x for x, _ in exporters]\nself.assertEqual(len(exporter_list), 3)\nself.assertIn('mockformat', exporter_list)\n@@ -74,7 +75,7 @@ class TestStoryExportManager(BaseTest):\nexporter_class = manager.StoryExportManager.get_exporter('mockformat')\nself.assertEqual(exporter_class, MockStoryExporter)\n- def test_register_analyzer(self):\n+ def test_register_exporter(self):\n\"\"\"Test so we raise KeyError when exporter is already registered.\"\"\"\nself.assertRaises(\nKeyError, manager.StoryExportManager.register_exporter,\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing manager test.
263,133
19.03.2020 09:52:15
0
89d64b6ddb956cefe6b4e933d25912188a5765a9
Adding a more generic export functionality in api client and a get formats function in manager.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -561,11 +561,15 @@ class Story(resource.BaseResource):\ndef to_markdown(self):\n\"\"\"Return a markdown formatted string with the content of the story.\"\"\"\n+ return self.to_export_format('markdown')\n+\n+ def to_export_format(self, export_format):\n+ \"\"\"Returns exported copy of the story as defined in export_format.\"\"\"\nresource_url = '{0:s}/sketches/{1:d}/stories/{2:d}/'.format(\nself._api.api_root, self._sketch.id, self.id)\ndata = {\n- 'export_format': 'markdown'\n+ 'export_format': export_format\n}\nresponse = self._api.session.post(resource_url, json=data)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/manager.py", "new_path": "timesketch/lib/stories/manager.py", "diff": "@@ -43,6 +43,11 @@ class StoryExportManager(object):\ncontinue\nyield exporter_type, exporter_class\n+ @classmethod\n+ def get_formats(cls):\n+ \"\"\"Retrieves the registered format types.\"\"\"\n+ return cls._class_registry.keys()\n+\n@classmethod\ndef get_exporter(cls, exporter_type):\n\"\"\"Retrieves a class object of a specific exporter.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a more generic export functionality in api client and a get formats function in manager.
263,133
19.03.2020 11:32:27
0
a41bfdafe30b8efb88665216b43e28a2a5402dfb
Adding a check of analyzer status.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -235,6 +235,28 @@ class Sketch(resource.BaseResource):\naggregations.append(aggregation_obj)\nreturn aggregations\n+ def get_analyzer_status(self):\n+ \"\"\"Returns a list of started analyzers and their status.\"\"\"\n+ stats_list = []\n+ for timeline in self.list_timelines():\n+ resource_uri = '{0:s}/sketches/{1:d}/timelines/{2:d}/analysis'.format(\n+ self.api.api_root, self.id, timeline.id)\n+ response = self.api.session.get(resource_uri)\n+ response_json = response.json()\n+ for result in response_json.get('objects', []):\n+ stat = {\n+ 'index': timeline.index,\n+ 'id': timeline.id,\n+ 'analyzer': result.get('analyzer_name', 'N/A'),\n+ 'results': result.get('result', 'N/A'),\n+ 'status': 'N/A',\n+ }\n+ status = result.get('status', [])\n+ if len(status) == 1:\n+ stat['status'] = status[0].get('status', 'N/A')\n+ stats_list.append(stat)\n+ return stats_list\n+\ndef get_aggregation(self, aggregation_id):\n\"\"\"Return a stored aggregation.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a check of analyzer status.
263,133
19.03.2020 12:57:23
0
14776003b2210465f2e3152a60312655b3797f23
Fixing linter and docstring
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -236,11 +236,19 @@ class Sketch(resource.BaseResource):\nreturn aggregations\ndef get_analyzer_status(self):\n- \"\"\"Returns a list of started analyzers and their status.\"\"\"\n+ \"\"\"Returns a list of started analyzers and their status.\n+\n+ Returns:\n+ A list of dict objects that contains status information\n+ of each analyzer run. The dict contains information about\n+ what timeline it ran against, the results and current\n+ status of the analyzer run.\n+ \"\"\"\nstats_list = []\n- for timeline in self.list_timelines():\n- resource_uri = '{0:s}/sketches/{1:d}/timelines/{2:d}/analysis'.format(\n- self.api.api_root, self.id, timeline.id)\n+ for timeline_obj in self.list_timelines():\n+ resource_uri = (\n+ '{0:s}/sketches/{1:d}/timelines/{2:d}/analysis').format(\n+ self.api.api_root, self.id, timeline_obj.id)\nresponse = self.api.session.get(resource_uri)\nresponse_json = response.json()\nobjects = response_json.get('objects')\n@@ -248,8 +256,8 @@ class Sketch(resource.BaseResource):\ncontinue\nfor result in objects[0]:\nstat = {\n- 'index': timeline.index,\n- 'timeline_id': timeline.id,\n+ 'index': timeline_obj.index,\n+ 'timeline_id': timeline_obj.id,\n'analyzer': result.get('analyzer_name', 'N/A'),\n'results': result.get('result', 'N/A'),\n'status': 'N/A',\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing linter and docstring
263,133
25.03.2020 14:46:05
0
df80f08e1cf06da755e5d2b47d7a38201939037e
Making further changes
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200320',\n+ version='20200325',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/story.py", "new_path": "api_client/python/timesketch_api_client/story.py", "diff": "@@ -561,7 +561,8 @@ class Story(resource.BaseResource):\ndef to_markdown(self):\n\"\"\"Return a markdown formatted string with the content of the story.\"\"\"\n- return self.to_export_format('markdown')\n+ story_dict = self.to_export_format('markdown')\n+ return story_dict.get('story', '')\ndef to_export_format(self, export_format):\n\"\"\"Returns exported copy of the story as defined in export_format.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_search.py", "new_path": "timesketch/lib/analyzers/browser_search.py", "diff": "@@ -243,8 +243,7 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\ndescription='Created by the browser search analyzer')\nstory = self.sketch.add_story(utils.BROWSER_STORY_TITLE)\n- if utils.BROWSER_STORY_HEADER not in story.data:\n- story.add_text(utils.BROWSER_STORY_HEADER)\n+ story.add_text(utils.BROWSER_STORY_HEADER, skip_if_already_there=True)\nstory.add_text(\n'## Browser Search Analyzer.\\n\\nThe browser search '\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_timeframe.py", "new_path": "timesketch/lib/analyzers/browser_timeframe.py", "diff": "@@ -210,8 +210,6 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\nhour_count = dict(aggregation.values.tolist())\ndata_frame_outside = data_frame[~data_frame.hour.isin(activity_hours)]\n- # ADD HOUR/DAY AND ADD TWO AGGREGATIONS AS CHARTS, BARCHART FOR HOUR\n- # SOMETHING ELSE FOR DAY!!! -> ADD THIS INTO THE BROWSER STORY\nfor event in utils.get_events_from_data_frame(\ndata_frame_outside, self.datastore):\nevent.add_tags(['outside-active-hours'])\n@@ -252,8 +250,7 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\ndescription='Created by the browser timeframe analyzer')\nstory = self.sketch.add_story(utils.BROWSER_STORY_TITLE)\n- if utils.BROWSER_STORY_HEADER not in story.data:\n- story.add_text(utils.BROWSER_STORY_HEADER)\n+ story.add_text(utils.BROWSER_STORY_HEADER, skip_if_already_there=True)\nstory.add_text(\n'## Browser Timeframe Analyzer.\\n\\nThe browser timeframe '\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -413,7 +413,7 @@ class Story(object):\n@property\ndef data(self):\n\"\"\"Return back the content of the story object.\"\"\"\n- return self.story.content\n+ return json.loads(self.story.content)\n@staticmethod\ndef _create_new_block():\n@@ -444,12 +444,26 @@ class Story(object):\ndb_session.add(self.story)\ndb_session.commit()\n- def add_text(self, text):\n+ def add_text(self, text, skip_if_already_there=False):\n\"\"\"Add a text block to the Story.\nArgs:\ntext (str): text (markdown is supported) to add to the story.\n- \"\"\"\n+ skip_if_already_there (boolean): if set to True then the text\n+ will not be added if a block with this text already exists.\n+ \"\"\"\n+ if skip_if_already_there and self.data:\n+ for block in self.data:\n+ if not block:\n+ continue\n+ if not isinstance(block, dict):\n+ continue\n+ old_text = block.get('content')\n+ if not old_text:\n+ continue\n+ if text == old_text:\n+ return\n+\nblock = self._create_new_block()\nblock['content'] = text\nself._commit(block)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/utils.py", "new_path": "timesketch/lib/analyzers/utils.py", "diff": "@@ -243,8 +243,12 @@ def _fix_np_nan(source_dict, attribute, replace_with=None):\nreplace_with = []\nvalue = source_dict.get(attribute)\n+ try:\nif numpy.isnan(value):\nsource_dict[attribute] = replace_with\n+ except TypeError:\n+ # The value does not need to be changed.\n+ pass\ndef get_events_from_data_frame(frame, datastore):\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/api_fetcher.py", "new_path": "timesketch/lib/stories/api_fetcher.py", "diff": "@@ -67,7 +67,9 @@ class ApiDataFetcher(interface.DataFetcher):\nif not agg_class:\nreturn pd.DataFrame()\naggregator = agg_class(sketch_id=self._sketch_id)\n- return aggregator.run(aggregation.parameters)\n+ parameter_string = aggregation.parameters\n+ parameters = json.loads(parameter_string)\n+ return aggregator.run(**parameters)\ndef get_view(self, view_dict):\n\"\"\"Returns a data frame from a view dict.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/interface.py", "new_path": "timesketch/lib/stories/interface.py", "diff": "@@ -80,7 +80,6 @@ class StoryExporter(object):\n'type': 'aggregation',\n'value': self._data_fetcher.get_aggregation(\nproperties.get('aggregation'))})\n- print('ADDED AGG: {}'.format(type(self._data_lines[-1].get('value'))))\ndef reset(self):\n\"\"\"Reset story by removing all blocks.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/stories/markdown.py", "new_path": "timesketch/lib/stories/markdown.py", "diff": "@@ -38,7 +38,7 @@ class MarkdownStoryExporter(interface.StoryExporter):\n\"\"\"Returns a markdown formatted string from a pandas DataFrame.\"\"\"\nnr_rows, _ = data_frame.shape\nif not nr_rows:\n- return ''\n+ return '*<empty table>*'\nif nr_rows <= (self._DATAFRAM_HEADER_ROWS + self._DATAFRAM_TAIL_ROWS):\nreturn tabulate.tabulate(\n" } ]
Python
Apache License 2.0
google/timesketch
Making further changes
263,093
26.03.2020 11:49:10
-3,600
02ce19e97f44210dc3870e62ea51a03ffa6b5c5e
Check field type
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/bucket.py", "new_path": "timesketch/lib/aggregators/bucket.py", "diff": "@@ -84,6 +84,8 @@ class TermsAggregation(interface.BaseAggregator):\nInstance of interface.AggregationResult with aggregation result.\n\"\"\"\nself.field = field\n+ formatted_field_name = self.format_field_by_type(field)\n+\n# Encoding information for Vega-Lite.\nencoding = {\n'x': {\n@@ -102,7 +104,7 @@ class TermsAggregation(interface.BaseAggregator):\n'aggs': {\n'aggregation': {\n'terms': {\n- 'field': '{0:s}.keyword'.format(field),\n+ 'field': formatted_field_name,\n'size': limit\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/interface.py", "new_path": "timesketch/lib/aggregators/interface.py", "diff": "@@ -147,6 +147,54 @@ class BaseAggregator(object):\n'description': self.DESCRIPTION,\n}\n+ def format_field_by_type(self, field_name):\n+ \"\"\"Format field name based on mapping type.\n+\n+ For text fields we need to use .keyword because text fields are not\n+ available to aggregations per default.\n+\n+ For all other types using the field name as is works.\n+\n+ Args:\n+ field_name (str): Name of the field.\n+\n+ Returns:\n+ Field name as string formatted after mapping type.\n+ \"\"\"\n+ # Default field format is just the name unchanged.\n+ field_format = field_name\n+ field_type = None\n+\n+ # Get the mapping for the field.\n+ mapping = self.elastic.indices.get_field_mapping(\n+ index=self.index, fields=field_name)\n+\n+ # The returned structure is nested so we need to unpack it.\n+ # Example:\n+ # {'<INDEX NAME>': {\n+ # 'mappings': {\n+ # 'inode': {\n+ # 'full_name': 'inode',\n+ # 'mapping': {\n+ # 'inode': {\n+ # 'type': 'long'\n+ # }\n+ # }\n+ # }\n+ # }\n+ # }}\n+ for value in mapping.values():\n+ mappings = value.get('mappings', {})\n+ mapping = mappings.get(field_name, {}).get('mapping', {})\n+ field_type = mapping.get(field_name, {}).get('type', None)\n+ if field_type:\n+ break\n+\n+ if field_type == 'text':\n+ field_format = '{0:s}.keyword'.format(field_name)\n+\n+ return field_format\n+\ndef elastic_aggregation(self, aggregation_spec):\n\"\"\"Helper method to execute aggregation in Elasticsearch.\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/term.py", "new_path": "timesketch/lib/aggregators/term.py", "diff": "@@ -64,7 +64,7 @@ def get_spec(field, query='', query_dsl=''):\n'aggregations': {\n'term_count': {\n'terms': {\n- 'field': '{0:s}.keyword'.format(field)\n+ 'field': field\n}\n}\n}\n@@ -155,8 +155,10 @@ class FilteredTermsAggregation(interface.BaseAggregator):\nraise ValueError('Both query_string and query_dsl are missing')\nself.field = field\n+ formatted_field_name = self.format_field_by_type(field)\n+\naggregation_spec = get_spec(\n- field=field, query=query_string, query_dsl=query_dsl)\n+ field=formatted_field_name, query=query_string, query_dsl=query_dsl)\n# Encoding information for Vega-Lite.\nencoding = {\n" } ]
Python
Apache License 2.0
google/timesketch
Check field type (#1147)
263,133
30.03.2020 09:45:05
0
51b463769f2e3265fd443f1a6d15482488547e9f
Adding a manual aggregator and fixing stories.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/__init__.py", "new_path": "timesketch/lib/aggregators/__init__.py", "diff": "# Register all aggregators here by importing them.\nfrom timesketch.lib.aggregators import bucket\n+from timesketch.lib.aggregators import feed\nfrom timesketch.lib.aggregators import term\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/bucket.py", "new_path": "timesketch/lib/aggregators/bucket.py", "diff": "@@ -80,9 +80,11 @@ class TermsAggregation(interface.BaseAggregator):\n\"\"\"Run the aggregation.\nArgs:\n- field: What field to aggregate.\n+ field: What field to aggregate on.\nlimit: How many buckets to return.\nsupported_charts: Chart type to render. Defaults to table.\n+ order_field: The name of the field that is used for the order\n+ of items in the aggregation, defaults to \"count\".\nReturns:\nInstance of interface.AggregationResult with aggregation result.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "timesketch/lib/aggregators/feed.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Feed aggregations.\"\"\"\n+\n+from __future__ import unicode_literals\n+\n+from timesketch.lib.aggregators import manager\n+from timesketch.lib.aggregators import interface\n+\n+\n+class ManualFeedAggregation(interface.BaseAggregator):\n+ \"\"\"Manual Feed Aggregation.\"\"\"\n+\n+ NAME = 'manual_feed'\n+ DISPLAY_NAME = 'Manual Feed Aggregation'\n+ DESCRIPTION = 'Aggregating values of a user supplied data'\n+\n+ SUPPORTED_CHARTS = frozenset(\n+ ['barchart', 'circlechart', 'hbarchart', 'table'])\n+\n+ # No Form fields since this is not meant to be used in the UI.\n+ FORM_FIELDS = []\n+\n+ def __init__(self, sketch_id=None, index=None):\n+ \"\"\"Initialize the aggregator object.\n+\n+ Args:\n+ sketch_id: Sketch ID.\n+ index: List of elasticsearch index names.\n+ \"\"\"\n+ super(ManualFeedAggregation, self).__init__(\n+ sketch_id=sketch_id, index=index)\n+ self.title = ''\n+\n+ @property\n+ def chart_title(self):\n+ \"\"\"Returns a title for the chart.\"\"\"\n+ if self.title:\n+ return self.title\n+ return 'Results From A Manually Fed Table'\n+\n+ # pylint: disable=arguments-differ\n+ def run(\n+ self, data, title='', supported_charts='tables', field='count',\n+ order_field='count'):\n+ \"\"\"Run the aggregation.\n+\n+ Args:\n+ data: list of dict objects, each entry in the list is a\n+ dictionary, representing a single entry in the aggregation.\n+ title: string with the aggregation title.\n+ supported_charts: Chart type to render. Defaults to table.\n+ field: What field to aggregate on.\n+ order_field: The name of the field that is used for the order\n+ of items in the aggregation, defaults to \"count\".\n+\n+ Returns:\n+ Instance of interface.AggregationResult with aggregation result.\n+\n+ Raises:\n+ ValueError: data is not supplied.\n+ \"\"\"\n+ if not data:\n+ raise ValueError('Data is missing')\n+\n+ self.title = title\n+\n+ # Encoding information for Vega-Lite.\n+ encoding = {\n+ 'x': {\n+ 'field': field,\n+ 'type': 'nominal',\n+ 'sort': {\n+ 'op': 'sum',\n+ 'field': order_field,\n+ 'order': 'descending'\n+ }\n+ },\n+ 'y': {'field': 'count', 'type': 'quantitative'}\n+ }\n+\n+ return interface.AggregationResult(\n+ encoding=encoding, values=data, chart_type=supported_charts)\n+\n+\n+manager.AggregatorManager.register_aggregator(\n+ ManualFeedAggregation, exclude_from_list=True)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/manager.py", "new_path": "timesketch/lib/aggregators/manager.py", "diff": "@@ -20,6 +20,7 @@ class AggregatorManager(object):\n\"\"\"The aggregator manager.\"\"\"\n_class_registry = {}\n+ _exclude_registry = set()\n@classmethod\ndef get_aggregators(cls):\n@@ -31,6 +32,8 @@ class AggregatorManager(object):\ntype: the aggregator class.\n\"\"\"\nfor agg_name, agg_class in iter(cls._class_registry.items()):\n+ if agg_name in cls._exclude_registry:\n+ continue\nyield agg_name, agg_class\n@classmethod\n@@ -54,13 +57,16 @@ class AggregatorManager(object):\nreturn aggregator_class\n@classmethod\n- def register_aggregator(cls, aggregator_class):\n+ def register_aggregator(cls, aggregator_class, exclude_from_list=False):\n\"\"\"Registers an aggregator class.\nThe aggregator classes are identified by their lower case name.\nArgs:\naggregator_class (type): the aggregator class to register.\n+ exclude_from_list (boolean): if set to True then the aggregator\n+ gets registered but will not be included in the\n+ get_aggregators function. Defaults to False.\nRaises:\nKeyError: if class is already set for the corresponding name.\n@@ -70,8 +76,11 @@ class AggregatorManager(object):\nraise KeyError('Class already set for name: {0:s}.'.format(\naggregator_class.NAME))\ncls._class_registry[aggregator_name] = aggregator_class\n+ if exclude_from_list:\n+ cls._exclude_registry.add(aggregator_name)\n@classmethod\ndef clear_registration(cls):\n\"\"\"Clears all aggregator registrations.\"\"\"\ncls._class_registry = {}\n+ cls._exclude_registry = set()\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/manager_test.py", "new_path": "timesketch/lib/aggregators/manager_test.py", "diff": "@@ -28,6 +28,15 @@ class MockAggregator(object):\nSUPPORTED_CHARTS = frozenset()\n+class MockAggregator2(object):\n+ \"\"\"Mock aggregator class.\"\"\"\n+ NAME = 'MockAggregatorAgain'\n+ DESCRIPTION = 'MockDescriptionForMocker'\n+ DISPLAY_NAME = 'MockDisplayName'\n+ FORM_FIELDS = {}\n+ SUPPORTED_CHARTS = frozenset()\n+\n+\nclass TestAggregatorManager(BaseTest):\n\"\"\"Tests for the functionality of the manager module.\"\"\"\n@@ -45,6 +54,14 @@ class TestAggregatorManager(BaseTest):\nself.assertEqual(aggregator_class, MockAggregator)\nself.assertEqual(aggregator_name, 'mockaggregator')\n+ # Register the second, but so that it does not appear in list.\n+ manager.AggregatorManager.register_aggregator(\n+ MockAggregator2, exclude_from_list=True)\n+\n+ aggregators = manager.AggregatorManager.get_aggregators()\n+ aggregator_list = list(aggregators)\n+ self.assertEqual(len(aggregator_list), 1)\n+\ndef test_get_aggregator(self):\n\"\"\"Test to get aggregator class from registry.\"\"\"\naggregator_class = manager.AggregatorManager.get_aggregator(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_search.py", "new_path": "timesketch/lib/analyzers/browser_search.py", "diff": "@@ -245,7 +245,6 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\nparams = {\n'query_string': 'tag:\"browser-search\"',\n- 'supported_charts': 'hbarchart',\n'field': 'domain',\n}\nagg_engines = self.sketch.add_aggregation(\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_timeframe.py", "new_path": "timesketch/lib/analyzers/browser_timeframe.py", "diff": "@@ -247,6 +247,7 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\nfirst = end\nindex = activity_hours.index(end)\nlast = activity_hours[index - 1]\n+\nstory.add_text(\n'## Browser Timeframe Analyzer.\\n\\nThe browser timeframe '\n'analyzer discovered {0:d} browser events that ocurred '\n@@ -263,6 +264,22 @@ class BrowserTimeframeSketchPlugin(interface.BaseSketchAnalyzer):\n'between {3:02d} and {4:02d} (hours in UTC)'.format(\ntagged_events, percent, total_count, first, last))\n+ params = {\n+ 'data': aggregation.to_dict(orient='records'),\n+ 'title': 'Browser Activity Per Hour',\n+ 'field': 'hour',\n+ 'order_field': 'hour',\n+ }\n+ agg_obj = self.sketch.add_aggregation(\n+ name='Browser Activity Per Hour', agg_name='manual_feed',\n+ agg_params=params, chart_type='barchart',\n+ description='Created by the browser timeframe analyzer')\n+ story.add_text(\n+ 'An overview of all browser activity per hour. The threshold '\n+ 'used to determine if an hour was considered to be active '\n+ 'was: {0:0.2f}'.format(threshold))\n+ story.add_aggregation(agg_obj)\n+\nreturn (\n'Tagged {0:d} out of {1:d} events as outside of normal '\n'active hours.').format(tagged_events, total_count)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a manual aggregator and fixing stories.
263,133
30.03.2020 11:19:33
0
e8a7e9fdad474219a31b0ea31baabf6afb9a1a35
Adding tooltips to charts and fixing search day.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/bucket.py", "new_path": "timesketch/lib/aggregators/bucket.py", "diff": "@@ -103,7 +103,10 @@ class TermsAggregation(interface.BaseAggregator):\n'order': 'descending'\n}\n},\n- 'y': {'field': 'count', 'type': 'quantitative'}\n+ 'y': {'field': 'count', 'type': 'quantitative'},\n+ 'tooltip': [\n+ {'field': field, 'type': 'nominal'},\n+ {'field': order_field, 'type': 'quantitative'}],\n}\naggregation_spec = {\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/aggregators/term.py", "new_path": "timesketch/lib/aggregators/term.py", "diff": "@@ -175,7 +175,10 @@ class FilteredTermsAggregation(interface.BaseAggregator):\n'order': 'descending'\n}\n},\n- 'y': {'field': 'count', 'type': 'quantitative'}\n+ 'y': {'field': 'count', 'type': 'quantitative'},\n+ 'tooltip': [\n+ {'field': field, 'type': 'nominal'},\n+ {'field': 'count', 'type': 'quantitative'}],\n}\nresponse = self.elastic_aggregation(aggregation_spec)\n" }, { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_search.py", "new_path": "timesketch/lib/analyzers/browser_search.py", "diff": "@@ -208,7 +208,7 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\nevent.add_attributes({\n'search_string': search_query,\n'search_engine': engine,\n- 'search_day': str(day)})\n+ 'search_day': 'D:{0:s}'.format(day)})\nevent.add_human_readable('{0:s} search query: {1:s}'.format(\nengine, search_query), self.NAME)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding tooltips to charts and fixing search day.
263,133
30.03.2020 11:20:35
0
e788285fe64269103b1d089de63722f3d126ffb7
Fix API client version
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200325',\n+ version='20200330',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Fix API client version
263,133
30.03.2020 11:23:05
0
d8eda5e4b5f2f09e82bf8fd58255584083e24f90
Fixing a spelling mistake
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/interface.py", "new_path": "timesketch/lib/analyzers/interface.py", "diff": "@@ -480,7 +480,7 @@ class Story(object):\naggregation (Aggregation): Saved aggregation to add to the story.\nagg_type (str): string indicating the type of aggregation, can be:\n\"table\" or the name of the chart to be used, eg \"barcharct\",\n- \"hbarchart\". Defaults to the valueu of supported_charts.\n+ \"hbarchart\". Defaults to the value of supported_charts.\n\"\"\"\ntoday = datetime.datetime.utcnow()\nblock = self._create_new_block()\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing a spelling mistake
263,133
30.03.2020 12:24:55
0
b1295e5ed5476d2dd3772866256ca755e67a29fa
Minor changes to the browser search story.
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/analyzers/browser_search.py", "new_path": "timesketch/lib/analyzers/browser_search.py", "diff": "@@ -258,18 +258,21 @@ class BrowserSearchSketchPlugin(interface.BaseSketchAnalyzer):\nstory.add_text(\n'## Browser Search Analyzer.\\n\\nThe browser search '\n- 'analyzer found {0:d} browser searches. This is a summary of '\n- 'it\\'s findings.\\n\\n'.format(simple_counter))\n+ 'analyzer takes URLs usually resevered for browser '\n+ 'search queries and extracts the search string.'\n+ 'In this timeline the analyzer discovered {0:d} '\n+ 'browser searches.\\n\\nThis is a summary of '\n+ 'it\\'s findings.'.format(simple_counter))\nstory.add_text(\n'The top 20 most commonly discovered searches were:')\nstory.add_aggregation(agg_obj)\nstory.add_text('The domains used to search:')\nstory.add_aggregation(agg_engines, 'hbarchart')\n+ story.add_text('And the most common days of search:')\n+ story.add_aggregation(agg_days)\nstory.add_text(\n'And an overview of all the discovered search terms:')\nstory.add_view(view)\n- story.add_text('And the most common days of search:')\n- story.add_aggregation(agg_days)\nreturn (\n'Browser Search completed with {0:d} search results '\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to the browser search story.
263,133
31.03.2020 09:34:56
0
ea0ed8a30426ffc7ae37abba6d7523c294b99ee8
Changing version information to trigger new travis.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200330',\n+ version='20200331',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Changing version information to trigger new travis.
263,127
31.03.2020 21:21:13
-7,200
515c8dcc8c8206b6190784223c472bda87fd036a
Fix docker installation documentation link.
[ { "change_type": "MODIFY", "old_path": "README.md", "new_path": "README.md", "diff": "@@ -20,7 +20,7 @@ Timesketch is an open source tool for collaborative forensic timeline analysis.\n#### Installation\n* [Install Timesketch manually](docs/Installation.md)\n-* [Use Docker](docker)\n+* [Use Docker](docker/README.md)\n* [Upgrade from existing installation](docs/Upgrading.md)\n#### Adding timelines\n" } ]
Python
Apache License 2.0
google/timesketch
Fix docker installation documentation link.
263,133
31.03.2020 20:40:59
0
a2e4d7d3c022c0e0f74d1267f334d07255309498
Forgot to update one thing
[ { "change_type": "MODIFY", "old_path": "timesketch/lib/charts/circle.py", "new_path": "timesketch/lib/charts/circle.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"Circles.\"\"\"\n+\"\"\"Circle chart class..\"\"\"\nfrom __future__ import unicode_literals\n" } ]
Python
Apache License 2.0
google/timesketch
Forgot to update one thing
263,093
08.04.2020 13:31:00
-7,200
76b901ddf2c8bdcf1a431bf3f12ca7805b804755
Add listing of groups and users, and ability to exapnd groups
[ { "change_type": "MODIFY", "old_path": "timesketch/tsctl.py", "new_path": "timesketch/tsctl.py", "diff": "@@ -91,6 +91,16 @@ class AddUser(Command):\nsys.stdout.write('User {0:s} created/updated\\n'.format(username))\n+class ListUsers(Command):\n+ \"\"\"List all users.\"\"\"\n+\n+ # pylint: disable=arguments-differ, method-hidden\n+ def run(self):\n+ \"\"\"The run method for the command.\"\"\"\n+ for user in User.query.all():\n+ print(user.username)\n+\n+\nclass AddGroup(Command):\n\"\"\"Create a new Timesketch group.\"\"\"\noption_list = (Option('--name', '-n', dest='name', required=True), )\n@@ -106,6 +116,16 @@ class AddGroup(Command):\nsys.stdout.write('Group {0:s} created\\n'.format(name))\n+class ListGroups(Command):\n+ \"\"\"List all groups.\"\"\"\n+\n+ # pylint: disable=arguments-differ, method-hidden\n+ def run(self):\n+ \"\"\"The run method for the command.\"\"\"\n+ for group in Group.query.all():\n+ print(group.name)\n+\n+\nclass GroupManager(Command):\n\"\"\"Manage group memberships.\"\"\"\noption_list = (\n@@ -116,23 +136,38 @@ class GroupManager(Command):\naction='store_true',\nrequired=False,\ndefault=False),\n+ Option(\n+ '--expand',\n+ dest='expand',\n+ action='store_true',\n+ required=False,\n+ default=False),\nOption('--group', '-g', dest='group_name', required=True),\n- Option('--user', '-u', dest='user_name', required=True), )\n+ Option('--user', '-u', dest='user_name', required=False, default=None)\n+ )\n# pylint: disable=arguments-differ, method-hidden\n- def run(self, remove, group_name, user_name):\n+ def run(self, remove, expand, group_name, user_name):\n\"\"\"Add the user to the group.\"\"\"\nif not isinstance(group_name, six.text_type):\ngroup_name = codecs.decode(group_name, 'utf-8')\n+ group = Group.query.filter_by(name=group_name).first()\n+\n+ # List all members of a group and then exit.\n+ if expand:\n+ for _user in group.users:\n+ print(_user.username)\n+ return\n+\nif not isinstance(user_name, six.text_type):\nuser_name = codecs.decode(user_name, 'utf-8')\n-\n- group = Group.query.filter_by(name=group_name).first()\n+ user = None\n+ if user_name:\nuser = User.query.filter_by(username=user_name).first()\n# Add or remove user from group\n- if remove:\n+ if remove and user:\ntry:\nuser.groups.remove(group)\nsys.stdout.write('{0:s} removed from group {1:s}\\n'.format(\n@@ -141,7 +176,7 @@ class GroupManager(Command):\nexcept ValueError:\nsys.stdout.write('{0:s} is not a member of group {1:s}\\n'.\nformat(user_name, group_name))\n- else:\n+ elif user:\nuser.groups.append(group)\ntry:\ndb_session.commit()\n@@ -444,7 +479,8 @@ class ImportTimeline(Command):\n# Start Celery pipeline for indexing and analysis.\n# Import here to avoid circular imports.\n- from timesketch.lib import tasks # pylint: disable=import-outside-toplevel\n+ # pylint: disable=import-outside-toplevel\n+ from timesketch.lib import tasks\npipeline = tasks.build_index_pipeline(\nfile_path=file_path, events='', timeline_name=timeline_name,\nindex_name=index_name, file_extension=extension,\n@@ -459,7 +495,9 @@ def main():\n# Setup Flask-script command manager and register commands.\nshell_manager = Manager(create_app)\nshell_manager.add_command('add_user', AddUser())\n+ shell_manager.add_command('list_users', ListUsers())\nshell_manager.add_command('add_group', AddGroup())\n+ shell_manager.add_command('list_groups', ListGroups)\nshell_manager.add_command('manage_group', GroupManager())\nshell_manager.add_command('add_index', AddSearchIndex())\nshell_manager.add_command('db', MigrateCommand)\n" } ]
Python
Apache License 2.0
google/timesketch
Add listing of groups and users, and ability to exapnd groups
263,108
17.04.2020 10:42:51
-7,200
89ef241a7c572227bdd3f31c668b84b644139019
Update installation and plaso documentation
[ { "change_type": "MODIFY", "old_path": "docs/EnablePlasoUpload.md", "new_path": "docs/EnablePlasoUpload.md", "diff": "@@ -7,12 +7,12 @@ To enable uploading and processing of Plaso storage files, there are a couple of\nNOTE: Due to changes in the format of the Plaso storage file you need to run the latest version of Plaso (>=1.5.0).\nFollowing the official Plaso documentation:\n-https://github.com/log2timeline/plaso/wiki/Ubuntu-Packaged-Release\n+https://plaso.readthedocs.io/en/latest/sources/user/Ubuntu-Packaged-Release.html\n$ sudo add-apt-repository universe\n$ sudo add-apt-repository ppa:gift/stable\n$ sudo apt-get update\n- $ sudo apt-get install python-plaso\n+ $ sudo apt-get install plaso-tools\n**Install Redis**\n" }, { "change_type": "MODIFY", "old_path": "docs/Installation.md", "new_path": "docs/Installation.md", "diff": "@@ -16,10 +16,10 @@ Install Java\n$ sudo apt-get install openjdk-8-jre-headless\n$ sudo apt-get install apt-transport-https\n-Install the latest Elasticsearch 6.x release:\n+Install the latest Elasticsearch 7.x release:\n$ sudo wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -\n- $ sudo echo \"deb https://artifacts.elastic.co/packages/6.x/apt stable main\" | sudo tee -a /etc/apt/sources.list.d/elastic-6.x.list\n+ $ sudo echo \"deb https://artifacts.elastic.co/packages/7.x/apt stable main\" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list\n$ sudo apt-get update\n$ sudo apt-get install elasticsearch\n" } ]
Python
Apache License 2.0
google/timesketch
Update installation and plaso documentation (#1169)
263,100
17.04.2020 10:43:38
-7,200
5a4926e3009a30db8c913eeaa1d3f7ca162e8199
Fixing typo libffi
[ { "change_type": "MODIFY", "old_path": "docs/Installation.md", "new_path": "docs/Installation.md", "diff": "@@ -59,7 +59,7 @@ Then you need to restart PostgreSQL:\nNow it is time to install Timesketch. First we need to install some dependencies:\n- $ sudo apt-get install python3-pip python3-dev libffi3-dev\n+ $ sudo apt-get install python3-pip python3-dev libffi-dev\nThen install Timesketch itself:\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing typo libffi (#1168)
263,133
05.05.2020 10:45:58
0
bb3f0227224fbd1c33988875f28c4aeb14e9b1ae
Moving the importer into a separate directory and a library.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "\"\"\"This is the setup file for the project.\"\"\"\nfrom __future__ import unicode_literals\n-import os\n-import glob\n-\nfrom setuptools import find_packages\nfrom setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200424',\n+ version='20200505',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n@@ -39,14 +36,11 @@ setup(\npackages=find_packages(),\ninclude_package_data=True,\nzip_safe=False,\n- scripts=glob.glob(os.path.join('tools', '[a-z]*.py')),\ninstall_requires=frozenset([\n'pandas',\n'requests',\n'altair',\n- 'xlrd',\n'google-auth',\n'google_auth_oauthlib',\n- 'pyyaml',\n'beautifulsoup4']),\n)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -473,6 +473,11 @@ class Sketch(resource.BaseResource):\nReturns:\nTimeline object instance.\n\"\"\"\n+ # TODO: Deprecate this function.\n+ logger.warning(\n+ 'This function is about to be deprecated, please use the '\n+ 'timesketch_import_client instead')\n+\nresource_url = '{0:s}/upload/'.format(self.api.api_root)\nfiles = {'file': open(file_path, 'rb')}\ndata = {'name': timeline_name, 'sketch_id': self.id,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "importer_client/python/setup.py", "diff": "+#!/usr/bin/env python\n+# Copyright 2017 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"This is the setup file for the project.\"\"\"\n+from __future__ import unicode_literals\n+\n+import os\n+import glob\n+\n+from setuptools import find_packages\n+from setuptools import setup\n+\n+\n+setup(\n+ name='timesketch-import-client',\n+ version='20200505',\n+ description='Timesketch Import Client',\n+ license='Apache License, Version 2.0',\n+ url='http://www.timesketch.org/',\n+ maintainer='Timesketch development team',\n+ maintainer_email='timesketch-dev@googlegroups.com',\n+ classifiers=[\n+ 'Development Status :: 4 - Beta',\n+ 'Environment :: Console',\n+ 'Operating System :: OS Independent',\n+ 'Programming Language :: Python',\n+ ],\n+ packages=find_packages(),\n+ include_package_data=True,\n+ zip_safe=False,\n+ scripts=glob.glob(os.path.join('tools', '[a-z]*.py')),\n+ install_requires=frozenset([\n+ 'pandas',\n+ 'xlrd',\n+ 'timesketch-api-client',\n+ 'pyyaml',\n+ ]),\n+ )\n" }, { "change_type": "ADD", "old_path": "importer_client/python/timesketch_import_client/__init__.py", "new_path": "importer_client/python/timesketch_import_client/__init__.py", "diff": "" }, { "change_type": "RENAME", "old_path": "api_client/python/timesketch_api_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -29,8 +29,8 @@ import dateutil.parser\nimport pandas\nimport six\n-from . import timeline\n-from . import definitions\n+from timesketch_api_client import timeline\n+from timesketch_api_client import definitions\ndef format_data_frame(dataframe, format_message_string):\n" }, { "change_type": "RENAME", "old_path": "api_client/python/timesketch_api_client/importer_test.py", "new_path": "importer_client/python/timesketch_import_client/importer_test.py", "diff": "" }, { "change_type": "RENAME", "old_path": "api_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -25,8 +25,8 @@ from typing import Dict\nimport yaml\nfrom timesketch_api_client import client\n-from timesketch_api_client import importer\nfrom timesketch_api_client import sketch\n+from timesketch_import_client import importer\nlogging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))\n" } ]
Python
Apache License 2.0
google/timesketch
Moving the importer into a separate directory and a library.
263,133
05.05.2020 10:53:08
0
9b074bb1ce699935ae3bbdec256a9edca2db45f5
Updating API importer documentation.
[ { "change_type": "MODIFY", "old_path": "docs/UploadDataViaAPI.md", "new_path": "docs/UploadDataViaAPI.md", "diff": "@@ -24,6 +24,12 @@ parsed or have readily available, but they are not in the correct format that\nTimesketch requires or you want an automatic way to import the data, or a way to\nbuilt an importer into your already existing toolsets.\n+This is therefore useful for uploading CSV or JSON files, or through other code\n+that processes data to stream to Timesketch. The importer takes in simple\n+configuration parameters to make the necessary adjustments to the data so that\n+it can be ingested by Timesketch. In the future these adjustments will be\n+configurable using a config file, until then a more manual approach is needed.\n+\n## Basics\nThe importer will take as an input either:\n@@ -96,7 +102,7 @@ connecting to a Timesketch instance.\nimport pandas as pd\nfrom timesketch_api_client import client\n-from timesketch_api_client import importer\n+from timesketch_import_client import importer\n...\ndef action():\n@@ -182,8 +188,8 @@ The function `add_file` in the importer is used to add a file.\nHere is an example of how the importer can be used:\n```\n-from timesketch_api_client import importer\nfrom timesketch_api_client import client\n+from timesketch_import_client import importer\n...\n@@ -207,7 +213,7 @@ and the final plaso storage file reassambled.\n```\nfrom timesketch_api_client import client\n-from timesketch_api_client import importer\n+from timesketch_import_client import importer\n...\ndef action():\n" } ]
Python
Apache License 2.0
google/timesketch
Updating API importer documentation.
263,133
05.05.2020 11:02:00
0
6b5c6a6e4dea9c5d8124d693565c8d68b880d903
Fixing test file to include the importer.
[ { "change_type": "MODIFY", "old_path": "run_tests.py", "new_path": "run_tests.py", "diff": "@@ -10,15 +10,15 @@ import argparse\ndef run_python_tests(coverage=False):\ntry:\nif coverage:\n- subprocess.check_call(\n+ subprocess.check_call((\n'nosetests --with-coverage'\n- + ' --cover-package=timesketch_api_client,timesketch'\n- + ' api_client/python/ timesketch/',\n- shell=True,\n- )\n+ ' --cover-package=timesketch_api_client,'\n+ 'timesketch_import_client,timesketch'\n+ ' api_client/python/ timesketch/'), shell=True)\nelse:\nsubprocess.check_call(\n- ['nosetests', '-x', 'timesketch/', 'api_client/python/'])\n+ ['nosetests', '-x', 'timesketch/', 'api_client/python/',\n+ 'importer_client/python'])\nfinally:\nsubprocess.check_call(['rm', '-f', '.coverage'])\n" } ]
Python
Apache License 2.0
google/timesketch
Fixing test file to include the importer.
263,133
05.05.2020 11:39:07
0
d521550f340ea4941593d1083e072ac99b5d3fc9
Adding importer to travis configs
[ { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "@@ -42,6 +42,7 @@ if test ${MODE} = \"dpkg\"; then\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y ${DPKG_PACKAGES}\";\ndocker exec cd api_client/python && python setup.py build && python setup.py install\n+ docker exec cd importer_client/python && python setup.py build && python setup.py install\ndocker exec cd ../../\ndocker cp ../timesketch ${CONTAINER_NAME}:/\n@@ -49,9 +50,11 @@ elif test ${MODE} = \"pypi\"; then\npip install -r requirements.txt;\npip install -r test_requirements.txt;\ncd api_client/python && python setup.py build && python setup.py install\n+ cd importer_client/python && python setup.py build && python setup.py install\nelif test ${TRAVIS_OS_NAME} = \"linux\"; then\npip3 install -r requirements.txt;\npip3 install -r test_requirements.txt;\ncd api_client/python && python setup.py build && python setup.py install\n+ cd importer_client/python && python setup.py build && python setup.py install\nfi\n" } ]
Python
Apache License 2.0
google/timesketch
Adding importer to travis configs
263,133
05.05.2020 12:35:07
0
351c0691ab91d78bc67ad04c27a8dfa97ec57741
Adding directory traversal to travis config.
[ { "change_type": "MODIFY", "old_path": "config/travis/install.sh", "new_path": "config/travis/install.sh", "diff": "@@ -42,6 +42,7 @@ if test ${MODE} = \"dpkg\"; then\ndocker exec -e \"DEBIAN_FRONTEND=noninteractive\" ${CONTAINER_NAME} sh -c \"apt-get install -y ${DPKG_PACKAGES}\";\ndocker exec cd api_client/python && python setup.py build && python setup.py install\n+ docker exec cd ../../\ndocker exec cd importer_client/python && python setup.py build && python setup.py install\ndocker exec cd ../../\ndocker cp ../timesketch ${CONTAINER_NAME}:/\n@@ -50,11 +51,13 @@ elif test ${MODE} = \"pypi\"; then\npip install -r requirements.txt;\npip install -r test_requirements.txt;\ncd api_client/python && python setup.py build && python setup.py install\n+ cd ../../\ncd importer_client/python && python setup.py build && python setup.py install\nelif test ${TRAVIS_OS_NAME} = \"linux\"; then\npip3 install -r requirements.txt;\npip3 install -r test_requirements.txt;\ncd api_client/python && python setup.py build && python setup.py install\n+ cd ../../\ncd importer_client/python && python setup.py build && python setup.py install\nfi\n" } ]
Python
Apache License 2.0
google/timesketch
Adding directory traversal to travis config.
263,133
05.05.2020 16:25:26
0
56a71309e0c8c9c6dadc376ce0d25c99c578117c
Adding a formatter.yaml file and moving functions to utils as well as adding functionality.
[ { "change_type": "ADD", "old_path": "importer_client/python/timesketch_import_client/data/__init__.py", "new_path": "importer_client/python/timesketch_import_client/data/__init__.py", "diff": "" }, { "change_type": "ADD", "old_path": null, "new_path": "importer_client/python/timesketch_import_client/data/formatter.yaml", "diff": "+# This YAML file defines how to process log files.\n+# The parameters here can be defined either as arguments\n+# to the import streamer, as a separate config file\n+# or in this default config.\n+#\n+# The format of the file is:\n+#\n+# name:\n+# message: <format_string>\n+# timestamp_desc: <description>\n+# encoding: <encoding>\n+# data_type: <data_type>\n+# columns: <list_of_columns>\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -31,19 +31,7 @@ import six\nfrom timesketch_api_client import timeline\nfrom timesketch_api_client import definitions\n-\n-\n-def format_data_frame(dataframe, format_message_string):\n- \"\"\"Add a message field to a data frame using a format message string.\"\"\"\n- dataframe['message'] = ''\n-\n- formatter = string.Formatter()\n- for literal_text, field, _, _ in formatter.parse(format_message_string):\n- dataframe['message'] = dataframe['message'] + literal_text\n-\n- if field:\n- dataframe['message'] = dataframe[\n- 'message'] + dataframe[field].astype(str)\n+from timesketch_import_client import utils\nclass ImportStreamer(object):\n@@ -57,8 +45,9 @@ class ImportStreamer(object):\n# chunking it up into smaller pieces.\nDEFAULT_FILESIZE_THRESHOLD = 104857600 # 100 Mb.\n- # Define a default encoding for processing text files.\n+ # Define default values for few of the variable.\nDEFAULT_TEXT_ENCODING = 'utf-8'\n+ DEFAULT_TIMESTAMP_DESC = 'Time Logged'\ndef __init__(self):\n\"\"\"Initialize the upload streamer.\"\"\"\n@@ -71,11 +60,11 @@ class ImportStreamer(object):\nself._sketch = None\nself._timeline_id = None\nself._timeline_name = None\n- self._timestamp_desc = None\nself._chunk = 1\nself._text_encoding = self.DEFAULT_TEXT_ENCODING\n+ self._timestamp_desc = self.DEFAULT_TIMESTAMP_DESC\nself._threshold_entry = self.DEFAULT_ENTRY_THRESHOLD\nself._threshold_filesize = self.DEFAULT_FILESIZE_THRESHOLD\n@@ -95,8 +84,11 @@ class ImportStreamer(object):\nmy_dict: a dictionary that may be missing few fields needed\nfor Timesketch.\n\"\"\"\n- if 'message' not in my_dict and self._format_string:\n- my_dict['message'] = self._format_string.format(**my_dict)\n+ if 'message' not in my_dict:\n+ format_string = (\n+ self._format_string or utils.get_combined_message_string(\n+ mydict=my_dict))\n+ my_dict['message'] = format_string.format(**my_dict)\n_ = my_dict.setdefault('timestamp_desc', self._timestamp_desc)\n@@ -140,8 +132,11 @@ class ImportStreamer(object):\nReturns:\nA pandas data frame with added columns needed for Timesketch.\n\"\"\"\n- if 'message' not in data_frame and self._format_string:\n- format_data_frame(data_frame, self._format_string)\n+ if 'message' not in data_frame:\n+ format_string = (\n+ self._format_string or utils.get_combined_message_string(\n+ dataframe=data_frame))\n+ utils.format_data_frame(data_frame, format_string)\nif 'timestamp_desc' not in data_frame:\ndata_frame['timestamp_desc'] = self._timestamp_desc\n" }, { "change_type": "ADD", "old_path": null, "new_path": "importer_client/python/timesketch_import_client/utils.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Some utility functions for the Timesketch importer.\"\"\"\n+\n+import string\n+\n+\n+# When there is no defined format message string a default one is used\n+# that is generated using the available columns or keys in the dataset.\n+# This constant defines what columns or keys should be skipped while\n+# generating this message field.\n+FIELDS_TO_SKIP_IN_FORMAT_STRING = frozenset([\n+ 'timestamp_desc', 'time', 'timestamp', 'data_type', 'datetime',\n+ 'source_short', 'source_long', 'source'\n+])\n+# This constant defines patterns that are used to skip columns or keys\n+# that start with the strings defined here.\n+FIELDS_TO_SKIP_STARTSWITH = frozenset([\n+ '_',\n+])\n+\n+\n+def format_data_frame(dataframe, format_message_string):\n+ \"\"\"Add a message field to a data frame using a format message string.\"\"\"\n+ dataframe['message'] = ''\n+\n+ formatter = string.Formatter()\n+ for literal_text, field, _, _ in formatter.parse(format_message_string):\n+ dataframe['message'] = dataframe['message'] + literal_text\n+\n+ if field:\n+ dataframe['message'] = dataframe[\n+ 'message'] + dataframe[field].astype(str)\n+\n+\n+def get_combined_message_string(dataframe=None, mydict=None):\n+ \"\"\"Returns a message string by combining all columns from a DataFrame/dict.\n+\n+ Args:\n+ dataframe (pandas.DataFrame): the data frame containing the data. Used\n+ to get column names for the message string if supplied.\n+ mydict (dict): if supplied the dictionary keys will be used to\n+ construct the message string.\n+\n+ Raises:\n+ ValueError if neither dataframe nor a dictionary is supplied.\n+\n+ Returns:\n+ A string that can be used as a default message string.\n+ \"\"\"\n+ if dataframe is None and mydict is None:\n+ raise ValueError('Need to define either a dict or a DataFrame')\n+\n+ if mydict:\n+ my_list = mydict.keys()\n+ else:\n+ my_list = list(dataframe.columns)\n+\n+ fields_to_delete = list(set(my_list).intersection(\n+ FIELDS_TO_SKIP_IN_FORMAT_STRING))\n+ for field in fields_to_delete:\n+ index = my_list.index(field)\n+ _ = my_list.pop(index)\n+\n+ for del_field in FIELDS_TO_SKIP_STARTSWITH:\n+ for index, field in enumerate(my_list):\n+ if field.startswith(del_field):\n+ _ = my_list.pop(index)\n+\n+ string_values = [\n+ '[{0:s}] = {{{0:s}}}'.format(x) for x in my_list]\n+ return ', '.join(string_values)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a formatter.yaml file and moving functions to utils as well as adding functionality.
263,133
05.05.2020 17:09:44
0
b64bbcd4074204b846c7f83bf3329b7668744997
Doing a query for timelines in file uploads
[ { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -1975,6 +1975,12 @@ class UploadFileResource(ResourceMixin, Resource):\nif searchindex:\nsearchindex.set_status('processing')\n+ timeline = Timeline.query.filter_by(\n+ name=searchindex.name,\n+ description=searchindex.description,\n+ sketch=sketch,\n+ user=current_user,\n+ searchindex=searchindex).first()\nelse:\n# Create the search index in the Timesketch database\nsearchindex = SearchIndex.get_or_create(\n" } ]
Python
Apache License 2.0
google/timesketch
Doing a query for timelines in file uploads
263,133
06.05.2020 11:12:42
0
fc43c47f13e8486c5532cc4db75ef310824d49e7
Adding functions to read and parse config files.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/setup.py", "new_path": "importer_client/python/setup.py", "diff": "@@ -36,6 +36,10 @@ setup(\n'Operating System :: OS Independent',\n'Programming Language :: Python',\n],\n+ data_files=[\n+ ('data', glob.glob(\n+ os.path.join('timesketch_import_client', 'data', '*.yaml'))),\n+ ],\npackages=find_packages(),\ninclude_package_data=True,\nzip_safe=False,\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/data/__init__.py", "new_path": "importer_client/python/timesketch_import_client/data/__init__.py", "diff": "+# Copyright 2019 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch data import configuration.\"\"\"\n+from __future__ import unicode_literals\n+\n+import codecs\n+import logging\n+import os\n+\n+import yaml\n+\n+\n+logger = logging.getLogger('import_client_config_loader')\n+\n+DEFAULT_FILE = 'formatter.yaml'\n+\n+\n+def load_config(file_path=''):\n+ \"\"\"Loads YAML config and returns a list of dict with the results.\n+\n+ Args:\n+ file_path (str): path to the YAML config file. This is optional\n+ and if not defined the default formatter.yaml file will be\n+ used that comes with the tool.\n+\n+ Returns:\n+ A list with dicts containing the loaded YAML config.\n+ \"\"\"\n+ if not file_path:\n+ base_path = os.path.dirname(__file__)\n+ file_path = os.path.join(base_path, DEFAULT_FILE)\n+\n+ if not file_path.endswith('.yaml'):\n+ logger.error('Can\\'t load a config that is not a YAML file.')\n+ return []\n+\n+ if not os.path.isfile(file_path):\n+ logger.error('File path does not exist, unable to load YAML config.')\n+ return []\n+\n+ with codecs.open(file_path, 'r') as fh:\n+ try:\n+ data = yaml.safe_load(fh)\n+ except (AttributeError, yaml.parser.ParserError) as e:\n+ logger.error('Unable to parse YAML file, with error: %s', e)\n+ return []\n+ if not data:\n+ return []\n+ return data\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/data/formatter.yaml", "new_path": "importer_client/python/timesketch_import_client/data/formatter.yaml", "diff": "#\n# The format of the file is:\n#\n-# name:\n-# message: <format_string>\n+# - name:\n+# message: '<format_string>'\n# timestamp_desc: <description>\n+# datetime: <column with time information>\n+# separator: <if a csv file then the separator>\n# encoding: <encoding>\n# data_type: <data_type>\n# columns: <list_of_columns>\n+#\n+# The config fields are either used for configuring the streamer or for\n+# identifying the file. The file identifier is either the use of a data_type\n+# or a list of available columns in the file.\n+#\n+# Configuration parameters:\n+# message - this is the format string for the message attribute. It can\n+# consist of a string with curly brackets for variable\n+# expansion, eg: \"User {user} visited {url}\", would generate\n+# a message string where the attributes \"user\" and \"url\" will\n+# get expanded.\n+#\n+# timestamp_desc - a string value that will be used to set the timestamp\n+# description field.\n+#\n+# datetime - if there is no column called datetime this config can be set\n+# to tell the tool in what column the date information is\n+# stored. Otherwise the tool will attempt to guess based on\n+# column names.\n+#\n+# separator - only applicable for CSV files, if the separator is not a\n+# comma (,) then this variable can be set to indicate the\n+# separator value.\n+#\n+# encoding - if the file encoding is not UTF-8 it can be set here.\n+#\n+# Identification parameters:\n+# data_type - this can be used if there is a field in the dataset that\n+# is called \"data_type\". There can only be one value of\n+# \"data_type\" in the data set for it to be matched on.\n+#\n+# columns - a list of columns that should be present in the data file\n+# for this to be a match on.\n+\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "from __future__ import unicode_literals\nimport codecs\n-import datetime\nimport io\nimport json\nimport logging\nimport math\nimport os\n-import string\nimport time\nimport uuid\n-import dateutil.parser\nimport pandas\n-import six\nfrom timesketch_api_client import timeline\nfrom timesketch_api_client import definitions\n+from timesketch_import_client import data as data_config\nfrom timesketch_import_client import utils\n@@ -52,10 +49,13 @@ class ImportStreamer(object):\ndef __init__(self):\n\"\"\"Initialize the upload streamer.\"\"\"\nself._count = 0\n+ self._csv_delimiter = None\nself._data_lines = []\n+ self._datetime_field = None\nself._format_string = None\nself._index = uuid.uuid4().hex\nself._last_response = None\n+ self._logfile_config = []\nself._resource_url = ''\nself._sketch = None\nself._timeline_id = None\n@@ -93,6 +93,12 @@ class ImportStreamer(object):\n_ = my_dict.setdefault('timestamp_desc', self._timestamp_desc)\nif 'datetime' not in my_dict:\n+ date = ''\n+ if self._datetime_field:\n+ value = my_dict.get(self._datetime_field)\n+ if value:\n+ date = utils.get_datestring_from_value(value)\n+ if not date:\nfor key in my_dict:\nkey_string = key.lower()\nif 'time' not in key_string:\n@@ -102,20 +108,12 @@ class ImportStreamer(object):\ncontinue\nvalue = my_dict[key]\n- if isinstance(value, six.string_types):\n- try:\n- date = dateutil.parser.parse(my_dict[key])\n- my_dict['datetime'] = date.isoformat()\n- break\n- except ValueError:\n- continue\n- else:\n- try:\n- date = datetime.datetime.utcfromtimestamp(value / 1e6)\n- my_dict['datetime'] = date.isoformat()\n+ date = utils.get_datestring_from_value(value)\n+ if date:\nbreak\n- except ValueError:\n- continue\n+\n+ if date:\n+ my_dict['datetime'] = date\n# We don't want to include any columns that start with an underscore.\nunderscore_columns = [x for x in my_dict if x.startswith('_')]\n@@ -142,6 +140,15 @@ class ImportStreamer(object):\ndata_frame['timestamp_desc'] = self._timestamp_desc\nif 'datetime' not in data_frame:\n+ if self._datetime_field and self._datetime_field in data_frame:\n+ try:\n+ data_frame['timestamp'] = pandas.to_datetime(\n+ data_frame[self._datetime_field], utc=True)\n+ except ValueError as e:\n+ logging.info(\n+ 'Unable to convert timestamp in column: %s, error %s',\n+ self._datetime_field, e)\n+ else:\nfor column in data_frame.columns[\ndata_frame.columns.str.contains('time', case=False)]:\nif column.lower() == 'timestamp_desc':\n@@ -153,8 +160,8 @@ class ImportStreamer(object):\nbreak\nexcept ValueError as e:\nlogging.info(\n- 'Unable to convert timestamp in column: %s, error %s',\n- column, e)\n+ 'Unable to convert timestamp in column: '\n+ '%s, error %s', column, e)\nif 'timestamp' in data_frame:\ndata_frame['datetime'] = data_frame['timestamp'].dt.strftime(\n@@ -165,6 +172,33 @@ class ImportStreamer(object):\ndata_frame.columns[~data_frame.columns.str.contains('^_')])\nreturn data_frame[columns]\n+ def _load_config(self, config_dict):\n+ \"\"\"Sets up the streamer based on a configuration dict.\n+\n+ Args:\n+ config_dict (dict): A dictionary that contains\n+ configuration details for the streamer.\n+ \"\"\"\n+ message = config_dict.get('message')\n+ if message:\n+ self.set_message_format_string(message)\n+\n+ timestamp_desc = config_dict.get('timestamp_desc')\n+ if timestamp_desc:\n+ self.set_timestamp_description(timestamp_desc)\n+\n+ separator = config_dict.get('separator')\n+ if separator:\n+ self.set_csv_delimiter(separator)\n+\n+ encoding = config_dict.get('encoding')\n+ if encoding:\n+ self.set_text_encoding(encoding)\n+\n+ datetime_string = config_dict.get('datetime')\n+ if datetime_string:\n+ self.set_datetime_column(datetime_string)\n+\ndef _ready(self):\n\"\"\"Check whether all variables have been set.\n@@ -334,6 +368,24 @@ class ImportStreamer(object):\nraise TypeError('Entry object needs to be a DataFrame')\nsize = data_frame.shape[0]\n+\n+ # Read through config files to see if we can configure the streamer.\n+ for config in self._logfile_config:\n+ data_type = config.get('data_type')\n+ if data_type and 'data_type' in data_frame:\n+ data_types = data_frame.data_type.unique()\n+ if len(data_types) == 1:\n+ if data_type == data_types[0]:\n+ self._load_config(config)\n+ break\n+ column_string = config.get('columns')\n+ if not column_string:\n+ continue\n+ columns = set(column_string.split(','))\n+ df_columns = set(data_frame.columns)\n+ if columns == df_columns:\n+ self._load_config(config)\n+\ndata_frame_use = self._fix_data_frame(data_frame)\nif 'datetime' not in data_frame_use:\n@@ -452,6 +504,8 @@ class ImportStreamer(object):\nfile_ending = filepath.lower().split('.')[-1]\nif file_ending == 'csv':\n+ if self._csv_delimiter:\n+ delimiter = self._csv_delimiter\nwith codecs.open(\nfilepath, 'r', encoding=self._text_encoding,\nerrors='replace') as fh:\n@@ -551,15 +605,37 @@ class ImportStreamer(object):\n\"\"\"Returns the last response from an upload.\"\"\"\nreturn self._last_response\n- def set_sketch(self, sketch):\n- \"\"\"Set a client for the streamer.\n+ def set_config_file(self, file_path=''):\n+ \"\"\"Loads a YAML config file describing the log file config.\n+\n+ This function reads a YAML config file, and uses the config\n+ from there to set up the streamer config. The config file\n+ can be a single entry and used to just setup the streamer\n+ or it can define a list of files and set the streamer\n+ depending on the input file itself.\nArgs:\n- sketch: an instance of Sketch that is used to communicate\n- with the API to upload data.\n+ file_path (str): the path to the config file. If not\n+ supplied the default value of features.yaml that\n+ comes with the tool is chosen.\n\"\"\"\n- self._sketch = sketch\n- self._resource_url = '{0:s}/upload/'.format(sketch.api.api_root)\n+ config = data_config.load_config(file_path)\n+ if isinstance(config, (list, tuple)):\n+ self._logfile_config = config\n+ return\n+\n+ # This is a single config dict.\n+ if isinstance(config, dict):\n+ self._load_config(config)\n+ self._logfile_config = [config]\n+\n+ def set_csv_delimiter(self, delimiter):\n+ \"\"\"Set the CSV delimiter for CSV file parsing.\"\"\"\n+ self._csv_delimiter = delimiter\n+\n+ def set_datetime_column(self, column):\n+ \"\"\"Sets the column where the timestamp is defined in.\"\"\"\n+ self._datetime_field = column\ndef set_entry_threshold(self, threshold):\n\"\"\"Set the threshold for number of entries per chunk.\"\"\"\n@@ -569,10 +645,24 @@ class ImportStreamer(object):\n\"\"\"Set the threshold for file size per chunk.\"\"\"\nself._threshold_filesize = threshold\n+ def set_index_name(self, index):\n+ \"\"\"Set the index name.\"\"\"\n+ self._index = index\n+\ndef set_message_format_string(self, format_string):\n\"\"\"Set the message format string.\"\"\"\nself._format_string = format_string\n+ def set_sketch(self, sketch):\n+ \"\"\"Set a client for the streamer.\n+\n+ Args:\n+ sketch: an instance of Sketch that is used to communicate\n+ with the API to upload data.\n+ \"\"\"\n+ self._sketch = sketch\n+ self._resource_url = '{0:s}/upload/'.format(sketch.api.api_root)\n+\ndef set_text_encoding(self, encoding):\n\"\"\"Set the default encoding for reading text files.\"\"\"\nself._text_encoding = encoding\n@@ -581,10 +671,6 @@ class ImportStreamer(object):\n\"\"\"Set the timeline name.\"\"\"\nself._timeline_name = name\n- def set_index_name(self, index):\n- \"\"\"Set the index name.\"\"\"\n- self._index = index\n-\ndef set_timestamp_description(self, description):\n\"\"\"Set the timestamp description field.\"\"\"\nself._timestamp_desc = description\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/utils.py", "new_path": "importer_client/python/timesketch_import_client/utils.py", "diff": "# limitations under the License.\n\"\"\"Some utility functions for the Timesketch importer.\"\"\"\n+import datetime\nimport string\n+import six\n+import dateutil.parser\n+\n# When there is no defined format message string a default one is used\n# that is generated using the available columns or keys in the dataset.\n@@ -81,3 +85,30 @@ def get_combined_message_string(dataframe=None, mydict=None):\nstring_values = [\n'[{0:s}] = {{{0:s}}}'.format(x) for x in my_list]\nreturn ', '.join(string_values)\n+\n+\n+def get_datestring_from_value(value):\n+ \"\"\"Returns an empty string or a date value.\n+\n+ Args:\n+ value (any): A string or an int/float that contains a timestamp\n+ value that can be parsed into a datetime.\n+\n+ Returns:\n+ A string with the timestamp in ISO 8601 or an empty string if not\n+ able to parse the timestamp.\n+ \"\"\"\n+ if isinstance(value, six.string_types):\n+ try:\n+ date = dateutil.parser.parse(value)\n+ return date.isoformat()\n+ except ValueError:\n+ pass\n+\n+ if isinstance(value, (int, float)):\n+ try:\n+ date = datetime.datetime.utcfromtimestamp(value / 1e6)\n+ return date.isoformat()\n+ except ValueError:\n+ pass\n+ return ''\n" } ]
Python
Apache License 2.0
google/timesketch
Adding functions to read and parse config files.
263,133
06.05.2020 12:51:34
0
5472333a076a8eeb57bba4cfdad7370a6c63d7a5
Adding a redline example to the formatter file.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/data/formatter.yaml", "new_path": "importer_client/python/timesketch_import_client/data/formatter.yaml", "diff": "# columns - a list of columns that should be present in the data file\n# for this to be a match on.\n+- redline:\n+ message: 'User: {UniqueUsername} did {EventType}: {Summary1} - {Summary2} - {Summary3}'\n+ timestamp_desc: Event Logged\n+ datetime: EventTimestamp\n+ columns: 'EventTimestamp,EventType,AuditType,Summary1,Summary2,Summary3,UniqueUsername'\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -118,6 +118,9 @@ def upload_file(\nif time_desc:\nstreamer.set_timestamp_description(time_desc)\n+ log_config_file = config_dict.get('log_config_file', '')\n+ streamer.set_config_file(log_config_file)\n+\nentry_threshold = config_dict.get('entry_threshold')\nif entry_threshold:\nstreamer.set_entry_threshold(entry_threshold)\n@@ -171,6 +174,13 @@ if __name__ == '__main__':\ndefault='', metavar='FILEPATH', dest='config_file', help=(\n'Path to a YAML config file that can be used to store '\n'all parameters to this tool (except this path)'))\n+ config_group.add_argument(\n+ '--log-config-file', '--log_config_file', '--lc', action='store',\n+ type=str, default='', metavar='FILEPATH', dest='log_config_file',\n+ help=(\n+ 'Path to a YAML config file that defines the config for parsing '\n+ 'and setting up file parsing. By default formatter.yaml that '\n+ 'comes with the importer will be used.'))\nconfig_group.add_argument(\n'--host', '--hostname', '--host-uri', '--host_uri', dest='host',\ntype=str, default='', action='store',\n@@ -286,8 +296,10 @@ if __name__ == '__main__':\n'entry_threshold', 0),\n'size_threshold': options.size_threshold or config_options.get(\n'size_threshold', 0),\n+ 'log_config_file': options.log_config_file,\n}\n+\nlogger.info('Uploading file.')\nresult = upload_file(\nmy_sketch=sketch, config_dict=config, file_path=options.path)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a redline example to the formatter file.
263,133
06.05.2020 15:18:29
0
320a1b8de3e7a4c8d3d24af65edbca1573cc7c2d
Adding a default load when using the with statement
[ { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -709,6 +709,8 @@ class ImportStreamer(object):\ndef __enter__(self):\n\"\"\"Make it possible to use \"with\" statement.\"\"\"\nself._reset()\n+ # Load the default config file to configure the tool with.\n+ self.set_config_file()\nreturn self\n# pylint: disable=unused-argument\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a default load when using the with statement
263,133
06.05.2020 19:43:29
0
f1915123aaad153ba3bee972219211e4bdc90ffc
Adding default filename to imports.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/importer.py", "new_path": "importer_client/python/timesketch_import_client/importer.py", "diff": "@@ -518,10 +518,16 @@ class ImportStreamer(object):\nif not os.path.isfile(filepath):\nraise TypeError('Entry object needs to be a file that exists.')\n+ if not self._timeline_name:\n+ base_path = os.path.basename(filepath)\n+ default_timeline_name, _, _ = base_path.rpartition('.')\n+ self.set_timeline_name(default_timeline_name)\n+\nfile_ending = filepath.lower().split('.')[-1]\nif file_ending == 'csv':\nif self._csv_delimiter:\ndelimiter = self._csv_delimiter\n+\nwith codecs.open(\nfilepath, 'r', encoding=self._text_encoding,\nerrors='replace') as fh:\n@@ -531,6 +537,7 @@ class ImportStreamer(object):\nself.add_data_frame(chunk_frame, part_of_iter=True)\nelif file_ending == 'plaso':\nself._upload_binary_file(filepath)\n+\nelif file_ending == 'jsonl':\nwith codecs.open(\nfilepath, 'r', encoding=self._text_encoding,\n@@ -540,6 +547,7 @@ class ImportStreamer(object):\nself.add_json(line.strip())\nexcept TypeError as e:\nlogger.error('Unable to decode line: {0!s}'.format(e))\n+\nelse:\nraise TypeError(\n'File needs to have a file extension of: .csv, .jsonl or '\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -281,8 +281,10 @@ if __name__ == '__main__':\nlogger.error('Unable to get sketch ID: {0:d}'.format(sketch_id))\nsys.exit(1)\n+ filename = os.path.basename(options.path)\n+ default_timeline_name, _, _ = filename.rpartition('.')\nconf_timeline_name = options.timeline_name or config_options.get(\n- 'timeline_name', 'unnamed_timeline_imported_from_importer')\n+ 'timeline_name', default_timeline_name)\nconfig = {\n'message_format_string': options.format_string or config_options.get(\n" } ]
Python
Apache License 2.0
google/timesketch
Adding default filename to imports.
263,133
07.05.2020 12:54:03
0
e66fc4f0fd2a06776ee165d865cd78266cf71a18
Incrementing the version of the importer client.
[ { "change_type": "MODIFY", "old_path": "importer_client/python/setup.py", "new_path": "importer_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-import-client',\n- version='20200505',\n+ version='20200507',\ndescription='Timesketch Import Client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Incrementing the version of the importer client.
263,133
07.05.2020 15:05:03
0
96819adedb41bdfb9a92041e2fa5a36a2579424e
Changing error reporting.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -644,7 +644,7 @@ class Sketch(resource.BaseResource):\nif response.status_code == 200:\nreturn response.json()\n- return '[{0:d}] {1:s} {2:s}'.format(\n+ return '[{0:d}] {1!s} {2!s}'.format(\nresponse.status_code, response.reason, response.text)\ndef run_analyzer(\n@@ -718,7 +718,7 @@ class Sketch(resource.BaseResource):\nif response.status_code == 200:\nreturn response.json()\n- return '[{0:d}] {1:s} {2:s}'.format(\n+ return '[{0:d}] {1!s} {2!s}'.format(\nresponse.status_code, response.reason, response.text)\ndef remove_acl(self, user_list=None, group_list=None, remove_public=False):\n" } ]
Python
Apache License 2.0
google/timesketch
Changing error reporting. (#1188)
263,133
11.05.2020 15:17:07
0
f830791cccbf5915d0c0042cb1d226c56bf56579
Adding a config and a crypto module to the API client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200505',\n+ version='20200512',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n@@ -38,6 +38,7 @@ setup(\nzip_safe=False,\ninstall_requires=frozenset([\n'pandas',\n+ 'crytography',\n'requests',\n'altair',\n'google-auth',\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch API library for reading/parsing configs.\"\"\"\n+from __future__ import unicode_literals\n+\n+import configparser\n+import logging\n+import os\n+\n+from . import client\n+#from . import crypto\n+\n+\n+logger = logging.getLogger('config_assistance_api')\n+\n+\n+class ConfigAssistant:\n+ \"\"\"A simple assistant that helps with setting up a Timesketch API client.\n+\n+ This assistant can read and save configs to a file. It also maintains\n+ a state about what config has been passed to it, to assist possible\n+ UIs to understand what is missing in order to setup a Timesketch API\n+ client.\n+\n+ Attributes:\n+ asdfsadf\n+ \"\"\"\n+\n+ # The name of the default config file.\n+ RC_FILENAME = '.timesketchrc'\n+\n+ # The needed items to configure a client.\n+ CLIENT_NEEDED = frozenset([\n+ 'host_uri',\n+ 'username',\n+ 'auth_mode',\n+ ])\n+ OAUTH_CLIENT_NEEDED = frozenset([\n+ 'client_id',\n+ 'client_secret',\n+ ])\n+\n+ def __init__(self):\n+ \"\"\"Initialize the configuration assistant.\"\"\"\n+ self._config = {}\n+\n+ @property\n+ def parameters(self):\n+ \"\"\"Return a list of configured parameters.\"\"\"\n+ return self._config.keys()\n+\n+ @property\n+ def missing(self):\n+ \"\"\"Return a list of missing parameters.\"\"\"\n+ return self.get_missing_config()\n+\n+ def get_config(self, name):\n+ \"\"\"Returns a value for a given config.\n+\n+ Raises:\n+ KeyError: if the config does not exist.\n+ \"\"\"\n+ return self._config[name]\n+\n+ def get_client(self):\n+ \"\"\"Returns a Timesketch API client if possible.\"\"\"\n+\n+ if self.missing:\n+ return None\n+\n+ # Check auth mode and go for crypto client if oauth...\n+ return client.TimesketchApi(\n+ host_uri=self._config.get('host_uri'),\n+ username=self._config.get('username'),\n+ password=self._config.get('password', ''),\n+ verify=self._config.get('verify', True),\n+ client_id=self._config.get('client_id', ''),\n+ client_secret=self._config.get('client_secret', ''),\n+ auth_mode=self._config.get('auth_mode', 'timesketch'),\n+ )\n+\n+ def get_missing_config(self):\n+ \"\"\"Returns a list of configuration parameters that are missing.\"\"\"\n+ needed_set = self.CLIENT_NEEDED\n+ auth_mode = self._config.get('auth_mode', '')\n+ if auth_mode.startswith('oauth'):\n+ needed_set = needed_set.union(self.OAUTH_CLIENT_NEEDED)\n+\n+ configured_set = set(self._config.keys())\n+ return list(needed_set.difference(configured_set))\n+\n+ def has_config(self, name):\n+ \"\"\"Returns a boolean indicating whether a config parameter is set.\n+\n+ Args:\n+ name (str): the name of the configuration.\n+\n+ Returns:\n+ bool: whether the object has been set or not.\n+ \"\"\"\n+ return name.lower() in self._config\n+\n+ def load_config(self, config_file_path=''):\n+ \"\"\"Load the config from file.\n+\n+ Args:\n+ config_file_path (str): Full path to the configuration file,\n+ if not supplied the default path will be used, which is\n+ the file RC_FILENAME inside the user's home directory.\n+\n+ Raises:\n+ IOError if the file does not exist or config does not load.\n+ \"\"\"\n+ if config_file_path:\n+ if not os.path.isfile(config_file_path):\n+ error_msg = (\n+ 'Unable to load config file, file {0:s} does not '\n+ 'exist.').format(config_file_path)\n+ logger.error(error_msg)\n+ raise IOError(error_msg)\n+ else:\n+ home_path = os.path.expanduser('~')\n+ config_file_path = os.path.join(home_path, self.RC_FILENAME)\n+\n+ if not os.path.isfile(config_file_path):\n+ fw = open(config_file_path, 'a')\n+ fw.close()\n+\n+ config = configparser.ConfigParser()\n+ try:\n+ files_read = config.read([config_file_path])\n+ except configparser.MissingSectionHeaderError as e:\n+ raise IOError(\n+ 'Unable to parse config file, with error: {0!s}'.format(e))\n+\n+ if not files_read:\n+ logger.warning('No config read')\n+ return\n+\n+ if 'timesketch' not in config.sections():\n+ logger.warning('No timesketch section in the config')\n+ return\n+\n+ timesketch_config = config['timesketch']\n+ for name, value in timesketch_config.items():\n+ self.set_config(name, value)\n+\n+ def save_config(self, file_path=''):\n+ \"\"\"Save the current config to a file.\n+\n+ Args:\n+ file_path (str): A full path to the location where the\n+ configuration file is to be stored. If not provided the\n+ default location will be used.\n+ \"\"\"\n+ if not file_path:\n+ home_path = os.path.expanduser('~')\n+ file_path = os.path.join(home_path, self.RC_FILENAME)\n+\n+ config = configparser.ConfigParser()\n+ config['timesketch'] = {\n+ 'host_uri': self._config.get('host_uri'),\n+ 'username': self._config.get('username'),\n+ 'verify': self._config.get('verify', True),\n+ 'client_id': self._config.get('client_id', ''),\n+ 'client_secret': self._config.get('client_secret', ''),\n+ 'auth_mode': self._config.get('auth_mode', 'timesketch')\n+ }\n+\n+ with open(file_path, 'w') as fw:\n+ config.write(fw)\n+\n+ def set_config(self, name, value):\n+ \"\"\"Saves a config.\n+\n+ Args:\n+ name (str): the name of the configuration value to be set.\n+ value (object): the value of the configuration object.\n+ \"\"\"\n+ self._config[name.lower()] = value\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/config_test.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Tests for the Timesketch config library for the API client.\"\"\"\n+from __future__ import unicode_literals\n+\n+import unittest\n+import tempfile\n+\n+from . import config\n+\n+\n+class TimesketchConfigAssistantTest(unittest.TestCase):\n+ \"\"\"Test ConfigAssistant.\"\"\"\n+\n+ TEST_CONFIG = \"\"\"\n+[timesketch]\n+host_uri = http://127.0.0.1\n+username = foobar\n+auth_mode = oauth\n+client_id = myidfoo\n+client_secret = sdfa@$FAsASDF132\n+verify = True\n+ \"\"\"\n+\n+ def test_get_missing_config(self):\n+ \"\"\"Test the missing config parameter.\"\"\"\n+ config_obj = config.ConfigAssistant()\n+ config_obj.set_config('host_uri', 'http://127.0.0.1')\n+\n+ missing = config_obj.get_missing_config()\n+ expected_missing = ['auth_mode', 'username']\n+ self.assertEqual(set(expected_missing), set(missing))\n+\n+ config_obj.set_config('username', 'foobar')\n+ missing = config_obj.get_missing_config()\n+ expected_missing = ['auth_mode']\n+ self.assertEqual(set(expected_missing), set(missing))\n+\n+ config_obj.set_config('auth_mode', 'oauth')\n+ missing = config_obj.get_missing_config()\n+ expected_missing = ['client_id', 'client_secret']\n+ self.assertEqual(set(expected_missing), set(missing))\n+\n+ def test_has_config(self):\n+ \"\"\"Test the has_config function.\"\"\"\n+ config_obj = config.ConfigAssistant()\n+ config_obj.set_config('host_uri', 'http://127.0.0.1')\n+ self.assertTrue(config_obj.has_config('host_uri'))\n+ self.assertFalse(config_obj.has_config('foobar'))\n+\n+ def test_load_config(self):\n+ \"\"\"Test loading config.\"\"\"\n+ config_obj = config.ConfigAssistant()\n+ with tempfile.NamedTemporaryFile(mode='w') as fw:\n+ fw.write(self.TEST_CONFIG)\n+\n+ fw.seek(0)\n+ config_obj.load_config(fw.name)\n+ expected_fields = [\n+ 'host_uri', 'auth_mode', 'verify', 'client_id',\n+ 'client_secret', 'username']\n+ self.assertEqual(set(expected_fields), set(config_obj.parameters))\n+\n+ self.assertEqual(config_obj.get_config('host_uri'), 'http://127.0.0.1')\n+\n+ #def test_save_config(self, file_path=''):\n+ def test_save_config(self):\n+ \"\"\"Test saving the config.\"\"\"\n+ config_obj = config.ConfigAssistant()\n+ config_obj.set_config('host_uri', 'http://127.0.0.1')\n+ config_obj.set_config('username', 'foobar')\n+ config_obj.set_config('auth_mode', 'oauth')\n+ config_obj.set_config('client_id', 'myidfoo')\n+ config_obj.set_config('client_secret', 'sdfa@$FAsASDF132')\n+\n+ data = ''\n+ with tempfile.NamedTemporaryFile(mode='w') as fw:\n+ config_obj.save_config(fw.name)\n+\n+ fw.seek(0)\n+ with open(fw.name, 'r') as fh:\n+ data = fh.read()\n+\n+ lines = [x.strip() for x in data.split('\\n') if x]\n+ expected_lines = [\n+ x.strip() for x in self.TEST_CONFIG.split('\\n') if x.strip()]\n+ self.assertEqual(set(lines), set(expected_lines))\n+\n+ def test_set_config(self):\n+ \"\"\"Test the set config.\"\"\"\n+ config_obj = config.ConfigAssistant()\n+ config_obj.set_config('host_uri', 'http://127.0.0.1')\n+\n+ self.assertTrue(config_obj.has_config('host_uri'))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch API crypto storage library for OAUTH client.\"\"\"\n+from __future__ import unicode_literals\n+\n+import base64\n+import os\n+import getpass\n+import json\n+import logging\n+import random\n+import string\n+import stat\n+\n+import cryptography\n+from google.oauth2 import credentials\n+\n+\n+logger = logging.getLogger('crypto_client_api')\n+\n+\n+class CredentialStorage:\n+ \"\"\"Class to store and retrieve stored credentials.\"\"\"\n+\n+ # A default shared secret that will be used as part of the key.\n+ SHARED_KEY = 'thetta er mjog leynt'\n+\n+ # The default filename of the token file.\n+ DEFAULT_CREDENTIAL_FILENAME = '.timesketch.token'\n+\n+ # The number of characters in the random part of the default key.\n+ RANDOM_KEY_LENGTH = 20\n+\n+ def __init__(self):\n+ \"\"\"Initialize the class.\"\"\"\n+ self._user = getpass.getuser()\n+ home_path = os.path.expanduser('~')\n+ self._filepath = os.path.join(\n+ home_path, self.DEFAULT_CREDENTIAL_FILENAME)\n+\n+ def _get_default_key(self):\n+ \"\"\"Returns the default encryption key.\"\"\"\n+ letters = string.ascii_letters\n+ random_string = ''.join(\n+ random.choice(letters) for _ in range(self.RANDOM_KEY_LENGTH))\n+\n+ key_string = b'{0:s}{1:s}{2:s}'.format(\n+ getpass.getuser(), random_string, self.SHARED_KEY)\n+\n+ return random_string, base64.b64encode(key_string)\n+\n+ def set_filepath(self, file_path):\n+ \"\"\"Set the filepath to the credential file.\"\"\"\n+ if os.path.isfile(file_path):\n+ self._filepath = file_path\n+\n+ def save_credentials(self, cred_obj, file_path=''):\n+ \"\"\"Save credential data to a token file.\n+\n+ This function will create an EncryptedFile (go/encryptedfile)\n+ in the user's home directory (~/.timesketch.token by default)\n+ that contains a stored copy of the credential object.\n+\n+ Args:\n+ cred_obj (google.oauth2.credentials.Credentials): the credential\n+ object that is to be stored on disk.\n+ file_path (str): Full path to the file storing the saved\n+ credentials.\n+ \"\"\"\n+ if not file_path:\n+ file_path = self._filepath\n+\n+ if not os.path.isfile(file_path):\n+ logger.error(\n+ 'Unable to save file, path %s does not exist.', file_path)\n+ return\n+\n+ data = {\n+ 'token': cred_obj.token,\n+ '_scopes': getattr(cred_obj, '_scopes', []),\n+ '_refresh_token': getattr(cred_obj, '_refresh_token', ''),\n+ '_id_token': getattr(cred_obj, '_id_token', ''),\n+ '_token_uri': getattr(cred_obj, '_token_uri', ''),\n+ '_client_id': getattr(cred_obj, '_client_id', ''),\n+ '_client_secret': getattr(cred_obj, '_client_secret', ''),\n+ }\n+ if cred_obj.expiry:\n+ data['expiry'] = cred_obj.expiry.isoformat()\n+ data_string = json.dumps(data)\n+\n+ random_string, key = self._get_default_key()\n+ fernet = cryptography.fernet.Fernet(key)\n+\n+ with open(file_path, 'w') as fw:\n+ fw.write(random_string)\n+ fw.write(fernet.encrypt(data_string))\n+\n+ file_permission = stat.S_IREAD | stat.S_IWRITE\n+ os.chmod(file_path, file_permission)\n+ logger.info('Credentials saved to: %s', file_path)\n+\n+ def load_credentials(self, file_path=''):\n+ \"\"\"Load credentials from a file and return a credential object.\n+\n+ Args:\n+ file_path (str): Full path to the file storing the saved\n+ credentials.\n+\n+ Returns:\n+ Credential object (oauth2.credentials.Credentials) read from\n+ the file.\n+ \"\"\"\n+ if not file_path:\n+ file_path = self._filepath\n+\n+ if not os.path.isfile(file_path):\n+ return None\n+\n+ with open(file_path, 'r') as fh:\n+ random_string = fh.read(self.RANDOM_KEY_LENGTH)\n+ data = fh.read()\n+ key_string = b'{0:s}{1:s}{2:s}'.format(\n+ getpass.getuser(), random_string, self.SHARED_KEY)\n+ key = base64.b64encode(key_string)\n+ fernet = cryptography.fernet.Fernet(key)\n+ data_string = fernet.decrypt(data)\n+ try:\n+ token_dict = json.loads(data_string)\n+ except ValueError:\n+ return None\n+\n+ return credentials.Credentials(\n+ token=token_dict.get('token'),\n+ refresh_token=token_dict.get('_refresh_token'),\n+ id_token=token_dict.get('_id_token'),\n+ token_uri=token_dict.get('_token_uri'),\n+ client_id=token_dict.get('_client_id'),\n+ client_secret=token_dict.get('_client_secret')\n+ )\n" } ]
Python
Apache License 2.0
google/timesketch
Adding a config and a crypto module to the API client.
263,133
11.05.2020 15:55:34
0
e186b7f2fa6c8404720d3897565cf2d870467d9e
fixing length
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -49,16 +49,27 @@ class CredentialStorage:\nself._filepath = os.path.join(\nhome_path, self.DEFAULT_CREDENTIAL_FILENAME)\n- def _get_default_key(self):\n- \"\"\"Returns the default encryption key.\"\"\"\n- letters = string.ascii_letters\n- random_string = ''.join(\n- random.choice(letters) for _ in range(self.RANDOM_KEY_LENGTH))\n+ def _get_key(self, seed_key):\n+ \"\"\"Returns an encryption key.\n+\n+ Args:\n+ seed_key (str): a seed used to generate an encryption key.\n+\n+ Returns:\n+ Bytes with the encryption key.\n+ \"\"\"\n+\n+ key_string_half = '{0:s}{1:s}'.format(\n+ getpass.getuser(), seed_key)\n- key_string = '{0:s}{1:s}{2:s}'.format(\n- getpass.getuser(), random_string, self.SHARED_KEY)\n+ if len(key_string_half) >= 32:\n+ key_string = key_string_half[:32]\n+ else:\n+ key_string = '{0:s}{1:s}'.format(\n+ key_string_half, self.SHARED_KEY)\n+ key_string = key_string[:32]\n- return random_string, base64.b64encode(bytes(key_string, 'utf-8'))\n+ return base64.b64encode(bytes(key_string, 'utf-8'))\ndef set_filepath(self, file_path):\n\"\"\"Set the filepath to the credential file.\"\"\"\n@@ -97,7 +108,10 @@ class CredentialStorage:\ndata['expiry'] = cred_obj.expiry.isoformat()\ndata_string = json.dumps(data)\n- random_string, key = self._get_default_key()\n+ letters = string.ascii_letters\n+ random_string = ''.join(\n+ random.choice(letters) for _ in range(self.RANDOM_KEY_LENGTH))\n+ key = self._get_key(random_string)\ncrypto = fernet.Fernet(key)\nwith open(file_path, 'w') as fw:\n@@ -127,10 +141,8 @@ class CredentialStorage:\nwith open(file_path, 'r') as fh:\nrandom_string = fh.read(self.RANDOM_KEY_LENGTH)\n+ key = self._get_key(random_string)\ndata = fh.read()\n- key_string = '{0:s}{1:s}{2:s}'.format(\n- getpass.getuser(), random_string, self.SHARED_KEY)\n- key = base64.b64encode(bytes(key_string, 'utf-8'))\ncrypto = fernet.Fernet(key)\ndata_string = crypto.decrypt(data)\ntry:\n" } ]
Python
Apache License 2.0
google/timesketch
fixing length
263,133
12.05.2020 09:25:06
0
33f768b15ce392aa594e1b693ddd9370a8937faf
Adding click support into import client, fixing config and crypto
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200512',\n+ version='20200513',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -67,7 +67,8 @@ class TimesketchApi(object):\nverify=True,\nclient_id='',\nclient_secret='',\n- auth_mode='timesketch'):\n+ auth_mode='timesketch',\n+ create_session=True):\n\"\"\"Initializes the TimesketchApi object.\nArgs:\n@@ -80,6 +81,9 @@ class TimesketchApi(object):\nauth_mode: The authentication mode to use. Defaults to 'timesketch'\nSupported values are 'timesketch' (Timesketch login form),\n'http-basic' (HTTP Basic authentication) and oauth.\n+ create_session: Boolean indicating whether the client object\n+ should create a session object. If set to False the\n+ function \"set_session\" needs to be called before proceeding.\nRaises:\nConnectionError: If the Timesketch server is unreachable.\n@@ -88,8 +92,13 @@ class TimesketchApi(object):\n\"\"\"\nself._host_uri = host_uri\nself.api_root = '{0:s}/api/v1'.format(host_uri)\n- self._credentials = None\n+ self.credentials = None\nself._flow = None\n+\n+ if not create_session:\n+ self.session = None\n+ return\n+\ntry:\nself.session = self._create_session(\nusername, password, verify=verify, client_id=client_id,\n@@ -100,6 +109,14 @@ class TimesketchApi(object):\nraise RuntimeError(\n'Unable to connect to server, with error: {0!s}'.format(e))\n+ def set_credentials(self, credential_object):\n+ \"\"\"Sets the credential object.\"\"\"\n+ self.credentials = credential_object\n+\n+ def set_session(self, session_object):\n+ \"\"\"Sets the session object.\"\"\"\n+ self.session = session_object\n+\ndef _authenticate_session(self, session, username, password):\n\"\"\"Post username/password to authenticate the HTTP seesion.\n@@ -209,8 +226,15 @@ class TimesketchApi(object):\nsession = flow.authorized_session()\nself._flow = flow\n- self._credentials = flow.credentials\n+ self.credentials = flow.credentials\n+ return self.authenticate_oauth_session(session)\n+\n+ def authenticate_oauth_session(self, session):\n+ \"\"\"Authenticate an OAUTH session.\n+ Args:\n+ session: Authorized session object.\n+ \"\"\"\n# Authenticate to the Timesketch backend.\nlogin_callback_url = '{0:s}{1:s}'.format(\nself._host_uri, self.DEFAULT_OAUTH_API_CALLBACK)\n@@ -308,12 +332,12 @@ class TimesketchApi(object):\ndef get_oauth_token_status(self):\n\"\"\"Return a dict with OAuth token status, if one exists.\"\"\"\n- if not self._credentials:\n+ if not self.credentials:\nreturn {\n'status': 'No stored credentials.'}\nreturn {\n- 'expired': self._credentials.expired,\n- 'expiry_time': self._credentials.expiry.isoformat(),\n+ 'expired': self.credentials.expired,\n+ 'expiry_time': self.credentials.expiry.isoformat(),\n}\ndef get_sketch(self, sketch_id):\n@@ -454,7 +478,7 @@ class TimesketchApi(object):\ndef refresh_oauth_token(self):\n\"\"\"Refresh an OAUTH token if one is defined.\"\"\"\n- if not self._credentials:\n+ if not self.credentials:\nreturn\nrequest = google.auth.transport.requests.Request()\n- self._credentials.refresh(request)\n+ self.credentials.refresh(request)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -18,13 +18,31 @@ import configparser\nimport logging\nimport os\n+from google.auth.transport import requests as auth_requests\n+\nfrom . import client\n-#from . import crypto\n+from . import crypto\nlogger = logging.getLogger('config_assistance_api')\n+def get_client(config_dict=None, config_path=''):\n+ \"\"\"Returns a Timesketch API client using the configuration assistant.\n+\n+ Args:\n+ config_dict (dict): optional dict that will be used to configure\n+ the client.\n+ config_path (str): optional path to the configuration file, if\n+ not supplied a default path will be used.\n+ \"\"\"\n+ assistant = ConfigAssistant()\n+ assistant.load_config_file(config_path)\n+ if config_dict:\n+ assistant.load_config_dict(config_dict)\n+ return assistant.get_client()\n+\n+\nclass ConfigAssistant:\n\"\"\"A simple assistant that helps with setting up a Timesketch API client.\n@@ -75,11 +93,14 @@ class ConfigAssistant:\ndef get_client(self):\n\"\"\"Returns a Timesketch API client if possible.\"\"\"\n-\nif self.missing:\nreturn None\n- # Check auth mode and go for crypto client if oauth...\n+ auth_mode = self._config.get('auth_mode', 'timesketch')\n+ if auth_mode.startswith('oauth'):\n+ credential_storage = crypto.CredentialStorage()\n+ credentials = credential_storage.load_credentials()\n+ if not credentials:\nreturn client.TimesketchApi(\nhost_uri=self._config.get('host_uri'),\nusername=self._config.get('username'),\n@@ -87,7 +108,34 @@ class ConfigAssistant:\nverify=self._config.get('verify', True),\nclient_id=self._config.get('client_id', ''),\nclient_secret=self._config.get('client_secret', ''),\n- auth_mode=self._config.get('auth_mode', 'timesketch'),\n+ auth_mode=auth_mode,\n+ )\n+\n+ ts = client.TimesketchApi(\n+ host_uri=self._config.get('host_uri'),\n+ username=self._config.get('username'),\n+ auth_mode=auth_mode,\n+ create_session=False)\n+ ts.set_credentials(credentials)\n+ session = auth_requests.AuthorizedSession(credentials)\n+ try:\n+ ts.refresh_oauth_token()\n+ except auth_requests.RefreshError as e:\n+ logger.error(\n+ 'Unable to refresh credentials, with error: %s', e)\n+ return None\n+ session = ts.authenticate_oauth_session(session)\n+ ts.set_session(session)\n+ return ts\n+\n+ return client.TimesketchApi(\n+ host_uri=self._config.get('host_uri'),\n+ username=self._config.get('username'),\n+ password=self._config.get('password', ''),\n+ verify=self._config.get('verify', True),\n+ client_id=self._config.get('client_id', ''),\n+ client_secret=self._config.get('client_secret', ''),\n+ auth_mode=auth_mode,\n)\ndef get_missing_config(self):\n@@ -111,7 +159,7 @@ class ConfigAssistant:\n\"\"\"\nreturn name.lower() in self._config\n- def load_config(self, config_file_path=''):\n+ def load_config_file(self, config_file_path=''):\n\"\"\"Load the config from file.\nArgs:\n@@ -156,6 +204,27 @@ class ConfigAssistant:\nfor name, value in timesketch_config.items():\nself.set_config(name, value)\n+ def load_config_dict(self, config_dict):\n+ \"\"\"Loads configuration from a dictionary.\n+\n+ Only loads the config items that are needed for the client,\n+ other keys are ignored in the dict object.\n+\n+ Args:\n+ config_dict (dict): dict object with configuration.\n+ \"\"\"\n+ fields = list(self.CLIENT_NEEDED)\n+ fields.extend(list(self.OAUTH_CLIENT_NEEDED))\n+\n+ for key, value in config_dict.items():\n+ key = key.lower()\n+ if key not in fields:\n+ continue\n+\n+ if not value:\n+ continue\n+ self.set_config(key, value)\n+\ndef save_config(self, file_path=''):\n\"\"\"Save the current config to a file.\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -114,9 +114,10 @@ class CredentialStorage:\nkey = self._get_key(random_string)\ncrypto = fernet.Fernet(key)\n- with open(file_path, 'w') as fw:\n- fw.write(random_string)\n- fw.write(crypto.encrypt(data_string))\n+ with open(file_path, 'wb') as fw:\n+ fw.write(bytes(random_string, 'utf-8'))\n+ fw.write(\n+ crypto.encrypt(bytes(data_string, 'utf-8')))\nfile_permission = stat.S_IREAD | stat.S_IWRITE\nos.chmod(file_path, file_permission)\n@@ -139,14 +140,22 @@ class CredentialStorage:\nif not os.path.isfile(file_path):\nreturn None\n- with open(file_path, 'r') as fh:\n+ with open(file_path, 'rb') as fh:\nrandom_string = fh.read(self.RANDOM_KEY_LENGTH)\n- key = self._get_key(random_string)\n+ key = self._get_key(random_string.decode('utf-8'))\ndata = fh.read()\ncrypto = fernet.Fernet(key)\n+ try:\ndata_string = crypto.decrypt(data)\n+ except fernet.InvalidSignature as e:\n+ logger.error(\n+ 'Unable to decrypt data, signature is not correct: %s', e)\n+ return None\n+ except fernet.InvalidToken as e:\n+ logger.error('Unable to decrypt data, error %s', e)\n+ return None\ntry:\n- token_dict = json.loads(data_string)\n+ token_dict = json.loads(data_string.decode('utf-8'))\nexcept ValueError:\nreturn None\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/setup.py", "new_path": "importer_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-import-client',\n- version='20200507',\n+ version='20200513',\ndescription='Timesketch Import Client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n@@ -45,6 +45,7 @@ setup(\nzip_safe=False,\nscripts=glob.glob(os.path.join('tools', '[a-z]*.py')),\ninstall_requires=frozenset([\n+ 'click',\n'pandas',\n'xlrd',\n'timesketch-api-client',\n" }, { "change_type": "ADD", "old_path": null, "new_path": "importer_client/python/timesketch_import_client/cli.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"CLI assistance for importer tools.\"\"\"\n+\n+import click\n+\n+def ask_question(question, input_type, default=None):\n+ \"\"\"Presents the user with a prompt with a default return value and a type.\n+\n+ Args:\n+ question (str): the text that the user will be prompted.\n+ input_type (type): the type of the input data.\n+ default (object): default value for the question, optional.\n+ \"\"\"\n+ if default:\n+ return click.prompt(question, type=input_type, default=default)\n+ return click.prompt(question, type=input_type)\n+\n+\n+def confirm_choice(choice, default=True, abort=True):\n+ \"\"\"Returns a bool from a yes/no question presented to the end user.\n+\n+ Args:\n+ choice (str): the question presented to the end user.\n+ default (bool): the default for the confirmation answer. If True the\n+ default is Y(es), if False the default is N(o)\n+ abort (bool): if the program should abort if the user answer to the\n+ confirm prompt is no. The default is an abort.\n+\n+ Returns:\n+ bool: False if the user entered no, True if the user entered yes\n+ \"\"\"\n+ return click.confirm(choice, abort=abort, default=default)\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -22,63 +22,16 @@ import sys\nfrom typing import Dict\n-import yaml\n-\n-from timesketch_api_client import client\n+from timesketch_api_client import crypto\n+from timesketch_api_client import config\nfrom timesketch_api_client import sketch\n+from timesketch_import_client import cli\nfrom timesketch_import_client import importer\nlogging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))\n-def get_api_client(\n- host: str, username: str, password: str = '', client_id: str = '',\n- client_secret: str = '', run_local: bool = False\n- ) -> client.TimesketchApi:\n- \"\"\"Returns a Timesketch API client.\n-\n- Args:\n- host (str): the Timesketch host.\n- username (str): the username to authenticate with.\n- password (str): optional used if OAUTH is not the authentication\n- mechanism.\n- client_id (str): if OAUTH is used then a client ID needs to be set.\n- client_secret (str): if OAUTH is used then a client secret needs to be\n- set.\n- run_local (bool): if OAUTH is used to authenticate and set to True\n- then the authentication URL is printed on screen\n- instead of starting a web server, this suits well\n- if the connection is over a SSH connection for\n- instance.\n-\n- Raises:\n- TypeError: If a non supported authentication mode is passed in.\n-\n- Returns:\n- A Timesketch API client object.\n- \"\"\"\n- if run_local and client_secret:\n- auth_mode = 'oauth_local'\n- elif client_secret:\n- auth_mode = 'oauth'\n- elif password:\n- auth_mode = 'timesketch'\n- else:\n- raise TypeError(\n- 'Neither password nor client secret provided, unable '\n- 'to authenticate')\n-\n- if not host.startswith('http'):\n- host = 'https://{0:s}'.format(host)\n-\n- api_client = client.TimesketchApi(\n- host_uri=host, username=username, password=password,\n- client_id=client_id, client_secret=client_secret, auth_mode=auth_mode)\n-\n- return api_client\n-\n-\ndef upload_file(\nmy_sketch: sketch.Sketch, config_dict: Dict[str, any],\nfile_path: str) -> str:\n@@ -169,11 +122,6 @@ if __name__ == '__main__':\nconfig_group = argument_parser.add_argument_group(\n'Configuration Arguments')\n- config_group.add_argument(\n- '--config-file', '--config_file', action='store', type=str,\n- default='', metavar='FILEPATH', dest='config_file', help=(\n- 'Path to a YAML config file that can be used to store '\n- 'all parameters to this tool (except this path)'))\nconfig_group.add_argument(\n'--log-config-file', '--log_config_file', '--lc', action='store',\ntype=str, default='', metavar='FILEPATH', dest='log_config_file',\n@@ -182,7 +130,7 @@ if __name__ == '__main__':\n'and setting up file parsing. By default formatter.yaml that '\n'comes with the importer will be used.'))\nconfig_group.add_argument(\n- '--host', '--hostname', '--host-uri', '--host_uri', dest='host',\n+ '--host', '--hostname', '--host-uri', '--host_uri', dest='host_uri',\ntype=str, default='', action='store',\nhelp='The URI to the Timesketch instance')\nconfig_group.add_argument(\n@@ -228,50 +176,57 @@ if __name__ == '__main__':\n'Path to the file that is to be imported.'))\noptions = argument_parser.parse_args()\n- config_options = {}\n-\n- if options.config_file:\n- if not os.path.isfile(options.config_file):\n- logger.error('Config file does not exist ({0:s})'.format(\n- options.config_file))\n- sys.exit(1)\n- with open(options.config_file, 'r') as fh:\n- config_options = yaml.safe_load(fh)\nif not os.path.isfile(options.path):\nlogger.error('Path {0:s} is not valid, unable to continue.')\nsys.exit(1)\n- conf_host = options.host or config_options.get('host', '')\n- if not conf_host:\n- logger.error('Hostname for Timesketch server must be set.')\n- sys.exit(1)\n+ assistant = config.ConfigAssistant()\n+ assistant.load_config_file()\n+ assistant.load_config_dict(vars(options))\n- conf_password = options.password or config_options.get('password', '')\n- conf_pwd_prompt = options.pwd_prompt or config_options.get(\n- 'pwd_prompt', False)\n- if not conf_password and conf_pwd_prompt:\n+ conf_password = ''\n+ if options.pwd_prompt:\nconf_password = getpass.getpass('Type in the password: ')\n+ else:\n+ conf_password = options.password\n- conf_client_id = options.client_id or config_options.get('client_id', '')\n- conf_client_secret = options.client_secret or config_options.get(\n- 'client_secret', '')\n- conf_username = options.username or config_options.get('username', '')\n- conf_run_local = options.run_local or config_options.get(\n- 'run_local', False)\n+ if conf_password:\n+ assistant.set_config('auth_mode', 'timesketch')\n+ assistant.set_config('password', conf_password)\n- logger.info('Creating a client.')\n- ts_client = get_api_client(\n- host=conf_host, username=conf_username, password=conf_password,\n- client_id=conf_client_id, client_secret=conf_client_secret,\n- run_local=conf_run_local)\n+ if options.run_local:\n+ assistant.set_config('auth_mode', 'oauth_local')\n+ if options.client_secret:\n+ assistant.set_config('auth_mode', 'oauth')\n+\n+ # Gather all questions that are missing.\n+ while True:\n+ for field in assistant.missing:\n+ value = cli.ask_question(\n+ 'What is the value for: {0:s} ='.format(field), input_type=str)\n+ if value:\n+ assistant.set_config(field, value)\n+ if not assistant.missing:\n+ break\n+\n+ logger.info('Creating a client.')\n+ ts_client = assistant.get_client()\nif not ts_client:\nlogger.error('Unable to create a Timesketch API client, exiting.')\nsys.exit(1)\nlogger.info('Client created.')\n- sketch_id = options.sketch_id or config_options.get('sketch_id', 0)\n+ logger.info('Saving TS config.')\n+ assistant.save_config()\n+\n+ if ts_client.credentials:\n+ logger.info('Saving Credentials.')\n+ cred_storage = crypto.CredentialStorage()\n+ cred_storage.save_credentials(ts_client.credentials)\n+\n+ sketch_id = options.sketch_id\nif sketch_id:\nsketch = ts_client.get_sketch(sketch_id)\nelse:\n@@ -283,25 +238,18 @@ if __name__ == '__main__':\nfilename = os.path.basename(options.path)\ndefault_timeline_name, _, _ = filename.rpartition('.')\n- conf_timeline_name = options.timeline_name or config_options.get(\n- 'timeline_name', default_timeline_name)\n+ conf_timeline_name = options.timeline_name or default_timeline_name\nconfig = {\n- 'message_format_string': options.format_string or config_options.get(\n- 'format_string', ''),\n+ 'message_format_string': options.format_string,\n'timeline_name': conf_timeline_name,\n- 'index_name': options.index_name or config_options.get(\n- 'index_name', ''),\n- 'timestamp_description': options.time_desc or config_options.get(\n- 'timestamp_description', ''),\n- 'entry_threshold': options.entry_threshold or config_options.get(\n- 'entry_threshold', 0),\n- 'size_threshold': options.size_threshold or config_options.get(\n- 'size_threshold', 0),\n+ 'index_name': options.index_name,\n+ 'timestamp_description': options.time_desc,\n+ 'entry_threshold': options.entry_threshold,\n+ 'size_threshold': options.size_threshold,\n'log_config_file': options.log_config_file,\n}\n-\nlogger.info('Uploading file.')\nresult = upload_file(\nmy_sketch=sketch, config_dict=config, file_path=options.path)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding click support into import client, fixing config and crypto
263,133
12.05.2020 11:18:49
0
61ca09b73affa21863e7a12ae63ed5b608e77ae3
Removing doc string.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -50,9 +50,6 @@ class ConfigAssistant:\na state about what config has been passed to it, to assist possible\nUIs to understand what is missing in order to setup a Timesketch API\nclient.\n-\n- Attributes:\n- asdfsadf\n\"\"\"\n# The name of the default config file.\n" } ]
Python
Apache License 2.0
google/timesketch
Removing doc string.
263,133
12.05.2020 15:49:11
0
f6f1e0e006a7153fc238677bfcf955a3702a086e
Adding credential objects, storing also user/pass combinations of auth.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -31,6 +31,7 @@ from google_auth_oauthlib import flow as googleauth_flow\nimport google.auth.transport.requests\nimport pandas\n+from . import crypto\nfrom . import definitions\nfrom . import error\nfrom . import index\n@@ -226,7 +227,8 @@ class TimesketchApi(object):\nsession = flow.authorized_session()\nself._flow = flow\n- self.credentials = flow.credentials\n+ self.credentials = crypto.TimesketchOAuthCredentials()\n+ self.credentials.credential = flow.credentials\nreturn self.authenticate_oauth_session(session)\ndef authenticate_oauth_session(self, session):\n@@ -336,8 +338,8 @@ class TimesketchApi(object):\nreturn {\n'status': 'No stored credentials.'}\nreturn {\n- 'expired': self.credentials.expired,\n- 'expiry_time': self.credentials.expiry.isoformat(),\n+ 'expired': self.credentials.credential.expired,\n+ 'expiry_time': self.credentials.credential.expiry.isoformat(),\n}\ndef get_sketch(self, sketch_id):\n@@ -481,4 +483,4 @@ class TimesketchApi(object):\nif not self.credentials:\nreturn\nrequest = google.auth.transport.requests.Request()\n- self.credentials.refresh(request)\n+ self.credentials.credential.refresh(request)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -94,9 +94,10 @@ class ConfigAssistant:\nreturn None\nauth_mode = self._config.get('auth_mode', 'timesketch')\n- if auth_mode.startswith('oauth'):\ncredential_storage = crypto.CredentialStorage()\ncredentials = credential_storage.load_credentials()\n+\n+ if auth_mode.startswith('oauth'):\nif not credentials:\nreturn client.TimesketchApi(\nhost_uri=self._config.get('host_uri'),\n@@ -114,7 +115,7 @@ class ConfigAssistant:\nauth_mode=auth_mode,\ncreate_session=False)\nts.set_credentials(credentials)\n- session = auth_requests.AuthorizedSession(credentials)\n+ session = auth_requests.AuthorizedSession(credentials.credential)\ntry:\nts.refresh_oauth_token()\nexcept auth_requests.RefreshError as e:\n@@ -125,10 +126,19 @@ class ConfigAssistant:\nts.set_session(session)\nreturn ts\n+ if credentials:\n+ username = credentials.credential.get(\n+ 'username', self._config.get('username', ''))\n+ password = credentials.credential.get(\n+ 'password', self._config.get('password', ''))\n+ else:\n+ username = self._config.get('username', '')\n+ password = self._config.get('password', '')\n+\nreturn client.TimesketchApi(\nhost_uri=self._config.get('host_uri'),\n- username=self._config.get('username'),\n- password=self._config.get('password', ''),\n+ username=username,\n+ password=password,\nverify=self._config.get('verify', True),\nclient_id=self._config.get('client_id', ''),\nclient_secret=self._config.get('client_secret', ''),\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -30,6 +30,149 @@ from google.oauth2 import credentials\nlogger = logging.getLogger('crypto_client_api')\n+class TimesketchCredentials:\n+ \"\"\"Class to store and retrieve credentials for Timesketch.\"\"\"\n+\n+ # The type of credential object.\n+ TYPE = ''\n+\n+ def __init__(self):\n+ \"\"\"Initialize the credential object.\"\"\"\n+ self._credential = None\n+\n+ @property\n+ def credential(self):\n+ \"\"\"Returns the credentials back.\"\"\"\n+ return self._credential\n+\n+ @credential.setter\n+ def credential(self, credential_obj):\n+ \"\"\"Sets the credential object.\"\"\"\n+ self._credential = credential_obj\n+\n+ def serialize(self):\n+ \"\"\"Return serialized bytes object.\"\"\"\n+ data = self.to_bytes()\n+ type_string = bytes(self.TYPE, 'utf-8').rjust(10)[:10]\n+\n+ return type_string + data\n+\n+ def deserialize(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+ \"\"\"\n+ type_data = data[:10]\n+ type_string = type_data.decode('utf-8').strip()\n+ if not self.TYPE.startswith(type_string):\n+ raise TypeError('Not the correct serializer.')\n+\n+ self.from_bytes(data[10:])\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ raise NotImplementedError\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+\n+class TimesketchPwdCredentials(TimesketchCredentials):\n+ \"\"\"Username and password credentials for Timesketch authentication.\"\"\"\n+\n+ TYPE = 'timesketch'\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+\n+ Raises:\n+ TypeError: if the data is not in bytes.\n+ \"\"\"\n+ if not isinstance(data, bytes):\n+ raise TypeError('Data needs to be bytes.')\n+\n+ try:\n+ data_dict = json.loads(data.decode('utf-8'))\n+ except ValueError:\n+ raise TypeError('Unable to parse the byte string.')\n+\n+ if not 'username' in data_dict:\n+ raise TypeError('Username is not set.')\n+ if not 'password' in data_dict:\n+ raise TypeError('Password is not set.')\n+ self._credential = data_dict\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ if not self._credential:\n+ return b''\n+\n+ data_string = json.dumps(self._credential)\n+ return bytes(data_string, 'utf-8')\n+\n+\n+class TimesketchOAuthCredentials(TimesketchCredentials):\n+ \"\"\"OAUTH credentials for Timesketch authentication.\"\"\"\n+\n+ TYPE = 'oauth'\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+\n+ Raises:\n+ TypeError: if the data is not in bytes.\n+ \"\"\"\n+ if not isinstance(data, bytes):\n+ raise TypeError('Data needs to be bytes.')\n+\n+ try:\n+ token_dict = json.loads(data.decode('utf-8'))\n+ except ValueError:\n+ raise TypeError('Unable to parse the byte string.')\n+\n+ self._credential = credentials.Credentials(\n+ token=token_dict.get('token'),\n+ refresh_token=token_dict.get('_refresh_token'),\n+ id_token=token_dict.get('_id_token'),\n+ token_uri=token_dict.get('_token_uri'),\n+ client_id=token_dict.get('_client_id'),\n+ client_secret=token_dict.get('_client_secret')\n+ )\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ if not self._credential:\n+ return b''\n+\n+ cred_obj = self._credential\n+ data = {\n+ 'token': cred_obj.token,\n+ '_scopes': getattr(cred_obj, '_scopes', []),\n+ '_refresh_token': getattr(cred_obj, '_refresh_token', ''),\n+ '_id_token': getattr(cred_obj, '_id_token', ''),\n+ '_token_uri': getattr(cred_obj, '_token_uri', ''),\n+ '_client_id': getattr(cred_obj, '_client_id', ''),\n+ '_client_secret': getattr(cred_obj, '_client_secret', ''),\n+ }\n+ if cred_obj.expiry:\n+ data['expiry'] = cred_obj.expiry.isoformat()\n+ data_string = json.dumps(data)\n+\n+ return bytes(data_string, 'utf-8')\n+\n+\nclass CredentialStorage:\n\"\"\"Class to store and retrieve stored credentials.\"\"\"\n@@ -84,42 +227,28 @@ class CredentialStorage:\nthat contains a stored copy of the credential object.\nArgs:\n- cred_obj (google.oauth2.credentials.Credentials): the credential\n+ cred_obj (TimesketchCredentials): the credential\nobject that is to be stored on disk.\nfile_path (str): Full path to the file storing the saved\ncredentials.\n\"\"\"\n- # TODO (kiddi): Support user/pass credentials as well. Create\n- # a separate credential object that wraps the OAUTH creds.\nif not file_path:\nfile_path = self._filepath\nif not os.path.isfile(file_path):\nlogger.info('File does not exist, creating it.')\n- data = {\n- 'token': cred_obj.token,\n- '_scopes': getattr(cred_obj, '_scopes', []),\n- '_refresh_token': getattr(cred_obj, '_refresh_token', ''),\n- '_id_token': getattr(cred_obj, '_id_token', ''),\n- '_token_uri': getattr(cred_obj, '_token_uri', ''),\n- '_client_id': getattr(cred_obj, '_client_id', ''),\n- '_client_secret': getattr(cred_obj, '_client_secret', ''),\n- }\n- if cred_obj.expiry:\n- data['expiry'] = cred_obj.expiry.isoformat()\n- data_string = json.dumps(data)\n-\nletters = string.ascii_letters\nrandom_string = ''.join(\nrandom.choice(letters) for _ in range(self.RANDOM_KEY_LENGTH))\nkey = self._get_key(random_string)\ncrypto = fernet.Fernet(key)\n+ data = cred_obj.serialize()\n+\nwith open(file_path, 'wb') as fw:\nfw.write(bytes(random_string, 'utf-8'))\n- fw.write(\n- crypto.encrypt(bytes(data_string, 'utf-8')))\n+ fw.write(crypto.encrypt(data))\nfile_permission = stat.S_IREAD | stat.S_IWRITE\nos.chmod(file_path, file_permission)\n@@ -156,16 +285,16 @@ class CredentialStorage:\nexcept fernet.InvalidToken as e:\nlogger.error('Unable to decrypt data, error %s', e)\nreturn None\n+\n+ # TODO: Implement a manager.\n+ cred_obj = TimesketchPwdCredentials()\ntry:\n- token_dict = json.loads(data_string.decode('utf-8'))\n- except ValueError:\n- return None\n+ cred_obj.deserialize(data_string)\n- return credentials.Credentials(\n- token=token_dict.get('token'),\n- refresh_token=token_dict.get('_refresh_token'),\n- id_token=token_dict.get('_id_token'),\n- token_uri=token_dict.get('_token_uri'),\n- client_id=token_dict.get('_client_id'),\n- client_secret=token_dict.get('_client_secret')\n- )\n+ return cred_obj\n+ except TypeError:\n+ logger.warning('Credential object is not \"timesketch\" auth.')\n+\n+ cred_obj = TimesketchOAuthCredentials()\n+ cred_obj.deserialize(data_string)\n+ return cred_obj\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -185,22 +185,31 @@ if __name__ == '__main__':\nassistant.load_config_file()\nassistant.load_config_dict(vars(options))\n+ cred_storage = crypto.CredentialStorage()\n+ credentials = cred_storage.load_credentials()\nconf_password = ''\n+\n+ if credentials:\n+ if credentials.TYPE.lower() == 'oauth':\n+ assistant.set_config('auth_mode', 'oauth')\n+ elif credentials.TYPE.lower() == 'timesketch':\n+ assistant.set_config('auth_mode', 'timesketch')\n+\n+ else:\nif options.pwd_prompt:\nconf_password = getpass.getpass('Type in the password: ')\nelse:\nconf_password = options.password\n- if conf_password:\n- assistant.set_config('auth_mode', 'timesketch')\n- assistant.set_config('password', conf_password)\n-\nif options.run_local:\nassistant.set_config('auth_mode', 'oauth_local')\nif options.client_secret:\nassistant.set_config('auth_mode', 'oauth')\n+ if conf_password:\n+ assistant.set_config('auth_mode', 'timesketch')\n+\n# Gather all questions that are missing.\nwhile True:\nfor field in assistant.missing:\n@@ -211,6 +220,15 @@ if __name__ == '__main__':\nif not assistant.missing:\nbreak\n+ if conf_password:\n+ credentials = crypto.TimesketchPwdCredentials()\n+ credentials.credential = {\n+ 'username': assistant.get_config('username'),\n+ 'password': conf_password\n+ }\n+ logger.info('Saving Credentials.')\n+ cred_storage.save_credentials(credentials)\n+\nlogger.info('Creating a client.')\nts_client = assistant.get_client()\nif not ts_client:\n@@ -223,7 +241,6 @@ if __name__ == '__main__':\nif ts_client.credentials:\nlogger.info('Saving Credentials.')\n- cred_storage = crypto.CredentialStorage()\ncred_storage.save_credentials(ts_client.credentials)\nsketch_id = options.sketch_id\n" } ]
Python
Apache License 2.0
google/timesketch
Adding credential objects, storing also user/pass combinations of auth.
263,133
13.05.2020 07:47:01
0
42df2733b1a084fae53bf8c5f2e51916c182a893
Changing crypto, using a salt and a different method for generating the key.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -19,11 +19,12 @@ import os\nimport getpass\nimport json\nimport logging\n-import random\n-import string\nimport stat\nfrom cryptography import fernet\n+from cryptography.hazmat.backends import default_backend\n+from cryptography.hazmat.primitives import hashes\n+from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\nfrom google.oauth2 import credentials\n@@ -177,13 +178,13 @@ class CredentialStorage:\n\"\"\"Class to store and retrieve stored credentials.\"\"\"\n# A default shared secret that will be used as part of the key.\n- SHARED_KEY = 'thetta er mjog leynt'\n+ SHARED_KEY = 'afar mikid leyndarmal'\n# The default filename of the token file.\nDEFAULT_CREDENTIAL_FILENAME = '.timesketch.token'\n- # The number of characters in the random part of the default key.\n- RANDOM_KEY_LENGTH = 20\n+ # Length of the salt.\n+ SALT_LENGTH = 16\ndef __init__(self):\n\"\"\"Initialize the class.\"\"\"\n@@ -192,27 +193,31 @@ class CredentialStorage:\nself._filepath = os.path.join(\nhome_path, self.DEFAULT_CREDENTIAL_FILENAME)\n- def _get_key(self, seed_key):\n+ def _get_key(self, salt, password=''):\n\"\"\"Returns an encryption key.\nArgs:\n- seed_key (str): a seed used to generate an encryption key.\n+ salt (bytes): a salt used during the encryption.\n+ password (str): optional password, if not supplied\n+ a default one will be generated.\nReturns:\nBytes with the encryption key.\n\"\"\"\n-\n- key_string_half = '{0:s}{1:s}'.format(\n- getpass.getuser(), seed_key)\n-\n- if len(key_string_half) >= 32:\n- key_string = key_string_half[:32]\n- else:\n- key_string = '{0:s}{1:s}'.format(\n- key_string_half, self.SHARED_KEY)\n- key_string = key_string[:32]\n-\n- return base64.b64encode(bytes(key_string, 'utf-8'))\n+ if not password:\n+ password = '{0:s}{1:s}'.format(\n+ getpass.getuser(), self.SHARED_KEY)\n+\n+ password = bytes(password, 'utf-8')\n+ kdf = PBKDF2HMAC(\n+ algorithm=hashes.SHA256(),\n+ length=32,\n+ salt=salt,\n+ iterations=100000,\n+ backend=default_backend()\n+ )\n+ return base64.urlsafe_b64encode(\n+ kdf.derive(password))\ndef set_filepath(self, file_path):\n\"\"\"Set the filepath to the credential file.\"\"\"\n@@ -238,16 +243,14 @@ class CredentialStorage:\nif not os.path.isfile(file_path):\nlogger.info('File does not exist, creating it.')\n- letters = string.ascii_letters\n- random_seed_string = ''.join(\n- random.choice(letters) for _ in range(self.RANDOM_KEY_LENGTH))\n- key = self._get_key(random_seed_string)\n+ salt = os.urandom(self.SALT_LENGTH)\n+ key = self._get_key(salt)\ncrypto = fernet.Fernet(key)\ndata = cred_obj.serialize()\nwith open(file_path, 'wb') as fw:\n- fw.write(bytes(random_seed_string, 'utf-8'))\n+ fw.write(salt)\nfw.write(crypto.encrypt(data))\nfile_permission = stat.S_IREAD | stat.S_IWRITE\n@@ -272,8 +275,8 @@ class CredentialStorage:\nreturn None\nwith open(file_path, 'rb') as fh:\n- random_seed_string = fh.read(self.RANDOM_KEY_LENGTH)\n- key = self._get_key(random_seed_string.decode('utf-8'))\n+ salt = fh.read(self.SALT_LENGTH)\n+ key = self._get_key(salt)\ndata = fh.read()\ncrypto = fernet.Fernet(key)\ntry:\n" } ]
Python
Apache License 2.0
google/timesketch
Changing crypto, using a salt and a different method for generating the key.
263,133
13.05.2020 13:38:58
0
95afd7a01c64c3131b9afb2544289a7a1db103d4
Adding the ability to define your own pwd for the token file, as well as randomly generating it by default.'
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -91,14 +91,15 @@ class ConfigAssistant:\n\"\"\"\nreturn self._config[name]\n- def get_client(self):\n+ def get_client(self, password=''):\n\"\"\"Returns a Timesketch API client if possible.\"\"\"\nif self.missing:\nreturn None\nauth_mode = self._config.get('auth_mode', 'timesketch')\ncredential_storage = crypto.CredentialStorage()\n- credentials = credential_storage.load_credentials()\n+ credentials = credential_storage.load_credentials(\n+ config_assistant=self, password=password)\nif auth_mode.startswith('oauth'):\nif not credentials:\n@@ -261,6 +262,12 @@ class ConfigAssistant:\n'auth_mode': self._config.get('auth_mode', 'timesketch')\n}\n+ if 'cred_key' in self._config:\n+ cred_key = self._config.get('cred_key')\n+ if isinstance(cred_key, bytes):\n+ cred_key = cred_key.decode('utf-8')\n+ config['timesketch']['cred_key'] = cred_key\n+\nwith open(file_path, 'w') as fw:\nconfig.write(fw)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -177,9 +177,6 @@ class TimesketchOAuthCredentials(TimesketchCredentials):\nclass CredentialStorage:\n\"\"\"Class to store and retrieve stored credentials.\"\"\"\n- # A default shared secret that will be used as part of the key.\n- SHARED_KEY = 'afar mikid leyndarmal'\n-\n# The default filename of the token file.\nDEFAULT_CREDENTIAL_FILENAME = '.timesketch.token'\n@@ -193,22 +190,17 @@ class CredentialStorage:\nself._filepath = os.path.join(\nhome_path, self.DEFAULT_CREDENTIAL_FILENAME)\n- def _get_key(self, salt, password=''):\n+ def _get_key(self, salt, password):\n\"\"\"Returns an encryption key.\nArgs:\nsalt (bytes): a salt used during the encryption.\n- password (str): optional password, if not supplied\n- a default one will be generated.\n+ password (bytes): the password used to decrypt/encrypt\n+ the message.\nReturns:\nBytes with the encryption key.\n\"\"\"\n- if not password:\n- password = '{0:s}{1:s}'.format(\n- getpass.getuser(), self.SHARED_KEY)\n-\n- password = bytes(password, 'utf-8')\nkdf = PBKDF2HMAC(\nalgorithm=hashes.SHA256(),\nlength=32,\n@@ -224,7 +216,8 @@ class CredentialStorage:\nif os.path.isfile(file_path):\nself._filepath = file_path\n- def save_credentials(self, cred_obj, file_path=''):\n+ def save_credentials(\n+ self, cred_obj, file_path='', password='', config_assistant=None):\n\"\"\"Save credential data to a token file.\nThis function will create an encrypted file\n@@ -234,17 +227,31 @@ class CredentialStorage:\nArgs:\ncred_obj (TimesketchCredentials): the credential\nobject that is to be stored on disk.\n- file_path (str): Full path to the file storing the saved\n+ file_path (str): full path to the file storing the saved\ncredentials.\n+ password (str): optional password to encrypt the\n+ credential file with. If not supplied a password\n+ will be generated.\n+ config_assistant (ConfigAssistant): optional configuration\n+ assistant object. Can be used to store the password to the\n+ credential file.\n\"\"\"\nif not file_path:\nfile_path = self._filepath\n+ if password:\n+ password = bytes(password, 'utf-8')\n+ else:\n+ password = fernet.Fernet.generate_key()\n+ if config_assistant:\n+ config_assistant.set_config('cred_key', password)\n+ config_assistant.save_config()\n+\nif not os.path.isfile(file_path):\nlogger.info('File does not exist, creating it.')\nsalt = os.urandom(self.SALT_LENGTH)\n- key = self._get_key(salt)\n+ key = self._get_key(salt, password)\ncrypto = fernet.Fernet(key)\ndata = cred_obj.serialize()\n@@ -257,12 +264,22 @@ class CredentialStorage:\nos.chmod(file_path, file_permission)\nlogger.info('Credentials saved to: %s', file_path)\n- def load_credentials(self, file_path=''):\n+ def load_credentials(\n+ self, file_path='', password='', config_assistant=None):\n\"\"\"Load credentials from a file and return a credential object.\nArgs:\nfile_path (str): Full path to the file storing the saved\ncredentials.\n+ password (str): optional password to encrypt the\n+ credential file with. If not supplied a password\n+ will be generated.\n+ config_assistant (ConfigAssistant): optional configuration\n+ assistant object. Can be used to store the password to the\n+ credential file.\n+\n+ Raises:\n+ IOError: If not able to decrypt the data.\nReturns:\nCredential object (oauth2.credentials.Credentials) read from\n@@ -274,20 +291,35 @@ class CredentialStorage:\nif not os.path.isfile(file_path):\nreturn None\n+ if password:\n+ password = bytes(password, 'utf-8')\n+ elif config_assistant:\n+ try:\n+ password = config_assistant.get_config('cred_key')\n+ password = bytes(password, 'utf-8')\n+ except KeyError:\n+ raise IOError(\n+ 'Not able to determine encryption key from config.')\n+ else:\n+ raise IOError(\n+ 'Neither password nor a configuration assistant passed to '\n+ 'tool, unable to determine password.')\n+\nwith open(file_path, 'rb') as fh:\nsalt = fh.read(self.SALT_LENGTH)\n- key = self._get_key(salt)\n+ key = self._get_key(salt, password)\ndata = fh.read()\ncrypto = fernet.Fernet(key)\ntry:\ndata_string = crypto.decrypt(data)\nexcept fernet.InvalidSignature as e:\n- logger.error(\n- 'Unable to decrypt data, signature is not correct: %s', e)\n- return None\n+ raise IOError(\n+ 'Unable to decrypt data, signature is not correct: '\n+ '{0!s}'.format(e))\nexcept fernet.InvalidToken as e:\n- logger.error('Unable to decrypt data, error %s', e)\n- return None\n+ raise IOError(\n+ 'Unable to decrypt data, password wrong? (error '\n+ '{0!s})'.format(e))\n# TODO: Implement a manager.\ncred_obj = TimesketchPwdCredentials()\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/timesketch_import_client/cli.py", "new_path": "importer_client/python/timesketch_import_client/cli.py", "diff": "import click\n-def ask_question(question, input_type, default=None):\n+def ask_question(question, input_type, default=None, hide_input=False):\n\"\"\"Presents the user with a prompt with a default return value and a type.\nArgs:\nquestion (str): the text that the user will be prompted.\ninput_type (type): the type of the input data.\ndefault (object): default value for the question, optional.\n+ hide_input (bool): whether the input should be hidden, eg. when asking\n+ for a password.\nReturns:\nobject: The value (type of input_type) that is ready by the user.\n\"\"\"\nif default:\n- return click.prompt(question, type=input_type, default=default)\n- return click.prompt(question, type=input_type)\n+ return click.prompt(\n+ question, type=input_type, default=default, hide_input=hide_input)\n+ return click.prompt(question, type=input_type, hide_input=hide_input)\ndef confirm_choice(choice, default=True, abort=True):\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -106,6 +106,11 @@ if __name__ == '__main__':\nauth_group.add_argument(\n'--pwd-prompt', '--pwd_prompt', action='store_true', default=False,\ndest='pwd_prompt', help='Prompt for password.')\n+ auth_group.add_argument(\n+ '--cred-prompt', '--cred_prompt', '--token-password',\n+ '--token_password', '--token', action='store_true', default=False,\n+ dest='cred_prompt',\n+ help='Prompt for password to decrypt and encrypt credential file.')\nauth_group.add_argument(\n'--client-secret', '--client_secret', action='store', type=str,\ndefault='', dest='client_secret', help='OAUTH client secret.')\n@@ -186,7 +191,23 @@ if __name__ == '__main__':\nassistant.load_config_dict(vars(options))\ncred_storage = crypto.CredentialStorage()\n- credentials = cred_storage.load_credentials()\n+ credential_password = ''\n+ if options.cred_prompt:\n+ credential_password = cli.ask_question(\n+ 'Enter password to encrypt/decrypt credential file',\n+ input_type=str, hide_input=True)\n+\n+ try:\n+ credentials = cred_storage.load_credentials(\n+ config_assistant=assistant, password=credential_password)\n+ except IOError as e:\n+ logger.error(\n+ 'Unable to decrypt the credential file, with error: %s', e)\n+ logger.error(\n+ 'If you\\'ve forgotten the password you can delete '\n+ 'the ~/.timesketch.token file and run the tool again.')\n+ sys.exit(1)\n+\nconf_password = ''\nif credentials:\n@@ -229,10 +250,12 @@ if __name__ == '__main__':\n'password': conf_password\n}\nlogger.info('Saving Credentials.')\n- cred_storage.save_credentials(credentials)\n+ cred_storage.save_credentials(\n+ credentials, password=credential_password,\n+ config_assistant=assistant)\nlogger.info('Creating a client.')\n- ts_client = assistant.get_client()\n+ ts_client = assistant.get_client(password=credential_password)\nif not ts_client:\nlogger.error('Unable to create a Timesketch API client, exiting.')\nsys.exit(1)\n@@ -243,7 +266,9 @@ if __name__ == '__main__':\nif ts_client.credentials:\nlogger.info('Saving Credentials.')\n- cred_storage.save_credentials(ts_client.credentials)\n+ cred_storage.save_credentials(\n+ ts_client.credentials, password=credential_password,\n+ config_assistant=assistant)\nsketch_id = options.sketch_id\nif sketch_id:\n" } ]
Python
Apache License 2.0
google/timesketch
Adding the ability to define your own pwd for the token file, as well as randomly generating it by default.'
263,133
13.05.2020 13:42:31
0
c5692e0549530ffbcd6ba755b53517708280f89d
Changing a docstring.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -91,8 +91,13 @@ class ConfigAssistant:\n\"\"\"\nreturn self._config[name]\n- def get_client(self, password=''):\n- \"\"\"Returns a Timesketch API client if possible.\"\"\"\n+ def get_client(self, token_password=''):\n+ \"\"\"Returns a Timesketch API client if possible.\n+\n+ Args:\n+ token_password (str): an optional password to decrypt\n+ the credential token file.\n+ \"\"\"\nif self.missing:\nreturn None\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -191,15 +191,15 @@ if __name__ == '__main__':\nassistant.load_config_dict(vars(options))\ncred_storage = crypto.CredentialStorage()\n- credential_password = ''\n+ token_password = ''\nif options.cred_prompt:\n- credential_password = cli.ask_question(\n+ token_password = cli.ask_question(\n'Enter password to encrypt/decrypt credential file',\ninput_type=str, hide_input=True)\ntry:\ncredentials = cred_storage.load_credentials(\n- config_assistant=assistant, password=credential_password)\n+ config_assistant=assistant, password=token_password)\nexcept IOError as e:\nlogger.error(\n'Unable to decrypt the credential file, with error: %s', e)\n@@ -251,11 +251,11 @@ if __name__ == '__main__':\n}\nlogger.info('Saving Credentials.')\ncred_storage.save_credentials(\n- credentials, password=credential_password,\n+ credentials, password=token_password,\nconfig_assistant=assistant)\nlogger.info('Creating a client.')\n- ts_client = assistant.get_client(password=credential_password)\n+ ts_client = assistant.get_client(token_password=token_password)\nif not ts_client:\nlogger.error('Unable to create a Timesketch API client, exiting.')\nsys.exit(1)\n@@ -267,7 +267,7 @@ if __name__ == '__main__':\nif ts_client.credentials:\nlogger.info('Saving Credentials.')\ncred_storage.save_credentials(\n- ts_client.credentials, password=credential_password,\n+ ts_client.credentials, password=token_password,\nconfig_assistant=assistant)\nsketch_id = options.sketch_id\n" } ]
Python
Apache License 2.0
google/timesketch
Changing a docstring.
263,133
13.05.2020 15:03:17
0
3d2dd6bd44ebaf0c5b2af7c410b62b96c68fa9a4
Forgot to update a single variable.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -104,7 +104,7 @@ class ConfigAssistant:\nauth_mode = self._config.get('auth_mode', 'timesketch')\ncredential_storage = crypto.CredentialStorage()\ncredentials = credential_storage.load_credentials(\n- config_assistant=self, password=password)\n+ config_assistant=self, password=token_password)\nif auth_mode.startswith('oauth'):\nif not credentials:\n" } ]
Python
Apache License 2.0
google/timesketch
Forgot to update a single variable.
263,133
14.05.2020 09:45:39
0
baad8ba114ceb87e684594820a9faaa625ac77b3
Adding code to complete config into the library.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200513',\n+ version='20200514',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n@@ -37,6 +37,7 @@ setup(\ninclude_package_data=True,\nzip_safe=False,\ninstall_requires=frozenset([\n+ 'click',\n'pandas',\n'cryptography',\n'requests',\n" }, { "change_type": "RENAME", "old_path": "importer_client/python/timesketch_import_client/cli.py", "new_path": "api_client/python/timesketch_api_client/cli_input.py", "diff": "" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -21,6 +21,7 @@ import os\nfrom google.auth.transport import requests as auth_requests\nfrom . import client\n+from . import cli_input\nfrom . import crypto\n@@ -43,6 +44,63 @@ def get_client(config_dict=None, config_path=''):\nreturn assistant.get_client()\n+def configure_missing_parameters(config_assistant, token_password=''):\n+ \"\"\"Fill in missing configuration for a config assistant.\n+\n+ This function will take in a configuration assistant object and check\n+ whether it is not fully configured. If it isn't it will ask the user\n+ to fill in the missing details.\n+\n+ It will also check to see whether a password has been set if the auth\n+ is username/password and ask for a password to store credentials.\n+\n+ Args:\n+ config_assistant (ConfigAssistant): a config assistant that might\n+ not be fully configured.\n+ token_password (str): an optional password to decrypt\n+ the credential token file.\n+ \"\"\"\n+ for field in config_assistant.missing:\n+ value = cli_input.ask_question(\n+ 'What is the value for [{0:s}]'.format(field), input_type=str)\n+ if value:\n+ config_assistant.set_config(field, value)\n+\n+ if config_assistant.missing:\n+ # We still have unanswered questions.\n+ return configure_missing_parameters(config_assistant, token_password)\n+\n+ config_assistant.save_config()\n+ credential_storage = crypto.CredentialStorage()\n+ credentials = credential_storage.load_credentials(\n+ config_assistant=config_assistant, password=token_password)\n+\n+ # Check if we are using username/password and we don't have credentials\n+ # saved.\n+ auth_mode = config_assistant.get_config('auth_mode')\n+ if auth_mode != 'timesketch':\n+ return None\n+\n+ if credentials:\n+ return None\n+\n+ username = config_assistant.get_config('username')\n+ password = cli_input.ask_question(\n+ 'Password for user {0:s}'.format(username), input_type=str,\n+ hide_input=True)\n+ credentials = crypto.TimesketchPwdCredentials()\n+ credentials.credential = {\n+ 'username': username,\n+ 'password': password\n+ }\n+ cred_storage = crypto.CredentialStorage()\n+ cred_storage.save_credentials(\n+ credentials, password=token_password,\n+ config_assistant=config_assistant)\n+ config_assistant.save_config()\n+ return None\n+\n+\nclass ConfigAssistant:\n\"\"\"A simple assistant that helps with setting up a Timesketch API client.\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -296,6 +296,7 @@ class CredentialStorage:\nelif config_assistant:\ntry:\npassword = config_assistant.get_config('cred_key')\n+ if not isinstance(password, bytes):\npassword = bytes(password, 'utf-8')\nexcept KeyError:\nraise IOError(\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/setup.py", "new_path": "importer_client/python/setup.py", "diff": "@@ -24,7 +24,7 @@ from setuptools import setup\nsetup(\nname='timesketch-import-client',\n- version='20200513',\n+ version='20200514',\ndescription='Timesketch Import Client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n@@ -45,7 +45,6 @@ setup(\nzip_safe=False,\nscripts=glob.glob(os.path.join('tools', '[a-z]*.py')),\ninstall_requires=frozenset([\n- 'click',\n'pandas',\n'xlrd',\n'timesketch-api-client',\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -22,10 +22,10 @@ import sys\nfrom typing import Dict\n+from timesketch_api_client import cli_input\nfrom timesketch_api_client import crypto\nfrom timesketch_api_client import config\nfrom timesketch_api_client import sketch\n-from timesketch_import_client import cli\nfrom timesketch_import_client import importer\n@@ -193,7 +193,7 @@ if __name__ == '__main__':\ncred_storage = crypto.CredentialStorage()\ntoken_password = ''\nif options.cred_prompt:\n- token_password = cli.ask_question(\n+ token_password = cli_input.ask_question(\n'Enter password to encrypt/decrypt credential file',\ninput_type=str, hide_input=True)\n@@ -233,16 +233,6 @@ if __name__ == '__main__':\nif conf_password:\nassistant.set_config('auth_mode', 'timesketch')\n- # Gather all questions that are missing.\n- while True:\n- for field in assistant.missing:\n- value = cli.ask_question(\n- 'What is the value for [{0:s}]'.format(field), input_type=str)\n- if value:\n- assistant.set_config(field, value)\n- if not assistant.missing:\n- break\n-\nif conf_password:\ncredentials = crypto.TimesketchPwdCredentials()\ncredentials.credential = {\n@@ -254,6 +244,10 @@ if __name__ == '__main__':\ncredentials, password=token_password,\nconfig_assistant=assistant)\n+ # Gather all questions that are missing.\n+ config.configure_missing_parameters(\n+ config_assistant=assistant, token_password=token_password)\n+\nlogger.info('Creating a client.')\nts_client = assistant.get_client(token_password=token_password)\nif not ts_client:\n@@ -286,7 +280,7 @@ if __name__ == '__main__':\nif options.timeline_name:\nconf_timeline_name = options.timeline_name\nelse:\n- conf_timeline_name = cli.ask_question(\n+ conf_timeline_name = cli_input.ask_question(\n'What is the timeline name', input_type=str,\ndefault=default_timeline_name)\n" } ]
Python
Apache License 2.0
google/timesketch
Adding code to complete config into the library.
263,133
14.05.2020 12:52:24
0
25d33ab85536ff0a1c5a8be298c278e2bb25213d
Minor changes to the API config client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200514',\n+ version='20200515',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -28,7 +28,7 @@ from . import crypto\nlogger = logging.getLogger('config_assistance_api')\n-def get_client(config_dict=None, config_path=''):\n+def get_client(config_dict=None, config_path='', token_password=''):\n\"\"\"Returns a Timesketch API client using the configuration assistant.\nArgs:\n@@ -36,12 +36,16 @@ def get_client(config_dict=None, config_path=''):\nthe client.\nconfig_path (str): optional path to the configuration file, if\nnot supplied a default path will be used.\n+ token_password (str): an optional password to decrypt\n+ the credential token file.\n\"\"\"\nassistant = ConfigAssistant()\nassistant.load_config_file(config_path)\nif config_dict:\nassistant.load_config_dict(config_dict)\n- return assistant.get_client()\n+\n+ configure_missing_parameters(assistant, token_password)\n+ return assistant.get_client(token_password=token_password)\ndef configure_missing_parameters(config_assistant, token_password=''):\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -329,7 +329,7 @@ class CredentialStorage:\nreturn cred_obj\nexcept TypeError:\n- logger.warning('Credential object is not \"timesketch\" auth.')\n+ logger.debug('Credential object is not \"timesketch\" auth.')\ncred_obj = TimesketchOAuthCredentials()\ncred_obj.deserialize(data_string)\n" } ]
Python
Apache License 2.0
google/timesketch
Minor changes to the API config client. (#1193)
263,133
15.05.2020 09:43:20
0
a612aadb2c936ab37816d36590960e1f97ee4ae7
Splitting credentials out of crypto storage module in API client.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/client.py", "new_path": "api_client/python/timesketch_api_client/client.py", "diff": "@@ -31,7 +31,7 @@ from google_auth_oauthlib import flow as googleauth_flow\nimport google.auth.transport.requests\nimport pandas\n-from . import crypto\n+from . import credentials\nfrom . import definitions\nfrom . import error\nfrom . import index\n@@ -227,7 +227,7 @@ class TimesketchApi(object):\nsession = flow.authorized_session()\nself._flow = flow\n- self.credentials = crypto.TimesketchOAuthCredentials()\n+ self.credentials = credentials.TimesketchOAuthCredentials()\nself.credentials.credential = flow.credentials\nreturn self.authenticate_oauth_session(session)\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/config.py", "new_path": "api_client/python/timesketch_api_client/config.py", "diff": "@@ -22,6 +22,7 @@ from google.auth.transport import requests as auth_requests\nfrom . import client\nfrom . import cli_input\n+from . import credentials as ts_credentials\nfrom . import crypto\n@@ -92,7 +93,7 @@ def configure_missing_parameters(config_assistant, token_password=''):\npassword = cli_input.ask_question(\n'Password for user {0:s}'.format(username), input_type=str,\nhide_input=True)\n- credentials = crypto.TimesketchPwdCredentials()\n+ credentials = ts_credentials.TimesketchPwdCredentials()\ncredentials.credential = {\n'username': username,\n'password': password\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/crypto.py", "new_path": "api_client/python/timesketch_api_client/crypto.py", "diff": "@@ -17,161 +17,18 @@ from __future__ import unicode_literals\nimport base64\nimport os\nimport getpass\n-import json\nimport logging\nimport stat\nfrom cryptography import fernet\n-from cryptography.hazmat.backends import default_backend\n+from cryptography.hazmat import backends\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC\n-from google.oauth2 import credentials\n+from . import credentials\n-logger = logging.getLogger('crypto_client_api')\n-\n-\n-class TimesketchCredentials:\n- \"\"\"Class to store and retrieve credentials for Timesketch.\"\"\"\n-\n- # The type of credential object.\n- TYPE = ''\n-\n- def __init__(self):\n- \"\"\"Initialize the credential object.\"\"\"\n- self._credential = None\n-\n- @property\n- def credential(self):\n- \"\"\"Returns the credentials back.\"\"\"\n- return self._credential\n- @credential.setter\n- def credential(self, credential_obj):\n- \"\"\"Sets the credential object.\"\"\"\n- self._credential = credential_obj\n-\n- def serialize(self):\n- \"\"\"Return serialized bytes object.\"\"\"\n- data = self.to_bytes()\n- type_string = bytes(self.TYPE, 'utf-8').rjust(10)[:10]\n-\n- return type_string + data\n-\n- def deserialize(self, data):\n- \"\"\"Deserialize a credential object from bytes.\n-\n- Args:\n- data (bytes): serialized credential object.\n- \"\"\"\n- type_data = data[:10]\n- type_string = type_data.decode('utf-8').strip()\n- if not self.TYPE.startswith(type_string):\n- raise TypeError('Not the correct serializer.')\n-\n- self.from_bytes(data[10:])\n-\n- def to_bytes(self):\n- \"\"\"Convert the credential object into bytes for storage.\"\"\"\n- raise NotImplementedError\n-\n- def from_bytes(self, data):\n- \"\"\"Deserialize a credential object from bytes.\n-\n- Args:\n- data (bytes): serialized credential object.\n- \"\"\"\n- raise NotImplementedError\n-\n-\n-class TimesketchPwdCredentials(TimesketchCredentials):\n- \"\"\"Username and password credentials for Timesketch authentication.\"\"\"\n-\n- TYPE = 'timesketch'\n-\n- def from_bytes(self, data):\n- \"\"\"Deserialize a credential object from bytes.\n-\n- Args:\n- data (bytes): serialized credential object.\n-\n- Raises:\n- TypeError: if the data is not in bytes.\n- \"\"\"\n- if not isinstance(data, bytes):\n- raise TypeError('Data needs to be bytes.')\n-\n- try:\n- data_dict = json.loads(data.decode('utf-8'))\n- except ValueError:\n- raise TypeError('Unable to parse the byte string.')\n-\n- if not 'username' in data_dict:\n- raise TypeError('Username is not set.')\n- if not 'password' in data_dict:\n- raise TypeError('Password is not set.')\n- self._credential = data_dict\n-\n- def to_bytes(self):\n- \"\"\"Convert the credential object into bytes for storage.\"\"\"\n- if not self._credential:\n- return b''\n-\n- data_string = json.dumps(self._credential)\n- return bytes(data_string, 'utf-8')\n-\n-\n-class TimesketchOAuthCredentials(TimesketchCredentials):\n- \"\"\"OAUTH credentials for Timesketch authentication.\"\"\"\n-\n- TYPE = 'oauth'\n-\n- def from_bytes(self, data):\n- \"\"\"Deserialize a credential object from bytes.\n-\n- Args:\n- data (bytes): serialized credential object.\n-\n- Raises:\n- TypeError: if the data is not in bytes.\n- \"\"\"\n- if not isinstance(data, bytes):\n- raise TypeError('Data needs to be bytes.')\n-\n- try:\n- token_dict = json.loads(data.decode('utf-8'))\n- except ValueError:\n- raise TypeError('Unable to parse the byte string.')\n-\n- self._credential = credentials.Credentials(\n- token=token_dict.get('token'),\n- refresh_token=token_dict.get('_refresh_token'),\n- id_token=token_dict.get('_id_token'),\n- token_uri=token_dict.get('_token_uri'),\n- client_id=token_dict.get('_client_id'),\n- client_secret=token_dict.get('_client_secret')\n- )\n-\n- def to_bytes(self):\n- \"\"\"Convert the credential object into bytes for storage.\"\"\"\n- if not self._credential:\n- return b''\n-\n- cred_obj = self._credential\n- data = {\n- 'token': cred_obj.token,\n- '_scopes': getattr(cred_obj, '_scopes', []),\n- '_refresh_token': getattr(cred_obj, '_refresh_token', ''),\n- '_id_token': getattr(cred_obj, '_id_token', ''),\n- '_token_uri': getattr(cred_obj, '_token_uri', ''),\n- '_client_id': getattr(cred_obj, '_client_id', ''),\n- '_client_secret': getattr(cred_obj, '_client_secret', ''),\n- }\n- if cred_obj.expiry:\n- data['expiry'] = cred_obj.expiry.isoformat()\n- data_string = json.dumps(data)\n-\n- return bytes(data_string, 'utf-8')\n+logger = logging.getLogger('crypto_client_api')\nclass CredentialStorage:\n@@ -206,7 +63,7 @@ class CredentialStorage:\nlength=32,\nsalt=salt,\niterations=100000,\n- backend=default_backend()\n+ backend=backends.default_backend()\n)\nreturn base64.urlsafe_b64encode(\nkdf.derive(password))\n@@ -225,7 +82,7 @@ class CredentialStorage:\nthat contains a stored copy of the credential object.\nArgs:\n- cred_obj (TimesketchCredentials): the credential\n+ cred_obj (credentials.TimesketchCredentials): the credential\nobject that is to be stored on disk.\nfile_path (str): full path to the file storing the saved\ncredentials.\n@@ -323,7 +180,7 @@ class CredentialStorage:\n'{0!s})'.format(e))\n# TODO: Implement a manager.\n- cred_obj = TimesketchPwdCredentials()\n+ cred_obj = credentials.TimesketchPwdCredentials()\ntry:\ncred_obj.deserialize(data_string)\n@@ -331,6 +188,6 @@ class CredentialStorage:\nexcept TypeError:\nlogger.debug('Credential object is not \"timesketch\" auth.')\n- cred_obj = TimesketchOAuthCredentials()\n+ cred_obj = credentials.TimesketchOAuthCredentials()\ncred_obj.deserialize(data_string)\nreturn cred_obj\n" }, { "change_type": "MODIFY", "old_path": "importer_client/python/tools/timesketch_importer.py", "new_path": "importer_client/python/tools/timesketch_importer.py", "diff": "@@ -23,6 +23,7 @@ import sys\nfrom typing import Dict\nfrom timesketch_api_client import cli_input\n+from timesketch_api_client import credentials as ts_credentials\nfrom timesketch_api_client import crypto\nfrom timesketch_api_client import config\nfrom timesketch_api_client import sketch\n@@ -234,7 +235,7 @@ if __name__ == '__main__':\nassistant.set_config('auth_mode', 'timesketch')\nif conf_password:\n- credentials = crypto.TimesketchPwdCredentials()\n+ credentials = ts_credentials.TimesketchPwdCredentials()\ncredentials.credential = {\n'username': assistant.get_config('username'),\n'password': conf_password\n" } ]
Python
Apache License 2.0
google/timesketch
Splitting credentials out of crypto storage module in API client.
263,133
15.05.2020 09:51:24
0
3bf44a16234dff6c351fbdcfdf8967b5fcbbf412
forgot to add the new file
[ { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/credentials.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch API crypto storage library for OAUTH client.\"\"\"\n+from __future__ import unicode_literals\n+\n+import base64\n+import os\n+import getpass\n+import json\n+import logging\n+import stat\n+\n+from google.oauth2 import credentials\n+\n+\n+logger = logging.getLogger('crypto_client_api')\n+\n+\n+class TimesketchCredentials:\n+ \"\"\"Class to store and retrieve credentials for Timesketch.\"\"\"\n+\n+ # The type of credential object.\n+ TYPE = ''\n+\n+ def __init__(self):\n+ \"\"\"Initialize the credential object.\"\"\"\n+ self._credential = None\n+\n+ @property\n+ def credential(self):\n+ \"\"\"Returns the credentials back.\"\"\"\n+ return self._credential\n+\n+ @credential.setter\n+ def credential(self, credential_obj):\n+ \"\"\"Sets the credential object.\"\"\"\n+ self._credential = credential_obj\n+\n+ def serialize(self):\n+ \"\"\"Return serialized bytes object.\"\"\"\n+ data = self.to_bytes()\n+ type_string = bytes(self.TYPE, 'utf-8').rjust(10)[:10]\n+\n+ return type_string + data\n+\n+ def deserialize(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+ \"\"\"\n+ type_data = data[:10]\n+ type_string = type_data.decode('utf-8').strip()\n+ if not self.TYPE.startswith(type_string):\n+ raise TypeError('Not the correct serializer.')\n+\n+ self.from_bytes(data[10:])\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ raise NotImplementedError\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+ \"\"\"\n+ raise NotImplementedError\n+\n+\n+class TimesketchPwdCredentials(TimesketchCredentials):\n+ \"\"\"Username and password credentials for Timesketch authentication.\"\"\"\n+\n+ TYPE = 'timesketch'\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+\n+ Raises:\n+ TypeError: if the data is not in bytes.\n+ \"\"\"\n+ if not isinstance(data, bytes):\n+ raise TypeError('Data needs to be bytes.')\n+\n+ try:\n+ data_dict = json.loads(data.decode('utf-8'))\n+ except ValueError:\n+ raise TypeError('Unable to parse the byte string.')\n+\n+ if not 'username' in data_dict:\n+ raise TypeError('Username is not set.')\n+ if not 'password' in data_dict:\n+ raise TypeError('Password is not set.')\n+ self._credential = data_dict\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ if not self._credential:\n+ return b''\n+\n+ data_string = json.dumps(self._credential)\n+ return bytes(data_string, 'utf-8')\n+\n+\n+class TimesketchOAuthCredentials(TimesketchCredentials):\n+ \"\"\"OAUTH credentials for Timesketch authentication.\"\"\"\n+\n+ TYPE = 'oauth'\n+\n+ def from_bytes(self, data):\n+ \"\"\"Deserialize a credential object from bytes.\n+\n+ Args:\n+ data (bytes): serialized credential object.\n+\n+ Raises:\n+ TypeError: if the data is not in bytes.\n+ \"\"\"\n+ if not isinstance(data, bytes):\n+ raise TypeError('Data needs to be bytes.')\n+\n+ try:\n+ token_dict = json.loads(data.decode('utf-8'))\n+ except ValueError:\n+ raise TypeError('Unable to parse the byte string.')\n+\n+ self._credential = credentials.Credentials(\n+ token=token_dict.get('token'),\n+ refresh_token=token_dict.get('_refresh_token'),\n+ id_token=token_dict.get('_id_token'),\n+ token_uri=token_dict.get('_token_uri'),\n+ client_id=token_dict.get('_client_id'),\n+ client_secret=token_dict.get('_client_secret')\n+ )\n+\n+ def to_bytes(self):\n+ \"\"\"Convert the credential object into bytes for storage.\"\"\"\n+ if not self._credential:\n+ return b''\n+\n+ cred_obj = self._credential\n+ data = {\n+ 'token': cred_obj.token,\n+ '_scopes': getattr(cred_obj, '_scopes', []),\n+ '_refresh_token': getattr(cred_obj, '_refresh_token', ''),\n+ '_id_token': getattr(cred_obj, '_id_token', ''),\n+ '_token_uri': getattr(cred_obj, '_token_uri', ''),\n+ '_client_id': getattr(cred_obj, '_client_id', ''),\n+ '_client_secret': getattr(cred_obj, '_client_secret', ''),\n+ }\n+ if cred_obj.expiry:\n+ data['expiry'] = cred_obj.expiry.isoformat()\n+ data_string = json.dumps(data)\n+\n+ return bytes(data_string, 'utf-8')\n" } ]
Python
Apache License 2.0
google/timesketch
forgot to add the new file
263,133
15.05.2020 09:54:53
0
cc250c39f4585f6854cea2a9a27f56ea417267b9
docstrings make the life go round
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/credentials.py", "new_path": "api_client/python/timesketch_api_client/credentials.py", "diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n-\"\"\"Timesketch API crypto storage library for OAUTH client.\"\"\"\n+\"\"\"Timesketch API credential library.\n+\n+This library contains classes that define how to serialize the different\n+credential objects Timesketch supports.\n+\"\"\"\nfrom __future__ import unicode_literals\nimport base64\n" } ]
Python
Apache License 2.0
google/timesketch
docstrings make the life go round
263,096
16.05.2020 22:52:45
-7,200
a7a31270c80b244cbfa13c7374d6c54aab004062
Remove $ from the README.md to be consistent. In other readme files we also do not write $, thus removing it here, makes it also easier to copy & paste the line
[ { "change_type": "MODIFY", "old_path": "docker/development/README.md", "new_path": "docker/development/README.md", "diff": "@@ -5,13 +5,13 @@ You can run Timesketch on Docker in development mode.\n### Start a developer version of docker containers in this directory\n```\n-$ docker-compose up -d\n+docker-compose up -d\n```\n### Find out container ID for the timesketch container\n```\n-$ CONTAINER_ID=\"$(sudo docker container list -f name=development_timesketch -q)\"\n+CONTAINER_ID=\"$(sudo docker container list -f name=development_timesketch -q)\"\n```\nIn the output look for CONTAINER ID for the timesketch container\n@@ -26,7 +26,7 @@ echo $CONTAINER_ID\n### Start a celery container shell\n```\n-$ sudo docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n+sudo docker exec -it $CONTAINER_ID celery -A timesketch.lib.tasks worker --loglevel info\n```\n### Start development webserver\n" } ]
Python
Apache License 2.0
google/timesketch
Remove $ from the README.md to be consistent. In other readme files we also do not write $, thus removing it here, makes it also easier to copy & paste the line
263,093
20.05.2020 13:16:39
-7,200
2845175333fa066961705d7d2882263d270572d6
Use gcr.io imaghes
[ { "change_type": "MODIFY", "old_path": "docker/dev/Dockerfile", "new_path": "docker/dev/Dockerfile", "diff": "# Use the latest Timesketch development base image\n-FROM timesketch/timesketch-dev-base:20200327\n+FROM gcr.io/timesketch-build/dev/timesketch-dev-base:latest\n# Install dependencies for Timesketch\nCOPY requirements.txt /timesketch-requirements.txt\nRUN pip3 install -r /timesketch-requirements.txt\n# Copy the entrypoint script into the container\n-COPY docker/development/docker-entrypoint.sh /docker-entrypoint.sh\n+COPY docker/dev/docker-entrypoint.sh /docker-entrypoint.sh\nRUN chmod a+x /docker-entrypoint.sh\n# Load the entrypoint script to be run later\n" }, { "change_type": "MODIFY", "old_path": "docker/dev/docker-compose.yml", "new_path": "docker/dev/docker-compose.yml", "diff": "@@ -3,7 +3,7 @@ services:\ntimesketch:\nbuild:\ncontext: ../../\n- dockerfile: ./docker/development/Dockerfile\n+ dockerfile: ./docker/dev/Dockerfile\nports:\n- \"127.0.0.1:5000:5000\"\nlinks:\n" }, { "change_type": "MODIFY", "old_path": "docker/e2e/Dockerfile", "new_path": "docker/e2e/Dockerfile", "diff": "-# Use the official Docker Hub Ubuntu 18.04 base image\n-FROM ubuntu:18.04\n-\n-# Setup install environment and Timesketch dependencies\n-RUN apt-get update && apt-get -y install \\\n- apt-transport-https \\\n- apt-utils \\\n- ca-certificates \\\n- git \\\n- libffi-dev \\\n- lsb-release \\\n- software-properties-common \\\n- python3-dev \\\n- python3-pip \\\n- python3-psycopg2 \\\n- && rm -rf /var/lib/apt/lists/*\n-\n-# Install Plaso\n-RUN add-apt-repository ppa:gift/stable\n-RUN apt-get update && apt-get -y install \\\n- plaso-tools \\\n- && rm -rf /var/lib/apt/lists/*\n-\n-# Use Python 3 pip (pip3) to install Timesketch\n-RUN pip3 install timesketch\n+FROM gcr.io/timesketch-build/release/timesketch:latest\n# Copy Timesketch config files into /etc/timesketch\nADD . /tmp/timesketch\n" } ]
Python
Apache License 2.0
google/timesketch
Use gcr.io imaghes
263,178
22.05.2020 13:41:20
-7,200
7789aa73897ea53013c637e67841c53919555350
Added missing tabulate dependency to dpkg files
[ { "change_type": "MODIFY", "old_path": "config/dpkg/changelog", "new_path": "config/dpkg/changelog", "diff": "-timesketch (20200131-1) unstable; urgency=low\n+timesketch (20200507-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Wed, 12 Feb 2020 07:08:38 +0100\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Fri, 22 May 2020 13:41:01 +0200\n" }, { "change_type": "MODIFY", "old_path": "config/dpkg/control", "new_path": "config/dpkg/control", "diff": "@@ -18,7 +18,7 @@ Description: Data files for Timesketch\nPackage: python3-timesketch\nArchitecture: all\n-Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 0.9.5), python3-altair (>= 2.4.1), python3-amqp (>= 2.2.1), python3-aniso8601 (>= 1.2.1), python3-asn1crypto (>= 0.24.0), python3-attr (>= 19.1.0), python3-bcrypt (>= 3.1.3), python3-billiard (>= 3.5.0.3), python3-blinker (>= 1.4), python3-bs4 (>= 4.6.3), python3-celery (>= 4.1.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.2.5), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 6.0), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.0.2), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.0), python3-flask-migrate (>= 2.1.1), python3-flask-restful (>= 0.3.6), python3-flask-script (>= 2.0.5), python3-flask-sqlalchemy (>= 2.2), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.6.3), python3-google-auth-oauthlib (>= 0.4.1), python3-gunicorn (>= 19.7.1), python3-idna (>= 2.6), python3-itsdangerous (>= 0.24), python3-jinja2 (>= 2.10), python3-jsonschema (>= 2.6.0), python3-jwt (>= 1.6.4), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.13.3), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.22.0), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 2.10.6), python3-requests (>= 2.20.1), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.1.13), python3-tabulate (>= 0.8.6), python3-toolz (>= 0.8.2), python3-tz, python3-urllib3 (>= 1.24.1), python3-vine (>= 1.1.4), python3-werkzeug (>= 0.14.1), python3-wtforms (>= 2.1), python3-xlrd (>= 1.2.0), python3-yaml (>= 3.10), ${python3:Depends}, ${misc:Depends}\nDescription: Python 3 module of Timesketch\nTimesketch is a web based tool for collaborative forensic\ntimeline analysis. Using sketches you and your collaborators can easily\n" } ]
Python
Apache License 2.0
google/timesketch
Added missing tabulate dependency to dpkg files
263,133
25.05.2020 11:51:08
0
20d2825b014e9f027f61bab0b9026ce892f496ba
Adding an analyzer result object to API client.
[ { "change_type": "ADD", "old_path": null, "new_path": "api_client/python/timesketch_api_client/analyzer.py", "diff": "+# Copyright 2020 Google Inc. All rights reserved.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\"\"\"Timesketch API analyzer result object.\"\"\"\n+from __future__ import unicode_literals\n+\n+import json\n+import logging\n+\n+from . import definitions\n+from . import resource\n+\n+logger = logging.getLogger('analyzer_results')\n+\n+\n+class AnalyzerResult(resource.BaseResource):\n+ \"\"\"Class to store and retrieve session information for an analyzer.\"\"\"\n+\n+ def __init__(self, timeline_id, session_id, sketch_id, api):\n+ \"\"\"Initialize the class.\"\"\"\n+ self._session_id = session_id\n+ self._sketch_id = sketch_id\n+ self._timeline_id = timeline_id\n+ resource_uri = (\n+ '{0:s}/sketches/{1:d}/timelines/{2:d}/analysis/').format(\n+ api.api_root, sketch_id, timeline_id)\n+ super(AnalyzerResult, self).__init__(api, resource_uri)\n+\n+ def _fetch_data(self):\n+ \"\"\"Returns...\"\"\"\n+ response = self.api.session.get(self.resource_uri)\n+ if not response.status_code in definitions.HTTP_STATUS_CODE_20X:\n+ return {}\n+\n+ data = response.json()\n+\n+ objects = data.get('objects')\n+ if not objects:\n+ return {}\n+\n+ for result in objects[0]:\n+ result_id = result.get('id')\n+ if result_id != self._session_id:\n+ continue\n+ status_list = result.get('status', [])\n+ if len(status_list) != 1:\n+ return {}\n+ status = status_list[0]\n+\n+ timeline = result.get('timeline', {})\n+\n+ return {\n+ 'id': status.get('id', -1),\n+ 'rid': result_id,\n+ 'analyzer': result.get('analyzer_name', 'N/A'),\n+ 'results': result.get('result'),\n+ 'description': result.get('description', 'N/A'),\n+ 'timeline': timeline.get('name', 'N/A'),\n+ 'user': result.get('user', {}).get('username', 'System'),\n+ 'parameters': json.loads(result.get('parameters', '{}')),\n+ 'status': status.get('status', 'Unknown'),\n+ }\n+\n+ return {}\n+\n+ @property\n+ def id(self):\n+ \"\"\"Returns the session ID.\"\"\"\n+ return self._session_id\n+\n+ @property\n+ def results(self):\n+ \"\"\"Returns the results from the analyzer session.\"\"\"\n+ data = self._fetch_data()\n+ return data.get('results', 'No results yet.')\n+\n+ @property\n+ def status(self):\n+ \"\"\"Returns the current status of the analyzer run.\"\"\"\n+ data = self._fetch_data()\n+ return data.get('status', 'Unknown')\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/error.py", "new_path": "api_client/python/timesketch_api_client/error.py", "diff": "@@ -27,3 +27,11 @@ def error_message(response, message=None, error=RuntimeError):\ntext = soup.p.string\nraise error('{0:s}, with error [{1:d}] {2!s} {3:s}'.format(\nmessage, response.status_code, response.reason, text))\n+\n+\n+class Error(Exception):\n+ \"\"\"Base error class.\"\"\"\n+\n+\n+class UnableToRunAnalyzer(Error):\n+ \"\"\"Raised when unable to run an analyzer.\"\"\"\n" }, { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/sketch.py", "new_path": "api_client/python/timesketch_api_client/sketch.py", "diff": "@@ -20,6 +20,7 @@ import logging\nimport pandas\n+from . import analyzer\nfrom . import aggregation\nfrom . import definitions\nfrom . import error\n@@ -665,8 +666,12 @@ class Sketch(resource.BaseResource):\nthere are more than a single timeline with the same name a\ntimeline_id is required.\n+ Raises:\n+ error.UnableToRunAnalyzer: if not able to run the analyzer.\n+\nReturns:\n- A string with the results of the API call to run the analyzer.\n+ If the analyzer runs successfully return back an AnalyzerResult\n+ object.\n\"\"\"\nif not timeline_id and not timeline_name:\nreturn (\n@@ -681,7 +686,7 @@ class Sketch(resource.BaseResource):\n# with parameters for the analyzer.\nif analyzer_kwargs:\nif not isinstance(analyzer_kwargs, dict):\n- return (\n+ raise error.UnableToRunAnalyzer(\n'Unable to run analyzer, analyzer kwargs needs to be a '\n'dict')\nif analyzer_name not in analyzer_kwargs:\n@@ -696,14 +701,15 @@ class Sketch(resource.BaseResource):\ntimelines.append(timeline_dict.get('id'))\nif not timelines:\n- return 'No timelines with the name: {0:s} were found'.format(\n- timeline_name)\n+ raise error.UnableToRunAnalyzer(\n+ 'No timelines with the name: {0:s} were found'.format(\n+ timeline_name))\nif len(timelines) != 1:\n- return (\n+ raise error.UnableToRunAnalyzer(\n'There are {0:d} timelines defined in the sketch with '\n'this name, please use a unique name or a '\n- 'timeline ID').format(len(timelines))\n+ 'timeline ID'.format(len(timelines)))\ntimeline_id = timelines[0]\n@@ -716,10 +722,26 @@ class Sketch(resource.BaseResource):\nresponse = self.api.session.post(resource_url, json=data)\nif response.status_code == 200:\n- return response.json()\n-\n- return '[{0:d}] {1!s} {2!s}'.format(\n- response.status_code, response.reason, response.text)\n+ data = response.json()\n+ objects = data.get('objects', [])\n+ if not objects:\n+ raise error.UnableToRunAnalyzer(\n+ 'No session data returned back, analyzer may have run but '\n+ 'unable to verify, please verify manually.')\n+\n+ session_id = objects[0].get('analysis_session')\n+ if not session_id:\n+ raise error.UnableToRunAnalyzer(\n+ 'Analyzer may have run, but there is no session ID to '\n+ 'verify that it has. Please verify manually.')\n+\n+ session = analyzer.AnalyzerResult(\n+ timeline_id=timeline_id, session_id=session_id,\n+ sketch_id=self.id, api=self.api)\n+ return session\n+\n+ raise error.UnableToRunAnalyzer('[{0:d}] {1!s} {2!s}'.format(\n+ response.status_code, response.reason, response.text))\ndef remove_acl(self, user_list=None, group_list=None, remove_public=False):\n\"\"\"Remove users or groups to the sketch ACL.\n" } ]
Python
Apache License 2.0
google/timesketch
Adding an analyzer result object to API client.
263,133
25.05.2020 11:51:57
0
6a168a384ac65d97c5241cacd1cac93e96a8de37
Upgrading the version number.
[ { "change_type": "MODIFY", "old_path": "api_client/python/setup.py", "new_path": "api_client/python/setup.py", "diff": "@@ -21,7 +21,7 @@ from setuptools import setup\nsetup(\nname='timesketch-api-client',\n- version='20200520',\n+ version='20200525',\ndescription='Timesketch API client',\nlicense='Apache License, Version 2.0',\nurl='http://www.timesketch.org/',\n" } ]
Python
Apache License 2.0
google/timesketch
Upgrading the version number.
263,133
25.05.2020 15:27:20
0
ec45d8e5e840d79e8753fa8ba83652cba51835ba
Making minor changes to the analyzer object.
[ { "change_type": "MODIFY", "old_path": "api_client/python/timesketch_api_client/analyzer.py", "new_path": "api_client/python/timesketch_api_client/analyzer.py", "diff": "\"\"\"Timesketch API analyzer result object.\"\"\"\nfrom __future__ import unicode_literals\n+import datetime\nimport json\nimport logging\n@@ -49,7 +50,7 @@ class AnalyzerResult(resource.BaseResource):\nreturn {}\nfor result in objects[0]:\n- result_id = result.get('id')\n+ result_id = result.get('analysissession_id', -1)\nif result_id != self._session_id:\ncontinue\nstatus_list = result.get('status', [])\n@@ -60,15 +61,22 @@ class AnalyzerResult(resource.BaseResource):\ntimeline = result.get('timeline', {})\nreturn {\n- 'id': status.get('id', -1),\n- 'rid': result_id,\n+ 'id': result_id,\n'analyzer': result.get('analyzer_name', 'N/A'),\n'results': result.get('result'),\n'description': result.get('description', 'N/A'),\n- 'timeline': timeline.get('name', 'N/A'),\n'user': result.get('user', {}).get('username', 'System'),\n'parameters': json.loads(result.get('parameters', '{}')),\n'status': status.get('status', 'Unknown'),\n+ 'status_date': status.get('updated_at', ''),\n+ 'log': result.get('log', ''),\n+ 'created': result.get('created_at'),\n+ 'timeline': timeline.get('name', 'N/A'),\n+ 'timeline_id': timeline.get('id', -1),\n+ 'timeline_user': timeline.get('user', {}).get(\n+ 'username', 'System'),\n+ 'timeline_name': timeline.get('name', 'N/A'),\n+ 'timeline_deleted': timeline.get('deleted', False),\n}\nreturn {}\n@@ -78,6 +86,12 @@ class AnalyzerResult(resource.BaseResource):\n\"\"\"Returns the session ID.\"\"\"\nreturn self._session_id\n+ @property\n+ def log(self):\n+ \"\"\"Returns back logs from the analyzer session, if there are any.\"\"\"\n+ data = self._fetch_data()\n+ return data.get('log', 'No recorded logs.')\n+\n@property\ndef results(self):\n\"\"\"Returns the results from the analyzer session.\"\"\"\n@@ -89,3 +103,12 @@ class AnalyzerResult(resource.BaseResource):\n\"\"\"Returns the current status of the analyzer run.\"\"\"\ndata = self._fetch_data()\nreturn data.get('status', 'Unknown')\n+\n+ @property\n+ def status_string(self):\n+ \"\"\"Returns a longer version of a status string.\"\"\"\n+ data = self._fetch_data()\n+ return '[{0:s}] Status: {1:s}'.format(\n+ data.get('status_date', datetime.datetime.utcnow().isoformat()),\n+ data.get('status', 'Unknown')\n+ )\n" }, { "change_type": "MODIFY", "old_path": "timesketch/api/v1/resources.py", "new_path": "timesketch/api/v1/resources.py", "diff": "@@ -188,6 +188,7 @@ class ResourceMixin(object):\n'analyzer_name': fields.String,\n'parameters': fields.String,\n'result': fields.String,\n+ 'analysissession_id': fields.Integer,\n'log': fields.String,\n'user': fields.Nested(user_fields),\n'timeline': fields.Nested(timeline_fields),\n@@ -2564,12 +2565,20 @@ class AnalysisResource(ResourceMixin, Resource):\n\"\"\"\nsketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\nif not sketch.has_permission(current_user, 'read'):\nabort(\nHTTP_STATUS_CODE_FORBIDDEN,\n'User does not have read access to sketch')\ntimeline = Timeline.query.get(timeline_id)\n+ if not timeline:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No timeline found with this ID.')\n+\nanalysis_history = Analysis.query.filter_by(timeline=timeline).all()\nreturn self.to_json(analysis_history)\n" } ]
Python
Apache License 2.0
google/timesketch
Making minor changes to the analyzer object.