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,093 | 02.10.2020 14:54:07 | -7,200 | a7ba9ecb664ea59b63a88442c29e9ebc5a5ac124 | Handle missing chips in filter | [
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -299,7 +299,8 @@ class View(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\n'terminate_after': DEFAULT_LIMIT,\n'indices': [],\n'exclude': [],\n- 'order': 'asc'\n+ 'order': 'asc',\n+ 'chips': []\n}\n# If not provided, get the saved filter from the view\nif not query_filter:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Handle missing chips in filter (#1387) |
263,133 | 02.10.2020 14:11:47 | 0 | 3998aaa802f7b574f660caf634e059c72dd6e33e | Adding the ability to check your own permission to a 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": "@@ -75,6 +75,19 @@ class Sketch(resource.BaseResource):\nreturn {}\nreturn json.loads(permission_string)\n+ @property\n+ def my_acl(self):\n+ \"\"\"Property that returns back the ACL for the current user.\"\"\"\n+ data = self.lazyload_data()\n+ objects = data.get('objects')\n+ if not objects:\n+ return []\n+ data_object = objects[0]\n+ permission_string = data_object.get('my_permissions')\n+ if not permission_string:\n+ return []\n+ return json.loads(permission_string)\n+\n@property\ndef labels(self):\n\"\"\"Property that returns the sketch labels.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201001'\n+__version__ = '20201002'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/__init__.py",
"new_path": "timesketch/api/v1/resources/__init__.py",
"diff": "@@ -170,6 +170,7 @@ class ResourceMixin(object):\n'label_string': fields.String,\n'status': fields.Nested(status_fields),\n'all_permissions': fields.String,\n+ 'my_permissions': fields.String,\n'created_at': fields.DateTime,\n'updated_at': fields.DateTime\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/acl.py",
"new_path": "timesketch/models/acl.py",
"diff": "@@ -173,6 +173,21 @@ class AccessControlMixin(object):\nreturn ace\nreturn ace\n+ @property\n+ def my_permissions(self):\n+ \"\"\"Return a string with the permissions of the current user.\"\"\"\n+ has_permissions = []\n+\n+ permissions = ['read', 'write', 'delete']\n+ for permission in permissions:\n+ if self.has_permission(user=current_user, permission=permission):\n+ has_permissions.append(permission)\n+\n+ if current_user.admin:\n+ has_permissions.append('admin')\n+\n+ return json.dumps(has_permissions)\n+\n@property\ndef all_permissions(self):\n\"\"\"Return a string with all object permissions.\"\"\"\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding the ability to check your own permission to a sketch. (#1389) |
263,133 | 06.10.2020 09:12:48 | 0 | 7e5513ba4cd1b6d6a3e74e16e126567d95b8fddc | Adding attributes to the sketch model. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -50,6 +50,7 @@ class Sketch(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nevents = relationship('Event', backref='sketch', lazy='select')\nstories = relationship('Story', backref='sketch', lazy='select')\naggregations = relationship('Aggregation', backref='sketch', lazy='select')\n+ attributes = relationship('Attribute', backref='sketch', lazy='select')\naggregationgroups = relationship(\n'AggregationGroup', backref='sketch', lazy='select')\nanalysis = relationship('Analysis', backref='sketch', lazy='select')\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding attributes to the sketch model. |
263,159 | 09.10.2020 12:14:49 | 0 | de89f736bdafc6e2d32e63252ee319d855d8d875 | Added support for optional keyword rdomain | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/ssh_sessionizer.py",
"new_path": "timesketch/lib/analyzers/ssh_sessionizer.py",
"diff": "@@ -12,15 +12,16 @@ from timesketch.lib.analyzers import sessionizer\nSSH_PATTERN = re.compile(r'^\\[sshd\\] \\[(?P<process_id>\\d+)\\]:')\n# pylint: disable=line-too-long\n-# Pattern for message of SSH events for successful connection to port:\n-# '[sshd] [{process_id}]: Connection from {client_ip} port {client_port} on {host_ip} port {host_port}'\n+# Pattern for message of SSH events for successful connection to port (rdomain is optional):\n+# '[sshd] [{process_id}]: Connection from {client_ip} port {client_port} on {host_ip} port {host_port} rdomain {rdomain}'\n#\n# The SSH_CONNECTION_PATTERN is compatible with IPv4\n# TODO Change the pattern to be compatible also with IPv6\nSSH_CONNECTION_PATTERN = \\\nre.compile(r'^\\[sshd\\] \\[(?P<process_id>\\d+)\\]: Connection from ' + \\\nr'(?P<client_ip>(\\d{1,3}\\.){3}\\d{1,3}) port (?P<client_port>\\d+) on ' + \\\n- r'(?P<host_ip>(\\d{1,3}\\.){3}\\d{1,3}) port (?P<host_port>\\d+)$')\n+ r'(?P<host_ip>(\\d{1,3}\\.){3}\\d{1,3}) port (?P<host_port>\\d+)' + \\\n+ r'( rdomain (?P<rdomain>.*))?$')\nclass SSHSessionizerSketchPlugin(sessionizer.SessionizerSketchPlugin):\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added support for optional keyword rdomain |
263,133 | 12.10.2020 17:10:04 | 0 | 60eb7d7828480df6292c61de5aeecd38e693fa9d | Minor bug fixes here and there. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sketch.py",
"new_path": "api_client/python/timesketch_api_client/sketch.py",
"diff": "@@ -317,8 +317,8 @@ class Sketch(resource.BaseResource):\nquery_filter = {\n'time_start': None,\n'time_end': None,\n- 'size': self.DEFAULT_SIZE_LIMIT,\n- 'terminate_after': self.DEFAULT_SIZE_LIMIT,\n+ 'size': 100,\n+ 'terminate_after': 100,\n'indices': '_all',\n'order': 'asc'\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201002'\n+__version__ = '20201013'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "requirements.txt",
"new_path": "requirements.txt",
"diff": "@@ -16,9 +16,9 @@ google-auth==1.7.0\ngoogle_auth_oauthlib==0.4.1\ngunicorn==19.10.0 # Note: Last version to support py2\nneo4jrestclient==2.1.1\n-numpy==1.17.5\n+numpy==1.19.0\noauthlib==3.1.0\n-pandas==0.25.3\n+pandas==1.1.3\nPyJWT==1.7.1\npython_dateutil==2.8.1\nPyYAML==5.3\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/stories/api_fetcher.py",
"new_path": "timesketch/lib/stories/api_fetcher.py",
"diff": "@@ -69,9 +69,16 @@ class ApiDataFetcher(interface.DataFetcher):\nif not agg_class:\nreturn pd.DataFrame()\n- aggregator = agg_class(sketch_id=self._sketch_id)\n+\nparameter_string = aggregation.parameters\nparameters = json.loads(parameter_string)\n+ index = parameters.pop('index', None)\n+ aggregator = agg_class(sketch_id=self._sketch_id, index=index)\n+\n+ chart_type = parameters.pop('supported_charts', None)\n+ chart_color = parameters.pop('chart_color', 'N/A')\n+ chart_title = parameters.pop('chart_title', 'N/A')\n+\ndata = {\n'aggregation': aggregator.run(**parameters),\n'name': aggregation.name,\n@@ -79,6 +86,8 @@ class ApiDataFetcher(interface.DataFetcher):\n'agg_type': aggregation.agg_type,\n'parameters': parameters,\n'chart_type': aggregation.chart_type,\n+ 'chart_title': chart_title,\n+ 'chart_color': chart_color,\n'user': aggregation.user,\n}\nreturn data\n@@ -117,14 +126,20 @@ class ApiDataFetcher(interface.DataFetcher):\nif not agg_class:\ncontinue\n- aggregator_obj = agg_class(sketch_id=self._sketch_id)\n+\n+\n+ index = aggregator_parameters.pop('index', None)\n+ aggregator_obj = agg_class(sketch_id=self._sketch_id, index=index)\nchart_type = aggregator_parameters.pop('supported_charts', None)\ncolor = aggregator_parameters.pop('chart_color', '')\n+ chart_title = aggregator_parameters.pop('chart_title', None)\nresult_obj = aggregator_obj.run(**aggregator_parameters)\n+ title = chart_title or aggregator_obj.chart_title\n+\nchart = result_obj.to_chart(\nchart_name=chart_type,\n- chart_title=aggregator_obj.chart_title,\n+ chart_title=title,\nas_chart=True, interactive=True, color=color)\nif result_chart is None:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor bug fixes here and there. |
263,133 | 12.10.2020 19:26:38 | 0 | 907076ce7c40393ae8438b83f57b8421cf59b8f7 | Fixing a linter issue | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/stories/api_fetcher.py",
"new_path": "timesketch/lib/stories/api_fetcher.py",
"diff": "@@ -75,7 +75,7 @@ class ApiDataFetcher(interface.DataFetcher):\nindex = parameters.pop('index', None)\naggregator = agg_class(sketch_id=self._sketch_id, index=index)\n- chart_type = parameters.pop('supported_charts', None)\n+ _ = parameters.pop('supported_charts', None)\nchart_color = parameters.pop('chart_color', 'N/A')\nchart_title = parameters.pop('chart_title', 'N/A')\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixing a linter issue |
263,096 | 14.10.2020 16:31:00 | -7,200 | 57d11614263a94e53b3e846557c1b5f111239d4a | Update APIClient.md
A small explanation how to use the return_fields filter | [
{
"change_type": "MODIFY",
"old_path": "docs/APIClient.md",
"new_path": "docs/APIClient.md",
"diff": "@@ -150,6 +150,13 @@ data = sketch.explore('google.com', as_pandas=True)\nThis will return back a pandas DataFrame with the search results.\n+Another example search query:\n+```\n+data = sketch.explore('192.168.0.1 AND NOT timestamp_desc:foobar', as_pandas=True,return_fields='datetime,message,timestamp_desc')\n+```\n+\n+This will return back a pandas DataFrame with the search results limited to the columns.\n+\n### Aggregations\nAnother option to explore the data is via aggregations. To get a list of available aggregators use:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Update APIClient.md
A small explanation how to use the return_fields filter |
263,133 | 15.10.2020 14:42:28 | 0 | 96ec30adf0b8c2e46ce66f0dd1ca389bfc8abe02 | API client: Adding a check for scroll ID in the explore 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": "@@ -947,6 +947,10 @@ class Sketch(resource.BaseResource):\nif stop_size and total_count >= stop_size:\nbreak\n+ if not scroll_id:\n+ logger.debug('No scroll ID, will stop.')\n+ break\n+\nmore_response = self.api.session.post(resource_url, json=form_data)\nif not error.check_return_status(more_response, logger):\nerror.error_message(\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201013'\n+__version__ = '20201015'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | API client: Adding a check for scroll ID in the explore function (#1413) |
263,133 | 18.10.2020 16:36:37 | 0 | 0ea12f20509f5e71b22064f7f7ab893ddb95d9c3 | Making few more changes to the colab | [
{
"change_type": "MODIFY",
"old_path": "notebooks/colab-timesketch-demo.ipynb",
"new_path": "notebooks/colab-timesketch-demo.ipynb",
"diff": "\"name\": \"Timesketch And Colab.ipynb\",\n\"provenance\": [],\n\"private_outputs\": true,\n+ \"toc_visible\": true,\n\"include_colab_link\": true\n},\n\"kernelspec\": {\n\"\\n\",\n\"## README\\n\",\n\"\\n\",\n- \"If you want to have your own copy of the colab to make some changes or do some other experimentation you can simply select \\\"File / Save a Copy in Drive\\\" button to make your own copy of this colab and start making changes.\\n\",\n+ \"If you simply click the `connect` button in the upper right corner you will\\n\",\n+ \"connect to a kernel runtime running in the cloud. It is a great way to explore\\n\",\n+ \"what colab has to offer and provides a quick way to play with the demo data.\\n\",\n\"\\n\",\n- \"If you want to connect colab to your own Timesketch instance (that is if it is not publicly reachable) you can build your own colab runtime, hit the small triangle right next to the \\\"**Connect**\\\" button in the upper right corner and select \\\"Connect to local runtime\\\". There will be instructions on how to setup your local runtime there. \\n\",\n+ \"However if you want to connect to your own Timesketch instance, or load data\\n\",\n+ \"from local drive or don't want the data to be read into a cloud machine then\\n\",\n+ \"it is better to run from a local runtime environment. Install jupyter on\\n\",\n+ \"your machine and follow the [guideline posted here](https://research.google.com/colaboratory/local-runtimes.html).\\n\",\n+ \"These instructions are also available from the pop-up that comes when\\n\",\n+ \"you select a local runtime.\\n\",\n\"\\n\",\n- \"Once you have your local runtime setup you should be able to reach your local Timesketch instance.\\n\"\n+ \"Once you have your local runtime setup you should be able to reach your local Timesketch instance.\\n\",\n+ \"\\n\",\n+ \"You cannot save changes to this colab document, if you want to have your own copy of the colab to make changes or do some other experimentation you can simply select \\\"File / Save a Copy in Drive\\\" button to make your own copy of this colab and start making changes.\\n\"\n]\n},\n{\n\"\\n\",\n\"Let's start by installing the TS API client... all commands that start with ! are executed in the shell, therefore if you are missing Python packages you can use pip.\\n\",\n\"\\n\",\n- \"This colab uses python2 as the underlying python binary.\"\n+ \"This is not needed if you are running a local kernel, that has the library already installed.\"\n]\n},\n{\n\"execution_count\": null,\n\"outputs\": []\n},\n- {\n- \"cell_type\": \"markdown\",\n- \"metadata\": {\n- \"id\": \"lWnyv25sRUyk\"\n- },\n- \"source\": [\n- \"Then we need to import some libraries that we'll use in this colab.\"\n- ]\n- },\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"nh4pwmG-RI2w\"\n+ \"id\": \"nh4pwmG-RI2w\",\n+ \"cellView\": \"form\"\n},\n\"source\": [\n+ \"# @title Import Libraries\\n\",\n+ \"# @markdown We first need to import libraries that we will use throughout the colab.\\n\",\n\"import altair as alt # For graphing.\\n\",\n\"import numpy as np # Never know when this will come in handy.\\n\",\n\"import pandas as pd # We will be using pandas quite heavily.\\n\",\n\"execution_count\": null,\n\"outputs\": []\n},\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"ojceENS4hEP5\"\n+ },\n+ \"source\": [\n+ \"(notice that the cell above is an actual code cell, it is just using formatting to *look nice*. If you want to see the code behind it, select the cell, and click the three dots and select \\\"Form | Show Code\\\")\"\n+ ]\n+ },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n\"The first time you request the client it will ask you questions. For this demonstration we are going to be using the demo server, so we will use the following configs:\\n\",\n\"\\n\",\n\"+ host_uri: **https://demo.timesketch.org**\\n\",\n- \"+ Uuername: **demo**\\n\",\n\"+ auth_mode: **timesketch** (this is simple user/pass)\\n\",\n+ \"+ Username: **demo**\\n\",\n\"+ Password: **demo**\\n\"\n]\n},\n},\n\"source\": [\n\"for i, sketch in enumerate(sketches):\\n\",\n- \" print(f'[{i}] {sketch.name} - {sketch.description}'\"\n+ \" print(f'[{i}] <sketch ID: {sketch.id} | {sketch.name} - {sketch.description}')\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"lT6Oh0GRSFg1\"\n},\n\"source\": [\n- \"gd_sketch = sketch_dict.get('The Greendale incident - 2019', sketches[0])\"\n+ \"gd_sketch = sketch_dict.get('Greendale', ts_client.get_sketch(1))\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"HejGxei3hfnM\"\n},\n\"source\": [\n- \"lines = []\\n\",\n- \"\\n\",\n- \"star_label = gd_sketch.search_by_label('__ts_star')\\n\",\n- \"\\n\",\n- \"for obj in star_label.get('objects', []):\\n\",\n- \" event = obj.get('_source', {})\\n\",\n- \" event['_id'] = obj.get('_id')\\n\",\n- \" event['_index'] = obj.get('_index')\\n\",\n- \" lines.append(event)\\n\",\n- \" \\n\",\n- \"labeled_events = pd.DataFrame(lines)\\n\",\n- \"\\n\",\n- \"labeled_events.shape\"\n+ \"starred_events = gd_sketch.search_by_label('__ts_star', as_pandas=True)\\n\",\n+ \"starred_events.shape\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"Logz1UvNbV87\"\n},\n\"source\": [\n- \"labeled_events.head(10)\"\n+ \"starred_events.head(10)\"\n],\n\"execution_count\": null,\n\"outputs\": []\n},\n\"source\": [\n\"pd.set_option('display.max_colwidth', 100)\\n\",\n- \"labeled_events.iloc[9]\"\n+ \"starred_events.iloc[9]\"\n],\n\"execution_count\": null,\n\"outputs\": []\n"
}
] | Python | Apache License 2.0 | google/timesketch | Making few more changes to the colab |
263,133 | 19.10.2020 14:08:50 | 0 | a6e8fb7a03a47c6d0e0f0a6903c757a7207d43fe | Updating colab | [
{
"change_type": "MODIFY",
"old_path": "notebooks/colab-timesketch-demo.ipynb",
"new_path": "notebooks/colab-timesketch-demo.ipynb",
"diff": "\"execution_count\": null,\n\"outputs\": []\n},\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"mFQTCGbNeRoR\"\n+ },\n+ \"source\": [\n+ \"### Remember to execute the cell below\\n\",\n+ \"\\n\",\n+ \"Just a gentle reminder that the cell below is a code cell, so it needs to be executed (you can see the \\\"play\\\" button next to it)\"\n+ ]\n+ },\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n\"# You can change this number if you would like to test out another view.\\n\",\n\"# The way the code works is that it checks first of you set the \\\"view_text\\\", and uses that to pick a view, otherwise the number is used.\\n\",\n\"view_number = 1\\n\",\n- \"view_text = '[phishy_domains] Phishy Domains'\\n\",\n+ \"view_text = 'Phishy Domains'\\n\",\n\"\\n\",\n\"if view_text:\\n\",\n\" for index, view in enumerate(views):\\n\",\n\"id\": \"XWjrJnivaSo9\"\n},\n\"source\": [\n- \"This tells us that the view returned back 670 events with 12 columns. Let's explore the first few entries, just so that we can wrap our head around what we got back.\"\n+ \"This tells us that the view returned back 2.284 events with 12 columns. Let's explore the first few entries, just so that we can wrap our head around what we got back.\"\n]\n},\n{\n\"id\": \"bdPUgvNtl82r\"\n},\n\"source\": [\n- \"Let's look at what columns we got back... and maybe create a slice that contains fewer columns.\"\n+ \"Let's look at what columns we got back... and maybe create a slice that contains fewer columns, or not necessarily fewer but at least more the ones that we want to be able to see.\"\n]\n},\n{\n\"execution_count\": null,\n\"outputs\": []\n},\n- {\n- \"cell_type\": \"code\",\n- \"metadata\": {\n- \"id\": \"Dqv6gXlKmEUW\"\n- },\n- \"source\": [\n- \"greendale_slice = greendale_frame[['datetime', 'timestamp_desc', 'tag', 'message', 'label']]\\n\",\n- \"\\n\",\n- \"greendale_slice.head(4)\"\n- ],\n- \"execution_count\": null,\n- \"outputs\": []\n- },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"EMvcyumPH4eW\"\n+ \"id\": \"Dqv6gXlKmEUW\"\n},\n\"source\": [\n- \"greendale_frame = gd_sketch.explore(view=views[view_number], return_fields='datetime,message,source_short,tag,timestamp_desc,url,domain,human_readable', as_pandas=True)\"\n+ \"greendale_frame = greendale_frame = gd_sketch.explore(\\n\",\n+ \" view=views[view_number],\\n\",\n+ \" return_fields='datetime,timestamp_desc,tag,message,label,url,domain,human_readable,access_count,title,domain_count,search_string',\\n\",\n+ \" as_pandas=True)\\n\",\n+ \"greendale_frame.head(4)\"\n],\n\"execution_count\": null,\n\"outputs\": []\n]\n},\n{\n- \"cell_type\": \"code\",\n+ \"cell_type\": \"markdown\",\n\"metadata\": {\n- \"id\": \"ip3vimOaIhhY\"\n+ \"id\": \"PKioTKqoI85E\"\n},\n\"source\": [\n- \"greendale_slice = greendale_frame[['datetime', 'timestamp_desc', 'tag', 'human_readable', 'url', 'domain']]\\n\",\n+ \"OK,.... since this is a phishy domain analyzer, and all the results we got back are essentially from that analyzer, let's look at few things. First of all let's look at the tags that are available.\\n\",\n\"\\n\",\n- \"greendale_slice.head(5)\"\n+ \"Let's start by doing a simple method of converting the tags that are now a list into a string and then finding the unique strings.\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"MFMRBxtRJDcK\"\n+ },\n+ \"source\": [\n+ \"greendale_frame.tag.str.join('|').unique()\"\n],\n\"execution_count\": null,\n\"outputs\": []\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n- \"id\": \"PKioTKqoI85E\"\n+ \"id\": \"5Ii81u63t_NJ\"\n},\n\"source\": [\n- \"OK,.... since this is a phishy domain analyzer, and all the results we got back are essentially from that analyzer, let's look at few things. First of all let's look at the tags tha are available.\"\n+ \"Then we can start to do this slightly differently, this time we want to get a list of all the different tags.\"\n]\n},\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"MFMRBxtRJDcK\"\n+ \"id\": \"JuTczR1_uKzO\"\n},\n\"source\": [\n- \"greendale_frame['tag_string'] = greendale_frame.tag.str.join('|')\\n\",\n+ \"tags = set()\\n\",\n+ \"def add_tag(tag_list):\\n\",\n+ \" list(map(tags.add, tag_list))\\n\",\n\"\\n\",\n- \"greendale_frame.tag_string.unique()\"\n+ \"greendale_frame.tag.apply(add_tag)\\n\",\n+ \"\\n\",\n+ \"print(tags)\\n\"\n],\n\"execution_count\": null,\n\"outputs\": []\n},\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"WYhye26yuepx\"\n+ },\n+ \"source\": [\n+ \"Let's go over the code above to understand what just happened.\\n\",\n+ \"\\n\",\n+ \"First of all a set is created, called `tags`, since this is a set it cannot contain duplicates (duplicates are ignored).\\n\",\n+ \"\\n\",\n+ \"Then we define a function that accepts a list, and then applies the function `tags.add` against every item in the list (the map function). This mean that for each entry in the supplied `tag_list` the function `tags.add` is called.\\n\",\n+ \"\\n\",\n+ \"Then finally we take the dataframe `greendale_frame` and call the `apply` function on the series `tag`. That takes the column or series `tag`, which contains lists of tags applied and then for each row in the data frame applies the function `add_tag` that we created.\\n\",\n+ \"\\n\",\n+ \"This code effectively does the following:\\n\",\n+ \"+ For each row of `greendale_frame` extract the `tag` list and apply the `add_tag` function\\n\",\n+ \"+ The add tag function takes then each entry in the tag list and adds it to the set `tags`\\n\",\n+ \"\\n\",\n+ \"This gives us a final set that contains exactly one copy of each tag that was applied to the records.\"\n+ ]\n+ },\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n\"id\": \"KP_joLR7JVJ8\"\n},\n\"source\": [\n- \"OK... so we've got some that are part of the whitelisted-domain... let's look at those the domains that are marked as \\\"phishy\\\" yet excluding those that are whitelisted.\"\n+ \"Looking at the results from the tags, we do see some `outside-active-hours` tags. Let's look at those specifically. What does that mean? That means that the timeframe analyzer determined that the browsing activity occurred outside regular hours of the timeline it analyzed.\"\n]\n},\n{\n\"id\": \"h9l165w_JdtT\"\n},\n\"source\": [\n- \"greendale_frame[~greendale_frame.tag_string.str.contains('whitelisted-domain')].domain.value_counts()\"\n+ \"greendale_frame[greendale_frame.tag.str.join(',').str.contains('outside-active-hours')].domain.value_counts()\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"-1PBtCtjJ5Ag\"\n},\n\"source\": [\n- \"greendale_slice[greendale_slice.domain == 'grendale.xyz']\"\n+ \"greendale_frame[greendale_frame.domain == 'grendale.xyz'][['datetime', 'url']]\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"vxnMcThfKEOs\"\n},\n\"source\": [\n- \"grendale = greendale_slice[greendale_slice.domain == 'grendale.xyz']\\n\",\n+ \"grendale = greendale_frame[greendale_frame.domain == 'grendale.xyz']\\n\",\n\"\\n\",\n\"string_set = set()\\n\",\n\"for string_list in grendale.human_readable:\\n\",\n\"source\": [\n\"grendale_array = grendale.url.unique()\\n\",\n\"\\n\",\n- \"greendale_slice[greendale_slice.url.isin(grendale_array)]\"\n+ \"greendale_frame[greendale_frame.url.isin(grendale_array)]\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"}\\n\",\n\"\\\"\\\"\\\"\\n\",\n\"\\n\",\n- \"data = gd_sketch.explore(query_dsl=query_dsl, return_fields='message,human_readable,datetime,timestamp_desc,source_short,data_type,tags,url,domain', as_pandas=True)\"\n+ \"data = gd_sketch.explore(\\n\",\n+ \"\\t\\tquery_dsl=query_dsl, \\n\",\n+ \"\\t\\treturn_fields='message,human_readable,datetime,timestamp_desc,source_short,data_type,tags,url,domain',\\n\",\n+ \"\\t\\tas_pandas=True)\\n\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"Hwe_qoUR14wL\"\n},\n\"source\": [\n- \"gd_sketch.list_aggregations()\"\n+ \"[(x.id, x.name, x.description) for x in gd_sketch.list_aggregations()]\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"0-sNmn4a1-K-\"\n},\n\"source\": [\n- \"aggregation = gd_sketch.list_aggregations()[0]\"\n+ \"aggregation = gd_sketch.list_aggregations()[6]\"\n],\n\"execution_count\": null,\n\"outputs\": []\n\"id\": \"1_H6Xtdy8RoX\"\n},\n\"source\": [\n- \"OK, so from the name, we can determine that this has to do with top 10 visited domains. We can also look at all of the stored aggregations\"\n+ \"OK, so from the name, we can guess what it contains. We can also look at all of the stored aggregations\"\n]\n},\n{\n\"id\": \"DrtWSb5Ix60q\"\n},\n\"source\": [\n+ \"The chart there is empty, since the aggregation didn't contain a chart.\\n\",\n+ \"\\n\",\n+ \"\\n\",\n\"We can also take a look at what aggregators can be used, if we want to run our own custom aggregator.\"\n]\n},\n\" aggregator_name='query_bucket',\\n\",\n\" aggregator_parameters={\\n\",\n\" 'field': 'data_type',\\n\",\n- \" 'query_string': 'tag:\\\"application_execution\\\"',\\n\",\n+ \" 'query_string': 'tag:\\\"browser-search\\\"',\\n\",\n\" 'supported_charts': 'barchart',\\n\",\n\" }\\n\",\n\").table\"\n\"gd_sketch.run_aggregator(\\n\",\n\" aggregator_name='query_bucket',\\n\",\n\" aggregator_parameters={\\n\",\n- \" 'field': 'path',\\n\",\n- \" 'query_string': 'tag:\\\"application_execution\\\"',\\n\",\n+ \" 'field': 'domain',\\n\",\n+ \" 'query_string': 'tag:\\\"browser-search\\\"',\\n\",\n\" 'supported_charts': 'barchart',\\n\",\n\" }\\n\",\n\").table\"\n\"id\": \"EtRw5wEABLIt\"\n},\n\"source\": [\n- \"gd_sketch.run_aggregator(\\n\",\n+ \"agg = gd_sketch.run_aggregator(\\n\",\n\" aggregator_name='query_bucket',\\n\",\n\" aggregator_parameters={\\n\",\n- \" 'field': 'link_target',\\n\",\n- \" 'query_string': 'tag:\\\"application_execution\\\"',\\n\",\n- \" 'supported_charts': 'barchart',\\n\",\n+ \" 'field': 'search_string',\\n\",\n+ \" 'query_string': 'tag:\\\"browser-search\\\"',\\n\",\n+ \" 'supported_charts': 'hbarchart',\\n\",\n\" }\\n\",\n- \").table\"\n+ \")\\n\",\n+ \"\\n\",\n+ \"agg.table\"\n+ ],\n+ \"execution_count\": null,\n+ \"outputs\": []\n+ },\n+ {\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {\n+ \"id\": \"NAV-KN6zIg82\"\n+ },\n+ \"source\": [\n+ \"Or as a chart\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"metadata\": {\n+ \"id\": \"LM_CT7eWIfRS\"\n+ },\n+ \"source\": [\n+ \"agg.chart\"\n],\n\"execution_count\": null,\n\"outputs\": []\n},\n\"source\": [\n\"login_data = gd_sketch.explore(\\n\",\n- \" 'data_type:\\\"windows:evtx:record\\\" AND event_identifier:4624', \\n\",\n- \" return_fields='datetime,timestamp_desc,human_readable,message,tag,event_identifier,computer_name,record_number,recovered,strings,username',\\n\",\n+ \" 'tag:\\\"logon-event\\\"',\\n\",\n+ \" return_fields=(\\n\",\n+ \" 'datetime,timestamp_desc,human_readable,message,tag,event_identifier,hostname,record_number,'\\n\",\n+ \" 'recovered,strings,username,strings_parsed,logon_type,logon_process,windows_domain,'\\n\",\n+ \" 'source_username,user_id,computer_name'),\\n\",\n\" as_pandas=True\\n\",\n\")\"\n],\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n- \"id\": \"ccCwN92sQ5qb\"\n+ \"id\": \"5ApoSLqLfXbX\"\n},\n\"source\": [\n- \"It seems as the login analyzer was not working properly... so let's extract these fields manually...\"\n+ \"Let's also look at what windows domains where used:\"\n]\n},\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"cg1xPWKXa9QY\"\n+ \"id\": \"tKF9UR3mbSC-\"\n},\n\"source\": [\n- \"login_data['account_name'] = login_data.message.str.extract(r'Account Name:.+Account Name:\\\\\\\\t\\\\\\\\t([^\\\\\\\\]+)\\\\\\\\n', expand=False)\\n\",\n- \"login_data['account_domain'] = login_data.message.str.extract(r'Account Domain:.+Account Domain:\\\\\\\\t\\\\\\\\t([^\\\\\\\\]+)\\\\\\\\n', expand=False)\\n\",\n- \"login_data['process_name'] = login_data.message.str.extract(r'Process Name:.+Process Name:\\\\\\\\t\\\\\\\\t([^\\\\\\\\]+)\\\\\\\\n', expand=False)\\n\",\n- \"login_data['date'] = pd.to_datetime(login_data.datetime)\"\n+ \"login_data.windows_domain.value_counts()\"\n],\n\"execution_count\": null,\n\"outputs\": []\n{\n\"cell_type\": \"markdown\",\n\"metadata\": {\n- \"id\": \"5ApoSLqLfXbX\"\n+ \"id\": \"9fy6EAURSpvK\"\n},\n\"source\": [\n- \"What accounts have logged in:\"\n+ \"And the logon types:\"\n]\n},\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"tKF9UR3mbSC-\"\n+ \"id\": \"DFU56oKaSUMC\"\n},\n\"source\": [\n- \"login_data.account_name.value_counts()\"\n+ \"login_data.logon_type.value_counts()\"\n],\n\"execution_count\": null,\n\"outputs\": []\n},\n- {\n- \"cell_type\": \"markdown\",\n- \"metadata\": {\n- \"id\": \"9fy6EAURSpvK\"\n- },\n- \"source\": [\n- \"Let's look at all the computers in there...\"\n- ]\n- },\n{\n\"cell_type\": \"code\",\n\"metadata\": {\n- \"id\": \"DFU56oKaSUMC\"\n+ \"id\": \"vG1SCs_wLTwe\"\n},\n\"source\": [\n\"login_data.computer_name.value_counts()\"\n\" data_slice = data_frame\\n\",\n\" title = 'Accounts Logged In'\\n\",\n\" \\n\",\n- \" data_grouped = data_slice[['account_name', 'date']].groupby('account_name', as_index=False).count()\\n\",\n- \" data_grouped['count'] = data_grouped.date\\n\",\n- \" del data_grouped['date']\\n\",\n+ \" data_grouped = data_slice[['username', 'datetime']].groupby('username', as_index=False).count()\\n\",\n+ \" data_grouped.rename(columns={'datetime': 'count'}, inplace=True)\\n\",\n\"\\n\",\n\" return alt.Chart(data_grouped, width=400).mark_bar().encode(\\n\",\n- \" x='account_name', y='count',\\n\",\n- \" tooltip=['account_name', 'count']\\n\",\n+ \" x='username', y='count',\\n\",\n+ \" tooltip=['username', 'count']\\n\",\n\" ).properties(\\n\",\n\" title=title\\n\",\n\" ).interactive()\\n\"\n"
}
] | Python | Apache License 2.0 | google/timesketch | Updating colab |
263,095 | 21.10.2020 12:02:24 | -7,200 | 468f27ffe0fcfd581c0a00eae905e403c6927780 | right usage of lower() | [
{
"change_type": "MODIFY",
"old_path": "test_tools/sigma_verify_rules.py",
"new_path": "test_tools/sigma_verify_rules.py",
"diff": "@@ -131,7 +131,7 @@ def run_verifier(rules_path, config_file_path):\nfor dirpath, dirnames, files in os.walk(rules_path):\n- if 'deprecated' in [x.lower for x in dirnames]:\n+ if 'deprecated' in [x.lower() for x in dirnames]:\ndirnames.remove('deprecated')\nlogger.info('deprecated in folder / filename found - ignored')\n"
}
] | Python | Apache License 2.0 | google/timesketch | right usage of lower() |
263,133 | 21.10.2020 23:20:30 | 0 | 724a001d74107a0d812d1650600665e9c0bb4301 | Need write to run an analyzer, add ability to add/remove labels from timelines, fix bug in upload | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/timeline.py",
"new_path": "api_client/python/timesketch_api_client/timeline.py",
"diff": "@@ -132,6 +132,67 @@ class Timeline(resource.BaseResource):\nstatus = status_list[0]\nreturn status.get('status')\n+ def add_timeline_label(self, label):\n+ \"\"\"Add a label to the timelinne.\n+\n+ Args:\n+ label (str): A string with the label to add to the timeline.\n+\n+ Returns:\n+ bool: A boolean to indicate whether the label was successfully\n+ added to the timeline.\n+ \"\"\"\n+ if label in self.labels:\n+ logger.error(\n+ 'Label [{0:s}] already applied to timeline.'.format(label))\n+ return False\n+\n+ resource_url = '{0:s}/{1:s}'.format(\n+ self.api.api_root, self.resource_uri)\n+\n+ data = {\n+ 'labels': [label],\n+ 'label_action': 'add',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to add the label to the timeline.')\n+\n+ return status\n+\n+ def remove_timeline_label(self, label):\n+ \"\"\"Remove a label from the timeline.\n+\n+ Args:\n+ label (str): A string with the label to remove from the timeline.\n+\n+ Returns:\n+ bool: A boolean to indicate whether the label was successfully\n+ removed from the timeline.\n+ \"\"\"\n+ if label not in self.labels:\n+ logger.error(\n+ 'Unable to remove label [{0:s}], not a label '\n+ 'attached to this timeline.'.format(label))\n+ return False\n+\n+ resource_url = '{0:s}/{1:s}'.format(\n+ self.api.api_root, self.resource_uri)\n+\n+ data = {\n+ 'labels': [label],\n+ 'label_action': 'remove',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to remove the label from the sketch.')\n+\n+ return status\n+\ndef delete(self):\n\"\"\"Deletes the timeline.\"\"\"\nresource_url = '{0:s}/{1:s}'.format(\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201015'\n+__version__ = '20201022'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/analysis.py",
"new_path": "timesketch/api/v1/resources/analysis.py",
"diff": "@@ -125,10 +125,11 @@ class AnalyzerRunResource(resources.ResourceMixin, Resource):\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n- if not sketch.has_permission(current_user, 'read'):\n+\n+ if not sketch.has_permission(current_user, 'write'):\nreturn abort(\nHTTP_STATUS_CODE_FORBIDDEN,\n- 'User does not have read permission on the sketch.')\n+ 'User does not have write permission on the sketch.')\nform = request.json\nif not form:\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "\"\"\"Timeline resources for version 1 of the Timesketch API.\"\"\"\nimport codecs\n+import json\nimport uuid\nimport six\n@@ -143,6 +144,26 @@ class TimelineListResource(resources.ResourceMixin, Resource):\nclass TimelineResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to get timeline.\"\"\"\n+ def _add_label(self, timeline, label):\n+ \"\"\"Add a label to the timeline.\"\"\"\n+ if timeline.has_label(label):\n+ logger.warning(\n+ 'Unable to apply the label [{0:s}] to timeline {1:s}, '\n+ 'already exists.'.format(label, timeline.name))\n+ return False\n+ timeline.add_label(label, user=current_user)\n+ return True\n+\n+ def _remove_label(self, timeline, label):\n+ \"\"\"Removes a label from a timeline.\"\"\"\n+ if not timeline.has_label(label):\n+ logger.warning(\n+ 'Unable to remove the label [{0:s}] from timeline {1:s}, '\n+ 'label does not exist.'.format(label, timeline.name))\n+ return False\n+ timeline.remove_label(label)\n+ return True\n+\n@login_required\ndef get(self, sketch_id, timeline_id):\n\"\"\"Handles GET request to the resource.\n@@ -157,6 +178,10 @@ class TimelineResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\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+\n# Check that this timeline belongs to the sketch\nif timeline.sketch_id != sketch.id:\nabort(\n@@ -184,7 +209,10 @@ class TimelineResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\ntimeline = Timeline.query.get(timeline_id)\n- form = forms.TimelineForm.build(request)\n+ if not timeline:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No timeline found with this ID.')\n# Check that this timeline belongs to the sketch\nif timeline.sketch_id != sketch.id:\n@@ -202,6 +230,40 @@ class TimelineResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate form data.')\n+ form = forms.TimelineForm.build(request)\n+\n+ if form.labels.data:\n+ label_string = form.labels.data\n+ label_action = form.label_action.data\n+ if label_string:\n+ labels = json.loads(label_string)\n+ else:\n+ labels = []\n+ if not isinstance(labels, (list, tuple)):\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST, (\n+ 'Label needs to be a JSON string that '\n+ 'converts a list of strings'))\n+ if not all([isinstance(x, str) for x in labels]):\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST, (\n+ 'Label needs to be a JSON string that '\n+ 'converts a list of strings (not all strings)'))\n+ if label_action not in ('add', 'remove'):\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Label action needs to be either add or remove.')\n+\n+ changed = False\n+ if label_action == 'add':\n+ changed = self._add_label(timeline=timeline, label=label)\n+ elif label_action == 'remove':\n+ changed = self._remove_label(timeline=timeline, label=label)\n+ if changed:\n+ db_session.add(timeline)\n+ db_session.commit()\n+ return HTTP_STATUS_CODE_OK\n+\ntimeline.name = form.name.data\ntimeline.description = form.description.data\ntimeline.color = form.color.data\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/upload.py",
"new_path": "timesketch/api/v1/resources/upload.py",
"diff": "@@ -64,7 +64,6 @@ class UploadFileResource(resources.ResourceMixin, Resource):\n# Check if search index already exists.\nsearchindex = SearchIndex.query.filter_by(\nname=timeline_name,\n- description=timeline_name,\nuser=current_user,\nindex_name=index_name).first()\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/forms.py",
"new_path": "timesketch/lib/forms.py",
"diff": "@@ -126,6 +126,8 @@ class CreateTimelineForm(BaseForm):\nclass TimelineForm(NameDescriptionForm):\n\"\"\"Form to edit a timeline.\"\"\"\n+ labels = StringField('Label', validators=[Optional()])\n+ label_action = StringField('LabelAction', validators=[Optional()])\ncolor = StringField(\n'Color',\nvalidators=[DataRequired(),\n"
}
] | Python | Apache License 2.0 | google/timesketch | Need write to run an analyzer, add ability to add/remove labels from timelines, fix bug in upload |
263,133 | 21.10.2020 23:36:18 | 0 | 7e7a77243c676fda4c28703b9e32fb0a062ca4c4 | Adding few fixes | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/timeline.py",
"new_path": "api_client/python/timesketch_api_client/timeline.py",
"diff": "@@ -45,6 +45,7 @@ class Timeline(resource.BaseResource):\n\"\"\"\nself.id = timeline_id\nself._labels = []\n+ self._color = ''\nself._name = name\nself._searchindex = searchindex\nresource_uri = 'sketches/{0:d}/timelines/{1:d}/'.format(\n@@ -71,6 +72,28 @@ class Timeline(resource.BaseResource):\nreturn self._labels\n+ @property\n+ def color(self):\n+ \"\"\"Property that returns timeline color.\n+\n+ Returns:\n+ Color name as string.\n+ \"\"\"\n+ if not self._color:\n+ timeline = self.lazyload_data()\n+ self._color = timeline['objects'][0]['color']\n+ return self._color\n+\n+ @property\n+ def description(self):\n+ \"\"\"Property that returns timeline description.\n+\n+ Returns:\n+ Description as string.\n+ \"\"\"\n+ timeline = self.lazyload_data()\n+ return timeline['objects'][0]['description']\n+\n@property\ndef name(self):\n\"\"\"Property that returns timeline name.\n@@ -151,6 +174,9 @@ class Timeline(resource.BaseResource):\nself.api.api_root, self.resource_uri)\ndata = {\n+ 'name': self.name,\n+ 'description': self.description,\n+ 'color': self.color,\n'labels': [label],\n'label_action': 'add',\n}\n@@ -182,6 +208,9 @@ class Timeline(resource.BaseResource):\nself.api.api_root, self.resource_uri)\ndata = {\n+ 'name': self.name,\n+ 'description': self.description,\n+ 'color': self.color,\n'labels': [label],\n'label_action': 'remove',\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -226,12 +226,11 @@ class TimelineResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_FORBIDDEN,\n'The user does not have write permission on the sketch.')\n+ form = forms.TimelineForm.build(request)\nif not form.validate_on_submit():\nabort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to validate form data.')\n- form = forms.TimelineForm.build(request)\n-\nif form.labels.data:\nlabel_string = form.labels.data\nlabel_action = form.label_action.data\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding few fixes |
263,133 | 22.10.2020 00:07:26 | 0 | 1c940e46fd039ecaa9b7faa09f67b5639d06f7ac | Adding delete permission requirements to remove label. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -263,6 +263,12 @@ class TimelineResource(resources.ResourceMixin, Resource):\nself._add_label(timeline=timeline, label=label))\nchanged = any(changes)\nelif label_action == 'remove':\n+ if not sketch.has_permission(\n+ user=current_user, permission='delete'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'The user does not have delete permission on sketch.')\n+\nchanges = []\nfor label in labels:\nchanges.append(\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding delete permission requirements to remove label. |
263,133 | 22.10.2020 10:35:55 | 0 | 9db263c2bfe9386990d97bab9b737929e33d7609 | Updating annotations | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/lib/ontology.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+\"\"\"Ontology for attributes as well as related functions.\"\"\"\n+\n+\n+# Define the ontology that is available for Timesketch.\n+ONTOLOGY = {\n+ 'text': {\n+ 'cast_as': str,\n+ 'description': 'Free flowing text.'},\n+ 'url.safe': {\n+ 'cast_as': str,\n+ 'description': 'Safe URL that can be visited.'},\n+ 'url.bad': {\n+ 'cast_as': str,\n+ 'description': 'URL related to a sketch.'},\n+}\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -21,6 +21,7 @@ from flask import current_app\nfrom flask import url_for\nfrom sqlalchemy import Column\n+from sqlalchemy import Enum\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Integer\nfrom sqlalchemy import Unicode\n@@ -50,7 +51,8 @@ class Sketch(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nevents = relationship('Event', backref='sketch', lazy='select')\nstories = relationship('Story', backref='sketch', lazy='select')\naggregations = relationship('Aggregation', backref='sketch', lazy='select')\n- attributes = relationship('Attribute', backref='sketch', lazy='select')\n+ attributes = relationship(\n+ 'AttributeContainer', backref='sketch', lazy='select')\naggregationgroups = relationship(\n'AggregationGroup', backref='sketch', lazy='select')\nanalysis = relationship('Analysis', backref='sketch', lazy='select')\n@@ -557,35 +559,53 @@ class AnalysisSession(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nself.sketch = sketch\n-class Attribute(BaseModel):\n- \"\"\"Implements the attribute model.\"\"\"\n+class AttributeContainer(BaseModel):\n+ \"\"\"Implements the attribute container model.\"\"\"\nuser_id = Column(Integer, ForeignKey('user.id'))\nsketch_id = Column(Integer, ForeignKey('sketch.id'))\nname = Column(UnicodeText())\n- value_type = Column(UnicodeText())\n- value_string = Column(UnicodeText())\n- value_int = Column(Integer())\n+ attributes = relationship(\n+ 'Attribute', backref='attributecontainer', lazy='select')\ndef __init__(\n- self, user, sketch, name, value_type,\n- value_string='', value_int=0):\n- \"\"\"Initialize the AnalysisSession object.\n+ self, user, sketch, name):\n+ \"\"\"Initialize the AttributeContainer object.\nArgs:\nuser (User): The user who created the aggregation\nsketch (Sketch): The sketch that the aggregation is bound to\nname (str): the name of the attribute.\n- value_type (str): a string that denotes the type, can be either\n- \"string\" or \"int\".\n- value_string (str): if value_type is set to \"string\" then this\n- variable holds the value.\n- value_int (int): if value_type is set to \"int\" then this variable\n- hols the value.\n\"\"\"\n- super(Attribute, self).__init__()\n+ super(AttributeContainer, self).__init__()\nself.user = user\nself.sketch = sketch\nself.name = name\n- self.value_type = value_type\n- self.value_string = value_string\n- self.value_int = value_int\n+\n+\n+class Attribute(BaseModel):\n+ \"\"\"Implements the attribute model.\"\"\"\n+ user_id = Column(Integer, ForeignKey('user.id'))\n+ attributecontainer_id = Column(\n+ Integer, ForeignKey('attributecontainer.id'))\n+ value = Column(UnicodeText())\n+ ontology = Column(UnicodeText())\n+\n+ def __init__(\n+ self, user, attributecontainer, value, ontology):\n+ \"\"\"Initialize the Attribute object.\n+\n+ Args:\n+ user (User): The user who created the aggregation\n+ attributecontainer (AttributeContainer): The attribute container\n+ this attribute is bound to.\n+ value (str): a string that contains the value for the attribute.\n+ The ontology couold influence how this will be cast when\n+ interpreted.\n+ ontology (str): The ontology of the value, The values that can\n+ be used are defined in timesketch/lib/ontology.py (ONTOLOGY).\n+ \"\"\"\n+ super(Attribute, self).__init__()\n+ self.user = user\n+ self.attributecontainer = attributecontainer\n+ self.value = value\n+ self.ontology = ontology\n"
}
] | Python | Apache License 2.0 | google/timesketch | Updating annotations |
263,133 | 23.10.2020 09:53:34 | 0 | 72d29d994290bd06d05544a0ccb967bf7c7bb770 | Adding the ability to add/remove attributes. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sketch.py",
"new_path": "api_client/python/timesketch_api_client/sketch.py",
"diff": "@@ -233,6 +233,73 @@ class Sketch(resource.BaseResource):\nsketch = self.lazyload_data()\nreturn sketch['objects'][0]['status'][0]['status']\n+ def add_attribute_list(self, name, values, ontology='text'):\n+ \"\"\"Add an attribute to the sketch.\n+\n+ Args:\n+ name (str): The name of the attribute.\n+ values (list): A list of string values of the attribute.\n+ ontology (str): The ontology (matches with\n+ timesketch/lib/ontology.py:ONTOLOGY), which defines\n+ how the attribute is interpreted.\n+\n+ Raises:\n+ ValueError: If any of the parameters are of the wrong type.\n+\n+ Returns:\n+ Boolean value whether the attribute was successfully\n+ added or not.\n+ \"\"\"\n+ if not isinstance(name, str):\n+ raise ValueError('Name needs to be a string.')\n+\n+ if not isinstance(values, (list, tuple)):\n+ if any([not isinstance(x, str) for x in values]):\n+ raise ValueError('All values need to be a string.')\n+\n+ if not isinstance(ontology, str):\n+ raise ValueError('Ontology needs to be a string.')\n+\n+ resource_url = '{0:s}/sketches/{1:d}/attribute/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'name': name,\n+ 'values': values,\n+ 'ontology': ontology,\n+ 'action': 'post',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to add the attribute to the sketch.')\n+\n+ return status\n+\n+ def add_attribute(self, name, value, ontology='text'):\n+ \"\"\"Add an attribute to the sketch.\n+\n+ Args:\n+ name (str): The name of the attribute.\n+ value (str): Value of the attribute, stored as a string.\n+ ontology (str): The ontology (matches with\n+ timesketch/lib/ontology.py:ONTOLOGY), which defines\n+ how the attribute is interpreted.\n+\n+ Raises:\n+ ValueError: If any of the parameters are of the wrong type.\n+\n+ Returns:\n+ Boolean value whether the attribute was successfully\n+ added or not.\n+ \"\"\"\n+ if not isinstance(name, str):\n+ raise ValueError('Name needs to be a string.')\n+\n+ return self.add_attribute_list(\n+ name=name, values=[value], ontology=ontology)\n+\ndef add_sketch_label(self, label):\n\"\"\"Add a label to the sketch.\n@@ -263,6 +330,38 @@ class Sketch(resource.BaseResource):\nreturn status\n+ def remove_attribute(self, name):\n+ \"\"\"Remove an attribute from the sketch.\n+\n+ Args:\n+ name (str): The name of the attribute.\n+\n+ Raises:\n+ ValueError: If any of the parameters are of the wrong type.\n+\n+ Returns:\n+ Boolean value whether the attribute was successfully\n+ removed or not.\n+ \"\"\"\n+ if not isinstance(name, str):\n+ raise ValueError('Name needs to be a string.')\n+\n+ resource_url = '{0:s}/sketches/{1:d}/attribute/'.format(\n+ self.api.api_root, self.id)\n+\n+ data = {\n+ 'name': name,\n+ 'ontology': 'text',\n+ 'action': 'delete',\n+ }\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ logger.error('Unable to remove the attriubute from the sketch.')\n+\n+ return status\n+\ndef remove_sketch_label(self, label):\n\"\"\"Remove a label from the sketch.\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201022'\n+__version__ = '20201023'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/analysis.py",
"new_path": "timesketch/api/v1/resources/analysis.py",
"diff": "@@ -46,10 +46,6 @@ class AnalysisResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this 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"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/sketch.py",
"new_path": "timesketch/api/v1/resources/sketch.py",
"diff": "@@ -31,7 +31,6 @@ from sqlalchemy import not_\nfrom timesketch.api.v1 import resources\nfrom timesketch.api.v1 import utils\nfrom timesketch.lib import forms\n-from timesketch.lib import ontology\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_OK\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_CREATED\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n@@ -320,22 +319,6 @@ class SketchResource(resources.ResourceMixin, Resource):\n}\nviews.append(view)\n- attributes = []\n- for container in sketch.attributes:\n- if container.sketch_id != sketch.id:\n- continue\n- name = container.name\n- container_attributes = []\n- for attribute in container.attributes:\n- ontology_dict = ontology.ONTOLOGY.get(attribute.ontology, {})\n- cast_as = ontology_dict.get('cast_as', str)\n- container_attribtes.append(cast_as(attribute.value))\n-\n- if len(container_attributes) == 1:\n- attributes.append((name, container_attributes[0]))\n- else:\n- attributes.append((name, container_attributes))\n-\nmeta = dict(\naggregators=aggregators,\nviews=views,\n@@ -357,7 +340,7 @@ class SketchResource(resources.ResourceMixin, Resource):\nanalyzers=[\nx for x, y in analyzer_manager.AnalysisManager.get_analyzers()\n],\n- attributes=attributes,\n+ attributes=utils.get_sketch_attributes(sketch),\nmappings=list(mappings),\nstats=stats_per_index,\nfilter_labels=self.datastore.get_filter_labels(\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/routes.py",
"new_path": "timesketch/api/v1/routes.py",
"diff": "@@ -24,6 +24,7 @@ from .resources.aggregation import AggregationResource\nfrom .resources.analysis import AnalysisResource\nfrom .resources.analysis import AnalyzerRunResource\nfrom .resources.analysis import AnalyzerSessionResource\n+from .resources.attribute import AttributeResource\nfrom .resources.explore import ExploreResource\nfrom .resources.event import EventResource\nfrom .resources.event import EventAnnotationResource\n@@ -76,6 +77,7 @@ API_ROUTES = [\n(EventAnnotationResource, '/sketches/<int:sketch_id>/event/annotate/'),\n(EventCreateResource, '/sketches/<int:sketch_id>/event/create/'),\n(ViewListResource, '/sketches/<int:sketch_id>/views/'),\n+ (AttributeResource, '/sketches/<int:sketch_id>/attribute/'),\n(ViewResource, '/sketches/<int:sketch_id>/views/<int:view_id>/'),\n(SearchTemplateListResource, '/searchtemplate/'),\n(SearchTemplateResource, '/searchtemplate/<int:searchtemplate_id>/'),\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/utils.py",
"new_path": "timesketch/api/v1/utils.py",
"diff": "@@ -23,6 +23,7 @@ from flask import jsonify\nimport altair as alt\n+from timesketch.lib import ontology\nfrom timesketch.lib.aggregators import manager as aggregator_manager\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n@@ -41,6 +42,26 @@ def bad_request(message):\nreturn response\n+def get_sketch_attributes(sketch):\n+ \"\"\"Returns a list of attributes of a sketch.\"\"\"\n+ attributes = []\n+ for container in sketch.attributes:\n+ if container.sketch_id != sketch.id:\n+ continue\n+ name = container.name\n+ container_attributes = []\n+ for attribute in container.attributes:\n+ ontology_dict = ontology.ONTOLOGY.get(attribute.ontology, {})\n+ cast_as = ontology_dict.get('cast_as', str)\n+ container_attribtes.append(cast_as(attribute.value))\n+\n+ if len(container_attributes) == 1:\n+ attributes.append((name, container_attributes[0]))\n+ else:\n+ attributes.append((name, container_attributes))\n+ return attributes\n+\n+\ndef run_aggregator(sketch_id, aggregator_name, aggregator_parameters=None,\nindex=None):\n\"\"\"Run an aggregator and return back results.\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding the ability to add/remove attributes. |
263,133 | 23.10.2020 09:54:47 | 0 | 56723e47590e95bfb9687ac109ea80198ed96cac | Adding the attribute resource | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/api/v1/resources/attribute.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+\"\"\"Attribute resources for version 1 of the Timesketch API.\"\"\"\n+\n+import logging\n+\n+from flask import jsonify\n+from flask import request\n+from flask import abort\n+from flask_restful import Resource\n+from flask_login import login_required\n+from flask_login import current_user\n+\n+from timesketch.api.v1 import resources\n+from timesketch.api.v1 import utils\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_OK\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n+from timesketch.models import db_session\n+from timesketch.models.sketch import AttributeContainer\n+from timesketch.models.sketch import Attribute\n+from timesketch.models.sketch import Sketch\n+\n+\n+logger = logging.getLogger('timesketch.sketch_api')\n+\n+\n+class AttributeResource(resources.ResourceMixin, Resource):\n+ \"\"\"Resource for sketch attributes.\"\"\"\n+\n+ def _check_form_entry(self, form, key_to_check):\n+ \"\"\"Check a form value and return an error string if applicable.\n+\n+ Args:\n+ form (dict): the dict that keeps the form data.\n+ key_to_check (str): the key in the form data to check against.\n+\n+ Returns:\n+ An empty string if there are no issues, otherwise an\n+ error string to use to abort.\n+ \"\"\"\n+ value = form.get(key_to_check)\n+ if not value:\n+ return 'Unable to save an attribute without a {0:s}.'.format(\n+ key_to_check)\n+\n+ if not isinstance(value, str):\n+ return 'Unable to save an attribute without a {0:s}.'.format(\n+ key_to_check)\n+\n+ return ''\n+\n+ @login_required\n+ def get(self, sketch_id):\n+ \"\"\"Handles GET request to the resource.\n+\n+ Returns:\n+ An analysis in JSON (instance of flask.wrappers.Response)\n+ \"\"\"\n+ sketch = 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+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access to sketch')\n+\n+ return self.to_json(utils.get_sketch_attributes(sketch))\n+\n+ @login_required\n+ def post(self, sketch_id):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ A string with the response from running the analyzer.\n+ \"\"\"\n+ sketch = 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+\n+ if not sketch.has_permission(current_user, 'write'):\n+ return abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write permission on the sketch.')\n+\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ if not form:\n+ return abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'Unable to add or remove an attribute from a '\n+ 'sketch without any data submitted.')\n+\n+ for check in ['name', 'ontology']:\n+ error_message = self._check_form_entry(form, check)\n+ if error_message:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST, error_message)\n+\n+ action = form.get('action', '')\n+ if action not in ('post', 'delete'):\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Action needs to be either \"post\" or \"delete\"')\n+\n+ name = form.get('name')\n+ ontology = form.get('ontology', 'text')\n+\n+ if action == 'post':\n+ values = form.get('values')\n+ if not values:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Missing values from the request.')\n+\n+ if not isinstance(values, (list, tuple)):\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST, 'Values needs to be a list.')\n+\n+ if any([not isinstance(x, str) for x in values]):\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'All values needs to be stored as strings.')\n+\n+ container = AttributeContainer(\n+ user=current_user,\n+ sketch=sketch,\n+ name=name)\n+ db_session.add(container)\n+ db_session.commit()\n+\n+ for value in values:\n+ attribute = Attribute(\n+ user=current_user,\n+ attributecontainer=container,\n+ value=value,\n+ ontology=ontology)\n+ container.attributes.append(attribute)\n+ db_session.add(attribute)\n+ db_session.commit()\n+\n+ db_session.add(container)\n+ db_session.commit()\n+\n+ return HTTP_STATUS_CODE_OK\n+\n+ if action != 'delete':\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST, 'Unable to proceed.')\n+\n+ for container in sketch.attributes:\n+ if container.name != name:\n+ continue\n+ for attribute in container.attributes:\n+ container.attributes.remove(attribute)\n+ sketch.attributes.remove(container)\n+ db_session.commit()\n+\n+ return HTTP_STATUS_CODE_OK\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding the attribute resource |
263,133 | 23.10.2020 10:13:48 | 0 | b3b894d49bbbcd03aa3ab176a48ebed8a7bfa52b | Adding the db migration file. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/migrations/versions/5610b4f43b04_attributes.py",
"diff": "+\"\"\"attributes\n+\n+Revision ID: 5610b4f43b04\n+Revises: None\n+Create Date: 2020-10-23 10:09:30.817613\n+\n+\"\"\"\n+\n+# revision identifiers, used by Alembic.\n+revision = '5610b4f43b04'\n+down_revision = None\n+\n+from alembic import op\n+import sqlalchemy as sa\n+from sqlalchemy.dialects import postgresql\n+\n+def upgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.drop_table('attribute_status')\n+ op.drop_table('attribute_label')\n+ op.drop_table('attribute_comment')\n+ op.add_column('attribute', sa.Column('attributecontainer_id', sa.Integer(), nullable=True))\n+ op.add_column('attribute', sa.Column('ontology', sa.UnicodeText(), nullable=True))\n+ op.add_column('attribute', sa.Column('value', sa.UnicodeText(), nullable=True))\n+ op.drop_constraint('attribute_sketch_id_fkey', 'attribute', type_='foreignkey')\n+ op.create_foreign_key(None, 'attribute', 'attributecontainer', ['attributecontainer_id'], ['id'])\n+ op.drop_column('attribute', 'sketch_id')\n+ # ### end Alembic commands ###\n+\n+\n+def downgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.add_column('attribute', sa.Column('sketch_id', sa.INTEGER(), autoincrement=False, nullable=True))\n+ op.drop_constraint(None, 'attribute', type_='foreignkey')\n+ op.create_foreign_key('attribute_sketch_id_fkey', 'attribute', 'sketch', ['sketch_id'], ['id'])\n+ op.drop_column('attribute', 'value')\n+ op.drop_column('attribute', 'ontology')\n+ op.drop_column('attribute', 'attributecontainer_id')\n+ op.create_table('attribute_comment',\n+ sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n+ sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('comment', sa.TEXT(), autoincrement=False, nullable=True),\n+ sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_comment_parent_id_fkey'),\n+ sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_comment_user_id_fkey'),\n+ sa.PrimaryKeyConstraint('id', name='attribute_comment_pkey')\n+ )\n+ op.create_table('attribute_label',\n+ sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n+ sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('label', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n+ sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_label_parent_id_fkey'),\n+ sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_label_user_id_fkey'),\n+ sa.PrimaryKeyConstraint('id', name='attribute_label_pkey')\n+ )\n+ op.create_table('attribute_status',\n+ sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n+ sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n+ sa.Column('status', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n+ sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n+ sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_status_parent_id_fkey'),\n+ sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_status_user_id_fkey'),\n+ sa.PrimaryKeyConstraint('id', name='attribute_status_pkey')\n+ )\n+ # ### end Alembic commands ###\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding the db migration file. |
263,133 | 23.10.2020 10:44:22 | 0 | d9d5e2d136d5ff743fce9996028e5688e64ebd49 | Moving the ontology to a YAML file | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sketch.py",
"new_path": "api_client/python/timesketch_api_client/sketch.py",
"diff": "@@ -240,8 +240,8 @@ class Sketch(resource.BaseResource):\nname (str): The name of the attribute.\nvalues (list): A list of string values of the attribute.\nontology (str): The ontology (matches with\n- timesketch/lib/ontology.py:ONTOLOGY), which defines\n- how the attribute is interpreted.\n+ /etc/ontology.yaml), which defines how the attribute\n+ is interpreted.\nRaises:\nValueError: If any of the parameters are of the wrong type.\n@@ -284,7 +284,7 @@ class Sketch(resource.BaseResource):\nname (str): The name of the attribute.\nvalue (str): Value of the attribute, stored as a string.\nontology (str): The ontology (matches with\n- timesketch/lib/ontology.py:ONTOLOGY), which defines\n+ /etc/timesketch/ontology.yaml), which defines\nhow the attribute is interpreted.\nRaises:\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "data/ontology.yaml",
"diff": "+# Define the ontology that is available for Timesketch.\n+# An ontology needs to define the name, which is what will\n+# be used to identify the ontology.\n+# + cast_as is used to define how the value should be\n+# interpreted in code.\n+# + description is a short text describing the ontology.\n+\n+text:\n+ cast_as: str\n+ description: \"Free flowing text.\"\n+\n+int:\n+ case_as: int\n+ description: \"Integer\"\n+\n+url.safe:\n+ cast_as: str\n+ description: \"Safe URL that can be visited.\"\n+\n+url.bad:\n+ cast_as: str\n+ description: \"URL related to a sketch.\"\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/attribute.py",
"new_path": "timesketch/api/v1/resources/attribute.py",
"diff": "import logging\n-from flask import jsonify\nfrom flask import request\nfrom flask import abort\nfrom flask_restful import Resource\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/utils.py",
"new_path": "timesketch/api/v1/utils.py",
"diff": "@@ -45,20 +45,24 @@ def bad_request(message):\ndef get_sketch_attributes(sketch):\n\"\"\"Returns a list of attributes of a sketch.\"\"\"\nattributes = []\n+ ontology_def = ontology.ONTOLOGY\nfor container in sketch.attributes:\nif container.sketch_id != sketch.id:\ncontinue\nname = container.name\ncontainer_attributes = []\nfor attribute in container.attributes:\n- ontology_dict = ontology.ONTOLOGY.get(attribute.ontology, {})\n- cast_as = ontology_dict.get('cast_as', str)\n- container_attribtes.append(cast_as(attribute.value))\n+ ontology_dict = ontology_def.get(attribute.ontology, {})\n+ cast_as_str = ontology_dict.get('cast_as', 'str')\n+ value = ontology.cast_variable(attribute.value, cast_as_str)\n+ container_attributes.append(value)\nif len(container_attributes) == 1:\n- attributes.append((name, container_attributes[0]))\n+ attributes.append(\n+ (name, container_attributes[0], attribute.ontology))\nelse:\n- attributes.append((name, container_attributes))\n+ attributes.append(\n+ (name, container_attributes, attribute.ontology))\nreturn attributes\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/ontology.py",
"new_path": "timesketch/lib/ontology.py",
"diff": "# limitations under the License.\n\"\"\"Ontology for attributes as well as related functions.\"\"\"\n+import yaml\n-# Define the ontology that is available for Timesketch.\n-ONTOLOGY = {\n- 'text': {\n- 'cast_as': str,\n- 'description': 'Free flowing text.'},\n- 'url.safe': {\n- 'cast_as': str,\n- 'description': 'Safe URL that can be visited.'},\n- 'url.bad': {\n- 'cast_as': str,\n- 'description': 'URL related to a sketch.'},\n-}\n+from timesketch.lib.analyzers import interface\n+\n+def ontology():\n+ \"\"\"Return a dict with the ontology definitions.\"\"\"\n+ return interface.get_yaml_config('ontology.yaml')\n+\n+\n+def cast_variable(value, cast_as_str):\n+ \"\"\"Cast a variable and return it.\n+\n+ Args:\n+ value (str): Value as a string.\n+ cast_as_str (str): The type to cast it as.\n+\n+ Returns:\n+ The value cast as cast_as_str defines.\n+ \"\"\"\n+ if cast_as_str == 'str':\n+ return value\n+\n+ if cast_as_str == 'int':\n+ return int(value)\n+\n+ if cast_as_str == 'float':\n+ return float(value)\n+\n+ if cast_as_str == 'bool':\n+ return bool(value == 'True')\n+\n+ # TODO: Support more casting.\n+ return value\n+\n+\n+ONTOLOGY = ontology()\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -21,7 +21,6 @@ from flask import current_app\nfrom flask import url_for\nfrom sqlalchemy import Column\n-from sqlalchemy import Enum\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Integer\nfrom sqlalchemy import Unicode\n@@ -568,8 +567,7 @@ class AttributeContainer(BaseModel):\nattributes = relationship(\n'Attribute', backref='attributecontainer', lazy='select')\n- def __init__(\n- self, user, sketch, name):\n+ def __init__(self, user, sketch, name):\n\"\"\"Initialize the AttributeContainer object.\nArgs:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Moving the ontology to a YAML file |
263,133 | 23.10.2020 11:23:12 | 0 | 738d9b7796fb2a119ed501a56e7d62553c8cc24c | Adding few values to the ontology | [
{
"change_type": "MODIFY",
"old_path": "data/ontology.yaml",
"new_path": "data/ontology.yaml",
"diff": "@@ -21,3 +21,10 @@ url.bad:\ncast_as: str\ndescription: \"URL related to a sketch.\"\n+float:\n+ cast_as: float\n+ description: \"Float.\"\n+\n+bool:\n+ case_as: bool\n+ description: \"Boolean, True or False values.\"\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding few values to the ontology |
263,133 | 23.10.2020 13:10:57 | 0 | aad7fa77c9c6de94acefc599998c3992d4a7347c | Making changes to the schema | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/attribute.py",
"new_path": "timesketch/api/v1/resources/attribute.py",
"diff": "@@ -138,10 +138,17 @@ class AttributeResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'All values needs to be stored as strings.')\n+ for container in sketch.attributes:\n+ if container.name == name:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to add the attribute, it already exists.')\n+\ncontainer = AttributeContainer(\nuser=current_user,\nsketch=sketch,\n- name=name)\n+ name=name,\n+ ontology=ontology)\ndb_session.add(container)\ndb_session.commit()\n@@ -149,8 +156,7 @@ class AttributeResource(resources.ResourceMixin, Resource):\nattribute = Attribute(\nuser=current_user,\nattributecontainer=container,\n- value=value,\n- ontology=ontology)\n+ value=value)\ncontainer.attributes.append(attribute)\ndb_session.add(attribute)\ndb_session.commit()\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/utils.py",
"new_path": "timesketch/api/v1/utils.py",
"diff": "@@ -52,26 +52,20 @@ def get_sketch_attributes(sketch):\ncontinue\nname = container.name\ncontainer_attributes = []\n- ontology_set = set()\n- for attribute in container.attributes:\n- ontology_string = attribute.ontology\n- ontology_set.add(ontology_string)\n+ ontology_string = container.ontology\nontology_dict = ontology_def.get(ontology_string, {})\ncast_as_str = ontology_dict.get('cast_as', 'str')\n+\n+ for attribute in container.attributes:\nvalue = ontology.cast_variable(attribute.value, cast_as_str)\ncontainer_attributes.append(value)\n- if len(ontology_set) > 1:\n- logger.error(\n- 'There should only be a single ontology per attribute')\n-\n- ontology_use = list(ontology_set)[0]\nif len(container_attributes) == 1:\nattributes.append(\n- (name, container_attributes[0], ontology_use))\n+ (name, container_attributes[0], ontology_string))\nelse:\nattributes.append(\n- (name, container_attributes, ontology_use))\n+ (name, container_attributes, ontology_string))\nreturn attributes\n"
},
{
"change_type": "DELETE",
"old_path": "timesketch/migrations/versions/5610b4f43b04_attributes.py",
"new_path": null,
"diff": "-\"\"\"attributes\n-\n-Revision ID: 5610b4f43b04\n-Revises: None\n-Create Date: 2020-10-23 10:09:30.817613\n-\n-\"\"\"\n-\n-# revision identifiers, used by Alembic.\n-revision = '5610b4f43b04'\n-down_revision = None\n-\n-from alembic import op\n-import sqlalchemy as sa\n-from sqlalchemy.dialects import postgresql\n-\n-def upgrade():\n- # ### commands auto generated by Alembic - please adjust! ###\n- op.drop_table('attribute_status')\n- op.drop_table('attribute_label')\n- op.drop_table('attribute_comment')\n- op.add_column('attribute', sa.Column('attributecontainer_id', sa.Integer(), nullable=True))\n- op.add_column('attribute', sa.Column('ontology', sa.UnicodeText(), nullable=True))\n- op.add_column('attribute', sa.Column('value', sa.UnicodeText(), nullable=True))\n- op.drop_constraint('attribute_sketch_id_fkey', 'attribute', type_='foreignkey')\n- op.create_foreign_key(None, 'attribute', 'attributecontainer', ['attributecontainer_id'], ['id'])\n- op.drop_column('attribute', 'sketch_id')\n- # ### end Alembic commands ###\n-\n-\n-def downgrade():\n- # ### commands auto generated by Alembic - please adjust! ###\n- op.add_column('attribute', sa.Column('sketch_id', sa.INTEGER(), autoincrement=False, nullable=True))\n- op.drop_constraint(None, 'attribute', type_='foreignkey')\n- op.create_foreign_key('attribute_sketch_id_fkey', 'attribute', 'sketch', ['sketch_id'], ['id'])\n- op.drop_column('attribute', 'value')\n- op.drop_column('attribute', 'ontology')\n- op.drop_column('attribute', 'attributecontainer_id')\n- op.create_table('attribute_comment',\n- sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n- sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('comment', sa.TEXT(), autoincrement=False, nullable=True),\n- sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_comment_parent_id_fkey'),\n- sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_comment_user_id_fkey'),\n- sa.PrimaryKeyConstraint('id', name='attribute_comment_pkey')\n- )\n- op.create_table('attribute_label',\n- sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n- sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('label', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n- sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_label_parent_id_fkey'),\n- sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_label_user_id_fkey'),\n- sa.PrimaryKeyConstraint('id', name='attribute_label_pkey')\n- )\n- op.create_table('attribute_status',\n- sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n- sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n- sa.Column('status', sa.VARCHAR(length=255), autoincrement=False, nullable=True),\n- sa.Column('parent_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.Column('user_id', sa.INTEGER(), autoincrement=False, nullable=True),\n- sa.ForeignKeyConstraint(['parent_id'], ['attribute.id'], name='attribute_status_parent_id_fkey'),\n- sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='attribute_status_user_id_fkey'),\n- sa.PrimaryKeyConstraint('id', name='attribute_status_pkey')\n- )\n- # ### end Alembic commands ###\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -564,21 +564,25 @@ class AttributeContainer(BaseModel):\nuser_id = Column(Integer, ForeignKey('user.id'))\nsketch_id = Column(Integer, ForeignKey('sketch.id'))\nname = Column(UnicodeText())\n+ ontology = Column(UnicodeText())\nattributes = relationship(\n'Attribute', backref='attributecontainer', lazy='select')\n- def __init__(self, user, sketch, name):\n+ def __init__(self, user, sketch, name, ontology):\n\"\"\"Initialize the AttributeContainer object.\nArgs:\nuser (User): The user who created the aggregation\nsketch (Sketch): The sketch that the aggregation is bound to\nname (str): the name of the attribute.\n+ ontology (str): The ontology of the value, The values that can\n+ be used are defined in timesketch/lib/ontology.py (ONTOLOGY).\n\"\"\"\nsuper(AttributeContainer, self).__init__()\nself.user = user\nself.sketch = sketch\nself.name = name\n+ self.ontology = ontology\nclass Attribute(BaseModel):\n@@ -587,10 +591,9 @@ class Attribute(BaseModel):\nattributecontainer_id = Column(\nInteger, ForeignKey('attributecontainer.id'))\nvalue = Column(UnicodeText())\n- ontology = Column(UnicodeText())\ndef __init__(\n- self, user, attributecontainer, value, ontology):\n+ self, user, attributecontainer, value):\n\"\"\"Initialize the Attribute object.\nArgs:\n@@ -600,11 +603,8 @@ class Attribute(BaseModel):\nvalue (str): a string that contains the value for the attribute.\nThe ontology couold influence how this will be cast when\ninterpreted.\n- ontology (str): The ontology of the value, The values that can\n- be used are defined in timesketch/lib/ontology.py (ONTOLOGY).\n\"\"\"\nsuper(Attribute, self).__init__()\nself.user = user\nself.attributecontainer = attributecontainer\nself.value = value\n- self.ontology = ontology\n"
}
] | Python | Apache License 2.0 | google/timesketch | Making changes to the schema |
263,133 | 23.10.2020 13:25:32 | 0 | 69c68d7208b152db18187214b541403f11fb4b80 | Minor changes to docker files. | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/docker-entrypoint.sh",
"new_path": "docker/dev/docker-entrypoint.sh",
"diff": "@@ -13,6 +13,9 @@ if [ \"$1\" = 'timesketch' ]; then\nmkdir /etc/timesketch\ncp /usr/local/src/timesketch/data/timesketch.conf /etc/timesketch/\ncp /usr/local/src/timesketch/data/features.yaml /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/tags.yaml /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/e2e/Dockerfile",
"new_path": "docker/e2e/Dockerfile",
"diff": "@@ -36,6 +36,8 @@ RUN pip3 install timesketch-import-client\n# Copy Timesketch config files into /etc/timesketch\nRUN mkdir /etc/timesketch\nRUN cp /tmp/timesketch/data/timesketch.conf /etc/timesketch/\n+RUN cp /tmp/timesketch/data/ontology.yaml /etc/timesketch/\n+RUN cp /tmp/timesketch/data/tags.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor changes to docker files. |
263,133 | 23.10.2020 13:32:14 | 0 | d5de8beca55b20074d0327b16071362ef469b18d | Minor docker change | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/docker-entrypoint.sh",
"new_path": "docker/dev/docker-entrypoint.sh",
"diff": "@@ -16,6 +16,7 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/tags.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/\n+ cp -r /usr/local/src/timesketch/data/sigma /etc/timesketch/sigma/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor docker change |
263,133 | 24.10.2020 09:16:51 | 0 | 0576c0cebbd40c200b5b365693589891cf008f7f | Addign revision file | [
{
"change_type": "MODIFY",
"old_path": "docs/Admin-Guide.md",
"new_path": "docs/Admin-Guide.md",
"diff": "@@ -260,13 +260,13 @@ tsctl similarity_score\nAfter changin the schema for the database a revision file needs to be generated.\nTo generate the file use the command:\n-\n```shell\n-tsctl db revision --autogenerate -m \"attributes\"\n+tsctl db stamp head\n+tsctl db upgrade\n```\n-And the to upgrade the database\n+This makes sure that the database is current. Then create a revision file:\n```shell\n-tsctl db upgrade\n+tsctl db migrate -m \"<message>\"\n```\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/migrations/versions/fc7bc5c66c63_.py",
"diff": "+\"\"\"Attributes\n+\n+Revision ID: fc7bc5c66c63\n+Revises: c380f6dff0bd\n+Create Date: 2020-10-23 15:44:16.011715\n+\n+\"\"\"\n+\n+# revision identifiers, used by Alembic.\n+revision = 'fc7bc5c66c63'\n+down_revision = 'c380f6dff0bd'\n+\n+from alembic import op\n+import sqlalchemy as sa\n+\n+\n+def upgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.create_table('attributecontainer',\n+ sa.Column('id', sa.Integer(), nullable=False),\n+ sa.Column('created_at', sa.DateTime(), nullable=True),\n+ sa.Column('updated_at', sa.DateTime(), nullable=True),\n+ sa.Column('user_id', sa.Integer(), nullable=True),\n+ sa.Column('sketch_id', sa.Integer(), nullable=True),\n+ sa.Column('name', sa.UnicodeText(), nullable=True),\n+ sa.Column('ontology', sa.UnicodeText(), nullable=True),\n+ sa.ForeignKeyConstraint(['sketch_id'], ['sketch.id'], ),\n+ sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n+ sa.PrimaryKeyConstraint('id')\n+ )\n+ op.create_table('attribute',\n+ sa.Column('id', sa.Integer(), nullable=False),\n+ sa.Column('created_at', sa.DateTime(), nullable=True),\n+ sa.Column('updated_at', sa.DateTime(), nullable=True),\n+ sa.Column('user_id', sa.Integer(), nullable=True),\n+ sa.Column('attributecontainer_id', sa.Integer(), nullable=True),\n+ sa.Column('value', sa.UnicodeText(), nullable=True),\n+ sa.ForeignKeyConstraint(['attributecontainer_id'], ['attributecontainer.id'], ),\n+ sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n+ sa.PrimaryKeyConstraint('id')\n+ )\n+ # ### end Alembic commands ###\n+\n+\n+def downgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.drop_table('attribute')\n+ op.drop_table('attributecontainer')\n+ # ### end Alembic commands ###\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/__init__.py",
"new_path": "timesketch/models/__init__.py",
"diff": "@@ -52,7 +52,7 @@ def init_db():\n\"\"\"Initialize the database based on the implemented models. This will setup\nthe database on the first run.\n\"\"\"\n- BaseModel.metadata.create_all(bind=engine)\n+ #BaseModel.metadata.create_all(bind=engine)\nBaseModel.query = db_session.query_property()\nreturn BaseModel\n"
}
] | Python | Apache License 2.0 | google/timesketch | Addign revision file |
263,133 | 24.10.2020 11:38:01 | 0 | c9d8c6c011d8d723e1f177bbe2b7d1535189a287 | Adding data frame attribute into the API client. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sketch.py",
"new_path": "api_client/python/timesketch_api_client/sketch.py",
"diff": "@@ -134,6 +134,19 @@ class Sketch(resource.BaseResource):\nmeta = data.get('meta', {})\nreturn meta.get('attributes', [])\n+\n+ @property\n+ def attributes_table(self):\n+ \"\"\"Property that returns the sketch attributes as a data frame.\"\"\"\n+ data = self.lazyload_data()\n+ meta = data.get('meta', {})\n+ attributes = meta.get('attributes', [])\n+\n+ data_frame = pandas.DataFrame(attributes)\n+ data_frame.columns = ['name', 'attributes', 'ontology']\n+\n+ return data_frame\n+\n@property\ndef description(self):\n\"\"\"Property that returns sketch description.\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding data frame attribute into the API client. |
263,133 | 26.10.2020 14:37:06 | 0 | 26f2e73d38aea9ecc0c951a952a08ca358736bda | Changing names of tables to avoid confusion. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/attribute.py",
"new_path": "timesketch/api/v1/resources/attribute.py",
"diff": "@@ -28,8 +28,8 @@ from timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\nfrom timesketch.models import db_session\n-from timesketch.models.sketch import AttributeContainer\nfrom timesketch.models.sketch import Attribute\n+from timesketch.models.sketch import AttributeValue\nfrom timesketch.models.sketch import Sketch\n@@ -138,30 +138,30 @@ class AttributeResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_BAD_REQUEST,\n'All values needs to be stored as strings.')\n- for container in sketch.attributes:\n- if container.name == name:\n+ for attribute in sketch.attributes:\n+ if attribute.name == name:\nreturn abort(\nHTTP_STATUS_CODE_BAD_REQUEST,\n'Unable to add the attribute, it already exists.')\n- container = AttributeContainer(\n+ attribute = Attribute(\nuser=current_user,\nsketch=sketch,\nname=name,\nontology=ontology)\n- db_session.add(container)\n+ db_session.add(attribute)\ndb_session.commit()\nfor value in values:\n- attribute = Attribute(\n+ attribute_value = AttributeValue(\nuser=current_user,\n- attributecontainer=container,\n+ attribute=attribute,\nvalue=value)\n- container.attributes.append(attribute)\n- db_session.add(attribute)\n+ attribute.values.append(attribute_value)\n+ db_session.add(attribute_value)\ndb_session.commit()\n- db_session.add(container)\n+ db_session.add(attribute)\ndb_session.commit()\nreturn HTTP_STATUS_CODE_OK\n@@ -170,12 +170,16 @@ class AttributeResource(resources.ResourceMixin, Resource):\nreturn abort(\nHTTP_STATUS_CODE_BAD_REQUEST, 'Unable to proceed.')\n- for container in sketch.attributes:\n- if container.name != name:\n+ for attribute in sketch.attributes:\n+ if attribute.name != name:\ncontinue\n- for attribute in container.attributes:\n- container.attributes.remove(attribute)\n- sketch.attributes.remove(container)\n+ for value in attribute.values:\n+ attribute.values.remove(value)\n+ sketch.attributes.remove(attribute)\ndb_session.commit()\nreturn HTTP_STATUS_CODE_OK\n+\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to delete the attribute, couldn\\'t find it.')\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/utils.py",
"new_path": "timesketch/api/v1/utils.py",
"diff": "@@ -47,29 +47,29 @@ def get_sketch_attributes(sketch):\n\"\"\"Returns a list of attributes of a sketch.\"\"\"\nattributes = []\nontology_def = ontology.ONTOLOGY\n- for container in sketch.attributes:\n- if container.sketch_id != sketch.id:\n+ for attribute in sketch.attributes:\n+ if attribute.sketch_id != sketch.id:\ncontinue\n- name = container.name\n- container_attributes = []\n- ontology_string = container.ontology\n+ name = attribute.name\n+ attribute_values = []\n+ ontology_string = attribute.ontology\nontology_dict = ontology_def.get(ontology_string, {})\ncast_as_str = ontology_dict.get('cast_as', 'str')\n- for attribute in container.attributes:\n+ for attr_value in attribute.values:\ntry:\n- value = ontology.cast_variable(attribute.value, cast_as_str)\n+ value = ontology.cast_variable(attr_value.value, cast_as_str)\nexcept TypeError:\nvalue = 'Unable to cast'\n- container_attributes.append(value)\n+ attribute_values.append(value)\n- if len(container_attributes) == 1:\n+ if len(attribute_values) == 1:\nattributes.append(\n- (name, container_attributes[0], ontology_string))\n+ (name, attribute_values[0], ontology_string))\nelse:\nattributes.append(\n- (name, container_attributes, ontology_string))\n+ (name, attribute_values, ontology_string))\nreturn attributes\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/migrations/versions/fc7bc5c66c63_.py",
"new_path": "timesketch/migrations/versions/fc7bc5c66c63_.py",
"diff": "@@ -16,7 +16,7 @@ import sqlalchemy as sa\ndef upgrade():\n# ### commands auto generated by Alembic - please adjust! ###\n- op.create_table('attributecontainer',\n+ op.create_table('attribute',\nsa.Column('id', sa.Integer(), nullable=False),\nsa.Column('created_at', sa.DateTime(), nullable=True),\nsa.Column('updated_at', sa.DateTime(), nullable=True),\n@@ -28,14 +28,14 @@ def upgrade():\nsa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\nsa.PrimaryKeyConstraint('id')\n)\n- op.create_table('attribute',\n+ op.create_table('attributevalue',\nsa.Column('id', sa.Integer(), nullable=False),\nsa.Column('created_at', sa.DateTime(), nullable=True),\nsa.Column('updated_at', sa.DateTime(), nullable=True),\nsa.Column('user_id', sa.Integer(), nullable=True),\n- sa.Column('attributecontainer_id', sa.Integer(), nullable=True),\n+ sa.Column('attribute_id', sa.Integer(), nullable=True),\nsa.Column('value', sa.UnicodeText(), nullable=True),\n- sa.ForeignKeyConstraint(['attributecontainer_id'], ['attributecontainer.id'], ),\n+ sa.ForeignKeyConstraint(['attribute_id'], ['attribute.id'], ),\nsa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\nsa.PrimaryKeyConstraint('id')\n)\n@@ -45,5 +45,5 @@ def upgrade():\ndef downgrade():\n# ### commands auto generated by Alembic - please adjust! ###\nop.drop_table('attribute')\n- op.drop_table('attributecontainer')\n+ op.drop_table('attributevalue')\n# ### end Alembic commands ###\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -50,8 +50,7 @@ class Sketch(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\nevents = relationship('Event', backref='sketch', lazy='select')\nstories = relationship('Story', backref='sketch', lazy='select')\naggregations = relationship('Aggregation', backref='sketch', lazy='select')\n- attributes = relationship(\n- 'AttributeContainer', backref='sketch', lazy='select')\n+ attributes = relationship('Attribute', backref='sketch', lazy='select')\naggregationgroups = relationship(\n'AggregationGroup', backref='sketch', lazy='select')\nanalysis = relationship('Analysis', backref='sketch', lazy='select')\n@@ -559,17 +558,17 @@ class AnalysisSession(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nself.sketch = sketch\n-class AttributeContainer(BaseModel):\n- \"\"\"Implements the attribute container model.\"\"\"\n+class Attribute(BaseModel):\n+ \"\"\"Implements the attribute model.\"\"\"\nuser_id = Column(Integer, ForeignKey('user.id'))\nsketch_id = Column(Integer, ForeignKey('sketch.id'))\nname = Column(UnicodeText())\nontology = Column(UnicodeText())\n- attributes = relationship(\n- 'Attribute', backref='attributecontainer', lazy='select')\n+ values = relationship(\n+ 'AttributeValue', backref='attribute', lazy='select')\ndef __init__(self, user, sketch, name, ontology):\n- \"\"\"Initialize the AttributeContainer object.\n+ \"\"\"Initialize the Attribute object.\nArgs:\nuser (User): The user who created the attribute\n@@ -578,33 +577,31 @@ class AttributeContainer(BaseModel):\nontology (str): The ontology of the value, The values that can\nbe used are defined in timesketch/lib/ontology.py (ONTOLOGY).\n\"\"\"\n- super(AttributeContainer, self).__init__()\n+ super(Attribute, self).__init__()\nself.user = user\nself.sketch = sketch\nself.name = name\nself.ontology = ontology\n-class Attribute(BaseModel):\n- \"\"\"Implements the attribute model.\"\"\"\n+class AttributeValue(BaseModel):\n+ \"\"\"Implements the attribute value model.\"\"\"\nuser_id = Column(Integer, ForeignKey('user.id'))\n- attributecontainer_id = Column(\n- Integer, ForeignKey('attributecontainer.id'))\n+ attribute_id = Column(Integer, ForeignKey('attribute.id'))\nvalue = Column(UnicodeText())\ndef __init__(\n- self, user, attributecontainer, value):\n- \"\"\"Initialize the Attribute object.\n+ self, user, attribute, value):\n+ \"\"\"Initialize the Attribute value object.\nArgs:\n- user (User): The user who created the attribute\n- attributecontainer (AttributeContainer): The attribute container\n- this attribute is bound to.\n+ user (User): The user who created the attribute value.\n+ attribute (Attribute): The attribute this value is bound to.\nvalue (str): a string that contains the value for the attribute.\n- The ontology couold influence how this will be cast when\n+ The ontology could influence how this will be cast when\ninterpreted.\n\"\"\"\n- super(Attribute, self).__init__()\n+ super(AttributeValue, self).__init__()\nself.user = user\n- self.attributecontainer = attributecontainer\n+ self.attribute = attribute\nself.value = value\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changing names of tables to avoid confusion. |
263,133 | 26.10.2020 14:46:23 | 0 | 5bb1c349c74883e88203f703197da766aea0e831 | minor change to the ontology | [
{
"change_type": "MODIFY",
"old_path": "data/ontology.yaml",
"new_path": "data/ontology.yaml",
"diff": "@@ -19,7 +19,11 @@ url.safe:\nurl.bad:\ncast_as: str\n- description: \"URL related to a sketch.\"\n+ description: \"URL related to a sketch, can morph into a search.\"\n+\n+domain:\n+ cast_as: str\n+ description: \"Domain related to a sketch, can morp into a search.\"\nfloat:\ncast_as: float\n"
}
] | Python | Apache License 2.0 | google/timesketch | minor change to the ontology |
263,133 | 26.10.2020 15:56:37 | 0 | ec706ff75b2aa52601542a8e08840d2b27c0b5e2 | Adding the ability for analyzers to add sketch attributes | [
{
"change_type": "MODIFY",
"old_path": "test_tools/timesketch/lib/analyzers/interface.py",
"new_path": "test_tools/timesketch/lib/analyzers/interface.py",
"diff": "@@ -486,6 +486,24 @@ class Sketch(object):\nview = VIEW_OBJECT(1, name)\nreturn view\n+ def add_sketch_attribute(self, name, values, ontology='text'):\n+ \"\"\"Add an attribute to the sketch.\n+\n+ Args:\n+ name (str): The name of the attribute\n+ values (list): A list of strings, which contains the values of the\n+ attribute.\n+ ontology (str): Ontology of the attribute, matches with\n+ data/ontology.yaml.\n+ \"\"\"\n+ params = {\n+ 'name': name,\n+ 'values': values,\n+ 'ontology': ontology,\n+ }\n+ change = SKETCH_CHANGE('ADD', 'sketch_attribute', params)\n+ self.updates.append(change)\n+\ndef add_story(self, title):\n\"\"\"Add a story to the Sketch.\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/interface.py",
"new_path": "timesketch/lib/analyzers/interface.py",
"diff": "@@ -404,6 +404,41 @@ class Sketch(object):\ndb_session.commit()\nreturn view\n+ def add_sketch_attribute(self, name, values, ontology='text'):\n+ \"\"\"Add an attribute to the sketch.\n+\n+ Args:\n+ name (str): The name of the attribute\n+ values (list): A list of strings, which contains the values of the\n+ attribute.\n+ ontology (str): Ontology of the attribute, matches with\n+ data/ontology.yaml.\n+ \"\"\"\n+ # Check first whether the attribute already exists.\n+ attribute = Attribute.query.filter_by(name=name).first()\n+\n+ if not attribute:\n+ attribute = Attribute(\n+ user=None,\n+ sketch=self.sql_sketch,\n+ name=name,\n+ ontology=ontology)\n+ db_session.add(attribute)\n+ db_session.commit()\n+\n+ for value in values:\n+ attribute_value = AttributeValue(\n+ user=None,\n+ attribute=attribute,\n+ value=value)\n+\n+ attribute.values.append(attribute_value)\n+ db_session.add(attribute_value)\n+ db_session.commit()\n+\n+ db_session.add(attribute)\n+ db_session.commit()\n+\ndef add_story(self, title):\n\"\"\"Add a story to the Sketch.\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding the ability for analyzers to add sketch attributes |
263,133 | 28.10.2020 07:37:05 | 0 | bb98ec7b6abe1a9bf545ab5ce9ce7db9206e1f6a | Fixing 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": "@@ -297,7 +297,9 @@ class TimesketchApi(object):\nif auth_mode == 'http-basic':\nsession.auth = (username, password)\n- session.verify = verify # Depending if SSL cert is verifiable\n+ # SSL Cert verification is turned on by default.\n+ if not verify:\n+ session.verify = False\n# Get and set CSRF token and authenticate the session if appropriate.\nself._set_csrf_token(session)\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": "@@ -130,20 +130,24 @@ class Sketch(resource.BaseResource):\n@property\ndef attributes(self):\n\"\"\"Property that returns the sketch attributes.\"\"\"\n- data = self.lazyload_data()\n+ data = self.lazyload_data(refresh_cache=True)\nmeta = data.get('meta', {})\n- return meta.get('attributes', [])\n+ return_dict = {}\n+ for items in meta.get('attributes', []):\n+ name, values, ontology = items\n+ return_dict[name] = (values, ontology)\n+ return return_dict\n@property\ndef attributes_table(self):\n\"\"\"Property that returns the sketch attributes as a data frame.\"\"\"\n- data = self.lazyload_data()\n+ data = self.lazyload_data(refresh_cache=True)\nmeta = data.get('meta', {})\nattributes = meta.get('attributes', [])\ndata_frame = pandas.DataFrame(attributes)\n- data_frame.columns = ['name', 'attributes', 'ontology']\n+ data_frame.columns = ['attribute', 'values', 'ontology']\nreturn data_frame\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201023'\n+__version__ = '20201027'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixing API client. (#1431) |
263,133 | 28.10.2020 13:27:07 | 0 | cd13ba9f9f4e8b8974a12c6e097985b150b6c339 | Minor updates to the text | [
{
"change_type": "MODIFY",
"old_path": "notebooks/colab-timesketch-demo.ipynb",
"new_path": "notebooks/colab-timesketch-demo.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/colab-timesketch-demo.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/kiddinn/timesketch/blob/colab_sauce/notebooks/colab-timesketch-demo.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n\"source\": [\n\"And now we can start creating a timesketch client. The client is the object used to connect to the TS server and provides the API to interact with it.\\n\",\n\"\\n\",\n- \"The easiest way to connect to TS is to use the configuration object.\\n\",\n+ \"The TS API consists of several objects, each with it's own purpose, some of them are:\\n\",\n+ \"+ **client**: A TS client object is the main `gateway` to TS. That includes\\n\",\n+ \"authenticating to TS, keeping a session to interact with the REST API, and providing functions that allow you to create new sketches, get a sketch, and work with search indices.\\n\",\n+ \"+ **sketch**: A sketch object is what you will most likely interact with the most. That allows you to operate on a sketch, so that means to see the sketch ACL, attributes, labels and other metadata as well as to run analyzers, search queries, aggregations, stories, tag or label events, etc.\\n\",\n+ \"+ **timeline**: A timeline object allows you to view properties of a timeline, as well as adding/removing labels from it.\\n\",\n+ \"+ **story**: A story object allows you to interact with a story, add/delete/edit blocks, move them around, export the story, etc.\\n\",\n+ \"+ **view**: A view object is an object that holds information about saved searches, or views in a sketch. This can be passed to the sketch to query data, or to view the content of the view.\\n\",\n+ \"+ **aggregation**: An aggregation object is used to run aggregation queries on the dataset. It can provide you with a data frame, a chart, or the option to save/delete aggregations.\\n\",\n\"\\n\",\n- \"The first time you request the client it will ask you questions. For this demonstration we are going to be using the demo server, so we will use the following configs:\\n\",\n+ \"Let's start by getting a TS client object. There are multiple ways of getting that, yet the easiest way is to use the configuration object. That automates most of the actions that are needed, and prompts the user with questions if data is missing (reading information from a configuration file to fill in the blanks).\\n\",\n+ \"\\n\",\n+ \"The first time you request the client it will ask you questions (since for the first time there will be no configuration file). For this demonstration we are going to be using the demo server, so we will use the following configs:\\n\",\n\"\\n\",\n\"+ host_uri: **https://demo.timesketch.org**\\n\",\n\"+ auth_mode: **timesketch** (this is simple user/pass)\\n\",\n\"+ Username: **demo**\\n\",\n- \"+ Password: **demo**\\n\"\n+ \"+ Password: **demo**\\n\",\n+ \"\\n\",\n+ \"*keep in mind that after answering these questions for the first time, a configuration file ~/.timesketchrc and ~/.timesketch.token will be saved so you don't need to answer these questions again.*\\n\"\n]\n},\n{\n\"+ __ts_comment: Event with a comment\\n\",\n\"+ __ts_hidden: A hidden event\\n\",\n\"\\n\",\n- \"Let's for instance look at all starred events in the Greendale index:\"\n+ \"Let's for instance look at all starred events in the Greendale index. We will use the parameter `as_pandas=True`. That will mean that the events will be returned as a [pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html). This is a very flexible object that we will use throughout this colab. We will try to introduce some basic operations on a pandas object, yet for more details there are plenty of guides that can be found online. One way to think about pandas is to think about spreadsheets, or databases, where the data is stored in a table (data frame), which consists of columns and rows. And then there are operations that work on either the column or the row.\\n\",\n+ \"\\n\",\n+ \"But let's start by looking at one such data frame, by looking for all starred events.\\n\",\n+ \"\\n\",\n+ \"Once we get the data frame back, we call `data_frame.shape`, which returns a tuple with two items, number of rows and number of columns. That way we can assess the size of the dataframe.\"\n]\n},\n{\n\"id\": \"168Ny0fObbx1\"\n},\n\"source\": [\n- \"pd.set_option('display.max_colwidth', 100)\\n\",\n+ \"pd.set_option('display.max_colwidth', 100) # this is just meant to make the output wider\\n\",\n\"starred_events.iloc[9]\"\n],\n\"execution_count\": null,\n\"id\": \"jEki5_BmZpKu\"\n},\n\"source\": [\n- \"Did you notice the \\\"`as_pandas=True`\\\" parameter that got passed to the \\\"`explore`\\\" function? That means that the data that we'll get back is a pandas DataFrame that we can now start exploring. \\n\",\n+ \"One thing you may notice is that throughout this colab we will use the \\\"`as_pandas=True`\\\" parameter to the \\\"`explore`\\\" function. That means that the data that we'll get back is a pandas DataFrame that we can now start exploring. \\n\",\n\"\\n\",\n\"Let's start with seeing how many entries we got back.\"\n]\n\"id\": \"XWjrJnivaSo9\"\n},\n\"source\": [\n- \"This tells us that the view returned back 2.284 events with 12 columns. Let's explore the first few entries, just so that we can wrap our head around what we got back.\"\n+ \"This tells us that the view returned back 2.284 events with 12 columns. Let's explore the first few entries, just so that we can wrap our head around what we got back.\\n\",\n+ \"\\n\",\n+ \"This is a great way to just get a feeling of what the data looks like that will be returned back. To see the first five entries we can use the `.head(5)` function, and the same if we want the last entries, we can use `.tail(5)`.\"\n]\n},\n{\n\"\\n\",\n\"greendale_frame.tag.apply(add_tag)\\n\",\n\"\\n\",\n- \"print(tags)\\n\"\n+ \"print(tags)\"\n],\n\"execution_count\": null,\n\"outputs\": []\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor updates to the text |
263,133 | 30.10.2020 07:58:20 | 0 | 6bdee3ece9c7acdfb4388dd081a0ae81751b7347 | Minor changes to the get_client in API client config module. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/config.py",
"new_path": "api_client/python/timesketch_api_client/config.py",
"diff": "@@ -17,6 +17,7 @@ from __future__ import unicode_literals\nimport configparser\nimport logging\nimport os\n+import requests\nfrom google.auth.transport import requests as auth_requests\n@@ -39,14 +40,36 @@ def get_client(config_dict=None, config_path='', token_password=''):\nnot supplied a default path will be used.\ntoken_password (str): an optional password to decrypt\nthe credential token file.\n+\n+ Returns:\n+ A timesketch client (TimesketchApi) or None if not possible.\n\"\"\"\nassistant = ConfigAssistant()\n+ try:\nassistant.load_config_file(config_path)\nif config_dict:\nassistant.load_config_dict(config_dict)\n+ except IOError as e:\n+ logger.error('Unable to load the config file, is it valid?')\n+ logger.error('Error: %s', e)\n+ try:\nconfigure_missing_parameters(assistant, token_password)\nreturn assistant.get_client(token_password=token_password)\n+ except IOError as e:\n+ logger.error('Unable to get a client, with error: %s', e)\n+ logger.error(\n+ 'If the issue is in the credentials then one solution '\n+ 'is to remove the ~/.timesketch.token file and the '\n+ 'credential section in ~/.timesketchrc or to remove '\n+ 'both files. Or you could have supplied a wrong '\n+ 'password to undecrypt the token file.')\n+ except RuntimeError, requests.ConnectionError as e:\n+ logger.error(\n+ 'Unable to connect to the Timesketch server, are you '\n+ 'connected to the network? Is the timesketch server '\n+ 'running and accessible from your host? The error '\n+ 'message is %s', e)\ndef configure_missing_parameters(config_assistant, token_password=''):\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201029'\n+__version__ = '20201030'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor changes to the get_client in API client config module. |
263,096 | 30.10.2020 09:04:39 | -3,600 | b92b96192a2958075e09647bb69086e81687c9af | Fix a small typo in 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": "@@ -741,7 +741,7 @@ class Sketch(resource.BaseResource):\n\"\"\"Return a stored aggregation group.\nArgs:\n- goup_id: id of the stored aggregation group.\n+ group_id: id of the stored aggregation group.\nReturns:\nAn aggregation group object (instance of AggregationGroup)\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fix a small typo in docstring |
263,133 | 30.10.2020 16:30:38 | 0 | bf304c01af41ba3e55cfa47e5701764529d45ba3 | Fixing badge in colab notebooks. | [
{
"change_type": "MODIFY",
"old_path": "notebooks/Stolen_Szechuan_Sauce_Analysis.ipynb",
"new_path": "notebooks/Stolen_Szechuan_Sauce_Analysis.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/kiddinn/timesketch/blob/colab_sauce/notebooks/Stolen_Szechuan_Sauce_Analysis.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/Stolen_Szechuan_Sauce_Analysis.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "notebooks/Stolen_Szechuan_Sauce_Data_Upload.ipynb",
"new_path": "notebooks/Stolen_Szechuan_Sauce_Data_Upload.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/kiddinn/timesketch/blob/colab_sauce/notebooks/Stolen_Szechuan_Sauce_Data_Upload.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/Stolen_Szechuan_Sauce_Data_Upload.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixing badge in colab notebooks. |
263,133 | 30.10.2020 16:31:28 | 0 | c3b12e587b14d4b48394194a6e88f8732fc5240f | Forgot one badge | [
{
"change_type": "MODIFY",
"old_path": "notebooks/colab-timesketch-demo.ipynb",
"new_path": "notebooks/colab-timesketch-demo.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/kiddinn/timesketch/blob/colab_sauce/notebooks/colab-timesketch-demo.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/colab-timesketch-demo.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/timesketch | Forgot one badge |
263,096 | 02.11.2020 17:24:25 | -3,600 | e10385c0a941f8b650917689a042f73a16839c38 | replace jaegeral with google and branch with master
Fix the link to the colab direct link | [
{
"change_type": "MODIFY",
"old_path": "Github_Timesketch_add_a_single_event_to_a_sketch.ipynb",
"new_path": "Github_Timesketch_add_a_single_event_to_a_sketch.ipynb",
"diff": "\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/jaegeral/timesketch/blob/single_event_notebook/Github_Timesketch_add_a_single_event_to_a_sketch.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/Github_Timesketch_add_a_single_event_to_a_sketch.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/timesketch | replace jaegeral with google and branch with master
Fix the link to the colab direct link |
263,096 | 02.11.2020 17:29:17 | -3,600 | c966ecfa25f89f45fbe1e2a908cb5c5f4cb6a269 | Update and rename Timesketch_add_a_single_event_to_a_sketch.ipynb to add_a_single_event_to_a_sketch.ipynb | [
{
"change_type": "RENAME",
"old_path": "notebooks/Timesketch_add_a_single_event_to_a_sketch.ipynb",
"new_path": "notebooks/add_a_single_event_to_a_sketch.ipynb",
"diff": "\"nbformat_minor\": 0,\n\"metadata\": {\n\"colab\": {\n- \"name\": \"Github_Timesketch_add_a_single_event_to_a_sketch.ipynb\",\n+ \"name\": \"Timesketch_add_a_single_event_to_a_sketch.ipynb\",\n\"provenance\": [],\n\"include_colab_link\": true\n},\n\"colab_type\": \"text\"\n},\n\"source\": [\n- \"<a href=\\\"https://colab.research.google.com/github/jaegeral/timesketch/blob/single_event_notebook/notebooks/Timesketch_add_a_single_event_to_a_sketch.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n+ \"<a href=\\\"https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/Timesketch_add_a_single_event_to_a_sketch.ipynb\\\" target=\\\"_parent\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"/></a>\"\n]\n},\n{\n"
}
] | Python | Apache License 2.0 | google/timesketch | Update and rename Timesketch_add_a_single_event_to_a_sketch.ipynb to add_a_single_event_to_a_sketch.ipynb |
263,096 | 03.11.2020 14:34:10 | -3,600 | c283ba075e6ce9b78e2caf8ca455b4296ea8f922 | Remove sudo from the docker dev guide
Be consistent in the documentation and remove sudo for this occurance as well | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/README.md",
"new_path": "docker/dev/README.md",
"diff": "## Docker for development\nYou can run Timesketch on Docker in development mode.\n-Make sure to follow the docker [post-install](https://docs.docker.com/engine/install/linux-postinstall/) to run without superuser. If not then make sure to execute all `docker` commands here as superuser.\n+Make sure to follow the docker [post-install](https://docs.docker.com/engine/install/linux-postinstall/) to run without superuser. If not then make sure to execute all `docker` commands here as *superuser*.\nNOTE: It is not recommended to try to run on a system with less than 8 GB of RAM.\n@@ -21,7 +21,7 @@ Timesketch development server is ready!\n### Find out container ID for the timesketch container\n```\n-CONTAINER_ID=\"$(sudo docker container list -f name=dev_timesketch -q)\"\n+CONTAINER_ID=\"$(docker container list -f name=dev_timesketch -q)\"\n```\nIn the output look for CONTAINER ID for the timesketch container\n"
}
] | Python | Apache License 2.0 | google/timesketch | Remove sudo from the docker dev guide
Be consistent in the documentation and remove sudo for this occurance as well |
263,145 | 09.11.2020 19:58:16 | 0 | 6b7f3ae07488190016c86f4c5b01a123cc50e853 | Update deploy_timesketch.sh
Updates URL to master branch.
I previously had errors generating the `config.env` (all I got was a 404) using `deploy_timesketch.sh` script. It would just write a `404: Not Found` in the config file. Once I've updated the URL I could use the script for deploying timesketch using Docker again. | [
{
"change_type": "MODIFY",
"old_path": "contrib/deploy_timesketch.sh",
"new_path": "contrib/deploy_timesketch.sh",
"diff": "@@ -66,7 +66,7 @@ ELASTIC_ADDRESS=\"elasticsearch\"\nELASTIC_PORT=9200\nREDIS_ADDRESS=\"redis\"\nREDIS_PORT=6379\n-GITHUB_BASE_URL=\"https://raw.githubusercontent.com/google/timesketch/docker-refactor\"\n+GITHUB_BASE_URL=\"https://raw.githubusercontent.com/google/timesketch/master\"\nELASTIC_MEM_USE_GB=$(cat /proc/meminfo | grep MemTotal | awk '{printf \"%.0f\", ($2 / 1000000 / 2)}')\necho \"OK\"\necho \"* Setting Elasticsearch memory allocation to ${ELASTIC_MEM_USE_GB}GB\"\n"
}
] | Python | Apache License 2.0 | google/timesketch | Update deploy_timesketch.sh (#1460)
Updates URL to master branch.
I previously had errors generating the `config.env` (all I got was a 404) using `deploy_timesketch.sh` script. It would just write a `404: Not Found` in the config file. Once I've updated the URL I could use the script for deploying timesketch using Docker again. |
263,093 | 10.11.2020 16:18:18 | -3,600 | 9501a500591aa9d699908611429eb9ab13e34608 | Don't use scrollig for nested queries | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/graphs/chrome_downloads.py",
"new_path": "timesketch/lib/graphs/chrome_downloads.py",
"diff": "@@ -80,7 +80,8 @@ class ChromeDownloadsGraph(BaseGraphPlugin):\nprefetch_events = self.event_stream(\nquery_string=prefetch_query,\nreturn_fields=prefetch_return_fields,\n- indices=['_all']\n+ indices=['_all'],\n+ scroll=False\n)\nfor prefetch_event in prefetch_events:\ncomputer_name = prefetch_event['_source'].get('hostname')\n"
}
] | Python | Apache License 2.0 | google/timesketch | Don't use scrollig for nested queries (#1461) |
263,171 | 12.11.2020 20:50:15 | -3,600 | b65300a5207532a12d120dfa0afb61bd1ed376bd | Added features to analyzer feature extract
* Improve options for extract multi ip
Add options:
store_type_list
overwrite_store_as
overwrite_and_merge_store_as
keep_multimatch | [
{
"change_type": "MODIFY",
"old_path": "data/features.yaml",
"new_path": "data/features.yaml",
"diff": "# tags: []\n# create_view: False\n# aggregate: False\n+# overwrite_store_as: True\n+# overwrite_and_merge_store_as: False\n+# store_type_list: False\n+# keep_multimatch: False\n#\n# Each definition needs to define either a query_string or a query_dsl.\n#\n# create an aggregation of the results and store it (ATM this does\n# nothing, but once aggregations are supported it will).\n#\n+# The overwrite_store_as is an optional boolean that determines if\n+# we want to overwrite the field store_as if it already exists.\n+#\n+# The overwrite_and_merge_store_as is an optional boolean that determines\n+# if we want to overwrite the field store_as and merge the existing values.\n+#\n+# The store_type_list is an optional boolean that determines if we want to\n+# store the extracted data in List type (default is text).\n+#\n+# The keep_multimatch is an optional boolean that determines if we want to\n+# store all matching results (default store first result).\n+#\n# The feature extraction works in the way that the query is run, and\n# the regular expression is run against the attribute to extract a value.\n# The first value extracted is then stored inside the \"store_as\" attribute.\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/feature_extraction.py",
"new_path": "timesketch/lib/analyzers/feature_extraction.py",
"diff": "@@ -102,6 +102,38 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\n'default_value': False,\n'optional': True,\n},\n+ {\n+ 'name': 'store_type_list',\n+ 'type': 'ts-dynamic-form-boolean',\n+ 'label': 'Store extracted result in type List',\n+ 'placeholder': 'Store results as field type list',\n+ 'default_value': False,\n+ 'optional': True,\n+ },\n+ {\n+ 'name': 'overwrite_store_as',\n+ 'type': 'ts-dynamic-form-boolean',\n+ 'label': 'Overwrite the field to store if already exist',\n+ 'placeholder': 'Overwrite the field to store',\n+ 'default_value': True,\n+ 'optional': True,\n+ },\n+ {\n+ 'name': 'overwrite_and_merge_store_as',\n+ 'type': 'ts-dynamic-form-boolean',\n+ 'label': 'Overwrite the field to store and merge value if exist',\n+ 'placeholder': 'Overwrite the field to store and merge value',\n+ 'default_value': False,\n+ 'optional': True,\n+ },\n+ {\n+ 'name': 'keep_multimatch',\n+ 'type': 'ts-dynamic-form-boolean',\n+ 'label': 'Keep multi match datas',\n+ 'placeholder': 'Keep multi match',\n+ 'default_value': False,\n+ 'optional': True,\n+ },\n{\n'name': 'aggregate',\n'type': 'ts-dynamic-form-boolean',\n@@ -146,6 +178,52 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nreturn ', '.join(return_strings)\n+ @staticmethod\n+ def _get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ keep_multi,\n+ merge_values,\n+ type_list):\n+ \"\"\"Returns the attribute value as it should be stored.\n+\n+ Args:\n+ current_val: current value of store_as.\n+ extracted_value: values matched from regexp (type list).\n+ keep_multi: choise if you keep all match from regex (type boolean).\n+ merge_values: choise if you merge value from extracted\n+ and current (type boolean).\n+ type_list: choise if you store values in list type(type boolean).\n+\n+ Returns:\n+ Value to store\n+ \"\"\"\n+ if not current_val:\n+ merge_values = False\n+ if len(extracted_value) == 1:\n+ keep_multi = False\n+ if type_list:\n+ if merge_values and keep_multi:\n+ return sorted(list(set(current_val) | set(extracted_value)))\n+ if merge_values:\n+ if extracted_value[0] not in current_val:\n+ current_val.append(extracted_value[0])\n+ return sorted(current_val)\n+ if keep_multi:\n+ return sorted(extracted_value)\n+ return [extracted_value[0]]\n+ if merge_values and keep_multi:\n+ list_cur = current_val.split(',')\n+ merge_list = sorted(list(set(list_cur) | set(extracted_value)))\n+ return ','.join(merge_list)\n+ if merge_values:\n+ if extracted_value[0] in current_val:\n+ return current_val\n+ return f'{current_val},{extracted_value[0]}'\n+ if keep_multi:\n+ return ','.join(extracted_value)\n+ return extracted_value[0]\n+\ndef extract_feature(self, name, config):\n\"\"\"Extract features from events.\n@@ -161,6 +239,11 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nquery = config.get('query_string')\nquery_dsl = config.get('query_dsl')\nattribute = config.get('attribute')\n+ store_type_list = config.get('store_type_list', False)\n+ keep_multimatch = config.get('keep_multimatch', False)\n+ overwrite_store_as = config.get('overwrite_store_as', True)\n+ overwrite_and_merge_store_as = config.get(\n+ 'overwrite_and_merge_store_as', False)\nif not attribute:\nlogger.warning('No attribute defined.')\n@@ -203,7 +286,7 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nemoji_names = config.get('emojis', [])\nemojis_to_add = [emojis.get_emoji(x) for x in emoji_names]\n- return_fields = [attribute]\n+ return_fields = [attribute, store_as]\nevents = self.event_stream(\nquery_string=query, query_dsl=query_dsl,\n@@ -227,9 +310,26 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nresult = expression.findall(attribute_value)\nif not result:\ncontinue\n+ result = list(set(result))\nevent_counter += 1\n- event.add_attributes({store_as: result[0]})\n+ store_as_current_val = event.source.get(store_as)\n+ if store_as_current_val and not overwrite_store_as:\n+ continue\n+ if isinstance(store_as_current_val, six.text_type):\n+ store_type_list = False\n+ elif isinstance(store_as_current_val, (list, tuple)):\n+ store_type_list = True\n+ new_value = self._get_attribute_value(\n+ store_as_current_val,\n+ result,\n+ keep_multimatch,\n+ overwrite_and_merge_store_as,\n+ store_type_list\n+ )\n+ if not new_value:\n+ continue\n+ event.add_attributes({store_as: new_value})\nevent.add_emojis(emojis_to_add)\nevent.add_tags(tags)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/feature_extraction_test.py",
"new_path": "timesketch/lib/analyzers/feature_extraction_test.py",
"diff": "@@ -5,9 +5,13 @@ import os\nimport re\nimport yaml\n+import mock\n+\nfrom timesketch.lib import emojis\n+from timesketch.lib.analyzers import feature_extraction\nfrom timesketch.lib.testlib import BaseTest\n+from timesketch.lib.testlib import MockDataStore\nclass TestFeatureExtractionPlugin(BaseTest):\n\"\"\"Tests the functionality of the analyzer.\"\"\"\n@@ -65,3 +69,124 @@ class TestFeatureExtractionPlugin(BaseTest):\nself.assertIsInstance(key, str)\nself.assertIsInstance(value, dict)\nself._config_validation(value)\n+\n+ # Mock the Elasticsearch datastore.\n+ @mock.patch(\n+ 'timesketch.lib.analyzers.interface.ElasticsearchDataStore',\n+ MockDataStore)\n+ def test_get_attribute_value(self):\n+ \"\"\"Test function _get_attribute_value().\"\"\"\n+ analyzer = feature_extraction.FeatureExtractionSketchPlugin(\n+ 'test_index', 1)\n+ current_val = ['hello']\n+ extracted_value = ['hello']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val=current_val,\n+ extracted_value=extracted_value,\n+ keep_multi=True,\n+ merge_values=True,\n+ type_list=True)\n+ new_val.sort()\n+\n+ self.assertEqual(new_val, ['hello'])\n+\n+ current_val = ['hello']\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ True,\n+ True,\n+ True)\n+ new_val.sort()\n+\n+ self.assertEqual(new_val, ['hello', 'hello2', 'hello3'])\n+\n+ current_val = ['hello']\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ False,\n+ True,\n+ True)\n+ new_val.sort()\n+\n+ self.assertEqual(new_val, ['hello', 'hello2'])\n+\n+ current_val = ['hello']\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ False,\n+ False,\n+ True)\n+ new_val.sort()\n+\n+ self.assertEqual(new_val, ['hello2'])\n+\n+ current_val = ['hello']\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ True,\n+ False,\n+ True)\n+ new_val.sort()\n+\n+ self.assertEqual(new_val, ['hello2', 'hello3'])\n+\n+ current_val = 'hello'\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ True,\n+ True,\n+ False)\n+\n+ self.assertEqual(new_val, 'hello,hello2,hello3')\n+\n+ current_val = 'hello'\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ False,\n+ True,\n+ False)\n+\n+ self.assertEqual(new_val, 'hello,hello2')\n+\n+ current_val = 'hello'\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ True,\n+ False,\n+ False)\n+\n+ self.assertEqual(new_val, 'hello2,hello3')\n+\n+ current_val = 'hello'\n+ extracted_value = ['hello2', 'hello3']\n+ # pylint: disable=protected-access\n+ new_val = analyzer._get_attribute_value(\n+ current_val,\n+ extracted_value,\n+ False,\n+ False,\n+ False)\n+\n+ self.assertEqual(new_val, 'hello2')\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added features to analyzer feature extract (#1452)
* Improve options for extract multi ip
Add options:
store_type_list
overwrite_store_as
overwrite_and_merge_store_as
keep_multimatch |
263,096 | 15.11.2020 10:44:18 | -3,600 | 1b34b88bb77e16fdb5e1a6400e28cca13ad1d3f8 | Fixed the sigma analyzer, removed hacky .keyword | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/sigma_tagger.py",
"new_path": "timesketch/lib/analyzers/sigma_tagger.py",
"diff": "@@ -117,11 +117,6 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nfor sigma_rule in parsed_sigma_rules:\ntry:\nsigma_rule_counter += 1\n- # TODO Investigate how to handle .keyword\n- # fields in Sigma.\n- # https://github.com/google/timesketch/issues/1199#issuecomment-639475885\n- sigma_rule = sigma_rule\\\n- .replace(\".keyword:\", \":\")\nlogger.info(\n'[sigma] Generated query {0:s}'\n.format(sigma_rule))\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed the sigma analyzer, removed hacky .keyword (#1468)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,093 | 17.11.2020 15:42:51 | -3,600 | 0b8d0e67022497244d0b825f08622cd5bb704963 | Fixed an issue in the winservices graph plugin | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/graphs/win_services.py",
"new_path": "timesketch/lib/graphs/win_services.py",
"diff": "@@ -36,13 +36,18 @@ class WinServiceGraph(BaseGraphPlugin):\nquery_string=query, return_fields=return_fields)\nfor event in events:\n- computer_name = event['_source'].get('computer_name')\n- username = event['_source'].get('username')\n- event_strings = event['_source'].get('strings')\n+ computer_name = event['_source'].get('computer_name', 'UNKNOWN')\n+ username = event['_source'].get('username', 'UNKNOWN')\n+ event_strings = event['_source'].get('strings', [])\n+\n+ # Skip event if we don't have enough data to build the graph.\n+ try:\nservice_name = event_strings[0]\nimage_path = event_strings[1]\nservice_type = event_strings[2]\nstart_type = event_strings[3]\n+ except IndexError:\n+ continue\ncomputer = self.graph.add_node(computer_name, {'type': 'computer'})\nuser = self.graph.add_node(username, {'type': 'user'})\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed an issue in the winservices graph plugin (#1475)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,093 | 17.11.2020 17:41:41 | -3,600 | a18812e585f2cf308728f37197103156336da34e | Add GH action badges | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "[](https://colab.research.google.com/github/google/timesketch/blob/master/notebooks/colab-timesketch-demo.ipynb)\n[](https://mybinder.org/v2/gh/google/timesketch/master?urlpath=%2Flab)\n[](https://twitter.com/intent/tweet?text=Digital%20Forensic%20Timeline%20Analysis&url=https://github.com/google/timesketch/&via=jberggren&hashtags=dfir)\n+\n+\n+\n+\n## Table of Contents\n1. [About Timesketch](#about-timesketch)\n"
}
] | Python | Apache License 2.0 | google/timesketch | Add GH action badges |
263,093 | 18.11.2020 17:00:57 | -3,600 | bbd6e30df1f7d9b98c31bac7e641cbe139cea5bc | Changed the graph interface to use ID from attributes | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/graphs/interface.py",
"new_path": "timesketch/lib/graphs/interface.py",
"diff": "@@ -58,7 +58,11 @@ class Graph:\nReturns:\nInstance of Node object.\n\"\"\"\n+ if not attributes:\n+ attributes = {}\n+\nnode = Node(label, attributes)\n+ node.set_attribute('id', node.id)\nif node.id not in self._nodes:\nself._nodes[node.id] = node\nreturn node\n@@ -73,8 +77,10 @@ class Graph:\nevent: (dict): Elasticsearch event.\nattributes: (dict) Attributes to add to node.\n\"\"\"\n- edge_id_string = ''.join([source.id, target.id, label]).lower()\n- edge_id = hashlib.md5(edge_id_string.encode('utf-8')).hexdigest()\n+ if not attributes:\n+ attributes = {}\n+\n+ attributes['id'] = ''.join([source.id, target.id, label]).lower()\nedge = Edge(source, target, label, attributes)\n@@ -88,7 +94,7 @@ class Graph:\nevents[index] = doc_ids\nedge.set_attribute('events', events)\n- self._edges[edge_id] = edge\n+ self._edges[edge.id] = edge\ndef commit(self):\n\"\"\"Commit all nodes and edges to the networkx graph object.\"\"\"\n@@ -129,20 +135,16 @@ class BaseGraphElement:\n\"\"\"\nself.label = label\nself.attributes = attributes or {}\n- self.id = self.id_from_label(label)\n+ self.id = self._generate_id()\n- @staticmethod\n- def id_from_label(label):\n+ def _generate_id(self):\n\"\"\"Generate ID for node/edge.\n- Args:\n- label (str): Node or edge label.\n-\nReturns:\nMD5 hash (str): MD5 hash of the provided label.\n\"\"\"\n- label = label.lower()\n- return hashlib.md5(label.encode('utf-8')).hexdigest()\n+ id_string = self.attributes.get('id', self.label)\n+ return hashlib.md5(id_string.encode('utf-8')).hexdigest()\ndef set_attribute(self, key, value):\n\"\"\"Add or replace an attribute to the element.\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changed the graph interface to use ID from attributes (#1480) |
263,178 | 20.11.2020 11:48:12 | -3,600 | 7f1d29507d97940829af8a770129bb1b008c9891 | Updated dpkg configuration files | [
{
"change_type": "MODIFY",
"old_path": "config/dpkg/changelog",
"new_path": "config/dpkg/changelog",
"diff": "-timesketch (20200805-1) unstable; urgency=low\n+timesketch (20201120-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Wed, 05 Aug 2020 13:39:41 +0000\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Fri, 20 Nov 2020 11:37:39 +0100\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 (>= 1.3.2), python3-altair (>= 4.1.0), 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.4.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.5.0), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 7.5.1), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.1.1), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.1), python3-flask-migrate (>= 2.5.2), python3-flask-restful (>= 0.3.7), python3-flask-script (>= 2.0.6), python3-flask-sqlalchemy (>= 2.4.1), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.7.0), 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.7.1), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-neo4jrestclient (>= 2.1.1), python3-numpy (>= 1.17.5), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.25.3), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 3.3.11), python3-requests (>= 2.23.0), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.3.12), 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.2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${python3:Depends}, ${misc:Depends}\n+Depends: timesketch-data (>= ${binary:Version}), python3-alembic (>= 1.3.2), python3-altair (>= 4.1.0), 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.4.0), python3-certifi (>= 2017.7.27.1), python3-cffi (>= 1.10.0), python3-chardet (>= 3.0.4), python3-ciso8601 (>= 2.1.1), python3-click (>= 6.7), python3-cryptography (>= 2.4.1), python3-datasketch (>= 1.5.0), python3-dateutil (>= 2.6.1), python3-editor (>= 1.0.3), python3-elasticsearch (>= 7.5.1), python3-entrypoints (>= 0.2.3), python3-flask (>= 1.1.1), python3-flask-bcrypt (>= 0.7.1), python3-flask-login (>= 0.4.1), python3-flask-migrate (>= 2.5.2), python3-flask-restful (>= 0.3.7), python3-flask-script (>= 2.0.6), python3-flask-sqlalchemy (>= 2.4.1), python3-flaskext.wtf (>= 0.14.2), python3-google-auth (>= 1.7.0), 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.7.1), python3-kombu (>= 4.1.0), python3-mako (>= 1.0.7), python3-markdown (>= 3.2.2), python3-markupsafe (>= 1.0), python3-networkx (>= 2.4), python3-numpy (>= 1.17.5), python3-oauthlib (>= 3.1.0), python3-pandas (>= 0.25.3), python3-parameterized (>= 0.6.1), python3-pycparser (>= 2.18), python3-pyrsistent (>= 0.14.11), python3-redis (>= 3.3.11), python3-requests (>= 2.23.0), python3-requests-oauthlib (>= 1.3.0), python3-sigmatools (>= 0.15.0), python3-six (>= 1.10.0), python3-sqlalchemy (>= 1.3.12), 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.2.1), python3-xlrd (>= 1.2.0), python3-xmltodict (>= 0.12.0), python3-yaml (>= 3.10), python3-zipp (>= 0.5), ${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 | Updated dpkg configuration files (#1487) |
263,133 | 20.11.2020 14:30:09 | 0 | 4f02103f48d5ee3a838b0fa9f6fd1dee6b4a7d9a | Added a linter GH workflow and adding a bit more resiliency into the error logging in the ES datastore | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".github/workflows/linter.yml",
"diff": "+name: pylint\n+\n+on:\n+ pull_request:\n+ types: [opened, synchronize, reopened]\n+\n+jobs:\n+ linter:\n+ runs-on: ubuntu-20.04\n+ strategy:\n+ matrix:\n+ os: [ubuntu-20.04]\n+ python-version: [3.7, 3.8]\n+\n+ steps:\n+ - uses: actions/checkout@v2\n+ - name: Set up Python ${{ matrix.python-version }}\n+ uses: actions/setup-python@v2\n+ with:\n+ python-version: ${{ matrix.python-version }}\n+ - name: Install dependencies\n+ run: |\n+ pip install pylint\n+ pip install -r test_requirements.txt\n+ pip install -r requirements.txt\n+ pip install -e .\n+ - name: Run linter\n+ run: |\n+ git config pull.rebase false && git fetch -p origin master\n+ for FILE in `git --no-pager diff origin/master --name-only | grep \\.py$`; do echo \"Running linter against ${FILE}\"; pylint --rcfile=.pylintrc ${FILE}; done\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -75,7 +75,7 @@ class ElasticsearchDataStore(object):\ndef __init__(self, host='127.0.0.1', port=9200):\n\"\"\"Create a Elasticsearch client.\"\"\"\n- super(ElasticsearchDataStore, self).__init__()\n+ super().__init__()\nself._error_container = {}\nself.client = Elasticsearch([{'host': host, 'port': port}])\nself.import_counter = Counter()\n@@ -418,7 +418,7 @@ class ElasticsearchDataStore(object):\nes_logger.error(\n'Unable to run search query: {0:s}'.format(cause),\nexc_info=True)\n- raise ValueError(cause)\n+ raise ValueError(cause) from e\nreturn _search_result\n@@ -688,8 +688,9 @@ class ElasticsearchDataStore(object):\ntry:\nself.client.indices.create(\nindex=index_name, body={'mappings': _document_mapping})\n- except ConnectionError:\n- raise RuntimeError('Unable to connect to Timesketch backend.')\n+ except ConnectionError as e:\n+ raise RuntimeError(\n+ 'Unable to connect to Timesketch backend.') from e\nexcept RequestError:\nindex_exists = self.client.indices.exists(index_name)\nes_logger.warning(\n@@ -718,7 +719,7 @@ class ElasticsearchDataStore(object):\nexcept ConnectionError as e:\nraise RuntimeError(\n'Unable to connect to Timesketch backend: {}'.format(e)\n- )\n+ ) from e\ndef import_event(self, index_name, event_type, event=None, event_id=None,\nflush_interval=DEFAULT_FLUSH_INTERVAL):\n@@ -832,7 +833,7 @@ class ElasticsearchDataStore(object):\nerror = index.get('error', {})\nstatus_code = index.get('status', 0)\n- doc_id = index.get('_id', '')\n+ doc_id = index.get('_id', '(unable to get doc id)')\ncaused_by = error.get('caused_by', {})\ncaused_reason = caused_by.get(\n@@ -852,10 +853,17 @@ class ElasticsearchDataStore(object):\ncaused_reason,\n)\nerror_list.append(error_msg)\n+ try:\nes_logger.error(\n'Unable to upload document: {0:s} to index {1:s} - '\n'[{2:d}] {3:s}'.format(\ndoc_id, index_name, status_code, error_msg))\n+ # We need to catch all exceptions here, since this is a crucial\n+ # call that we do not want to break operation.\n+ except Exception: # pylint: disable=broad-except\n+ es_logger.error(\n+ 'Unable to upload document, and unable to log the '\n+ 'error itself.', exc_info=True)\nreturn_dict['error_container'] = self._error_container\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added a linter GH workflow and adding a bit more resiliency into the error logging in the ES datastore (#1488) |
263,096 | 02.12.2020 13:39:20 | -3,600 | 385a141bbb4666e7a66f8dd829515447d3da9da3 | Added Sigma object to the 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": "@@ -36,6 +36,7 @@ from . import error\nfrom . import index\nfrom . import sketch\nfrom . import version\n+from . import sigma\nlogger = logging.getLogger('timesketch_api.client')\n@@ -499,3 +500,52 @@ class TimesketchApi:\nreturn\nrequest = google.auth.transport.requests.Request()\nself.credentials.credential.refresh(request)\n+\n+ def list_sigma_rules(self, as_pandas=False):\n+ \"\"\"Get a list of sigma objects.\n+\n+ Args:\n+ as_pandas: Boolean indicating that the results will be returned\n+ as a Pandas DataFrame instead of a list of dicts.\n+\n+ Returns:\n+ List of Sigme rule object instances or a pandas Dataframe with all\n+ rules if as_pandas is True.\n+\n+ Raises:\n+ ValueError: If no rules are found.\n+ \"\"\"\n+ rules = []\n+ response = self.fetch_resource_data('sigma/')\n+\n+ if not response:\n+ raise ValueError('No rules found.')\n+\n+ if as_pandas:\n+ return pandas.DataFrame.from_records(response.get('objects'))\n+\n+ for rule_dict in response['objects']:\n+ rule_uuid = rule_dict.get('id')\n+ title = rule_dict.get('title')\n+ es_query = rule_dict.get('es_query')\n+ file_name = rule_dict.get('file_name')\n+ description = rule_dict.get('description')\n+ file_relpath = rule_dict.get('file_relpath')\n+ index_obj = sigma.Sigma(\n+ rule_uuid, api=self, es_query=es_query, file_name=file_name,\n+ title=title, description=description,\n+ file_relpath=file_relpath)\n+ rules.append(index_obj)\n+ return rules\n+\n+\n+ def get_sigma_rule(self, rule_uuid):\n+ \"\"\"Get a sigma rule.\n+\n+ Args:\n+ rule_uuid: UUID of the Sigma rule.\n+\n+ Returns:\n+ Instance of a Sigma object.\n+ \"\"\"\n+ return sigma.Sigma(rule_uuid, api=self)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "api_client/python/timesketch_api_client/sigma.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 sigma library.\"\"\"\n+from __future__ import unicode_literals\n+\n+import logging\n+\n+from . import resource\n+\n+logger = logging.getLogger('timesketch_api.sigma')\n+\n+\n+class Sigma(resource.BaseResource):\n+ \"\"\"Timesketch sigma object.\n+\n+ A sigma object in Timesketch is a collection of one or more rules.\n+\n+ Attributes:\n+ rule_uuid: The ID of the rule.\n+ \"\"\"\n+\n+\n+ def __init__(self, rule_uuid, api, es_query=None,\n+ file_name=None, title=None, description=None,\n+ file_relpath=None):\n+ \"\"\"Initializes the Sigma object.\n+\n+ Args:\n+ rule_uuid: Id of the sigma rule.\n+ api: An instance of TimesketchApi object.\n+ es_query: Elastic Search query of the rule\n+ file_name: File name of the rule\n+ title: Title of the rule\n+ description: Description of the rule\n+ file_relpath: path of the file relative to the config value\n+\n+ \"\"\"\n+ self.rule_uuid = rule_uuid\n+ self._description = description\n+ self._es_query = es_query\n+ self._file_name = file_name\n+ self._title = title\n+ self._file_relpath = file_relpath\n+ self._resource_uri = f'sigma/{self.rule_uuid}'\n+ super().__init__(\n+ api=api, resource_uri=self._resource_uri)\n+\n+ @property\n+ def es_query(self):\n+ \"\"\"Returns the elastic search query.\"\"\"\n+ sigma_data = self.data\n+\n+ if not sigma_data:\n+ return ''\n+\n+ return sigma_data.get('es_query', '')\n+\n+ @property\n+ def title(self):\n+ \"\"\"Returns the sigma rule title.\"\"\"\n+ sigma_data = self.data\n+\n+ if not sigma_data:\n+ return ''\n+\n+ return sigma_data.get('title', '')\n+\n+ @property\n+ def id(self):\n+ \"\"\"Returns the sigma rule id.\"\"\"\n+ sigma_data = self.data\n+\n+ if not sigma_data:\n+ return ''\n+\n+ return sigma_data.get('id', '')\n+\n+ @property\n+ def file_relpath(self):\n+ \"\"\"Returns the relative filepath of the rule.\"\"\"\n+ sigma_data = self.data\n+\n+ if not sigma_data:\n+ return ''\n+\n+ return sigma_data.get('file_relpath', '')\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "api_client/python/timesketch_api_client/sigma_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 test_lib\n+from . import client\n+\n+\n+class TimesketchSigmaTest(unittest.TestCase):\n+ \"\"\"Test Sigma.\"\"\"\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+\n+ def test_sigma_rule(self):\n+ \"\"\"Test single Sigma rule.\"\"\"\n+\n+ rule = self.api_client.get_sigma_rule(\n+ '5266a592-b793-11ea-b3de-0242ac130004')\n+\n+ self.assertIsNotNone(rule)\n+\n+ self.assertEqual(\n+ rule.title, 'Suspicious Installation of Zenmap',\n+ 'Title of the rule does not match')\n+ self.assertEqual(\n+ rule.id, '5266a592-b793-11ea-b3de-0242ac130004',\n+ 'Id of the rule does not match')\n+\n+ def test_sigma_rules(self):\n+ '''Testing the Sigma rules list'''\n+\n+ rules = self.api_client.list_sigma_rules()\n+ self.assertIsNotNone(rules)\n+\n+ rule1 = rules[0]\n+\n+ self.assertEqual(\n+ rule1.title, 'Suspicious Installation of Zenmap',\n+ 'Title of the rule does not match')\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": "@@ -221,6 +221,79 @@ def mock_response(*args, **kwargs):\n}]\n}\n+ sigma_list = {\n+ 'meta': {\n+ 'current_user': 'dev',\n+ 'rules_count': 2\n+ },\n+ 'objects': [\n+ {\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/06/26',\n+ 'description': 'Detects suspicious installation of Zenmap',\n+ 'detection': {\n+ 'condition': 'keywords',\n+ 'keywords': ['*apt-get install zmap*']\n+ },\n+ 'falsepositives': ['Unknown'],\n+ 'id': '5266a592-b793-11ea-b3de-0242ac130004',\n+ 'level': 'high',\n+ 'logsource': {\n+ 'product': 'linux', 'service': 'shell'\n+ },\n+ 'es_query': '(\"*apt\\\\-get\\\\ install\\\\ zmap*\")',\n+ 'modified': '2020/06/26',\n+ 'references': ['httpx://foobar.com'],\n+ 'title': 'Suspicious Installation of Zenmap',\n+ 'file_name': 'lnx_susp_zenmap',\n+ 'file_relpath' : '/linux/syslog/foobar/'\n+\n+ }, {\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/11/10',\n+ 'description': 'Detects suspicious installation of foobar',\n+ 'detection': {\n+ 'condition': 'keywords',\n+ 'keywords': ['*apt-get install foobar*']\n+ },\n+ 'falsepositives': ['Unknown'],\n+ 'id': '776bdd11-f3aa-436e-9d03-9d6159e9814e',\n+ 'level': 'high',\n+ 'logsource': {\n+ 'product': 'linux', 'service': 'shell'\n+ },\n+ 'es_query': '(\"*apt\\\\-get\\\\ install\\\\ foo*\")',\n+ 'modified': '2020/06/26',\n+ 'references': ['httpx://foobar.com'],\n+ 'title': 'Suspicious Installation of Zenmap',\n+ 'file_name': 'lnx_susp_zenmap',\n+ 'file_relpath' : '/windows/foobar/'\n+ }\n+ ]\n+ }\n+\n+ sigma_rule = {\n+ 'title': 'Suspicious Installation of Zenmap',\n+ 'id': '5266a592-b793-11ea-b3de-0242ac130004',\n+ 'description': 'Detects suspicious installation of Zenmap',\n+ 'references': ['httpx://foobar.com'],\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/06/26',\n+ 'modified': '2020/06/26',\n+ 'logsource': {\n+ 'product': 'linux', 'service': 'shell'\n+ },\n+ 'detection': {\n+ 'keywords': ['*apt-get install zmap*'],\n+ 'condition': 'keywords'\n+ },\n+ 'falsepositives': ['Unknown'],\n+ 'level': 'high',\n+ 'es_query': '(\"*apt\\\\-get\\\\ install\\\\ zmap*\")',\n+ 'file_name': 'lnx_susp_zenmap',\n+ 'file_relpath' : '/linux/syslog/foobar/'\n+ }\n+\n# Register API endpoints to the correct mock response data.\nurl_router = {\n'http://127.0.0.1':\n@@ -245,6 +318,10 @@ def mock_response(*args, **kwargs):\nMockResponse(json_data=story_data),\n'http://127.0.0.1/api/v1/sketches/1/archive/':\nMockResponse(json_data=archive_data),\n+ 'http://127.0.0.1/api/v1/sigma/5266a592-b793-11ea-b3de-0242ac130004':\n+ MockResponse(json_data=sigma_rule),\n+ 'http://127.0.0.1/api/v1/sigma/':\n+ MockResponse(json_data=sigma_list),\n}\nif kwargs.get('empty', False):\n"
},
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -220,3 +220,9 @@ EMAIL_RECIPIENTS = []\n# Configuration to construct URLs for resources.\nEXTERNAL_HOST_URL = 'https://localhost'\n+\n+#-------------------------------------------------------------------------------\n+# Sigma Settings\n+\n+SIGMA_RULES_FOLDERS = ['/etc/timesketch/data/sigma/rules/']\n+SIGMA_CONFIG = '/etc/timesketch/sigma_config.yaml'\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/docker-entrypoint.sh",
"new_path": "docker/dev/build/docker-entrypoint.sh",
"diff": "@@ -12,8 +12,8 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/features.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/tags.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\n- cp /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/\n- cp -r /usr/local/src/timesketch/data/sigma /etc/timesketch/sigma/\n+ ln -s /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/sigma_config.yaml\n+ ln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/sigma/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/APIClient.md",
"new_path": "docs/APIClient.md",
"diff": "@@ -351,6 +351,41 @@ aggregation.name = 'TopDomains'\naggregation.save()\n```\n+### Sigma rules\n+\n+### Get a single rule\n+\n+To get a Sigma rule that is stored on the server via uuid of the rule:\n+\n+```python\n+rule = ts.get_sigma_rule(\"5266a592-b793-11ea-b3de-0242ac130004\")\n+```\n+\n+Returns an object, where you can do something like that:\n+\n+```python\n+rule.data()\n+```\n+\n+To get this:\n+\n+```JSON\n+{'title': 'Suspicious Installation of Zenmap', 'id': '5266a592-b793-11ea-b3de-0242ac130004', 'description': 'Detects suspicious installation of Zenmap', 'references': ['https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html'], 'author': 'Alexander Jaeger', 'date': '2020/06/26', 'modified': '2020/06/26', 'logsource': {'product': 'linux', 'service': 'shell'}, 'detection': {'keywords': ['*apt-get install zmap*'], 'condition': 'keywords'}, 'falsepositives': ['Unknown'], 'level': 'high', 'es_query': '(data_type:(\"shell\\\\:zsh\\\\:history\" OR \"bash\\\\:history\\\\:command\" OR \"apt\\\\:history\\\\:line\" OR \"selinux\\\\:line\") AND \"*apt\\\\-get\\\\ install\\\\ zmap*\")', 'file_name': 'lnx_susp_zenmap'}\n+```\n+\n+### Get a list of rules\n+\n+Another option to explore Sigma rules is via the `list_sigma_rules` function.\n+To get a list of available Sigma rules use:\n+\n+```python\n+ts.list_sigma_rules()\n+```\n+\n+The output can be:\n++ A pandas DataFrame if the `as_pandas=True` is set\n++ A python dict (default behavior)\n+\n### Other Options\nThe sketch object can be used to do several other actions that are not documented in this first document, such as:\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/api/v1/resources/sigma.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+\"\"\"Sigma resources for version 1 of the Timesketch API.\"\"\"\n+\n+import logging\n+\n+from flask import abort\n+from flask import jsonify\n+from flask_restful import Resource\n+from flask_login import login_required\n+from flask_login import current_user\n+\n+import timesketch.lib.sigma_util as ts_sigma_lib\n+\n+from timesketch.api.v1 import resources\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n+\n+logger = logging.getLogger('timesketch.api.sigma')\n+\n+\n+class SigmaListResource(resources.ResourceMixin, Resource):\n+ \"\"\"Resource to get list of Sigma rules.\"\"\"\n+\n+ @login_required\n+ def get(self):\n+ \"\"\"Handles GET request to the resource.\n+\n+ Returns:\n+ Dict of sigma rules\n+ \"\"\"\n+ sigma_rules = []\n+\n+ try:\n+ sigma_rules = ts_sigma_lib.get_all_sigma_rules()\n+\n+ except ValueError:\n+ logger.error('OS Error, unable to get the path to the Sigma rules',\n+ exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'OS Error, unable to get the path to the Sigma rules')\n+\n+ meta = {'current_user': current_user.username,\n+ 'rules_count': len(sigma_rules)}\n+ return jsonify({'objects': sigma_rules, 'meta': meta})\n+\n+\n+class SigmaResource(resources.ResourceMixin, Resource):\n+ \"\"\"Resource to get a Sigma rule.\"\"\"\n+\n+ @login_required\n+ def get(self, rule_uuid):\n+ \"\"\"Handles GET request to the resource.\n+\n+ Args:\n+ rule_uuid: uuid of the sigma rule\n+\n+ Returns:\n+ JSON sigma rule\n+ \"\"\"\n+ return_rule = None\n+ try:\n+ sigma_rules = ts_sigma_lib.get_all_sigma_rules()\n+\n+ except ValueError:\n+ logger.error('OS Error, unable to get the path to the Sigma rules',\n+ exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'OS Error, unable to get the path to the Sigma rules')\n+\n+ for rule in sigma_rules:\n+ if rule is not None:\n+ if rule_uuid == rule.get('id'):\n+ return_rule = rule\n+\n+ if return_rule is None:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sigma rule found with this ID.')\n+\n+ return return_rule\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/routes.py",
"new_path": "timesketch/api/v1/routes.py",
"diff": "@@ -53,6 +53,8 @@ from .resources.user import UserListResource\nfrom .resources.user import GroupListResource\nfrom .resources.user import CollaboratorResource\nfrom .resources.user import LoggedInUserResource\n+from .resources.sigma import SigmaResource\n+from .resources.sigma import SigmaListResource\nfrom .resources.graph import GraphListResource\nfrom .resources.graph import GraphResource\nfrom .resources.graph import GraphPluginListResource\n@@ -100,9 +102,11 @@ API_ROUTES = [\n(GroupListResource, '/groups/'),\n(CollaboratorResource, '/sketches/<int:sketch_id>/collaborators/'),\n(VersionResource, '/version/'),\n+ (SigmaListResource, '/sigma/'),\n+ (SigmaResource, '/sigma/<string:rule_uuid>/'),\n(LoggedInUserResource, '/users/me/'),\n(GraphListResource, '/sketches/<int:sketch_id>/graphs/'),\n(GraphResource, '/sketches/<int:sketch_id>/graphs/<int:graph_id>/'),\n(GraphPluginListResource, '/graphs/'),\n- (GraphCacheResource, '/sketches/<int:sketch_id>/graph/'),\n+ (GraphCacheResource, '/sketches/<int:sketch_id>/graph/')\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/sigma_tagger.py",
"new_path": "timesketch/lib/analyzers/sigma_tagger.py",
"diff": "from __future__ import unicode_literals\nimport logging\n-import os\nimport time\n-import codecs\nimport elasticsearch\n-from sigma.backends import elasticsearch as sigma_elasticsearch\n-import sigma.configuration as sigma_configuration\n-from sigma.parser import collection as sigma_collection\nfrom timesketch.lib.analyzers import utils\nfrom timesketch.lib.analyzers import interface\nfrom timesketch.lib.analyzers import manager\n+import timesketch.lib.sigma_util as ts_sigma_lib\nlogger = logging.getLogger('timesketch.analyzers.sigma_tagger')\n@@ -24,27 +20,6 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nNAME = 'sigma'\n- _CONFIG_FILE = 'sigma_config.yaml'\n-\n- # Path to the directory containing the Sigma Rules to run, relative to\n- # this file.\n- _RULES_PATH = ''\n-\n- def __init__(self, index_name, sketch_id):\n- \"\"\"Initialize the Index Analyzer.\n-\n- Args:\n- index_name: Elasticsearch index name.\n- sketch_id: Sketch ID.\n- \"\"\"\n- super(SigmaPlugin, self).__init__(index_name, sketch_id)\n- sigma_config_path = interface.get_config_path(self._CONFIG_FILE)\n- logger.debug('[sigma] Loading config from {0!s}'.format(\n- sigma_config_path))\n- with open(sigma_config_path, 'r') as sigma_config_file:\n- sigma_config = sigma_config_file.read()\n- self.sigma_config = sigma_configuration.SigmaConfiguration(sigma_config)\n-\ndef run_sigma_rule(self, query, tag_name):\n\"\"\"Runs a sigma rule and applies the appropriate tags.\n@@ -71,70 +46,48 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nReturns:\nString with summary of the analyzer result.\n\"\"\"\n- sigma_backend = sigma_elasticsearch.ElasticsearchQuerystringBackend(\n- self.sigma_config, {})\n- tags_applied = {}\n+ tags_applied = {}\nsigma_rule_counter = 0\n+ sigma_rules = ts_sigma_lib.get_all_sigma_rules()\n- rules_path = os.path.join(os.path.dirname(__file__), self._RULES_PATH)\n-\n+ if sigma_rules is None:\n+ logger.error('No Sigma rules found. Check SIGMA_RULES_FOLDERS')\n- for dirpath, dirnames, files in os.walk(rules_path):\n+ problem_strings = []\n+ output_strings = []\n- if 'deprecated' in dirnames:\n- dirnames.remove('deprecated')\n-\n- for rule_filename in files:\n- if rule_filename.lower().endswith('yml'):\n-\n- # if a sub dir is found, append it to be scanned for rules\n- if os.path.isdir(os.path.join(rules_path, rule_filename)):\n- logger.error(\n- 'this is a directory, skipping: {0:s}'.format(\n- rule_filename))\n- continue\n-\n- tag_name, _ = rule_filename.rsplit('.')\n- tags_applied[tag_name] = 0\n- rule_file_path = os.path.join(dirpath, rule_filename)\n- rule_file_path = os.path.abspath(rule_file_path)\n- logger.info('[sigma] Reading rules from {0!s}'.format(\n- rule_file_path))\n- with codecs.open(rule_file_path, 'r', encoding='utf-8',\n- errors='replace') as rule_file:\n- try:\n- rule_file_content = rule_file.read()\n- parser = sigma_collection.SigmaCollectionParser(\n- rule_file_content, self.sigma_config, None)\n- parsed_sigma_rules = parser.generate(sigma_backend)\n- except NotImplementedError as exception:\n- logger.error(\n- 'Error generating rule in file {0:s}: {1!s}'\n- .format(rule_file_path, exception))\n- continue\n-\n- for sigma_rule in parsed_sigma_rules:\n+ for rule in sigma_rules:\n+ tags_applied[rule.get('file_name')] = 0\ntry:\nsigma_rule_counter += 1\n- logger.info(\n- '[sigma] Generated query {0:s}'\n- .format(sigma_rule))\ntagged_events_counter = self.run_sigma_rule(\n- sigma_rule, tag_name)\n- tags_applied[tag_name] += tagged_events_counter\n+ rule.get('es_query'), rule.get('file_name'))\n+ tags_applied[rule.get('file_name')] += tagged_events_counter\nexcept elasticsearch.TransportError as e:\nlogger.error(\n- 'Timeout generating rule in file {0:s}: '\n+ 'Timeout executing search for {0:s}: '\n'{1!s} waiting for 10 seconds'.format(\n- rule_file_path, e), exc_info=True)\n- time.sleep(10) # waiting 10 seconds\n+ rule.get('file_name'), e), exc_info=True)\n+ # this is caused by to many ES queries in short time range\n+ # thus waiting for 10 seconds before sending the next one.\n+ time.sleep(10)\n+ # This except block is by purpose very broad as one bad rule could\n+ # otherwise stop the whole analyzer run\n+ # it might be an option to write the problematic rules to the output\n+ except: # pylint: disable=bare-except\n+ logger.error(\n+ 'Problem with rule in file {0:s}: '.format(\n+ rule.get('file_name')), exc_info=True)\n+ problem_strings.append('* {0:s}'.format(\n+ rule.get('file_name')))\n+ continue\ntotal_tagged_events = sum(tags_applied.values())\n- output_string = 'Applied {0:d} tags\\n'.format(total_tagged_events)\n+ output_strings.append('Applied {0:d} tags'.format(total_tagged_events))\nfor tag_name, tagged_events_counter in tags_applied.items():\n- output_string += '* {0:s}: {1:d}\\n'.format(\n- tag_name, tagged_events_counter)\n+ output_strings.append('* {0:s}: {1:d}'.format(\n+ tag_name, tagged_events_counter))\nif sigma_rule_counter > 0:\nview = self.sketch.add_view(\n@@ -149,8 +102,7 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\nagg_params=agg_params, view_id=view.id, chart_type='hbarchart',\ndescription='Created by the Sigma analyzer')\n-\n- story = self.sketch.add_story(\"Sigma Rule hits\")\n+ story = self.sketch.add_story('Sigma Rule hits')\nstory.add_text(\nutils.SIGMA_STORY_HEADER, skip_if_exists=True)\n@@ -167,14 +119,15 @@ class SigmaPlugin(interface.BaseSketchAnalyzer):\n'And an overview of all the discovered search terms:')\nstory.add_view(view)\n+ output_strings.append('Problematic rules:')\n+ output_strings.extend(problem_strings)\n+\n+ return '\\n'.join(output_strings)\n- return output_string\nclass RulesSigmaPlugin(SigmaPlugin):\n\"\"\"Sigma plugin to run rules.\"\"\"\n- _RULES_PATH = '../../../data/sigma/rules/'\n-\nNAME = 'sigma'\nmanager.AnalysisManager.register_analyzer(RulesSigmaPlugin)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/lib/sigma_util.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 Sigma lib functions.\"\"\"\n+\n+import os\n+import codecs\n+import logging\n+import yaml\n+\n+from flask import current_app\n+\n+import sigma.configuration as sigma_configuration\n+\n+from sigma.backends import elasticsearch as sigma_es\n+from sigma.parser import collection as sigma_collection\n+from sigma.parser import exceptions as sigma_exceptions\n+\n+logger = logging.getLogger('timesketch.lib.sigma')\n+\n+\n+def get_sigma_config_file():\n+ \"\"\"Get a sigma.configuration.SigmaConfiguration object.\n+\n+ Returns:\n+ A sigma.configuration.SigmaConfiguration object\n+\n+ Raises:\n+ ValueError: If SIGMA_CONFIG is not found in the config file.\n+ or the Sigma config file is not readabale.\n+ \"\"\"\n+ config_file = current_app.config.get('SIGMA_CONFIG')\n+\n+ if not config_file:\n+ raise ValueError(\n+ 'SIGMA_CONFIG not found in config file')\n+\n+ if not os.path.isfile(config_file):\n+ raise ValueError(\n+ 'Unable to open file: [{0:s}], it does not exist.'.format(\n+ config_file))\n+\n+ if not os.access(config_file, os.R_OK):\n+ raise ValueError(\n+ 'Unable to open file: [{0:s}], cannot open it for '\n+ 'read, please check permissions.'.format(config_file))\n+\n+ with open(config_file, 'r') as config_file:\n+ sigma_config_file = config_file.read()\n+\n+ sigma_config = sigma_configuration.SigmaConfiguration(sigma_config_file)\n+\n+ return sigma_config\n+\n+def get_sigma_rules_path():\n+ \"\"\"Get Sigma rules paths.\n+\n+ Returns:\n+ A list of strings to the Sigma rules\n+\n+ Raises:\n+ ValueError: If SIGMA_RULES_FOLDERS is not found in the config file.\n+ or the folders are not readabale.\n+ \"\"\"\n+ rules_path = current_app.config.get('SIGMA_RULES_FOLDERS', [])\n+\n+ if not rules_path:\n+ raise ValueError(\n+ 'SIGMA_RULES_FOLDERS not found in config file')\n+\n+ for folder in rules_path:\n+ if not os.path.isdir(folder):\n+ raise ValueError(\n+ 'Unable to open dir: [{0:s}], it does not exist.'.format(\n+ folder))\n+\n+ if not os.access(folder, os.R_OK):\n+ raise ValueError(\n+ 'Unable to open dir: [{0:s}], cannot open it for '\n+ 'read, please check permissions.'.format(folder))\n+\n+ return rules_path\n+\n+\n+def get_sigma_rules(rule_folder):\n+ \"\"\"Returns the Sigma rules for a folder including subfolders.\n+\n+ Args:\n+ rule_folder: folder to be checked for rules\n+\n+ Returns:\n+ A array of Sigma rules as JSON\n+\n+ Raises:\n+ ValueError: If SIGMA_RULES_FOLDERS is not found in the config file.\n+ or the folders are not readabale.\n+ \"\"\"\n+ return_array = []\n+\n+ for dirpath, dirnames, files in os.walk(rule_folder):\n+ if 'deprecated' in [x.lower() for x in dirnames]:\n+ dirnames.remove('deprecated')\n+\n+ for rule_filename in files:\n+ if rule_filename.lower().endswith('.yml'):\n+ # if a sub dir is found, do not try to parse it.\n+ if os.path.isdir(os.path.join(dirpath, rule_filename)):\n+ continue\n+\n+ rule_file_path = os.path.join(dirpath, rule_filename)\n+ parsed_rule = get_sigma_rule(rule_file_path)\n+ if parsed_rule:\n+ return_array.append(parsed_rule)\n+\n+ return return_array\n+\n+\n+def get_all_sigma_rules():\n+ \"\"\"Returns all Sigma rules\n+\n+ Returns:\n+ A array of Sigma rules\n+\n+ Raises:\n+ ValueError: If SIGMA_RULES_FOLDERS is not found in the config file.\n+ or the folders are not readabale.\n+ \"\"\"\n+ sigma_rules = []\n+\n+ rules_paths = get_sigma_rules_path()\n+\n+ for folder in rules_paths:\n+ sigma_rules.extend(get_sigma_rules(folder))\n+\n+ return sigma_rules\n+\n+\n+def get_sigma_rule(filepath):\n+ \"\"\" Returns a JSON represenation for a rule\n+\n+ Args:\n+ filepath: path to the sigma rule to be parsed\n+\n+ Returns:\n+ Json representation of the parsed rule\n+ \"\"\"\n+ try:\n+ sigma_config = get_sigma_config_file()\n+ except ValueError as e:\n+ logger.error(\n+ 'Problem reading the Sigma config {0:s}: '\n+ .format(e), exc_info=True)\n+ return None\n+\n+ sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_config, {})\n+\n+ if filepath.lower().endswith('.yml'):\n+ # if a sub dir is found, nothing can be parsed\n+ if os.path.isdir(filepath):\n+ return None\n+\n+ abs_path = os.path.abspath(filepath)\n+\n+ with codecs.open(\n+ abs_path, 'r', encoding='utf-8', errors='replace') as file:\n+ try:\n+ rule_return = {}\n+ rule_yaml_data = yaml.safe_load_all(file.read())\n+ for doc in rule_yaml_data:\n+ rule_return.update(doc)\n+ parser = sigma_collection.SigmaCollectionParser(\n+ str(doc), sigma_config, None)\n+ parsed_sigma_rules = parser.generate(sigma_backend)\n+\n+ except NotImplementedError as exception:\n+ logger.error(\n+ 'Error generating rule in file {0:s}: {1!s}'\n+ .format(abs_path, exception))\n+ return None\n+\n+ except sigma_exceptions.SigmaParseError as exception:\n+ logger.error(\n+ 'Sigma parsing error generating rule in file {0:s}: {1!s}'\n+ .format(abs_path, exception))\n+ return None\n+\n+ except yaml.parser.ParserError as exception:\n+ logger.error(\n+ 'Yaml parsing error generating rule in file {0:s}: {1!s}'\n+ .format(abs_path, exception))\n+ return None\n+\n+ sigma_es_query = ''\n+\n+ for sigma_rule in parsed_sigma_rules:\n+ sigma_es_query = sigma_rule\n+\n+ rule_return.update(\n+ {'es_query':sigma_es_query})\n+ rule_return.update(\n+ {'file_name':os.path.basename(filepath)})\n+\n+ # in case multiple folders are in the config, need to remove them\n+ for rule_path in get_sigma_rules_path():\n+ file_relpath = os.path.relpath(filepath, rule_path)\n+\n+ rule_return.update(\n+ {'file_relpath':file_relpath})\n+\n+ return rule_return\n+\n+ return None\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added Sigma object to the API client (#1456) |
263,133 | 03.12.2020 12:54:15 | 0 | 3911225d647665f69e406fd39036c25d507ead57 | Making changes to the search API client. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/search.py",
"new_path": "api_client/python/timesketch_api_client/search.py",
"diff": "@@ -448,13 +448,9 @@ class Search(resource.SketchResource):\nraise ValueError(\n'Unable to query with a query filter that isn\\'t a dict.')\n- stop_size = query_filter.get('size', 0)\n- terminate_after = query_filter.get('terminate_after', 0)\n- if terminate_after and (terminate_after < stop_size):\n- stop_size = terminate_after\n-\n+ stop_size = self._max_entries\nscrolling = not bool(stop_size and (\n- stop_size < self.DEFAULT_SIZE_LIMIT))\n+ stop_size <= self.DEFAULT_SIZE_LIMIT))\nform_data = {\n'query': self._query_string,\n@@ -487,8 +483,6 @@ class Search(resource.SketchResource):\nwhile count > 0:\nif self._max_entries and total_count >= self._max_entries:\nbreak\n- if stop_size and total_count >= stop_size:\n- break\nif not scroll_id:\nlogger.debug('No scroll ID, will stop.')\n@@ -681,6 +675,10 @@ class Search(resource.SketchResource):\ndef max_entries(self, max_entries):\n\"\"\"Make changes to the max entries of return values.\"\"\"\nself._max_entries = max_entries\n+ if max_entries < self.DEFAULT_SIZE_LIMIT:\n+ _ = self.query_filter\n+ self._query_filter['size'] = max_entries\n+ self._query_filter['terminate_after'] = max_entries\nself.commit()\n@property\n@@ -724,8 +722,8 @@ class Search(resource.SketchResource):\nself._query_filter = {\n'time_start': None,\n'time_end': None,\n- 'size': self._max_entries,\n- 'terminate_after': self._max_entries,\n+ 'size': self.DEFAULT_SIZE_LIMIT,\n+ 'terminate_after': self.DEFAULT_SIZE_LIMIT,\n'indices': '_all',\n'order': 'asc',\n'chips': [],\n@@ -738,7 +736,10 @@ class Search(resource.SketchResource):\ndef query_filter(self, query_filter):\n\"\"\"Make changes to the query filter.\"\"\"\nif isinstance(query_filter, str):\n+ try:\nquery_filter = json.loads(query_filter)\n+ except json.JSONDecodeError as exc:\n+ raise ValueError('Unable to parse the string as JSON') from exc\nif not isinstance(query_filter, dict):\nraise ValueError('Query filter needs to be a dict.')\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20201130'\n+__version__ = '20201203'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Making changes to the search API client. (#1500) |
263,148 | 04.12.2020 19:33:30 | 0 | 282c3fcd96a9f6b696b7fc53cec1947fc27f0305 | Enabled connection to production Elastic instance (using SSL) | [
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -28,6 +28,10 @@ SQLALCHEMY_DATABASE_URI = 'postgresql://<USERNAME>:<PASSWORD>@localhost/timesket\n# http://www.elasticsearch.org/blog/scripting-security/\nELASTIC_HOST = '127.0.0.1'\nELASTIC_PORT = 9200\n+ELASTIC_USER = None\n+ELASTIC_PASSWORD = None\n+ELASTIC_SSL = False\n+ELASTIC_VERIFY_CERTS = True\n# Define what labels should be defined that make it so that a sketch and\n# timelines will not be deleted. This can be used to add a list of different\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/aggregators/interface.py",
"new_path": "timesketch/lib/aggregators/interface.py",
"diff": "from __future__ import unicode_literals\n-from elasticsearch import Elasticsearch\nfrom flask import current_app\nimport pandas\nfrom timesketch.lib.charts import manager as chart_manager\n+from timesketch.lib.datastores.elastic import ElasticsearchDataStore\nfrom timesketch.models.sketch import Sketch as SQLSketch\n@@ -154,9 +154,10 @@ class BaseAggregator(object):\nif not sketch_id and not index:\nraise RuntimeError('Need at least sketch_id or index')\n- self.elastic = Elasticsearch(\n+ self.elastic = ElasticsearchDataStore(\nhost=current_app.config['ELASTIC_HOST'],\nport=current_app.config['ELASTIC_PORT'])\n+\nself.field = ''\nself.index = index\nself.sketch = SQLSketch.query.get(sketch_id)\n@@ -198,7 +199,7 @@ class BaseAggregator(object):\nfield_type = None\n# Get the mapping for the field.\n- mapping = self.elastic.indices.get_field_mapping(\n+ mapping = self.elastic.client.indices.get_field_mapping(\nindex=self.index, fields=field_name)\n# The returned structure is nested so we need to unpack it.\n@@ -236,8 +237,8 @@ class BaseAggregator(object):\nReturns:\nElasticsearch aggregation result.\n\"\"\"\n- # pylint: disable=unexpected-keyword-arg\n- aggregation = self.elastic.search(\n+ # pylint: disable=unexpected-keyword-arg, no-value-for-parameter\n+ aggregation = self.elastic.client.search(\nindex=self.index, body=aggregation_spec, size=0)\nreturn aggregation\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -32,6 +32,7 @@ from elasticsearch.exceptions import RequestError\n# pylint: disable=redefined-builtin\nfrom elasticsearch.exceptions import ConnectionError\nfrom flask import abort\n+from flask import current_app\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n@@ -77,7 +78,20 @@ class ElasticsearchDataStore(object):\n\"\"\"Create a Elasticsearch client.\"\"\"\nsuper().__init__()\nself._error_container = {}\n+\n+ self.user = current_app.config.get('ELASTIC_USER', 'user')\n+ self.password = current_app.config.get('ELASTIC_PASSWORD', 'pass')\n+ self.ssl = current_app.config.get('ELASTIC_SSL', False)\n+ self.verify = current_app.config.get('ELASTIC_VERIFY_CERTS', True)\n+\n+ if self.ssl:\n+ self.client = Elasticsearch([{'host': host, 'port': port}],\n+ http_auth=(self.user, self.password),\n+ use_ssl=self.ssl,\n+ verify_certs=self.verify)\n+ else:\nself.client = Elasticsearch([{'host': host, 'port': port}])\n+\nself.import_counter = Counter()\nself.import_events = []\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/testlib.py",
"new_path": "timesketch/lib/testlib.py",
"diff": "@@ -45,6 +45,10 @@ class TestConfig(object):\nWTF_CSRF_ENABLED = False\nELASTIC_HOST = None\nELASTIC_PORT = None\n+ ELASTIC_USER = None\n+ ELASTIC_PASSWORD = None\n+ ELASTIC_SSL = False\n+ ELASTIC_VERIFY_CERTS = True\nLABELS_TO_PREVENT_DELETION = ['protected', 'magic']\nUPLOAD_ENABLED = False\nGRAPH_BACKEND_ENABLED = False\n"
}
] | Python | Apache License 2.0 | google/timesketch | Enabled connection to production Elastic instance (using SSL) (#1503) |
263,096 | 04.12.2020 20:50:47 | -3,600 | d7d252f87602e9625f8e8bc3ae6bce93a13fb2ed | Sigma Rule maintain improvement | [
{
"change_type": "MODIFY",
"old_path": "test_tools/sigma_verify_rules.py",
"new_path": "test_tools/sigma_verify_rules.py",
"diff": "@@ -17,84 +17,21 @@ This tool can be used to verify your rules before running an analyzer.\nIt also does not require you to have a full blown Timesketch instance.\nDefault this tool will show only the rules that cause problems.\nExample way of running the tool:\n- $ sigma_verify_rules.py --config_file ../data/sigma_config.yaml ../data/linux/\n+$ PYTHONPATH=. python3 test_tools/sigma_verify_rules.py --config_file\n+../data/sigma_config.yaml --config_file data/sigma_config.yaml\n+--debug data/sigma/rules/windows/ --move data/sigma/rules/problematic/\n\"\"\"\n-\nimport logging\nimport os\nimport argparse\nimport sys\n-import codecs\n-import sigma.parser.exceptions\n-import sigma.configuration as sigma_configuration\n-from sigma.backends import elasticsearch as sigma_elasticsearch\n-from sigma.parser import collection as sigma_collection\n+from timesketch.lib import sigma_util# pylint: disable=no-name-in-module\nlogger = logging.getLogger('timesketch.test_tool.sigma-verify')\nlogging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))\n-RULE_EXTENSIONS = ('yml', 'yaml')\n-\n-def get_codepath():\n- \"\"\"Return the absolute path to where the tool is run from.\"\"\"\n- # TODO: move this function to a library as it is duplicate to WebUI\n-\n- path = __file__\n- if path.startswith(os.path.sep):\n- return path\n-\n- dirname = os.path.dirname(path)\n- for sys_path in sys.path:\n- if sys_path.endswith(dirname):\n- return sys_path\n- return dirname\n-\n-def verify_rules_file(rule_file_path, sigma_config, sigma_backend):\n- \"\"\"Verifies a given file path contains a valid sigma rule.\n-\n- Args:\n- rule_file_path: the path to the rules.\n- sigma_config: config to use\n- sigma_backend: A sigma.backends instance\n-\n- Raises:\n- None\n-\n- Returns:\n- true: rule_file_path contains a valid sigma rule\n- false: rule_file_path does not contain a valid sigma rule\n- \"\"\"\n-\n- logger.debug('[sigma] Reading rules from {0:s}'.format(\n- rule_file_path))\n-\n- if not os.path.isfile(rule_file_path):\n- logger.error('Rule file not found')\n- return False\n-\n- path, rule_filename = os.path.split(rule_file_path)\n-\n- with codecs.open(rule_file_path, 'r', encoding='utf-8') as rule_file:\n- try:\n- rule_file_content = rule_file.read()\n- parser = sigma_collection.SigmaCollectionParser(\n- rule_file_content, sigma_config, None)\n- parsed_sigma_rules = parser.generate(sigma_backend)\n- except NotImplementedError:\n- logger.error('{0:s} Error with file {1:s}'.format(\n- rule_filename, rule_file_path), exc_info=True)\n- return False\n- except (sigma.parser.exceptions.SigmaParseError, TypeError):\n- logger.error(\n- '{0:s} Error with file {1:s} '\n- 'you should not use this rule in Timesketch '.format(\n- rule_filename, rule_file_path), exc_info=True)\n- return False\n-\n- return True\n-\ndef run_verifier(rules_path, config_file_path):\n\"\"\"Run an sigma parsing test on a dir and returns results from the run.\n@@ -112,6 +49,9 @@ def run_verifier(rules_path, config_file_path):\n- sigma_verified_rules with rules that can be added\n- sigma_rules_with_problems with rules that should not be added\n\"\"\"\n+ if not config_file_path:\n+ raise IOError('No config_file_path given')\n+\nif not os.path.isdir(rules_path):\nraise IOError('Rules not found at path: {0:s}'.format(\nrules_path))\n@@ -119,51 +59,59 @@ def run_verifier(rules_path, config_file_path):\nraise IOError('Config file path not found at path: {0:s}'.format(\nconfig_file_path))\n- sigma_config_path = config_file_path\n+ sigma_config = sigma_util.get_sigma_config_file(\n+ config_file=config_file_path)\n- with open(sigma_config_path, 'r') as sigma_config_file:\n- sigma_config_con = sigma_config_file.read()\n- sigma_config = sigma_configuration.SigmaConfiguration(sigma_config_con)\n- backend = sigma_elasticsearch.ElasticsearchQuerystringBackend(\n- sigma_config, {})\nreturn_verified_rules = []\nreturn_rules_with_problems = []\nfor dirpath, dirnames, files in os.walk(rules_path):\n-\nif 'deprecated' in [x.lower() for x in dirnames]:\ndirnames.remove('deprecated')\n- logger.info('deprecated in folder / filename found - ignored')\nfor rule_filename in files:\n- if not rule_filename.lower().endswith(RULE_EXTENSIONS):\n- continue\n-\n- # If a sub dir is found, skip it\n- if os.path.isdir(os.path.join(rules_path, rule_filename)):\n- logger.debug(\n- 'Directory found, skipping: {0:s}'.format(rule_filename))\n+ if rule_filename.lower().endswith('.yml'):\n+ # if a sub dir is found, do not try to parse it.\n+ if os.path.isdir(os.path.join(dirpath, rule_filename)):\ncontinue\nrule_file_path = os.path.join(dirpath, rule_filename)\n- rule_file_path = os.path.abspath(rule_file_path)\n-\n- if verify_rules_file(rule_file_path, sigma_config, backend):\n+ parsed_rule = sigma_util.get_sigma_rule(\n+ rule_file_path, sigma_config)\n+ if parsed_rule:\nreturn_verified_rules.append(rule_file_path)\nelse:\n- logger.info('File did not work{0:s}'.format(rule_file_path))\nreturn_rules_with_problems.append(rule_file_path)\nreturn return_verified_rules, return_rules_with_problems\n-if __name__ == '__main__':\n- code_path = get_codepath()\n- # We want to ensure our mocked libraries get loaded first.\n- sys.path.insert(0, code_path)\n+def move_problematic_rule(filepath, move_to_path, reason=None):\n+ \"\"\" Moves a problematic rule to a subfolder so it is not used again\n+ Args:\n+ filepath: path to the sigma rule that caused problems\n+ move_to_path: path to move the problematic rules to\n+ reason: optional reason why file is moved\n+ \"\"\"\n+ logging.info('Moving the rule: {0:s} to {1:s}'.format(\n+ filepath, move_to_path))\n+ try:\n+ os.makedirs(move_to_path, exist_ok=True)\n+ debug_path = os.path.join(move_to_path, 'debug.log')\n+\n+ with open(debug_path, 'a') as file_objec:\n+ file_objec.write(f'{filepath}\\n{reason}\\n\\n')\n+\n+ base_path = os.path.basename(filepath)\n+ os.rename(filepath, f'{move_to_path}{base_path}')\n+ except OSError:\n+ logger.error('OS Error - no rules moved')\n+\n+\n+if __name__ == '__main__':\ndescription = (\n- 'Mock an sigma analyzer run. This tool is intended for developers '\n+ 'Mock an sigma parser run. This tool is intended for developers '\n'of sigma rules as well as Timesketch server admins. '\n'The tool can also be used for automatic testing to make sure the '\n'rules are still working as intended.')\n@@ -185,6 +133,11 @@ if __name__ == '__main__':\n'--debug', action='store_true', help='print debug messages ')\narguments.add_argument(\n'--info', action='store_true', help='print info messages ')\n+ arguments.add_argument(\n+ '--move', dest='move_to_path', action='store',\n+ default='', type=str, help=(\n+ 'Path to the file containing the config data to feed sigma '\n+ ))\ntry:\noptions = arguments.parse_args()\nexcept UnicodeEncodeError:\n@@ -214,6 +167,10 @@ if __name__ == '__main__':\nprint('### You should NOT import the following rules ###')\nprint('### To get the reason per rule, re-run with --info###')\nfor badrule in sigma_rules_with_problems:\n+ if options.move_to_path:\n+ move_problematic_rule(\n+ badrule, options.move_to_path,\n+ 'sigma_verify_rules.py found an issue')\nprint(badrule)\nif len(sigma_verified_rules) > 0:\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -29,9 +29,12 @@ from sigma.parser import exceptions as sigma_exceptions\nlogger = logging.getLogger('timesketch.lib.sigma')\n-def get_sigma_config_file():\n+def get_sigma_config_file(config_file=None):\n\"\"\"Get a sigma.configuration.SigmaConfiguration object.\n+ Args:\n+ config_file: Optional path to a config file\n+\nReturns:\nA sigma.configuration.SigmaConfiguration object\n@@ -39,24 +42,27 @@ def get_sigma_config_file():\nValueError: If SIGMA_CONFIG is not found in the config file.\nor the Sigma config file is not readabale.\n\"\"\"\n- config_file = current_app.config.get('SIGMA_CONFIG')\n+ if config_file:\n+ config_file_path = config_file\n+ else:\n+ config_file_path = current_app.config.get('SIGMA_CONFIG')\nif not config_file:\nraise ValueError(\n'SIGMA_CONFIG not found in config file')\n- if not os.path.isfile(config_file):\n+ if not os.path.isfile(config_file_path):\nraise ValueError(\n'Unable to open file: [{0:s}], it does not exist.'.format(\n- config_file))\n+ config_file_path))\n- if not os.access(config_file, os.R_OK):\n+ if not os.access(config_file_path, os.R_OK):\nraise ValueError(\n'Unable to open file: [{0:s}], cannot open it for '\n- 'read, please check permissions.'.format(config_file))\n+ 'read, please check permissions.'.format(config_file_path))\n- with open(config_file, 'r') as config_file:\n- sigma_config_file = config_file.read()\n+ with open(config_file_path, 'r') as config_file_read:\n+ sigma_config_file = config_file_read.read()\nsigma_config = sigma_configuration.SigmaConfiguration(sigma_config_file)\n@@ -72,7 +78,11 @@ def get_sigma_rules_path():\nValueError: If SIGMA_RULES_FOLDERS is not found in the config file.\nor the folders are not readabale.\n\"\"\"\n+ try:\nrules_path = current_app.config.get('SIGMA_RULES_FOLDERS', [])\n+ except RuntimeError as e:\n+ raise ValueError(\n+ 'SIGMA_RULES_FOLDERS not found in config file') from e\nif not rules_path:\nraise ValueError(\n@@ -92,11 +102,13 @@ def get_sigma_rules_path():\nreturn rules_path\n-def get_sigma_rules(rule_folder):\n+def get_sigma_rules(rule_folder, sigma_config=None):\n\"\"\"Returns the Sigma rules for a folder including subfolders.\nArgs:\nrule_folder: folder to be checked for rules\n+ sigma_config: optional argument to pass a\n+ sigma.configuration.SigmaConfiguration object\nReturns:\nA array of Sigma rules as JSON\n@@ -118,7 +130,7 @@ def get_sigma_rules(rule_folder):\ncontinue\nrule_file_path = os.path.join(dirpath, rule_filename)\n- parsed_rule = get_sigma_rule(rule_file_path)\n+ parsed_rule = get_sigma_rule(rule_file_path, sigma_config)\nif parsed_rule:\nreturn_array.append(parsed_rule)\n@@ -145,26 +157,38 @@ def get_all_sigma_rules():\nreturn sigma_rules\n-def get_sigma_rule(filepath):\n+def get_sigma_rule(filepath, sigma_config=None):\n\"\"\" Returns a JSON represenation for a rule\nArgs:\nfilepath: path to the sigma rule to be parsed\n+ sigma_config: optional argument to pass a\n+ sigma.configuration.SigmaConfiguration object\nReturns:\nJson representation of the parsed rule\n\"\"\"\ntry:\n- sigma_config = get_sigma_config_file()\n+ if sigma_config:\n+ sigma_conf_obj = sigma_config\n+ else:\n+ sigma_conf_obj = get_sigma_config_file()\nexcept ValueError as e:\nlogger.error(\n'Problem reading the Sigma config {0:s}: '\n.format(e), exc_info=True)\nreturn None\n- sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_config, {})\n+ sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_conf_obj, {})\n+\n+ try:\n+ sigma_rules_paths = get_sigma_rules_path()\n+ except ValueError:\n+ sigma_rules_paths = None\n+\n+ if not filepath.lower().endswith('.yml'):\n+ return None\n- if filepath.lower().endswith('.yml'):\n# if a sub dir is found, nothing can be parsed\nif os.path.isdir(filepath):\nreturn None\n@@ -211,12 +235,13 @@ def get_sigma_rule(filepath):\n{'file_name':os.path.basename(filepath)})\n# in case multiple folders are in the config, need to remove them\n- for rule_path in get_sigma_rules_path():\n+ if sigma_rules_paths:\n+ for rule_path in sigma_rules_paths:\nfile_relpath = os.path.relpath(filepath, rule_path)\n+ else:\n+ file_relpath = 'N/A'\nrule_return.update(\n{'file_relpath':file_relpath})\nreturn rule_return\n-\n- return None\n"
}
] | Python | Apache License 2.0 | google/timesketch | Sigma Rule maintain improvement (#1502) |
263,093 | 07.12.2020 17:04:17 | -3,600 | 34e21f378ed4344850dac2c62795561ce1f26331 | use docker network | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/timesketchrc",
"new_path": "docker/dev/build/timesketchrc",
"diff": "[timesketch]\n-host_uri = http://localhost:5000\n+host_uri = http://timesketch:5000\nusername = dev\nverify = True\nclient_id =\nclient_secret =\nauth_mode = userpass\ncred_key = oqyymP-6FS9IY-Id-5nieXMzIajJ7NWx9Ndm_r7K0xg=\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/dev/docker-compose.yml",
"new_path": "docker/dev/docker-compose.yml",
"diff": "@@ -9,6 +9,7 @@ services:\n- elasticsearch\n- postgres\n- redis\n+ - notebook\nenvironment:\n- POSTGRES_USER=timesketch\n- POSTGRES_PASSWORD=password\n@@ -52,10 +53,8 @@ services:\nnotebook:\nimage: us-docker.pkg.dev/osdfir-registry/timesketch/notebook:latest\nports:\n- - 8844:8844\n+ - \"127.0.0.1:8844:8844\"\nrestart: on-failure\n- network_mode: \"host\"\nvolumes:\n- ../../:/usr/local/src/timesketch/:ro\n- /tmp/:/usr/local/src/picadata/\n\\ No newline at end of file\n-\n"
}
] | Python | Apache License 2.0 | google/timesketch | use docker network (#1507) |
263,133 | 09.12.2020 11:26:28 | 0 | 55d5bac9966b41c14ea9f620cbcd8c34c28b56e5 | Added a check for default section value in API client | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/config.py",
"new_path": "api_client/python/timesketch_api_client/config.py",
"diff": "@@ -243,6 +243,9 @@ class ConfigAssistant:\nlogger.warning('No config read')\nreturn\n+ if not section:\n+ section = 'timesketch'\n+\nif section not in config.sections():\nlogger.warning('No %s section in the config', section)\nreturn\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added a check for default section value in API client (#1516) |
263,096 | 09.12.2020 18:16:29 | -3,600 | 7d0827daf911d4e6b73d0f08f7b7d9ce82e20582 | [docs] How to run a single test file
There are multiple ways to run single test files, but at least one method for people getting started running a single test file within docker (so we know the environment is controlled and ready to be used) | [
{
"change_type": "MODIFY",
"old_path": "docs/Developers-Guide.md",
"new_path": "docs/Developers-Guide.md",
"diff": "@@ -44,6 +44,19 @@ To run TSLint in watch mode, use\n! yarn run lint --watch\n```\n+To run a single test (there are multiple ways to do it), open a shell in the docker container:\n+```\n+docker exec -it $CONTAINER_ID /bin/bash\n+```\n+Switch to:\n+```\n+cd /usr/local/src/timesketch\n+```\n+And execute the single test\n+```\n+nosetests timesketch/lib/emojis_test.py -v\n+```\n+\n#### Building Timesketch frontend\nTo build frontend files and put bundles in `timesketch/static/dist/`, use\n"
}
] | Python | Apache License 2.0 | google/timesketch | [docs] How to run a single test file (#1517)
There are multiple ways to run single test files, but at least one method for people getting started running a single test file within docker (so we know the environment is controlled and ready to be used)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,093 | 11.12.2020 13:51:27 | -3,600 | a29a1b6a5ff535f6310fb62ddf505d2a721b3de3 | require view name | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/view.py",
"new_path": "timesketch/api/v1/resources/view.py",
"diff": "@@ -83,6 +83,9 @@ class ViewListResource(resources.ResourceMixin, Resource):\nif isinstance(query_filter, tuple):\nquery_filter = query_filter[0]\n+ if not view_name:\n+ abort(HTTP_STATUS_CODE_BAD_REQUEST, 'View name is missing.')\n+\n# Create a new search template based on this view (only if requested by\n# the user).\nif form.new_searchtemplate.data:\n"
}
] | Python | Apache License 2.0 | google/timesketch | require view name (#1523) |
263,133 | 14.12.2020 14:32:19 | 0 | efc54ce12ccf310a7beeb4cbe25b4115cbf0a480 | Added API client support for graphs. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/setup.py",
"new_path": "api_client/python/setup.py",
"diff": "@@ -57,6 +57,7 @@ setup(\n'requests',\n'altair',\n'google-auth',\n+ 'networkx',\n'google_auth_oauthlib',\n'beautifulsoup4']),\n)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "api_client/python/timesketch_api_client/graph.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 graph object.\"\"\"\n+import copy\n+import datetime\n+import json\n+import logging\n+\n+import dateutil.parser\n+import pandas\n+import numpy\n+import networkx as nx\n+\n+from . import error\n+from . import resource\n+\n+\n+logger = logging.getLogger('timesketch_api.graph')\n+\n+\n+class Graph(resource.SketchResource):\n+ \"\"\"Graph object.\"\"\"\n+\n+ # This defines a list of layouts that are available\n+ # for the graph.\n+ _GRAPH_LAYOUTS = {\n+ 'bipartite': nx.bipartite_layout,\n+ 'circular': nx.circular_layout,\n+ 'kamada': nx.kamada_kawai_layout,\n+ 'kamada_kawai': nx.kamada_kawai_layout,\n+ 'planar': nx.planar_layout,\n+ 'random': nx.random_layout,\n+ 'rescale': nx.rescale_layout,\n+ 'shell': nx.shell_layout,\n+ 'spectral': nx.spectral_layout,\n+ 'multipartite': nx.multipartite_layout,\n+ 'spring': nx.spring_layout,\n+ }\n+\n+ def __init__(self, sketch):\n+ \"\"\"Initialize the graph object.\"\"\"\n+ resource_uri = f'sketches/{sketch.id}/graphs/'\n+ super().__init__(sketch=sketch, resource_uri=resource_uri)\n+\n+ self._created_at = None\n+ self._graph = None\n+ self._description = ''\n+ self._layout = None\n+ self._name = ''\n+ self._updated_at = None\n+ self._graph_config = {}\n+\n+ def _parse_graph_dict(self, graph_dict):\n+ \"\"\"Takes a dict object and constructs graph data from it.\n+\n+ Args:\n+ graph_dict (dict): a dict that contains graph elements, as\n+ return back by the API.\n+ \"\"\"\n+ graph_string = graph_dict.get('graph_elements')\n+\n+ if isinstance(graph_string, str):\n+ try:\n+ self.resource_data = json.loads(graph_string)\n+ except json.JSONDecodeError as exc:\n+ raise ValueError('Unable to read graph data') from exc\n+ elif isinstance(graph_string, dict):\n+ self.resource_data = graph_string\n+ else:\n+ raise ValueError('Graph elements missing or not of correct value.')\n+\n+ graph_config = graph_dict.get('graph_config')\n+ if graph_config:\n+ self._graph_config = json.loads(graph_config)\n+\n+ self._created_at = dateutil.parser.parse(\n+ graph_dict.get('created_at', ''))\n+ self._updated_at = dateutil.parser.parse(\n+ graph_dict.get('updated_at', ''))\n+\n+ def _serialize(self, config_dict):\n+ \"\"\"Serialize a graph config dictionary as JSON.\n+\n+ Due to networkx's use of numpy.ndarray to describe\n+ coordinates JSON is unable to serialize the dictionary.\n+ It is therefore needed to convert the ndarray into lists\n+ so that they can be serialized by JSON.\n+\n+ Args:\n+ config_dict (dict): the graph config dictionary.\n+\n+ Returns:\n+ A JSON serialized string with the dictionary's content.\n+ \"\"\"\n+ for key, item in config_dict.get('layout', {}).items():\n+ if not isinstance(item, numpy.ndarray):\n+ continue\n+ config_dict['layout'][key] = list(item)\n+\n+ return json.dumps(config_dict)\n+\n+ @property\n+ def created_at(self):\n+ \"\"\"Property that returns back the creation time of a graph.\"\"\"\n+ if self._created_at:\n+ return self._created_at.isoformat()\n+ return self._created_at\n+\n+ def delete(self):\n+ \"\"\"Deletes the saved graph from the store.\"\"\"\n+ if not self._resource_id:\n+ logger.warning(\n+ 'Unable to delete the saved graph, it does not appear to be '\n+ 'saved in the first place.')\n+ return False\n+\n+ resource_url = (\n+ f'{self.api.api_root}/sketches/{self._sketch.id}/graphs/'\n+ f'{self._resource_id}/')\n+\n+ response = self.api.session.delete(resource_url)\n+ return error.check_return_status(response, logger)\n+\n+ @property\n+ def description(self):\n+ \"\"\"Property that returns back the description of the saved search.\"\"\"\n+ return self._description\n+\n+ @description.setter\n+ def description(self, description):\n+ \"\"\"Make changes to the saved search description field.\"\"\"\n+ self._description = description\n+ self.commit()\n+\n+ @property\n+ def draw(self):\n+ \"\"\"Property that returns back a drawing with the graph.\"\"\"\n+ if not self.graph:\n+ return None\n+\n+ if not self.graph.size():\n+ return None\n+\n+ data = self.data.get('elements', {})\n+ nodes = data.get('nodes', [])\n+\n+ label_dict = {\n+ x.get('data', {}).get('name', ''): x.get(\n+ 'data', {}).get('label', '') for x in nodes\n+ }\n+\n+ edges = data.get('edges', [])\n+ edge_dict = {\n+ x.get('data', {}).get('name', ''): x.get(\n+ 'data', {}).get('label', '') for x in edges\n+ }\n+ label_dict.update(edge_dict)\n+\n+ label_keys = list(label_dict.keys())\n+ for key in label_keys:\n+ if not key:\n+ _ = label_dict.pop(key)\n+\n+ return nx.draw_networkx(\n+ self.graph, with_labels=True, labels=label_dict,\n+ pos=self.layout)\n+\n+ @property\n+ def graph(self):\n+ \"\"\"Property that returns back a graph object.\"\"\"\n+ if self._graph:\n+ return self._graph\n+\n+ if not self.resource_data:\n+ return nx.Graph()\n+\n+ # It is necessary to do a deep copy, otherwise the upstream\n+ # nx library modifies the resource data.\n+ graph_dict = copy.deepcopy(self.resource_data)\n+ self._graph = nx.cytoscape_graph(graph_dict)\n+ return self._graph\n+\n+ @property\n+ def graph_config(self):\n+ \"\"\"Property that returns the graph config.\"\"\"\n+ if self._graph_config:\n+ return self._graph_config\n+\n+ self._graph_config = {\n+ 'filter': {\n+ 'indices': [\n+ t.index_name for t in self._sketch.list_timelines()],\n+ },\n+ 'layout': self.layout\n+ }\n+ return self._graph_config\n+\n+ @graph_config.setter\n+ def graph_config(self, graph_config):\n+ \"\"\"Change the graph config.\"\"\"\n+ if not isinstance(graph_config, dict):\n+ raise ValueError('Graph config needs to be a dict.')\n+\n+ self._graph_config = graph_config\n+\n+ def from_graph(self, graph_obj):\n+ \"\"\"Initialize from a networkx graph object.\n+\n+ Args:\n+ graph_obj (nx.Graph): a graph object.\n+ \"\"\"\n+ if not graph_obj.size():\n+ logger.warning('Unable to load graph from an empty graph object.')\n+ return\n+ self.resource_data = nx.cytoscape_data(graph_obj)\n+ self._graph = graph_obj\n+ self._name = ''\n+ self._description = 'From a graph object.'\n+ time = datetime.datetime.now(datetime.timezone.utc)\n+ self._created_at = time\n+ self._updated_at = time\n+\n+ def from_manual(self, data, **kwargs): # pylint: disable=arguments-differ\n+ \"\"\"Generate a new graph using a dictionary.\n+\n+ Args:\n+ data (dict): A dictionary of dictionaries adjacency representation.\n+ kwargs (dict[str, object]): Depending on the resource they may\n+ require different sets of arguments to be able to run a raw\n+ API request.\n+\n+ Raises:\n+ ValueError: If the import is not successful.\n+ \"\"\"\n+ super().from_manual(**kwargs)\n+ if not isinstance(data, dict):\n+ raise ValueError('Data needs to be a dict of dictionaries')\n+\n+ try:\n+ graph = nx.from_dict_of_dicts(data)\n+ except AttributeError as exc:\n+ raise ValueError('Unable to generate a graph') from exc\n+\n+ self.from_graph(graph)\n+\n+ def from_plugin(self, plugin_name, plugin_config=None, refresh=False):\n+ \"\"\"Initialize the graph from a cached plugin graph.\n+\n+ Args:\n+ plugin_name (str): the name of the graph plugin to use.\n+ plugin_config (dict): optional dictionary to configure the plugin.\n+ refresh (bool): optional bool that if set refreshes the graph,\n+ otherwise the graph is pulled from the cache, if it exists.\n+ Defaults to False, meaning it pulls from the cache if it\n+ exists.\n+\n+ Raises:\n+ ValueError: If the plugin doesn't exist or some issues came up\n+ during processing.\n+ \"\"\"\n+ plugin_names = [x.get('name', '') for x in self.plugins]\n+ if plugin_name.lower() not in plugin_names:\n+ raise ValueError(\n+ f'Plugin [{plugin_name}] not part of the supported plugins.')\n+\n+ if plugin_config and not isinstance(plugin_config, dict):\n+ raise ValueError('Plugin config needs to be a dict.')\n+\n+ resource_url = f'{self.api.api_root}/sketches/{self._sketch.id}/graph/'\n+ data = {\n+ 'plugin': plugin_name,\n+ 'config': plugin_config,\n+ 'refresh': bool(refresh),\n+ }\n+ if plugin_config:\n+ if isinstance(plugin_config, str):\n+ self._graph_config = json.loads(plugin_config)\n+ else:\n+ self._graph_config = plugin_config\n+\n+ response = self.api.session.post(resource_url, json=data)\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ error.error_message(\n+ response, 'Unable to retrieve cached graph', error=RuntimeError)\n+\n+ response_json = error.get_response_json(response, logger)\n+ cache_dict = response_json.get('objects', [{}])[0]\n+ self._parse_graph_dict(cache_dict)\n+ self._description = f'Graph created from the {plugin_name} plugin.'\n+\n+ def from_saved(self, graph_id): # pylint: disable=arguments-differ\n+ \"\"\"Initialize the graph object from a saved graph.\n+\n+ Args:\n+ graph_id: integer value for the saved graph (primary key).\n+\n+ Raises:\n+ ValueError: If issues came up during processing.\n+ \"\"\"\n+ resource_id = f'sketches/{self._sketch.id}/graphs/{graph_id}/'\n+ data = self.api.fetch_resource_data(resource_id)\n+\n+ objects = data.get('objects')\n+ if not objects:\n+ logger.warning(\n+ 'Unable to load saved graph with ID: %d, '\n+ 'are you sure it exists?', graph_id)\n+ graph_dict = objects[0]\n+ self._parse_graph_dict(graph_dict)\n+\n+ self._resource_id = graph_id\n+ self._name = graph_dict.get('name', 'No name')\n+ self._description = graph_dict.get('description', '')\n+ self._username = graph_dict.get('user', {}).get('username', 'System')\n+ self._created_at = dateutil.parser.parse(\n+ graph_dict.get('created_at', ''))\n+ self._updated_at = dateutil.parser.parse(\n+ graph_dict.get('updated_at', ''))\n+\n+ @property\n+ def layout(self):\n+ \"\"\"Property that returns back the layout of the graph.\"\"\"\n+ if self._layout:\n+ return self._layout\n+\n+ layout = self._GRAPH_LAYOUTS.get('spring')\n+ self._layout = layout(self.graph)\n+ return self._layout\n+\n+ @layout.setter\n+ def layout(self, layout):\n+ \"\"\"Change the layout manually.\"\"\"\n+ if not isinstance(layout, dict):\n+ raise ValueError('Layout needs to be a dict.')\n+ self._layout = layout\n+\n+ @property\n+ def layout_strings(self):\n+ \"\"\"Property that returns a list of potential layouts to use.\"\"\"\n+ return list(self._GRAPH_LAYOUTS.keys())\n+\n+ @property\n+ def name(self):\n+ \"\"\"Property that returns the query name.\"\"\"\n+ return self._name\n+\n+ @name.setter\n+ def name(self, name):\n+ \"\"\"Make changes to the saved search name.\"\"\"\n+ self._name = name\n+ self.commit()\n+\n+ @property\n+ def plugins(self):\n+ \"\"\"Property that returns back the supported plugins.\"\"\"\n+ plugin_dict = self.api.fetch_resource_data('graphs/')\n+ return plugin_dict\n+\n+ @property\n+ def plugins_table(self):\n+ \"\"\"Property that returns a dataframe with the available plugins.\"\"\"\n+ return pandas.DataFrame(self.plugins)\n+\n+ def save(self):\n+ \"\"\"Save the search in the database.\n+\n+ Raises:\n+ ValueError: if there are values missing in order to save the query.\n+ \"\"\"\n+ if not self.name:\n+ raise ValueError(\n+ 'No name for the graph. Please select a name first.')\n+\n+ if not self.description:\n+ logger.warning(\n+ 'No description selected for graph, saving without one')\n+\n+ if self._resource_id:\n+ resource_url = (\n+ f'{self.api.api_root}/sketches/{self._sketch.id}/graphs/'\n+ f'{self._resource_id}/')\n+ else:\n+ resource_url = (\n+ f'{self.api.api_root}/sketches/{self._sketch.id}/graphs/')\n+\n+ cytoscape_json = nx.readwrite.json_graph.cytoscape_data(self.graph)\n+ elements = cytoscape_json.get('elements', [])\n+ element_list = []\n+ for group in elements:\n+ for element in elements[group]:\n+ element['group'] = group\n+ element_list.append(element)\n+\n+ data = {\n+ 'name': self.name,\n+ 'graph_config': self._serialize(self.graph_config),\n+ 'description': self.description,\n+ 'elements': element_list,\n+ }\n+\n+ response = self.api.session.post(resource_url, json=data)\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ error.error_message(\n+ response, 'Unable to save search', error=RuntimeError)\n+\n+ response_json = error.get_response_json(response, logger)\n+\n+ graph_dict = response_json.get('objects', [{}])[0]\n+ self._resource_id = graph_dict.get('id', 0)\n+ return f'Saved graph to ID: {self._resource_id}'\n+\n+ def set_layout_type(self, layout_string):\n+ \"\"\"Use a layout from the layout strings.\"\"\"\n+ layout = self._GRAPH_LAYOUTS.get(layout_string)\n+ if layout:\n+ self.layout = layout(self.graph)\n+\n+ def to_dict(self):\n+ \"\"\"Returns a dict with the graph content.\"\"\"\n+ return self.resource_data\n+\n+ def to_pandas(self):\n+ \"\"\"Returns a pandas dataframe with the graph content.\"\"\"\n+ if not self.resource_data:\n+ return pandas.DataFrame()\n+\n+ data = self.resource_data\n+ elements = data.get('elements', {})\n+ nodes = elements.get('nodes', [])\n+ edges = elements.get('edges', [])\n+\n+ node_list = [x.get('data') for x in nodes]\n+ edge_list = [x.get('data') for x in edges]\n+ node_df = pandas.DataFrame(node_list)\n+ node_df['type'] = 'node'\n+ edge_df = pandas.DataFrame(edge_list)\n+ edge_df['type'] = 'edge'\n+ return pandas.concat([node_df, edge_df])\n+\n+ @property\n+ def updated_at(self):\n+ \"\"\"Property that returns back the last updated time of a graph.\"\"\"\n+ if self._updated_at:\n+ return self._updated_at.isoformat()\n+ return self._updated_at\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "api_client/python/timesketch_api_client/graph_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+import unittest\n+import mock\n+\n+from . import client\n+from . import graph\n+from . import test_lib\n+\n+\n+class GraphTest(unittest.TestCase):\n+ \"\"\"Test Graph 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_from_manual(self):\n+ \"\"\"Test setting up a graph from manual.\"\"\"\n+ data = {\n+ 0: {\n+ 1: {'weight': 1}\n+ }\n+ }\n+ graph_obj = graph.Graph(self.sketch)\n+ graph_obj.from_manual(data)\n+ self.assertEqual(graph_obj.graph.size(), 1)\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 analyzer\nfrom . import aggregation\nfrom . import definitions\nfrom . import error\n+from . import graph\nfrom . import resource\nfrom . import search\nfrom . import story\n@@ -644,6 +645,30 @@ class Sketch(resource.BaseResource):\naggregations.append(aggregation_obj)\nreturn aggregations\n+ def list_graphs(self):\n+ \"\"\"Returns a list of stored graphs.\"\"\"\n+ if self.is_archived():\n+ raise RuntimeError(\n+ 'Unable to list graphs on an archived sketch.')\n+\n+ resource_uri = (\n+ f'{self.api.api_root}/sketches/{self.id}/graphs/')\n+\n+ response = self.api.session.get(resource_uri)\n+ response_json = error.get_response_json(response, logger)\n+ objects = response_json.get('objects')\n+ if not objects:\n+ logger.warning('No graphs discovered.')\n+ return []\n+\n+ return_list = []\n+ graph_list = objects[0]\n+ for graph_dict in graph_list:\n+ graph_obj = graph.Graph(sketch=self)\n+ graph_obj.from_saved(graph_dict.get('id'))\n+ return_list.append(graph_obj)\n+ return return_list\n+\ndef get_analyzer_status(self, as_sessions=False):\n\"\"\"Returns a list of started analyzers and their status.\n"
},
{
"change_type": "MODIFY",
"old_path": "end_to_end_tests/__init__.py",
"new_path": "end_to_end_tests/__init__.py",
"diff": "\"\"\"End to end test module.\"\"\"\n# Register all tests by importing them.\n+from . import graph_test\nfrom . import query_test\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "end_to_end_tests/graph_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+\"\"\"End to end tests of Timesketch graph functionality.\"\"\"\n+\n+from timesketch_api_client import graph\n+\n+from . import interface\n+from . import manager\n+\n+\n+class GraphTest(interface.BaseEndToEndTest):\n+ \"\"\"End to end tests for query functionality.\"\"\"\n+\n+ NAME = 'graph_test'\n+\n+ def setup(self):\n+ \"\"\"Import test timeline.\"\"\"\n+ self.import_timeline('evtx.plaso')\n+\n+ def test_graph(self):\n+ \"\"\"Test pulling graphs from the backend.\"\"\"\n+ empty_list = self.sketch.list_graphs()\n+\n+ self.assertions.assertEqual(empty_list, [])\n+\n+ graph_obj = graph.Graph(self.sketch)\n+ graph_obj.from_plugin('winservice')\n+ self.assertions.assertEqual(graph_obj.graph.size(), 12)\n+\n+ graph_obj.name = 'foobar'\n+ graph_obj.description = 'this is it'\n+\n+ graph_obj.save()\n+\n+ _ = self.sketch.lazyload_data(refresh_cache=True)\n+ graph_list = self.sketch.list_graphs()\n+ self.assertions.assertEqual(len(graph_list), 1)\n+ graph_saved = graph_list[0]\n+ self.assertions.assertEqual(graph_saved.graph.size(), 12)\n+ self.assertions.assertEqual(graph_saved.name, 'foobar')\n+ self.assertions.assertEqual(graph_saved.description, 'this is it')\n+\n+\n+\n+manager.EndToEndTestManager.register_test(GraphTest)\n"
},
{
"change_type": "MODIFY",
"old_path": "end_to_end_tests/interface.py",
"new_path": "end_to_end_tests/interface.py",
"diff": "@@ -48,6 +48,7 @@ class BaseEndToEndTest(object):\nself.sketch = self.api.create_sketch(name=self.NAME)\nself.assertions = unittest.TestCase()\nself._counter = collections.Counter()\n+ self._imported_files = []\ndef import_timeline(self, filename):\n\"\"\"Import a Plaso, CSV or JSONL file.\n@@ -58,6 +59,8 @@ class BaseEndToEndTest(object):\nRaises:\nTimeoutError if import takes too long.\n\"\"\"\n+ if filename in self._imported_files:\n+ return\nfile_path = os.path.join(TEST_DATA_DIR, filename)\nprint('Importing: {0:s}'.format(file_path))\n@@ -82,6 +85,7 @@ class BaseEndToEndTest(object):\nbreak\nretry_count += 1\ntime.sleep(sleep_time_seconds)\n+ self._imported_files.append(filename)\ndef _get_test_methods(self):\n\"\"\"Inspect class and list all methods that matches the criteria.\n"
},
{
"change_type": "MODIFY",
"old_path": "end_to_end_tests/tools/run_in_container.py",
"new_path": "end_to_end_tests/tools/run_in_container.py",
"diff": "# limitations under the License.\n\"\"\"Script to run all end to end tests.\"\"\"\n+import sys\nimport time\nfrom collections import Counter\n@@ -38,3 +39,6 @@ if __name__ == '__main__':\nsuccessful_tests = counter['tests'] - counter['errors']\nprint('{0:d} total tests: {1:d} successful and {2:d} failed'.format(\ncounter['tests'], successful_tests, counter['errors']))\n+\n+ if counter['errors']:\n+ sys.exit(1)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/__init__.py",
"new_path": "timesketch/api/v1/resources/__init__.py",
"diff": "@@ -161,6 +161,7 @@ class ResourceMixin(object):\n'id': fields.Integer,\n'name': fields.String,\n'user': fields.Nested(user_fields),\n+ 'description': fields.String,\n'created_at': fields.DateTime,\n'updated_at': fields.DateTime\n}\n@@ -168,6 +169,7 @@ class ResourceMixin(object):\ngraphcache_fields = {\n'id': fields.Integer,\n'graph_elements': fields.String,\n+ 'graph_config': fields.String,\n'created_at': fields.DateTime,\n'updated_at': fields.DateTime\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/graph.py",
"new_path": "timesketch/api/v1/resources/graph.py",
"diff": "@@ -31,9 +31,11 @@ from timesketch.models.sketch import Sketch\nfrom timesketch.models.sketch import Graph\nfrom timesketch.models.sketch import GraphCache\n-from timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n-from timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_CREATED\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_OK\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\nlogger = logging.getLogger('timesketch.graph_api')\n@@ -66,16 +68,34 @@ class GraphListResource(resources.ResourceMixin, Resource):\n'User does not have write access on sketch.')\nform = request.json\n+\nname = form.get('name')\n+ description = form.get('description')\nelements = form.get('elements')\n+ graph_config = form.get('graph_config')\n+\n+ if graph_config:\n+ if isinstance(graph_config, dict):\n+ graph_json = json.dumps(graph_config)\n+ elif isinstance(graph_config, str):\n+ graph_json = graph_config\n+ else:\n+ graph_json = ''\n+ logger.warning(\n+ 'Graph config not of the correct value, not saving.')\n+ else:\n+ graph_json = ''\ngraph = Graph(\nuser=current_user, sketch=sketch, name=str(name),\n+ graph_config=graph_json,\n+ description=description,\ngraph_elements=json.dumps(elements))\n+\ndb_session.add(graph)\ndb_session.commit()\n- return self.to_json(graph)\n+ return self.to_json(graph, status_code=HTTP_STATUS_CODE_CREATED)\nclass GraphResource(resources.ResourceMixin, Resource):\n@@ -134,9 +154,100 @@ class GraphResource(resources.ResourceMixin, Resource):\nresponse = self.to_json(graph).json\nresponse['objects'][0]['graph_elements'] = formatted_graph\n+ response['objects'][0]['graph_config'] = graph.graph_config\nreturn jsonify(response)\n+ @login_required\n+ def post(self, sketch_id, graph_id):\n+ \"\"\"Handles GET request to the resource.\n+\n+ Returns:\n+ List of graphs in JSON (instance of flask.wrappers.Response)\n+ \"\"\"\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ if not sketch:\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'write'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have write access controls on sketch.')\n+\n+ graph = Graph.query.get(graph_id)\n+ if not graph:\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, 'No graph found with this ID.')\n+\n+ if not sketch.id == graph.sketch.id:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Graph does not belong to this sketch.')\n+\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ name = form.get('name')\n+ if name:\n+ graph.name = name\n+\n+ description = form.get('description')\n+ if description:\n+ graph.description = description\n+\n+ elements = form.get('elements')\n+ if elements:\n+ graph.graph_elements = json.dumps(elements)\n+\n+ graph_config = form.get('graph_config')\n+ graph_json = ''\n+ if graph_config:\n+ if isinstance(graph_config, dict):\n+ graph_json = json.dumps(graph_config)\n+ elif isinstance(graph_config, str):\n+ graph_json = graph_config\n+ if graph_json:\n+ graph.graph_config = graph_json\n+\n+ db_session.add(graph)\n+ db_session.commit()\n+\n+ return self.to_json(graph, status_code=HTTP_STATUS_CODE_CREATED)\n+\n+ @login_required\n+ def delete(self, sketch_id, graph_id):\n+ \"\"\"Handles DELETE request to the resource.\n+\n+ Args:\n+ sketch_id: Integer primary key for a sketch database model\n+ graph_id: Integer primary key for a graph database model\n+ \"\"\"\n+ sketch = Sketch.query.get_with_acl(sketch_id)\n+ graph = Graph.query.get(graph_id)\n+\n+ if not graph:\n+ msg = 'No Graph 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 graph belongs to the sketch\n+ if graph.sketch.id != sketch.id:\n+ msg = (\n+ f'The sketch ID ({sketch.id}) does not match with the story'\n+ f'sketch ID ({graph.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.graphs.remove(graph)\n+ db_session.commit()\n+ return HTTP_STATUS_CODE_OK\n+\nclass GraphPluginListResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to get all graph plugins.\"\"\"\n@@ -188,12 +299,17 @@ class GraphCacheResource(resources.ResourceMixin, Resource):\ncache = GraphCache.get_or_create(\nsketch=sketch, graph_plugin=plugin_name)\n+ if graph_config:\n+ cache_config = graph_config\n+ else:\n+ cache_config = cache.graph_config\n+\n+ if isinstance(cache_config, str):\n+ cache_config = json.loads(cache_config)\n+\n# Refresh cache if timelines have been added/removed from the sketch.\n- if cache.graph_config:\n- cache_graph_config = json.loads(cache.graph_config)\n- if cache_graph_config:\n- cache_graph_config = json.loads(cache.graph_config)\n- cache_graph_filter = cache_graph_config.get('filter', {})\n+ if cache_config:\n+ cache_graph_filter = cache_config.get('filter', {})\ncache_filter_indices = cache_graph_filter.get('indices', [])\nif set(sketch_indices) ^ set(cache_filter_indices):\nrefresh = True\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added API client support for graphs. (#1522) |
263,096 | 15.12.2020 21:38:22 | -3,600 | 956a6d0f1db9730baeb58a54abe88605fc26f986 | Improve evtx mapping | [
{
"change_type": "MODIFY",
"old_path": "data/sigma_config.yaml",
"new_path": "data/sigma_config.yaml",
"diff": "@@ -60,6 +60,11 @@ logsources:\nsource_name:\n- \"Microsoft-Windows-Security-Auditing\"\n- \"Microsoft-Windows-Eventlog\"\n+ service_windows_system:\n+ service: system\n+ conditions:\n+ source_name:\n+ - \"Microsoft-Windows-Eventlog\"\npowershell:\nservice: powershell\nconditions:\n@@ -79,4 +84,54 @@ fieldmappings:\nService: xml_string\nMessage: xml_string\nkeywords: xml_string # that might be wrong, only introduced during powershell stuff\n-\n+ Source: message\n+ LogonType: xml_string\n+ LogonProcessName: xml_string\n+ LogonGuid: xml_string\n+ SubjectDomainName: xml_string\n+ SubjectUserName: xml_string\n+ TargetUserSid: xml_string\n+ TargetUserName: xml_String\n+ TargetDomainName: xml_string\n+ TargetLogonId: xml_string\n+ AuthenticationPackageName: xml_string\n+ WorkstationName: xml_string\n+ LogonGuid: xml_string\n+ TransmittedServices: xml_string\n+ ProcessId: xml_string\n+ IpAddress: xml_string\n+ IpPort: xml_String #not sure if that mapping is used somewhere else\n+ SourceNetworkAddress: xml_string\n+ TargetOutboundUserName: xml_string\n+ TargetOutboundDomainName: xml_string\n+ Level: xml_string # this might also cause conflicts.\n+ ServiceFileName: xml_string\n+ ObjectValueName: xml_string\n+ DestPort: xml_string\n+ LayerRTID: xml_string\n+ AccessMask: xml_string\n+ ShareName: xml_string\n+ RelativeTargetName: xml_string\n+ AccountName: xml_string\n+ PrivilegeList: xml_string\n+ SubjectLogonId: xml_string\n+ CallingProcessName: xml_string\n+ SAMAccountName: xml_string\n+ ObjectServer: xml_string\n+ Properties: xml_string\n+ HiveName: xml_string\n+ AttributeLDAPDisplayName: xml_string\n+ GroupName: xml_string\n+ UserName: xml_string\n+ DeviceDescription: xml_string\n+ DeviceClassName: xml_string\n+ TicketOptions: xml_string\n+ TicketEncryptionType: xml_string\n+ Properties: xml_string\n+ SourceWorkstation: xml_string\n+ DestinationAddress: xml_string\n+ DestinationPort: xml_string\n+ SourceAddress: xml_string\n+ Keywords: xml_string\n+ LDAPDisplayName: xml_string\n+ AuditPolicyChanges: xml_string\n"
}
] | Python | Apache License 2.0 | google/timesketch | Improve evtx mapping (#1529)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,155 | 16.12.2020 07:49:04 | 0 | 1d6fbc9ec64023d1b4a6e38ec221aeef3e5c5078 | Add a Date sorting function in the AnalyzerHistory component | [
{
"change_type": "MODIFY",
"old_path": "timesketch/frontend/src/components/Sketch/AnalyzerHistory.vue",
"new_path": "timesketch/frontend/src/components/Sketch/AnalyzerHistory.vue",
"diff": "@@ -39,7 +39,7 @@ limitations under the License.\nicon-prev=\"chevron-left\"\nicon-next=\"chevron-right\"\ndefault-sort=\"created_at\">\n- <b-table-column field=\"created_at\" label=\"Date\" width=\"150\" sortable v-slot=\"props\">\n+ <b-table-column field=\"created_at\" label=\"Date\" width=\"150\" sortable custom-sort=\"dateSort\" v-slot=\"props\">\n{{ new Date(props.row.created_at) | moment(\"YYYY-MM-DD HH:mm\") }}\n</b-table-column>\n@@ -79,6 +79,11 @@ export default {\nreturn this.$store.state.sketch\n}\n},\n+ methods: {\n+ dateSort(a, b, key) {\n+ return a[key] - b[key];\n+ },\n+ },\ncreated() {\nApiClient.getSketchTimelineAnalysis(this.sketch.id, this.timeline.id).then((response) => {\nthis.analyses = response.data.objects[0]\n"
}
] | Python | Apache License 2.0 | google/timesketch | Add a Date sorting function in the AnalyzerHistory component (#1525) |
263,178 | 29.12.2020 13:44:12 | -3,600 | 7e204e05cdcb6db1748b21f82a9b3252eb72fc2d | Changes to dpkg configuration for Ubuntu 20.04 | [
{
"change_type": "MODIFY",
"old_path": "config/dpkg/control",
"new_path": "config/dpkg/control",
"diff": "@@ -27,7 +27,7 @@ Description: Python 3 module of Timesketch\nPackage: timesketch-server\nArchitecture: all\n-Depends: apt-transport-https, gunicorn3, python3-psycopg2, python3-timesketch (>= ${binary:Version}), ${python3:Depends}, ${misc:Depends}\n+Depends: apt-transport-https, gunicorn, python3-psycopg2, python3-timesketch (>= ${binary:Version}), ${python3:Depends}, ${misc:Depends}\nRecommends: elasticsearch, openjdk-8-jre-headless, postgresql, redis-server\nDescription: Timesketch server\nTimesketch is a web based tool for collaborative forensic\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changes to dpkg configuration for Ubuntu 20.04 (#1545) |
263,166 | 06.01.2021 16:07:18 | -3,600 | 8666b8e8f326b64b2516eda8a4067da71b913ce8 | Removed requirements of delete permissions to remove labels on a timeline | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -267,12 +267,6 @@ class TimelineResource(resources.ResourceMixin, Resource):\nself._add_label(timeline=timeline, label=label))\nchanged = any(changes)\nelif label_action == 'remove':\n- if not sketch.has_permission(\n- user=current_user, permission='delete'):\n- abort(\n- HTTP_STATUS_CODE_FORBIDDEN,\n- 'The user does not have delete permission on sketch.')\n-\nchanges = []\nfor label in labels:\nchanges.append(\n"
}
] | Python | Apache License 2.0 | google/timesketch | Removed requirements of delete permissions to remove labels on a timeline (#1544) |
263,178 | 07.01.2021 00:39:37 | -3,600 | a63f5d3dcd04cebde05035fd73e7f9effc310d4d | Changes to dpkg configuration for release | [
{
"change_type": "MODIFY",
"old_path": "config/dpkg/changelog",
"new_path": "config/dpkg/changelog",
"diff": "-timesketch (20201120-1) unstable; urgency=low\n+timesketch (20201229-1) unstable; urgency=low\n* Auto-generated\n- -- Timesketch development team <timesketch-dev@googlegroups.com> Fri, 20 Nov 2020 11:37:39 +0100\n+ -- Timesketch development team <timesketch-dev@googlegroups.com> Tue, 29 Dec 2020 23:31:21 +0100\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changes to dpkg configuration for release (#1546)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,133 | 07.01.2021 11:29:08 | 0 | 681d403278b46b587fab017a463194c6235e5495 | minor minor change, sleeping some more | [
{
"change_type": "MODIFY",
"old_path": "end_to_end_tests/interface.py",
"new_path": "end_to_end_tests/interface.py",
"diff": "@@ -87,6 +87,10 @@ class BaseEndToEndTest(object):\nbreak\nretry_count += 1\ntime.sleep(sleep_time_seconds)\n+\n+ # Adding in one more sleep for good measure (preventing flaky tests).\n+ time.sleep(sleep_time_seconds)\n+\nself._imported_files.append(filename)\ndef _get_test_methods(self):\n"
}
] | Python | Apache License 2.0 | google/timesketch | minor minor change, sleeping some more (#1551) |
263,133 | 21.01.2021 23:07:19 | 0 | f454231ccfa5866022df5035e5302c80dba33bcb | Changes to API and API client | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/analyzer.py",
"new_path": "api_client/python/timesketch_api_client/analyzer.py",
"diff": "@@ -38,6 +38,19 @@ class AnalyzerResult(resource.BaseResource):\napi.api_root, sketch_id, timeline_id)\nsuper().__init__(api, resource_uri)\n+ def _get_status_data(self):\n+ \"\"\"Yields a dict for each analyzer status.\"\"\"\n+ data = self._fetch_data()\n+ for entry in data.get('analyzers', []):\n+ yield {\n+ 'log': entry.get('log', 'No recorded logs.'),\n+ 'name': entry.get('name', 'No Name'),\n+ 'results': entry.get('results', ''),\n+ 'status': entry.get('status', 'Unknown'),\n+ 'date': entry.get(\n+ 'status_date', datetime.datetime.utcnow().isoformat()),\n+ }\n+\ndef _fetch_data(self):\n\"\"\"Returns a dict with the analyzer results.\"\"\"\nresponse = self.api.session.get(self.resource_uri)\n@@ -92,9 +105,8 @@ class AnalyzerResult(resource.BaseResource):\n@property\ndef log(self):\n\"\"\"Returns back logs from the analyzer session, if there are any.\"\"\"\n- data = self._fetch_data()\nreturn_strings = []\n- for entry in data.get('analyzers', []):\n+ for entry in self._get_status_data():\nreturn_strings.append(\n'[{0:s}] = {1:s}'.format(\nentry.get('name', 'No Name'),\n@@ -104,9 +116,8 @@ class AnalyzerResult(resource.BaseResource):\n@property\ndef results(self):\n\"\"\"Returns the results from the analyzer session.\"\"\"\n- data = self._fetch_data()\nreturn_strings = []\n- for entry in data.get('analyzers', []):\n+ for entry in self._get_status_data():\nresults = entry.get('results')\nif not results:\nresults = 'No results yet.'\n@@ -115,24 +126,46 @@ class AnalyzerResult(resource.BaseResource):\nentry.get('name', 'No Name'), results))\nreturn '\\n'.join(return_strings)\n+ @property\n+ def results_dict(self):\n+ \"\"\"Returns the results from the analyzer session as a dict.\"\"\"\n+ result_dict = {}\n+ for entry in self._get_status_data():\n+ results = entry.get('results')\n+ if not results:\n+ results = 'No results yet.'\n+ name = entry.get('name', 'No Name')\n+ result_dict.setdefault(name, [])\n+ result_dict[name].append(results)\n+ return result_dict\n+\n@property\ndef status(self):\n\"\"\"Returns the current status of the analyzer run.\"\"\"\n- data = self._fetch_data()\nreturn_strings = []\n- for entry in data.get('analyzers', []):\n+ for entry in self._get_status_data():\nreturn_strings.append(\n'[{0:s}] = {1:s}'.format(\nentry.get('name', 'No Name'),\nentry.get('status', 'Unknown.')))\nreturn '\\n'.join(return_strings)\n+ @property\n+ def status_dict(self):\n+ \"\"\"Returns the current status of the analyzers run as a dict.\"\"\"\n+ return_dict = {}\n+ for entry in self._get_status_data():\n+ name = entry.get('name', 'No Name')\n+\n+ return_dict.setdefault(name, [])\n+ return_dict[name].append(entry.get('status', 'Unknown'))\n+ return return_dict\n+\n@property\ndef status_string(self):\n\"\"\"Returns a longer version of a status string.\"\"\"\n- data = self._fetch_data()\nreturn_strings = []\n- for entry in data.get('analyzers', []):\n+ for entry in self._get_status_data():\nreturn_strings.append(\n'{0:s} - {1:s}: {2:s}'.format(\nentry.get('name', 'No Name'),\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/search.py",
"new_path": "api_client/python/timesketch_api_client/search.py",
"diff": "@@ -385,6 +385,7 @@ class Search(resource.SketchResource):\nself._chips = []\nself._created_at = ''\nself._description = ''\n+ self._indices = '_all'\nself._max_entries = self.DEFAULT_SIZE_LIMIT\nself._name = ''\nself._query_dsl = ''\n@@ -673,6 +674,49 @@ class Search(resource.SketchResource):\nself.resource_data = data\n+ @property\n+ def indices(self):\n+ \"\"\"Return the current set of indices used in the search.\"\"\"\n+ return self._indices\n+\n+ @indices.setter\n+ def indices(self, indices):\n+ \"\"\"Make changes to the current set of indices.\"\"\"\n+ if not isinstance(indices, list):\n+ logger.warning(\n+ 'Indices needs to be a list of strings (indices that were '\n+ 'passed in were not a list).')\n+ return\n+ if not all([isinstance(x, str) for x in indices]):\n+ logger.warning(\n+ 'Indices needs to be a list of strings, not all entries '\n+ 'in the indices list are strings.')\n+ return\n+\n+ # Indices here can be either a list of timeline names or a list of\n+ # search indices. We need to verify that these exist before saving\n+ # them.\n+ timelines = {\n+ t.index_name: t.name for t in self._sketch.list_timelines()}\n+\n+ new_indices = []\n+ for index in indices:\n+ if index in timelines:\n+ new_indices.append(index)\n+ continue\n+\n+ if index in timelines.values():\n+ for index_name, timeline_name in timelines.items():\n+ if timeline_name == index:\n+ new_indices.append(index_name)\n+ break\n+\n+ if not new_indices:\n+ logger.warning('No valid indices found, not changin the value.')\n+ return\n+\n+ self._indices = new_indices\n+\n@property\ndef max_entries(self):\n\"\"\"Return the maximum number of entries in the return value.\"\"\"\n@@ -738,12 +782,14 @@ class Search(resource.SketchResource):\n'time_end': None,\n'size': self.DEFAULT_SIZE_LIMIT,\n'terminate_after': self.DEFAULT_SIZE_LIMIT,\n- 'indices': '_all',\n+ 'indices': self.indices,\n'order': 'asc',\n'chips': [],\n}\n+\nquery_filter = self._query_filter\nquery_filter['chips'] = [x.chip for x in self._chips]\n+ query_filter['indices'] = self.indices\nreturn query_filter\n@query_filter.setter\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/timeline.py",
"new_path": "api_client/python/timesketch_api_client/timeline.py",
"diff": "\"\"\"Timesketch API client library.\"\"\"\nfrom __future__ import unicode_literals\n-import fnmatch\nimport json\nimport logging\n@@ -169,7 +168,7 @@ class Timeline(resource.BaseResource):\n\"\"\"Run an analyzer on a timeline.\nArgs:\n- analyzer_name: the name of the analyzer class to run against the\n+ analyzer_name: a name of an analyzer class to run against the\ntimeline.\nanalyzer_kwargs: optional dict with parameters for the analyzer.\nThis is optional and just for those analyzers that can accept\n@@ -189,40 +188,80 @@ class Timeline(resource.BaseResource):\nraise error.UnableToRunAnalyzer(\n'Unable to run an analyzer on an archived timeline.')\n- resource_url = '{0:s}/sketches/{1:d}/analyzer/'.format(\n- self.api.api_root, self._sketch_id)\n-\n- # The analyzer_kwargs is expected to be a dict with the key\n- # being the analyzer name, and the value being the key/value dict\n- # with parameters for the analyzer.\nif analyzer_kwargs:\nif not isinstance(analyzer_kwargs, dict):\nraise error.UnableToRunAnalyzer(\n'Unable to run analyzer, analyzer kwargs needs to be a '\n'dict')\n+\nif analyzer_name not in analyzer_kwargs:\nanalyzer_kwargs = {analyzer_name: analyzer_kwargs}\n+ elif not isinstance(analyzer_kwargs[analyzer_name], dict):\n+ raise error.UnableToRunAnalyzer(\n+ 'Unable to run analyzer, analyzer kwargs needs to be a '\n+ 'dict where the value for the analyzer is also a dict.')\n+\n+ return self.run_analyzers(\n+ analyzer_names=[analyzer_name], analyzer_kwargs=analyzer_kwargs,\n+ ignore_previous=ignore_previous)\n+\n+\n+ def run_analyzers(\n+ self, analyzer_names, analyzer_kwargs=None, ignore_previous=False):\n+ \"\"\"Run an analyzer on a timeline.\n+\n+ Args:\n+ analyzer_names: a list of analyzer class names to run against the\n+ timeline.\n+ analyzer_kwargs: optional dict with parameters for the analyzer.\n+ This is optional and just for those analyzers that can accept\n+ further parameters. It is expected that this is a dict with\n+ the key value being the analyzer name, and the value being\n+ another key/value dict with the parameters for that analyzer.\n+ ignore_previous (bool): an optional bool, if set to True then\n+ analyzer is run irrelevant on whether it has been previously\n+ been run.\n+\n+ Raises:\n+ error.UnableToRunAnalyzer: if not able to run the analyzer.\n+\n+ Returns:\n+ If the analyzer runs successfully return back an AnalyzerResult\n+ object.\n+ \"\"\"\n+ if self.is_archived():\n+ raise error.UnableToRunAnalyzer(\n+ 'Unable to run an analyzer on an archived timeline.')\n+\n+ resource_url = '{0:s}/sketches/{1:d}/analyzer/'.format(\n+ self.api.api_root, self._sketch_id)\nif not ignore_previous:\n+ all_names = {x.lower() for x in analyzer_names}\n+ done_names = set()\n+\nresponse = self.api.fetch_resource_data(\nf'sketches/{self._sketch_id}/timelines/{self.id}/analysis/')\nanalyzer_data = response.get('objects', [[]])\n- stop_running = False\n+\n+ if analyzer_data:\nfor result in analyzer_data[0]:\nresult_analyzer = result.get('analyzer_name', 'N/A')\n- if fnmatch.fnmatch(result_analyzer, analyzer_name):\n+ done_names.add(result_analyzer.lower())\n+\n+ analyzer_names = list(all_names.difference(done_names))\n+ for name in all_names.intersection(done_names):\nlogger.error(\n- 'Analyzer {0:s} has already been run on the timeline, '\n+ f'Analyzer {0:s} has already been run on the timeline, '\n'use \"ignore_previous=True\" to overwrite'.format(\n- result_analyzer))\n- stop_running = True\n+ name))\n- if stop_running:\n+ if not analyzer_names:\nreturn None\ndata = {\n'timeline_id': self.id,\n- 'analyzer_names': [analyzer_name],\n+ 'analyzer_names': analyzer_names,\n'analyzer_kwargs': analyzer_kwargs,\n}\nresponse = self.api.session.post(resource_url, json=data)\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210106'\n+__version__ = '20210120'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/docker-entrypoint.sh",
"new_path": "docker/dev/build/docker-entrypoint.sh",
"diff": "@@ -13,7 +13,8 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/tags.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\nln -s /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/sigma_config.yaml\n- ln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/sigma/\n+ mkdir /etc/timesketch/data\n+ ln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/data/sigma/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\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": "@@ -554,7 +554,7 @@ class ImportStreamer(object):\ntry:\njson_obj = json.loads(json_entry)\nexcept json.JSONDecodeError as e:\n- raise TypeError('Data not as JSON, error: {0!s}'.format(e))\n+ raise TypeError('Data not as JSON, error: {0!s}'.format(e)) from e\njson_dict = {}\nif isinstance(json_obj, (list, tuple)):\n@@ -673,6 +673,10 @@ class ImportStreamer(object):\n@property\ndef timeline(self):\n\"\"\"Returns a timeline object.\"\"\"\n+ if not self._timeline_id:\n+ logger.warning('No timeline ID has been stored as of yet.')\n+ return None\n+\ntimeline_obj = timeline.Timeline(\ntimeline_id=self._timeline_id,\nsketch_id=self._sketch.id,\n"
},
{
"change_type": "MODIFY",
"old_path": "importer_client/python/timesketch_import_client/version.py",
"new_path": "importer_client/python/timesketch_import_client/version.py",
"diff": "# limitations under the License.\n\"\"\"Version information for Timesketch Import Client.\"\"\"\n-__version__ = '20201206'\n+__version__ = '20210120'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "requirements.txt",
"new_path": "requirements.txt",
"diff": "@@ -22,7 +22,7 @@ PyJWT==1.7.1\npython_dateutil==2.8.1\nPyYAML==5.3\nredis==3.3.11\n-requests==2.23.0\n+requests==2.25.0\nsigmatools==0.14 ; python_version > '3.4'\nsix==1.12.0\nSQLAlchemy==1.3.12\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/aggregation.py",
"new_path": "timesketch/api/v1/resources/aggregation.py",
"diff": "import json\nimport time\n+from elasticsearch.exceptions import NotFoundError\n+\nfrom flask import jsonify\nfrom flask import request\nfrom flask import abort\n@@ -482,7 +484,14 @@ class AggregationExploreResource(resources.ResourceMixin, Resource):\nchart_title = aggregator_parameters.pop(\n'chart_title', aggregator.chart_title)\ntime_before = time.time()\n+ try:\nresult_obj = aggregator.run(**aggregator_parameters)\n+ except NotFoundError:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'Attempting to run an aggregation on a non-existing '\n+ 'Elastic index, index: {0:s} and parameters: {1!s}'.format(\n+ index, aggregator_parameters))\ntime_after = time.time()\naggregator_description = aggregator.describe\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -184,12 +184,18 @@ class TimelineResource(resources.ResourceMixin, Resource):\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n- timeline = Timeline.query.get(timeline_id)\n+ timeline = Timeline.query.get(timeline_id)\nif not timeline:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No Timeline found with this ID.')\n+ if not timeline.sketch_id:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ f'The timeline {timeline_id} does not have an associated '\n+ 'sketch, does it belong to a sketch?')\n+\n# Check that this timeline belongs to the sketch\nif timeline.sketch_id != sketch.id:\nabort(\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/interface.py",
"new_path": "timesketch/lib/analyzers/interface.py",
"diff": "@@ -49,6 +49,20 @@ def _flush_datastore_decorator(func):\n\"\"\"Decorator that flushes the bulk insert queue in the datastore.\"\"\"\ndef wrapper(self, *args, **kwargs):\nfunc_return = func(self, *args, **kwargs)\n+\n+ # Add in tagged events and emojis.\n+ for event_dict in self.tagged_events.values():\n+ event = event_dict.get('event')\n+ tags = event_dict.get('tags')\n+\n+ event.commit({'tag': tags})\n+\n+ for event_dict in self.emoji_events.values():\n+ event = event_dict.get('event')\n+ emojis = event_dict.get('emojis')\n+\n+ event.commit({'__ts_emojis': emojis})\n+\nself.datastore.flush_queued_events()\nreturn func_return\nreturn wrapper\n@@ -113,17 +127,19 @@ class Event(object):\nindex_name: The name of the Elasticsearch index.\nsource: Source document from Elasticsearch.\n\"\"\"\n- def __init__(self, event, datastore, sketch=None):\n+ def __init__(self, event, datastore, sketch=None, analyzer=None):\n\"\"\"Initialize Event object.\nArgs:\nevent: Dictionary of event from Elasticsearch.\ndatastore: Instance of ElasticsearchDatastore.\nsketch: Optional instance of a Sketch object.\n+ analyzer: Optional instance of a BaseIndexAnalyzer object.\nRaises:\nKeyError if event dictionary is missing mandatory fields.\n\"\"\"\n+ self._analyzer = analyzer\nself.datastore = datastore\nself.sketch = sketch\n@@ -162,7 +178,7 @@ class Event(object):\nself.datastore.import_event(\nself.index_name, self.event_type, event_id=self.event_id,\n- event=event_to_commit, flush_interval=1)\n+ event=event_to_commit)\nself.updated_event = {}\ndef add_attributes(self, attributes):\n@@ -201,7 +217,18 @@ class Event(object):\nreturn\nexisting_tags = self.source.get('tag', [])\n+ if self._analyzer:\n+ if self.event_id in self._analyzer.tagged_events:\n+ existing_tags = self._analyzer.tagged_events[\n+ self.event_id].get('tags')\n+ else:\n+ self._analyzer.tagged_events[self.event_id] = {\n+ 'event': self, 'tags': existing_tags}\n+\nnew_tags = list(set().union(existing_tags, tags))\n+ if self._analyzer:\n+ self._analyzer.tagged_events[self.event_id]['tags'] = new_tags\n+ else:\nupdated_event_attribute = {'tag': new_tags}\nself._update(updated_event_attribute)\n@@ -217,7 +244,21 @@ class Event(object):\nexisting_emoji_list = self.source.get('__ts_emojis', [])\nif not isinstance(existing_emoji_list, (list, tuple)):\nexisting_emoji_list = []\n+\n+ if self._analyzer:\n+ if self.event_id in self._analyzer.emoji_events:\n+ existing_emoji_list = self._analyzer.emoji_events[\n+ self.event_id].get('emojis')\n+ else:\n+ self._analyzer.emoji_events[self.event_id] = {\n+ 'event': self, 'emojis': existing_emoji_list}\n+\nnew_emoji_list = list(set().union(existing_emoji_list, emojis))\n+\n+ if self._analyzer:\n+ self._analyzer.emoji_events[\n+ self.event_id]['emojis'] = new_emoji_list\n+ else:\nupdated_event_attribute = {'__ts_emojis': new_emoji_list}\nself._update(updated_event_attribute)\n@@ -716,6 +757,8 @@ class BaseIndexAnalyzer(object):\nindex_name: Name if Elasticsearch index.\ndatastore: Elasticsearch datastore client.\nsketch: Instance of Sketch object.\n+ tagged_events: Dict with all events to add tags and those tags.\n+ emoji_events: Dict with all events to add emojis and those emojis.\n\"\"\"\nNAME = 'name'\n@@ -743,6 +786,10 @@ class BaseIndexAnalyzer(object):\nself.name = self.NAME\nself.index_name = index_name\nself.timeline_name = ''\n+\n+ self.tagged_events = {}\n+ self.emoji_events = {}\n+\nself.datastore = ElasticsearchDataStore(\nhost=current_app.config['ELASTIC_HOST'],\nport=current_app.config['ELASTIC_PORT'])\n@@ -801,7 +848,8 @@ class BaseIndexAnalyzer(object):\nenable_scroll=scroll,\n)\nfor event in event_generator:\n- yield Event(event, self.datastore, sketch=self.sketch)\n+ yield Event(\n+ event, self.datastore, sketch=self.sketch, analyzer=self)\n@_flush_datastore_decorator\ndef run_wrapper(self, analysis_id):\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/win_evtxgap.py",
"new_path": "timesketch/lib/analyzers/win_evtxgap.py",
"diff": "@@ -63,7 +63,7 @@ class EvtxGapPlugin(interface.BaseSketchAnalyzer):\nsketch_id: Sketch ID\n\"\"\"\nself.index_name = index_name\n- super(EvtxGapPlugin, self).__init__(index_name, sketch_id)\n+ super().__init__(index_name, sketch_id)\ndef run(self):\n\"\"\"Entry point for the analyzer.\n@@ -107,13 +107,22 @@ class EvtxGapPlugin(interface.BaseSketchAnalyzer):\nif len(missing_records) > len(all_numbers) / 2:\n# Let's rather calculate the ranges of records instead of\n# missing records.\n+ if record_numbers:\nrecord_ranges = list(get_range(\n- sorted(list(record_numbers)), sorted(list(all_numbers))))\n+ sorted(list(record_numbers)),\n+ sorted(list(all_numbers))))\n+ else:\n+ record_ranges = []\nrecord_gaps[source] = {'included': record_ranges}\nelse:\n- record_gaps[source] = {'missing': list(get_range(\n- sorted(list(missing_records)), sorted(list(all_numbers))))}\n+ if missing_records:\n+ missing_ = list(get_range(\n+ sorted(list(missing_records)),\n+ sorted(list(all_numbers))))\n+ else:\n+ missing_ = []\n+ record_gaps[source] = {'missing': missing_}\n# 2. Find gaps in ranges of days with/without records.\nevent_frame['datetime'] = pd.to_datetime(event_frame.datetime)\n@@ -144,7 +153,10 @@ class EvtxGapPlugin(interface.BaseSketchAnalyzer):\ncurrent_days = [int(day) for day in event_count.day.values]\nmissing_days = list(set(all_days).difference(set(current_days)))\n+ if missing_days:\nmissing_ranges = list(get_range(missing_days, all_days))\n+ else:\n+ missing_ranges = []\nif not (missing_ranges and record_gaps):\nreturn (\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -831,6 +831,7 @@ class ElasticsearchDataStore(object):\nexcept (ConnectionTimeout, socket.timeout):\n# TODO: Add a retry here.\nes_logger.error('Unable to add events', exc_info=True)\n+ return {}\nerrors_in_upload = results.get('errors', False)\nreturn_dict['errors_in_upload'] = errors_in_upload\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -46,8 +46,7 @@ def get_sigma_config_file(config_file=None):\nconfig_file_path = config_file\nelse:\nconfig_file_path = current_app.config.get('SIGMA_CONFIG')\n-\n- if not config_file:\n+ if not config_file_path:\nraise ValueError(\n'SIGMA_CONFIG not found in config file')\n@@ -173,10 +172,9 @@ def get_sigma_rule(filepath, sigma_config=None):\nsigma_conf_obj = sigma_config\nelse:\nsigma_conf_obj = get_sigma_config_file()\n- except ValueError as e:\n+ except ValueError:\nlogger.error(\n- 'Problem reading the Sigma config {0:s}: '\n- .format(e), exc_info=True)\n+ 'Problem reading the Sigma config', exc_info=True)\nreturn None\nsigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_conf_obj, {})\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changes to API and API client (#1562) |
263,130 | 22.01.2021 08:13:52 | -3,600 | 69eee10ab34ecda4fc5f9b76d45a01c6ee9dcc8d | Added new IP address related feature extractors | [
{
"change_type": "MODIFY",
"old_path": "data/features.yaml",
"new_path": "data/features.yaml",
"diff": "@@ -102,3 +102,24 @@ linkedin_accounts:\naggregate: True\ntags: ['linkedin-account']\nemojis: ['ID_BUTTON']\n+\n+rdp_ipv4_addresses:\n+ query_string: 'data_type:\"windows:evtx:record\" AND\n+ source_name:\"Microsoft-Windows-TerminalServices-LocalSessionManager\"'\n+ attribute: 'strings'\n+ store_as: 'ip_address'\n+ re: '((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'\n+\n+ssh_client_ipv4_addresses:\n+ query_string: 'reporter:\"sshd\"'\n+ attribute: 'message'\n+ store_as: 'client_ip'\n+ re: '^\\[sshd\\] \\[\\d+\\]: Connection from ((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\n+ port \\d+ on (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) port \\d+(?: rdomain ? .*)?$'\n+\n+ssh_host_ipv4_addresses:\n+ query_string: 'reporter:\"sshd\"'\n+ attribute: 'message'\n+ store_as: 'host_ip'\n+ re: '^\\[sshd\\] \\[\\d+\\]: Connection from (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\n+ port \\d+ on ((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) port \\d+(?: rdomain ? .*)?$'\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/ssh_sessionizer.py",
"new_path": "timesketch/lib/analyzers/ssh_sessionizer.py",
"diff": "@@ -19,8 +19,10 @@ SSH_PATTERN = re.compile(r'^\\[sshd\\] \\[(?P<process_id>\\d+)\\]:')\n# TODO Change the pattern to be compatible also with IPv6\nSSH_CONNECTION_PATTERN = \\\nre.compile(r'^\\[sshd\\] \\[(?P<process_id>\\d+)\\]: Connection from ' + \\\n- r'(?P<client_ip>(\\d{1,3}\\.){3}\\d{1,3}) port (?P<client_port>\\d+) on ' + \\\n- r'(?P<host_ip>(\\d{1,3}\\.){3}\\d{1,3}) port (?P<host_port>\\d+)' + \\\n+ r'(?P<client_ip>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) ' + \\\n+ r'port (?P<client_port>\\d+) on ' + \\\n+ r'(?P<host_ip>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) ' + \\\n+ r'port (?P<host_port>\\d+)' + \\\nr'( rdomain (?P<rdomain>.*))?$')\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added new IP address related feature extractors (#1563) |
263,106 | 31.01.2021 16:15:43 | -19,080 | c021944e60d98cc984556d996cdd6fa8d0dcfc54 | hypen error in readme | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "4. [Contributing](#contributing)\n## About Timesketch\n-Timesketch is an open source tool for collaborative forensic timeline analysis. Using sketches you and your collaborators can easily organize your timelines and analyze them all at the same time. Add meaning to your raw data with rich annotations, comments, tags and stars.\n+Timesketch is an open-source tool for collaborative forensic timeline analysis. Using sketches you and your collaborators can easily organize your timelines and analyze them all at the same time. Add meaning to your raw data with rich annotations, comments, tags and stars.\n<img src=\"https://01dd8b4c-a-62cb3a1a-s-sites.googlegroups.com/site/timesketchforensics/about/timesketch-201708.png\" alt=\"Timesketch\" width=\"1000\"/>\n"
}
] | Python | Apache License 2.0 | google/timesketch | hypen error in readme (#1572) |
263,133 | 01.02.2021 11:56:34 | 0 | 72e4eeb3594cdff0e1e284bb13942fc7f01ddf89 | Adding datetime limits on the aggregation bucket. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/aggregation.py",
"new_path": "timesketch/api/v1/resources/aggregation.py",
"diff": "@@ -492,6 +492,11 @@ class AggregationExploreResource(resources.ResourceMixin, Resource):\n'Attempting to run an aggregation on a non-existing '\n'Elastic index, index: {0:s} and parameters: {1!s}'.format(\nindex, aggregator_parameters))\n+ except ValueError as exc:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to run the aggregation, with error: {0!s}'.format(\n+ exc))\ntime_after = time.time()\naggregator_description = aggregator.describe\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/aggregators/bucket.py",
"new_path": "timesketch/lib/aggregators/bucket.py",
"diff": "from __future__ import unicode_literals\n+import datetime\n+\nfrom timesketch.lib.aggregators import manager\nfrom timesketch.lib.aggregators import interface\n@@ -45,6 +47,24 @@ class TermsAggregation(interface.BaseAggregator):\n'default_value': '',\n'display': True\n},\n+ {\n+ 'type': 'ts-dynamic-form-datetime-input',\n+ 'name': 'start_time',\n+ 'label': (\n+ 'ISO formatted timestamp for the start time '\n+ 'of the aggregated data'),\n+ 'placeholder': 'Enter a start date for the aggregation',\n+ 'default_value': '',\n+ 'display': True\n+ },\n+ {\n+ 'type': 'ts-dynamic-form-datetime-input',\n+ 'name': 'end_time',\n+ 'label': 'ISO formatted end time for the aggregation',\n+ 'placeholder': 'Enter an end date for the aggregation',\n+ 'default_value': '',\n+ 'display': True\n+ },\n{\n'type': 'ts-dynamic-form-text-input',\n'name': 'limit',\n@@ -65,13 +85,17 @@ class TermsAggregation(interface.BaseAggregator):\n# pylint: disable=arguments-differ\ndef run(\nself, field, limit=10, supported_charts='table',\n- order_field='count'):\n+ start_time='', end_time='', order_field='count'):\n\"\"\"Run the aggregation.\nArgs:\nfield: What field to aggregate on.\nlimit: How many buckets to return.\nsupported_charts: Chart type to render. Defaults to table.\n+ start_time: Optional ISO formatted date string that limits the time\n+ range for the aggregation.\n+ end_time: Optional ISO formatted date string that limits the time\n+ range for the aggregation.\norder_field: The name of the field that is used for the order\nof items in the aggregation, defaults to \"count\".\n@@ -109,6 +133,52 @@ class TermsAggregation(interface.BaseAggregator):\n}\n}\n+ query_filter = None\n+ if start_time:\n+ try:\n+ _ = datetime.datetime.fromisoformat(start_time)\n+ except ValueError:\n+ raise ValueError(\n+ 'Start time is not ISO formatted [{0:s}'.format(\n+ start_time)) from ValueError\n+\n+ if end_time:\n+ try:\n+ _ = datetime.datetime.fromisoformat(end_time)\n+ except ValueError:\n+ raise ValueError(\n+ 'End time is not ISO formatted [{0:s}'.format(\n+ end_time)) from ValueError\n+\n+ if start_time and end_time:\n+ query_filter = {\n+ 'range': {\n+ 'datetime': {\n+ 'gte': start_time,\n+ 'lte': end_time,\n+ }\n+ }\n+ }\n+ elif start_time:\n+ query_filter = {\n+ 'range': {\n+ 'datetime': {\n+ 'gte': start_time,\n+ }\n+ }\n+ }\n+ elif end_time:\n+ query_filter = {\n+ 'range': {\n+ 'datetime': {\n+ 'lte': end_time,\n+ }\n+ }\n+ }\n+\n+ if query_filter:\n+ aggregation_spec['aggs']['my_filter'] = {'filter': query_filter}\n+\nresponse = self.elastic_aggregation(aggregation_spec)\naggregations = response.get('aggregations', {})\naggregation = aggregations.get('aggregation', {})\n"
}
] | Python | Apache License 2.0 | google/timesketch | Adding datetime limits on the aggregation bucket. (#1568) |
263,130 | 03.02.2021 14:20:22 | -3,600 | 2285e1125a82b8a627ed4f9353b7cbb57a1c484c | Small bugfix in SSH features regex | [
{
"change_type": "MODIFY",
"old_path": "data/features.yaml",
"new_path": "data/features.yaml",
"diff": "@@ -121,5 +121,5 @@ ssh_host_ipv4_addresses:\nquery_string: 'reporter:\"sshd\"'\nattribute: 'message'\nstore_as: 'host_ip'\n- re: '^\\[sshd\\] \\[\\d+\\]: Connection from ((?:[0-9]{1,3}\\.){3}[0-9]{1,3})\n- port \\d+ on (?:[0-9]{1,3}\\.){3}[0-9]{1,3} port \\d+(?: rdomain ? .*)?$'\n+ re: '^\\[sshd\\] \\[\\d+\\]: Connection from (?:[0-9]{1,3}\\.){3}[0-9]{1,3}\n+ port \\d+ on ((?:[0-9]{1,3}\\.){3}[0-9]{1,3}) port \\d+(?: rdomain ? .*)?$'\n"
}
] | Python | Apache License 2.0 | google/timesketch | Small bugfix in SSH features regex (#1582) |
263,133 | 08.02.2021 15:13:02 | 0 | 8cdda1a6b8b6edc11c7bba29001b9a083552d98e | Fixed by adding mappings to deployment script. | [
{
"change_type": "MODIFY",
"old_path": "contrib/deploy_timesketch.sh",
"new_path": "contrib/deploy_timesketch.sh",
"diff": "@@ -79,6 +79,7 @@ curl -s $GITHUB_BASE_URL/docker/release/config.env > timesketch/config.env\n# Fetch default Timesketch config files\ncurl -s $GITHUB_BASE_URL/data/timesketch.conf > timesketch/etc/timesketch/timesketch.conf\ncurl -s $GITHUB_BASE_URL/data/tags.yaml > timesketch/etc/timesketch/tags.yaml\n+curl -s $GITHUB_BASE_URL/data/plaso.mappings > timesketch/etc/timesketch/plaso.mappings\ncurl -s $GITHUB_BASE_URL/data/features.yaml > timesketch/etc/timesketch/features.yaml\ncurl -s $GITHUB_BASE_URL/data/sigma_config.yaml > timesketch/etc/timesketch/sigma_config.yaml\ncurl -s $GITHUB_BASE_URL/data/sigma/rules/lnx_susp_zenmap.yml > timesketch/etc/timesketch/sigma/rules/lnx_susp_zenmap.yml\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed #1600 by adding mappings to deployment script. (#1601) |
263,130 | 11.02.2021 16:35:21 | -3,600 | 491d650c5a5d682b112534a91e1e520eff55a05f | Added extractions of IP address from RdpCoreTS event logs into the feature extraction | [
{
"change_type": "MODIFY",
"old_path": "data/features.yaml",
"new_path": "data/features.yaml",
"diff": "@@ -103,13 +103,20 @@ linkedin_accounts:\ntags: ['linkedin-account']\nemojis: ['ID_BUTTON']\n-rdp_ipv4_addresses:\n+rdp_ts_ipv4_addresses:\nquery_string: 'data_type:\"windows:evtx:record\" AND\nsource_name:\"Microsoft-Windows-TerminalServices-LocalSessionManager\"'\nattribute: 'strings'\nstore_as: 'ip_address'\nre: '(?:[0-9]{1,3}\\.){3}[0-9]{1,3}'\n+rdp_rds_ipv4_addresses:\n+ query_string: 'data_type:\"windows:evtx:record\" AND\n+ source_name:\"Microsoft-Windows-RemoteDesktopServices-RdpCoreTS\"'\n+ attribute: 'strings'\n+ store_as: 'client_ip'\n+ re: '(?:[0-9]{1,3}\\.){3}[0-9]{1,3}'\n+\nssh_client_ipv4_addresses:\nquery_string: 'reporter:\"sshd\"'\nattribute: 'message'\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added extractions of IP address from RdpCoreTS event logs into the feature extraction (#1605) |
263,133 | 11.02.2021 17:21:24 | 0 | cbbdfd76e2e5d44c4fd547ea8323eeb2b1fc592c | Upgraded the importer version | [
{
"change_type": "MODIFY",
"old_path": "importer_client/python/timesketch_import_client/version.py",
"new_path": "importer_client/python/timesketch_import_client/version.py",
"diff": "# limitations under the License.\n\"\"\"Version information for Timesketch Import Client.\"\"\"\n-__version__ = '20210120'\n+__version__ = '20210129'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Upgraded the importer version (#1606) |
263,133 | 17.02.2021 09:43:47 | 0 | fea297501bd7a45b3d8309848a4d189a02c41801 | Fixed issues with running analyzers in API client. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/timeline.py",
"new_path": "api_client/python/timesketch_api_client/timeline.py",
"diff": "@@ -251,7 +251,7 @@ class Timeline(resource.BaseResource):\nanalyzer_names = list(all_names.difference(done_names))\nfor name in all_names.intersection(done_names):\nlogger.error(\n- f'Analyzer {0:s} has already been run on the timeline, '\n+ 'Analyzer {0:s} has already been run on the timeline, '\n'use \"ignore_previous=True\" to overwrite'.format(\nname))\n@@ -277,9 +277,13 @@ class Timeline(resource.BaseResource):\n'unable to verify, please verify manually.')\nanalyzer_results = []\n- for session in objects:\n+ for session_dict in objects[0]:\n+ for analysis_dict in session_dict.get('analyses', []):\n+ session_id = analysis_dict.get('analysissession_id')\n+ if not session_id:\n+ continue\nanalyzer_result = analyzer.AnalyzerResult(\n- timeline_id=self.id, session_id=session.id,\n+ timeline_id=self.id, session_id=session_id,\nsketch_id=self._sketch_id, api=self.api)\nanalyzer_results.append(analyzer_result)\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210205'\n+__version__ = '20210217'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed issues with running analyzers in API client. (#1623) |
263,096 | 18.02.2021 14:29:21 | -3,600 | fb1580c9e6f79e399b9e8a7033af8302e9f0a15f | Added concepts and API dev guide to documentations | [
{
"change_type": "MODIFY",
"old_path": "docs/Developers-Guide.md",
"new_path": "docs/Developers-Guide.md",
"diff": "@@ -4,6 +4,17 @@ It is recommended to develop Timesketch using a docker container. Refer to [Dock\nNote: Exclamation mark `!` denotes commands that should run in the docker container shell, dollar sign `$` denotes commands to run in your local shell.\n+#### Locations and concepts\n+\n+* Timesketch provides a webinterface and a REST API\n+* The configurations is located at ```/data``` sourcecode folder\n+* The front end uses ```Vue.js``` framework and is stored at ```/timesketch/frontend```\n+* Code that is used in potentially multiple locations is stored in ```/timesketch/lib```\n+* Analyzers are located at ```/timesketch/lib/analyzers```\n+* The API methods are defined in ```/timesketch/api```\n+* API client code is in ```/api_client/python/timesketch_api_client```\n+* Data models are defined in ```/timesketch/models```\n+\n#### Frontend development\nFirst we need to get an interactive shell to the container to install the frontend modules:\n@@ -57,6 +68,15 @@ And execute the single test\nnosetests timesketch/lib/emojis_test.py -v\n```\n+##### Writing tests\n+It is recommended to write unittests as much as possible.\n+\n+Test files in Timesketch have the naming convention ```_test.py``` and are stored next to the files they test. E.g. a test file for ```/timesketch/lib/emojis.py``` is stored as ```/timesketch/lib/emojis_test.py```\n+\n+The unittests for the api client can use ```mock``` to emulate responses from the server. The mocked answers are written in: ```api_client/python/timesketch_api_client/test_lib.py```.\n+\n+To introduce a new API endpoint to be tested, the endpoint needs to be registered in the ```url_router``` section in ```/api_client/python/timesketch_api_client/test_lib.py``` and the response needs to be defined in the same file.\n+\n#### Building Timesketch frontend\nTo build frontend files and put bundles in `timesketch/static/dist/`, use\n@@ -159,3 +179,28 @@ effect. In the menu select `Kernel | Restart`, now you should be able to go back\ninto the notebook and make use of the latest changes in the API client.\n\n+\n+#### API development\n+\n+Exposing new functionality via the API starts at ```/timesketch/api/v1/routes.py```. In that file the different routes / endpoints are defined that can be used.\n+Typically every route has a dedicated Resource file in ```/timesketch/api/v1/resources```.\n+\n+A resource can have ```GET``` as well as ```POST```or other HTTP methods each defined in the same resource file. A good example of a resource that has a mixture is ```/timesketch/api/v1/resources/archive.py```.\n+\n+To write tests for the resource, add a section in ```/timesketch/api/v1/resources_test.py```\n+\n+##### Error handling\n+\n+It is recommended to expose the error with as much detail as possible to the user / tool that is trying to access the resource.\n+\n+For example the following will give a human readable information as well as a HTTP status code that client code can react on\n+```python\n+if not sketch:\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+```\n+On the opposite side the following is not recommended:\n+```python\n+if not sketch:\n+ abort(HTTP_STATUS_CODE_BAD_REQUEST, 'Error')\n+```\n+\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added concepts and API dev guide to documentations (#1618)
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,096 | 24.02.2021 15:58:51 | -3,600 | 1b5654cd3043bff1abee437802eff164e74d192f | Fixed some spelling mistakes in various files comments | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/client.py",
"new_path": "api_client/python/timesketch_api_client/client.py",
"diff": "@@ -140,7 +140,7 @@ class TimesketchApi:\nself.session = session_object\ndef _authenticate_session(self, session, username, password):\n- \"\"\"Post username/password to authenticate the HTTP seesion.\n+ \"\"\"Post username/password to authenticate the HTTP session.\nArgs:\nsession: Instance of requests.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": "@@ -215,7 +215,7 @@ class ConfigAssistant:\nthe file RC_FILENAME inside the user's home directory.\nsection (str): The configuration section to read from. This\nis optional and defaults to timesketch. This can be\n- useful if you have mutiple Timesketch servers to connect to,\n+ useful if you have multiple Timesketch servers to connect to,\nwith each one of them having a separate section in the config\nfile.\n@@ -293,7 +293,7 @@ class ConfigAssistant:\ndefault location will be used.\nsection (str): The configuration section to write to. This\nis optional and defaults to timesketch. This can be\n- useful if you have mutiple Timesketch servers to connect to,\n+ useful if you have multiple Timesketch servers to connect to,\nwith each one of them having a separate section in the config\nfile.\ntoken_file_path (str): Optional path to the location of the token\n@@ -370,7 +370,7 @@ def get_client(\nnot supplied a default path will be used.\nconfig_section (str): The configuration section to read from. This\nis optional and defaults to timesketch. This can be\n- useful if you have mutiple Timesketch servers to connect to,\n+ useful if you have multiple Timesketch servers to connect to,\nwith each one of them having a separate section in the config\nfile.\ntoken_password (str): an optional password to decrypt\n@@ -438,7 +438,7 @@ def configure_missing_parameters(\nThis defaults to False.\nconfig_section (str): The configuration section to read from. This\nis optional and defaults to timesketch. This can be\n- useful if you have mutiple Timesketch servers to connect to,\n+ useful if you have multiple Timesketch servers to connect to,\nwith each one of them having a separate section in the config\nfile.\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/search.py",
"new_path": "api_client/python/timesketch_api_client/search.py",
"diff": "@@ -28,7 +28,7 @@ logger = logging.getLogger('timesketch_api.search')\nclass Chip:\n\"\"\"Class definition for a query filter chip.\"\"\"\n- # The type of a chip that is defiend.\n+ # The type of a chip that is defined.\nCHIP_TYPE = ''\n# The chip value defines what property or attribute of the\n@@ -701,12 +701,15 @@ class Search(resource.SketchResource):\n@indices.setter\ndef indices(self, indices):\n\"\"\"Make changes to the current set of indices.\"\"\"\n+ def _is_string_or_int(item):\n+ return isinstance(item, (str, int))\n+\nif not isinstance(indices, list):\nlogger.warning(\n'Indices needs to be a list of strings (indices that were '\n'passed in were not a list).')\nreturn\n- if not all([isinstance(x, (str, int)) for x in indices]):\n+ if not all(map(_is_string_or_int, indices)):\nlogger.warning(\n'Indices needs to be a list of strings or ints, not all '\n'entries in the indices list are valid string/int.')\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": "@@ -388,7 +388,7 @@ class Sketch(resource.BaseResource):\nstatus = error.check_return_status(response, logger)\nif not status:\n- logger.error('Unable to remove the attriubute from the sketch.')\n+ logger.error('Unable to remove the attribute from the sketch.')\nreturn status\n@@ -772,7 +772,7 @@ class Sketch(resource.BaseResource):\nReturns:\nA 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+ a None if neither story_id or story_title is defined or if\nthe view does not exist. If a story title is defined and\nnot a story id, the first story that is found with the same\ntitle will be returned.\n@@ -802,7 +802,7 @@ class Sketch(resource.BaseResource):\nReturns:\nA search object (instance of search.Search) if one is found.\n- Returns a None if neiter view_id or view_name is defined or if\n+ Returns a None if neither view_id or view_name is defined or if\nthe search does not exist.\n\"\"\"\nreturn self.get_saved_search(search_id=view_id, search_name=view_name)\n@@ -818,7 +818,7 @@ class Sketch(resource.BaseResource):\nReturns:\nA search object (instance of search.Search) if one is found.\n- Returns a None if neiter search_id or search_name is defined or if\n+ Returns a None if neither search_id or search_name is defined or if\nthe search does not exist.\n\"\"\"\nif self.is_archived():\n@@ -1537,7 +1537,7 @@ class Sketch(resource.BaseResource):\nreturn self._archived\ndef archive(self):\n- \"\"\"Archive a sketch and return a boolean whether it was succesful.\"\"\"\n+ \"\"\"Archive a sketch and return a boolean whether it was successful.\"\"\"\nif self.is_archived():\nlogger.error('Sketch already archived.')\nreturn False\n@@ -1554,7 +1554,7 @@ class Sketch(resource.BaseResource):\nreturn return_status\ndef unarchive(self):\n- \"\"\"Unarchives a sketch and return boolean whether it was succesful.\"\"\"\n+ \"\"\"Unarchives a sketch and return boolean whether it was successful.\"\"\"\nif not self.is_archived():\nlogger.error('Sketch wasn\\'t archived.')\nreturn False\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/Admin-Guide.md",
"new_path": "docs/Admin-Guide.md",
"diff": "- [search_template](#search_template)\n- [import](#import)\n- [similarity_score](#similarity_score)\n+ - [Upgrade DB After Schema Change](#upgrade-db-after-schema-change)\n## Installation\n@@ -176,7 +177,7 @@ tsctl db\nWill drop all databases.\n-Comand:\n+Command:\n```shell\ntsctl drop_db\n@@ -199,7 +200,7 @@ Delete timeline permanently from Timesketch and Elasticsearch. It will alert if\nindex_name: The name of the index in Elasticsearch\n```\n-Comand:\n+Command:\n```shell\ntsctl purge\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/CreateTimeLineFromOtherData.md",
"new_path": "docs/CreateTimeLineFromOtherData.md",
"diff": "# Create Timeline from other data\n-At a certain point during an investigation, data will be generated that would add value to a timeline but are not formated or covered in [Create timeline from JSON/JSONL/CSV file](docs/CreateTimelineFromJSONorCSV.md).\n+At a certain point during an investigation, data will be generated that would add value to a timeline but are not formatted or covered in [Create timeline from JSON/JSONL/CSV file](docs/CreateTimelineFromJSONorCSV.md).\nFor such a case, assume all your data is in a file called `raw_data` and it is not a CSV or a JSON that matches the timesketch format and is not a plaso output file that could be uploaded according to the [documentation](/docs/CreateTimelineFromPlaso.md).\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/UseSigma.md",
"new_path": "docs/UseSigma.md",
"diff": "@@ -13,7 +13,7 @@ The other option is to use Sigma via the API and the API client.\nTimesketch deliberately does not provide a set of Sigma rules, as those would add complexity to maintain.\nTo use the official community rules you can clone [github.com/Neo23x0/sigma](https://github.com/Neo23x0/sigma) to /data/sigma.\n-This directory will not be catched by git.\n+This directory will not be caught by git.\n```shell\ncd data\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": "@@ -412,7 +412,7 @@ class ImportStreamer(object):\n'formatted according using this format string: '\n'%Y-%m-%dT%H:%M:%S%z. If that is not provided the data frame '\n'needs to have a column that has the word \"time\" in it, '\n- 'that can be used to conver to a datetime field.')\n+ 'that can be used to convert to a datetime field.')\nif 'message' not in data_frame_use:\nraise ValueError(\n@@ -483,7 +483,7 @@ class ImportStreamer(object):\nheader : int, list of int, default 0\nRow (0-indexed) to use for the column labels of the\nparsed DataFrame. If a list of integers is passed those\n- row positions wil be combined into a ``MultiIndex``. Use\n+ row positions will be combined into a ``MultiIndex``. Use\nNone if there is no header.\nnames : array-like, default None\nList of column names to use. If file contains no header\n"
},
{
"change_type": "MODIFY",
"old_path": "test_tools/timesketch/lib/analyzers/interface.py",
"new_path": "test_tools/timesketch/lib/analyzers/interface.py",
"diff": "@@ -244,7 +244,7 @@ class Event(object):\n\"\"\"Update the status of an event.\nArgs:\n- change: optional change object (instace of a namedtuple).\n+ change: optional change object (instance of a namedtuple).\nIf supplied the context will be updated with the\nchange information.\n\"\"\"\n@@ -710,7 +710,7 @@ class BaseSketchAnalyzer(BaseIndexAnalyzer):\nsketch_id: Sketch ID.\n\"\"\"\nself.sketch = Sketch(sketch_id=sketch_id)\n- super(BaseSketchAnalyzer, self).__init__(file_name)\n+ super().__init__(file_name)\ndef set_context(self, context):\n\"\"\"Sets the context of the analyzer.\n@@ -718,7 +718,7 @@ class BaseSketchAnalyzer(BaseIndexAnalyzer):\nArgs:\ncontext: Context object (instance of AnalyzerContext).\n\"\"\"\n- super(BaseSketchAnalyzer, self).set_context(context)\n+ super().set_context(context)\nself._context.sketch = self.sketch\nself.sketch.set_context(self._context)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/aggregation.py",
"new_path": "timesketch/api/v1/resources/aggregation.py",
"diff": "@@ -52,8 +52,9 @@ class AggregationResource(resources.ResourceMixin, Resource):\nHandler for /api/v1/sketches/:sketch_id/aggregation/:aggregation_id\nArgs:\n- sketch_id: Integer primary key for a sketch database model\n- aggregation_id: Integer primary key for an agregation database model\n+ sketch_id: Integer primary key for a sketch database model.\n+ aggregation_id: Integer primary key for an aggregation database\n+ model.\nReturns:\nJSON with aggregation results\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/sketch.py",
"new_path": "timesketch/api/v1/resources/sketch.py",
"diff": "@@ -230,7 +230,7 @@ class SketchResource(resources.ResourceMixin, Resource):\n@staticmethod\ndef _get_sketch_for_admin(sketch):\n- \"\"\"Returns a limited sketch view for adminstrators.\n+ \"\"\"Returns a limited sketch view for administrators.\nAn administrator needs to get information about all sketches\nthat are stored on the backend. However that view should be\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/feature_extraction.py",
"new_path": "timesketch/lib/analyzers/feature_extraction.py",
"diff": "@@ -192,10 +192,10 @@ class FeatureExtractionSketchPlugin(interface.BaseSketchAnalyzer):\nArgs:\ncurrent_val: current value of store_as.\nextracted_value: values matched from regexp (type list).\n- keep_multi: choise if you keep all match from regex (type boolean).\n- merge_values: choise if you merge value from extracted\n+ keep_multi: choice if you keep all match from regex (type boolean).\n+ merge_values: choice if you merge value from extracted\nand current (type boolean).\n- type_list: choise if you store values in list type(type boolean).\n+ type_list: choice if you store values in list type(type boolean).\nReturns:\nValue to store\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/analyzers/interface.py",
"new_path": "timesketch/lib/analyzers/interface.py",
"diff": "@@ -548,7 +548,7 @@ class AggregationGroup(object):\n\"\"\"Add an aggregation object to the group.\nArgs:\n- aggregation_obj (Aggregation): the Aggregation objec.\n+ aggregation_obj (Aggregation): the Aggregation object.\n\"\"\"\nself.group.aggregations.append(aggregation_obj)\nself.group.orientation = self._orientation\n@@ -567,7 +567,7 @@ class AggregationGroup(object):\n\"\"\"Sets how charts should be joined.\nArgs:\n- orienation: string that contains how they should be connected\n+ orientation: string that contains how they should be connected\ntogether, That is the chart orientation, the options are:\n\"layer\", \"horizontal\" and \"vertical\". The default behavior\nis \"layer\".\n@@ -582,7 +582,7 @@ class AggregationGroup(object):\nself.commit()\ndef set_vertical(self):\n- \"\"\"Sets the \"orienation\" to vertical.\"\"\"\n+ \"\"\"Sets the \"orientation\" to vertical.\"\"\"\nself._orientation = 'vertical'\nself.commit()\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -560,7 +560,7 @@ class ElasticsearchDataStore(object):\nquery_dsl: Dictionary containing Elasticsearch DSL query\nindices: List of indices to query\nreturn_fields: List of fields to return\n- enable_scroll: Boolean determing whether scrolling is enabled.\n+ enable_scroll: Boolean determining whether scrolling is enabled.\ntimeline_ids: Optional list of IDs of Timeline objects that should\nbe queried as part of the search.\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -157,7 +157,7 @@ def get_all_sigma_rules():\ndef get_sigma_rule(filepath, sigma_config=None):\n- \"\"\" Returns a JSON represenation for a rule\n+ \"\"\" Returns a JSON representation for a rule\nArgs:\nfilepath: path to the sigma rule to be parsed\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed some spelling mistakes in various files comments (#1634) |
263,096 | 26.02.2021 11:36:35 | -3,600 | 047156ed112c0b1aa0dadf1b4d863ad787baa75a | Added more Sigma support into the API and 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": "@@ -550,16 +550,12 @@ class TimesketchApi:\nreturn pandas.DataFrame.from_records(response.get('objects'))\nfor rule_dict in response['objects']:\n- rule_uuid = rule_dict.get('id')\n- title = rule_dict.get('title')\n- es_query = rule_dict.get('es_query')\n- file_name = rule_dict.get('file_name')\n- description = rule_dict.get('description')\n- file_relpath = rule_dict.get('file_relpath')\n- index_obj = sigma.Sigma(\n- rule_uuid, api=self, es_query=es_query, file_name=file_name,\n- title=title, description=description,\n- file_relpath=file_relpath)\n+ if not rule_dict:\n+ raise ValueError('No rules found.')\n+\n+ index_obj = sigma.Sigma(api=self)\n+ for key, value in rule_dict.items():\n+ index_obj.set_value(key, value)\nrules.append(index_obj)\nreturn rules\n@@ -573,4 +569,31 @@ class TimesketchApi:\nReturns:\nInstance of a Sigma object.\n\"\"\"\n- return sigma.Sigma(rule_uuid, api=self)\n+ sigma_obj = sigma.Sigma(api=self)\n+ sigma_obj.from_rule_uuid(rule_uuid)\n+\n+ return sigma_obj\n+\n+ def get_sigma_rule_by_text(self, rule_text):\n+ \"\"\"Returns a Sigma Object based on a sigma rule text.\n+\n+ Args:\n+ rule_text: Full Sigma rule text.\n+\n+ Returns:\n+ Instance of a Sigma object.\n+\n+ Raises:\n+ ValueError: No Rule text given or issues parsing it.\n+ \"\"\"\n+ if not rule_text:\n+ raise ValueError('No rule text given.')\n+\n+ try:\n+ sigma_obj = sigma.Sigma(api=self)\n+ sigma_obj.from_text(rule_text)\n+ except ValueError:\n+ logger.error(\n+ 'Parsing Error, unable to parse the Sigma rule',exc_info=True)\n+\n+ return sigma_obj\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma.py",
"new_path": "api_client/python/timesketch_api_client/sigma.py",
"diff": "@@ -17,6 +17,7 @@ from __future__ import unicode_literals\nimport logging\nfrom . import resource\n+from . import error\nlogger = logging.getLogger('timesketch_api.sigma')\n@@ -31,67 +32,157 @@ class Sigma(resource.BaseResource):\n\"\"\"\n- def __init__(self, rule_uuid, api, es_query=None,\n- file_name=None, title=None, description=None,\n- file_relpath=None):\n+ def __init__(self, api):\n\"\"\"Initializes the Sigma object.\nArgs:\n- rule_uuid: Id of the sigma rule.\napi: An instance of TimesketchApi object.\n- es_query: Elastic Search query of the rule\n- file_name: File name of the rule\n- title: Title of the rule\n- description: Description of the rule\n- file_relpath: path of the file relative to the config value\n\"\"\"\n- self.rule_uuid = rule_uuid\n- self._description = description\n- self._es_query = es_query\n- self._file_name = file_name\n- self._title = title\n- self._file_relpath = file_relpath\n- self._resource_uri = f'sigma/{self.rule_uuid}'\n+ self._attr_dict = {}\n+ resource_uri = 'sigma/'\nsuper().__init__(\n- api=api, resource_uri=self._resource_uri)\n+ api=api, resource_uri=resource_uri)\n@property\n- def es_query(self):\n- \"\"\"Returns the elastic search query.\"\"\"\n- sigma_data = self.data\n+ def attributes(self):\n+ \"\"\"Returns a list of all attribute keys for the rule\"\"\"\n+ return list(self._attr_dict.keys())\n- if not sigma_data:\n+ def get_attribute(self, key):\n+ \"\"\"Get a value for a given key in case it has no dedicated property\"\"\"\n+ if not self._attr_dict:\nreturn ''\n+ return self._attr_dict.get(key, '')\n- return sigma_data.get('es_query', '')\n+ @property\n+ def es_query(self):\n+ \"\"\"Returns the ElasticSearch query.\"\"\"\n+ return self.get_attribute('es_query')\n@property\ndef title(self):\n\"\"\"Returns the sigma rule title.\"\"\"\n- sigma_data = self.data\n-\n- if not sigma_data:\n- return ''\n-\n- return sigma_data.get('title', '')\n+ return self.get_attribute('title')\n@property\ndef id(self):\n\"\"\"Returns the sigma rule id.\"\"\"\n- sigma_data = self.data\n-\n- if not sigma_data:\n- return ''\n-\n- return sigma_data.get('id', '')\n+ return self.get_attribute('id')\n@property\ndef file_relpath(self):\n\"\"\"Returns the relative filepath of the rule.\"\"\"\n- sigma_data = self.data\n+ return self.get_attribute('file_relpath')\n- if not sigma_data:\n- return ''\n+ @property\n+ def rule_uuid(self):\n+ \"\"\"Returns the rule id.\"\"\"\n+ return self.get_attribute('rule_uuid')\n+\n+ @property\n+ def file_name(self):\n+ \"\"\"Returns the rule filename.\"\"\"\n+ return self.get_attribute('file_name')\n+\n+ @property\n+ def description(self):\n+ \"\"\"Returns the rule description.\"\"\"\n+ return self.get_attribute('description')\n+\n+ @property\n+ def level(self):\n+ \"\"\"Returns the rule confidence level.\"\"\"\n+ return self.get_attribute('level')\n+\n+ @property\n+ def falsepositives(self):\n+ \"\"\"Returns the rule falsepositives.\"\"\"\n+ return self.get_attribute('falsepositives')\n+\n+ @property\n+ def author(self):\n+ \"\"\"Returns the rule author.\"\"\"\n+ return self.get_attribute('author')\n+\n+ @property\n+ def date(self):\n+ \"\"\"Returns the rule date.\"\"\"\n+ return self.get_attribute('date')\n+\n+ @property\n+ def modified(self):\n+ \"\"\"Returns the rule modified date.\"\"\"\n+ return self.get_attribute('modified')\n+\n+\n+ @property\n+ def logsource(self):\n+ \"\"\"Returns the rule logsource.\"\"\"\n+ return self.get_attribute('logsource')\n+\n+ @property\n+ def detection(self):\n+ \"\"\"Returns the rule detection.\"\"\"\n+ return self.get_attribute('detection')\n+\n+ @property\n+ def references(self):\n+ \"\"\"Returns the rule references.\"\"\"\n+ return self.get_attribute('references')\n+\n+ def set_value(self, key, value):\n+ \"\"\"Sets the value for a given key\n+\n+ Args:\n+ key: key to set the value\n+ value: value to set\n+\n+ \"\"\"\n+ self._attr_dict[key] = value\n+\n+ def _load_rule_dict(self, rule_dict):\n+ \"\"\"Load a dict into a rule\"\"\"\n+ for key, value in rule_dict.items():\n+ self.set_value(key, value)\n+\n+ def from_rule_uuid(self, rule_uuid):\n+ \"\"\"Get a Sigma object from a rule uuid.\n+\n+ Args:\n+ rule_uuid: Id of the sigma rule.\n+\n+ \"\"\"\n+ self.resource_uri = f'sigma/rule/{rule_uuid}'\n+ super().__init__(\n+ api=self.api, resource_uri=self.resource_uri)\n+\n+ self.lazyload_data(refresh_cache=True)\n+ for key, value in self.resource_data.items():\n+ self.set_value(key, value)\n+\n+\n+ def from_text(self, rule_text):\n+ \"\"\"Get a Sigma object from a rule text.\n+\n+ Args:\n+ rule_text: Rule text to be parsed.\n+\n+ Raises:\n+ ValueError: If no response was given\n+ \"\"\"\n+ self.resource_uri = '{0:s}/sigma/text/'.format(self.api.api_root)\n+ data = {'title': 'Get_Sigma_by_text', 'content': rule_text}\n+ response = self.api.session.post(self.resource_uri, data=data)\n+ response_dict = error.get_response_json(response, logger)\n+\n+ objects = response_dict.get('objects')\n+\n+ if not objects:\n+ logger.warning(\n+ 'Unable to parse rule with given text')\n+ raise ValueError('No rules found.')\n- return sigma_data.get('file_relpath', '')\n+ rule_dict = objects[0]\n+ for key, value in rule_dict.items():\n+ self.set_value(key, value)\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma_test.py",
"new_path": "api_client/python/timesketch_api_client/sigma_test.py",
"diff": "@@ -20,6 +20,38 @@ import mock\nfrom . import test_lib\nfrom . import client\n+MOCK_SIGMA_RULE = \"\"\"\n+title: Suspicious Installation of Zenmap\n+id: 5266a592-b793-11ea-b3de-0242ac130004\n+description: Detects suspicious installation of Zenmap\n+references:\n+ - https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html\n+author: Alexander Jaeger\n+date: 2020/06/26\n+modified: 2021/01/01\n+logsource:\n+ product: linux\n+ service: shell\n+detection:\n+ keywords:\n+ # Generic suspicious commands\n+ - '*apt-get install zmap*'\n+ condition: keywords\n+falsepositives:\n+ - Unknown\n+level: high\n+\"\"\"\n+\n+MOCK_SIGMA_RULE_ERROR1 = \"\"\"\n+title: Suspicious Foobar\n+id: 5266a592-b793-11ea-b3de-0242ac130004\n+description: Detects suspicious installation of Zenmap\n+references:\n+ - https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html\n+author: Alexander Jaeger\n+date: 2020/06/26\n+modified: 2020/06/26\n+\"\"\"\nclass TimesketchSigmaTest(unittest.TestCase):\n\"\"\"Test Sigma.\"\"\"\n@@ -34,25 +66,74 @@ class TimesketchSigmaTest(unittest.TestCase):\n\"\"\"Test single Sigma rule.\"\"\"\nrule = self.api_client.get_sigma_rule(\n- '5266a592-b793-11ea-b3de-0242ac130004')\n-\n+ rule_uuid='5266a592-b793-11ea-b3de-0242ac130004')\n+ rule.from_rule_uuid('5266a592-b793-11ea-b3de-0242ac130004')\n+ self.assertGreater(len(rule.attributes),5)\nself.assertIsNotNone(rule)\n+ self.assertIn('Alexander', rule.author)\n+ self.assertIn('Alexander', rule.get_attribute('author'))\n+ self.assertEqual(rule.id, '5266a592-b793-11ea-b3de-0242ac130004')\n+ self.assertEqual(rule.title, 'Suspicious Installation of Zenmap')\n+ self.assertIn('zmap', rule.es_query, 'ES_Query does not match')\n+ self.assertIn('b793', rule.id)\n+ self.assertIn('/syslog/foobar/', rule.file_relpath)\n+ self.assertIn('sigma/rule/5266a592', rule.resource_uri)\n+ self.assertIn('suspicious installation of Zenmap', rule.description)\n+ self.assertIn('high', rule.level)\n+ self.assertEqual(len(rule.falsepositives), 1)\n+ self.assertIn('Unknown', rule.falsepositives[0])\n+ self.assertIn('susp_zenmap', rule.file_name)\n+ self.assertIn('2020/06/26', rule.date)\n+ self.assertIn('2021/01/01', rule.modified)\n+ self.assertIn('high', rule.level)\n+ self.assertIn('foobar.com', rule.references[0])\n+ self.assertEqual(len(rule.detection), 2)\n+ self.assertEqual(len(rule.logsource), 2)\n- self.assertEqual(\n- rule.title, 'Suspicious Installation of Zenmap',\n- 'Title of the rule does not match')\n- self.assertEqual(\n- rule.id, '5266a592-b793-11ea-b3de-0242ac130004',\n- 'Id of the rule does not match')\ndef test_sigma_rules(self):\n'''Testing the Sigma rules list'''\nrules = self.api_client.list_sigma_rules()\nself.assertIsNotNone(rules)\n+ self.assertEqual(len(rules), 2)\n+ rule = rules[0]\n+ self.assertEqual(rule.title, 'Suspicious Installation of Zenmap')\n+ self.assertIn('zmap', rule.es_query, 'ES_Query does not match')\n+ self.assertIn('b793', rule.id)\n+ self.assertIn('Alexander', rule.author)\n+ self.assertIn('2020/06/26',rule.date)\n+ self.assertIn('installation of Zenmap', rule.description)\n+ self.assertEqual(len(rule.detection), 2)\n+ self.assertIn('zmap*', rule.es_query)\n+ self.assertIn('Unknown', rule.falsepositives[0])\n+ self.assertEqual(len(rule.detection), 2)\n+ self.assertEqual(len(rule.logsource), 2)\n+ self.assertIn('2020/06/26', rule.modified)\n+ self.assertIn('/linux/syslog/foobar', rule.file_relpath)\n+ self.assertIn('lnx_susp_zenmap', rule.file_name)\n+ self.assertIn('high', rule.level)\n+ self.assertIn('foobar.com', rule.references[0])\n+\n- rule1 = rules[0]\n+ def test_get_sigma_rule_by_text(self):\n- self.assertEqual(\n- rule1.title, 'Suspicious Installation of Zenmap',\n- 'Title of the rule does not match')\n+ rule = self.api_client.get_sigma_rule_by_text(MOCK_SIGMA_RULE)\n+\n+ self.assertIsNotNone(rule)\n+ self.assertGreater(len(rule.attributes),5)\n+ self.assertIn('zsh', rule.es_query)\n+ self.assertIn('Installation of foobar', rule.title)\n+ self.assertIn('', rule.id)\n+ self.assertIn('', rule.file_relpath)\n+ self.assertIn('http://127.0.0.1/api/v1/sigma/text/', rule.resource_uri)\n+ self.assertIn('suspicious installation of foobar', rule.description)\n+ self.assertIn('high', rule.level)\n+ self.assertEqual(len(rule.falsepositives), 1)\n+ self.assertIn('Unknown', rule.falsepositives[0])\n+ self.assertIn('N/A', rule.file_name)\n+ self.assertIn('Alexander', rule.author)\n+ self.assertIn('2020/12/10', rule.date)\n+ self.assertIn('2021/01/01', rule.modified)\n+ self.assertEqual(len(rule.detection), 2)\n+ self.assertEqual(len(rule.logsource), 2)\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": "@@ -251,7 +251,6 @@ def mock_response(*args, **kwargs):\n'title': 'Suspicious Installation of Zenmap',\n'file_name': 'lnx_susp_zenmap',\n'file_relpath' : '/linux/syslog/foobar/'\n-\n}, {\n'author': 'Alexander Jaeger',\n'date': '2020/11/10',\n@@ -270,7 +269,7 @@ def mock_response(*args, **kwargs):\n'modified': '2020/06/26',\n'references': ['httpx://foobar.com'],\n'title': 'Suspicious Installation of Zenmap',\n- 'file_name': 'lnx_susp_zenmap',\n+ 'file_name': 'lnx_susp_foobar',\n'file_relpath' : '/windows/foobar/'\n}\n]\n@@ -283,7 +282,7 @@ def mock_response(*args, **kwargs):\n'references': ['httpx://foobar.com'],\n'author': 'Alexander Jaeger',\n'date': '2020/06/26',\n- 'modified': '2020/06/26',\n+ 'modified': '2021/01/01',\n'logsource': {\n'product': 'linux', 'service': 'shell'\n},\n@@ -298,6 +297,37 @@ def mock_response(*args, **kwargs):\n'file_relpath' : '/linux/syslog/foobar/'\n}\n+ sigma_rule_text_mock = {\n+ 'meta': {\n+ 'parsed': True\n+ },\n+ 'objects':[\n+ {\n+ 'title': 'Installation of foobar',\n+ 'id': 'bb1e0d1d-cd13-4b65-bf7e-69b4e740266b',\n+ 'description': 'Detects suspicious installation of foobar',\n+ 'references': ['https://samle.com/foobar'],\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/12/10',\n+ 'modified': '2021/01/01',\n+ 'logsource': {\n+ 'product': 'linux',\n+ 'service': 'shell'\n+ },\n+ 'detection': {\n+ 'keywords': ['*apt-get install foobar*'],\n+ 'condition': 'keywords'\n+ },\n+ 'falsepositives': ['Unknown'],\n+ 'level': 'high',\n+ 'es_query':\n+ '(data_type:(\"shell\\\\:zsh\\\\:history\" OR \"bash\\\\:history\\\\:command\" OR \"apt\\\\:history\\\\:line\" OR \"selinux\\\\:line\") AND \"*apt\\\\-get\\\\ install\\\\ foobar*\")',# pylint: disable=line-too-long\n+ 'file_name': 'N/A',\n+ 'file_relpath': 'N/A'\n+ }\n+ ]\n+ }\n+\n# Register API endpoints to the correct mock response data.\nurl_router = {\n'http://127.0.0.1':\n@@ -322,10 +352,12 @@ def mock_response(*args, **kwargs):\nMockResponse(json_data=story_data),\n'http://127.0.0.1/api/v1/sketches/1/archive/':\nMockResponse(json_data=archive_data),\n- 'http://127.0.0.1/api/v1/sigma/5266a592-b793-11ea-b3de-0242ac130004':\n+ 'http://127.0.0.1/api/v1/sigma/rule/5266a592-b793-11ea-b3de-0242ac130004':# pylint: disable=line-too-long\nMockResponse(json_data=sigma_rule),\n'http://127.0.0.1/api/v1/sigma/':\nMockResponse(json_data=sigma_list),\n+ 'http://127.0.0.1/api/v1/sigma/text/':\n+ MockResponse(json_data=sigma_rule_text_mock),\n}\nif kwargs.get('empty', False):\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/sigma.py",
"new_path": "timesketch/api/v1/resources/sigma.py",
"diff": "\"\"\"Sigma resources for version 1 of the Timesketch API.\"\"\"\nimport logging\n+import yaml\nfrom flask import abort\nfrom flask import jsonify\n+from flask import request\nfrom flask_restful import Resource\nfrom flask_login import login_required\nfrom flask_login import current_user\n+from sigma.parser import exceptions as sigma_exceptions\n+\nimport timesketch.lib.sigma_util as ts_sigma_lib\nfrom timesketch.api.v1 import resources\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\nlogger = logging.getLogger('timesketch.api.sigma')\n@@ -50,10 +55,10 @@ class SigmaListResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\n'OS Error, unable to get the path to the Sigma rules')\n-\n+ # TODO: idea for meta: add a list of folders that have been parsed\nmeta = {'current_user': current_user.username,\n'rules_count': len(sigma_rules)}\n- return jsonify({'objects': sigma_rules, 'meta': meta})\n+ return jsonify({'objects': [sigma_rules], 'meta': meta})\nclass SigmaResource(resources.ResourceMixin, Resource):\n@@ -89,4 +94,78 @@ class SigmaResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sigma rule found with this ID.')\n- return return_rule\n+ meta = {'current_user': current_user.username,\n+ 'rules_count': len(sigma_rules)}\n+ return jsonify({'objects': return_rule, 'meta': meta})\n+\n+\n+class SigmaByTextResource(resources.ResourceMixin, Resource):\n+ \"\"\"Resource to get a Sigma rule by text.\"\"\"\n+\n+ @login_required\n+ def post(self):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ JSON sigma rule\n+ \"\"\"\n+\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ action = form.get('action', '')\n+\n+ # TODO: that can eventually go away since there are no other actions\n+ if action != 'post':\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Action needs to be \"post\"')\n+\n+ content = form.get('content')\n+ if not content:\n+ return abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Missing values from the request.')\n+\n+ try:\n+ sigma_rule = ts_sigma_lib.get_sigma_rule_by_text(content)\n+\n+ except ValueError:\n+ logger.error('Sigma Parsing error with the user provided rule',\n+ exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Error unable to parse the provided Sigma rule')\n+\n+ except NotImplementedError as exception:\n+ logger.error(\n+ 'Sigma Parsing error: Feature in the rule provided '\n+ ' is not implemented in this backend', exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Error generating rule {0!s}'.format(exception))\n+\n+ except sigma_exceptions.SigmaParseError as exception:\n+ logger.error(\n+ 'Sigma Parsing error: unknown error', exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Sigma parsing error generating rule with error: {0!s}'.format(\n+ exception))\n+\n+ except yaml.parser.ParserError as exception:\n+ logger.error(\n+ 'Sigma Parsing error: an invalid yml file has been provided',\n+ exc_info=True)\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Sigma parsing error: invalid yaml provided {0!s}'.format(\n+ exception))\n+\n+ if sigma_rule is None:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sigma was parsed')\n+ metadata = {'parsed': True}\n+\n+ return jsonify({'objects': [sigma_rule], 'meta': metadata})\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources_test.py",
"new_path": "timesketch/api/v1/resources_test.py",
"diff": "@@ -363,3 +363,171 @@ class TimelineListResourceTest(BaseTest):\ndata=json.dumps(data, ensure_ascii=False),\ncontent_type='application/json')\nself.assertEqual(response.status_code, HTTP_STATUS_CODE_CREATED)\n+\n+\n+class SigmaResourceTest(BaseTest):\n+ \"\"\"Test Sigma resource.\"\"\"\n+ resource_url = '/api/v1/sigma/rule/'\n+ expected_response = {\n+ 'objects': {\n+ 'description': 'Detects suspicious installation of Zenmap',\n+ 'id': '5266a592-b793-11ea-b3de-0242ac130004',\n+ 'level': 'high',\n+ 'logsource': {\n+ 'product': 'linux', 'service': 'shell'\n+ },\n+ 'title': 'Suspicious Installation of Zenmap',\n+ }\n+ }\n+\n+ def test_get_sigma_rule(self):\n+ \"\"\"Authenticated request to get an sigma rule.\"\"\"\n+ self.login()\n+ response = self.client.get(self.resource_url +\n+ '5266a592-b793-11ea-b3de-0242ac130004')\n+ self.assertIsNotNone(response)\n+\n+\n+class SigmaListResourceTest(BaseTest):\n+ \"\"\"Test Sigma resource.\"\"\"\n+ resource_url = '/api/v1/sigma/'\n+ expected_response = {\n+ 'meta': {\n+ 'current_user': 'test1', 'rules_count': 1\n+ },\n+ 'objects':[[{\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/06/26',\n+ 'description': 'Detects suspicious installation of Zenmap',\n+ 'detection': {\n+ 'condition': 'keywords',\n+ 'keywords': [\n+ '*apt-get install zmap*'\n+ ]\n+ },\n+ 'es_query': '*apt\\\\-get\\\\ install\\\\ zmap*',\n+ 'falsepositives': ['Unknown'],\n+ 'file_name': 'lnx_susp_zenmap.yml',\n+ 'file_relpath': 'lnx_susp_zenmap.yml',\n+ 'id': '5266a592-b793-11ea-b3de-0242ac130004',\n+ 'level': 'high',\n+ 'logsource': {\n+ 'product': 'linux',\n+ 'service': 'shell'\n+ },\n+ 'modified': '2020/06/26',\n+ 'references': [\n+ 'https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html'\n+ ],\n+ 'title': 'Suspicious Installation of Zenmap'\n+ }]]}\n+ def test_get_sigma_rule_list(self):\n+ self.login()\n+ response = self.client.get(self.resource_url)\n+ data = json.loads(response.get_data(as_text=True))\n+ print(data)\n+ self.assertDictContainsSubset(self.expected_response, response.json)\n+ self.assertIsNotNone(response)\n+\n+class SigmaByTextResourceTest(BaseTest):\n+ \"\"\"Test Sigma by text resource.\"\"\"\n+\n+ resource_url = '/api/v1/sigma/text/'\n+ correct_rule = '''\n+ title: Installation of foobar\n+ id: bb1e0d1d-cd13-4b65-bf7e-69b4e740266b\n+ description: Detects suspicious installation of foobar\n+ references:\n+ - https://samle.com/foobar\n+ author: Alexander Jaeger\n+ date: 2020/12/10\n+ modified: 2020/12/10\n+ logsource:\n+ product: linux\n+ service: shell\n+ detection:\n+ keywords:\n+ # Generic suspicious commands\n+ - '*apt-get install foobar*'\n+ condition: keywords\n+ falsepositives:\n+ - Unknown\n+ level: high\n+ '''\n+ expected_response = {\n+ 'meta': {\n+ 'parsed': True\n+ },\n+ 'objects':[\n+ {\n+ 'title': 'Installation of foobar',\n+ 'id': 'bb1e0d1d-cd13-4b65-bf7e-69b4e740266b',\n+ 'description': 'Detects suspicious installation of foobar',\n+ 'references': ['https://samle.com/foobar'],\n+ 'author': 'Alexander Jaeger',\n+ 'date': '2020/12/10',\n+ 'modified': '2020/12/10',\n+ 'logsource': {\n+ 'product': 'linux',\n+ 'service': 'shell'\n+ },\n+ 'detection': {\n+ 'keywords': ['*apt-get install foobar*'],\n+ 'condition': 'keywords'\n+ },\n+ 'falsepositives': ['Unknown'],\n+ 'level': 'high',\n+ 'es_query':\n+ '(data_type:(\"shell\\\\:zsh\\\\:history\" OR \"bash\\\\:history\\\\:command\" OR \"apt\\\\:history\\\\:line\" OR \"selinux\\\\:line\") AND \"*apt\\\\-get\\\\ install\\\\ foobar*\")',# pylint: disable=line-too-long\n+ 'file_name': 'N/A',\n+ 'file_relpath': 'N/A'\n+ }\n+ ]\n+ }\n+\n+ def test_get_sigma_rule(self):\n+ \"\"\"Authenticated request to get an sigma rule by text.\"\"\"\n+ self.login()\n+\n+ data = dict(action='post', content=self.correct_rule)\n+ response = self.client.post(\n+ self.resource_url,\n+ data=json.dumps(data, ensure_ascii=False),\n+ content_type='application/json')\n+ self.assertIsNotNone(response)\n+ self.assertEqual(response.status_code, HTTP_STATUS_CODE_OK)\n+ self.assertDictContainsSubset(self.expected_response, response.json)\n+ self.assert200(response)\n+\n+ # wrong sigma rule\n+ data = dict(action='post', content='foobar: asd')\n+ response = self.client.post(\n+ self.resource_url,\n+ data=json.dumps(data, ensure_ascii=False),\n+ content_type='application/json')\n+ data = json.loads(response.get_data(as_text=True))\n+\n+ self.assertIn('No detection definitions found', data['message'])\n+ self.assertEqual(response.status_code, HTTP_STATUS_CODE_BAD_REQUEST)\n+\n+ # wrong action\n+ data = dict(action='get', content=self.correct_rule)\n+ response = self.client.post(\n+ self.resource_url,\n+ data=json.dumps(data, ensure_ascii=False),\n+ content_type='application/json')\n+ data = json.loads(response.get_data(as_text=True))\n+\n+ self.assertIn('Action needs to be \"post\"', data['message'])\n+ self.assertEqual(response.status_code, HTTP_STATUS_CODE_BAD_REQUEST)\n+\n+ # no content given\n+ data = dict(action='post')\n+ response = self.client.post(\n+ self.resource_url,\n+ data=json.dumps(data, ensure_ascii=False),\n+ content_type='application/json')\n+ data = json.loads(response.get_data(as_text=True))\n+\n+ self.assertIn('Missing values from the request', data['message'])\n+ self.assertEqual(response.status_code, HTTP_STATUS_CODE_BAD_REQUEST)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/routes.py",
"new_path": "timesketch/api/v1/routes.py",
"diff": "@@ -56,6 +56,7 @@ from .resources.user import CollaboratorResource\nfrom .resources.user import LoggedInUserResource\nfrom .resources.sigma import SigmaResource\nfrom .resources.sigma import SigmaListResource\n+from .resources.sigma import SigmaByTextResource\nfrom .resources.graph import GraphListResource\nfrom .resources.graph import GraphResource\nfrom .resources.graph import GraphPluginListResource\n@@ -105,7 +106,8 @@ API_ROUTES = [\n(CollaboratorResource, '/sketches/<int:sketch_id>/collaborators/'),\n(VersionResource, '/version/'),\n(SigmaListResource, '/sigma/'),\n- (SigmaResource, '/sigma/<string:rule_uuid>/'),\n+ (SigmaResource, '/sigma/rule/<string:rule_uuid>/'),\n+ (SigmaByTextResource, '/sigma/text/'),\n(LoggedInUserResource, '/users/me/'),\n(GraphListResource, '/sketches/<int:sketch_id>/graphs/'),\n(GraphResource, '/sketches/<int:sketch_id>/graphs/<int:graph_id>/'),\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -25,6 +25,7 @@ import sigma.configuration as sigma_configuration\nfrom sigma.backends import elasticsearch as sigma_es\nfrom sigma.parser import collection as sigma_collection\nfrom sigma.parser import exceptions as sigma_exceptions\n+from sigma.config.exceptions import SigmaConfigParseError\nlogger = logging.getLogger('timesketch.lib.sigma')\n@@ -34,21 +35,21 @@ def get_sigma_config_file(config_file=None):\nArgs:\nconfig_file: Optional path to a config file\n-\nReturns:\nA sigma.configuration.SigmaConfiguration object\n-\nRaises:\nValueError: If SIGMA_CONFIG is not found in the config file.\nor the Sigma config file is not readabale.\n+ SigmaConfigParseError: If config file could not be parsed.\n\"\"\"\nif config_file:\nconfig_file_path = config_file\nelse:\n- config_file_path = current_app.config.get('SIGMA_CONFIG')\n+ config_file_path = current_app.config.get(\n+ 'SIGMA_CONFIG', './data/sigma_config.yaml')\n+\nif not config_file_path:\n- raise ValueError(\n- 'SIGMA_CONFIG not found in config file')\n+ raise ValueError('No config_file_path set via param or config file')\nif not os.path.isfile(config_file_path):\nraise ValueError(\n@@ -63,7 +64,11 @@ def get_sigma_config_file(config_file=None):\nwith open(config_file_path, 'r') as config_file_read:\nsigma_config_file = config_file_read.read()\n+ try:\nsigma_config = sigma_configuration.SigmaConfiguration(sigma_config_file)\n+ except SigmaConfigParseError:\n+ logger.error('Parsing error with {0:s}'.format(sigma_config_file))\n+ raise\nreturn sigma_config\n@@ -103,15 +108,12 @@ def get_sigma_rules_path():\ndef get_sigma_rules(rule_folder, sigma_config=None):\n\"\"\"Returns the Sigma rules for a folder including subfolders.\n-\nArgs:\nrule_folder: folder to be checked for rules\nsigma_config: optional argument to pass a\nsigma.configuration.SigmaConfiguration object\n-\nReturns:\nA array of Sigma rules as JSON\n-\nRaises:\nValueError: If SIGMA_RULES_FOLDERS is not found in the config file.\nor the folders are not readabale.\n@@ -157,25 +159,27 @@ def get_all_sigma_rules():\ndef get_sigma_rule(filepath, sigma_config=None):\n- \"\"\" Returns a JSON representation for a rule\n-\n+ \"\"\"Returns a JSON represenation for a rule\nArgs:\nfilepath: path to the sigma rule to be parsed\nsigma_config: optional argument to pass a\nsigma.configuration.SigmaConfiguration object\n-\nReturns:\nJson representation of the parsed rule\n+ Raises:\n+ ValueError: Parsing error\n+ IsADirectoryError: If a directory is passed as filepath\n\"\"\"\ntry:\nif sigma_config:\nsigma_conf_obj = sigma_config\nelse:\nsigma_conf_obj = get_sigma_config_file()\n- except ValueError:\n+ except ValueError as e:\nlogger.error(\n'Problem reading the Sigma config', exc_info=True)\n- return None\n+ raise ValueError('Problem reading the Sigma config') from e\n+\nsigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_conf_obj, {})\n@@ -185,11 +189,11 @@ def get_sigma_rule(filepath, sigma_config=None):\nsigma_rules_paths = None\nif not filepath.lower().endswith('.yml'):\n- return None\n+ raise ValueError(f'{filepath} does not end with .yml')\n# if a sub dir is found, nothing can be parsed\nif os.path.isdir(filepath):\n- return None\n+ raise IsADirectoryError(f'{filepath} is a directory - must be a file')\nabs_path = os.path.abspath(filepath)\n@@ -208,13 +212,13 @@ def get_sigma_rule(filepath, sigma_config=None):\nlogger.error(\n'Error generating rule in file {0:s}: {1!s}'\n.format(abs_path, exception))\n- return None\n+ raise\nexcept sigma_exceptions.SigmaParseError as exception:\nlogger.error(\n'Sigma parsing error generating rule in file {0:s}: {1!s}'\n.format(abs_path, exception))\n- return None\n+ raise\nexcept yaml.parser.ParserError as exception:\nlogger.error(\n@@ -243,3 +247,64 @@ def get_sigma_rule(filepath, sigma_config=None):\n{'file_relpath':file_relpath})\nreturn rule_return\n+\n+def get_sigma_rule_by_text(rule_text, sigma_config=None):\n+ \"\"\"Returns a JSON represenation for a rule\n+\n+ Args:\n+ rule_text: Text of the sigma rule to be parsed\n+ sigma_config: config file object\n+\n+ Returns:\n+ Json representation of the parsed rule\n+ Raises:\n+ sigma_exceptions.SigmaParseError: Issue with parsing the given rule\n+ yaml.parser.ParserError: Not a correct YAML text provided\n+ NotImplementedError: A feature in the provided Sigma rule is not\n+ implemented in Sigma for Timesketch\n+ \"\"\"\n+ if sigma_config is None:\n+ sigma_config = get_sigma_config_file()\n+\n+ sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_config, {})\n+\n+ rule_return = {}\n+\n+ # TODO check if input validation is needed / useful.\n+ try:\n+ parser = sigma_collection.SigmaCollectionParser(\n+ rule_text, sigma_config, None)\n+ parsed_sigma_rules = parser.generate(sigma_backend)\n+ rule_yaml_data = yaml.safe_load_all(rule_text)\n+ for doc in rule_yaml_data:\n+ rule_return.update(doc)\n+\n+ except NotImplementedError as exception:\n+ logger.error(\n+ 'Error generating rule {0!s}'.format(exception))\n+ raise\n+\n+ except sigma_exceptions.SigmaParseError as exception:\n+ logger.error(\n+ 'Sigma parsing error generating rule {0!s}'\n+ .format(exception))\n+ raise\n+\n+ except yaml.parser.ParserError as exception:\n+ logger.error(\n+ 'Yaml parsing error generating rule {0!s}'.format(exception))\n+ raise\n+\n+ sigma_es_query = ''\n+\n+ for sigma_rule in parsed_sigma_rules:\n+ sigma_es_query = sigma_rule\n+\n+ rule_return.update(\n+ {'es_query':sigma_es_query})\n+ rule_return.update(\n+ {'file_name':'N/A'})\n+ rule_return.update(\n+ {'file_relpath':'N/A'})\n+\n+ return rule_return\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/lib/sigma_util_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 sigma_util score.\"\"\"\n+from __future__ import absolute_import\n+from __future__ import division\n+from __future__ import print_function\n+from __future__ import unicode_literals\n+\n+from sigma.parser import exceptions as sigma_exceptions\n+\n+from timesketch.lib.testlib import BaseTest\n+import timesketch.lib.sigma_util as sigma_util\n+\n+\n+\n+MOCK_SIGMA_RULE = \"\"\"\n+title: Suspicious Installation of Zenmap\n+id: 5266a592-b793-11ea-b3de-0242ac130004\n+description: Detects suspicious installation of Zenmap\n+references:\n+ - https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html\n+author: Alexander Jaeger\n+date: 2020/06/26\n+modified: 2020/06/26\n+logsource:\n+ product: linux\n+ service: shell\n+detection:\n+ keywords:\n+ # Generic suspicious commands\n+ - '*apt-get install zmap*'\n+ condition: keywords\n+falsepositives:\n+ - Unknown\n+level: high\n+\"\"\"\n+\n+MOCK_SIGMA_RULE_ERROR1 = \"\"\"\n+title: Suspicious Foobar\n+id: 5266a592-b793-11ea-b3de-0242ac130004\n+description: Detects suspicious installation of Zenmap\n+references:\n+ - https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html\n+author: Alexander Jaeger\n+date: 2020/06/26\n+modified: 2020/06/26\n+\"\"\"\n+\n+\n+class TestSigmaUtilLib(BaseTest):\n+ \"\"\"Tests for the sigma support library.\"\"\"\n+\n+\n+ def test_get_rule_by_text(self):\n+ \"\"\"Test getting sigma rule by text.\"\"\"\n+\n+ rule = sigma_util.get_sigma_rule_by_text(MOCK_SIGMA_RULE)\n+\n+ self.assertIsNotNone(MOCK_SIGMA_RULE)\n+ self.assertIsNotNone(rule)\n+ self.assertIn('zmap', rule.get('es_query'))\n+ self.assertIn('b793', rule.get('id'))\n+ self.assertRaises(\n+ sigma_exceptions.SigmaParseError,\n+ sigma_util.get_sigma_rule_by_text,\n+ MOCK_SIGMA_RULE_ERROR1)\n+\n+ def test_get_sigma_config_file(self):\n+ \"\"\"Test getting sigma config file\"\"\"\n+ self.assertRaises(ValueError, sigma_util.get_sigma_config_file, '/foo')\n+ self.assertIsNotNone(sigma_util.get_sigma_config_file())\n+\n+ def test_get_sigma_rule(self):\n+ \"\"\"Test getting sigma rule from file\"\"\"\n+\n+ filepath = './data/sigma/rules/lnx_susp_zenmap.yml'\n+\n+ rule = sigma_util.get_sigma_rule(filepath)\n+\n+ self.assertIsNotNone(rule)\n+ self.assertIn('zmap', rule.get('es_query'))\n+ self.assertIn('b793', rule.get('id'))\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/testlib.py",
"new_path": "timesketch/lib/testlib.py",
"diff": "@@ -55,6 +55,7 @@ class TestConfig(object):\nAUTO_INDEX_ANALYZERS = []\nAUTO_SKETCH_ANALYZERS = []\nSIMILARITY_DATA_TYPES = []\n+ SIGMA_RULES_FOLDERS = ['./data/sigma/rules/']\nclass MockElasticClient(object):\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added more Sigma support into the API and API client (#1511) |
263,155 | 26.02.2021 11:42:58 | -3,600 | 234a0fc04f294f99ef48d756571eeb1432321018 | Replaced the use of the csv library in import task to use pandas (for csv/json data ingestion) | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "test_tools/test_events/sigma_events.csv",
"diff": "+\"message\",\"timestamp\",\"datetime\",\"timestamp_desc\",\"extra_field_1\",\"command\",\"data_type\",\"display_name\",\"filename\",\"packages\",\"parser\"\n+\"A message\",\"123456789\",\"2015-07-24T19:01:01+00:00\",\"Write time\",\"foo\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Another message\",\"123456790\",\"2015-07-24T19:01:02+00:00\",\"Write time\",\"bar\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Yet more messages\",\"123456791\",\"2015-07-24T19:01:03+00:00\",\"Write time\",\"baz\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Install: zmap:amd64 (1.1.0-1) [Commandline: apt-get install zmap]\",\"123456791\",\"2015-07-24T19:01:03+00:00\",\"foo\",\"\",\"Commandline: apt-get install zmap\",\"apt:history:line\",\"GZIP:/var/log/apt/history.log.1.gz\",\"/var/log/apt/history.log.1.gz\",\"Install: zmap:amd64 (1.1.0-1)\",\"apt_history\"\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/utils.py",
"new_path": "timesketch/lib/utils.py",
"diff": "@@ -23,24 +23,32 @@ import json\nimport logging\nimport random\nimport smtplib\n-import sys\nimport time\nimport codecs\n+\n+import pandas\nimport six\nfrom dateutil import parser\nfrom flask import current_app\n+from pandas import Timestamp\nfrom timesketch.lib import errors\nlogger = logging.getLogger('timesketch.utils')\n-# Set CSV field size limit to systems max value.\n-csv.field_size_limit(sys.maxsize)\n-\n# Fields to scrub from timelines.\nFIELDS_TO_REMOVE = ['_id', '_type', '_index', '_source', '__ts_timeline_id']\n+# Number of rows processed at once when ingesting a CSV file.\n+DEFAULT_CHUNK_SIZE = 10000\n+\n+# Columns that must be present in ingested timesketch files.\n+TIMESKETCH_FIELDS = frozenset({'message', 'datetime', 'timestamp_desc'})\n+\n+# Columns that must be present in ingested redline files.\n+REDLINE_FIELDS = frozenset({'Alert', 'Tag', 'Timestamp', 'Field', 'Summary'})\n+\ndef random_color():\n\"\"\"Generates a random color.\n@@ -83,6 +91,26 @@ def _scrub_special_tags(dict_obj):\n_ = dict_obj.pop(field)\n+def _validate_csv_fields(mandatory_fields, data):\n+ \"\"\"Validate parsed CSV fields against mandatory fields.\n+\n+ Args:\n+ mandatory_fields: a list of fields that must be present.\n+ data: a DataFrame built from the ingested file.\n+\n+ Raises:\n+ RuntimeError: if there are missing fields.\n+ \"\"\"\n+ mandatory_set = set(mandatory_fields)\n+ parsed_set = set(data.columns)\n+\n+ if mandatory_set.issubset(parsed_set):\n+ return\n+\n+ raise RuntimeError('Missing fields in CSV header: {0:s}'.format(\n+ ','.join(list(mandatory_set.difference(parsed_set)))))\n+\n+\ndef validate_indices(indices, datastore):\n\"\"\"Returns a list of valid indices.\n@@ -100,97 +128,81 @@ def validate_indices(indices, datastore):\ni for i in indices if datastore.client.indices.exists(index=i)]\n-def read_and_validate_csv(file_handle, delimiter=','):\n+def read_and_validate_csv(\n+ file_handle, delimiter=',', mandatory_fields=None):\n\"\"\"Generator for reading a CSV file.\nArgs:\nfile_handle: a file-like object containing the CSV content.\ndelimiter: character used as a field separator, default: ','\n+ mandatory_fields: list of fields that must be present in the CSV header.\nRaises:\nRuntimeError: when there are missing fields.\nDataIngestionError: when there are issues with the data ingestion.\n\"\"\"\n- # Columns that must be present in the CSV file.\n- mandatory_fields = ['message', 'datetime', 'timestamp_desc']\n-\n+ if not mandatory_fields:\n+ mandatory_fields = TIMESKETCH_FIELDS\n# Ensures delimiter is a string.\nif not isinstance(delimiter, six.text_type):\ndelimiter = codecs.decode(delimiter, 'utf8')\n- # Due to issues with python2.\n- if six.PY2:\n- delimiter = str(delimiter)\n-\n- reader = csv.DictReader(file_handle, delimiter=delimiter)\n- csv_header = reader.fieldnames\n- missing_fields = []\n- # Validate the CSV header\n- for field in mandatory_fields:\n- if field not in csv_header:\n- missing_fields.append(field)\n- if missing_fields:\n- raise RuntimeError(\n- 'Missing fields in CSV header: {0:s}'.format(\n- ','.join(missing_fields)))\n+ header_reader = pandas.read_csv(file_handle, sep=delimiter, nrows=0)\n+ _validate_csv_fields(mandatory_fields, header_reader)\n+\ntry:\n- for row in reader:\n- # There is a condition in which the CSV reader can read a\n- # single lines as multiple, causing issues with importing.\n- # TODO: Swap the CSV library for the user of pandas.\n- if not row:\n- continue\n- if not row['datetime']:\n+ reader = pandas.read_csv(\n+ file_handle, sep=delimiter, chunksize=DEFAULT_CHUNK_SIZE)\n+ for idx, chunk in enumerate(reader):\n+ skipped_rows = chunk[chunk['datetime'].isnull()]\n+ if not skipped_rows.empty:\nlogger.warning(\n- 'Row missing a datetime object, skipping [{0:s}]'.format(\n- ','.join([str(x).replace(\n- '\\n', '').strip() for x in row.values()])))\n- continue\n- try:\n- # normalize datetime to ISO 8601 format if it's not the case.\n- parsed_datetime = parser.parse(row['datetime'])\n- row['datetime'] = parsed_datetime.isoformat()\n+ '{0} rows skipped since they were missing a datetime field '\n+ 'or it was empty '.format(len(skipped_rows)))\n- normalized_timestamp = int(\n- time.mktime(parsed_datetime.utctimetuple()) * 1000000)\n- normalized_timestamp += parsed_datetime.microsecond\n- row['timestamp'] = str(normalized_timestamp)\n- if 'tag' in row:\n- row['tag'] = [x for x in _parse_tag_field(row['tag']) if x]\n+ # Normalize datetime to ISO 8601 format if it's not the case.\n+ try:\n+ chunk['datetime'] = pandas.to_datetime(chunk['datetime'])\n- _scrub_special_tags(row)\n+ chunk['timestamp'] = chunk['datetime'].dt.strftime(\n+ '%s%f').astype(int)\n+ chunk['datetime'] = chunk['datetime'].apply(\n+ Timestamp.isoformat).astype(str)\nexcept ValueError:\n+ warning_string = (\n+ 'Rows {0} to {1} skipped due to malformed '\n+ 'datetime values ')\n+ logger.warning(warning_string.format(\n+ idx * reader.chunksize, chunk.shape[0]))\ncontinue\n-\n+ if 'tag' in chunk:\n+ chunk['tag'] = chunk['tag'].apply(_parse_tag_field)\n+ for _, row in chunk.iterrows():\n+ _scrub_special_tags(row)\nyield row\n- except csv.Error as e:\n+ except pandas.errors.ParserError as e:\nerror_string = 'Unable to read file, with error: {0!s}'.format(e)\nlogger.error(error_string)\n- raise errors.DataIngestionError(error_string)\n+ raise errors.DataIngestionError(error_string) from e\ndef read_and_validate_redline(file_handle):\n\"\"\"Generator for reading a Redline CSV file.\n+\nArgs:\nfile_handle: a file-like object containing the CSV content.\n+\n+ Raises:\n+ RuntimeError: if there are missing fields.\n\"\"\"\n- # Columns that must be present in the CSV file\n- mandatory_fields = ['Alert', 'Tag', 'Timestamp', 'Field', 'Summary']\ncsv.register_dialect(\n- 'myDialect', delimiter=',', quoting=csv.QUOTE_ALL,\n+ 'redlineDialect', delimiter=',', quoting=csv.QUOTE_ALL,\nskipinitialspace=True)\n- reader = csv.DictReader(file_handle, delimiter=',', dialect='myDialect')\n-\n- csv_header = reader.fieldnames\n- missing_fields = []\n- # Validate the CSV header\n- for field in mandatory_fields:\n- if field not in csv_header:\n- missing_fields.append(field)\n- if missing_fields:\n- raise RuntimeError(\n- 'Missing fields in CSV header: {0:s}'.format(missing_fields))\n+ reader = pandas.read_csv(file_handle, delimiter=',',\n+ dialect='redlineDialect')\n+\n+ _validate_csv_fields(REDLINE_FIELDS, reader)\nfor row in reader:\ndt = parser.parse(row['Timestamp'])\ntimestamp = int(time.mktime(dt.timetuple())) * 1000\n@@ -202,13 +214,13 @@ def read_and_validate_redline(file_handle):\ntag = row['Tag']\nrow_to_yield = {}\n- row_to_yield[\"message\"] = summary\n- row_to_yield[\"timestamp\"] = timestamp\n- row_to_yield[\"datetime\"] = dt_iso_format\n- row_to_yield[\"timestamp_desc\"] = timestamp_desc\n- row_to_yield[\"alert\"] = alert #extra field\n+ row_to_yield['message'] = summary\n+ row_to_yield['timestamp'] = timestamp\n+ row_to_yield['datetime'] = dt_iso_format\n+ row_to_yield['timestamp_desc'] = timestamp_desc\ntags = [tag]\n- row_to_yield[\"tag\"] = tags # extra field\n+ row_to_yield['alert'] = alert # Extra field\n+ row_to_yield['tag'] = tags # Extra field\nyield row_to_yield\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/utils_test.py",
"new_path": "timesketch/lib/utils_test.py",
"diff": "@@ -20,6 +20,12 @@ import re\nfrom timesketch.lib.testlib import BaseTest\nfrom timesketch.lib.utils import get_validated_indices\nfrom timesketch.lib.utils import random_color\n+from timesketch.lib.utils import read_and_validate_csv\n+\n+TEST_CSV = \"test_tools/test_events/sigma_events.csv\"\n+ISO8601_REGEX = r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[' \\\n+ r'1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][' \\\n+ r'0-9])(\\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$'\nclass TestUtils(BaseTest):\n@@ -37,9 +43,21 @@ class TestUtils(BaseTest):\nvalid_indices = ['test']\ninvalid_indices = ['test', 'fail']\n-\ntest_indices, _ = get_validated_indices(valid_indices, sketch)\nself.assertListEqual(sketch_indices, test_indices)\ntest_indices, _ = get_validated_indices(invalid_indices, sketch)\nself.assertFalse('fail' in test_indices)\n+\n+ def test_header_validation(self):\n+ \"\"\"Test for Timesketch header validation.\"\"\"\n+ mandatory_fields = ['message', 'datetime', 'fortytwo']\n+ with self.assertRaises(RuntimeError):\n+ # Call next to work around lazy generators.\n+ next(read_and_validate_csv(TEST_CSV, ',', mandatory_fields))\n+\n+ def test_date_normalisation(self):\n+ \"\"\"Test for ISO date compliance.\"\"\"\n+ data_generator = read_and_validate_csv(TEST_CSV)\n+ for row in data_generator:\n+ self.assertRegex(row['datetime'], ISO8601_REGEX)\n"
}
] | Python | Apache License 2.0 | google/timesketch | Replaced the use of the csv library in import task to use pandas (for csv/json data ingestion) (#1534) |
263,096 | 26.02.2021 15:51:41 | -3,600 | 9265d81b530c1fcda1465ce013ade27bd9338f9a | Fixed couple of bugs in the sigma API and API Client | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma.py",
"new_path": "api_client/python/timesketch_api_client/sigma.py",
"diff": "@@ -161,7 +161,6 @@ class Sigma(resource.BaseResource):\nfor key, value in self.resource_data.items():\nself.set_value(key, value)\n-\ndef from_text(self, rule_text):\n\"\"\"Get a Sigma object from a rule text.\n@@ -173,11 +172,10 @@ class Sigma(resource.BaseResource):\n\"\"\"\nself.resource_uri = '{0:s}/sigma/text/'.format(self.api.api_root)\ndata = {'title': 'Get_Sigma_by_text', 'content': rule_text}\n- response = self.api.session.post(self.resource_uri, data=data)\n+ response = self.api.session.post(self.resource_uri, json=data)\nresponse_dict = error.get_response_json(response, logger)\nobjects = response_dict.get('objects')\n-\nif not objects:\nlogger.warning(\n'Unable to parse rule with given text')\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/sigma.py",
"new_path": "timesketch/api/v1/resources/sigma.py",
"diff": "@@ -58,7 +58,7 @@ class SigmaListResource(resources.ResourceMixin, Resource):\n# TODO: idea for meta: add a list of folders that have been parsed\nmeta = {'current_user': current_user.username,\n'rules_count': len(sigma_rules)}\n- return jsonify({'objects': [sigma_rules], 'meta': meta})\n+ return jsonify({'objects': sigma_rules, 'meta': meta})\nclass SigmaResource(resources.ResourceMixin, Resource):\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources_test.py",
"new_path": "timesketch/api/v1/resources_test.py",
"diff": "@@ -395,7 +395,7 @@ class SigmaListResourceTest(BaseTest):\n'meta': {\n'current_user': 'test1', 'rules_count': 1\n},\n- 'objects':[[{\n+ 'objects':[{\n'author': 'Alexander Jaeger',\n'date': '2020/06/26',\n'description': 'Detects suspicious installation of Zenmap',\n@@ -420,7 +420,7 @@ class SigmaListResourceTest(BaseTest):\n'https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html'\n],\n'title': 'Suspicious Installation of Zenmap'\n- }]]}\n+ }]}\ndef test_get_sigma_rule_list(self):\nself.login()\nresponse = self.client.get(self.resource_url)\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed couple of bugs in the sigma API and API Client (#1646) |
263,096 | 28.02.2021 14:32:12 | -3,600 | fc3417c0a34c0c4bc87ac6ac7fbf0355d419ddb7 | Changed docker config: e2e / dev Sigma directory was not created before | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/docker-entrypoint.sh",
"new_path": "docker/dev/build/docker-entrypoint.sh",
"diff": "@@ -15,7 +15,7 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\nln -s /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/sigma_config.yaml\nmkdir /etc/timesketch/data\n- ln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/data/sigma/\n+ ln -s /usr/local/src/timesketch/data/sigma/ /etc/timesketch/data/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/e2e/Dockerfile",
"new_path": "docker/e2e/Dockerfile",
"diff": "@@ -40,6 +40,8 @@ RUN cp /tmp/timesketch/data/tags.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/plaso.mappings /etc/timesketch/\nRUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\n+RUN mkdir /etc/timesketch/data\n+RUN cp -r /tmp/timesketch/data/sigma /etc/timesketch/data/\n# Copy the entrypoint script into the container\nCOPY docker/e2e/docker-entrypoint.sh /\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changed docker config: e2e / dev Sigma directory was not created before (#1650) |
263,135 | 28.02.2021 15:06:31 | -3,600 | f52747c0e9e419234f8ed6c7f55ff8325f84a73f | Added the ability to use elasticsearch with SSL but without username/password authentication. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -89,10 +89,15 @@ class ElasticsearchDataStore(object):\nself.verify = current_app.config.get('ELASTIC_VERIFY_CERTS', True)\nif self.ssl:\n- self.client = Elasticsearch([{'host': host, 'port': port}],\n+ if self.user and self.password:\n+ self.client = Elasticsearch(\n+ [{'host': host, 'port': port}],\nhttp_auth=(self.user, self.password),\n- use_ssl=self.ssl,\n- verify_certs=self.verify)\n+ use_ssl=self.ssl, verify_certs=self.verify)\n+ else:\n+ self.client = Elasticsearch(\n+ [{'host': host, 'port': port}],\n+ use_ssl=self.ssl, verify_certs=self.verify)\nelse:\nself.client = Elasticsearch([{'host': host, 'port': port}])\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added the ability to use elasticsearch with SSL but without username/password authentication. (#1645) |
263,096 | 28.02.2021 18:59:17 | -3,600 | 81f91a898ea28fc57f00a33d1f94b5c22b00fc0e | Fixed few minor checks in sigma libraries where unittests did not reflect the reality | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma.py",
"new_path": "api_client/python/timesketch_api_client/sigma.py",
"diff": "@@ -158,7 +158,12 @@ class Sigma(resource.BaseResource):\napi=self.api, resource_uri=self.resource_uri)\nself.lazyload_data(refresh_cache=True)\n- for key, value in self.resource_data.items():\n+ objects = self.data.get('objects')\n+ if not objects:\n+ logger.error('Unable to parse rule with given text')\n+ raise ValueError('No rules found.')\n+ rule_dict = objects[0]\n+ for key, value in rule_dict.items():\nself.set_value(key, value)\ndef from_text(self, rule_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": "@@ -276,6 +276,11 @@ def mock_response(*args, **kwargs):\n}\nsigma_rule = {\n+ 'meta': {\n+ 'parsed': True\n+ },\n+ 'objects':[\n+ {\n'title': 'Suspicious Installation of Zenmap',\n'id': '5266a592-b793-11ea-b3de-0242ac130004',\n'description': 'Detects suspicious installation of Zenmap',\n@@ -296,7 +301,8 @@ def mock_response(*args, **kwargs):\n'file_name': 'lnx_susp_zenmap',\n'file_relpath' : '/linux/syslog/foobar/'\n}\n-\n+ ]\n+ }\nsigma_rule_text_mock = {\n'meta': {\n'parsed': True\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/sigma.py",
"new_path": "timesketch/api/v1/resources/sigma.py",
"diff": "@@ -84,7 +84,6 @@ class SigmaResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\n'OS Error, unable to get the path to the Sigma rules')\n-\nfor rule in sigma_rules:\nif rule is not None:\nif rule_uuid == rule.get('id'):\n@@ -96,7 +95,7 @@ class SigmaResource(resources.ResourceMixin, Resource):\nmeta = {'current_user': current_user.username,\n'rules_count': len(sigma_rules)}\n- return jsonify({'objects': return_rule, 'meta': meta})\n+ return jsonify({'objects': [return_rule], 'meta': meta})\nclass SigmaByTextResource(resources.ResourceMixin, Resource):\n@@ -114,14 +113,6 @@ class SigmaByTextResource(resources.ResourceMixin, Resource):\nif not form:\nform = request.data\n- action = form.get('action', '')\n-\n- # TODO: that can eventually go away since there are no other actions\n- if action != 'post':\n- return abort(\n- HTTP_STATUS_CODE_BAD_REQUEST,\n- 'Action needs to be \"post\"')\n-\ncontent = form.get('content')\nif not content:\nreturn abort(\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources_test.py",
"new_path": "timesketch/api/v1/resources_test.py",
"diff": "@@ -489,7 +489,7 @@ class SigmaByTextResourceTest(BaseTest):\n\"\"\"Authenticated request to get an sigma rule by text.\"\"\"\nself.login()\n- data = dict(action='post', content=self.correct_rule)\n+ data = dict(content=self.correct_rule)\nresponse = self.client.post(\nself.resource_url,\ndata=json.dumps(data, ensure_ascii=False),\n@@ -500,7 +500,7 @@ class SigmaByTextResourceTest(BaseTest):\nself.assert200(response)\n# wrong sigma rule\n- data = dict(action='post', content='foobar: asd')\n+ data = dict(content='foobar: asd')\nresponse = self.client.post(\nself.resource_url,\ndata=json.dumps(data, ensure_ascii=False),\n@@ -510,17 +510,6 @@ class SigmaByTextResourceTest(BaseTest):\nself.assertIn('No detection definitions found', data['message'])\nself.assertEqual(response.status_code, HTTP_STATUS_CODE_BAD_REQUEST)\n- # wrong action\n- data = dict(action='get', content=self.correct_rule)\n- response = self.client.post(\n- self.resource_url,\n- data=json.dumps(data, ensure_ascii=False),\n- content_type='application/json')\n- data = json.loads(response.get_data(as_text=True))\n-\n- self.assertIn('Action needs to be \"post\"', data['message'])\n- self.assertEqual(response.status_code, HTTP_STATUS_CODE_BAD_REQUEST)\n-\n# no content given\ndata = dict(action='post')\nresponse = self.client.post(\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed few minor checks in sigma libraries where unittests did not reflect the reality (#1647) |
263,096 | 28.02.2021 23:35:49 | -3,600 | da936fafe36dd0d950bfe34af235f3bd5441f87c | Fixed some lint issues in the the e2e Docker readme file | [
{
"change_type": "MODIFY",
"old_path": "docker/e2e/README.md",
"new_path": "docker/e2e/README.md",
"diff": "Timesketch has support for Docker. This is a convenient way of getting up and running.\nNOTE: Windows based host systems are not supported at this time.\n-### Install Docker\n+## Install Docker\n+\nFollow the official instructions [here](https://www.docker.com/community-edition)\n-### Install Docker Compose\n+## Install Docker Compose\n+\nFollow the official instructions [here](https://docs.docker.com/compose/install/)\n-### Clone Timesketch\n+## Clone Timesketch\n```shell\ngit clone https://github.com/google/timesketch.git\ncd timesketch\n```\n-### Verify the Kernel Settings\n+\n+## Verify the Kernel Settings\n+\nFollow the official instructions [here](https://www.elastic.co/guide/en/elasticsearch/reference/6.4/docker.html#docker-cli-run-prod-mode)\n-### Build and Start Containers\n+## Build and Start Containers\n```shell\ncd docker/e2e\nsudo docker-compose up\n```\n-### Access Timesketch\n+## Access Timesketch\n+\n* Retrieve the randomly generated password from startup logs: `TIMESKETCH_PASSWORD set randomly to: xxx`\n* Go to: http://127.0.0.1/\n* Login with username: admin and the retrieved random password\n-### Test your installation\n+## Test your installation\n+\n1. You can now create your first sketch by pressing the green button on the middle of the page\n2. Add the test timeline under the [Timeline](http://127.0.0.1:5000/sketch/1/timelines/) tab in your new sketch\n3. Go to http://127.0.0.1:5000/explore/ and have fun exploring!\n-### Where is my data stored?\n+## Where is my data stored?\n+\nThe timesketch docker config is set to write all data to the host filesystem, not the containers. This is accomplished with docker [volumes](https://docs.docker.com/engine/admin/volumes/volumes/) that map to the following locations:\n-- elasticsearch: /var/lib/elasticsearch\n-- postgres: /var/lib/postgresql\n-- redis: /var/lib/redis\n+* elasticsearch: /var/lib/elasticsearch\n+* postgres: /var/lib/postgresql\n+* redis: /var/lib/redis\n-#### Mac\n+### Mac\nOn mac, you can set up the shares as following\n@@ -56,7 +63,3 @@ sudo chown `whoami` /var/lib/redis\n```\nThese locations on the host filesystem can be backed with any storage mechanism to persist sketch data beyond the container lifetimes.\n-\n-\n-\n-\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed some lint issues in the the e2e Docker readme file (#1653) |
263,133 | 01.03.2021 12:43:46 | 0 | 78efda91972e72832e1e0f5cbe730562f4873a95 | Added search templates to API and API client | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/error.py",
"new_path": "api_client/python/timesketch_api_client/error.py",
"diff": "@@ -92,7 +92,8 @@ def get_response_json(response, logger):\ntry:\nreturn response.json()\nexcept json.JSONDecodeError as e:\n- logger.error('Unable to decode response: {0!s}'.format(e))\n+ logger.error(\n+ 'Unable to decode response: {0!s}'.format(e), exc_info=True)\nreturn {}\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/resource.py",
"new_path": "api_client/python/timesketch_api_client/resource.py",
"diff": "@@ -160,6 +160,11 @@ class SketchResource(BaseResource):\n\"\"\"Property that returns a list of the resource labels.\"\"\"\nreturn self._labels\n+ @property\n+ def sketch(self):\n+ \"\"\"Property that returns the sketch object.\"\"\"\n+ return self._sketch\n+\n@property\ndef table(self):\n\"\"\"Property that returns a pandas DataFrame.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/search.py",
"new_path": "api_client/python/timesketch_api_client/search.py",
"diff": "@@ -20,6 +20,7 @@ import pandas\nfrom . import error\nfrom . import resource\n+from . import searchtemplate\nlogger = logging.getLogger('timesketch_api.search')\n@@ -634,7 +635,7 @@ class Search(resource.SketchResource):\nself.query_filter = query_filter\nself._query_string = query_string\n- self._query_dsl = query_dsl\n+ self.query_dsl = query_dsl\nself._return_fields = return_fields\nif max_entries:\n@@ -887,8 +888,12 @@ class Search(resource.SketchResource):\ndef save(self):\n\"\"\"Save the search in the database.\n+ Returns:\n+ String with the identification of the saved search.\n+\nRaises:\nValueError: if there are values missing in order to save the query.\n+ RuntimeError: if the search could not be saved.\n\"\"\"\nif not self.name:\nraise ValueError(\n@@ -944,6 +949,24 @@ class Search(resource.SketchResource):\nself._resource_id = search_dict.get('id', 0)\nreturn f'Saved search to ID: {self._resource_id}'\n+ def save_as_template(self):\n+ \"\"\"Save the search as a search template.\n+\n+ Returns:\n+ A search template object (searchtemplate.SearchTemplate).\n+ \"\"\"\n+ if not self._resource_id:\n+ logger.warning('Search has not been saved first, saving now.')\n+ return_string = self.save()\n+ logger.info(return_string)\n+\n+ template = searchtemplate.SearchTemplate(self.api)\n+ template.from_search_object(self)\n+\n+ print(template.save())\n+ self._searchtemplate = template.id\n+ return template\n+\n@property\ndef scrolling(self):\n\"\"\"Returns whether scrolling is enabled or not.\"\"\"\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": "@@ -28,6 +28,7 @@ from . import error\nfrom . import graph\nfrom . import resource\nfrom . import search\n+from . import searchtemplate\nfrom . import story\nfrom . import timeline\n@@ -925,6 +926,28 @@ class Sketch(resource.BaseResource):\nreturn searches\n+ def list_search_templates(self):\n+ \"\"\"Get a list of all search templates that are available.\n+\n+ Returns:\n+ List of searchtemplate.SearchTemplate object instances.\n+ \"\"\"\n+ response = self.api.fetch_resource_data('searchtemplate/')\n+ objects = response.get('objects', [])\n+ if not objects:\n+ return []\n+\n+ template_dicts = objects[0]\n+\n+ template_list = []\n+ for template_dict in template_dicts:\n+ template_obj = searchtemplate.SearchTemplate(api=self.api)\n+ template_obj.from_saved(template_dict.get('id'), sketch_id=self.id)\n+\n+ template_list.append(template_obj)\n+\n+ return template_list\n+\ndef list_timelines(self):\n\"\"\"List all timelines for this sketch.\n@@ -1135,6 +1158,13 @@ class Sketch(resource.BaseResource):\nIf the analyzer runs successfully return back an AnalyzerResult\nobject.\n\"\"\"\n+ # TODO: Deprecate this function.\n+ logger.warning(\n+ 'This function is about to be deprecated, please use the '\n+ '`.run_analyzer()` function of a timeline object instead. '\n+ 'This function does not support all functionality of the newer '\n+ 'implementation in the timeline object.')\n+\nif self.is_archived():\nraise error.UnableToRunAnalyzer(\n'Unable to run an analyzer on an archived sketch.')\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/timeline.py",
"new_path": "api_client/python/timesketch_api_client/timeline.py",
"diff": "@@ -81,6 +81,17 @@ class Timeline(resource.BaseResource):\nself._color = timeline['objects'][0]['color']\nreturn self._color\n+ @property\n+ def data_sources(self):\n+ \"\"\"Property that returns the timeline data sources.\"\"\"\n+ data = self.lazyload_data(refresh_cache=True)\n+ objects = data.get('objects', [])\n+ if not objects:\n+ return []\n+\n+ timeline_data = objects[0]\n+ return timeline_data.get('datasources', [])\n+\n@property\ndef description(self):\n\"\"\"Property that returns timeline description.\n@@ -181,8 +192,7 @@ class Timeline(resource.BaseResource):\nerror.UnableToRunAnalyzer: if not able to run the analyzer.\nReturns:\n- If the analyzer runs successfully return back an AnalyzerResult\n- object.\n+ A list of AnalyzerResult objects.\n\"\"\"\nif self.is_archived():\nraise error.UnableToRunAnalyzer(\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210217'\n+__version__ = '20210226'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/searchtemplate.py",
"new_path": "timesketch/api/v1/resources/searchtemplate.py",
"diff": "# limitations under the License.\n\"\"\"SearchTemplate resources for version 1 of the Timesketch API.\"\"\"\n+import json\n+\nfrom flask import abort\n+from flask import request\nfrom flask_restful import Resource\n+from flask_login import current_user\nfrom flask_login import login_required\nfrom timesketch.api.v1 import resources\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_BAD_REQUEST\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n+from timesketch.lib.definitions import HTTP_STATUS_CODE_OK\n+\n+from timesketch.models import db_session\nfrom timesketch.models.sketch import SearchTemplate\n+from timesketch.models.sketch import Sketch\n+from timesketch.models.sketch import View\nclass SearchTemplateResource(resources.ResourceMixin, Resource):\n@@ -36,9 +47,39 @@ class SearchTemplateResource(resources.ResourceMixin, Resource):\nSearch template in JSON (instance of flask.wrappers.Response)\n\"\"\"\nsearchtemplate = SearchTemplate.query.get(searchtemplate_id)\n+\n+ meta = {'sketch_ids': []}\n+ saved_searches = View.query.filter_by(\n+ searchtemplate=searchtemplate)\n+ for saved_search in saved_searches:\n+ meta['sketch_ids'].append(saved_search.id)\n+\nif not searchtemplate:\nabort(HTTP_STATUS_CODE_NOT_FOUND, 'Search template was not found')\n- return self.to_json(searchtemplate)\n+ return self.to_json(searchtemplate, meta=meta)\n+\n+ @login_required\n+ def delete(self, searchtemplate_id):\n+ \"\"\"Handles DELETE request to the resource.\n+\n+ Args:\n+ searchtemplate_id: Primary key for a search template database model\n+\n+ Returns:\n+ HTTP status 200 if successful, otherwise error messages.\n+ \"\"\"\n+ searchtemplate = SearchTemplate.query.get(searchtemplate_id)\n+ if not searchtemplate:\n+ abort(HTTP_STATUS_CODE_NOT_FOUND, 'Search template was not found')\n+\n+ saved_searches = View.query.filter_by(searchtemplate=searchtemplate)\n+ for saved_search in saved_searches:\n+ saved_search.searchtemplate = None\n+\n+ db_session.delete(searchtemplate)\n+ db_session.commit()\n+\n+ return HTTP_STATUS_CODE_OK\nclass SearchTemplateListResource(resources.ResourceMixin, Resource):\n@@ -51,4 +92,93 @@ class SearchTemplateListResource(resources.ResourceMixin, Resource):\nReturns:\nView in JSON (instance of flask.wrappers.Response)\n\"\"\"\n- return self.to_json(SearchTemplate.query.all())\n+ templates = SearchTemplate.query.all()\n+ meta = {\n+ 'collection': []\n+ }\n+ for template in templates:\n+ saved_searches = View.query.filter_by(\n+ searchtemplate=template)\n+ for saved_search in saved_searches:\n+ data = {\n+ 'search_id': saved_search.id,\n+ 'template_id': template.id,\n+ 'sketch_id': saved_search.sketch.id\n+ }\n+ meta['collection'].append(data)\n+\n+ return self.to_json(templates, meta=meta)\n+\n+ @login_required\n+ def post(self):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ View in JSON (instance of flask.wrappers.Response)\n+ \"\"\"\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ search_id = form.get('search_id')\n+ if not search_id:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to save the searchtemplate, the saved search ID is '\n+ 'missing.')\n+\n+ search_obj = View.query.get(search_id)\n+ if not search_obj:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No search found with this ID.')\n+\n+ templates = SearchTemplate.query.filter_by(\n+ name=search_obj.name,\n+ description=search_obj.description).all()\n+\n+ if templates:\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'This search has already been saved as a template.')\n+\n+ sketch = Sketch.query.get_with_acl(search_obj.sketch.id)\n+ if not sketch:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\n+ if not sketch.has_permission(current_user, 'read'):\n+ abort(HTTP_STATUS_CODE_FORBIDDEN,\n+ 'User does not have read access controls on sketch.')\n+\n+ if sketch.get_status.status == 'archived':\n+ abort(\n+ HTTP_STATUS_CODE_BAD_REQUEST,\n+ 'Unable to query on an archived sketch.')\n+\n+ # Remove date filter chips from the saved search.\n+ query_filter_dict = json.loads(search_obj.query_filter)\n+ chips = []\n+ for chip in query_filter_dict.get('chips', []):\n+ chip_type = chip.get('type', '')\n+ if not chip_type.startswith('datetime'):\n+ chips.append(chip)\n+\n+ query_filter_dict['chips'] = chips\n+ query_filter = json.dumps(query_filter_dict, ensure_ascii=False)\n+\n+ searchtemplate = SearchTemplate(\n+ name=search_obj.name,\n+ description=search_obj.description,\n+ user=current_user,\n+ query_string=search_obj.query_string,\n+ query_filter=query_filter,\n+ query_dsl=search_obj.query_dsl)\n+\n+ db_session.add(searchtemplate)\n+ db_session.commit()\n+\n+ search_obj.searchtemplate = searchtemplate\n+ db_session.add(search_obj)\n+ db_session.commit()\n+\n+ return self.to_json(searchtemplate)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -379,7 +379,6 @@ class SearchTemplate(AccessControlMixin, LabelMixin, StatusMixin, CommentMixin,\n'exclude': [],\n'indices': '_all',\n'terminate_after': 40,\n- 'from': 0,\n'order': 'asc',\n'size': '40'\n}\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added search templates to API and API client (#1643) |
263,133 | 01.03.2021 13:43:39 | 0 | be9f516eb92ae2d99b380aa7b1894a0eac83e2db | Forgot to include the `searchtemplate.py` file in the last PR | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "api_client/python/timesketch_api_client/searchtemplate.py",
"diff": "+# Copyright 2021 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 search template object.\"\"\"\n+\n+import logging\n+\n+from . import error\n+from . import resource\n+from . import search\n+\n+\n+logger = logging.getLogger('timesketch_api.searchtemplate')\n+\n+\n+class SearchTemplate(resource.BaseResource):\n+ \"\"\"Search template object. TEST e2e\"\"\"\n+\n+ def __init__(self, api):\n+ \"\"\"Initialize the search template object.\"\"\"\n+ super().__init__(api, 'searchtemplate/')\n+ self._description = ''\n+ self._name = ''\n+ self._resource_id = None\n+ self._search_id = None\n+ self._sketch_id = None\n+\n+ @property\n+ def description(self):\n+ \"\"\"Property that returns the template description.\"\"\"\n+ if self._description:\n+ return self._description\n+\n+ if not self._resource_id:\n+ logger.error('No resource ID, have you loaded the template yet?')\n+ raise ValueError('Unable to get a name, not loaded yet.')\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects')\n+ if not objects:\n+ return 'No description'\n+\n+ self._description = objects[0].get('description', 'N/A')\n+ return self._description\n+\n+ def delete(self):\n+ \"\"\"Deletes the saved graph from the store.\"\"\"\n+ if not self._resource_id:\n+ raise ValueError(\n+ 'Unable to delete the search template, since the template '\n+ 'does not seem to be saved, which is required.')\n+\n+ resource_url = (\n+ f'{self.api.api_root}/searchtemplate/{self._resource_id}/')\n+ response = self.api.session.delete(resource_url)\n+ return error.check_return_status(response, logger)\n+\n+ def from_saved(self, template_id, sketch_id=0):\n+ \"\"\"Initialize the search template from a saved template, by ID value.\n+\n+ Args:\n+ template_id: integer value for the saved search template.\n+ sketch_id: optional integer value for a sketch ID. If not\n+ provided, an attempt is made to figure it out.\n+\n+ Raises:\n+ ValueError: If issues came up during processing.\n+ \"\"\"\n+ self._resource_id = template_id\n+ self.resource_uri = f'searchtemplate/{self._resource_id}/'\n+\n+ if sketch_id:\n+ self._sketch_id = sketch_id\n+ else:\n+ data = self.lazyload_data(refresh_cache=True)\n+ meta = data.get('meta', {})\n+ sketch_ids = meta.get('sketch_ids', [])\n+ if len(sketch_ids) > 1:\n+ sketch_string = ', '.join(sketch_ids)\n+ raise ValueError(\n+ 'Search template has too many attached saved searches, '\n+ 'please pick one from: {0:s}'.format(sketch_string))\n+ self._sketch_id = sketch_ids[0]\n+\n+ def from_search_object(self, search_obj):\n+ \"\"\"Initialize template from a search object.\n+\n+ Args:\n+ search_obj (search.Search): a search object.\n+ \"\"\"\n+ self._search_id = search_obj.id\n+ self._sketch_id = search_obj.sketch.id\n+\n+ response = self.api.fetch_resource_data('searchtemplate/')\n+ meta = response.get('meta', {})\n+ template_id = 0\n+ for data in meta.get('collection', []):\n+ if data.get('search_id') == self._search_id:\n+ template_id = data.get('template_id', 0)\n+\n+ if not template_id:\n+ return\n+\n+ self._resource_id = template_id\n+ self.resource_uri = f'searchtemplate/{self._resource_id}/'\n+\n+ @property\n+ def id(self):\n+ \"\"\"Property that returns back the search template ID.\"\"\"\n+ return self._resource_id\n+\n+ @property\n+ def name(self):\n+ \"\"\"Property that returns the template name.\"\"\"\n+ if self._name:\n+ return self._name\n+\n+ if not self._resource_id:\n+ logger.error('No resource ID, have you loaded the template yet?')\n+ raise ValueError('Unable to get a name, not loaded yet.')\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects')\n+ if not objects:\n+ return 'No name'\n+\n+ self._name = objects[0].get('name', 'N/A')\n+ return self._name\n+\n+ def set_sketch(self, sketch=None, sketch_id=None):\n+ \"\"\"Set the sketch for the search template.\n+\n+ Args:\n+ sketch (sketch.Sketch): an optional sketch object to use as the\n+ sketch object for the search template.\n+ sketch_id (int): an optional sketch ID to use as the sketch ID\n+ for the search template.\n+\n+ Raises:\n+ ValueError: If neither a sketch nor a sketch ID is set.\n+ \"\"\"\n+ if not sketch and not sketch_id:\n+ raise ValueError('Either sketch or sketch ID needs to be set.')\n+\n+ if sketch:\n+ self._sketch_id = sketch\n+ elif isinstance(sketch_id, int):\n+ self._sketch_id = sketch_id\n+ else:\n+ raise ValueError(\n+ 'Sketch needs to be set, or an integer value for '\n+ 'a sketch ID.')\n+\n+ def save(self):\n+ \"\"\"Save the search template.\"\"\"\n+ if self._resource_id:\n+ raise ValueError(\n+ 'The template has already been saved, ATM updates to an '\n+ 'existing template are not yet supported.')\n+\n+ if not self._search_id:\n+ raise ValueError(\n+ 'Unable to save the search template since the identification '\n+ 'value of the saved search is not known. The object needs '\n+ 'to be initialized from a previously saved search.')\n+\n+ data = {\n+ 'search_id': self._search_id,\n+ }\n+ resource_url = f'{self.api.api_root}/searchtemplate/'\n+ response = self.api.session.post(resource_url, json=data)\n+\n+ status = error.check_return_status(response, logger)\n+ if not status:\n+ error.error_message(\n+ response, 'Unable to save search as a template',\n+ error=RuntimeError)\n+\n+ response_json = error.get_response_json(response, logger)\n+ template_dict = response_json.get('objects', [{}])[0]\n+\n+ self._resource_id = template_dict.get('id', 0)\n+ self.resource_uri = f'searchtemplate/{self._resource_id}/'\n+ return f'Saved search as a template to ID: {self.id}'\n+\n+ def to_search(self):\n+ \"\"\"Returns a search object from a template.\"\"\"\n+ if not self._resource_id:\n+ raise ValueError(\n+ 'Unable to get a search object unless it is tied to a '\n+ 'template.')\n+\n+ if not self._sketch_id:\n+ raise ValueError(\n+ 'Unable to get a search object unless it is tied to '\n+ 'a sketch.')\n+\n+ data = self.lazyload_data(refresh_cache=True)\n+ objects = data.get('objects')\n+ if not objects:\n+ raise ValueError(\n+ 'Unable to get search object, issue with retrieving '\n+ 'template data.')\n+\n+ template_dict = objects[0]\n+ sketch = self.api.get_sketch(self._sketch_id)\n+\n+ search_obj = search.Search(sketch=sketch)\n+ search_obj.from_manual(\n+ query_string=template_dict.get('query_string'),\n+ query_dsl=template_dict.get('query_dsl'),\n+ query_filter=template_dict.get('query_filter'))\n+ search_obj.name = template_dict.get('name', 'No Name')\n+ search_obj.description = template_dict.get(\n+ 'description', 'No Description')\n+ return search_obj\n"
}
] | Python | Apache License 2.0 | google/timesketch | Forgot to include the `searchtemplate.py` file in the last PR (#1655) |
263,133 | 03.03.2021 13:01:30 | 0 | c0e575550690bc4e4c59e8a0fd5c2ee42cea88f1 | Cleaned up some of the API code. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/index.py",
"new_path": "api_client/python/timesketch_api_client/index.py",
"diff": "@@ -42,9 +42,9 @@ class SearchIndex(resource.BaseResource):\nself.id = searchindex_id\nself._labels = []\nself._searchindex_name = searchindex_name\n- self._resource_uri = 'searchindices/{0:d}'.format(self.id)\n+ resource_uri = f'searchindices/{self.id}'\nsuper().__init__(\n- api=api, resource_uri=self._resource_uri)\n+ api=api, resource_uri=resource_uri)\ndef _get_object_dict(self):\n\"\"\"Returns the object dict from the resources dict.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma.py",
"new_path": "api_client/python/timesketch_api_client/sigma.py",
"diff": "@@ -154,8 +154,6 @@ class Sigma(resource.BaseResource):\n\"\"\"\nself.resource_uri = f'sigma/rule/{rule_uuid}'\n- super().__init__(\n- api=self.api, resource_uri=self.resource_uri)\nself.lazyload_data(refresh_cache=True)\nobjects = self.data.get('objects')\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": "@@ -23,7 +23,6 @@ import pandas\nfrom . import analyzer\nfrom . import aggregation\n-from . import definitions\nfrom . import error\nfrom . import graph\nfrom . import resource\n@@ -33,7 +32,6 @@ from . import story\nfrom . import timeline\n-logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO'))\nlogger = logging.getLogger('timesketch_api.sketch')\n@@ -48,8 +46,6 @@ class Sketch(resource.BaseResource):\napi: An instance of TimesketchApi object.\n\"\"\"\n- DEFAULT_SIZE_LIMIT = 10000\n-\ndef __init__(self, sketch_id, api, sketch_name=None):\n\"\"\"Initializes the Sketch object.\n@@ -62,60 +58,7 @@ class Sketch(resource.BaseResource):\nself.api = api\nself._archived = None\nself._sketch_name = sketch_name\n- self._resource_uri = 'sketches/{0:d}'.format(self.id)\n- super().__init__(api=api, resource_uri=self._resource_uri)\n-\n- def _build_pandas_dataframe(self, search_response, return_fields=None):\n- \"\"\"Return a Pandas DataFrame from a query result dict.\n-\n- Args:\n- search_response: dictionary with query results.\n- return_fields: List of fields that should be included in the\n- response. Optional and defaults to None.\n-\n- Returns:\n- pandas DataFrame with the results.\n- \"\"\"\n- return_list = []\n- timelines = {}\n- for timeline_obj in self.list_timelines():\n- timelines[timeline_obj.index] = timeline_obj.name\n-\n- return_field_list = []\n- if return_fields:\n- if return_fields.startswith('\\''):\n- return_fields = return_fields[1:]\n- if return_fields.endswith('\\''):\n- return_fields = return_fields[:-1]\n- return_field_list = return_fields.split(',')\n-\n- for result in search_response.get('objects', []):\n- source = result.get('_source', {})\n- if not return_fields or '_id' in return_field_list:\n- source['_id'] = result.get('_id')\n- if not return_fields or '_type' in return_field_list:\n- source['_type'] = result.get('_type')\n- if not return_fields or '_index' in return_field_list:\n- source['_index'] = result.get('_index')\n- if not return_fields or '_source' in return_field_list:\n- source['_source'] = timelines.get(result.get('_index'))\n-\n- return_list.append(source)\n-\n- data_frame = pandas.DataFrame(return_list)\n- if 'datetime' in data_frame:\n- try:\n- data_frame['datetime'] = pandas.to_datetime(data_frame.datetime)\n- except pandas.errors.OutOfBoundsDatetime:\n- pass\n- elif 'timestamp' in data_frame:\n- try:\n- data_frame['datetime'] = pandas.to_datetime(\n- data_frame.timestamp / 1e6, utc=True, unit='s')\n- except pandas.errors.OutOfBoundsDatetime:\n- pass\n-\n- return data_frame\n+ super().__init__(api=api, resource_uri=f'sketches/{self.id}')\n@property\ndef acl(self):\n@@ -212,7 +155,7 @@ class Sketch(resource.BaseResource):\n@property\ndef my_acl(self):\n\"\"\"Property that returns back the ACL for the current user.\"\"\"\n- data = self.lazyload_data()\n+ data = self.lazyload_data(refresh_cache=True)\nobjects = data.get('objects')\nif not objects:\nreturn []\n@@ -261,8 +204,24 @@ class Sketch(resource.BaseResource):\nReturns:\nSketch status as string.\n\"\"\"\n- sketch = self.lazyload_data()\n- return sketch['objects'][0]['status'][0]['status']\n+ data = self.lazyload_data(refresh_cache=True)\n+ objects = data.get('objects')\n+ if not objects:\n+ return 'Unknown'\n+\n+ if not isinstance(objects, (list, tuple)):\n+ return 'Unknown'\n+\n+ first_object = objects[0]\n+ status_list = first_object.get('status')\n+\n+ if not status_list:\n+ return 'Unknown'\n+\n+ if len(status_list) < 1:\n+ return 'Unknown'\n+\n+ return status_list[0].get('status', 'Unknown')\ndef add_attribute_list(self, name, values, ontology='text'):\n\"\"\"Add an attribute to the sketch.\n@@ -357,7 +316,8 @@ class Sketch(resource.BaseResource):\nstatus = error.check_return_status(response, logger)\nif not status:\n- logger.error('Unable to add the label to the sketch.')\n+ logger.error(\n+ 'Unable to add the label [{0:s}] to the sketch.'.format(label))\nreturn status\n@@ -806,6 +766,10 @@ class Sketch(resource.BaseResource):\nReturns a None if neither view_id or view_name is defined or if\nthe search does not exist.\n\"\"\"\n+ logger.warning(\n+ 'This function is about to be deprecated, use '\n+ 'get_saved_search() instead.')\n+\nreturn self.get_saved_search(search_id=view_id, search_name=view_name)\ndef get_saved_search(self, search_id=None, search_name=None):\n@@ -900,6 +864,9 @@ class Sketch(resource.BaseResource):\nReturns:\nList of search object (instance of search.Search).\n\"\"\"\n+ logger.warning(\n+ 'This function will soon be deprecated, use list_saved_searches() '\n+ 'instead.')\nreturn self.list_saved_searches()\ndef list_saved_searches(self):\n@@ -970,80 +937,44 @@ class Sketch(resource.BaseResource):\ntimelines.append(timeline_obj)\nreturn timelines\n+ # pylint: disable=unused-argument\ndef upload(self, timeline_name, file_path, index=None):\n- \"\"\"Upload a CSV, JSONL or Plaso file to the server for indexing.\n+ \"\"\"Deprecated function to upload data, does nothing.\nArgs:\ntimeline_name: Name of the resulting timeline.\nfile_path: Path to the file to be uploaded.\nindex: Index name for the ES database\n- Returns:\n- Timeline object instance.\n+ Raises:\n+ RuntimeError: If this function is used, since it has been\n+ deprecated in favor of the importer client.\n\"\"\"\n- if self.is_archived():\n- raise RuntimeError(\n- 'Unable to upload files to an archived sketch.')\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 (this function is not '\n- 'guaranteed to work)')\n-\n- resource_url = f'{self.api.api_root}/upload/'\n- files = {'file': open(file_path, 'rb')}\n- _, _, file_ending = file_path.rpartition('.')\n- data = {\n- 'name': timeline_name,\n- 'sketch_id': self.id,\n- 'label': file_ending,\n- 'index_name': index}\n-\n- response = self.api.session.post(resource_url, files=files, data=data)\n- response_dict = error.get_response_json(response, logger)\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-\n- return timeline_obj\n-\n+ message = (\n+ 'This function has been deprecated, use the CLI tool: '\n+ 'timesketch_importer: https://github.com/google/timesketch/blob/'\n+ 'master/docs/UploadData.md#using-the-importer-clie-tool or the '\n+ 'importer library: https://github.com/google/timesketch/blob/'\n+ 'master/docs/UploadDataViaAPI.md')\n+ logger.error(message)\n+ raise RuntimeError(message)\n+\n+ # pylint: disable=unused-argument\ndef add_timeline(self, searchindex):\n- \"\"\"Add timeline to sketch.\n+ \"\"\"Deprecated function to add timeline to sketch.\nArgs:\nsearchindex: SearchIndex object instance.\n- Returns:\n- Timeline object instance.\n+ Raises:\n+ RuntimeError: If this function is called.\n\"\"\"\n- if self.is_archived():\n- raise RuntimeError(\n- 'Unable to add a timeline to an archived sketch.')\n+ message = (\n+ 'This function has been deprecated, since adding already existing '\n+ 'indices to a sketch is no longer supported.')\n- resource_url = '{0:s}/sketches/{1:d}/timelines/'.format(\n- self.api.api_root, self.id)\n- form_data = {'timeline': searchindex.id}\n- response = self.api.session.post(resource_url, json=form_data)\n-\n- if response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n- error.error_message(\n- response, message='Failed adding timeline',\n- error=RuntimeError)\n-\n- response_dict = error.get_response_json(response, logger)\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+ logger.error(message)\n+ raise RuntimeError(message)\ndef explore(self,\nquery_string=None,\n@@ -1091,6 +1022,10 @@ class Sketch(resource.BaseResource):\nRuntimeError: if the query is missing needed values, or if the\nsketch is archived.\n\"\"\"\n+ logger.warning(\n+ 'Using this function is discouraged, please consider using '\n+ 'the search.Search object instead, which is more flexible.')\n+\nif not (query_string or query_filter or query_dsl or view):\nraise RuntimeError('You need to supply a query or view')\n@@ -1380,8 +1315,7 @@ class Sketch(resource.BaseResource):\nreturn None\ndef comment_event(self, event_id, index, comment_text):\n- \"\"\"\n- Adds a comment to a single event.\n+ \"\"\"Adds a comment to a single event.\nArgs:\nevent_id: id of the event\n@@ -1502,6 +1436,10 @@ class Sketch(resource.BaseResource):\nraise RuntimeError(\n'Unable to search for labels in an archived sketch.')\n+ logger.warning(\n+ 'This function will be deprecated soon. Use the search.Search '\n+ 'object instead and add a search.LabelChip to search for labels.')\n+\nquery = {\n'nested': {\n'path': 'timesketch_label',\n@@ -1632,7 +1570,7 @@ class Sketch(resource.BaseResource):\nreturn return_status\ndef export(self, file_path):\n- \"\"\"Exports the content of the story to a ZIP file.\n+ \"\"\"Exports the content of the sketch to a ZIP file.\nArgs:\nfile_path (str): a file path where the ZIP file will be saved.\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210226'\n+__version__ = '20210302'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Cleaned up some of the API code. (#1657) |
263,133 | 04.03.2021 13:12:38 | 0 | 6788356ade315873a79fabadbb51e08b860e6e2e | Made slight changes to the API client and REST API. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/config.py",
"new_path": "api_client/python/timesketch_api_client/config.py",
"diff": "@@ -478,7 +478,11 @@ def configure_missing_parameters(\nif config_assistant.missing:\n# We still have unanswered questions.\n- return configure_missing_parameters(config_assistant, token_password)\n+ return configure_missing_parameters(\n+ config_assistant=config_assistant,\n+ token_password=token_password,\n+ confirm_choices=confirm_choices,\n+ config_section=config_section)\nif confirm_choices:\n# Go through prior answered parameters.\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": "@@ -63,7 +63,7 @@ class Sketch(resource.BaseResource):\n@property\ndef acl(self):\n\"\"\"Property that returns back a ACL dict.\"\"\"\n- data = self.lazyload_data()\n+ data = self.lazyload_data(refresh_cache=True)\nobjects = data.get('objects')\nif not objects:\nreturn {}\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210302'\n+__version__ = '20210304'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -345,7 +345,14 @@ class TimelineResource(resources.ResourceMixin, Resource):\n# Check if this searchindex is used in other sketches.\nclose_index = True\nsearchindex = timeline.searchindex\n- for timeline_ in searchindex.timelines:\n+ index_name = searchindex.index_name\n+ search_indices = SearchIndex.query.filter_by(\n+ index_name=index_name).all()\n+ timelines = []\n+ for index in search_indices:\n+ timelines.extend(index.timelines)\n+\n+ for timeline_ in timelines:\nif timeline_.sketch.id != sketch.id:\nclose_index = False\nbreak\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/upload.py",
"new_path": "timesketch/api/v1/resources/upload.py",
"diff": "@@ -79,6 +79,10 @@ class UploadFileResource(resources.ResourceMixin, Resource):\nif not data_label:\ndata_label = 'generic'\n+ # Since CSV and JSON are basically the same label, we combine it here.\n+ if data_label in ('csv', 'json', 'jsonl'):\n+ data_label = 'csv_jsonl'\n+\nindices = [t.searchindex for t in sketch.active_timelines]\nfor index in indices:\nif index.has_label(data_label) and sketch.has_permission(\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/tasks.py",
"new_path": "timesketch/lib/tasks.py",
"diff": "@@ -25,6 +25,7 @@ import io\nimport json\nimport six\n+from elasticsearch.exceptions import NotFoundError\nfrom elasticsearch.exceptions import RequestError\nfrom flask import current_app\n@@ -127,6 +128,31 @@ def init_worker(**kwargs):\ndb_session.configure(bind=engine)\n+def _close_index(index_name, data_store, timeline_id):\n+ \"\"\"Helper function to close an index if it is not used somewhere else.\n+\n+ Args:\n+ index_name: String with the Elastic index name.\n+ data_store: Instance of elastic.ElasticsearchDataStore.\n+ timeline_id: ID of the timeline the index belongs to.\n+ \"\"\"\n+ indices = SearchIndex.query.filter_by(index_name=index_name).all()\n+ for index in indices:\n+ for timeline in index.timelines:\n+ if timeline.get_status.status in ('closed', 'deleted', 'archived'):\n+ continue\n+\n+ if timeline.id != timeline_id:\n+ return\n+\n+ try:\n+ data_store.client.indices.close(index=index_name)\n+ except NotFoundError:\n+ logger.error(\n+ 'Unable to close index: {0:s} - index not '\n+ 'found'.format(index_name))\n+\n+\ndef _set_timeline_status(timeline_id, status, error_msg=None):\n\"\"\"Helper function to set status for searchindex and all related timelines.\n@@ -549,11 +575,15 @@ def run_plaso(\nindex_name=index_name, doc_type=event_type, mappings=mappings)\nexcept errors.DataIngestionError as e:\n_set_timeline_status(timeline_id, status='fail', error_msg=str(e))\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nraise\nexcept (RuntimeError, ImportError, NameError, UnboundLocalError,\nRequestError) as e:\n_set_timeline_status(timeline_id, status='fail', error_msg=str(e))\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nraise\nexcept Exception as e: # pylint: disable=broad-except\n@@ -561,6 +591,8 @@ def run_plaso(\nerror_msg = traceback.format_exc()\n_set_timeline_status(timeline_id, status='fail', error_msg=error_msg)\nlogger.error('Error: {0!s}\\n{1:s}'.format(e, error_msg))\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nreturn None\nmessage = 'Index timeline [{0:s}] to index [{1:s}] (source: {2:s})'\n@@ -660,17 +692,23 @@ def run_csv_jsonl(\nexcept errors.DataIngestionError as e:\n_set_timeline_status(timeline_id, status='fail', error_msg=str(e))\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nraise\nexcept (RuntimeError, ImportError, NameError, UnboundLocalError,\nRequestError) as e:\n_set_timeline_status(timeline_id, status='fail', error_msg=str(e))\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nraise\nexcept Exception as e: # pylint: disable=broad-except\n# Mark the searchindex and timelines as failed and exit the task\nerror_msg = traceback.format_exc()\n_set_timeline_status(timeline_id, status='fail', error_msg=error_msg)\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nlogger.error('Error: {0!s}\\n{1:s}'.format(e, error_msg))\nreturn None\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/acl.py",
"new_path": "timesketch/models/acl.py",
"diff": "@@ -259,6 +259,8 @@ class AccessControlMixin(object):\nreturn_dict.setdefault(name, [])\nreturn_dict[name].append(ace.permission)\n+ return_dict['is_public'] = bool(self.is_public)\n+\nreturn return_dict\ndef get_permissions(self, permission):\n"
}
] | Python | Apache License 2.0 | google/timesketch | Made slight changes to the API client and REST API. (#1664) |
263,093 | 09.03.2021 08:05:49 | -3,600 | fa100f6d4c38d581c408ba58a9d08c0f79264a97 | Update 2021_timesketch_summit.md | [
{
"change_type": "MODIFY",
"old_path": "docs/events/2021_timesketch_summit.md",
"new_path": "docs/events/2021_timesketch_summit.md",
"diff": "@@ -24,7 +24,7 @@ Please use the [Google form](https://forms.gle/1D23n4SkoCPay1eDA) to sign up.\n## Agenda and talks\n-- Presentations: 16:00 - 18:15 UTC\n+- Presentations: 16:00 - 18:40 UTC\n- Workshops: 19:00 - 21:00 UTC\nAll times are in **UTC**\n"
}
] | Python | Apache License 2.0 | google/timesketch | Update 2021_timesketch_summit.md |
263,133 | 10.03.2021 08:28:32 | 0 | e6205eaf6576a29b369b951189e1fd338d56d008 | Added several enhancements to the importer and importer tasks. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/client.py",
"new_path": "api_client/python/timesketch_api_client/client.py",
"diff": "@@ -499,6 +499,26 @@ class TimesketchApi:\nsearchindex_id = response_dict['objects'][0]['id']\nreturn self.get_searchindex(searchindex_id), created\n+ def check_celery_status(self, job_id=''):\n+ \"\"\"Return information about outstanding celery tasks or a specific one.\n+\n+ Args:\n+ job_id (str): Optional Celery job identification string. If\n+ provided that specific job ID is queried, otherwise\n+ a check for all outstanding jobs is checked.\n+\n+ Returns:\n+ A list of dict objects with the status of the celery task/tasks\n+ that were outstanding.\n+ \"\"\"\n+ if job_id:\n+ response = self.fetch_resource_data(\n+ 'tasks/?job_id={0:s}'.format(job_id))\n+ else:\n+ response = self.fetch_resource_data('tasks/')\n+\n+ return response.get('objects', [])\n+\ndef list_searchindices(self):\n\"\"\"Get list of all searchindices that the user has access to.\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210304'\n+__version__ = '20210308'\ndef get_version():\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": "@@ -48,8 +48,12 @@ class ImportStreamer(object):\nDEFAULT_TEXT_ENCODING = 'utf-8'\nDEFAULT_TIMESTAMP_DESC = 'Time Logged'\n+ # Define the maximum amount of retries for a file/chunk upload.\n+ DEFAULT_RETRY_LIMIT = 3\n+\ndef __init__(self):\n\"\"\"Initialize the upload streamer.\"\"\"\n+ self._celery_task_id = ''\nself._count = 0\nself._config_helper = None\nself._data_label = ''\n@@ -218,15 +222,20 @@ class ImportStreamer(object):\nself._count = 0\nself._data_lines = []\n- def _upload_data_buffer(self, end_stream):\n+ def _upload_data_buffer(self, end_stream, retry_count=0):\n\"\"\"Upload data to Timesketch.\nArgs:\nend_stream: boolean indicating whether this is the last chunk of\nthe stream.\n+ retry_count: optional int that is only set if this is a retry\n+ of the upload.\n+\n+ Raises:\n+ RuntimeError: If the data buffer is not successfully uploaded.\n\"\"\"\nif not self._data_lines:\n- return\n+ return None\nstart_time = time.time()\ndata = {\n@@ -255,32 +264,49 @@ class ImportStreamer(object):\n# sleep.\ntime.sleep(2)\n- # TODO: Add in the ability to re-upload failed file.\nif response.status_code not in definitions.HTTP_STATUS_CODE_20X:\n+ if retry_count >= self.DEFAULT_RETRY_LIMIT:\nraise RuntimeError(\n'Error uploading data: [{0:d}] {1!s} {2!s}, '\n'index {3:s}'.format(\nresponse.status_code, response.reason, response.text,\nself._index))\n+ logger.warning(\n+ 'Unable to upload data buffer: {0:d}, retrying (attempt '\n+ '{1:d}/{2:d})'.format(\n+ self._chunk, retry_count + 1, self.DEFAULT_RETRY_LIMIT))\n+\n+ return self._upload_data_buffer(\n+ end_stream=end_stream, retry_count=retry_count + 1)\n+\nlogger.debug(\n'Data buffer nr. {0:d} uploaded, total time: {1:.2f}s'.format(\nself._chunk, time.time() - start_time))\nself._chunk += 1\nresponse_dict = response.json()\nobject_dict = response_dict.get('objects', [{}])[0]\n+ meta_dict = response_dict.get('meta', {})\n+ self._celery_task_id = meta_dict.get('task_id', '')\nself._timeline_id = object_dict.get('id')\nself._index = object_dict.get('searchindex', {}).get('index_name')\nself._last_response = response_dict\n- def _upload_data_frame(self, data_frame, end_stream):\n+ return None\n+\n+ def _upload_data_frame(self, data_frame, end_stream, retry_count=0):\n\"\"\"Upload data to Timesketch.\nArgs:\ndata_frame: a pandas DataFrame with the content to upload.\nend_stream: boolean indicating whether this is the last chunk of\nthe stream.\n+ retry_count: optional int that is only set if this is a retry\n+ of the upload.\n+\n+ Raises:\n+ RuntimeError: If the dataframe is not successfully uploaded.\n\"\"\"\ndata = {\n'name': self._timeline_name,\n@@ -297,21 +323,33 @@ class ImportStreamer(object):\ndata['context'] = self._upload_context\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:\n+ if retry_count >= self.DEFAULT_RETRY_LIMIT:\nraise RuntimeError(\n'Error uploading data: [{0:d}] {1!s} {2!s}, '\n'index {3:s}'.format(\nresponse.status_code, response.reason, response.text,\nself._index))\n+ logger.warning(\n+ 'Unable to upload dataframe, retrying (attempt '\n+ '{0:d}/{1:d})'.format(\n+ retry_count + 1, self.DEFAULT_RETRY_LIMIT))\n+\n+ return self._upload_data_frame(\n+ data_frame=data_frame, end_stream=end_stream,\n+ retry_count=retry_count + 1)\n+\n+ self._chunk += 1\nresponse_dict = response.json()\nobject_dict = response_dict.get('objects', [{}])[0]\n+ meta_dict = response_dict.get('meta', {})\n+ self._celery_task_id = meta_dict.get('task_id', '')\nself._timeline_id = object_dict.get('id')\nself._index = object_dict.get('searchindex', {}).get('index_name')\nself._last_response = response_dict\n+ return None\ndef _upload_binary_file(self, file_path):\n\"\"\"Upload binary data to Timesketch, potentially chunking it up.\n@@ -362,17 +400,29 @@ class ImportStreamer(object):\nfile_stream = io.BytesIO(binary_data)\nfile_stream.name = file_path\nfile_dict = {'file': file_stream}\n- response = self._sketch.api.session.post(\n- self._resource_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+ retry_count = 0\n+ while True:\n+ if retry_count >= self.DEFAULT_RETRY_LIMIT:\nraise RuntimeError(\n- 'Error uploading data chunk: {0:d}/{1:d}. Status code: '\n- '{2:d} - {3!s} {4!s}'.format(\n+ 'Error uploading data chunk: {0:d}/{1:d}. Status '\n+ 'code: {2:d} - {3!s} {4!s}'.format(\nindex, chunks, response.status_code,\nresponse.reason, response.text))\n+ response = self._sketch.api.session.post(\n+ self._resource_url, files=file_dict, data=data)\n+\n+ if response.status_code in definitions.HTTP_STATUS_CODE_20X:\n+ break\n+\n+ retry_count += 1\n+ logger.warning(\n+ 'Error uploading data chunk {0:d}/{1:d}, retry '\n+ 'attempt {2:d}/{3:d}'.format(\n+ index, chunks, retry_count,\n+ self.DEFAULT_RETRY_LIMIT))\n+\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@@ -382,6 +432,8 @@ class ImportStreamer(object):\nresponse_dict = response.json()\nobject_dict = response_dict.get('objects', [{}])[0]\n+ meta_dict = response_dict.get('meta', {})\n+ self._celery_task_id = meta_dict.get('task_id', '')\nself._timeline_id = object_dict.get('id')\nself._index = object_dict.get('searchindex', {}).get('index_name')\n@@ -616,6 +668,11 @@ class ImportStreamer(object):\nself.add_dict(json_dict)\n+ @property\n+ def celery_task_id(self):\n+ \"\"\"Return the celery task identification for the upload.\"\"\"\n+ return self._celery_task_id\n+\ndef close(self):\n\"\"\"Close the streamer.\"\"\"\ntry:\n@@ -726,6 +783,23 @@ class ImportStreamer(object):\n\"\"\"Set the timestamp description field.\"\"\"\nself._timestamp_desc = description\n+ @property\n+ def state(self):\n+ \"\"\"Returns a state string for the indexing process.\"\"\"\n+ if not self._celery_task_id:\n+ return 'Unknown'\n+\n+ tasks = self._sketch.api.check_celery_status(\n+ job_id=self._celery_task_id)\n+\n+ if len(tasks) > 1:\n+ for task in tasks:\n+ if task.get('task_id', '') == self._celery_task_id:\n+ return task.get('state', 'Unknown')\n+\n+ task = tasks[0]\n+ return task.get('state', 'Unknown')\n+\n@property\ndef timeline(self):\n\"\"\"Returns a timeline object.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "importer_client/python/timesketch_import_client/version.py",
"new_path": "importer_client/python/timesketch_import_client/version.py",
"diff": "# limitations under the License.\n\"\"\"Version information for Timesketch Import Client.\"\"\"\n-__version__ = '20210225'\n+__version__ = '20210305'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "importer_client/python/tools/timesketch_importer.py",
"new_path": "importer_client/python/tools/timesketch_importer.py",
"diff": "@@ -19,6 +19,7 @@ import getpass\nimport logging\nimport os\nimport sys\n+import time\nfrom typing import Dict\n@@ -67,7 +68,9 @@ def upload_file(\nfile_path (str): the path to the file to upload.\nReturns:\n- A string with results (whether successful or not).\n+ A tuple with the timeline object (timeline.Timeline) or None if not\n+ able to upload the timeline as well as the celery task identification\n+ for the indexing.\n\"\"\"\nif not my_sketch or not hasattr(my_sketch, 'id'):\nreturn 'Sketch needs to be set'\n@@ -86,6 +89,9 @@ def upload_file(\nif log_config_file:\nimport_helper.add_config(log_config_file)\n+ timeline = None\n+ task_id = ''\n+ logger.info('About to upload file.')\nwith importer.ImportStreamer() as streamer:\nstreamer.set_sketch(my_sketch)\nstreamer.set_config_helper(import_helper)\n@@ -126,9 +132,11 @@ def upload_file(\nstreamer.set_upload_context(' '.join(sys.argv))\nstreamer.add_file(file_path)\n+ timeline = streamer.timeline\n+ task_id = streamer.celery_task_id\n- return 'File got successfully uploaded to sketch: {0:d}'.format(\n- my_sketch.id)\n+ logger.info('File upload completed.')\n+ return timeline, task_id\ndef main(args=None):\n@@ -182,6 +190,14 @@ def main(args=None):\nconfig_group = argument_parser.add_argument_group(\n'Configuration Arguments')\n+ config_group.add_argument(\n+ '--quick', '-q', '--no-wait', '--no_wait', action='store_false',\n+ default=True, dest='wait_timeline', help=(\n+ 'By default the tool will wait until the timeline has been '\n+ 'indexed and print out some details of the import. This option '\n+ 'makes the tool exit as soon as the data has been imported and '\n+ 'does not wait until it\\'s been indexed.'))\n+\nconfig_group.add_argument(\n'--log-config-file', '--log_config_file', '--lc', action='store',\ntype=str, default='', metavar='FILEPATH', dest='log_config_file',\n@@ -409,9 +425,44 @@ def main(args=None):\n}\nlogger.info('Uploading file.')\n- result = upload_file(\n+ timeline, task_id = upload_file(\nmy_sketch=my_sketch, config_dict=config_dict, file_path=options.path)\n- logger.info(result)\n+\n+ if not options.wait_timeline:\n+ logger.info('File got successfully uploaded to sketch: {0:d}'.format(\n+ my_sketch.id))\n+ return\n+\n+ if not timeline:\n+ logger.warning(\n+ 'There does not seem to be any timeline returned, check whether '\n+ 'the data got uploaded.')\n+ return\n+\n+ print('Checking file upload status: ', end='')\n+ while True:\n+ status = timeline.status\n+ if status in ('archived', 'failed', 'fail'):\n+ print('[FAIL]')\n+ print('Unable to index timeline, reason: {0:s}'.format(\n+ timeline.description))\n+ return\n+\n+ if status not in ('ready', 'success'):\n+ print('.', end='')\n+ time.sleep(3)\n+ continue\n+\n+ print('[DONE]')\n+ print(f'Timeline uploaded to ID: {timeline.id}.')\n+\n+ task_state = 'Unknown'\n+ task_list = ts_client.check_celery_status(task_id)\n+ for task in task_list:\n+ if task.get('task_id', '') == task_id:\n+ task_state = task.get('state', 'Unknown')\n+ print(f'Status of the index is: {task_state}')\n+ break\nif __name__ == '__main__':\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/task.py",
"new_path": "timesketch/api/v1/resources/task.py",
"diff": "import datetime\n-from flask import jsonify\nfrom flask import current_app\n+from flask import jsonify\n+from flask import request\nfrom flask_restful import Resource\nfrom flask_login import login_required\nfrom flask_login import current_user\n@@ -30,11 +31,24 @@ class TaskResource(resources.ResourceMixin, Resource):\n# pylint: disable=import-outside-toplevel\ndef __init__(self):\n- super(TaskResource, self).__init__()\n+ super().__init__()\n# pylint: disable=import-outside-toplevel\nfrom timesketch.app import create_celery_app\nself.celery = create_celery_app()\n+ def _get_celery_information(self, job_id):\n+ # pylint: disable=too-many-function-args\n+ celery_task = self.celery.AsyncResult(job_id)\n+ task = dict(\n+ task_id=celery_task.task_id,\n+ state=celery_task.state,\n+ successful=celery_task.successful(),\n+ result=False)\n+\n+ if task.get('state', '') == 'SUCCESS':\n+ task['result'] = celery_task.result\n+ return task\n+\n@login_required\ndef get(self):\n\"\"\"Handles GET request to the resource.\n@@ -44,24 +58,25 @@ class TaskResource(resources.ResourceMixin, Resource):\n\"\"\"\ntimeout_threshold_seconds = current_app.config.get(\n'CELERY_TASK_TIMEOUT', 7200)\n+\n+ schema = {'objects': [], 'meta': {}}\n+\n+ job_id = request.args.get('job_id', '')\n+ if job_id:\n+ task = self._get_celery_information(job_id)\n+ schema['objects'].append(task)\n+ return jsonify(schema)\n+\nindices = SearchIndex.query.filter(\nSearchIndex.status.any(status='processing')).filter_by(\nuser=current_user).all()\n- schema = {'objects': [], 'meta': {}}\nfor search_index in indices:\nif search_index.get_status.status == 'deleted':\ncontinue\n- # pylint: disable=too-many-function-args\n- celery_task = self.celery.AsyncResult(search_index.index_name)\n- task = dict(\n- task_id=celery_task.task_id,\n- state=celery_task.state,\n- successful=celery_task.successful(),\n- name=search_index.name,\n- result=False)\n- if celery_task.state == 'SUCCESS':\n- task['result'] = celery_task.result\n- elif celery_task.state == 'PENDING':\n+ task = self._get_celery_information(search_index.index_name)\n+ task['name'] = search_index.name\n+\n+ if task.get('state', '') == 'PENDING':\ntime_pending = (\nsearch_index.updated_at - datetime.datetime.now())\nif time_pending.seconds > timeout_threshold_seconds:\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/timeline.py",
"new_path": "timesketch/api/v1/resources/timeline.py",
"diff": "@@ -192,18 +192,18 @@ class TimelineResource(resources.ResourceMixin, Resource):\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No Timeline found with this ID.')\n- if not timeline.sketch_id:\n+ if timeline.sketch is None:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\nf'The timeline {timeline_id} does not have an associated '\n'sketch, does it belong to a sketch?')\n# Check that this timeline belongs to the sketch\n- if timeline.sketch_id != sketch.id:\n+ if timeline.sketch.id != sketch.id:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\n'The sketch ID ({0:d}) does not match with the timeline '\n- 'sketch ID ({1:d})'.format(sketch.id, timeline.sketch_id))\n+ 'sketch ID ({1:d})'.format(sketch.id, timeline.sketch.id))\nif not sketch.has_permission(user=current_user, permission='read'):\nabort(\n@@ -230,12 +230,17 @@ class TimelineResource(resources.ResourceMixin, Resource):\nHTTP_STATUS_CODE_NOT_FOUND,\n'No timeline found with this ID.')\n+ if timeline.sketch is None:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No sketch associated with this timeline.')\n+\n# Check that this timeline belongs to the sketch\n- if timeline.sketch_id != sketch.id:\n+ if timeline.sketch.id != sketch.id:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND,\n'The sketch ID ({0:d}) does not match with the timeline '\n- 'sketch ID ({1:d})'.format(sketch.id, timeline.sketch_id))\n+ 'sketch ID ({1:d})'.format(sketch.id, timeline.sketch.id))\nif not sketch.has_permission(user=current_user, permission='write'):\nabort(\n@@ -314,18 +319,34 @@ class TimelineResource(resources.ResourceMixin, Resource):\nif not sketch:\nabort(\nHTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')\n+\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+\n+ if timeline.sketch is None:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No sketch associated with this timeline.')\n# Check that this timeline belongs to the sketch\n- if timeline.sketch_id != sketch.id:\n+ if timeline.sketch.id != sketch.id:\nif not timeline:\nmsg = 'No timeline found with this ID.'\nelif not sketch:\nmsg = 'No sketch found with this ID.'\nelse:\n+ sketch_use = sketch.id or 'No sketch ID'\n+ sketch_string = str(sketch_use)\n+\n+ timeline_use = timeline.sketch.id or (\n+ 'No sketch associated with the timeline.')\n+ timeline_string = str(timeline_use)\n+\nmsg = (\n- 'The sketch ID ({0:d}) does not match with the timeline '\n- 'sketch ID ({1:d})'.format(sketch.id, timeline.sketch_id))\n+ 'The sketch ID ({0:s}) does not match with the timeline '\n+ 'sketch ID ({1:s})'.format(sketch_string, timeline_string))\nabort(HTTP_STATUS_CODE_NOT_FOUND, msg)\nif not sketch.has_permission(user=current_user, permission='write'):\n@@ -353,6 +374,9 @@ class TimelineResource(resources.ResourceMixin, Resource):\ntimelines.extend(index.timelines)\nfor timeline_ in timelines:\n+ if timeline_.sketch is None:\n+ continue\n+\nif timeline_.sketch.id != sketch.id:\nclose_index = False\nbreak\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/upload.py",
"new_path": "timesketch/api/v1/resources/upload.py",
"diff": "@@ -219,8 +219,13 @@ class UploadFileResource(resources.ResourceMixin, Resource):\nindex_name=searchindex.index_name, file_extension=file_extension,\nsketch_id=sketch_id, only_index=enable_stream,\ntimeline_id=timeline.id)\n- pipeline.apply_async()\n+ task_id = uuid.uuid4().hex\n+ pipeline.apply_async(task_id=task_id)\n+ if meta is None:\n+ meta = {}\n+\n+ meta['task_id'] = task_id\nreturn self.to_json(\ntimeline, status_code=HTTP_STATUS_CODE_CREATED, meta=meta)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/tasks.py",
"new_path": "timesketch/lib/tasks.py",
"diff": "@@ -622,6 +622,8 @@ def run_plaso(\nexcept subprocess.CalledProcessError as e:\n# Mark the searchindex and timelines as failed and exit the task\n_set_timeline_status(timeline_id, status='fail', error_msg=e.output)\n+ _close_index(\n+ index_name=index_name, data_store=es, timeline_id=timeline_id)\nreturn e.output\n# Mark the searchindex and timelines as ready\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/utils.py",
"new_path": "timesketch/lib/utils.py",
"diff": "@@ -150,6 +150,9 @@ def read_and_validate_csv(\nheader_reader = pandas.read_csv(file_handle, sep=delimiter, nrows=0)\n_validate_csv_fields(mandatory_fields, header_reader)\n+ if hasattr(file_handle, 'seek'):\n+ file_handle.seek(0)\n+\ntry:\nreader = pandas.read_csv(\nfile_handle, sep=delimiter, chunksize=DEFAULT_CHUNK_SIZE)\n@@ -179,8 +182,8 @@ def read_and_validate_csv(\nchunk['tag'] = chunk['tag'].apply(_parse_tag_field)\nfor _, row in chunk.iterrows():\n_scrub_special_tags(row)\n- yield row\n- except pandas.errors.ParserError as e:\n+ yield row.to_dict()\n+ except (pandas.errors.EmptyDataError, pandas.errors.ParserError) as e:\nerror_string = 'Unable to read file, with error: {0!s}'.format(e)\nlogger.error(error_string)\nraise errors.DataIngestionError(error_string) from e\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/version.py",
"new_path": "timesketch/version.py",
"diff": "# limitations under the License.\n\"\"\"Version information for Timesketch.\"\"\"\n-__version__ = '20210224'\n+__version__ = '20210308'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added several enhancements to the importer and importer tasks. (#1667) |
263,133 | 11.03.2021 10:35:04 | 0 | 3013e20cf834f6517c7ee31716b150f9d470b133 | Changed how the NAN values are filled in for CSV ingestion. | [
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/datastores/elastic.py",
"new_path": "timesketch/lib/datastores/elastic.py",
"diff": "@@ -32,7 +32,6 @@ from elasticsearch.exceptions import RequestError\nfrom elasticsearch.exceptions import ConnectionError\nfrom flask import abort\nfrom flask import current_app\n-import numpy as np\nimport prometheus_client\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n@@ -925,9 +924,6 @@ class ElasticsearchDataStore(object):\nif not isinstance(k, six.text_type):\nk = codecs.decode(k, 'utf8')\n- if isinstance(v, float) and np.isnan(v):\n- v = ''\n-\n# Make sure we have decoded strings in the event dict.\nif isinstance(v, six.binary_type):\nv = codecs.decode(v, 'utf8')\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/utils.py",
"new_path": "timesketch/lib/utils.py",
"diff": "@@ -180,6 +180,10 @@ def read_and_validate_csv(\ncontinue\nif 'tag' in chunk:\nchunk['tag'] = chunk['tag'].apply(_parse_tag_field)\n+\n+ # Fill all NaN values with an empty string, otherwise JSON decoding\n+ # in Elastic will fail.\n+ chunk.fillna('', inplace=True)\nfor _, row in chunk.iterrows():\n_scrub_special_tags(row)\nyield row.to_dict()\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changed how the NAN values are filled in for CSV ingestion. (#1676) |
263,133 | 15.03.2021 09:08:49 | 0 | f1c45f476ebd53c5472131fe2f86d8a39b67f8b6 | Minor bug fixes to the API client | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/search.py",
"new_path": "api_client/python/timesketch_api_client/search.py",
"diff": "@@ -702,6 +702,12 @@ class Search(resource.SketchResource):\n@indices.setter\ndef indices(self, indices):\n\"\"\"Make changes to the current set of indices.\"\"\"\n+\n+ if indices == '_all':\n+ self._indices = '_all'\n+ self.commit()\n+ return\n+\ndef _is_string_or_int(item):\nreturn isinstance(item, (str, int))\n@@ -716,20 +722,34 @@ class Search(resource.SketchResource):\n'entries in the indices list are valid string/int.')\nreturn\n+ if len(indices) == 1 and indices[0] == '_all':\n+ self._indices = '_all'\n+ self.commit()\n+ return\n+\n# Indices here can be either a list of timeline names, IDs or a list\n# of search indices. We need to verify that these exist before saving\n# them.\n- timelines = {\n- t.index_name: t.name for t in self._sketch.list_timelines()}\n+ valid_ids = set()\n+ timeline_indices = {} # Dict[index] = List[name]\n+ timeline_names = {} # Dict[name] = id\n+\n+ for timeline_object in self._sketch.list_timelines():\n+ timeline_indices.setdefault(timeline_object.index_name, [])\n+ timeline_indices[timeline_object.index_name].append(\n+ timeline_object.name)\n+ valid_ids.add(timeline_object.id)\n- valid_ids = [t.id for t in self._sketch.list_timelines()]\n+ timeline_names[timeline_object.name] = timeline_object.id\nnew_indices = []\nfor index in indices:\n- if index in timelines:\n- new_indices.append(index)\n+ # Is this an index name, include all timeline IDs.\n+ if index in timeline_indices:\n+ new_indices.extend(timeline_indices[index])\ncontinue\n+ # Is this a timeline ID?\nif isinstance(index, int):\nif index in valid_ids:\nnew_indices.append(str(index))\n@@ -740,14 +760,16 @@ class Search(resource.SketchResource):\nnew_indices.append(index)\ncontinue\n- if index in timelines.values():\n- new_indices.append(index)\n+ # Is this a timeline name?\n+ if index in timeline_names:\n+ new_indices.append(timeline_names[index])\nif not new_indices:\n- logger.warning('No valid indices found, not changin the value.')\n+ logger.warning('No valid indices found, not changing the value.')\nreturn\nself._indices = new_indices\n+ self.commit()\n@property\ndef max_entries(self):\n@@ -780,12 +802,14 @@ class Search(resource.SketchResource):\n# Trigger a creation of a query filter if it does not exist.\n_ = self.query_filter\nself._query_filter['order'] = 'asc'\n+ self.commit()\ndef order_descending(self):\n\"\"\"Set the order of objects returned back descending.\"\"\"\n# Trigger a creation of a query filter if it does not exist.\n_ = self.query_filter\nself._query_filter['order'] = 'desc'\n+ self.commit()\n@property\ndef query_dsl(self):\n@@ -884,6 +908,7 @@ class Search(resource.SketchResource):\ndef return_size(self, return_size):\n\"\"\"Make changes to the maximum number of entries in the return.\"\"\"\nself._max_entries = return_size\n+ self.commit()\ndef save(self):\n\"\"\"Save the search in the database.\n@@ -1011,7 +1036,7 @@ class Search(resource.SketchResource):\nreturn_list = []\ntimelines = {\n- t.index_name: t.name for t in self._sketch.list_timelines()}\n+ t.id: t.name for t in self._sketch.list_timelines()}\nreturn_field_list = []\nreturn_fields = self._return_fields\n@@ -1031,7 +1056,11 @@ class Search(resource.SketchResource):\nif not return_fields or '_index' in return_field_list:\nsource['_index'] = result.get('_index')\nif not return_fields or '_source' in return_field_list:\n- source['_source'] = timelines.get(result.get('_index'))\n+ source['_source'] = timelines.get(\n+ result.get('__ts_timeline_id'))\n+ if not return_fields or '__ts_timeline_id' in return_field_list:\n+ source['_source'] = timelines.get(\n+ result.get('__ts_timeline_id'))\nreturn_list.append(source)\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": "@@ -321,10 +321,9 @@ class AggregationBlock(BaseBlock):\nname = aggregation_obj.name\ndescription = aggregation_obj.description\nagg_id = aggregation_obj.id\n- meta = aggregation_obj.data.get('meta', {})\n- agg_type = meta.get('name', '')\n- created_at = ''\n- updated_at = ''\n+ agg_type = aggregation_obj.aggregator_name\n+ created_at = aggregation_obj.created_at\n+ updated_at = aggregation_obj.updated_at\nparameters = json.dumps(aggregation_obj.parameters)\nuser = aggregation_obj.user\nelse:\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210308'\n+__version__ = '20210312'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Minor bug fixes to the API client (#1686) |
263,144 | 19.03.2021 14:50:07 | -3,600 | 37f5bd5a20451c9a625c0c8cdf6c387a49c5e131 | Fixed broken links in README.md
Fix broken links | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -27,23 +27,23 @@ Timesketch is an open-source tool for collaborative forensic timeline analysis.\n## Getting started\n#### Installation\n-* [Install Timesketch](docs/admin-guide/install.md)\n+* [Install Timesketch](docs/getting-started/install.md)\n#### Adding timelines\n-* [Upload data](docs/admin-guide/upload-data.md)\n+* [Upload data](docs/getting-started/upload-data.md)\n#### Using Timesketch\n-* [Users guide](docs/user-guide/basic-concepts)\n+* [Users guide](docs/learn/basic-concepts.md)\n#### Adding a Notebook Container\n-* [Installation](docs/Notebook.md)\n+* [Installation](docs/learn/notebook.md)\n## Community\n-* [Community guide](docs/community.md)\n+* [Community guide](docs/community/resources.md)\n## Contributing\n* [Prerequisites](CONTRIBUTING.md)\n-* [Developers guide](developers/developer-guide.md)\n+* [Developers guide](docs/developers/developer-guide.md)\n---\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed broken links in README.md (#1696)
Fix broken links |
263,109 | 22.03.2021 09:22:19 | -3,600 | 8f51d3a778df9bed788fec06799d1983d71064bc | Updated link
The link was broken: It has been fixed | [
{
"change_type": "MODIFY",
"old_path": "docker/release/README.md",
"new_path": "docker/release/README.md",
"diff": "# Release Docker images\n-For instruction on how to deploy, see: https://github.com/google/timesketch/blob/master/docs/Installation.md\n\\ No newline at end of file\n+For instruction on how to deploy, see: https://github.com/google/timesketch/blob/master/docs/getting-started/install.md\n"
}
] | Python | Apache License 2.0 | google/timesketch | Updated link (#1702)
The link was broken: It has been fixed |
263,133 | 23.03.2021 08:19:26 | 0 | 6d66c2a23bf1f13b82876ccb0667e945a978f3d7 | Changed how import errors are presented as well as ability to change passwords for the current user. | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sketch.py",
"new_path": "api_client/python/timesketch_api_client/sketch.py",
"diff": "@@ -925,9 +925,14 @@ class Sketch(resource.BaseResource):\nraise RuntimeError(\n'Unable to list timelines on an archived sketch.')\n- sketch = self.lazyload_data()\ntimelines = []\n- for timeline_dict in sketch['objects'][0]['timelines']:\n+\n+ data = self.lazyload_data()\n+ objects = data.get('objects')\n+ if not objects:\n+ return timelines\n+\n+ for timeline_dict in objects[0].get('timelines', []):\ntimeline_obj = timeline.Timeline(\ntimeline_id=timeline_dict['id'],\nsketch_id=self.id,\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/user.py",
"new_path": "api_client/python/timesketch_api_client/user.py",
"diff": "\"\"\"Timesketch API client library.\"\"\"\nimport logging\n+from . import error\nfrom . import resource\n@@ -43,6 +44,29 @@ class User(resource.BaseResource):\nreturn self._object_data\n+ def change_password(self, new_password):\n+ \"\"\"Change the password for the user.\n+\n+ Args:\n+ new_password (str): String with the password.\n+\n+ Raises:\n+ ValueError: If there was an error.\n+\n+ Returns:\n+ Boolean: Whether the password was sucessfully modified.\n+ \"\"\"\n+ if not new_password:\n+ raise ValueError('No new password supplied.')\n+\n+ if not isinstance(new_password, str):\n+ raise ValueError('Password needs to be a string value.')\n+\n+ data = {'password': new_password}\n+ resource_url = f'{self.api.api_root}/{self.resource_uri}'\n+ response = self.api.session.post(resource_url, json=data)\n+ return error.check_return_status(response, logger)\n+\n@property\ndef groups(self):\n\"\"\"Property that returns the groups the user belongs to.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/version.py",
"new_path": "api_client/python/timesketch_api_client/version.py",
"diff": "\"\"\"Version information for Timesketch API Client.\"\"\"\n-__version__ = '20210312'\n+__version__ = '20210319'\ndef get_version():\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/release/build/Dockerfile-release",
"new_path": "docker/release/build/Dockerfile-release",
"diff": "-# Use the official Docker Hub Ubuntu 18.04 base image\n-FROM ubuntu:18.04\n+# Use the official Docker Hub Ubuntu 20.04 base image\n+FROM ubuntu:20.04\nMAINTAINER Timesketch <timesketch-dev@googlegroups.com>\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/export.py",
"new_path": "timesketch/api/v1/export.py",
"diff": "@@ -115,7 +115,7 @@ def export_story(story, sketch, story_exporter, zip_file):\ndef query_to_filehandle(\nquery_string='', query_dsl='', query_filter=None, sketch=None,\n- datastore=None, indices=None):\n+ datastore=None, indices=None, timeline_ids=None, return_fields=None):\n\"\"\"Query the datastore and return back a file object with the results.\nThis function takes a query string or DSL, queries the datastore\n@@ -129,6 +129,9 @@ def query_to_filehandle(\nsketch (timesketch.models.sketch.Sketch): a sketch object.\ndatastore (elastic.ElasticsearchDataStore): the datastore object.\nindices (list): List of indices to query\n+ timeline_ids (list): Optional list of IDs of Timeline objects that\n+ should be queried as part of the search.\n+ return_fields (list): List of fields to return\nReturns:\nfile-like object in a CSV format with the results.\n@@ -147,6 +150,8 @@ def query_to_filehandle(\nquery_filter=query_filter,\nquery_dsl=query_dsl,\nenable_scroll=True,\n+ timeline_ids=timeline_ids,\n+ return_fields=return_fields,\nindices=indices)\nscroll_id = result.get('_scroll_id', '')\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/explore.py",
"new_path": "timesketch/api/v1/resources/explore.py",
"diff": "@@ -182,7 +182,9 @@ class ExploreResource(resources.ResourceMixin, Resource):\nquery_filter=query_filter,\nindices=indices,\nsketch=sketch,\n- datastore=self.datastore)\n+ datastore=self.datastore,\n+ return_fields=return_fields,\n+ timeline_ids=timeline_ids)\nfh.seek(0)\nzip_file.writestr('query_results.csv', fh.read())\nfile_object.seek(0)\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/upload.py",
"new_path": "timesketch/api/v1/resources/upload.py",
"diff": "\"\"\"Upload resources for version 1 of the Timesketch API.\"\"\"\nimport codecs\n+import logging\nimport os\nimport uuid\n@@ -37,6 +38,8 @@ from timesketch.models.sketch import Sketch\nfrom timesketch.models.sketch import Timeline\nfrom timesketch.models.sketch import DataSource\n+logger = logging.getLogger('timesketch.api_upload')\n+\nclass UploadFileResource(resources.ResourceMixin, Resource):\n\"\"\"Resource that processes uploaded files.\"\"\"\n@@ -151,8 +154,6 @@ class UploadFileResource(resources.ResourceMixin, Resource):\n'please create an issue on Github: https://github.com/'\n'google/timesketch/issues/new/choose')\n- searchindex.set_status('processing')\n-\ntimelines = Timeline.query.filter_by(\nname=timeline_name, sketch=sketch).all()\n@@ -162,11 +163,24 @@ class UploadFileResource(resources.ResourceMixin, Resource):\ntimeline = timeline_\nbreak\n- abort(\n- HTTP_STATUS_CODE_BAD_REQUEST,\n+ logger.error(\n'There is a timeline in the sketch that has the same name '\n- 'but is stored in a different index, check the data_label '\n- 'on the uploaded data')\n+ 'but is stored in a different index: name {0:s} attempting '\n+ 'index: {1:s} but found index {2:s} - retrying with a '\n+ 'different timeline name.'.format(\n+ timeline_name, searchindex.index_name,\n+ timeline_.searchindex.index_name))\n+\n+ timeline_name = '{0:s}_{1:s}'.format(\n+ timeline_name, uuid.uuid4().hex[-5:])\n+ return self._upload_and_index(\n+ file_extension=file_extension, timeline_name=timeline_name,\n+ index_name=searchindex.index_name, sketch=sketch, form=form,\n+ enable_stream=enable_stream,\n+ original_filename=original_filename, data_label=data_label,\n+ file_path=file_path, events=events, meta=meta)\n+\n+ searchindex.set_status('processing')\nif not timeline:\ntimeline = Timeline.get_or_create(\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/user.py",
"new_path": "timesketch/api/v1/resources/user.py",
"diff": "@@ -25,6 +25,7 @@ from timesketch.api.v1 import resources\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_OK\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_FORBIDDEN\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_NOT_FOUND\n+from timesketch.models import db_session\nfrom timesketch.models.sketch import Sketch\nfrom timesketch.models.user import User\nfrom timesketch.models.user import Group\n@@ -71,6 +72,34 @@ class LoggedInUserResource(resources.ResourceMixin, Resource):\n\"\"\"\nreturn self.to_json(current_user)\n+ @login_required\n+ def post(self):\n+ \"\"\"Handles POST request to the resource.\n+\n+ Returns:\n+ HTTP status code indicating whether operation was sucessful.\n+ \"\"\"\n+ form = request.json\n+ if not form:\n+ form = request.data\n+\n+ password = form.get('password', '')\n+\n+ if not password:\n+ abort(\n+ HTTP_STATUS_CODE_NOT_FOUND,\n+ 'No password supplied, unable to change the password.')\n+\n+ if not isinstance(password, str):\n+ abort(\n+ HTTP_STATUS_CODE_FORBIDDEN,\n+ 'Password needs to be a string.')\n+\n+ current_user.set_password(plaintext=password)\n+ db_session.add(current_user)\n+ db_session.commit()\n+ return HTTP_STATUS_CODE_OK\n+\nclass CollaboratorResource(resources.ResourceMixin, Resource):\n\"\"\"Resource to update sketch collaborators.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/tasks.py",
"new_path": "timesketch/lib/tasks.py",
"diff": "@@ -48,11 +48,12 @@ from timesketch.lib.utils import read_and_validate_csv\nfrom timesketch.lib.utils import read_and_validate_jsonl\nfrom timesketch.lib.utils import send_email\nfrom timesketch.models import db_session\n+from timesketch.models.sketch import Analysis\n+from timesketch.models.sketch import AnalysisSession\n+from timesketch.models.sketch import DataSource\nfrom timesketch.models.sketch import SearchIndex\nfrom timesketch.models.sketch import Sketch\nfrom timesketch.models.sketch import Timeline\n-from timesketch.models.sketch import Analysis\n-from timesketch.models.sketch import AnalysisSession\nfrom timesketch.models.user import User\n@@ -180,8 +181,10 @@ def _set_timeline_status(timeline_id, status, error_msg=None):\n# Update description if there was a failure in ingestion.\nif error_msg:\n- # TODO: Don't overload the description field.\n- timeline.description = error_msg\n+ data_source = DataSource.query.filter_by(\n+ timeline_id=timeline.id).first()\n+ if data_source:\n+ data_source.error_message = error_msg\n# Commit changes to database\ndb_session.add(timeline)\n@@ -623,6 +626,18 @@ def run_plaso(\nif timeline_id:\ncmd.extend(['--timeline_identifier', str(timeline_id)])\n+ elastic_username = current_app.config.get('ELASTIC_USER', '')\n+ if elastic_username:\n+ cmd.extend(['--elastic_user', elastic_username])\n+\n+ elastic_password = current_app.config.get('ELASTIC_PASSWORD', '')\n+ if elastic_password:\n+ cmd.extend(['--elastic_password', elastic_password])\n+\n+ elastic_ssl = current_app.config.get('ELASTIC_SSL', False)\n+ if elastic_ssl:\n+ cmd.extend(['--use_ssl'])\n+\n# Run psort.py\ntry:\nsubprocess.check_output(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "timesketch/migrations/versions/75af34d75b1e_extending_the_data_source_schema.py",
"diff": "+\"\"\"Extending the data source schema.\n+\n+Revision ID: 75af34d75b1e\n+Revises: 41cae2c10cd7\n+Create Date: 2021-03-19 13:18:17.575912\n+\n+\"\"\"\n+# This code is auto generated. Ignore linter errors.\n+# pylint: skip-file\n+\n+\n+# revision identifiers, used by Alembic.\n+revision = '75af34d75b1e'\n+down_revision = '41cae2c10cd7'\n+\n+from alembic import op\n+import sqlalchemy as sa\n+\n+\n+def upgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.add_column(\n+ 'datasource',\n+ sa.Column('error_message', sa.UnicodeText(), nullable=True))\n+ # ### end Alembic commands ###\n+\n+\n+def downgrade():\n+ # ### commands auto generated by Alembic - please adjust! ###\n+ op.drop_column('datasource', 'error_message')\n+ # ### end Alembic commands ###\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/models/sketch.py",
"new_path": "timesketch/models/sketch.py",
"diff": "@@ -704,9 +704,10 @@ class DataSource(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nfile_size = Column(BigInteger())\noriginal_filename = Column(UnicodeText())\ndata_label = Column(UnicodeText())\n+ error_message = Column(UnicodeText())\ndef __init__(self, timeline, user, provider, context, file_on_disk,\n- file_size, original_filename, data_label):\n+ file_size, original_filename, data_label, error_message=''):\n\"\"\"Initialize the DataSource object.\nArgs:\n@@ -718,6 +719,8 @@ class DataSource(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nfile_size (int): Size on disk for uploaded file.\noriginal_filename (str): Original filename for uploaded file.\ndata_label (str): Data label for the uploaded data.\n+ error_message (str): Optional error message in case the data source\n+ did not successfully import.\n\"\"\"\nsuper().__init__()\nself.timeline = timeline\n@@ -728,3 +731,4 @@ class DataSource(LabelMixin, StatusMixin, CommentMixin, BaseModel):\nself.file_size = file_size\nself.original_filename = original_filename\nself.data_label = data_label\n+ self.error_message = error_message\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/version.py",
"new_path": "timesketch/version.py",
"diff": "# limitations under the License.\n\"\"\"Version information for Timesketch.\"\"\"\n-__version__ = '20210308'\n+__version__ = '20210319'\ndef get_version():\n"
}
] | Python | Apache License 2.0 | google/timesketch | Changed how import errors are presented as well as ability to change passwords for the current user. (#1700) |
263,133 | 25.03.2021 14:29:21 | 0 | 28ea5ad804d4bc6a6fa62efd84f8a64560954ca7 | Added upper memory limits to psort. | [
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -148,6 +148,11 @@ CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'\n# for plaso files.\nPLASO_MAPPING_FILE = '/etc/timesketch/plaso.mappings'\n+# Upper limits for the process memory that psort.py is allocated when ingesting\n+# plaso files. The size is in bytes, with the default value of\n+# 4294967296 or 4 GiB.\n+PLASO_UPPER_MEMORY_LIMIT = None\n+\n#-------------------------------------------------------------------------------\n# Graph backend configuration.\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/tasks.py",
"new_path": "timesketch/lib/tasks.py",
"diff": "@@ -176,10 +176,11 @@ def _set_timeline_status(timeline_id, status, error_msg=None):\nreturn\n# Check if there is at least one data source that hasn't failed.\n- multiple_sources = any([not x.error_message for x in timeline.datasources])\n+ multiple_sources = any(not x.error_message for x in timeline.datasources)\nif multiple_sources:\n- if status != 'fail':\n+ timeline_status = timeline.get_status.status.lower()\n+ if timeline_status != 'process' and status != 'fail':\ntimeline.set_status(status)\ntimeline.searchindex.set_status(status)\nelse:\n@@ -644,6 +645,11 @@ def run_plaso(\nif elastic_ssl:\ncmd.extend(['--use_ssl'])\n+\n+ psort_memory = current_app.config.get('PLASO_UPPER_MEMORY_LIMIT', '')\n+ if psort_memory:\n+ cmd.extend(['--process_memory_limit', str(psort_memory)])\n+\n# Run psort.py\ntry:\nsubprocess.check_output(\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added upper memory limits to psort. (#1722) |
263,131 | 25.03.2021 23:04:33 | -28,800 | d0664c47a97b4a51ff7586f227faa2ee20841ade | Allow other OIDC providers for authentication | [
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -109,8 +109,20 @@ GOOGLE_IAP_PUBLIC_KEY_URL = 'https://www.gstatic.com/iap/verify/public_key'\n# that user should be allowed to access the server.\n# Enable Cloud OIDC authentication support.\n+# For Google's federated identity, leave AUTH_URI and DICOVERY_URL to None.\n+# For others, refer to your OIDC provider configuration. Configuration can be\n+# obtain from the dicovery url. eg. https://accounts.google.com/.well-known/openid-configuration\n+\n+# Some OIDC providers expects a specific Algorithm. If so, specify in ALGORITHM.\n+# Eg. HS256, HS384, HS512, RS256, RS384, RS512.\n+# For Google, leave it to None\n+\nGOOGLE_OIDC_ENABLED = False\n+GOOGLE_OIDC_AUTH_URL = None\n+GOOGLE_OIDC_DISCOVERY_URL = None\n+GOOGLE_OIDC_ALGORITHM = None\n+\nGOOGLE_OIDC_CLIENT_ID = None\nGOOGLE_OIDC_CLIENT_SECRET = None\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/google_auth.py",
"new_path": "timesketch/lib/google_auth.py",
"diff": "@@ -38,12 +38,10 @@ from flask import session\nfrom timesketch.lib.definitions import HTTP_STATUS_CODE_OK\n-\nCSRF_KEY = 'google_oauth2_csrf_token'\nAUTH_URI = 'https://accounts.google.com/o/oauth2/v2/auth'\nDISCOVERY_URL = 'https://accounts.google.com/.well-known/openid-configuration'\n-\nclass JwtValidationError(Exception):\n\"\"\"Raised when a JSON Web Token cannot be validated.\"\"\"\n@@ -91,8 +89,10 @@ def _fetch_oauth2_discovery_document():\nReturns:\nHTTP response.\n\"\"\"\n+ discovery_url = current_app.config.get(\n+ 'GOOGLE_OIDC_DISCOVERY_URL', DISCOVERY_URL)\ntry:\n- resp = requests.get(DISCOVERY_URL)\n+ resp = requests.get(discovery_url)\nexcept requests.exceptions.RequestException as e:\nraise DiscoveryDocumentError(\n'Cannot fetch discovery document: {}'.format(e)) from e\n@@ -120,6 +120,7 @@ def get_oauth2_authorize_url(hosted_domain=None):\nReturns:\nAuthorization URL.\n\"\"\"\n+ auth_uri = current_app.config.get('GOOGLE_OIDC_AUTH_URL', AUTH_URI)\ncsrf_token = _generate_random_token()\nnonce = _generate_random_token()\nredirect_uri = url_for(\n@@ -146,7 +147,7 @@ def get_oauth2_authorize_url(hosted_domain=None):\nparams['hd'] = hosted_domain\nurlencoded_params = urlparse.urlencode(params)\n- google_authorization_url = '{}?{}'.format(AUTH_URI, urlencoded_params)\n+ google_authorization_url = '{}?{}'.format(auth_uri, urlencoded_params)\nreturn google_authorization_url\n@@ -199,7 +200,9 @@ def decode_jwt(encoded_jwt, public_key, algorithm, expected_audience):\nArgs:\nencoded_jwt: The contents of the X-Goog-IAP-JWT-Assertion header.\npublic_key: Key to verify signature of the JWT.\n- algorithm: Algorithm used for the key. E.g. ES256, RS256\n+ algorithm: Algorithm used for the key. E.g. ES256, RS256. If the\n+ GOOGLE_OIDC_ALGORITHM is set in the config, it will overwrite\n+ the algorithm used here.\nexpected_audience: Expected audience in the JWT.\nReturns:\n@@ -208,9 +211,12 @@ def decode_jwt(encoded_jwt, public_key, algorithm, expected_audience):\nRaises:\nJwtValidationError: if the JWT token cannot be decoded.\n\"\"\"\n+ chosen_algorithm = current_app.config.get(\n+ 'GOOGLE_OIDC_ALGORITHM', algorithm)\ntry:\ndecoded_jwt = jwt.decode(\n- jwt=encoded_jwt, key=public_key, algorithms=[algorithm],\n+ jwt=encoded_jwt, key=public_key,\n+ algorithms=[chosen_algorithm],\naudience=expected_audience)\nreturn decoded_jwt\nexcept (jwt.exceptions.InvalidTokenError,\n"
}
] | Python | Apache License 2.0 | google/timesketch | Allow other OIDC providers for authentication (#1717) |
263,096 | 31.03.2021 01:13:59 | -7,200 | 2a6f6289f4f41313c94bcd0ca9279d82d79d7878 | Updated developer-guide.md
The command displayed was wrong | [
{
"change_type": "MODIFY",
"old_path": "docs/developers/developer-guide.md",
"new_path": "docs/developers/developer-guide.md",
"diff": "@@ -107,7 +107,7 @@ End2end (e2e) tests are run on Github with every commit. Those tests will setup\nTo run the e2e-tests locally execute to setup the e2e docker images and run them:\n```bash\n-sh end_to_end_tests/tools/run_in_container.py\n+$ sh end_to_end_tests/tools/run_end_to_end_tests.sh\n```\nThe tests are stored in:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Updated developer-guide.md (#1725)
The command displayed was wrong |
263,096 | 11.04.2021 11:57:20 | -7,200 | 726d088b975e61cb16958278a71f4e01cd90d99a | Add Get Timesketch client object into dev/notebook snippet
That should be something that people do on a regular base... | [
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/snippets.json",
"new_path": "docker/dev/build/snippets.json",
"diff": "\"# agg.title = 'Top 10 Domains'\",\n\"# agg.save()\"\n]\n- }\n+ },\n+ {\n+ \"name\" : \"Get Timesketch client object\",\n+ \"code\" : [\n+ \"# Execute cell in order to get a Timesketch API client instance.\",\n+ \"client = state.get_from_cache('timesketch_client')\"\n+ ]\n+ },\n]\n}\n"
}
] | Python | Apache License 2.0 | google/timesketch | Add Get Timesketch client object into dev/notebook snippet (#1737)
That should be something that people do on a regular base... |
263,093 | 11.04.2021 14:47:21 | -7,200 | 04fb2cdb1bef5ad8652648673f7d1215295f63cd | Set timeline ID in the GCS importer
* Set timeline ID in the GCS importer
Quick fix for the GCS importer.
* Update contrib/gcs_importer.py | [
{
"change_type": "MODIFY",
"old_path": "contrib/gcs_importer.py",
"new_path": "contrib/gcs_importer.py",
"diff": "@@ -77,7 +77,7 @@ def setup_sketch(timeline_name, index_name, username, sketch_id=None):\nsketch_id: (str) Optional sketch_id to add timeline to\nReturns:\n- (str) Sketch ID\n+ (tuple) sketch ID and timeline ID as integers\n\"\"\"\nwith app.app_context():\nuser = User.get_or_create(username=username)\n@@ -133,7 +133,7 @@ def setup_sketch(timeline_name, index_name, username, sketch_id=None):\ndb_session.commit()\ntimeline.set_status('processing')\n- return sketch.id\n+ return sketch.id, timeline.id\ndef callback(message):\n@@ -172,14 +172,15 @@ def callback(message):\ntimeline_name = os.path.splitext(gcs_plaso_filename)[0]\nindex_name = uuid.uuid4().hex\n- sketch_id = setup_sketch(timeline_name, index_name, 'admin',\n- sketch_id_from_metadata)\n+ sketch_id, timeline_id = setup_sketch(\n+ timeline_name, index_name, 'admin', sketch_id_from_metadata)\n# Start indexing\nwith app.app_context():\npipeline = tasks.build_index_pipeline(\nfile_path=local_plaso_file, timeline_name=gcs_base_filename,\n- index_name=index_name, file_extension='plaso', sketch_id=sketch_id)\n+ index_name=index_name, file_extension='plaso', sketch_id=sketch_id,\n+ timeline_id=timeline_id)\npipeline.apply_async()\nlogger.info('File sent for indexing: {}'. format(gcs_base_filename))\n"
}
] | Python | Apache License 2.0 | google/timesketch | Set timeline ID in the GCS importer (#1738)
* Set timeline ID in the GCS importer
Quick fix for the GCS importer.
* Update contrib/gcs_importer.py
Co-authored-by: Johan Berggren <jberggren@gmail.com>
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,096 | 12.04.2021 12:24:59 | -7,200 | 762b7f564fef6ba0524c6a4e255a43e1ea69623f | Fixed a bug in Sigma | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources_test.py",
"new_path": "timesketch/api/v1/resources_test.py",
"diff": "@@ -405,7 +405,12 @@ class SigmaListResourceTest(BaseTest):\n'*apt-get install zmap*'\n]\n},\n- 'es_query': '*apt\\\\-get\\\\ install\\\\ zmap*',\n+ 'es_query':\n+ '(data_type:(\"shell\\\\:zsh\\\\:history\" OR '\\\n+ '\"bash\\\\:history\\\\:command\" OR '\\\n+ '\"apt\\\\:history\\\\:line\" OR '\\\n+ '\"selinux\\\\:line\") AND '\\\n+ '\"*apt\\\\-get\\\\ install\\\\ zmap*\")',\n'falsepositives': ['Unknown'],\n'file_name': 'lnx_susp_zenmap.yml',\n'file_relpath': 'lnx_susp_zenmap.yml',\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -171,8 +171,10 @@ def get_sigma_rule(filepath, sigma_config=None):\nIsADirectoryError: If a directory is passed as filepath\n\"\"\"\ntry:\n- if sigma_config:\n+ if isinstance(sigma_config, sigma_configuration.SigmaConfiguration):\nsigma_conf_obj = sigma_config\n+ elif isinstance(sigma_config, str):\n+ sigma_conf_obj = get_sigma_config_file(sigma_config)\nelse:\nsigma_conf_obj = get_sigma_config_file()\nexcept ValueError as e:\n@@ -205,7 +207,7 @@ def get_sigma_rule(filepath, sigma_config=None):\nfor doc in rule_yaml_data:\nrule_return.update(doc)\nparser = sigma_collection.SigmaCollectionParser(\n- str(doc), sigma_config, None)\n+ str(doc), sigma_conf_obj, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\nexcept NotImplementedError as exception:\n@@ -263,17 +265,26 @@ def get_sigma_rule_by_text(rule_text, sigma_config=None):\nNotImplementedError: A feature in the provided Sigma rule is not\nimplemented in Sigma for Timesketch\n\"\"\"\n- if sigma_config is None:\n- sigma_config = get_sigma_config_file()\n+ try:\n+ if isinstance(sigma_config, sigma_configuration.SigmaConfiguration):\n+ sigma_conf_obj = sigma_config\n+ elif isinstance(sigma_config, str):\n+ sigma_conf_obj = get_sigma_config_file(sigma_config)\n+ else:\n+ sigma_conf_obj = get_sigma_config_file()\n+ except ValueError as e:\n+ logger.error(\n+ 'Problem reading the Sigma config', exc_info=True)\n+ raise ValueError('Problem reading the Sigma config') from e\n- sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_config, {})\n+ sigma_backend = sigma_es.ElasticsearchQuerystringBackend(sigma_conf_obj, {})\nrule_return = {}\n# TODO check if input validation is needed / useful.\ntry:\nparser = sigma_collection.SigmaCollectionParser(\n- rule_text, sigma_config, None)\n+ rule_text, sigma_conf_obj, None)\nparsed_sigma_rules = parser.generate(sigma_backend)\nrule_yaml_data = yaml.safe_load_all(rule_text)\nfor doc in rule_yaml_data:\n"
}
] | Python | Apache License 2.0 | google/timesketch | Fixed a bug in Sigma (#1741) |
263,096 | 12.04.2021 12:34:25 | -7,200 | cb62b592ad36e33f54b9a3399b147827ddcfe329 | Added os filsystem information to sigma mappings
That is especially useful if plaso parsed image timelines are ingested into TS. | [
{
"change_type": "MODIFY",
"old_path": "data/sigma_config.yaml",
"new_path": "data/sigma_config.yaml",
"diff": "@@ -70,6 +70,11 @@ logsources:\nconditions:\nsource_name:\n- \"Microsoft-Windows-Security-Auditing\"\n+ os:\n+ service: filesystem\n+ conditions:\n+ data_type:\n+ - \"fs:stat\"\nfieldmappings:\nEventID: event_identifier\nComputerName: computer_name\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added os filsystem information to sigma mappings (#1734)
That is especially useful if plaso parsed image timelines are ingested into TS.
Co-authored-by: Kristinn <kristinn@log2timeline.net> |
263,096 | 18.04.2021 12:49:34 | -7,200 | 47161572d8870283b132d0ec89628449df0e76d4 | Added Sigma api e2e as well as a notebook example | [
{
"change_type": "MODIFY",
"old_path": "api_client/python/timesketch_api_client/sigma.py",
"new_path": "api_client/python/timesketch_api_client/sigma.py",
"diff": "@@ -78,7 +78,7 @@ class Sigma(resource.BaseResource):\n@property\ndef rule_uuid(self):\n\"\"\"Returns the rule id.\"\"\"\n- return self.get_attribute('rule_uuid')\n+ return self.get_attribute('id')\n@property\ndef file_name(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -254,5 +254,5 @@ EXTERNAL_HOST_URL = 'https://localhost'\n#-------------------------------------------------------------------------------\n# Sigma Settings\n-SIGMA_RULES_FOLDERS = ['/etc/timesketch/data/sigma/rules/']\n+SIGMA_RULES_FOLDERS = ['/etc/timesketch/sigma/rules/']\nSIGMA_CONFIG = '/etc/timesketch/sigma_config.yaml'\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/docker-entrypoint.sh",
"new_path": "docker/dev/build/docker-entrypoint.sh",
"diff": "@@ -14,8 +14,8 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/plaso.mappings /etc/timesketch/\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\nln -s /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/sigma_config.yaml\n- mkdir /etc/timesketch/data\n- ln -s /usr/local/src/timesketch/data/sigma/ /etc/timesketch/data/\n+ ln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/\n+\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/e2e/Dockerfile",
"new_path": "docker/e2e/Dockerfile",
"diff": "@@ -41,8 +41,8 @@ RUN cp /tmp/timesketch/data/tags.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/plaso.mappings /etc/timesketch/\nRUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\n-RUN mkdir /etc/timesketch/data\n-RUN cp -r /tmp/timesketch/data/sigma /etc/timesketch/data/\n+RUN cp -r /tmp/timesketch/data/sigma /etc/timesketch/sigma\n+\n# Copy the entrypoint script into the container\nCOPY docker/e2e/docker-entrypoint.sh /\n"
},
{
"change_type": "MODIFY",
"old_path": "end_to_end_tests/client_test.py",
"new_path": "end_to_end_tests/client_test.py",
"diff": "# limitations under the License.\n\"\"\"End to end tests of Timesketch client functionality.\"\"\"\n+from timesketch_api_client import search\n+\nfrom . import interface\nfrom . import manager\n@@ -49,4 +51,66 @@ class ClientTest(interface.BaseEndToEndTest):\nself.assertions.assertTrue(bool(index.name))\n+ def test_sigma_list(self):\n+ \"\"\"Client Sigma list tests.\"\"\"\n+\n+ rules = self.api.list_sigma_rules()\n+ self.assertions.assertGreaterEqual(len(rules), 1)\n+ rule = rules[0]\n+ self.assertions.assertIn('b793-11ea-b3de-0242ac130004', rule.id)\n+ self.assertions.assertIn('b793-11ea-b3de-0242ac130004', rule.rule_uuid)\n+ self.assertions.assertIn('Installation of Zenmap', rule.title)\n+ self.assertions.assertIn('zmap', rule.es_query)\n+ self.assertions.assertIn('Alexander', rule.author)\n+ self.assertions.assertIn('2020/06/26',rule.date)\n+ self.assertions.assertIn('installation of Zenmap', rule.description)\n+ self.assertions.assertEqual(len(rule.detection), 2)\n+ self.assertions.assertIn('zmap*', rule.es_query)\n+ self.assertions.assertIn('shell\\\\:zsh\\\\:history', rule.es_query)\n+ self.assertions.assertIn('Unknown', rule.falsepositives[0])\n+ self.assertions.assertEqual(len(rule.logsource), 2)\n+ self.assertions.assertIn('2020/06/26', rule.modified)\n+ self.assertions.assertIn('lnx_susp_zenmap.yml', rule.file_relpath)\n+ self.assertions.assertIn('lnx_susp_zenmap', rule.file_name)\n+ self.assertions.assertIn('high', rule.level)\n+ self.assertions.assertIn('rmusser.net', rule.references[0])\n+\n+ def test_get_sigma_rule(self):\n+ \"\"\"Client Sigma object tests.\"\"\"\n+\n+ rule = self.api.get_sigma_rule(\n+ rule_uuid='5266a592-b793-11ea-b3de-0242ac130004')\n+ rule.from_rule_uuid('5266a592-b793-11ea-b3de-0242ac130004')\n+ self.assertions.assertGreater(len(rule.attributes),5)\n+ self.assertions.assertIsNotNone(rule)\n+ self.assertions.assertIn('Alexander', rule.author)\n+ self.assertions.assertIn('Alexander', rule.get_attribute('author'))\n+ self.assertions.assertIn('b793-11ea-b3de-0242ac130004', rule.id)\n+ self.assertions.assertIn('Installation of Zenmap', rule.title)\n+ self.assertions.assertIn('zmap', rule.es_query)\n+ self.assertions.assertIn('shell\\\\:zsh\\\\:history', rule.es_query)\n+ self.assertions.assertIn('lnx_susp_zenmap.yml', rule.file_relpath)\n+ self.assertions.assertIn('sigma/rule/5266a592', rule.resource_uri)\n+ self.assertions.assertIn('installation of Zenmap', rule.description)\n+ self.assertions.assertIn('high', rule.level)\n+ self.assertions.assertEqual(len(rule.falsepositives), 1)\n+ self.assertions.assertIn('Unknown', rule.falsepositives[0])\n+ self.assertions.assertIn('susp_zenmap', rule.file_name)\n+ self.assertions.assertIn('2020/06/26', rule.date)\n+ self.assertions.assertIn('2020/06/26', rule.modified)\n+ self.assertions.assertIn('high', rule.level)\n+ self.assertions.assertIn('rmusser.net', rule.references[0])\n+ self.assertions.assertEqual(len(rule.detection), 2)\n+ self.assertions.assertEqual(len(rule.logsource), 2)\n+\n+ # Test an actual query\n+\n+ self.import_timeline('sigma_events.csv')\n+ search_obj = search.Search(self.sketch)\n+ search_obj.query_string = rule.es_query\n+ data_frame = search_obj.table\n+ count = len(data_frame)\n+ self.assertions.assertEqual(count, 1)\n+\n+\nmanager.EndToEndTestManager.register_test(ClientTest)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "end_to_end_tests/test_data/sigma_events.csv",
"diff": "+\"message\",\"timestamp\",\"datetime\",\"timestamp_desc\",\"extra_field_1\",\"command\",\"data_type\",\"display_name\",\"filename\",\"packages\",\"parser\"\n+\"A message\",\"123456789\",\"2015-07-24T19:01:01+00:00\",\"Write time\",\"foo\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Another message\",\"123456790\",\"2015-07-24T19:01:02+00:00\",\"Write time\",\"bar\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Yet more messages\",\"123456791\",\"2015-07-24T19:01:03+00:00\",\"Write time\",\"baz\",\"\",\"\",\"\",\"\",\"\",\"\"\n+\"Install: zmap:amd64 (1.1.0-1) [Commandline: apt-get install zmap]\",\"123456791\",\"2015-07-24T19:01:03+00:00\",\"foo\",\"\",\"Commandline: apt-get install zmap\",\"apt:history:line\",\"GZIP:/var/log/apt/history.log.1.gz\",\"/var/log/apt/history.log.1.gz\",\"Install: zmap:amd64 (1.1.0-1)\",\"apt_history\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "end_to_end_tests/test_data/sigma_events.jsonl",
"diff": "+{\"message\": \"A message\",\"timestamp\": 123456789,\"datetime\": \"2015-07-24T19:01:01+00:00\",\"timestamp_desc\": \"Write time\",\"extra_field_1\": \"foo\"}\n+{\"message\": \"Another message\",\"timestamp\": 123456790,\"datetime\": \"2015-07-24T19:01:02+00:00\",\"timestamp_desc\": \"Write time\",\"extra_field_1\": \"bar\"}\n+{\"message\": \"Yet more messages\",\"timestamp\": 123456791,\"datetime\": \"2015-07-24T19:01:03+00:00\",\"timestamp_desc\": \"Write time\",\"extra_field_1\": \"baz\"}\n+{\"message\": \"Install: zmap:amd64 (1.1.0-1) [Commandline: apt-get install zmap]\",\"timestamp\": 123456791,\"datetime\": \"2015-07-24T19:01:03+00:00\",\"timestamp_desc\": \"foo\",\"command\":\"Commandline: apt-get install zmap\",\"data_type\":\"apt:history:line\",\"display_name\":\"GZIP:/var/log/apt/history.log.1.gz\",\"filename\":\"/var/log/apt/history.log.1.gz\",\"packages\":\"Install: zmap:amd64 (1.1.0-1)\",\"parser\":\"apt_history\"}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "notebooks/Sigma_test_Notebook.ipynb",
"diff": "+{\n+ \"metadata\": {\n+ \"language_info\": {\n+ \"codemirror_mode\": {\n+ \"name\": \"ipython\",\n+ \"version\": 3\n+ },\n+ \"file_extension\": \".py\",\n+ \"mimetype\": \"text/x-python\",\n+ \"name\": \"python\",\n+ \"nbconvert_exporter\": \"python\",\n+ \"pygments_lexer\": \"ipython3\",\n+ \"version\": \"3.8.5-final\"\n+ },\n+ \"orig_nbformat\": 2,\n+ \"kernelspec\": {\n+ \"name\": \"python3\",\n+ \"display_name\": \"Python 3.8.5 64-bit ('.venv': venv)\",\n+ \"metadata\": {\n+ \"interpreter\": {\n+ \"hash\": \"0df2a34fcd01e2a1b8bbe214038ede9153dc0ad9a9d0372ae1c18b294cad4266\"\n+ }\n+ }\n+ },\n+ \"metadata\": {\n+ \"interpreter\": {\n+ \"hash\": \"2556566ac8fd219b8b3cb0c76c8e4f226085ddd0e18628d37e0282e6a68fc0ff\"\n+ }\n+ }\n+ },\n+ \"nbformat\": 4,\n+ \"nbformat_minor\": 2,\n+ \"cells\": [\n+ {\n+ \"source\": [\n+ \"# Sigma example notebook\\n\",\n+ \"\\n\",\n+ \"This notebook should showcase some use cases with regards to Sigma.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"!pip install -q timesketch_api_client\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"from timesketch_api_client import search\\n\",\n+ \"from picatrix.lib import state as state_lib\\n\",\n+ \"\\n\",\n+ \"import requests\\n\",\n+ \"import io\\n\",\n+ \"import altair as alt\\n\",\n+ \"import numpy as np\\n\",\n+ \"import pandas as pd\\n\",\n+ \"from timesketch_api_client import config\\n\",\n+ \"from timesketch_import_client import helper\\n\",\n+ \"from timesketch_import_client import importer\\n\",\n+ \"from timesketch_api_client import search\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"# Create the sketch and import some data\\n\",\n+ \"\\n\",\n+ \"First we want to create a sketch and import a small data set. It is recommended to do that with the dev docker container.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"ts_client = config.get_client()\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"We create a new sketch\\n\",\n+ \"\\n\",\n+ \"That will be called test and will be filled with some test data from the Github repository.\\n\",\n+ \"\\n\",\n+ \"The downloaded csv will be read into a pandas dataframe for further processing.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"sketch = ts_client.create_sketch(name=\\\"test\\\")\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"url = \\\"https://raw.githubusercontent.com/google/timesketch/master/test_tools/test_events/sigma_events.csv\\\" \\n\",\n+ \"download = requests.get(url).content\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"df = pd.read_csv(io.StringIO(download.decode('utf-8')))\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"df.head(4)\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"## Import the data to timesketch\\n\",\n+ \"\\n\",\n+ \"The easiest way to do that is using the import client as shown below.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"import_helper = helper.ImportHelper() \\n\",\n+ \"\\n\",\n+ \"with importer.ImportStreamer() as streamer:\\n\",\n+ \" streamer.set_sketch(sketch)\\n\",\n+ \" streamer.set_config_helper(import_helper) \\n\",\n+ \"\\n\",\n+ \" streamer.set_timeline_name('sigma_events.csv')\\n\",\n+ \" streamer.add_data_frame(df)\\n\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"# Fetch Rules\\n\",\n+ \"\\n\",\n+ \"Now we want to fetch all the rules installed on the Timesketch instance. For the dev docker container we only expect one rule.\\n\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rules = ts_client.list_sigma_rules()\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"for rule in rules:\\n\",\n+ \" print(f'ID: {rule.id} Title: {rule.title}')\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rule1 = rules[0]\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"The API also gives us the elastic search query we could use to explore the data.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rule1.es_query\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"# Single rule\\n\",\n+ \"\\n\",\n+ \"Next we want to fetch a single rule by a given uuid.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"single_rule = ts_client.get_sigma_rule(rule_uuid='5266a592-b793-11ea-b3de-0242ac130004')\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"single_rule.id\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"single_rule.es_query\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"# Text Sigma examples\\n\",\n+ \"\\n\",\n+ \"The API also provides the option to provide a Sigma rule by text and the backend will parse it with the installed Sigma mappings. This can be especially helpful when developing new rules before installing and exposing them to all the other user of a Timesketch instance.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"MOCK_SIGMA_RULE = \\\"\\\"\\\"\\n\",\n+ \"title: Suspicious Installation of Zenmap\\n\",\n+ \"id: 5266a592-b793-11ea-b3de-0242ac130004\\n\",\n+ \"description: Detects suspicious installation of Zenmap\\n\",\n+ \"references:\\n\",\n+ \" - https://rmusser.net/docs/ATT&CK-Stuff/ATT&CK/Discovery.html\\n\",\n+ \"author: Alexander Jaeger\\n\",\n+ \"date: 2020/06/26\\n\",\n+ \"modified: 2021/01/01\\n\",\n+ \"logsource:\\n\",\n+ \" product: linux\\n\",\n+ \" service: shell\\n\",\n+ \"detection:\\n\",\n+ \" keywords:\\n\",\n+ \" # Generic suspicious commands\\n\",\n+ \" - '*apt-get install zmap*'\\n\",\n+ \" condition: keywords\\n\",\n+ \"falsepositives:\\n\",\n+ \" - Unknown\\n\",\n+ \"level: high\\n\",\n+ \"\\\"\\\"\\\"\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rule_by_text = ts_client.get_sigma_rule_by_text(MOCK_SIGMA_RULE)\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rule_by_text.es_query\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"rule_by_text.references\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"# Analyzer\\n\",\n+ \"\\n\",\n+ \"Timesketch also has a Sigma analyzer that will add labels to all matching events. To do so you need a Timeline object to run the analyzer. The Analyzer then will take all rules installed on the Timesketch instance and go over the Timeline.\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"timelines = sketch.list_timelines()\\n\",\n+ \"timeline = None\\n\",\n+ \"for timeline_ in timelines:\\n\",\n+ \" if timeline_.name == 'sigma_events.csv':\\n\",\n+ \" timeline = timeline_\\n\",\n+ \" break\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"result = timeline.run_analyzer(analyzer_name='sigma', ignore_previous=True)\\n\"\n+ ]\n+ },\n+ {\n+ \"cell_type\": \"code\",\n+ \"execution_count\": null,\n+ \"metadata\": {},\n+ \"outputs\": [],\n+ \"source\": [\n+ \"sketch.get_analyzer_status()\"\n+ ]\n+ },\n+ {\n+ \"source\": [\n+ \"This should show something like:\\n\",\n+ \"```\\n\",\n+ \"[{'index': <timesketch_api_client.index.SearchIndex at 0x126a09820>,\\n\",\n+ \" 'timeline_id': 1,\\n\",\n+ \" 'session_id': 1,\\n\",\n+ \" 'analyzer': 'sigma',\\n\",\n+ \" 'results': 'Applied 1 tags\\\\n* lnx_susp_zenmap.yml: 1\\\\nProblematic rules:',\\n\",\n+ \" 'status': 'DONE'}]\\n\",\n+ \"```\"\n+ ],\n+ \"cell_type\": \"markdown\",\n+ \"metadata\": {}\n+ }\n+ ]\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/sigma_util.py",
"new_path": "timesketch/lib/sigma_util.py",
"diff": "@@ -134,7 +134,6 @@ def get_sigma_rules(rule_folder, sigma_config=None):\nparsed_rule = get_sigma_rule(rule_file_path, sigma_config)\nif parsed_rule:\nreturn_array.append(parsed_rule)\n-\nreturn return_array\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added Sigma api e2e as well as a notebook example (#1730) |
263,171 | 30.04.2021 15:44:56 | -7,200 | 3121bfb3c2ae6fc94fc06cf247c0cef52fcfca9d | Added generic mappings for CSV/JSON ingestion | [
{
"change_type": "MODIFY",
"old_path": "contrib/deploy_timesketch.sh",
"new_path": "contrib/deploy_timesketch.sh",
"diff": "@@ -80,6 +80,7 @@ curl -s $GITHUB_BASE_URL/docker/release/config.env > timesketch/config.env\ncurl -s $GITHUB_BASE_URL/data/timesketch.conf > timesketch/etc/timesketch/timesketch.conf\ncurl -s $GITHUB_BASE_URL/data/tags.yaml > timesketch/etc/timesketch/tags.yaml\ncurl -s $GITHUB_BASE_URL/data/plaso.mappings > timesketch/etc/timesketch/plaso.mappings\n+curl -s $GITHUB_BASE_URL/data/generic.mappings > timesketch/etc/timesketch/generic.mappings\ncurl -s $GITHUB_BASE_URL/data/features.yaml > timesketch/etc/timesketch/features.yaml\ncurl -s $GITHUB_BASE_URL/data/sigma_config.yaml > timesketch/etc/timesketch/sigma_config.yaml\ncurl -s $GITHUB_BASE_URL/data/sigma/rules/lnx_susp_zenmap.yml > timesketch/etc/timesketch/sigma/rules/lnx_susp_zenmap.yml\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "data/generic.mappings",
"diff": "+{\n+ \"date_detection\": false,\n+ \"properties\": {\n+ \"datetime\": {\n+ \"type\": \"date\"\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "data/timesketch.conf",
"new_path": "data/timesketch.conf",
"diff": "@@ -159,6 +159,7 @@ CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'\n# File location to store the mappings used when Elastic indices are created\n# for plaso files.\nPLASO_MAPPING_FILE = '/etc/timesketch/plaso.mappings'\n+GENERIC_MAPPING_FILE = '/etc/timesketch/generic.mappings'\n# Upper limits for the process memory that psort.py is allocated when ingesting\n# plaso files. The size is in bytes, with the default value of\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/dev/build/docker-entrypoint.sh",
"new_path": "docker/dev/build/docker-entrypoint.sh",
"diff": "@@ -12,6 +12,7 @@ if [ \"$1\" = 'timesketch' ]; then\ncp /usr/local/src/timesketch/data/features.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/tags.yaml /etc/timesketch/\ncp /usr/local/src/timesketch/data/plaso.mappings /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/generic.mappings /etc/timesketch/\ncp /usr/local/src/timesketch/data/ontology.yaml /etc/timesketch/\nln -s /usr/local/src/timesketch/data/sigma_config.yaml /etc/timesketch/sigma_config.yaml\nln -s /usr/local/src/timesketch/data/sigma /etc/timesketch/\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/e2e/Dockerfile",
"new_path": "docker/e2e/Dockerfile",
"diff": "@@ -40,6 +40,7 @@ RUN cp /tmp/timesketch/data/ontology.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/tags.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/\nRUN cp /tmp/timesketch/data/plaso.mappings /etc/timesketch/\n+RUN cp /tmp/timesketch/data/generic.mappings /etc/timesketch/\nRUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/\nRUN cp -r /tmp/timesketch/data/sigma /etc/timesketch/sigma\nRUN chmod -R go+r /etc/timesketch\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/e2e/docker-entrypoint.sh",
"new_path": "docker/e2e/docker-entrypoint.sh",
"diff": "if [ \"$1\" = 'timesketch' ]; then\n# Copy the mappings for plaso ingestion.\ncp /usr/local/src/timesketch/data/plaso.mappings /etc/timesketch/\n+ cp /usr/local/src/timesketch/data/generic.mappings /etc/timesketch/\n# Set SECRET_KEY in /etc/timesketch/timesketch.conf if it isn't already set\nif grep -q \"SECRET_KEY = '<KEY_GOES_HERE>'\" /etc/timesketch/timesketch.conf; then\n"
},
{
"change_type": "MODIFY",
"old_path": "timesketch/lib/tasks.py",
"new_path": "timesketch/lib/tasks.py",
"diff": "@@ -652,6 +652,21 @@ def run_csv_jsonl(\n'Index timeline [{0:s}] to index [{1:s}] (source: {2:s})'.format(\ntimeline_name, index_name, source_type))\n+ mappings = None\n+ mappings_file_path = current_app.config.get('GENERIC_MAPPING_FILE', '')\n+ if os.path.isfile(mappings_file_path):\n+ try:\n+ with open(mappings_file_path, 'r') as mfh:\n+ mappings = json.load(mfh)\n+\n+ if not isinstance(mappings, dict):\n+ raise RuntimeError(\n+ 'Unable to create mappings, the mappings are not a '\n+ 'dict, please look at the file: {0:s}'.format(\n+ mappings_file_path))\n+ except (json.JSONDecodeError, IOError):\n+ logger.error('Unable to read in mapping', exc_info=True)\n+\nes = ElasticsearchDataStore(\nhost=current_app.config['ELASTIC_HOST'],\nport=current_app.config['ELASTIC_PORT'])\n@@ -662,7 +677,8 @@ def run_csv_jsonl(\nerror_msg = ''\nerror_count = 0\ntry:\n- es.create_index(index_name=index_name, doc_type=event_type)\n+ es.create_index(\n+ index_name=index_name, doc_type=event_type, mappings=mappings)\nfor event in read_and_validate(file_handle):\nes.import_event(\nindex_name, event_type, event, timeline_id=timeline_id)\n"
}
] | Python | Apache License 2.0 | google/timesketch | Added generic mappings for CSV/JSON ingestion (#1753) |
263,093 | 17.05.2021 15:19:33 | -7,200 | 6c733f4f4c50229012531ab02705ba42ccce64f7 | get first entry based on ID | [
{
"change_type": "MODIFY",
"old_path": "timesketch/api/v1/resources/explore.py",
"new_path": "timesketch/api/v1/resources/explore.py",
"diff": "@@ -425,7 +425,8 @@ class SearchHistoryResource(resources.ResourceMixin, Resource):\ntree = {}\nroot_node = SearchHistory.query.filter_by(\n- user=current_user, sketch=sketch).first()\n+ user=current_user, sketch=sketch).order_by(\n+ SearchHistory.id).first()\nlast_node = SearchHistory.query.filter_by(\nuser=current_user, sketch=sketch).order_by(\nSearchHistory.id.desc()).first()\n"
}
] | Python | Apache License 2.0 | google/timesketch | get first entry based on ID (#1773) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.